Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(immer): initial #54

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lerna.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"packages": [
"./packages/core",
"./packages/immer",
"./packages/lens",
"./packages/fp-ts",
"./packages/react",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
"homepage": "https://github.com/raveclassic/frp-ts#readme",
"workspaces": [
"./packages/core",
"./packages/lens",
"./packages/immer",
"./packages/fp-ts",
"./packages/lens",
"./packages/react",
"./packages/test-utils",
"./packages/utils"
Expand Down
18 changes: 18 additions & 0 deletions packages/immer/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.js"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
15 changes: 15 additions & 0 deletions packages/immer/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
testRunner: 'jasmine2',
displayName: 'immer',
preset: '../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
transform: {
'^.+\\.[tj]s$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/packages/immer',
}
33 changes: 33 additions & 0 deletions packages/immer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@frp-ts/immer",
"version": "1.0.0-alpha.15",
"description": "Immer integration package",
"typedocMain": "./src/index.ts",
"author": "raveclassic",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/raveclassic/frp-ts.git"
},
"bugs": {
"url": "https://github.com/raveclassic/frp-ts/issues"
},
"homepage": "https://github.com/raveclassic/frp-ts#readme",
"scripts": {},
"private": false,
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"immer": "^9.0.12",
"tslib": "^2.3.1"
},
"dependencies": {
"@frp-ts/core": "^1.0.0-alpha.15",
"@frp-ts/utils": "^1.0.0-alpha.15"
},
"devDependencies": {
"immer": "^9.0.12",
"tslib": "^2.3.1"
}
}
41 changes: 41 additions & 0 deletions packages/immer/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"root": "packages/immer",
"sourceRoot": "packages/immer/src",
"projectType": "library",
"targets": {
"build": {
"executor": "@nrwl/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/packages/immer",
"main": "packages/immer/src/index.ts",
"tsConfig": "packages/immer/tsconfig.lib.json",
"assets": ["packages/immer/*.md"]
}
},
"lint": {
"executor": "@nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["packages/immer/**/*.ts"]
}
},
"test": {
"executor": "@nrwl/jest:jest",
"outputs": ["coverage/packages/immer"],
"options": {
"jestConfig": "packages/immer/jest.config.js",
"passWithNoTests": true,
"codeCoverage": true
}
},
"deploy": {
"executor": "ngx-deploy-npm:deploy",
"options": {
"access": "public",
"noBuild": true
}
}
},
"tags": []
}
67 changes: 67 additions & 0 deletions packages/immer/src/immer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { newAtom } from '@frp-ts/core'
import { produceMany } from './immer'
import { produce } from 'immer'

describe('immer', () => {
describe('direct integration', () => {
it('updates the state with "produce"', () => {
interface State {
readonly foo: number
}
const state = newAtom<State>({ foo: 0 })
state.modify(
produce((state) => {
state.foo++
}),
)
expect(state.get()).toEqual<State>({ foo: 1 })
})
})
describe('produceMany', () => {
it('updates nested values', () => {
interface State {
readonly foo: number
}
const state = newAtom<State>({ foo: 0 })
const methods = produceMany(state, {
inc: () => (state) => {
state.foo += 1
},
})
methods.inc()
expect(state.get().foo).toEqual(1)
})
})
describe('stress test', () => {
it('runs', () => {
interface Dog {
name: string
}
interface House {
dog: Dog
}
interface AppState {
house: House
}

const initialState: AppState = { house: { dog: { name: 'Fido' } } }
const storeState = newAtom(initialState)
const storeMethods = produceMany(storeState, {
renameTheDog: (newName: string) => (state) => {
state.house.dog.name = newName
},
})

const store = { ...storeState, ...storeMethods }

store.renameTheDog('Odif')
expect(store.get()).toEqual<AppState>({
house: {
dog: {
name: 'Odif',
},
},
})
})
})
})
23 changes: 23 additions & 0 deletions packages/immer/src/immer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Atom } from '@frp-ts/core'
import { mapRecord } from '@frp-ts/utils'
import immer, { Draft } from 'immer'

interface Recipe<Value> {
// any is needed due to variance
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(...args: readonly any[]): (draft: Draft<Value>) => void
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use the immer syntax for this recipe

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's simpler, see doc

{
  toggleTodo: (draft, id) => {
      const todo = draft.find(todo => todo.id === id)
      todo.done = !todo.done
  }
}

}

export function produceMany<Input, Recipes extends Record<PropertyKey, Recipe<Input>>>(
input: Atom<Input>,
recipes: Recipes,
): {
readonly [Name in keyof Recipes]: (...args: Parameters<Recipes[Name]>) => void
} {
return mapRecord(
recipes,
(recipe) =>
(...args) =>
input.set(immer(input.get(), recipe(...args))),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not modify?

Suggested change
input.set(immer(input.get(), recipe(...args))),
input.modify(immer(recipe(...args))),

)
}
1 change: 1 addition & 0 deletions packages/immer/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { produceMany } from './immer'
22 changes: 22 additions & 0 deletions packages/immer/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "CommonJS",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": ["."],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
10 changes: 10 additions & 0 deletions packages/immer/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"declaration": true,
"types": []
},
"include": ["**/*.ts"],
"exclude": ["**/*.spec.ts"]
}
9 changes: 9 additions & 0 deletions packages/immer/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": ["**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
}
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { memo1, memo2, constVoid, memoMany } from './function'
export { recordKeys, mapRecord } from './record'
14 changes: 14 additions & 0 deletions packages/utils/src/record.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { mapRecord, recordKeys } from './record'

describe('record', () => {
describe('recordKeys', () => {
it('returns keys a list of keys', () => {
expect(recordKeys({ foo: 'foo', bar: 123 })).toEqual(['foo', 'bar'])
})
})
describe('mapObject', () => {
it('maps values of an object', () => {
expect(mapRecord({ foo: 1, bar: 2 }, (value) => `${value}`)).toEqual({ foo: '1', bar: '2' })
})
})
})
16 changes: 16 additions & 0 deletions packages/utils/src/record.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export function recordKeys<T extends Record<string, unknown>>(obj: T): readonly (keyof T & string)[] {
// eslint-disable-next-line no-restricted-syntax
return Object.keys(obj) as never
}

export function mapRecord<Input extends Record<PropertyKey, unknown>, Result>(
input: Input,
f: (value: Input[keyof Input], key: keyof Input) => Result,
): { readonly [Key in keyof Input]: Result } {
// eslint-disable-next-line no-restricted-syntax
const result: Record<keyof Input, Result> = {} as never
for (const key of recordKeys(input)) {
result[key] = f(input[key], key)
}
return result
}
17 changes: 17 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pnpm-workspace.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
packages:
- packages/core
- packages/lens
- packages/immer
- packages/fp-ts
- packages/lens
- packages/react
- packages/test-utils
- packages/utils
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"baseUrl": ".",
"paths": {
"@frp-ts/core": ["packages/core/src/index.ts"],
"@frp-ts/immer": ["packages/immer/src/index.ts"],
"@frp-ts/fp-ts": ["packages/fp-ts/src/index.ts"],
"@frp-ts/lens": ["packages/lens/src/index.ts"],
"@frp-ts/react": ["packages/react/src/index.ts"],
Expand Down
1 change: 1 addition & 0 deletions workspace.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"version": 2,
"projects": {
"core": "packages/core",
"immer": "packages/immer",
"fp-ts": "packages/fp-ts",
"lens": "packages/lens",
"react": "packages/react",
Expand Down