mayoiga 0.1.1 → 0.1.4
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 +55 -35
- package/component.d.ts +1 -0
- package/component.js +1 -0
- package/dist/component.test.js +62 -3
- package/dist/index.d.ts +19 -1
- package/dist/index.js +11 -7
- package/dist/index.test.js +5 -2
- package/docs/.nojekyll +1 -0
- package/docs/assets/highlight.css +92 -0
- package/docs/assets/icons.css +1043 -0
- package/docs/assets/icons.png +0 -0
- package/docs/assets/icons@2x.png +0 -0
- package/docs/assets/main.js +52 -0
- package/docs/assets/search.js +1 -0
- package/docs/assets/style.css +1414 -0
- package/docs/assets/widgets.png +0 -0
- package/docs/assets/widgets@2x.png +0 -0
- package/docs/index.html +41 -0
- package/docs/modules.html +4 -0
- package/example/src/demo-app.tsx +123 -0
- package/example/src/index.tsx +15 -0
- package/package.json +10 -5
- package/setup/vite-global-setup.js +1 -0
- package/setup/vite-set-global.js +0 -0
- package/src/component.test.tsx +204 -0
- package/src/component.tsx +23 -0
- package/src/index.test.tsx +122 -0
- package/src/index.ts +332 -0
- package/src/utils.ts +8 -0
- package/tsconfig.json +38 -0
- package/vite.config.js +10 -0
- package/yarn.lock +2202 -0
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
package/README.md
CHANGED
|
@@ -2,59 +2,79 @@
|
|
|
2
2
|
|
|
3
3
|
# Mayoiga
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Fully typed form state management system for React.
|
|
6
6
|
|
|
7
|
+
No magic, ref free. It's built for complicated form state management.
|
|
7
8
|
|
|
8
|
-
##
|
|
9
|
+
## Feature
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
- Submit level validation
|
|
13
|
-
- Less learning cost
|
|
14
|
-
- Cooperate with any component library (Bootstarap, MaterialDesign, ant-design or whatever )
|
|
11
|
+
Support strong typed form state.
|
|
12
|
+
Every form should have two kind of types:
|
|
15
13
|
|
|
16
|
-
|
|
14
|
+
1. form state before validation
|
|
15
|
+
2. state after validation succeed
|
|
17
16
|
|
|
17
|
+
i.e. before validation, a field named "bio" might be nullable (`{bio: null | string}`) but it must not empty to submit (`{bio: zod.string().nonempty()}`).
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
Also considers:
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
- No ref, DOM free
|
|
22
|
+
- High performance, high tuning possibility
|
|
23
|
+
- Mayoiga uses "external state and selector" pattern. You can built your own form if you known what you would like to
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
## Features does not support
|
|
24
26
|
|
|
25
|
-
-
|
|
27
|
+
- Short coding
|
|
26
28
|
|
|
27
|
-
|
|
29
|
+
It's not a library for short coding or copy and paste template.
|
|
28
30
|
|
|
29
31
|
|
|
30
|
-
###
|
|
32
|
+
### Quickstart
|
|
31
33
|
|
|
32
34
|
```typeScript
|
|
33
35
|
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
expect(result.data.age).toBe(PARSED_RESULT);
|
|
42
|
-
} else {
|
|
43
|
-
expect('should not called').toBe(result.err);
|
|
44
|
-
}
|
|
36
|
+
const schema = zod.object({
|
|
37
|
+
name: zod.string(),
|
|
38
|
+
age: zod
|
|
39
|
+
.string()
|
|
40
|
+
.transform((val) => Number(val))
|
|
41
|
+
.refine((val) => (Number.isNaN(val) ? 0 : val)),
|
|
42
|
+
marked: zod.literal(true),
|
|
45
43
|
});
|
|
46
44
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
<button data-testid="submit-button" onClick={handleSubmitTester} />
|
|
52
|
-
</div>
|
|
53
|
-
)
|
|
45
|
+
type BeforeValidation = {
|
|
46
|
+
name: string;
|
|
47
|
+
age: string;
|
|
48
|
+
marked: boolean;
|
|
54
49
|
};
|
|
55
50
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
51
|
+
const {
|
|
52
|
+
components: {Field, Slicer},
|
|
53
|
+
handleSubmit,
|
|
54
|
+
} = createFormHook({name:'test', age: '42', marked: false} as BeforeValidation, schema);
|
|
55
|
+
|
|
56
|
+
function App() {
|
|
57
|
+
const submitHandler = handleSubmit((e) => (result) => {
|
|
58
|
+
if (result.error) {
|
|
59
|
+
return alert('Err!');
|
|
60
|
+
}
|
|
61
|
+
console.log(result.data); /*
|
|
62
|
+
{
|
|
63
|
+
name: 'test',
|
|
64
|
+
age: 42, <- age is typed "number" before validation because of definition
|
|
65
|
+
marked: true, <- have to be "true", not as boolean. it's power of zod
|
|
66
|
+
}
|
|
67
|
+
*/
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
return (
|
|
71
|
+
<form onSubmit={handleSubmit(onSubmit)}>
|
|
72
|
+
<Field name="name">{(tool) => <input {...tool} />}</Field>
|
|
73
|
+
<Field name="age">{(tool) => <input {...tool} />}</Field>
|
|
74
|
+
<Field name="marked">{(tool) => <input {...tool} />}</Field>
|
|
75
|
+
<input type="submit" />
|
|
76
|
+
</form>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
59
79
|
|
|
60
80
|
```
|
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');
|
package/dist/component.test.js
CHANGED
|
@@ -4,11 +4,14 @@ import React from 'react';
|
|
|
4
4
|
import { test, expect } from 'vitest';
|
|
5
5
|
import * as zod from 'zod';
|
|
6
6
|
import { Field, Slicer } from './component';
|
|
7
|
-
import { createFormHook
|
|
7
|
+
import { createFormHook } from './index';
|
|
8
8
|
const testSchema = zod.object({
|
|
9
9
|
name: zod.string(),
|
|
10
10
|
description: zod.string(),
|
|
11
|
-
age: zod
|
|
11
|
+
age: zod
|
|
12
|
+
.string()
|
|
13
|
+
.transform((val) => Number(val))
|
|
14
|
+
.refine((val) => (Number.isNaN(val) ? 0 : val)),
|
|
12
15
|
marked: zod.boolean(),
|
|
13
16
|
});
|
|
14
17
|
const createTestHook = () => createFormHook({ name: '', description: '', age: '', marked: false }, testSchema);
|
|
@@ -36,7 +39,7 @@ test('Slice component works fine in basic usage.', async () => {
|
|
|
36
39
|
const TestFormHook = createTestHook();
|
|
37
40
|
const Top = () => {
|
|
38
41
|
return (React.createElement("div", null,
|
|
39
|
-
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) }))));
|
|
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) })))));
|
|
40
43
|
};
|
|
41
44
|
render(React.createElement(Top, null));
|
|
42
45
|
const INPUT_AGE = '42';
|
|
@@ -51,3 +54,59 @@ test('Slice component works fine in basic usage.', async () => {
|
|
|
51
54
|
});
|
|
52
55
|
});
|
|
53
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
|
+
});
|
|
84
|
+
test('`deps` field could destruct memoization', async () => {
|
|
85
|
+
const TestFormHook = createTestHook();
|
|
86
|
+
// intentional sample to replicate the situation
|
|
87
|
+
const OtherFormHook = createFormHook({ minAge: '30' }, zod.object({ minAge: zod.string() }));
|
|
88
|
+
const DATA_ID_RE_RENDER_BY_DEPS = 'refresh-by-deps';
|
|
89
|
+
const DATA_ID_NOT_RERENDER_NO_DEPS = 'no-refersh-no-deps';
|
|
90
|
+
function App() {
|
|
91
|
+
const minAge = OtherFormHook.useSelector((s) => Number(s.value.minAge));
|
|
92
|
+
return (React.createElement("div", null,
|
|
93
|
+
React.createElement(Field, { controller: OtherFormHook.controller, name: "minAge" }, (tool) => React.createElement("input", { "data-testid": "minAgeInput", type: "number", ...tool })),
|
|
94
|
+
React.createElement(Field, { controller: TestFormHook.controller, name: "age" }, (tool) => React.createElement("input", { "data-testid": "ageInput", type: "number", ...tool })),
|
|
95
|
+
React.createElement(Slicer, { controller: TestFormHook.controller, selector: (s) => [Number(s.value.age)], deps: [minAge] }, (_tool, age) => (React.createElement("div", { "data-testid": DATA_ID_RE_RENDER_BY_DEPS }, age >= minAge ? 'You can buy this content' : 'go home'))),
|
|
96
|
+
React.createElement(Slicer, { controller: TestFormHook.controller, selector: (s) => [Number(s.value.age)] }, (_tool, age) => (React.createElement("div", { "data-testid": DATA_ID_NOT_RERENDER_NO_DEPS }, age >= minAge ? 'You can buy this content' : 'go home')))));
|
|
97
|
+
}
|
|
98
|
+
render(React.createElement(App, null));
|
|
99
|
+
await userEvent.type(screen.getByTestId('ageInput'), '16');
|
|
100
|
+
await waitFor(() => {
|
|
101
|
+
expect(screen.getByTestId(DATA_ID_RE_RENDER_BY_DEPS).textContent).toBe('go home');
|
|
102
|
+
// expect(await screen.findByText('You can buy this content')).toBeDefined();
|
|
103
|
+
});
|
|
104
|
+
await userEvent.clear(screen.getByTestId('minAgeInput'));
|
|
105
|
+
await userEvent.type(screen.getByTestId('minAgeInput'), '10');
|
|
106
|
+
await waitFor(() => {
|
|
107
|
+
expect(screen.getByTestId(DATA_ID_RE_RENDER_BY_DEPS).textContent, 'Slicer should re-execute renderProps if `deps` are changed').toBe('You can buy this content');
|
|
108
|
+
});
|
|
109
|
+
await waitFor(() => {
|
|
110
|
+
expect(screen.getByTestId(DATA_ID_NOT_RERENDER_NO_DEPS).textContent, 'Same logic but would not refresh because external dependencies are not applied').toBe('go home');
|
|
111
|
+
});
|
|
112
|
+
});
|
package/dist/index.d.ts
CHANGED
|
@@ -22,12 +22,26 @@ export declare type FieldProps<State extends StateRestriction, Name extends keyo
|
|
|
22
22
|
onChange(this: void, name: Name, value: State[Name]): void;
|
|
23
23
|
onChange(this: void, e: ChangeEvent<HTMLElement>): void;
|
|
24
24
|
}, value: State[Name], errorMessage: string | null) => ReactNode;
|
|
25
|
+
/**
|
|
26
|
+
* Mayoiga Field will memoize the result of renderProps for performance.
|
|
27
|
+
* If your renderProps depends on external variables, you should apply those on deps
|
|
28
|
+
*/
|
|
29
|
+
deps?: ReadonlyArray<unknown>;
|
|
25
30
|
};
|
|
26
31
|
export declare type SliceProps<State extends StateRestriction, Selected extends ReadonlyArray<unknown>> = {
|
|
27
32
|
selector: (s: FullFormState<State>) => Selected;
|
|
28
33
|
children: (tool: {
|
|
29
34
|
handleChange: HandleChangeAction<State>;
|
|
30
35
|
}, ...value: Readonly<Selected>) => ReactNode;
|
|
36
|
+
/**
|
|
37
|
+
* Mayoiga Slicer will memoize the result of renderProps for performance.
|
|
38
|
+
* If your renderProps depends on external variables, you should apply those on deps
|
|
39
|
+
*
|
|
40
|
+
* ```typescript
|
|
41
|
+
* <Slicer selector={s => [s.value.selected]} deps={[selection]}>{(tools, selected: string) => <AwesomeSelection value={selected} options={selection} />}</Slicer>
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
deps?: ReadonlyArray<unknown>;
|
|
31
45
|
};
|
|
32
46
|
declare type FormControllerBehavior<StateBeforeValidation> = {
|
|
33
47
|
/** For testing */
|
|
@@ -44,7 +58,8 @@ declare type FormControllerBehavior<StateBeforeValidation> = {
|
|
|
44
58
|
/**
|
|
45
59
|
* You can handle server side or other external error via this action.
|
|
46
60
|
*/
|
|
47
|
-
|
|
61
|
+
pushFormErrors: (validator: (state: StateBeforeValidation) => Partial<FormErrors<StateBeforeValidation>>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
62
|
+
reduceFormErrors: (reducer: (prev: FormErrors<StateBeforeValidation>) => FormErrors<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
48
63
|
/**
|
|
49
64
|
*/
|
|
50
65
|
handleChange: HandleChangeAction<StateBeforeValidation, (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>>;
|
|
@@ -52,6 +67,9 @@ declare type FormControllerBehavior<StateBeforeValidation> = {
|
|
|
52
67
|
handleBulkChange: (setter: (prev: StateBeforeValidation) => Partial<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
53
68
|
};
|
|
54
69
|
declare type ActionsCanBePublic<State extends StateRestriction> = {
|
|
70
|
+
reset: VoidFunction;
|
|
71
|
+
initializeForm: (initial: Partial<State>) => void;
|
|
72
|
+
pushFormErrors: (validator: (state: State) => Partial<FormErrors<State>>) => void;
|
|
55
73
|
handleChange: HandleChangeAction<State>;
|
|
56
74
|
handleBulkChange: (setter: (prev: State) => Partial<State>) => void;
|
|
57
75
|
};
|
package/dist/index.js
CHANGED
|
@@ -51,7 +51,11 @@ function createFormStore(initialState, schema) {
|
|
|
51
51
|
}, {});
|
|
52
52
|
return { ...prev, isDirty: true, isValid: false, errors: newErrors };
|
|
53
53
|
},
|
|
54
|
-
|
|
54
|
+
pushFormErrors: (validator) => (prev) => {
|
|
55
|
+
const pushedErrors = validator(prev.value);
|
|
56
|
+
return { ...prev, errors: { ...prev.errors, ...pushedErrors } };
|
|
57
|
+
},
|
|
58
|
+
reduceFormErrors: (reducer) => (prev) => {
|
|
55
59
|
return { ...prev, errors: reducer(prev.errors) };
|
|
56
60
|
},
|
|
57
61
|
handleChange: (name, value) => (prev) => {
|
|
@@ -100,15 +104,15 @@ export function createFormHook(initialState, schema) {
|
|
|
100
104
|
},
|
|
101
105
|
components: {
|
|
102
106
|
Slicer(props) {
|
|
103
|
-
const { selector, children } = props;
|
|
104
|
-
const
|
|
107
|
+
const { selector, children, deps } = props;
|
|
108
|
+
const slicedValues = formHook.useSelector(selector);
|
|
105
109
|
return useMemo(() => {
|
|
106
|
-
const renderContent = children({ handleChange: formHook.actions.handleChange }, ...
|
|
110
|
+
const renderContent = children({ handleChange: formHook.actions.handleChange }, ...slicedValues);
|
|
107
111
|
return createElement(Fragment, {}, renderContent);
|
|
108
|
-
},
|
|
112
|
+
}, deps ? [...slicedValues, ...deps] : slicedValues);
|
|
109
113
|
},
|
|
110
114
|
Field(props) {
|
|
111
|
-
const { name, children } = props;
|
|
115
|
+
const { name, children, deps } = props;
|
|
112
116
|
const [value, errMsg] = store.useSelector((s) => [s.value[name], s.errors[name]]);
|
|
113
117
|
return useMemo(() => {
|
|
114
118
|
const renderContent = children({
|
|
@@ -129,7 +133,7 @@ export function createFormHook(initialState, schema) {
|
|
|
129
133
|
},
|
|
130
134
|
}, value, errMsg);
|
|
131
135
|
return createElement(Fragment, {}, renderContent);
|
|
132
|
-
}, [value, errMsg]);
|
|
136
|
+
}, deps ? [value, errMsg, ...deps] : [value, errMsg]);
|
|
133
137
|
},
|
|
134
138
|
},
|
|
135
139
|
actions: store.actions,
|