import type { FieldValues, Path, UseFormSetValue } from 'react-hook-form'; type Groups = Record>; /** The dotted paths of a section's fields: in the form, with a default, and placed there by `belongs`. */ export const sectionFields = ( formValues: object, formDefaults: object, belongs: (path: string) => boolean ): { path: string; value: unknown }[] => { const values = formValues as Groups; const defaults = formDefaults as Groups; const fields: { path: string; value: unknown }[] = []; for (const [group, entries] of Object.entries(defaults)) { for (const [key, value] of Object.entries(entries)) { const path = `${group}.${key}`; if (belongs(path) && values[group] && key in values[group]) { fields.push({ path, value }); } } } return fields; }; /** * Puts the defaults back into the fields of one section. The form turns * dirty, nothing is saved: the merchant still decides with Save changes. */ export const resetSectionFields = ( setValue: UseFormSetValue, values: object, defaults: object, belongs: (path: string) => boolean ): void => { for (const { path, value } of sectionFields(values, defaults, belongs)) { setValue(path as Path, value as never, { shouldDirty: true, shouldValidate: true, }); } };