mayoiga 0.1.2 → 0.1.5

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/README.md CHANGED
@@ -2,59 +2,79 @@
2
2
 
3
3
  # Mayoiga
4
4
 
5
- The React Hook based form library. Of course it is TypeScript friendly.
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
- ## Supported functionality
9
+ ## Feature
9
10
 
10
- - TypeScript oriented
11
- - Form level validation
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
- With less boilerplate code!!
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
- ## How to use
19
+ Also considers:
20
20
 
21
- ### API you should see
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
- There are only two functions which you should know to use Mayoiga.
25
+ ## Features does not support
24
26
 
25
- - [useForm](https://hachibeedi.github.io/mayoiga/modules/_mayoiga_.html#useform)
27
+ - Short coding
26
28
 
27
- - [createFormScope](https://hachibeedi.github.io/mayoiga/modules/_mayoiga_.html#createformscope)
29
+ It's not a library for short coding or copy and paste template.
28
30
 
29
31
 
30
- ### Minimum example:
32
+ ### Quickstart
31
33
 
32
34
  ```typeScript
33
35
 
34
- const TestFormHook = createFormHook({name:'', description: '', age: ''} as FormStateBeforeValidation, testSchema);
35
-
36
- const INPUT_AGE = '9';
37
- const PARSED_RESULT = Number(INPUT_AGE);
38
-
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);
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
- const Top = () => {
48
- return (
49
- <div>
50
- <AgeInputComponent formHook={TestFormHook} />
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
- act(() => {
57
- render(<Top />);
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
  ```
@@ -1,5 +1,5 @@
1
1
  import type { SliceProps, FieldProps, StateRestriction, Controller } from './index';
2
- declare type ControlledComponentProps<State, Props> = Props & {
2
+ declare type ControlledComponentProps<State extends StateRestriction, Props> = Props & {
3
3
  controller: Controller<State>;
4
4
  };
5
5
  export declare function Slicer<State extends StateRestriction, R extends ReadonlyArray<unknown>>(props: ControlledComponentProps<State, SliceProps<State, R>>): JSX.Element;
@@ -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, } from './index';
7
+ import { createFormHook } from './index';
8
8
  const testSchema = zod.object({
9
9
  name: zod.string(),
10
10
  description: zod.string(),
11
- age: zod.string().transform(val => Number(val)).refine(val => Number.isNaN(val) ? 0 : val),
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,14 +22,28 @@ 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
- declare type FormControllerBehavior<StateBeforeValidation> = {
46
+ declare type FormControllerBehavior<StateBeforeValidation extends StateRestriction> = {
33
47
  /** For testing */
34
48
  peek: (eyeball: (prev: FullFormState<StateBeforeValidation>) => void) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
35
49
  reset: () => () => FullFormState<StateBeforeValidation>;
@@ -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
- handleError: (reducer: (prev: FormErrors<StateBeforeValidation>) => FormErrors<StateBeforeValidation>) => (prev: FullFormState<StateBeforeValidation>) => FullFormState<StateBeforeValidation>;
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>>;
@@ -54,9 +69,9 @@ declare type FormControllerBehavior<StateBeforeValidation> = {
54
69
  declare type ActionsCanBePublic<State extends StateRestriction> = {
55
70
  reset: VoidFunction;
56
71
  initializeForm: (initial: Partial<State>) => void;
72
+ pushFormErrors: (validator: (state: State) => Partial<FormErrors<State>>) => void;
57
73
  handleChange: HandleChangeAction<State>;
58
74
  handleBulkChange: (setter: (prev: State) => Partial<State>) => void;
59
- handleError: (reducer: (prev: FormErrors<State>) => FormErrors<State>) => void;
60
75
  };
61
76
  /**
62
77
  * Restricted type interface of the form store
@@ -86,6 +101,6 @@ declare type FormHook<State extends StateRestriction, Schema extends ZodType<any
86
101
  /**
87
102
  * @typeParam InitialState should be shallow
88
103
  */
89
- export declare function createFormHook<StateBeforeValidation, Schema extends ZodType<any, any, any>>(initialState: StateBeforeValidation, schema: Schema): FormHook<StateBeforeValidation, Schema>;
104
+ export declare function createFormHook<StateBeforeValidation extends StateRestriction, Schema extends ZodType<any, any, any>>(initialState: StateBeforeValidation, schema: Schema): FormHook<StateBeforeValidation, Schema>;
90
105
  export declare function useFormSlice<State extends StateRestriction, Sliced>(formController: Controller<State>, selector: (s: FullFormState<State>) => Sliced): readonly [Sliced, ActionsCanBePublic<State>];
91
106
  export {};
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
- handleError: (reducer) => (prev) => {
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 value = formHook.useSelector(selector);
107
+ const { selector, children, deps } = props;
108
+ const slicedValues = formHook.useSelector(selector);
105
109
  return useMemo(() => {
106
- const renderContent = children({ handleChange: formHook.actions.handleChange }, ...value);
110
+ const renderContent = children({ handleChange: formHook.actions.handleChange }, ...slicedValues);
107
111
  return createElement(Fragment, {}, renderContent);
108
- }, value);
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,
@@ -7,13 +7,16 @@ import { createFormHook, useFormSlice } from './index';
7
7
  const testSchema = zod.object({
8
8
  name: zod.string(),
9
9
  description: zod.string(),
10
- age: zod.string().transform(val => Number(val)).refine(val => Number.isNaN(val) ? 0 : val),
10
+ age: zod
11
+ .string()
12
+ .transform((val) => Number(val))
13
+ .refine((val) => (Number.isNaN(val) ? 0 : val)),
11
14
  marked: zod.boolean(),
12
15
  });
13
16
  const createTestHook = () => createFormHook({ name: '', description: '', age: '', marked: false }, testSchema);
14
17
  const AgeInputComponent = (props) => {
15
18
  const { controller } = props;
16
- const [[age, errorMessage], { handleChange }] = useFormSlice(controller, s => [s.value.age, s.errors.age]);
19
+ const [[age, errorMessage], { handleChange }] = useFormSlice(controller, (s) => [s.value.age, s.errors.age]);
17
20
  return (React.createElement("div", null,
18
21
  React.createElement("input", { "data-testid": "age-input", value: age, name: "age", onChange: (e) => {
19
22
  handleChange('age', e.currentTarget.value);
package/docs/.nojekyll CHANGED
@@ -0,0 +1 @@
1
+ TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false.
@@ -0,0 +1,92 @@
1
+ :root {
2
+ --light-hl-0: #0000FF;
3
+ --dark-hl-0: #569CD6;
4
+ --light-hl-1: #000000;
5
+ --dark-hl-1: #D4D4D4;
6
+ --light-hl-2: #0070C1;
7
+ --dark-hl-2: #4FC1FF;
8
+ --light-hl-3: #001080;
9
+ --dark-hl-3: #9CDCFE;
10
+ --light-hl-4: #795E26;
11
+ --dark-hl-4: #DCDCAA;
12
+ --light-hl-5: #267F99;
13
+ --dark-hl-5: #4EC9B0;
14
+ --light-hl-6: #098658;
15
+ --dark-hl-6: #B5CEA8;
16
+ --light-hl-7: #A31515;
17
+ --dark-hl-7: #CE9178;
18
+ --light-hl-8: #AF00DB;
19
+ --dark-hl-8: #C586C0;
20
+ --light-hl-9: #008000;
21
+ --dark-hl-9: #6A9955;
22
+ --light-code-background: #F5F5F5;
23
+ --dark-code-background: #1E1E1E;
24
+ }
25
+
26
+ @media (prefers-color-scheme: light) { :root {
27
+ --hl-0: var(--light-hl-0);
28
+ --hl-1: var(--light-hl-1);
29
+ --hl-2: var(--light-hl-2);
30
+ --hl-3: var(--light-hl-3);
31
+ --hl-4: var(--light-hl-4);
32
+ --hl-5: var(--light-hl-5);
33
+ --hl-6: var(--light-hl-6);
34
+ --hl-7: var(--light-hl-7);
35
+ --hl-8: var(--light-hl-8);
36
+ --hl-9: var(--light-hl-9);
37
+ --code-background: var(--light-code-background);
38
+ } }
39
+
40
+ @media (prefers-color-scheme: dark) { :root {
41
+ --hl-0: var(--dark-hl-0);
42
+ --hl-1: var(--dark-hl-1);
43
+ --hl-2: var(--dark-hl-2);
44
+ --hl-3: var(--dark-hl-3);
45
+ --hl-4: var(--dark-hl-4);
46
+ --hl-5: var(--dark-hl-5);
47
+ --hl-6: var(--dark-hl-6);
48
+ --hl-7: var(--dark-hl-7);
49
+ --hl-8: var(--dark-hl-8);
50
+ --hl-9: var(--dark-hl-9);
51
+ --code-background: var(--dark-code-background);
52
+ } }
53
+
54
+ body.light {
55
+ --hl-0: var(--light-hl-0);
56
+ --hl-1: var(--light-hl-1);
57
+ --hl-2: var(--light-hl-2);
58
+ --hl-3: var(--light-hl-3);
59
+ --hl-4: var(--light-hl-4);
60
+ --hl-5: var(--light-hl-5);
61
+ --hl-6: var(--light-hl-6);
62
+ --hl-7: var(--light-hl-7);
63
+ --hl-8: var(--light-hl-8);
64
+ --hl-9: var(--light-hl-9);
65
+ --code-background: var(--light-code-background);
66
+ }
67
+
68
+ body.dark {
69
+ --hl-0: var(--dark-hl-0);
70
+ --hl-1: var(--dark-hl-1);
71
+ --hl-2: var(--dark-hl-2);
72
+ --hl-3: var(--dark-hl-3);
73
+ --hl-4: var(--dark-hl-4);
74
+ --hl-5: var(--dark-hl-5);
75
+ --hl-6: var(--dark-hl-6);
76
+ --hl-7: var(--dark-hl-7);
77
+ --hl-8: var(--dark-hl-8);
78
+ --hl-9: var(--dark-hl-9);
79
+ --code-background: var(--dark-code-background);
80
+ }
81
+
82
+ .hl-0 { color: var(--hl-0); }
83
+ .hl-1 { color: var(--hl-1); }
84
+ .hl-2 { color: var(--hl-2); }
85
+ .hl-3 { color: var(--hl-3); }
86
+ .hl-4 { color: var(--hl-4); }
87
+ .hl-5 { color: var(--hl-5); }
88
+ .hl-6 { color: var(--hl-6); }
89
+ .hl-7 { color: var(--hl-7); }
90
+ .hl-8 { color: var(--hl-8); }
91
+ .hl-9 { color: var(--hl-9); }
92
+ pre, code { background: var(--code-background); }