Skip to content

Commit

Permalink
refactor: Rename types
Browse files Browse the repository at this point in the history
- `UserData` → `SchemaData`
- `UserResponse` → `SchemaResponse`
  • Loading branch information
DafyddLlyr committed Aug 22, 2024
1 parent 73d8374 commit f0b331a
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 46 deletions.
32 changes: 16 additions & 16 deletions editor.planx.uk/src/@planx/components/List/Public/Context.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useSchema } from "@planx/components/shared/Schema/hook";
import {
Schema,
UserData,
UserResponse,
SchemaData,
SchemaResponse,
} from "@planx/components/shared/Schema/model"
import {
getPreviouslySubmittedData,
Expand Down Expand Up @@ -32,7 +32,7 @@ interface ListContextValue {
removeItem: (index: number) => void;
editItem: (index: number) => void;
cancelEditItem: () => void;
formik: FormikProps<UserData>;
formik: FormikProps<SchemaData>;
validateAndSubmitForm: () => void;
listProps: PublicProps<List>;
/**
Expand Down Expand Up @@ -62,11 +62,11 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
previousValues: getPreviouslySubmittedData(props),
});

const formik = useFormik<UserData>({
const formik = useFormik<SchemaData>({
...formikConfig,
onSubmit: (values) => {
// defaultPassportData (array) is used when coming "back"
const defaultPassportData = makeData(props, values.userData)?.["data"];
const defaultPassportData = makeData(props, values.schemaData)?.["data"];

// flattenedPassportData makes individual list items compatible with Calculate components
const flattenedPassportData = flatten(defaultPassportData, { depth: 2 });
Expand Down Expand Up @@ -107,7 +107,7 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
);

const [activeItemInitialState, setActiveItemInitialState] = useState<
UserResponse | undefined
SchemaResponse | undefined
>(undefined);

const [addItemError, setAddItemError] = useState<boolean>(false);
Expand All @@ -128,21 +128,21 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
if (activeIndex !== -1) return setAddItemError(true);

// Do not allow new item to be added if it will exceed max
if (schema.max && formik.values.userData.length === schema.max) {
if (schema.max && formik.values.schemaData.length === schema.max) {
return setMaxError(true);
}

// Add new item, and set to active
setAddItemError(false);
formik.values.userData.push(initialValues);
setActiveIndex(formik.values.userData.length - 1);
formik.values.schemaData.push(initialValues);
setActiveIndex(formik.values.schemaData.length - 1);
};

const saveItem = async () => {
resetErrors();

const errors = await formik.validateForm();
const isValid = !errors.userData?.length;
const isValid = !errors.schemaData?.length;
if (isValid) {
exitEditMode();
setAddItemError(false);
Expand All @@ -157,10 +157,10 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
setActiveIndex((prev) => (prev === -1 ? 0 : prev - 1));
}

// Remove item from userData
// Remove item from schemaData
formik.setFieldValue(
"userData",
formik.values.userData.filter((_, i) => i !== index),
"schemaData",
formik.values.schemaData.filter((_, i) => i !== index),
);
};

Expand All @@ -169,7 +169,7 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
if (activeIndex !== -1) return setUnsavedItemError(true);

// Manually validate minimum number of items
if (formik.values.userData.length < schema.min) {
if (formik.values.schemaData.length < schema.min) {
return setMinError(true);
}

Expand All @@ -187,14 +187,14 @@ export const ListProvider: React.FC<ListProviderProps> = (props) => {
};

const editItem = (index: number) => {
setActiveItemInitialState(formik.values.userData[index]);
setActiveItemInitialState(formik.values.schemaData[index]);
setActiveIndex(index);
};

const exitEditMode = () => setActiveIndex(-1);

const resetItemToPreviousState = () =>
formik.setFieldValue(`userData[${activeIndex}]`, activeItemInitialState);
formik.setFieldValue(`schemaData[${activeIndex}]`, activeItemInitialState);

const isPageComponent = schema.max === 1;

Expand Down
8 changes: 4 additions & 4 deletions editor.planx.uk/src/@planx/components/List/Public/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ const InactiveListCard: React.FC<{
</TableCell>
<TableCell>
{formatSchemaDisplayValue(
formik.values.userData[i][field.data.fn],
formik.values.schemaData[i][field.data.fn],
schema.fields[j],
)}
</TableCell>
Expand Down Expand Up @@ -137,9 +137,9 @@ const Root = () => {
(errors.max && `You can provide at most ${schema.max} response(s)`) ||
"";

// Hide the "+ Add another" button if the schema has a max length of 1, unless the only item has been cancelled/removed (userData = [])
// Hide the "+ Add another" button if the schema has a max length of 1, unless the only item has been cancelled/removed (schemaData = [])
const shouldShowAddAnotherButton =
schema.max !== 1 || formik.values.userData.length < 1;
schema.max !== 1 || formik.values.schemaData.length < 1;

return (
<Card handleSubmit={validateAndSubmitForm} isValid>
Expand All @@ -152,7 +152,7 @@ const Root = () => {
/>
<ErrorWrapper error={rootError}>
<>
{formik.values.userData.map((_, i) =>
{formik.values.schemaData.map((_, i) =>
i === activeIndex ? (
<ActiveListCard key={`card-${i}`} index={i} />
) : (
Expand Down
4 changes: 2 additions & 2 deletions editor.planx.uk/src/@planx/components/List/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UserResponse } from "./../shared/Schema/model";
import { SchemaResponse } from "./../shared/Schema/model";
import {
flatten,
sumIdenticalUnits,
Expand Down Expand Up @@ -63,7 +63,7 @@ describe("passport data shape", () => {
identicalUnits: 2,
},
],
} as unknown as Record<string, UserResponse[]>;
} as unknown as Record<string, SchemaResponse[]>;

expect(
sumIdenticalUnits("proposal.units.residential", defaultPassportData),
Expand Down
6 changes: 3 additions & 3 deletions editor.planx.uk/src/@planx/components/List/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { styled } from "@mui/material/styles";
import React from "react";

import { Field, UserResponse } from "./../shared/Schema/model";
import { Field, SchemaResponse } from "./../shared/Schema/model";

const List = styled("ul")(() => ({
listStylePosition: "inside",
Expand Down Expand Up @@ -54,7 +54,7 @@ export function formatSchemaDisplayValue(
*/
export function sumIdenticalUnits(
fn: string,
passportData: Record<string, UserResponse[]>,
passportData: Record<string, SchemaResponse[]>,
): number {
let sum = 0;
passportData[`${fn}`].map((item) => {
Expand All @@ -73,7 +73,7 @@ export function sumIdenticalUnits(
*/
export function sumIdenticalUnitsByDevelopmentType(
fn: string,
passportData: Record<string, UserResponse[]>,
passportData: Record<string, SchemaResponse[]>,
): Record<string, number> {
// Sum identical units by development type (@todo read all possible option `val` from Schema in future)
const baseSums: Record<string, number> = {
Expand Down
10 changes: 5 additions & 5 deletions editor.planx.uk/src/@planx/components/shared/Schema/Fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import type {
MapField,
NumberField,
QuestionField,
SchemaData,
TextField,
UserData,
} from "@planx/components/shared/Schema/model";
import { FormikProps } from "formik";
import { Feature } from "geojson";
Expand All @@ -34,7 +34,7 @@ import { DESCRIPTION_TEXT, ERROR_MESSAGE } from "../constants";
import BasicRadio from "../Radio/BasicRadio";

type Props<T extends Field> = {
formik: FormikProps<UserData>
formik: FormikProps<SchemaData>
activeIndex: number;
} & T;

Expand All @@ -43,9 +43,9 @@ type Props<T extends Field> = {
*/
const getFieldProps = <T extends Field>(props: Props<T>) => ({
id: `input-${props.type}-${props.data.fn}`,
errorMessage: get(props.formik.errors, ["userData", props.activeIndex, props.data.fn]),
name: `userData[${props.activeIndex}]['${props.data.fn}']`,
value: props.formik.values.userData[props.activeIndex][props.data.fn],
errorMessage: get(props.formik.errors, ["schemaData", props.activeIndex, props.data.fn]),
name: `schemaData[${props.activeIndex}]['${props.data.fn}']`,
value: props.formik.values.schemaData[props.activeIndex][props.data.fn],
});

export const TextFieldInput: React.FC<Props<TextField>> = (props) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import React from "react";
import InputRow from "ui/shared/InputRow";

import { ChecklistFieldInput, DateFieldInput, MapFieldInput, NumberFieldInput, RadioFieldInput, SelectFieldInput, TextFieldInput } from "./Fields";
import { Field, Schema, UserData } from "./model";
import { Field, Schema, SchemaData } from "./model";

type InputFieldProps = {
activeIndex: number;
formik: FormikProps<UserData>;
formik: FormikProps<SchemaData>;
} & Field;

/**
Expand Down Expand Up @@ -39,11 +39,11 @@ interface SchemaFieldsProps {
/**
* Optional index of currently active schema instance.
* Only required if multiple user responses are allowed, e.g. in the List component.
* Defaults to 0 as `UserData` always holds an array of responses
* Defaults to 0 as `SchemaData` always holds an array of responses
*/
activeIndex?: number;
/** Formik instance generated from config provided by useSchema hook */
formik: FormikProps<UserData>;
formik: FormikProps<SchemaData>;
schema: Schema;
}

Expand Down
14 changes: 7 additions & 7 deletions editor.planx.uk/src/@planx/components/shared/Schema/hook.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { FormikConfig } from "formik";

import { generateInitialValues, generateValidationSchema, Schema, UserData, UserResponse } from "./model";
import { generateInitialValues, generateValidationSchema, Schema, SchemaData, SchemaResponse } from "./model";

type UseSchema = (props: {
schema: Schema;
previousValues?: UserResponse[];
previousValues?: SchemaResponse[];
}) => {
/**
* Extensible Formik config which allows custom form state and submission logic
* @example const formik = useFormik<UserData & MyCustomState>(...)
* @example const formik = useFormik<UserData>(...formikConfig, onSubmit: () => {...})
* @example const formik = useFormik<SchemaData & MyCustomState>(...)
* @example const formik = useFormik<SchemaData>(...formikConfig, onSubmit: () => {...})
*/
formikConfig: Omit<FormikConfig<UserData>, "onSubmit">,
formikConfig: Omit<FormikConfig<SchemaData>, "onSubmit">,
/**
* A blank set of initial values matching the schema
* Can be if multiple responses are allowed (e.g. in the List component)
*/
initialValues: UserResponse,
initialValues: SchemaResponse,
}

/**
Expand All @@ -38,7 +38,7 @@ export const useSchema: UseSchema = ({

const formikConfig = {
initialValues: {
userData: getInitialValues(),
schemaData: getInitialValues(),
},
validateOnBlur: false,
validateOnChange: false,
Expand Down
10 changes: 5 additions & 5 deletions editor.planx.uk/src/@planx/components/shared/Schema/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ export interface Schema {
max?: number;
}

export type UserResponse = Record<Field["data"]["fn"], string | any[]>; // string | string[] | Feature[]
export type SchemaResponse = Record<Field["data"]["fn"], string | string[] | any[] >; // string | string[] | Feature[]

/**
* Output data from a form using the useSchema hook
*/
export type UserData = { userData: UserResponse[] };
export type SchemaData = { schemaData: SchemaResponse[] };

/**
* For each field in schema, return a map of Yup validation schema
Expand Down Expand Up @@ -160,14 +160,14 @@ export const generateValidationSchema = (schema: Schema) => {
);

const validationSchema = object().shape({
userData: array().of(fieldvalidationSchema),
schemaData: array().of(fieldvalidationSchema),
});

return validationSchema;
};

export const generateInitialValues = (schema: Schema): UserResponse => {
const initialValues: UserResponse = {};
export const generateInitialValues = (schema: Schema): SchemaResponse => {
const initialValues: SchemaResponse = {};
schema.fields.forEach((field) => {
["checklist", "map"].includes(field.type)
? (initialValues[field.data.fn] = [])
Expand Down

0 comments on commit f0b331a

Please sign in to comment.