mayoiga 0.1.7 → 0.2.0
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/dist/component.d.ts +19 -3
- package/dist/component.js +20 -3
- package/dist/index.d.ts +153 -10
- package/dist/index.js +112 -23
- package/dist/utils.d.ts +2 -1
- package/dist/utils.js +5 -0
- package/package.json +34 -35
- package/.eslintrc.js +0 -111
- package/.github/workflows/checker.yml +0 -42
- package/.gitignore +0 -217
- package/.prettierrc +0 -5
- package/dist/component.test.d.ts +0 -1
- package/dist/component.test.js +0 -112
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -113
- package/docs/.nojekyll +0 -1
- package/docs/assets/highlight.css +0 -92
- package/docs/assets/icons.css +0 -1043
- package/docs/assets/icons.png +0 -0
- package/docs/assets/icons@2x.png +0 -0
- package/docs/assets/main.js +0 -52
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1414
- package/docs/assets/widgets.png +0 -0
- package/docs/assets/widgets@2x.png +0 -0
- package/docs/index.html +0 -41
- package/docs/modules.html +0 -4
- package/example/src/demo-app.tsx +0 -123
- package/example/src/index.tsx +0 -15
- package/setup/vite-global-setup.js +0 -1
- package/setup/vite-set-global.js +0 -0
- package/src/component.test.tsx +0 -204
- package/src/component.tsx +0 -23
- package/src/index.test.tsx +0 -176
- package/src/index.ts +0 -352
- package/src/utils.ts +0 -8
- package/tsconfig.json +0 -38
- package/vite.config.js +0 -10
- package/yarn.lock +0 -2649
package/src/component.tsx
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import React from 'react';
|
|
2
|
-
|
|
3
|
-
import type {SliceProps, FieldProps, StateRestriction, Controller} from './index';
|
|
4
|
-
|
|
5
|
-
type ControlledComponentProps<State extends StateRestriction, Props> = Props & {
|
|
6
|
-
controller: Controller<State>;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
export function Slicer<State extends StateRestriction, R extends ReadonlyArray<unknown>>(
|
|
10
|
-
props: ControlledComponentProps<State, SliceProps<State, R>>,
|
|
11
|
-
) {
|
|
12
|
-
const {controller, ...restProps} = props;
|
|
13
|
-
const {Slicer: Delegate} = controller.components;
|
|
14
|
-
return <Delegate {...restProps} />;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function Field<State extends StateRestriction, Name extends keyof State>(
|
|
18
|
-
props: ControlledComponentProps<State, FieldProps<State, Name>>,
|
|
19
|
-
) {
|
|
20
|
-
const {controller, ...restProps} = props;
|
|
21
|
-
const {Field: Delegate} = controller.components;
|
|
22
|
-
return <Delegate {...restProps} />;
|
|
23
|
-
}
|
package/src/index.test.tsx
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
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
|
-
const testSchema = zod.object({
|
|
14
|
-
name: zod.string(),
|
|
15
|
-
description: zod.string(),
|
|
16
|
-
age: zod
|
|
17
|
-
.string()
|
|
18
|
-
.transform((val) => Number(val))
|
|
19
|
-
.refine((val) => (Number.isNaN(val) ? 0 : val)),
|
|
20
|
-
marked: zod.boolean(),
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
// every fields are optional for test
|
|
24
|
-
type FormStateBeforeValidation = {
|
|
25
|
-
name: string;
|
|
26
|
-
description: string;
|
|
27
|
-
age: string;
|
|
28
|
-
marked: boolean;
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
const initialState = {name: '', description: '', age: '', marked: false};
|
|
32
|
-
const createTestHook = () => createFormHook(initialState as FormStateBeforeValidation, testSchema);
|
|
33
|
-
|
|
34
|
-
const AgeInputComponent = (props: {controller: Controller<FormStateBeforeValidation>}) => {
|
|
35
|
-
const {controller} = props;
|
|
36
|
-
const [[age, errorMessage], {handleChange}] = useFormSlice(controller, (s) => [s.value.age, s.errors.age] as const);
|
|
37
|
-
return (
|
|
38
|
-
<div>
|
|
39
|
-
<input
|
|
40
|
-
data-testid="age-input"
|
|
41
|
-
value={age}
|
|
42
|
-
name="age"
|
|
43
|
-
onChange={(e) => {
|
|
44
|
-
handleChange('age' as const, e.currentTarget.value);
|
|
45
|
-
}}
|
|
46
|
-
/>
|
|
47
|
-
<span data-testid="age-error">{errorMessage}</span>
|
|
48
|
-
</div>
|
|
49
|
-
);
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
// afterEach(cleanup);
|
|
53
|
-
|
|
54
|
-
test('useSelector can select the fields', async () => {
|
|
55
|
-
const TestFormHook = createTestHook();
|
|
56
|
-
|
|
57
|
-
const Top = () => {
|
|
58
|
-
return (
|
|
59
|
-
<div>
|
|
60
|
-
<AgeInputComponent controller={TestFormHook.controller} />
|
|
61
|
-
</div>
|
|
62
|
-
);
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
render(<Top />);
|
|
66
|
-
|
|
67
|
-
const INPUT_AGE = '4';
|
|
68
|
-
|
|
69
|
-
// fireEvent.change(screen.getByTestId('age-input') , {target: {value: INPUT_AGE}})
|
|
70
|
-
// calling `userEvent` in here will cause race condition...
|
|
71
|
-
await userEvent.type(screen.getByTestId('age-input'), INPUT_AGE);
|
|
72
|
-
// TestFormHook.actions.handleBulkChange(prev => ({...prev, name: 'test', description: 'desc'}));
|
|
73
|
-
|
|
74
|
-
await waitFor(() => {
|
|
75
|
-
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
76
|
-
expect(ageInput.value).toBe(INPUT_AGE);
|
|
77
|
-
});
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
test('zod parse value before submit', async () => {
|
|
81
|
-
const TestFormHook = createTestHook();
|
|
82
|
-
|
|
83
|
-
const INPUT_AGE = '9';
|
|
84
|
-
const PARSED_RESULT = Number(INPUT_AGE);
|
|
85
|
-
|
|
86
|
-
const handleSubmitTester = TestFormHook.handleSubmit((e) => (result) => {
|
|
87
|
-
if (result.success) {
|
|
88
|
-
expect(result.data.age).toBe(PARSED_RESULT);
|
|
89
|
-
} else {
|
|
90
|
-
expect('should not called').toBe(result.error);
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
const Top = () => {
|
|
95
|
-
return (
|
|
96
|
-
<div>
|
|
97
|
-
<AgeInputComponent controller={TestFormHook} />
|
|
98
|
-
<button data-testid="submit-button" onClick={handleSubmitTester} />
|
|
99
|
-
</div>
|
|
100
|
-
);
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
render(<Top />);
|
|
104
|
-
|
|
105
|
-
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
106
|
-
await userEvent.type(ageInput, INPUT_AGE);
|
|
107
|
-
|
|
108
|
-
await waitFor(() => {
|
|
109
|
-
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
110
|
-
expect(ageInput.value).toBe(INPUT_AGE);
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
const submitButton = screen.getByTestId('submit-button');
|
|
114
|
-
await userEvent.click(submitButton);
|
|
115
|
-
|
|
116
|
-
await waitFor(() => {
|
|
117
|
-
console.log('waiting');
|
|
118
|
-
TestFormHook.api.actions.peek((s) => {
|
|
119
|
-
expect(s.value.age).toBe(INPUT_AGE);
|
|
120
|
-
expect(s.errors.age).toBeNull();
|
|
121
|
-
});
|
|
122
|
-
});
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
test('User is able to re-initialize the form state', async () => {
|
|
126
|
-
const TestFormHook = createTestHook();
|
|
127
|
-
|
|
128
|
-
const Top = () => {
|
|
129
|
-
return (
|
|
130
|
-
<div>
|
|
131
|
-
<AgeInputComponent controller={TestFormHook.controller} />
|
|
132
|
-
</div>
|
|
133
|
-
);
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
render(<Top />);
|
|
137
|
-
|
|
138
|
-
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
139
|
-
await userEvent.type(ageInput, '9999');
|
|
140
|
-
|
|
141
|
-
expect(TestFormHook.api.getState().isDirty).toBeTruthy();
|
|
142
|
-
TestFormHook.actions.initializeForm({}, {cleanup: true});
|
|
143
|
-
expect(TestFormHook.api.getState().isDirty).toBeFalsy();
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
test('User is able to push server side validation', async () => {
|
|
147
|
-
const TestFormHook = createTestHook();
|
|
148
|
-
|
|
149
|
-
const Top = () => {
|
|
150
|
-
return (
|
|
151
|
-
<div>
|
|
152
|
-
<AgeInputComponent controller={TestFormHook.controller} />
|
|
153
|
-
</div>
|
|
154
|
-
);
|
|
155
|
-
};
|
|
156
|
-
|
|
157
|
-
render(<Top />);
|
|
158
|
-
|
|
159
|
-
const ageInput: HTMLInputElement = screen.getByTestId('age-input');
|
|
160
|
-
await userEvent.type(ageInput, '9999');
|
|
161
|
-
|
|
162
|
-
TestFormHook.actions.pushFormErrors((_s) => ({age: 'server side error'}));
|
|
163
|
-
const state1 = TestFormHook.api.getState();
|
|
164
|
-
expect(state1.isDirty).toBeTruthy();
|
|
165
|
-
expect(state1.isValid).toBeFalsy();
|
|
166
|
-
expect(state1.errors.age).toEqual('server side error');
|
|
167
|
-
|
|
168
|
-
await userEvent.type(ageInput, 'hgoehoge');
|
|
169
|
-
|
|
170
|
-
// confirm empty field won't overwrite any messages
|
|
171
|
-
TestFormHook.actions.pushFormErrors((_s) => ({}));
|
|
172
|
-
const state2 = TestFormHook.api.getState();
|
|
173
|
-
expect(state2.isDirty).toBeTruthy();
|
|
174
|
-
expect(state2.isValid).toBeFalsy();
|
|
175
|
-
expect(state2.errors.age).toEqual('Invalid input');
|
|
176
|
-
});
|
package/src/index.ts
DELETED
|
@@ -1,352 +0,0 @@
|
|
|
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
|
-
* Mayoiga Field will memoize the result of renderProps for performance.
|
|
41
|
-
* If your renderProps depends on external variables, you should apply those on deps
|
|
42
|
-
*/
|
|
43
|
-
deps?: ReadonlyArray<unknown>;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
export type SliceProps<State extends StateRestriction, Selected extends ReadonlyArray<unknown>> = {
|
|
47
|
-
selector: (s: FullFormState<State>) => Selected;
|
|
48
|
-
children: (tool: {handleChange: HandleChangeAction<State>}, ...value: Readonly<Selected>) => ReactNode;
|
|
49
|
-
/**
|
|
50
|
-
* Mayoiga Slicer will memoize the result of renderProps for performance.
|
|
51
|
-
* If your renderProps depends on external variables, you should apply those on deps
|
|
52
|
-
*
|
|
53
|
-
* ```typescript
|
|
54
|
-
* <Slicer selector={s => [s.value.selected]} deps={[selection]}>{(tools, selected: string) => <AwesomeSelection value={selected} options={selection} />}</Slicer>
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
deps?: ReadonlyArray<unknown>;
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
type FormControllerBehavior<StateBeforeValidation extends StateRestriction> = {
|
|
61
|
-
/** For testing */
|
|
62
|
-
peek: (
|
|
63
|
-
eyeball: (prev: FullFormState<StateBeforeValidation>) => void,
|
|
64
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
65
|
-
|
|
66
|
-
reset: () => () => FullFormState<StateBeforeValidation>;
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Initialize form state without validation.
|
|
70
|
-
*
|
|
71
|
-
* @param initialVal value to initialize form state
|
|
72
|
-
* @param opts.cleanup if true, form state is become pristine (which means, `form.isDirty` is going to be false) .
|
|
73
|
-
*/
|
|
74
|
-
initializeForm: (
|
|
75
|
-
initialVal: Partial<StateBeforeValidation>,
|
|
76
|
-
opts?: {
|
|
77
|
-
cleanup?: true;
|
|
78
|
-
},
|
|
79
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Handle issue that zod reported
|
|
83
|
-
*/
|
|
84
|
-
handleIssues: (issues: ReadonlyArray<ZodIssue>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* You can handle server side or other external error via this action.
|
|
88
|
-
*/
|
|
89
|
-
pushFormErrors: (
|
|
90
|
-
validator: (state: StateBeforeValidation) => Partial<FormErrors<StateBeforeValidation>>,
|
|
91
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
92
|
-
|
|
93
|
-
reduceFormErrors: (
|
|
94
|
-
reducer: (prev: FormErrors<StateBeforeValidation>) => FormErrors<StateBeforeValidation>,
|
|
95
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
*/
|
|
99
|
-
handleChange: HandleChangeAction<
|
|
100
|
-
StateBeforeValidation,
|
|
101
|
-
(prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>
|
|
102
|
-
>;
|
|
103
|
-
|
|
104
|
-
reduceFormState: (
|
|
105
|
-
reducer: (prevValue: StateBeforeValidation) => StateBeforeValidation,
|
|
106
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
107
|
-
handleBulkChange: (
|
|
108
|
-
setter: (prev: StateBeforeValidation) => Partial<StateBeforeValidation>,
|
|
109
|
-
) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
const initialFormState = Object.freeze({isDirty: false, isValid: false});
|
|
113
|
-
|
|
114
|
-
function createFormStore<StateBeforeValidation extends StateRestriction, Schema extends ZodType<any, any, any>>(
|
|
115
|
-
initialState: StateBeforeValidation,
|
|
116
|
-
schema: Schema,
|
|
117
|
-
): Subscriber<FullFormState<StateBeforeValidation>, FormControllerBehavior<StateBeforeValidation>> {
|
|
118
|
-
type FullState = FullFormState<StateBeforeValidation>;
|
|
119
|
-
type Err = FormErrors<StateBeforeValidation>;
|
|
120
|
-
type StateKeys = keyof StateBeforeValidation;
|
|
121
|
-
|
|
122
|
-
const initialErrors = Object.freeze(
|
|
123
|
-
Object.keys(initialState).reduce((buf, k) => {
|
|
124
|
-
buf[k as StateKeys] = null;
|
|
125
|
-
return buf;
|
|
126
|
-
}, {} as any as Err),
|
|
127
|
-
);
|
|
128
|
-
|
|
129
|
-
const fullInitialState: FullState = Object.freeze({
|
|
130
|
-
...initialFormState,
|
|
131
|
-
value: {...initialState},
|
|
132
|
-
errors: {...initialErrors},
|
|
133
|
-
});
|
|
134
|
-
|
|
135
|
-
const withValidation = (prev: FullState, newValue: StateBeforeValidation) => {
|
|
136
|
-
const result = schema.safeParse(newValue);
|
|
137
|
-
if (result.success) {
|
|
138
|
-
return {...prev, isDirty: true, isValid: true, value: newValue, errors: initialErrors};
|
|
139
|
-
}
|
|
140
|
-
const newErrors = result.error.issues.reduce((buf, iss) => {
|
|
141
|
-
// TODO: should support nested value?
|
|
142
|
-
const shallowPath = iss.path[0];
|
|
143
|
-
if (shallowPath === undefined) {
|
|
144
|
-
return buf;
|
|
145
|
-
}
|
|
146
|
-
buf[shallowPath as any as StateKeys] = iss.message;
|
|
147
|
-
return buf;
|
|
148
|
-
}, {} as any as Err);
|
|
149
|
-
|
|
150
|
-
return {...prev, isDirty: true, isValid: false, errors: newErrors, value: newValue};
|
|
151
|
-
};
|
|
152
|
-
|
|
153
|
-
return createStore(fullInitialState, {
|
|
154
|
-
peek: (eyeball) => (prev) => {
|
|
155
|
-
eyeball(prev);
|
|
156
|
-
return prev;
|
|
157
|
-
},
|
|
158
|
-
|
|
159
|
-
reset: () => () => fullInitialState,
|
|
160
|
-
initializeForm: (initialVal, opts) => (prev) => ({
|
|
161
|
-
...prev,
|
|
162
|
-
value: {...prev.value, ...initialVal},
|
|
163
|
-
errors: {...initialErrors},
|
|
164
|
-
isDirty: opts?.cleanup === true ? false : prev.isDirty,
|
|
165
|
-
}),
|
|
166
|
-
handleIssues: (issues) => (prev) => {
|
|
167
|
-
// FIXME: handle duplication
|
|
168
|
-
const newErrors = issues.reduce((buf, iss) => {
|
|
169
|
-
const shallowPath = iss.path[0];
|
|
170
|
-
if (shallowPath === undefined) {
|
|
171
|
-
return buf;
|
|
172
|
-
}
|
|
173
|
-
buf[shallowPath as any as StateKeys] = iss.message;
|
|
174
|
-
return buf;
|
|
175
|
-
}, {} as any as Err);
|
|
176
|
-
|
|
177
|
-
return {...prev, isDirty: true, isValid: false, errors: newErrors};
|
|
178
|
-
},
|
|
179
|
-
pushFormErrors: (validator) => (prev) => {
|
|
180
|
-
const pushedErrors = validator(prev.value);
|
|
181
|
-
const allErrors = {...prev.errors, ...pushedErrors};
|
|
182
|
-
return {...prev, isValid: Object.keys(allErrors).length === 0, errors: allErrors};
|
|
183
|
-
},
|
|
184
|
-
reduceFormErrors: (reducer) => (prev) => {
|
|
185
|
-
return {...prev, errors: reducer(prev.errors)};
|
|
186
|
-
},
|
|
187
|
-
handleChange: (name, value) => (prev) => {
|
|
188
|
-
if (name in prev.value === false) {
|
|
189
|
-
return prev;
|
|
190
|
-
}
|
|
191
|
-
const newValue = {...prev.value, [name]: value};
|
|
192
|
-
return withValidation(prev, newValue);
|
|
193
|
-
},
|
|
194
|
-
reduceFormState: (reducer) => (prev) => {
|
|
195
|
-
const reducedState = reducer(prev.value);
|
|
196
|
-
return withValidation(prev, reducedState);
|
|
197
|
-
},
|
|
198
|
-
handleBulkChange: (setter) => (prev) => {
|
|
199
|
-
const mergedNewState = {...prev.value, ...setter(prev.value)};
|
|
200
|
-
return withValidation(prev, mergedNewState);
|
|
201
|
-
},
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
type ActionsCanBePublic<State extends StateRestriction> = {
|
|
206
|
-
reset: VoidFunction;
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Initialize form state without validation.
|
|
210
|
-
*
|
|
211
|
-
* @param initialVal value to initialize form state
|
|
212
|
-
* @param opts.cleanup if true, form state is become pristine (which means, `form.isDirty` is going to be false) .
|
|
213
|
-
*/
|
|
214
|
-
initializeForm: (
|
|
215
|
-
initial: Partial<State>,
|
|
216
|
-
opts?: {
|
|
217
|
-
cleanup?: true;
|
|
218
|
-
},
|
|
219
|
-
) => void;
|
|
220
|
-
pushFormErrors: (validator: (state: State) => Partial<FormErrors<State>>) => void;
|
|
221
|
-
handleChange: HandleChangeAction<State>;
|
|
222
|
-
handleBulkChange: (setter: (prev: State) => Partial<State>) => void;
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
* Restricted type interface of the form store
|
|
227
|
-
* TODO: more restriction
|
|
228
|
-
*/
|
|
229
|
-
export type Controller<State extends StateRestriction> = {
|
|
230
|
-
useInitialize: (initialValue: Partial<State>) => void;
|
|
231
|
-
useSelector: <R>(selector: (state: FullFormState<State>) => R, isEqual?: (prev: R, current: R) => boolean) => R;
|
|
232
|
-
|
|
233
|
-
actions: ActionsCanBePublic<State>;
|
|
234
|
-
components: {
|
|
235
|
-
Field: <Name extends keyof State>(props: FieldProps<State, Name>) => ReactElement<any, any> | null;
|
|
236
|
-
Slicer: <Selected extends ReadonlyArray<unknown>>(props: SliceProps<State, Selected>) => ReactElement<any, any> | null;
|
|
237
|
-
};
|
|
238
|
-
};
|
|
239
|
-
|
|
240
|
-
type FormHook<State extends StateRestriction, Schema extends ZodType<any, any, any>> = {
|
|
241
|
-
controller: Controller<State>;
|
|
242
|
-
|
|
243
|
-
handleSubmit: (
|
|
244
|
-
handler: (
|
|
245
|
-
e: BaseSyntheticEvent,
|
|
246
|
-
) => (
|
|
247
|
-
val: {success: true; data: zodInfer<Schema>; error: undefined} | {success: false; error: ReadonlyArray<ZodIssue>},
|
|
248
|
-
) => void | Promise<void>,
|
|
249
|
-
) => (e: BaseSyntheticEvent) => void;
|
|
250
|
-
|
|
251
|
-
api: Subscriber<FullFormState<State>, FormControllerBehavior<State>>;
|
|
252
|
-
} & Controller<State>;
|
|
253
|
-
|
|
254
|
-
/**
|
|
255
|
-
* @typeParam InitialState should be shallow
|
|
256
|
-
*/
|
|
257
|
-
export function createFormHook<StateBeforeValidation extends StateRestriction, Schema extends ZodType<any, any, any>>(
|
|
258
|
-
initialState: StateBeforeValidation,
|
|
259
|
-
schema: Schema,
|
|
260
|
-
): FormHook<StateBeforeValidation, Schema> {
|
|
261
|
-
const store = createFormStore(initialState, schema);
|
|
262
|
-
|
|
263
|
-
const formHook = {
|
|
264
|
-
useInitialize: (initialValue: Partial<StateBeforeValidation>) => {
|
|
265
|
-
useEffect(() => {
|
|
266
|
-
store.actions.initializeForm(initialValue);
|
|
267
|
-
}, []);
|
|
268
|
-
},
|
|
269
|
-
useSelector: store.useSelector,
|
|
270
|
-
handleSubmit: (
|
|
271
|
-
handler: (
|
|
272
|
-
e: BaseSyntheticEvent,
|
|
273
|
-
) => (
|
|
274
|
-
val: {success: true; data: zodInfer<Schema>; error: undefined} | {success: false; error: ReadonlyArray<ZodIssue>},
|
|
275
|
-
) => void | Promise<void>,
|
|
276
|
-
) => {
|
|
277
|
-
return (e: BaseSyntheticEvent) => {
|
|
278
|
-
const eventHandled = handler(e);
|
|
279
|
-
const value = store.getState().value;
|
|
280
|
-
return schema.safeParseAsync(value).then((result: SafeParseReturnType<StateBeforeValidation, zodInfer<typeof schema>>) => {
|
|
281
|
-
// FIXME: hook formを捨ててzodのバージョンをあげればこの辺に型をつけられる
|
|
282
|
-
if (result.success) {
|
|
283
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
284
|
-
return eventHandled({success: true, data: result.data, error: undefined});
|
|
285
|
-
}
|
|
286
|
-
void eventHandled({success: false, error: result.error.issues});
|
|
287
|
-
store.actions.handleIssues(result.error.issues);
|
|
288
|
-
});
|
|
289
|
-
};
|
|
290
|
-
},
|
|
291
|
-
|
|
292
|
-
components: {
|
|
293
|
-
Slicer<R extends ReadonlyArray<unknown>>(props: SliceProps<StateBeforeValidation, R>) {
|
|
294
|
-
const {selector, children, deps} = props;
|
|
295
|
-
const slicedValues = formHook.useSelector(selector);
|
|
296
|
-
return useMemo(
|
|
297
|
-
() => {
|
|
298
|
-
const renderContent = children({handleChange: formHook.actions.handleChange}, ...slicedValues);
|
|
299
|
-
return createElement(Fragment, {}, renderContent);
|
|
300
|
-
},
|
|
301
|
-
deps ? [...slicedValues, ...deps] : slicedValues,
|
|
302
|
-
);
|
|
303
|
-
},
|
|
304
|
-
Field<Name extends keyof StateBeforeValidation>(props: FieldProps<StateBeforeValidation, Name>) {
|
|
305
|
-
const {name, children, deps} = props;
|
|
306
|
-
const [value, errMsg] = store.useSelector((s) => [s.value[name], s.errors[name]] as const);
|
|
307
|
-
return useMemo(
|
|
308
|
-
() => {
|
|
309
|
-
const renderContent = children(
|
|
310
|
-
{
|
|
311
|
-
name,
|
|
312
|
-
value,
|
|
313
|
-
onChange: (name_or_event: unknown, value_or_none?: unknown) => {
|
|
314
|
-
if (typeof name_or_event === 'string') {
|
|
315
|
-
// assumes name is valid if it's string
|
|
316
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
317
|
-
return store.actions.handleChange(name_or_event as Name, value_or_none as any);
|
|
318
|
-
}
|
|
319
|
-
if (isChangeEvent(name_or_event)) {
|
|
320
|
-
const target: any = name_or_event.currentTarget || name_or_event.target;
|
|
321
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
|
|
322
|
-
return store.actions.handleChange(target.name, target.value);
|
|
323
|
-
}
|
|
324
|
-
throw new Error('`handleChange` handles unexpected formed object.');
|
|
325
|
-
},
|
|
326
|
-
},
|
|
327
|
-
value,
|
|
328
|
-
errMsg,
|
|
329
|
-
);
|
|
330
|
-
return createElement(Fragment, {}, renderContent);
|
|
331
|
-
},
|
|
332
|
-
deps ? [value, errMsg, ...deps] : [value, errMsg],
|
|
333
|
-
);
|
|
334
|
-
},
|
|
335
|
-
},
|
|
336
|
-
actions: store.actions,
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
return {
|
|
340
|
-
controller: formHook,
|
|
341
|
-
api: store,
|
|
342
|
-
...formHook,
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
export function useFormSlice<State extends StateRestriction, Sliced>(
|
|
347
|
-
formController: Controller<State>,
|
|
348
|
-
selector: (s: FullFormState<State>) => Sliced,
|
|
349
|
-
) {
|
|
350
|
-
const sliced = formController.useSelector((s) => selector(s));
|
|
351
|
-
return [sliced, formController.actions] as const;
|
|
352
|
-
}
|
package/src/utils.ts
DELETED
package/tsconfig.json
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "esnext",
|
|
4
|
-
"module": "esnext",
|
|
5
|
-
"declaration": true,
|
|
6
|
-
"jsx": "react",
|
|
7
|
-
"moduleResolution": "node",
|
|
8
|
-
// TODO: skip while vitest is broken
|
|
9
|
-
"skipLibCheck": true,
|
|
10
|
-
|
|
11
|
-
"strict": true,
|
|
12
|
-
|
|
13
|
-
"noUnusedLocals": true,
|
|
14
|
-
"noUnusedParameters": false,
|
|
15
|
-
"noImplicitReturns": true,
|
|
16
|
-
"noFallthroughCasesInSwitch": true,
|
|
17
|
-
"noUncheckedIndexedAccess": true,
|
|
18
|
-
"useUnknownInCatchVariables": true,
|
|
19
|
-
"exactOptionalPropertyTypes": true,
|
|
20
|
-
|
|
21
|
-
"forceConsistentCasingInFileNames": true,
|
|
22
|
-
"removeComments": false,
|
|
23
|
-
|
|
24
|
-
"allowSyntheticDefaultImports": true,
|
|
25
|
-
"esModuleInterop": true,
|
|
26
|
-
"noErrorTruncation": true,
|
|
27
|
-
|
|
28
|
-
"lib": ["dom", "esnext"],
|
|
29
|
-
// TODO: node is for vitest... I should isolate it probably?
|
|
30
|
-
"types": ["react/next"],
|
|
31
|
-
|
|
32
|
-
"rootDir": "./src",
|
|
33
|
-
"outDir": "./dist"
|
|
34
|
-
},
|
|
35
|
-
"include": [
|
|
36
|
-
"./src/**/*"
|
|
37
|
-
],
|
|
38
|
-
}
|
package/vite.config.js
DELETED