mayoiga 0.0.22 → 0.1.3

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.
Files changed (64) hide show
  1. package/.eslintrc.js +111 -0
  2. package/.github/workflows/checker.yml +42 -0
  3. package/.gitignore +217 -0
  4. package/.prettierrc +5 -0
  5. package/README.md +21 -45
  6. package/component.d.ts +1 -0
  7. package/component.js +1 -0
  8. package/dist/component.d.ts +7 -0
  9. package/dist/component.js +11 -0
  10. package/dist/component.test.d.ts +1 -0
  11. package/dist/component.test.js +83 -0
  12. package/dist/index.d.ts +92 -0
  13. package/dist/index.js +150 -0
  14. package/dist/index.test.d.ts +1 -0
  15. package/dist/index.test.js +77 -0
  16. package/dist/utils.d.ts +2 -0
  17. package/dist/utils.js +6 -0
  18. package/docs/.nojekyll +0 -0
  19. package/docs/assets/css/main.css +2328 -0
  20. package/docs/assets/images/icons.png +0 -0
  21. package/docs/assets/images/icons@2x.png +0 -0
  22. package/docs/assets/images/widgets.png +0 -0
  23. package/docs/assets/images/widgets@2x.png +0 -0
  24. package/docs/assets/js/main.js +1 -0
  25. package/docs/assets/js/search.js +3 -0
  26. package/docs/globals.html +185 -0
  27. package/docs/index.html +249 -0
  28. package/docs/modules/_actions_.html +398 -0
  29. package/docs/modules/_forms_.html +362 -0
  30. package/docs/modules/_index_.html +170 -0
  31. package/docs/modules/_inputprotocol_.html +319 -0
  32. package/docs/modules/_mayoiga_.html +783 -0
  33. package/docs/modules/_reducer_.html +417 -0
  34. package/example/src/demo-app.tsx +123 -0
  35. package/example/src/index.tsx +15 -0
  36. package/package.json +42 -44
  37. package/setup/vite-global-setup.js +1 -0
  38. package/setup/vite-set-global.js +0 -0
  39. package/src/component.test.tsx +146 -0
  40. package/src/component.tsx +23 -0
  41. package/src/index.test.tsx +122 -0
  42. package/src/index.ts +311 -0
  43. package/src/utils.ts +8 -0
  44. package/tsconfig.json +38 -0
  45. package/vite.config.js +10 -0
  46. package/yarn.lock +2378 -0
  47. package/lib/actions.d.ts +0 -28
  48. package/lib/actions.js +0 -29
  49. package/lib/actions.js.map +0 -1
  50. package/lib/forms.d.ts +0 -21
  51. package/lib/forms.js +0 -82
  52. package/lib/forms.js.map +0 -1
  53. package/lib/index.d.ts +0 -3
  54. package/lib/index.js +0 -7
  55. package/lib/index.js.map +0 -1
  56. package/lib/inputProtocol.d.ts +0 -17
  57. package/lib/inputProtocol.js +0 -24
  58. package/lib/inputProtocol.js.map +0 -1
  59. package/lib/mayoiga.d.ts +0 -110
  60. package/lib/mayoiga.js +0 -131
  61. package/lib/mayoiga.js.map +0 -1
  62. package/lib/reducer.d.ts +0 -20
  63. package/lib/reducer.js +0 -53
  64. package/lib/reducer.js.map +0 -1
package/.eslintrc.js ADDED
@@ -0,0 +1,111 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ plugins: ['@typescript-eslint/eslint-plugin', "testing-library"],
4
+ extends: [
5
+ 'eslint:recommended',
6
+ 'plugin:@typescript-eslint/recommended',
7
+ // Lintの時間があまりに長いようなら無効化も考える
8
+ 'plugin:@typescript-eslint/recommended-requiring-type-checking',
9
+
10
+ 'plugin:import/errors',
11
+ 'plugin:import/typescript',
12
+ 'plugin:testing-library/react',
13
+ ],
14
+ parserOptions: {
15
+ project: './tsconfig.json',
16
+ ecmaVersion: 'next',
17
+ sourceType: 'module',
18
+ ecaFeatures: {
19
+ jsx: true,
20
+ },
21
+ },
22
+ rules: {
23
+ curly: 'error',
24
+ eqeqeq: ['error', 'smart'],
25
+
26
+ 'no-return-await': 'error',
27
+ 'require-await': 'error',
28
+ 'no-await-in-loop': 'error',
29
+
30
+ '@typescript-eslint/prefer-readonly': 'error',
31
+ // '@typescript-eslint/prefer-readonly-parameter-types': ["error", {ignoreInferredTypes: true}],
32
+ '@typescript-eslint/array-type': ['error', {default: 'generic', readonly: 'generic'}],
33
+ '@typescript-eslint/consistent-type-imports': [
34
+ 'error',
35
+ {
36
+ prefer: 'type-imports',
37
+ },
38
+ ],
39
+
40
+ 'padding-line-between-statements': [
41
+ 'error',
42
+ {blankLine: 'always', prev: 'multiline-const', next: 'multiline-const'},
43
+ {blankLine: 'always', prev: '*', next: 'function'},
44
+ {blankLine: 'always', prev: '*', next: 'class'},
45
+ {blankLine: 'always', prev: '*', next: 'export'},
46
+ ],
47
+
48
+ 'no-use-before-define': 'off',
49
+ '@typescript-eslint/no-use-before-define': ['error'],
50
+
51
+ 'no-unused-vars': 'off',
52
+ '@typescript-eslint/no-unused-vars': [
53
+ 'error',
54
+ {
55
+ vars: 'all',
56
+ args: 'none',
57
+ ignoreRestSiblings: true,
58
+
59
+ argsIgnorePattern: '^_',
60
+ varsIgnorePattern: '^_',
61
+ },
62
+ ],
63
+
64
+ '@typescript-eslint/explicit-function-return-type': 'off',
65
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
66
+ '@typescript-eslint/no-explicit-any': 'off',
67
+
68
+ // 要検討
69
+ '@typescript-eslint/no-unsafe-assignment': 'off',
70
+ // voidとのunionで微妙な挙動をするので一旦停止
71
+ '@typescript-eslint/no-misused-promises': [
72
+ 'error',
73
+ {
74
+ checksVoidReturn: false,
75
+ },
76
+ ],
77
+
78
+ 'import/newline-after-import': 'error',
79
+ 'import/named': 'off',
80
+ 'import/no-named-default': 'error',
81
+ 'import/no-default-export': 'off',
82
+ 'import/default': 'off',
83
+ 'import/no-useless-path-segments': 'error',
84
+ 'import/order': [
85
+ 'error',
86
+ {
87
+ groups: ['builtin', 'external', 'internal', 'parent', ['index', 'sibling'], 'type'],
88
+ 'newlines-between': 'always-and-inside-groups',
89
+ alphabetize: {
90
+ order: 'asc' /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */,
91
+ caseInsensitive: true /* ignore case. Options: [true, false] */,
92
+ },
93
+ },
94
+ ],
95
+
96
+ },
97
+ settings: {
98
+ 'import/parsers': {
99
+ '@typescript-eslint/parser': ['.js', '.jsx', '.ts', '.tsx'],
100
+ },
101
+
102
+ 'import/ignore': ['node_modules'],
103
+ },
104
+ "overrides": [
105
+ {
106
+ // 3) Now we enable eslint-plugin-testing-library rules or preset only for matching files!
107
+ "files": ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
108
+ "extends": ["plugin:testing-library/react"]
109
+ },
110
+ ]
111
+ };
@@ -0,0 +1,42 @@
1
+ name: Lint Check
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+
8
+ runs-on: ubuntu-latest
9
+
10
+ strategy:
11
+ matrix:
12
+ node-version: [16.x]
13
+
14
+ steps:
15
+ - uses: actions/checkout@v1
16
+ - name: Use Node.js ${{ matrix.node-version }}
17
+ uses: actions/setup-node@v1
18
+ with:
19
+ node-version: ${{ matrix.node-version }}
20
+
21
+ - uses: actions/checkout@v1
22
+ - name: Cache node_modules
23
+ uses: actions/cache@preview
24
+ with:
25
+ path: ~/.cache/yarn
26
+ key: ${{ runner.os }}-projectname-${{ hashFiles(format('{0}{1}', github.workspace, '/yarn.lock')) }}
27
+ restore-keys:
28
+ ${{ runner.os }}-projectname-
29
+
30
+ - name: Install node_modules
31
+ if: steps.cache.outputs.cache-hit != 'true'
32
+ run: |
33
+ npm install -g yarn
34
+ yarn install
35
+
36
+ - name: Lint
37
+ run: |
38
+ yarn check-all
39
+
40
+ - name: Test
41
+ run: |
42
+ yarn test
package/.gitignore ADDED
@@ -0,0 +1,217 @@
1
+
2
+ # Created by https://www.toptal.com/developers/gitignore/api/macos,node,visualstudiocode,vim
3
+ # Edit at https://www.toptal.com/developers/gitignore?templates=macos,node,visualstudiocode,vim
4
+
5
+ ### macOS ###
6
+ # General
7
+ .DS_Store
8
+ .AppleDouble
9
+ .LSOverride
10
+
11
+ # Icon must end with two \r
12
+ Icon
13
+
14
+
15
+ # Thumbnails
16
+ ._*
17
+
18
+ # Files that might appear in the root of a volume
19
+ .DocumentRevisions-V100
20
+ .fseventsd
21
+ .Spotlight-V100
22
+ .TemporaryItems
23
+ .Trashes
24
+ .VolumeIcon.icns
25
+ .com.apple.timemachine.donotpresent
26
+
27
+ # Directories potentially created on remote AFP share
28
+ .AppleDB
29
+ .AppleDesktop
30
+ Network Trash Folder
31
+ Temporary Items
32
+ .apdisk
33
+
34
+ ### Node ###
35
+ # Logs
36
+ logs
37
+ *.log
38
+ npm-debug.log*
39
+ yarn-debug.log*
40
+ yarn-error.log*
41
+ lerna-debug.log*
42
+ .pnpm-debug.log*
43
+
44
+ # Diagnostic reports (https://nodejs.org/api/report.html)
45
+ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
46
+
47
+ # Runtime data
48
+ pids
49
+ *.pid
50
+ *.seed
51
+ *.pid.lock
52
+
53
+ # Directory for instrumented libs generated by jscoverage/JSCover
54
+ lib-cov
55
+
56
+ # Coverage directory used by tools like istanbul
57
+ coverage
58
+ *.lcov
59
+
60
+ # nyc test coverage
61
+ .nyc_output
62
+
63
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
64
+ .grunt
65
+
66
+ # Bower dependency directory (https://bower.io/)
67
+ bower_components
68
+
69
+ # node-waf configuration
70
+ .lock-wscript
71
+
72
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
73
+ build/Release
74
+
75
+ # Dependency directories
76
+ node_modules/
77
+ jspm_packages/
78
+
79
+ # Snowpack dependency directory (https://snowpack.dev/)
80
+ web_modules/
81
+
82
+ # TypeScript cache
83
+ *.tsbuildinfo
84
+
85
+ # Optional npm cache directory
86
+ .npm
87
+
88
+ # Optional eslint cache
89
+ .eslintcache
90
+
91
+ # Optional stylelint cache
92
+ .stylelintcache
93
+
94
+ # Microbundle cache
95
+ .rpt2_cache/
96
+ .rts2_cache_cjs/
97
+ .rts2_cache_es/
98
+ .rts2_cache_umd/
99
+
100
+ # Optional REPL history
101
+ .node_repl_history
102
+
103
+ # Output of 'npm pack'
104
+ *.tgz
105
+
106
+ # Yarn Integrity file
107
+ .yarn-integrity
108
+
109
+ # dotenv environment variable files
110
+ .env
111
+ .env.development.local
112
+ .env.test.local
113
+ .env.production.local
114
+ .env.local
115
+
116
+ # parcel-bundler cache (https://parceljs.org/)
117
+ .cache
118
+ .parcel-cache
119
+
120
+ # Next.js build output
121
+ .next
122
+ out
123
+
124
+ # Nuxt.js build / generate output
125
+ .nuxt
126
+ dist
127
+
128
+ # Gatsby files
129
+ .cache/
130
+ # Comment in the public line in if your project uses Gatsby and not Next.js
131
+ # https://nextjs.org/blog/next-9-1#public-directory-support
132
+ # public
133
+
134
+ # vuepress build output
135
+ .vuepress/dist
136
+
137
+ # vuepress v2.x temp and cache directory
138
+ .temp
139
+
140
+ # Docusaurus cache and generated files
141
+ .docusaurus
142
+
143
+ # Serverless directories
144
+ .serverless/
145
+
146
+ # FuseBox cache
147
+ .fusebox/
148
+
149
+ # DynamoDB Local files
150
+ .dynamodb/
151
+
152
+ # TernJS port file
153
+ .tern-port
154
+
155
+ # Stores VSCode versions used for testing VSCode extensions
156
+ .vscode-test
157
+
158
+ # yarn v2
159
+ .yarn/cache
160
+ .yarn/unplugged
161
+ .yarn/build-state.yml
162
+ .yarn/install-state.gz
163
+ .pnp.*
164
+
165
+ ### Node Patch ###
166
+ # Serverless Webpack directories
167
+ .webpack/
168
+
169
+ # Optional stylelint cache
170
+
171
+ # SvelteKit build / generate output
172
+ .svelte-kit
173
+
174
+ ### Vim ###
175
+ # Swap
176
+ [._]*.s[a-v][a-z]
177
+ !*.svg # comment out if you don't need vector files
178
+ [._]*.sw[a-p]
179
+ [._]s[a-rt-v][a-z]
180
+ [._]ss[a-gi-z]
181
+ [._]sw[a-p]
182
+
183
+ # Session
184
+ Session.vim
185
+ Sessionx.vim
186
+
187
+ # Temporary
188
+ .netrwhist
189
+ *~
190
+ # Auto-generated tag files
191
+ tags
192
+ # Persistent undo
193
+ [._]*.un~
194
+
195
+ ### VisualStudioCode ###
196
+ .vscode/*
197
+ !.vscode/settings.json
198
+ !.vscode/tasks.json
199
+ !.vscode/launch.json
200
+ !.vscode/extensions.json
201
+ !.vscode/*.code-snippets
202
+
203
+ # Local History for Visual Studio Code
204
+ .history/
205
+
206
+ # Built Visual Studio Code Extensions
207
+ *.vsix
208
+
209
+ ### VisualStudioCode Patch ###
210
+ # Ignore all local history of files
211
+ .history
212
+ .ionide
213
+
214
+ # Support for Project snippet scope
215
+
216
+ # End of https://www.toptal.com/developers/gitignore/api/macos,node,visualstudiocode,vim
217
+
package/.prettierrc ADDED
@@ -0,0 +1,5 @@
1
+ printWidth: 140
2
+ parser: typescript
3
+ bracketSpacing: false
4
+ trailingComma: all
5
+ singleQuote: true
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ [![Lint Check](https://github.com/hachibeeDI/mayoiga/actions/workflows/checker.yml/badge.svg)](https://github.com/hachibeeDI/mayoiga/actions/workflows/checker.yml)
2
+
1
3
  # Mayoiga
2
4
 
3
5
  The React Hook based form library. Of course it is TypeScript friendly.
@@ -13,8 +15,6 @@ The React Hook based form library. Of course it is TypeScript friendly.
13
15
 
14
16
  With less boilerplate code!!
15
17
 
16
- You can see more working demo [under the example directory](example/src/demo-app.tsx) .
17
-
18
18
 
19
19
  ## How to use
20
20
 
@@ -23,62 +23,38 @@ You can see more working demo [under the example directory](example/src/demo-app
23
23
  There are only two functions which you should know to use Mayoiga.
24
24
 
25
25
  - [useForm](https://hachibeedi.github.io/mayoiga/modules/_mayoiga_.html#useform)
26
- - [createFormScope](https://hachibeedi.github.io/mayoiga/modules/_mayoiga_.html#createformscope)
27
-
28
- And if you would like to bring it to production, you need to know how to about [InputProtocol](https://hachibeedi.github.io/mayoiga/modules/_inputprotocol_.html#inputprotocol).
29
- To know about that, `mayoiga/lib/forms` can be a good example.
30
26
 
31
- There is a short article which explains Mayoiga https://dev.to/hachibeedi/react-use-form-type-safe-react-hooks-based-form-utility-4k5h.
27
+ - [createFormScope](https://hachibeedi.github.io/mayoiga/modules/_mayoiga_.html#createformscope)
32
28
 
33
29
 
34
30
  ### Minimum example:
35
31
 
36
32
  ```typeScript
37
33
 
38
- import * as React from 'react';
39
- import {FC} from 'react';
40
-
41
- import {useForm, createFormScope} from 'mayoiga';
42
- import {Input, NumberInput} from 'mayoiga/lib/forms';
34
+ const TestFormHook = createFormHook({name:'', description: '', age: ''} as FormStateBeforeValidation, testSchema);
43
35
 
44
- const required = (target: string) => (target.length === 0 ? 'required' : undefined);
36
+ const INPUT_AGE = '9';
37
+ const PARSED_RESULT = Number(INPUT_AGE);
45
38
 
46
- const between = (min: number, max: number) => (target: number) => {
47
- if (target < min) {
48
- return `more than ${min}`;
39
+ const handleSubmitTester = TestFormHook.handleSubmit((e) => (result) => {
40
+ if (result.success) {
41
+ expect(result.data.age).toBe(PARSED_RESULT);
42
+ } else {
43
+ expect('should not called').toBe(result.err);
49
44
  }
50
- if (target > max) {
51
- return `less than ${max}`;
52
- }
53
- };
54
-
55
- const choice = function<T>(...candidates: Array<T>) {
56
- return (target: T) => (candidates.includes(target) ? undefined : 'You should choose from the candidates.');
57
- };
45
+ });
58
46
 
59
- const INITIAL_FORM_STATE = {
60
- name: '',
61
- age: 13,
62
- seed: 'fish',
47
+ const Top = () => {
48
+ return (
49
+ <div>
50
+ <AgeInputComponent formHook={TestFormHook} />
51
+ <button data-testid="submit-button" onClick={handleSubmitTester} />
52
+ </div>
53
+ )
63
54
  };
64
55
 
65
- const {context, scope} = createFormScope<typeof INITIAL_FORM_STATE>();
66
-
67
- const DemoForm = scope(props => {
68
- const {Form, Field} = useForm(context);
69
- return (
70
- <Form onSubmit={value => console.log(value)}>
71
- <Field name="name" component={Input} validations={[required]} />
72
- <Field name="age" component={NumberInput} validations={[between(5, 20)]} />
73
- <Field name="seed" component={Input} validations={[choice('fish', 'squid', 'octopus')]} />
74
-
75
- <button disabled={!props.touched || Object.values(props.errors).some(e => !!e.length)}>submit</button>
76
- </Form>
77
- );
56
+ act(() => {
57
+ render(<Top />);
78
58
  });
79
59
 
80
- export default function DemoApp() {
81
- return <DemoForm initialState={INITIAL_FORM_STATE} onSubmit={value => alert(`submit ${JSON.stringify(value)}`)} />;
82
- }
83
-
84
60
  ```
package/component.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {Slicer, Field} from "./dist/component";
package/component.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/component.js');
@@ -0,0 +1,7 @@
1
+ import type { SliceProps, FieldProps, StateRestriction, Controller } from './index';
2
+ declare type ControlledComponentProps<State, Props> = Props & {
3
+ controller: Controller<State>;
4
+ };
5
+ export declare function Slicer<State extends StateRestriction, R extends ReadonlyArray<unknown>>(props: ControlledComponentProps<State, SliceProps<State, R>>): JSX.Element;
6
+ export declare function Field<State extends StateRestriction, Name extends keyof State>(props: ControlledComponentProps<State, FieldProps<State, Name>>): JSX.Element;
7
+ export {};
@@ -0,0 +1,11 @@
1
+ import React from 'react';
2
+ export function Slicer(props) {
3
+ const { controller, ...restProps } = props;
4
+ const { Slicer: Delegate } = controller.components;
5
+ return React.createElement(Delegate, { ...restProps });
6
+ }
7
+ export function Field(props) {
8
+ const { controller, ...restProps } = props;
9
+ const { Field: Delegate } = controller.components;
10
+ return React.createElement(Delegate, { ...restProps });
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,83 @@
1
+ import { render, screen, waitFor } from '@testing-library/react';
2
+ import userEvent from '@testing-library/user-event';
3
+ import React from 'react';
4
+ import { test, expect } from 'vitest';
5
+ import * as zod from 'zod';
6
+ import { Field, Slicer } from './component';
7
+ import { createFormHook } from './index';
8
+ const testSchema = zod.object({
9
+ name: zod.string(),
10
+ description: zod.string(),
11
+ age: zod
12
+ .string()
13
+ .transform((val) => Number(val))
14
+ .refine((val) => (Number.isNaN(val) ? 0 : val)),
15
+ marked: zod.boolean(),
16
+ });
17
+ const createTestHook = () => createFormHook({ name: '', description: '', age: '', marked: false }, testSchema);
18
+ // afterEach(cleanup);
19
+ test('Field component works fine in basic usage.', async () => {
20
+ const TestFormHook = createTestHook();
21
+ const Top = () => {
22
+ return (React.createElement("div", null,
23
+ React.createElement(Field, { controller: TestFormHook.controller, name: "age" }, (tool) => React.createElement("input", { "data-testid": "age-input", ...tool }))));
24
+ };
25
+ render(React.createElement(Top, null));
26
+ const INPUT_AGE = '42';
27
+ // calling `userEvent` in here will cause race condition...
28
+ await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
29
+ await waitFor(() => {
30
+ const ageInput = screen.getByTestId('age-input');
31
+ expect(ageInput.value).toBe(INPUT_AGE);
32
+ TestFormHook.api.actions.peek((s) => {
33
+ expect(s.value.age).toBe(INPUT_AGE);
34
+ expect(s.errors.age).toBeNull();
35
+ });
36
+ });
37
+ });
38
+ test('Slice component works fine in basic usage.', async () => {
39
+ const TestFormHook = createTestHook();
40
+ const Top = () => {
41
+ return (React.createElement("div", null,
42
+ React.createElement(Slicer, { controller: TestFormHook.controller, selector: (s) => [s.value.age] }, (tool, age) => (React.createElement("input", { "data-testid": "age-input", name: "age", value: age, onChange: (e) => tool.handleChange('age', e.target.value) })))));
43
+ };
44
+ render(React.createElement(Top, null));
45
+ const INPUT_AGE = '42';
46
+ // calling `userEvent` in here will cause race condition...
47
+ await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
48
+ await waitFor(() => {
49
+ const ageInput = screen.getByTestId('age-input');
50
+ expect(ageInput.value).toBe(INPUT_AGE);
51
+ TestFormHook.api.actions.peek((s) => {
52
+ expect(s.value.age).toBe(INPUT_AGE);
53
+ expect(s.errors.age).toBeNull();
54
+ });
55
+ });
56
+ });
57
+ test('A user able to create a reusable component', async () => {
58
+ const TestFormHook = createTestHook();
59
+ function NarrowTypedExpected(props) {
60
+ return (React.createElement(Field, { controller: props.controller, name: "age" }, (tool) => React.createElement("input", { "data-testid": "age-input", ...tool })));
61
+ }
62
+ function ErrorDisplayer(props) {
63
+ const { controller } = props;
64
+ return (React.createElement(Slicer, { controller: controller, selector: (s) => [s.value.age] }, (tool, age) => (React.createElement("button", { onClick: (e) => {
65
+ controller.actions.pushFormErrors((_state) => ({ age: age === '42' ? 'yes!!!' : 'noooo' }));
66
+ } }))));
67
+ }
68
+ render(React.createElement("div", null,
69
+ React.createElement(NarrowTypedExpected, { controller: TestFormHook.controller }),
70
+ React.createElement(ErrorDisplayer, { controller: TestFormHook.controller })));
71
+ const INPUT_AGE = '42';
72
+ // calling `userEvent` in here will cause race condition...
73
+ await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
74
+ await userEvent.click(screen.getByRole('button'));
75
+ await waitFor(() => {
76
+ const ageInput = screen.getByTestId('age-input');
77
+ expect(ageInput.value).toBe(INPUT_AGE);
78
+ TestFormHook.api.actions.peek((s) => {
79
+ expect(s.value.age).toBe(INPUT_AGE);
80
+ expect(s.errors.age).toBe('yes!!!');
81
+ });
82
+ });
83
+ });
@@ -0,0 +1,92 @@
1
+ import type { Subscriber } from 'nozuchi';
2
+ import type { BaseSyntheticEvent, ChangeEvent, ReactNode, ReactElement } from 'react';
3
+ import type { infer as zodInfer, ZodIssue, ZodType } from 'zod';
4
+ export declare type StateRestriction = Record<string, any>;
5
+ declare type FormStatus = {
6
+ isDirty: boolean;
7
+ isValid: boolean;
8
+ };
9
+ declare type FormErrors<State extends StateRestriction> = {
10
+ [k in keyof State]: string | null;
11
+ };
12
+ export declare type FullFormState<State extends StateRestriction> = FormStatus & {
13
+ value: State;
14
+ errors: FormErrors<State>;
15
+ };
16
+ export declare type HandleChangeAction<State extends StateRestriction, R = void> = <Name extends keyof State>(name: Name, value: State[Name]) => R;
17
+ export declare type FieldProps<State extends StateRestriction, Name extends keyof State> = {
18
+ name: Name;
19
+ children: (tool: {
20
+ name: Name;
21
+ value: State[Name];
22
+ onChange(this: void, name: Name, value: State[Name]): void;
23
+ onChange(this: void, e: ChangeEvent<HTMLElement>): void;
24
+ }, value: State[Name], errorMessage: string | null) => ReactNode;
25
+ };
26
+ export declare type SliceProps<State extends StateRestriction, Selected extends ReadonlyArray<unknown>> = {
27
+ selector: (s: FullFormState<State>) => Selected;
28
+ children: (tool: {
29
+ handleChange: HandleChangeAction<State>;
30
+ }, ...value: Readonly<Selected>) => ReactNode;
31
+ };
32
+ declare type FormControllerBehavior<StateBeforeValidation> = {
33
+ /** For testing */
34
+ peek: (eyeball: (prev: FullFormState<StateBeforeValidation>) => void) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
35
+ reset: () => () => FullFormState<StateBeforeValidation>;
36
+ /**
37
+ * Initialize form state without validation.
38
+ */
39
+ initializeForm: (initialVal: Partial<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
40
+ /**
41
+ * Handle issue that zod reported
42
+ */
43
+ handleIssues: (issues: ReadonlyArray<ZodIssue>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
44
+ /**
45
+ * You can handle server side or other external error via this action.
46
+ */
47
+ pushFormErrors: (validator: (state: StateBeforeValidation) => Partial<FormErrors<StateBeforeValidation>>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
48
+ reduceFormErrors: (reducer: (prev: FormErrors<StateBeforeValidation>) => FormErrors<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
49
+ /**
50
+ */
51
+ handleChange: HandleChangeAction<StateBeforeValidation, (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>>;
52
+ reduceFormState: (reducer: (prevValue: StateBeforeValidation) => StateBeforeValidation) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
53
+ handleBulkChange: (setter: (prev: StateBeforeValidation) => Partial<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
54
+ };
55
+ declare type ActionsCanBePublic<State extends StateRestriction> = {
56
+ reset: VoidFunction;
57
+ initializeForm: (initial: Partial<State>) => void;
58
+ pushFormErrors: (validator: (state: State) => Partial<FormErrors<State>>) => void;
59
+ handleChange: HandleChangeAction<State>;
60
+ handleBulkChange: (setter: (prev: State) => Partial<State>) => void;
61
+ };
62
+ /**
63
+ * Restricted type interface of the form store
64
+ * TODO: more restriction
65
+ */
66
+ export declare type Controller<State extends StateRestriction> = {
67
+ useInitialize: (initialValue: Partial<State>) => void;
68
+ useSelector: <R>(selector: (state: FullFormState<State>) => R, isEqual?: (prev: R, current: R) => boolean) => R;
69
+ actions: ActionsCanBePublic<State>;
70
+ components: {
71
+ Field: <Name extends keyof State>(props: FieldProps<State, Name>) => ReactElement<any, any> | null;
72
+ Slicer: <Selected extends ReadonlyArray<unknown>>(props: SliceProps<State, Selected>) => ReactElement<any, any> | null;
73
+ };
74
+ };
75
+ declare type FormHook<State extends StateRestriction, Schema extends ZodType<any, any, any>> = {
76
+ controller: Controller<State>;
77
+ handleSubmit: (handler: (e: BaseSyntheticEvent) => (val: {
78
+ success: true;
79
+ data: zodInfer<Schema>;
80
+ error: undefined;
81
+ } | {
82
+ success: false;
83
+ error: ReadonlyArray<ZodIssue>;
84
+ }) => void | Promise<void>) => (e: BaseSyntheticEvent) => void;
85
+ api: Subscriber<FullFormState<State>, FormControllerBehavior<State>>;
86
+ } & Controller<State>;
87
+ /**
88
+ * @typeParam InitialState should be shallow
89
+ */
90
+ export declare function createFormHook<StateBeforeValidation, Schema extends ZodType<any, any, any>>(initialState: StateBeforeValidation, schema: Schema): FormHook<StateBeforeValidation, Schema>;
91
+ export declare function useFormSlice<State extends StateRestriction, Sliced>(formController: Controller<State>, selector: (s: FullFormState<State>) => Sliced): readonly [Sliced, ActionsCanBePublic<State>];
92
+ export {};