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

feat(core): use-formts setup #11

Merged
merged 7 commits into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
103 changes: 103 additions & 0 deletions src/core/hooks/create-initial-state.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { createFormSchema } from "../builders/create-form-schema";

import { createInitialState } from "./create-initial-state";

describe("create-initial-state", () => {
it("should be empty for empty schema", () => {
expect(createInitialState({})).toEqual({});
});

it("for one-element schema", () => {
const schema = createFormSchema(fields => ({
stringField: fields.string(),
}));

expect(createInitialState(schema)).toEqual({ stringField: "" });
});

it("for one-element schema", () => {
const schema = createFormSchema(fields => ({
stringField: fields.string(),
}));

expect(createInitialState(schema)).toEqual({ stringField: "" });
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

duplicated test


it("for multi-element schema", () => {
const schema = createFormSchema(fields => ({
stringField: fields.string(),
boolField: fields.bool(),
numberField: fields.number(),
arrayField: fields.array(fields.number()),
choiceField: fields.choice("Banana", "Avocado", "Cream"),
}));

expect(createInitialState(schema)).toEqual({
stringField: "",
boolField: false,
numberField: "",
arrayField: [],
choiceField: "Banana",
});
});

it("for multi-element schema with single-element init", () => {
const schema = createFormSchema(fields => ({
stringField: fields.string(),
boolField: fields.bool(),
numberField: fields.number(),
arrayField: fields.array(fields.number()),
choiceField: fields.choice("Banana", "Avocado", "Cream"),
}));

expect(createInitialState(schema, { stringField: "dodo" })).toEqual({
stringField: "dodo",
boolField: false,
numberField: "",
arrayField: [],
choiceField: "Banana",
});
});

it("for multi-element schema with multiple-element init", () => {
const schema = createFormSchema(fields => ({
stringField: fields.string(),
boolField: fields.bool(),
numberField: fields.number(),
arrayField: fields.array(fields.number()),
choiceField: fields.choice("Banana", "Avocado", "Cream"),
}));

expect(
createInitialState(schema, {
stringField: "dodo",
boolField: true,
numberField: 0,
arrayField: [1, 2, 3],
choiceField: "Cream",
})
).toEqual({
stringField: "dodo",
boolField: true,
numberField: 0,
arrayField: [1, 2, 3],
choiceField: "Cream",
});
});

it("for nested-object", () => {
const schema = createFormSchema(fields => ({
parent: fields.object({
kain: fields.choice("Banana", "Spinach"),
abel: fields.bool(),
}),
}));

expect(createInitialState(schema, { parent: { abel: true } })).toEqual({
parent: {
kain: "Banana",
abel: true,
},
});
});
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe another test case test case for sth like

const schema = createFormSchema(fields => ({
   arr: fields.array(fields.object({ foo: fields.string(), bar: fields.string() }))
}));
const init = { arr: [{ foo: "foo" }]}

const expectedResult = { arr: [{ foo: "foo", bar: "" }]}

36 changes: 36 additions & 0 deletions src/core/hooks/create-initial-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { deepMerge, DeepPartial, entries } from "../../utils";
import { _FieldDescriptorImpl } from "../types/field-descriptor";
import { FormSchema } from "../types/form-schema";
import {
isArrayDesc,
isObjectDesc,
schemaImpl,
_DescriptorApprox_,
_FormSchemaApprox_,
} from "../types/form-schema-approx";

export const createInitialState = <Values extends object>(
_schema: FormSchema<Values, any>,
initial?: DeepPartial<Values>
): Values => {
const schema = schemaImpl(_schema);

const initialStateFromDecoders = entries(schema).reduce(
(shape, [key, value]) => {
const descriptor = value as _DescriptorApprox_<Values[typeof key]>;

const fieldInitialValue =
isArrayDesc(descriptor) || isObjectDesc(descriptor)
? descriptor.root.init()
: descriptor.init();

shape[key] = fieldInitialValue;
return shape;
},
{} as Values
);

return initial
? deepMerge(initialStateFromDecoders, initial)
: initialStateFromDecoders;
};
185 changes: 182 additions & 3 deletions src/core/hooks/use-formts.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,186 @@
import { assert, IsExact } from "conditional-type-checks";

import { createFormSchema } from "../builders/create-form-schema";

import { useFormts } from "./use-formts";

describe("useFormts", () => {
it("should not be implemented yet", () => {
expect(() => useFormts()).toThrowError("not implemented!");
// dummy test for temporal implementation
describe("use-formts", () => {
const Schema = createFormSchema(fields => ({
theString: fields.string(),
theChoice: fields.choice("A", "B", "C"),
theNum: fields.number(),
theBool: fields.bool(),
theArrayString: fields.array(fields.string()),
theArrayChoice: fields.array(fields.choice("a", "b", "c")),
theArrayArrayString: fields.array(fields.array(fields.string())),
theInstance: fields.instanceOf(Date),
}));

const [fields, get, set] = useFormts({
Schema,
initialValues: {
theNum: 12,
theArrayArrayString: [["here"], ["comes", "the", "sun"]],
theArrayChoice: ["a"],
},
});

it("state is properly initialized", () => {
expect(fields.theString).toEqual("");
expect(fields.theChoice).toEqual("A");
expect(fields.theNum).toEqual(12);
expect(fields.theBool).toEqual(false);
expect(fields.theArrayString).toEqual([]);
expect(fields.theArrayChoice).toEqual(["a"]);
expect(fields.theArrayArrayString).toEqual([
["here"],
["comes", "the", "sun"],
]);
expect(fields.theInstance).toEqual(null);
});

it("get should work for non-arrays", () => {
expect(get(Schema.theString)).toEqual("");
expect(get(Schema.theChoice)).toEqual("A");
expect(get(Schema.theNum)).toEqual(12);
expect(get(Schema.theBool)).toEqual(false);
expect(get(Schema.theInstance)).toEqual(null);
});

it("get should work for one-element array", () => {
const root = get(Schema.theArrayChoice.root);
assert<IsExact<typeof root, ("a" | "b" | "c")[]>>(true);

const first = get(Schema.theArrayChoice.nth(0));
assert<IsExact<typeof first, "a" | "b" | "c">>(true);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't it be "a" | "b" | "c" | undefiend ?


expect(root).toEqual(["a"]);
expect(first).toEqual("a");
expect(get(Schema.theArrayChoice.nth(1))).toEqual(undefined);
});

it("get should work for no-element array", () => {
const root = get(Schema.theArrayString.root);
const first = get(Schema.theArrayString.nth(0));

expect(root).toEqual([]);
expect(first).toEqual(undefined);
});

it("get should work for 2D array", () => {
const root = get(Schema.theArrayArrayString.root);
const first = get(Schema.theArrayArrayString.nth(0).root);
const firstOfFirst = get(Schema.theArrayArrayString.nth(0).nth(0));

const second = get(Schema.theArrayArrayString.nth(1).root);
const secondOfSecond = get(Schema.theArrayArrayString.nth(1).nth(1));

const wrong = get(Schema.theArrayArrayString.nth(19).nth(10));

expect(root).toEqual([["here"], ["comes", "the", "sun"]]);
expect(first).toEqual(["here"]);
expect(firstOfFirst).toEqual("here");

expect(second).toEqual(["comes", "the", "sun"]);
expect(secondOfSecond).toEqual("the");

expect(wrong).toEqual(undefined);
});

it("set should work for string", () => {
const shape = set(Schema.theString, "set");

expect(shape.theString).toEqual("set");
expect(shape.theChoice).toEqual("A");
expect(shape.theNum).toEqual(12);
expect(shape.theBool).toEqual(false);
expect(shape.theArrayString).toEqual([]);
expect(shape.theArrayChoice).toEqual(["a"]);
expect(shape.theArrayArrayString).toEqual([
["here"],
["comes", "the", "sun"],
]);
expect(shape.theInstance).toEqual(null);
});

it("set should work for choice", () => {
// !TS will allow to pass any string here
const shape = set(Schema.theChoice, "C");

expect(shape.theString).toEqual("");
expect(shape.theChoice).toEqual("C");
expect(shape.theNum).toEqual(12);
expect(shape.theBool).toEqual(false);
expect(shape.theArrayString).toEqual([]);
expect(shape.theArrayChoice).toEqual(["a"]);
expect(shape.theArrayArrayString).toEqual([
["here"],
["comes", "the", "sun"],
]);
expect(shape.theInstance).toEqual(null);
});

it("set should work for array", () => {
const shape = set(Schema.theArrayChoice.root, ["b", "b"]);

expect(shape.theString).toEqual("");
expect(shape.theChoice).toEqual("A");
expect(shape.theNum).toEqual(12);
expect(shape.theBool).toEqual(false);
expect(shape.theArrayString).toEqual([]);
expect(shape.theArrayChoice).toEqual(["b", "b"]);
expect(shape.theArrayArrayString).toEqual([
["here"],
["comes", "the", "sun"],
]);
expect(shape.theInstance).toEqual(null);
});

it("set should work for array element", () => {
const shape = set(Schema.theArrayArrayString.nth(1).nth(1), "THE");

expect(shape.theArrayArrayString).toEqual([
["here"],
["comes", "THE", "sun"],
]);
});

it("should work for nested objects", () => {
const Schema = createFormSchema(fields => ({
fridge: fields.object({
fruit: fields.array(fields.choice("banana", "berry", "kiwi")),
milk: fields.number(),
}),
}));

const [fields, get, set] = useFormts({
Schema,
initialValues: {
fridge: {
fruit: ["banana", "banana"],
milk: 10,
},
},
});

const fruit = fields.fridge.fruit;
expect(fruit).toEqual(["banana", "banana"]);

const milk = fields.fridge.milk;
expect(milk).toEqual(10);

expect(get(Schema.fridge.root)).toEqual({
fruit: ["banana", "banana"],
milk: 10,
});
expect(get(Schema.fridge.fruit.root)).toEqual(["banana", "banana"]);
expect(get(Schema.fridge.milk)).toEqual(10);

const shape1 = set(Schema.fridge.root, { fruit: ["berry"], milk: 12 });
expect(shape1.fridge).toEqual({ fruit: ["berry"], milk: 12 });

const shape2 = set(Schema.fridge.fruit.nth(0), "kiwi");
expect(shape2.fridge).toEqual({ fruit: ["kiwi", "banana"], milk: 10 });
});
});
50 changes: 47 additions & 3 deletions src/core/hooks/use-formts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,48 @@
/** don't use it yet.. */
export const useFormts = () => {
throw new Error("not implemented!");
import { DeepPartial, get, set } from "../../utils";
import {
FieldDescriptor,
_FieldDescriptorImpl,
} from "../types/field-descriptor";
import { FormSchema } from "../types/form-schema";
import { impl } from "../types/type-mapper-util";

import { createInitialState } from "./create-initial-state";

export type FormtsOptions<Values extends object, Err> = {
/** Definition of form fields created using `createForm.schema` function. */
Schema: FormSchema<Values, Err>;

/**
* Values used to override the defaults when filling the form
* after the component is mounted or after form reset (optional).
* The defaults depend on field type (defined in the Schema).
*/
initialValues?: DeepPartial<Values>;
};

export const useFormts = <Values extends object, Err>(
options: FormtsOptions<Values, Err>
): [
Values,
<T, Err>(desc: FieldDescriptor<T, Err>) => T,
<T, Err>(desc: FieldDescriptor<T, Err>, value: T) => Values
] => {
const formState = createInitialState(options.Schema, options.initialValues);
const get = getter(formState);
const set = setter(formState);

return [formState, get, set];
};

const getter = <Values extends object>(state: Values) => <T, Err>(
desc: FieldDescriptor<T, Err>
): T => {
return get(state, impl(desc).path) as any;
};

const setter = <Values extends object>(state: Values) => <T, Err>(
desc: FieldDescriptor<T, Err>,
value: {} & T
): Values => {
return set(state, impl(desc).path, value) as any;
};
8 changes: 8 additions & 0 deletions src/core/types/field-handle-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FieldHandle } from "./field-handle";

/**
* Tree of field handles used to interact with all fields of the form
*/
export type FieldHandleSchema<Values extends object, Err> = {
readonly [K in keyof Values]: FieldHandle<Values[K], Err>;
};
Loading