Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested schema #48

Merged
merged 6 commits into from
Jan 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"devDependencies": {
"@size-limit/preset-small-lib": "^7.0.5",
"@tsconfig/recommended": "^1.0.1",
"@types/object-path": "^0.11.1",
"@types/ramda": "^0.27.61",
"dts-cli": "^1.1.3",
"size-limit": "^7.0.5",
Expand Down Expand Up @@ -78,5 +79,8 @@
"bugs": {
"url": "https://github.com/JoshuaAmaju/elderform/issues"
},
"homepage": "https://github.com/JoshuaAmaju/elderform#readme"
"homepage": "https://github.com/JoshuaAmaju/elderform#readme",
"dependencies": {
"object-path": "^0.11.8"
}
}
15 changes: 7 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import recPath from 'object-path';
import type { Interpreter } from 'xstate';
import { interpret } from 'xstate';
import {
Expand All @@ -9,12 +10,11 @@ import {
States,
} from './machine';
import { Validator } from './machine/types';
import { FlattenKeys, FlattenValues } from './machine/utils';

export * from './machine/types';
export { object, retry } from './tools';

export type { Context, States, Events };

export { EventTypes };

declare var __DEV__: boolean;
Expand Down Expand Up @@ -50,7 +50,9 @@ export type Handler<T, E> = (
HandleActions<T>;

export type Handlers<T, Es> = {
[K in keyof T]: Handler<T[K], Es>;
[K in FlattenKeys<T>]: K extends keyof T
? Handler<T[K] extends object ? FlattenValues<T[K]> : T[K], Es>
: Handler<any, Es>;
};

type Generate<T, D, E, Es> = (ctx: Context<T, D, E, Es>) => Handlers<T, Es>;
Expand Down Expand Up @@ -98,10 +100,7 @@ export type Service<T, D, E, Es> = {
setField: <K extends keyof T>(name: K, value: T[K]) => void;
setFieldWithValidate: <K extends keyof T>(name: K, value: T[K]) => void;
subscribe: (
fn: (
val: SubscriptionValue<T, D, E, Es>,
handlers: { [K in keyof T]: Handler<T[K], Es> }
) => void
fn: (val: SubscriptionValue<T, D, E, Es>, handlers: Handlers<T, Es>) => void
) => () => void;
__generate: Generate<T, D, E, Es>;
__service: Interpreter<
Expand Down Expand Up @@ -159,9 +158,9 @@ export const createForm = <T = any, D = any, E = any, Es = any, TData = D>({

const entries = Object.keys(actors).map((k) => {
const id = k as keyof T;
const value = values[id];
const error = errors.get(id);
const state = states[id] as any;
const value = recPath.get(values, k);

const handler: Handler<T[typeof id], Es> = {
state,
Expand Down
39 changes: 29 additions & 10 deletions src/machine/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { choose, pure } from 'xstate/lib/actions';
import { Validator } from '..';
import { actor } from './actor';
import { Schema } from './types';
import { flatten } from './utils';
import recPath from 'object-path';

declare var __DEV__: boolean;

Expand Down Expand Up @@ -100,6 +102,21 @@ const onChangeWithValidateActions = [
),
] as any;

const validateActions = [
'removeError',
'setActorIdle',
send(
({ values }: any, { id }: any) => ({
values,
type: 'VALIDATE',
value: recPath.get(values, id),
}),
{
to: (_, { id }) => id,
}
),
] as any;

export const machine = <T, D, E, Es>() => {
return createMachine<
Context<T, D, E, Es>,
Expand Down Expand Up @@ -135,7 +152,7 @@ export const machine = <T, D, E, Es>() => {
actions: onChangeActions,
},

[EventTypes.Validate]: {
[EventTypes.ChangeWithValidate]: {
target: 'idle',
cond: 'hasSchema',
actions: onChangeWithValidateActions,
Expand Down Expand Up @@ -251,7 +268,7 @@ export const machine = <T, D, E, Es>() => {

[EventTypes.Validate]: {
cond: 'hasSchema',
actions: onChangeWithValidateActions,
actions: validateActions,
},

[EventTypes.ChangeWithValidate]: {
Expand All @@ -273,7 +290,7 @@ export const machine = <T, D, E, Es>() => {
return Object.keys(actors)
.filter((key) => !__ignore.has(key as keyof T))
.map((key) => {
const value = values[key as keyof T];
const value = recPath.get(values, key);
return send(
{ value, values, type: 'VALIDATE' },
{ to: key as string }
Expand Down Expand Up @@ -403,10 +420,9 @@ export const machine = <T, D, E, Es>() => {

setInitialStates: assign({
states: ({ schema }) => {
const entries = Object.keys(schema as Schema).map((key) => [
key,
'idle',
]);
const flattened = flatten(schema as Schema);

const entries = Object.keys(flattened).map((key) => [key, 'idle']);
return Object.fromEntries(entries);
},
}),
Expand All @@ -415,11 +431,13 @@ export const machine = <T, D, E, Es>() => {
actors: ({ schema }) => {
const shape = schema as Schema;

const entries = Object.keys(shape).map((key) => {
const flattened = flatten(shape);

const entries = Object.keys(flattened).map((key) => {
const act = spawn(
actor({
id: key as string,
validator: shape[key],
validator: flattened[key],
}),
key as string
);
Expand All @@ -433,7 +451,8 @@ export const machine = <T, D, E, Es>() => {

setValue: assign({
values: ({ values }, { id, value }: any) => {
return { ...values, [id]: value };
recPath.set(values, id, value);
return values;
},
}),

Expand Down
4 changes: 3 additions & 1 deletion src/machine/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export type Schema<T = any> = { [K in keyof T]: Validator<T, T[K]> };
export type Schema<T = any> = {
[K in keyof T]: Schema<T[K]> | Validator<T, T[K]>;
};

export type Validator<SchemaType = any, T = any> = (
value: T,
Expand Down
50 changes: 50 additions & 0 deletions src/machine/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Validator } from './types';

export type FlattenKeys<T> = {
[K in keyof T & (string | number)]: RecursiveKeyOfHandleValue<T[K], `${K}`>;
}[keyof T & (string | number)];

type RecursiveKeyOfInner<T> = {
[K in keyof T & (string | number)]: RecursiveKeyOfHandleValue<T[K], `.${K}`>;
}[keyof T & (string | number)];

type RecursiveKeyOfHandleValue<
TValue,
Text extends string
> = TValue extends any[]
? Text
: TValue extends object
? Text | `${Text}${RecursiveKeyOfInner<TValue>}`
: Text;

export type FlattenValues<T> = {
[K in keyof T & (string | number)]: RecursiveValueOfHandleValue<T[K]>;
}[keyof T & (string | number)];

type RecursiveValueOfInner<T> = {
[K in keyof T & (string | number)]: RecursiveValueOfHandleValue<T[K]>;
}[keyof T & (string | number)];

type RecursiveValueOfHandleValue<TValue> = TValue extends object
? RecursiveValueOfInner<TValue>
: TValue;

export const flatten = <T>(
obj: T,
roots: (keyof T)[] = [],
sep = '.'
): { [K in keyof T]: Validator } => {
return Object.keys(obj).reduce((accumulator, k) => {
const key = k as keyof T;
const value = obj[key];

return {
...accumulator,
...(Object.prototype.toString.call(value) === '[object Object]'
? // keep working if value is an object
flatten(value as any, roots.concat([key]), sep)
: // include current prop and value and prefix prop with the roots
{ [roots.concat([key]).join(sep)]: value }),
};
}, {} as any);
};
103 changes: 103 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,106 @@ describe('dynamic schema', () => {
});
});
});

describe('nested schemas', () => {
const schema = object({
name: (v: any) => z.string().parse(v),
address: object({
line: (v: any) => z.string().parse(v),
city: (v: any) => z.string().parse(v),
state: (v: any) => z.string().parse(v),
}),
});

type Form = Infer<typeof schema>;

let service: Interpreter<
Context<Form, any, any>,
any,
Events<Form, any, any>,
States<Form, any, any>
> | null;

beforeEach(() => {
const def = machine<Form, any, any, any>();

service = interpret(
def.withContext({
...def.context,
schema,
values: {
name: 'Jane',
address: {
line: 'No 4',
city: 'Alausa',
state: 'Lagos',
},
},
})
).start();
});

afterEach(() => {
service?.stop();
service = null;
});

it('should support nested values', (done) => {
service?.onTransition((state) => {
const { values } = state.context;

expect(values).toMatchObject({
name: 'Jane',
address: {
line: 'No 4',
city: 'Alausa',
state: 'Lagos',
},
});

done();
});
});

it('should support setting value using dot notation', (done) => {
service?.onChange(({ values }) => {
expect(values).toMatchObject({
name: 'Jane',
address: { line: 'No 15', city: 'Alausa', state: 'Lagos' },
});

done();
});

service?.send({
type: EventTypes.Change,
id: 'address.line' as any,
value: 'No 15',
});
});

it('should access field state and error using dot notation', (done) => {
const dotKey = 'address.line' as keyof Form;

service?.onTransition(({ event, context }) => {
expect(context.errors.has(dotKey)).toBe(false);

switch (event.type) {
case 'VALIDATING':
expect(context.states[dotKey]).toBe('validating');
break;

case 'SUCCESS':
expect(context.states[dotKey]).toBe('success');
done();
break;

default:
expect(context.states[dotKey]).toBe('idle');
break;
}
});

service?.send({ id: dotKey, type: EventTypes.Validate });
});
});