mayoiga 0.0.21 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +111 -0
- package/.github/workflows/checker.yml +42 -0
- package/.gitignore +217 -0
- package/.prettierrc +5 -0
- package/README.md +21 -45
- package/component.d.ts +1 -0
- package/component.js +1 -0
- package/dist/component.d.ts +7 -0
- package/dist/component.js +11 -0
- package/dist/component.test.d.ts +1 -0
- package/dist/component.test.js +53 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.js +146 -0
- package/dist/index.test.d.ts +1 -0
- package/dist/index.test.js +74 -0
- package/dist/utils.d.ts +2 -0
- package/dist/utils.js +6 -0
- package/docs/.nojekyll +0 -0
- package/docs/assets/css/main.css +2328 -0
- package/docs/assets/images/icons.png +0 -0
- package/docs/assets/images/icons@2x.png +0 -0
- package/docs/assets/images/widgets.png +0 -0
- package/docs/assets/images/widgets@2x.png +0 -0
- package/docs/assets/js/main.js +1 -0
- package/docs/assets/js/search.js +3 -0
- package/docs/globals.html +185 -0
- package/docs/index.html +249 -0
- package/docs/modules/_actions_.html +398 -0
- package/docs/modules/_forms_.html +362 -0
- package/docs/modules/_index_.html +170 -0
- package/docs/modules/_inputprotocol_.html +319 -0
- package/docs/modules/_mayoiga_.html +783 -0
- package/docs/modules/_reducer_.html +417 -0
- package/example/src/demo-app.tsx +123 -0
- package/example/src/index.tsx +15 -0
- package/package.json +41 -44
- package/setup/vite-global-setup.js +1 -0
- package/setup/vite-set-global.js +0 -0
- package/src/component.test.tsx +91 -0
- package/src/component.tsx +19 -0
- package/src/index.test.tsx +120 -0
- package/src/index.ts +303 -0
- package/src/utils.ts +8 -0
- package/tsconfig.json +38 -0
- package/vite.config.js +10 -0
- package/yarn.lock +2378 -0
- package/lib/actions.d.ts +0 -28
- package/lib/actions.js +0 -29
- package/lib/actions.js.map +0 -1
- package/lib/forms.d.ts +0 -21
- package/lib/forms.js +0 -82
- package/lib/forms.js.map +0 -1
- package/lib/index.d.ts +0 -3
- package/lib/index.js +0 -7
- package/lib/index.js.map +0 -1
- package/lib/inputProtocol.d.ts +0 -17
- package/lib/inputProtocol.js +0 -24
- package/lib/inputProtocol.js.map +0 -1
- package/lib/mayoiga.d.ts +0 -110
- package/lib/mayoiga.js +0 -131
- package/lib/mayoiga.js.map +0 -1
- package/lib/reducer.d.ts +0 -20
- package/lib/reducer.js +0 -53
- package/lib/reducer.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mayoiga",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"main": "
|
|
6
|
-
"types": "
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Type safe hook based form library for React",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
7
|
"files": [
|
|
8
|
-
"
|
|
8
|
+
"dist",
|
|
9
|
+
"/component.js",
|
|
10
|
+
"/component.d.ts",
|
|
11
|
+
"!*.test.js"
|
|
9
12
|
],
|
|
10
13
|
"scripts": {
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
14
|
+
"clean": "rm -rf dist",
|
|
15
|
+
"test": "vitest run",
|
|
16
|
+
"prebuild": "npm run clean",
|
|
17
|
+
"build": "tsc",
|
|
18
|
+
"check:style": "prettier --check 'src/**/*.{js,ts}'",
|
|
19
|
+
"check:lint": "eslint 'src/**/*.{ts,tsx}'",
|
|
20
|
+
"check-all": "npm run check:style && npm run check:lint && npm run build --noEmit && npm run test",
|
|
21
|
+
"fix-all": "npm run check:style --write && npm run check:lint --fix",
|
|
22
|
+
"prepublish": "npm run check-all && npm run build"
|
|
17
23
|
},
|
|
18
24
|
"repository": {
|
|
19
25
|
"type": "git",
|
|
@@ -26,45 +32,36 @@
|
|
|
26
32
|
"validation",
|
|
27
33
|
"state"
|
|
28
34
|
],
|
|
29
|
-
"author": "
|
|
35
|
+
"author": "OGURA Daiki",
|
|
30
36
|
"license": "MIT",
|
|
31
37
|
"bugs": {
|
|
32
38
|
"url": "https://github.com/hachibeeDI/mayoiga/issues"
|
|
33
39
|
},
|
|
34
40
|
"homepage": "https://github.com/hachibeeDI/mayoiga#readme",
|
|
35
|
-
"devDependencies": {
|
|
36
|
-
"@babel/cli": "^7.4.4",
|
|
37
|
-
"@babel/core": "^7.4.5",
|
|
38
|
-
"@babel/plugin-proposal-class-properties": "^7.4.4",
|
|
39
|
-
"@babel/plugin-proposal-object-rest-spread": "^7.4.4",
|
|
40
|
-
"@babel/preset-env": "^7.4.5",
|
|
41
|
-
"@babel/preset-react": "^7.0.0",
|
|
42
|
-
"@babel/preset-typescript": "^7.3.3",
|
|
43
|
-
"@types/node": "^11.11.4",
|
|
44
|
-
"@types/react": "^16.8.19",
|
|
45
|
-
"@types/react-dom": "^16.8.2",
|
|
46
|
-
"babel-loader": "^8.0.6",
|
|
47
|
-
"prettier": "^1.18.2",
|
|
48
|
-
"react": "^16.8.6",
|
|
49
|
-
"react-dom": "^16.8.6",
|
|
50
|
-
"tslint": "^5.14.0",
|
|
51
|
-
"tslint-config-prettier": "^1.18.0",
|
|
52
|
-
"tslint-immutable": "^6.0.0",
|
|
53
|
-
"tslint-plugin-prettier": "^2.0.1",
|
|
54
|
-
"tslint-react": "^4.0.0",
|
|
55
|
-
"typedoc": "^0.14.2",
|
|
56
|
-
"typescript": "^3.5.1",
|
|
57
|
-
"typescript-eslint-parser": "^22.0.0",
|
|
58
|
-
"webpack": "^4.29.6",
|
|
59
|
-
"webpack-cli": "^3.3.3",
|
|
60
|
-
"webpack-dev-server": "^3.7.1"
|
|
61
|
-
},
|
|
62
41
|
"peerDependencies": {
|
|
63
|
-
"
|
|
42
|
+
"zod": "^3.14.4"
|
|
64
43
|
},
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
"@types/react": "^16.8.19"
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"nozuchi": "^0.0.3"
|
|
68
46
|
},
|
|
69
|
-
"
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@testing-library/react": "^13.0.0",
|
|
49
|
+
"@testing-library/user-event": "^14.1.1",
|
|
50
|
+
"@types/node": "^17.0.23",
|
|
51
|
+
"@types/react": "^18.0.1",
|
|
52
|
+
"@types/use-sync-external-store": "^0.0.3",
|
|
53
|
+
"@typescript-eslint/eslint-plugin": "^5.20.0",
|
|
54
|
+
"@typescript-eslint/parser": "^5.20.0",
|
|
55
|
+
"eslint": "^8.13.0",
|
|
56
|
+
"eslint-plugin-import": "^2.26.0",
|
|
57
|
+
"eslint-plugin-testing-library": "^5.3.1",
|
|
58
|
+
"jsdom": "^19.0.0",
|
|
59
|
+
"prettier": "^2.6.2",
|
|
60
|
+
"react": "^18.0.0",
|
|
61
|
+
"react-dom": "^18.0.0",
|
|
62
|
+
"typescript": "^4.6.3",
|
|
63
|
+
"use-sync-external-store": "^1.0.0",
|
|
64
|
+
"vitest": "^0.9.3",
|
|
65
|
+
"zod": "^3.14.4"
|
|
66
|
+
}
|
|
70
67
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
|
File without changes
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
|
|
2
|
+
import {render, screen, waitFor} from '@testing-library/react';
|
|
3
|
+
import userEvent from '@testing-library/user-event';
|
|
4
|
+
import React from 'react';
|
|
5
|
+
|
|
6
|
+
import {test, expect} from 'vitest';
|
|
7
|
+
|
|
8
|
+
import * as zod from 'zod';
|
|
9
|
+
|
|
10
|
+
import { Field, Slicer } from './component';
|
|
11
|
+
|
|
12
|
+
import {createFormHook, } from './index';
|
|
13
|
+
|
|
14
|
+
const testSchema = zod.object({
|
|
15
|
+
name: zod.string(),
|
|
16
|
+
description: zod.string(),
|
|
17
|
+
age: zod.string().transform(val => Number(val)).refine(val => Number.isNaN(val) ? 0 : val),
|
|
18
|
+
marked: zod.boolean(),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// every fields are optional for test
|
|
22
|
+
type FormStateBeforeValidation = {
|
|
23
|
+
name: string;
|
|
24
|
+
description: string;
|
|
25
|
+
age: string;
|
|
26
|
+
marked: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const createTestHook = () => createFormHook({name:'', description: '', age: '', marked: false} as FormStateBeforeValidation, testSchema);
|
|
30
|
+
|
|
31
|
+
// afterEach(cleanup);
|
|
32
|
+
|
|
33
|
+
test('Field component works fine in basic usage.', async () => {
|
|
34
|
+
const TestFormHook = createTestHook();
|
|
35
|
+
|
|
36
|
+
const Top = () => {
|
|
37
|
+
return (
|
|
38
|
+
<div>
|
|
39
|
+
<Field controller={TestFormHook.controller} name="age">{
|
|
40
|
+
(tool) => <input data-testid="age-input" {...tool} />
|
|
41
|
+
}</Field>
|
|
42
|
+
</div>
|
|
43
|
+
)
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
render(<Top />);
|
|
47
|
+
|
|
48
|
+
const INPUT_AGE = '42';
|
|
49
|
+
|
|
50
|
+
// calling `userEvent` in here will cause race condition...
|
|
51
|
+
await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
|
|
52
|
+
|
|
53
|
+
await waitFor(() => {
|
|
54
|
+
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
55
|
+
expect(ageInput.value).toBe(INPUT_AGE);
|
|
56
|
+
TestFormHook.api.actions.peek((s) => {
|
|
57
|
+
expect(s.value.age).toBe(INPUT_AGE);
|
|
58
|
+
expect(s.errors.age).toBeNull();
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('Slice component works fine in basic usage.', async () => {
|
|
64
|
+
const TestFormHook = createTestHook();
|
|
65
|
+
|
|
66
|
+
const Top = () => {
|
|
67
|
+
return (
|
|
68
|
+
<div>
|
|
69
|
+
<Slicer controller={TestFormHook.controller} selector={s => [s.value.age] as const}>{
|
|
70
|
+
(tool, age: string) => <input data-testid="age-input" name="age" value={age} onChange={e => tool.handleChange('age' as const, e.target.value)} />
|
|
71
|
+
}</Slicer>
|
|
72
|
+
</div>
|
|
73
|
+
)
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
render(<Top />);
|
|
77
|
+
|
|
78
|
+
const INPUT_AGE = '42';
|
|
79
|
+
|
|
80
|
+
// calling `userEvent` in here will cause race condition...
|
|
81
|
+
await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
|
|
82
|
+
|
|
83
|
+
await waitFor(() => {
|
|
84
|
+
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
85
|
+
expect(ageInput.value).toBe(INPUT_AGE);
|
|
86
|
+
TestFormHook.api.actions.peek((s) => {
|
|
87
|
+
expect(s.value.age).toBe(INPUT_AGE);
|
|
88
|
+
expect(s.errors.age).toBeNull();
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
import type {SliceProps, FieldProps, StateRestriction, Controller, } from './index';
|
|
4
|
+
|
|
5
|
+
type ControlledComponentProps<State, Props> = Props & {
|
|
6
|
+
controller: Controller<State>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function Slicer<State extends StateRestriction, R extends ReadonlyArray<unknown>>(props: ControlledComponentProps<State, SliceProps<State, R>>) {
|
|
10
|
+
const {controller, ...restProps} = props;
|
|
11
|
+
const {Slicer: Delegate} = controller.components;
|
|
12
|
+
return <Delegate {...restProps} />;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function Field<State extends StateRestriction, Name extends keyof State>(props: ControlledComponentProps<State, FieldProps<State, Name>>) {
|
|
16
|
+
const {controller, ...restProps} = props;
|
|
17
|
+
const {Field: Delegate} = controller.components;
|
|
18
|
+
return <Delegate {...restProps} />;
|
|
19
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import {render, screen, waitFor} from '@testing-library/react';
|
|
2
|
+
import userEvent from '@testing-library/user-event';
|
|
3
|
+
import React from 'react';
|
|
4
|
+
|
|
5
|
+
import {test, expect} from 'vitest';
|
|
6
|
+
|
|
7
|
+
import * as zod from 'zod';
|
|
8
|
+
|
|
9
|
+
import {createFormHook, useFormSlice} from './index';
|
|
10
|
+
|
|
11
|
+
import type {Controller} from './index';
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
const testSchema = zod.object({
|
|
15
|
+
name: zod.string(),
|
|
16
|
+
description: zod.string(),
|
|
17
|
+
age: zod.string().transform(val => Number(val)).refine(val => Number.isNaN(val) ? 0 : val),
|
|
18
|
+
marked: zod.boolean(),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// every fields are optional for test
|
|
22
|
+
type FormStateBeforeValidation = {
|
|
23
|
+
name: string;
|
|
24
|
+
description: string;
|
|
25
|
+
age: string;
|
|
26
|
+
marked: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const createTestHook = () => createFormHook({name:'', description: '', age: '', marked: false} as FormStateBeforeValidation, testSchema);
|
|
30
|
+
|
|
31
|
+
const AgeInputComponent = (props: {controller: Controller<FormStateBeforeValidation>}) => {
|
|
32
|
+
const {controller} = props;
|
|
33
|
+
const [[age, errorMessage], {handleChange}] = useFormSlice(controller, s => [s.value.age, s.errors.age] as const);
|
|
34
|
+
return (
|
|
35
|
+
<div>
|
|
36
|
+
<input
|
|
37
|
+
data-testid="age-input"
|
|
38
|
+
value={age}
|
|
39
|
+
name="age"
|
|
40
|
+
onChange={(e) => {
|
|
41
|
+
handleChange('age' as const, e.currentTarget.value);
|
|
42
|
+
}}
|
|
43
|
+
/>
|
|
44
|
+
<span data-testid="age-error">{errorMessage}</span>
|
|
45
|
+
</div>
|
|
46
|
+
);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// afterEach(cleanup);
|
|
50
|
+
|
|
51
|
+
test('useSelector can select the fields', async () => {
|
|
52
|
+
const TestFormHook = createTestHook();
|
|
53
|
+
|
|
54
|
+
const Top = () => {
|
|
55
|
+
return (
|
|
56
|
+
<div>
|
|
57
|
+
<AgeInputComponent controller={TestFormHook.controller} />
|
|
58
|
+
</div>
|
|
59
|
+
)
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
render(<Top />);
|
|
63
|
+
|
|
64
|
+
const INPUT_AGE = '4';
|
|
65
|
+
|
|
66
|
+
// fireEvent.change(screen.getByTestId('age-input') , {target: {value: INPUT_AGE}})
|
|
67
|
+
// calling `userEvent` in here will cause race condition...
|
|
68
|
+
await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
|
|
69
|
+
// TestFormHook.actions.handleBulkChange(prev => ({...prev, name: 'test', description: 'desc'}));
|
|
70
|
+
|
|
71
|
+
await waitFor(() => {
|
|
72
|
+
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
73
|
+
expect(ageInput.value).toBe(INPUT_AGE);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('zod parse value before submit', async () => {
|
|
78
|
+
const TestFormHook = createTestHook();
|
|
79
|
+
|
|
80
|
+
const INPUT_AGE = '9';
|
|
81
|
+
const PARSED_RESULT = Number(INPUT_AGE);
|
|
82
|
+
|
|
83
|
+
const handleSubmitTester = TestFormHook.handleSubmit((e) => (result) => {
|
|
84
|
+
if (result.success) {
|
|
85
|
+
expect(result.data.age).toBe(PARSED_RESULT);
|
|
86
|
+
} else {
|
|
87
|
+
expect('should not called').toBe(result.error);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const Top = () => {
|
|
92
|
+
return (
|
|
93
|
+
<div>
|
|
94
|
+
<AgeInputComponent controller={TestFormHook} />
|
|
95
|
+
<button data-testid="submit-button" onClick={handleSubmitTester} />
|
|
96
|
+
</div>
|
|
97
|
+
)
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
render(<Top />);
|
|
101
|
+
|
|
102
|
+
const ageInput: HTMLInputElement = screen.getByTestId('age-input') ;
|
|
103
|
+
await userEvent.type(ageInput, INPUT_AGE);
|
|
104
|
+
|
|
105
|
+
await waitFor(() => {
|
|
106
|
+
const ageInput: HTMLInputElement = screen.getByTestId('age-input') ;
|
|
107
|
+
expect(ageInput.value).toBe(INPUT_AGE);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const submitButton = screen.getByTestId('submit-button');
|
|
111
|
+
await userEvent.click(submitButton);
|
|
112
|
+
|
|
113
|
+
await waitFor(() => {
|
|
114
|
+
console.log('waiting');
|
|
115
|
+
TestFormHook.api.actions.peek((s) => {
|
|
116
|
+
expect(s.value.age).toBe(INPUT_AGE);
|
|
117
|
+
expect(s.errors.age).toBeNull();
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import {createStore} from 'nozuchi';
|
|
2
|
+
import {createElement, Fragment, useEffect, useMemo} from 'react';
|
|
3
|
+
|
|
4
|
+
import {isChangeEvent} from './utils';
|
|
5
|
+
|
|
6
|
+
import type {Subscriber} from 'nozuchi';
|
|
7
|
+
import type {BaseSyntheticEvent, ChangeEvent, ReactNode, ReactElement} from 'react';
|
|
8
|
+
|
|
9
|
+
import type {infer as zodInfer, SafeParseReturnType, ZodIssue, ZodType} from 'zod';
|
|
10
|
+
|
|
11
|
+
export type StateRestriction = Record<string, any>;
|
|
12
|
+
|
|
13
|
+
type FormStatus = {
|
|
14
|
+
isDirty: boolean;
|
|
15
|
+
isValid: boolean;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
type FormErrors<State extends StateRestriction> = {
|
|
19
|
+
[k in keyof State]: string | null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type FullFormState<State extends StateRestriction> = FormStatus & {value: State; errors: FormErrors<State>};
|
|
23
|
+
|
|
24
|
+
export type HandleChangeAction<State extends StateRestriction, R = void> = <Name extends keyof State>(name: Name, value: State[Name]) => R;
|
|
25
|
+
|
|
26
|
+
export type FieldProps<State extends StateRestriction, Name extends keyof State> = {
|
|
27
|
+
name: Name;
|
|
28
|
+
children: (
|
|
29
|
+
tool: {
|
|
30
|
+
name: Name;
|
|
31
|
+
value: State[Name];
|
|
32
|
+
onChange(this: void, name: Name, value: State[Name]): void;
|
|
33
|
+
onChange(this: void, e: ChangeEvent<HTMLElement>): void;
|
|
34
|
+
},
|
|
35
|
+
value: State[Name],
|
|
36
|
+
errorMessage: string | null,
|
|
37
|
+
) => ReactNode;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type SliceProps<State extends StateRestriction, Selected extends ReadonlyArray<unknown>> = {
|
|
41
|
+
selector: (s: FullFormState<State>) => Selected;
|
|
42
|
+
children: (tool: {handleChange: HandleChangeAction<State>}, ...value: Readonly<Selected>) => ReactNode;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
type FormControllerBehavior<StateBeforeValidation> = {
|
|
46
|
+
/** For testing */
|
|
47
|
+
peek: (
|
|
48
|
+
eyeball: (prev: FullFormState<StateBeforeValidation>) => void,
|
|
49
|
+
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
50
|
+
|
|
51
|
+
reset: () => () => FullFormState<StateBeforeValidation>;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Initialize form state without validation.
|
|
55
|
+
*/
|
|
56
|
+
initializeForm: (
|
|
57
|
+
initialVal: Partial<StateBeforeValidation>,
|
|
58
|
+
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Handle issue that zod reported
|
|
62
|
+
*/
|
|
63
|
+
handleIssues: (issues: ReadonlyArray<ZodIssue>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* You can handle server side or other external error via this action.
|
|
67
|
+
*/
|
|
68
|
+
handleError: (
|
|
69
|
+
reducer: (prev: FormErrors<StateBeforeValidation>) => FormErrors<StateBeforeValidation>,
|
|
70
|
+
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
*/
|
|
74
|
+
handleChange: HandleChangeAction<
|
|
75
|
+
StateBeforeValidation,
|
|
76
|
+
(prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>
|
|
77
|
+
>;
|
|
78
|
+
|
|
79
|
+
reduceFormState: (
|
|
80
|
+
reducer: (prevValue: StateBeforeValidation) => StateBeforeValidation,
|
|
81
|
+
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
82
|
+
handleBulkChange: (
|
|
83
|
+
setter: (prev: StateBeforeValidation) => Partial<StateBeforeValidation>,
|
|
84
|
+
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const initialFormState = Object.freeze({isDirty: false, isValid: false});
|
|
88
|
+
|
|
89
|
+
function createFormStore<StateBeforeValidation extends StateRestriction, Schema extends ZodType<any, any, any>>(
|
|
90
|
+
initialState: StateBeforeValidation,
|
|
91
|
+
schema: Schema,
|
|
92
|
+
): Subscriber<FullFormState<StateBeforeValidation>, FormControllerBehavior<StateBeforeValidation>> {
|
|
93
|
+
type FullState = FullFormState<StateBeforeValidation>;
|
|
94
|
+
type Err = FormErrors<StateBeforeValidation>;
|
|
95
|
+
type StateKeys = keyof StateBeforeValidation;
|
|
96
|
+
|
|
97
|
+
const initialErrors = Object.freeze(
|
|
98
|
+
Object.keys(initialState).reduce((buf, k) => {
|
|
99
|
+
buf[k as StateKeys] = null;
|
|
100
|
+
return buf;
|
|
101
|
+
}, {} as any as Err),
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const fullInitialState: FullState = Object.freeze({
|
|
105
|
+
...initialFormState,
|
|
106
|
+
value: {...initialState},
|
|
107
|
+
errors: {...initialErrors},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const withValidation = (prev: FullState, newValue: StateBeforeValidation) => {
|
|
111
|
+
const result = schema.safeParse(newValue);
|
|
112
|
+
if (result.success) {
|
|
113
|
+
return {...prev, isDirty: true, isValid: true, value: newValue, errors: initialErrors};
|
|
114
|
+
}
|
|
115
|
+
const newErrors = result.error.issues.reduce((buf, iss) => {
|
|
116
|
+
// TODO: should support nested value?
|
|
117
|
+
const shallowPath = iss.path[0];
|
|
118
|
+
if (shallowPath === undefined) {
|
|
119
|
+
return buf;
|
|
120
|
+
}
|
|
121
|
+
buf[shallowPath as any as StateKeys] = iss.message;
|
|
122
|
+
return buf;
|
|
123
|
+
}, {} as any as Err);
|
|
124
|
+
|
|
125
|
+
return {...prev, isDirty: true, isValid: false, errors: newErrors, value: newValue};
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
return createStore(fullInitialState, {
|
|
129
|
+
peek: (eyeball) => (prev) => {
|
|
130
|
+
eyeball(prev);
|
|
131
|
+
return prev;
|
|
132
|
+
},
|
|
133
|
+
|
|
134
|
+
reset: () => () => fullInitialState,
|
|
135
|
+
initializeForm: (initialVal) => (prev) => ({
|
|
136
|
+
...prev,
|
|
137
|
+
value: {...prev.value, ...initialVal},
|
|
138
|
+
errors: {...initialErrors},
|
|
139
|
+
}),
|
|
140
|
+
handleIssues: (issues) => (prev) => {
|
|
141
|
+
// FIXME: handle duplication
|
|
142
|
+
const newErrors = issues.reduce((buf, iss) => {
|
|
143
|
+
const shallowPath = iss.path[0];
|
|
144
|
+
if (shallowPath === undefined) {
|
|
145
|
+
return buf;
|
|
146
|
+
}
|
|
147
|
+
buf[shallowPath as any as StateKeys] = iss.message;
|
|
148
|
+
return buf;
|
|
149
|
+
}, {} as any as Err);
|
|
150
|
+
|
|
151
|
+
return {...prev, isDirty: true, isValid: false, errors: newErrors};
|
|
152
|
+
},
|
|
153
|
+
handleError: (reducer) => (prev) => {
|
|
154
|
+
return {...prev, errors: reducer(prev.errors)};
|
|
155
|
+
},
|
|
156
|
+
handleChange: (name, value) => (prev) => {
|
|
157
|
+
if (name in prev.value === false) {
|
|
158
|
+
return prev;
|
|
159
|
+
}
|
|
160
|
+
const newValue = {...prev.value, [name]: value};
|
|
161
|
+
return withValidation(prev, newValue);
|
|
162
|
+
},
|
|
163
|
+
reduceFormState: (reducer) => (prev) => {
|
|
164
|
+
const reducedState = reducer(prev.value);
|
|
165
|
+
return withValidation(prev, reducedState);
|
|
166
|
+
},
|
|
167
|
+
handleBulkChange: (setter) => (prev) => {
|
|
168
|
+
const mergedNewState = {...prev.value, ...setter(prev.value)};
|
|
169
|
+
return withValidation(prev, mergedNewState);
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
type ActionsCanBePublic<State extends StateRestriction> = {
|
|
175
|
+
reset: VoidFunction;
|
|
176
|
+
initializeForm: (initial: Partial<State>) => void;
|
|
177
|
+
handleChange: HandleChangeAction<State>;
|
|
178
|
+
handleBulkChange: (setter: (prev: State) => Partial<State>) => void;
|
|
179
|
+
handleError: (reducer: (prev: FormErrors<State>) => FormErrors<State>) => void;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Restricted type interface of the form store
|
|
184
|
+
* TODO: more restriction
|
|
185
|
+
*/
|
|
186
|
+
export type Controller<State extends StateRestriction> = {
|
|
187
|
+
useInitialize: (initialValue: Partial<State>) => void;
|
|
188
|
+
useSelector: <R>(selector: (state: FullFormState<State>) => R, isEqual?: (prev: R, current: R) => boolean) => R;
|
|
189
|
+
|
|
190
|
+
actions: ActionsCanBePublic<State>;
|
|
191
|
+
components: {
|
|
192
|
+
Field: <Name extends keyof State>(props: FieldProps<State, Name>) => ReactElement<any, any> | null;
|
|
193
|
+
Slicer: <Selected extends ReadonlyArray<unknown>>(props: SliceProps<State, Selected>) => ReactElement<any, any> | null;
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
type FormHook<State extends StateRestriction, Schema extends ZodType<any, any, any>> = {
|
|
198
|
+
controller: Controller<State>;
|
|
199
|
+
|
|
200
|
+
handleSubmit: (
|
|
201
|
+
handler: (
|
|
202
|
+
e: BaseSyntheticEvent,
|
|
203
|
+
) => (
|
|
204
|
+
val: {success: true; data: zodInfer<Schema>; error: undefined} | {success: false; error: ReadonlyArray<ZodIssue>},
|
|
205
|
+
) => void | Promise<void>,
|
|
206
|
+
) => (e: BaseSyntheticEvent) => void;
|
|
207
|
+
|
|
208
|
+
api: Subscriber<FullFormState<State>, FormControllerBehavior<State>>;
|
|
209
|
+
} & Controller<State>;
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @typeParam InitialState should be shallow
|
|
213
|
+
*/
|
|
214
|
+
export function createFormHook<StateBeforeValidation, Schema extends ZodType<any, any, any>>(
|
|
215
|
+
initialState: StateBeforeValidation,
|
|
216
|
+
schema: Schema,
|
|
217
|
+
): FormHook<StateBeforeValidation, Schema> {
|
|
218
|
+
const store = createFormStore(initialState, schema);
|
|
219
|
+
|
|
220
|
+
const formHook = {
|
|
221
|
+
useInitialize: (initialValue: Partial<StateBeforeValidation>) => {
|
|
222
|
+
useEffect(() => {
|
|
223
|
+
store.actions.initializeForm(initialValue);
|
|
224
|
+
}, []);
|
|
225
|
+
},
|
|
226
|
+
useSelector: store.useSelector,
|
|
227
|
+
handleSubmit: (
|
|
228
|
+
handler: (
|
|
229
|
+
e: BaseSyntheticEvent,
|
|
230
|
+
) => (
|
|
231
|
+
val: {success: true; data: zodInfer<Schema>; error: undefined} | {success: false; error: ReadonlyArray<ZodIssue>},
|
|
232
|
+
) => void | Promise<void>,
|
|
233
|
+
) => {
|
|
234
|
+
return (e: BaseSyntheticEvent) => {
|
|
235
|
+
const eventHandled = handler(e);
|
|
236
|
+
const value = store.getState().value;
|
|
237
|
+
return schema.safeParseAsync(value).then((result: SafeParseReturnType<StateBeforeValidation, zodInfer<typeof schema>>) => {
|
|
238
|
+
// FIXME: hook formを捨ててzodのバージョンをあげればこの辺に型をつけられる
|
|
239
|
+
if (result.success) {
|
|
240
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
241
|
+
return eventHandled({success: true, data: result.data, error: undefined});
|
|
242
|
+
}
|
|
243
|
+
void eventHandled({success: false, error: result.error.issues});
|
|
244
|
+
store.actions.handleIssues(result.error.issues);
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
components: {
|
|
250
|
+
Slicer<R extends ReadonlyArray<unknown>>(props: SliceProps<StateBeforeValidation, R>) {
|
|
251
|
+
const {selector, children} = props;
|
|
252
|
+
const value = formHook.useSelector(selector);
|
|
253
|
+
return useMemo(() => {
|
|
254
|
+
const renderContent = children({handleChange: formHook.actions.handleChange}, ...value);
|
|
255
|
+
return createElement(Fragment, {}, renderContent);
|
|
256
|
+
}, value);
|
|
257
|
+
},
|
|
258
|
+
Field<Name extends keyof StateBeforeValidation>(props: FieldProps<StateBeforeValidation, Name>) {
|
|
259
|
+
const {name, children} = props;
|
|
260
|
+
const [value, errMsg] = store.useSelector((s) => [s.value[name], s.errors[name]] as const);
|
|
261
|
+
return useMemo(() => {
|
|
262
|
+
const renderContent = children(
|
|
263
|
+
{
|
|
264
|
+
name,
|
|
265
|
+
value,
|
|
266
|
+
onChange: (name_or_event: unknown, value_or_none?: unknown) => {
|
|
267
|
+
if (typeof name_or_event === 'string') {
|
|
268
|
+
// assumes name is valid if it's string
|
|
269
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
270
|
+
return store.actions.handleChange(name_or_event as Name, value_or_none as any);
|
|
271
|
+
}
|
|
272
|
+
if (isChangeEvent(name_or_event)) {
|
|
273
|
+
const target: any = name_or_event.currentTarget || name_or_event.target;
|
|
274
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
|
|
275
|
+
return store.actions.handleChange(target.name, target.value);
|
|
276
|
+
}
|
|
277
|
+
throw new Error('`handleChange` handles unexpected formed object.');
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
value,
|
|
281
|
+
errMsg,
|
|
282
|
+
);
|
|
283
|
+
return createElement(Fragment, {}, renderContent);
|
|
284
|
+
}, [value, errMsg]);
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
actions: store.actions,
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
controller: formHook,
|
|
292
|
+
api: store,
|
|
293
|
+
...formHook,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function useFormSlice<State extends StateRestriction, Sliced>(
|
|
298
|
+
formController: Controller<State>,
|
|
299
|
+
selector: (s: FullFormState<State>) => Sliced,
|
|
300
|
+
) {
|
|
301
|
+
const sliced = formController.useSelector((s) => selector(s));
|
|
302
|
+
return [sliced, formController.actions] as const;
|
|
303
|
+
}
|