Slide 29
Slide 29 text
"use strict";
import React from "react";
import { useOnChange } from "$app/components/useOnChange";
import { CustomFieldRow } from "./row";
const ADD_FIELD = "add-field";
const REMOVE_FIELD = "remove-field";
const CHANGE_NAME = "change-name";
const CHANGE_IS_REQUIRED = "change-is-required";
const RESET = "reset";
const customFieldsReducer = (state, action) => {
switch (action.type) {
case ADD_FIELD: {
return [...state, { name: "", required: false }];
}
case REMOVE_FIELD: {
return state.filter((_, idx) => idx !== action.index);
}
case CHANGE_NAME: {
return state.map((fld, idx) => {
if (idx === action.index) {
return { ...fld, name: action.newName };
}
return fld;
});
}
case CHANGE_IS_REQUIRED: {
return state.map((fld, idx) => {
if (idx === action.index) {
return { ...fld, required: action.newValue };
}
return fld;
});
}
case RESET: {
return action.customFields;
}
default:
return state;
}
};
const CustomFields = ({ customFields, onStateChange }) => {
const [customFieldsState, dispatch] = React.useReducer(
customFieldsReducer,
customFields,
customFields =>
customFields.length === 0 ? [{ name: "", required: false }] : customFields
);
const isInitial = React.useRef(true);
React.useEffect(() => {
onStateChange(
customFieldsState.filter(field => field.name.length > 0),
isInitial.current
);
isInitial.current = false;
}, [customFieldsState]);
useOnChange(() => {
isInitial.current = true;
dispatch({ type: RESET, customFields });
}, [customFields]);
return (
{customFieldsState.map((field, idx) => (
dispatch({ type: CHANGE_NAME, index: idx, newName })
}
onChangeIsRequired={newValue =>
dispatch({ type: CHANGE_IS_REQUIRED, index: idx, newValue })
}
onRemove={() => dispatch({ type: REMOVE_FIELD, index: idx })}
/>
))}
dispatch({ type: ADD_FIELD })}
>
{I18n.t("js.add_custom_field_button_label")}
);
};
export { CustomFields };