@modular-forms/qwik
Version:
The modular and type-safe form library for Qwik
57 lines (56 loc) • 2.45 kB
JavaScript
import { getInitialFieldArrayStore } from './getInitialFieldArrayStore';
import { getInitialFieldStore } from './getInitialFieldStore';
import { getPathValue } from './getPathValue';
import { getUniqueId } from './getUniqueId';
/**
* Returns a tuple with the initial stores of the fields and field arrays.
*
* @param loader The form loader.
* @param action The form action.
*
* @returns The initial stores tuple.
*/
export function getInitialStores({ loader, action, fieldArrays, }) {
function getActionValue(name) {
return action?.value?.values && getPathValue(name, action.value.values);
}
// Create function to generate array items
const generateItems = () => getUniqueId();
// Create function to get error of field
const getActionError = (name) => action?.value?.errors[name] || '';
// Create recursive function to create initial stores
const createInitialStores = (stores, data, prevPath) => Object.entries(data).reduce((stores, [path, value]) => {
// Create new compound path
const compoundPath = prevPath ? `${prevPath}.${path}` : path;
// If it is a field array, set initial store
if (fieldArrays?.includes(compoundPath.replace(/.\d+./g, '.$.'))) {
const initialItems = value.map(generateItems);
stores[1][compoundPath] =
getInitialFieldArrayStore(compoundPath, {
initialItems,
items: getActionValue(compoundPath)?.map(generateItems) || [...initialItems],
error: getActionError(compoundPath),
});
// Otherwise, if it is a field, set initial store
}
else if (!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
value instanceof Date) {
stores[0][compoundPath] =
getInitialFieldStore(compoundPath, {
initialValue: value,
value: getActionValue(compoundPath) ?? value,
error: getActionError(compoundPath),
});
}
// If it is an object or array, add nested stores
if (value && typeof value === 'object') {
createInitialStores(stores, value, compoundPath);
}
// Return modified stores
return stores;
}, stores);
// Create and return initial stores
return createInitialStores([{}, {}], loader.value);
}