@conform-to/react
Version:
Conform view adapter for react
415 lines (399 loc) • 17 kB
JavaScript
import { objectSpread2 as _objectSpread2 } from '../_virtual/_rollupPluginBabelHelpers.mjs';
import { parsePath, getRelativePath, appendPath, deepEqual, getPathValue, normalize, formatPath } from '@conform-to/dom/future';
import { when, generateUniqueKey, merge, getPathArray } from './util.mjs';
function initializeState(options) {
var _options$resetKey, _options$defaultValue;
return {
resetKey: (_options$resetKey = options === null || options === void 0 ? void 0 : options.resetKey) !== null && _options$resetKey !== void 0 ? _options$resetKey : generateUniqueKey(),
listKeys: {},
defaultValue: (_options$defaultValue = options === null || options === void 0 ? void 0 : options.defaultValue) !== null && _options$defaultValue !== void 0 ? _options$defaultValue : {},
targetValue: null,
serverValue: null,
serverError: null,
clientError: null,
touchedFields: []
};
}
/**
* Updates form state based on action type:
* - Client actions: update target value and client errors
* - Server actions: update server errors and clear client errors, with optional target value
* - Initialize: set initial server value
*/
function updateState(state, action) {
var _action$targetValue, _action$targetValue2, _action$intent, _action$ctx$handlers;
if (action.reset) {
return action.ctx.reset(action.targetValue);
}
var value = (_action$targetValue = action.targetValue) !== null && _action$targetValue !== void 0 ? _action$targetValue : action.submission.payload;
// Apply the form error and target value from the result first
state = action.type === 'client' ? merge(state, {
targetValue: (_action$targetValue2 = action.targetValue) !== null && _action$targetValue2 !== void 0 ? _action$targetValue2 : state.targetValue,
serverValue: action.targetValue ? null : state.serverValue,
// Update client error only if the error is different from the previous one to minimize unnecessary re-renders
clientError: typeof action.error !== 'undefined' && !deepEqual(state.clientError, action.error) ? action.error : state.clientError,
// Reset server error if form value is changed
serverError: typeof action.error !== 'undefined' && !deepEqual(state.serverValue, value) ? null : state.serverError
}) : merge(state, {
// Clear client error to avoid showing stale errors
clientError: null,
// Update server error if the error is defined.
// There is no need to check if the error is different as we are updating other states as well
serverError: typeof action.error !== 'undefined' ? action.error : state.serverError,
listKeys: action.type === 'server' && action.targetValue ? pruneListKeys(state.listKeys, action.targetValue) : state.listKeys,
targetValue: action.type === 'server' && action.targetValue ? action.targetValue : state.targetValue,
// Keep track of the value that the serverError is based on
serverValue: !deepEqual(state.serverValue, value) ? value : state.serverValue
});
// Validate the whole form if no intent is provided (default submission)
var intent = (_action$intent = action.intent) !== null && _action$intent !== void 0 ? _action$intent : {
type: 'validate'
};
var handler = (_action$ctx$handlers = action.ctx.handlers) === null || _action$ctx$handlers === void 0 ? void 0 : _action$ctx$handlers[intent.type];
if (typeof (handler === null || handler === void 0 ? void 0 : handler.update) === 'function') {
var _handler$validate, _handler$validate2;
if ((_handler$validate = (_handler$validate2 = handler.validate) === null || _handler$validate2 === void 0 ? void 0 : _handler$validate2.call(handler, intent.payload)) !== null && _handler$validate !== void 0 ? _handler$validate : true) {
return handler.update(state, _objectSpread2(_objectSpread2({}, action), {}, {
ctx: {
reset: action.ctx.reset,
cancelled: action.ctx.cancelled
},
intent: {
type: intent.type,
payload: intent.payload
}
}));
}
}
return state;
}
/**
* Removes list keys where array length has changed to force regeneration.
* Minimizes UI state loss by only invalidating keys when necessary.
*/
function pruneListKeys(listKeys, targetValue) {
var result = listKeys;
for (var [name, keys] of Object.entries(listKeys)) {
var list = getPathArray(targetValue, name);
// Reset list keys only if the length has changed
// to minimize potential UI state loss due to key changes
if (keys.length !== list.length) {
// Create a shallow copy to avoid mutating the original object
if (result === listKeys) {
result = _objectSpread2({}, result);
}
// Remove the list key to force regeneration
delete result[name];
}
}
return result;
}
function getDefaultPayload(context, name) {
var _ref, _context$state$server;
var value = getPathValue((_ref = (_context$state$server = context.state.serverValue) !== null && _context$state$server !== void 0 ? _context$state$server : context.state.targetValue) !== null && _ref !== void 0 ? _ref : context.state.defaultValue, name);
if (value === null) {
return null;
}
return normalize(value, context.serialize, name);
}
function getDefaultValue(context, name) {
var _ref2, _context$state$server2;
var value = getPathValue((_ref2 = (_context$state$server2 = context.state.serverValue) !== null && _context$state$server2 !== void 0 ? _context$state$server2 : context.state.targetValue) !== null && _ref2 !== void 0 ? _ref2 : context.state.defaultValue, name);
var serializedValue = context.serialize(value, {
name
});
if (typeof serializedValue === 'string') {
return serializedValue;
}
return '';
}
function getDefaultOptions(context, name) {
var _ref3, _context$state$server3;
var value = getPathValue((_ref3 = (_context$state$server3 = context.state.serverValue) !== null && _context$state$server3 !== void 0 ? _context$state$server3 : context.state.targetValue) !== null && _ref3 !== void 0 ? _ref3 : context.state.defaultValue, name);
var serializedValue = context.serialize(value, {
name
});
if (Array.isArray(serializedValue) && serializedValue.every(item => typeof item === 'string')) {
return serializedValue;
}
if (typeof serializedValue === 'string') {
return [serializedValue];
}
return [];
}
function isDefaultChecked(context, name) {
var _ref4, _context$state$server4;
var value = getPathValue((_ref4 = (_context$state$server4 = context.state.serverValue) !== null && _context$state$server4 !== void 0 ? _context$state$server4 : context.state.targetValue) !== null && _ref4 !== void 0 ? _ref4 : context.state.defaultValue, name);
var serializedValue = context.serialize(value, {
name
});
if (typeof serializedValue === 'string') {
return serializedValue === context.serialize(true, {
name
});
}
return false;
}
/**
* Determine if the field is touched
*
* This checks if the field is in the list of touched fields,
* or if there is any child field that is touched, i.e. form / fieldset
*/
function isTouched(state) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (state.touchedFields.includes(name)) {
return true;
}
var paths = parsePath(name);
return state.touchedFields.some(field => field !== name && getRelativePath(field, paths) !== null);
}
function getDefaultListKey(prefix, initialValue, name) {
return getPathArray(initialValue, name).map((_, index) => "".concat(prefix, "-").concat(appendPath(name, index)));
}
function getListKey(context, name) {
var _context$state$listKe, _context$state$listKe2, _ref5, _context$state$server5;
return (_context$state$listKe = (_context$state$listKe2 = context.state.listKeys) === null || _context$state$listKe2 === void 0 ? void 0 : _context$state$listKe2[name]) !== null && _context$state$listKe !== void 0 ? _context$state$listKe : getDefaultListKey(context.state.resetKey, (_ref5 = (_context$state$server5 = context.state.serverValue) !== null && _context$state$server5 !== void 0 ? _context$state$server5 : context.state.targetValue) !== null && _ref5 !== void 0 ? _ref5 : context.state.defaultValue, name);
}
function getErrors(state, name) {
var _state$serverError;
var error = (_state$serverError = state.serverError) !== null && _state$serverError !== void 0 ? _state$serverError : state.clientError;
if (!error || !isTouched(state, name)) {
return;
}
var errors = name ? error.fieldErrors[name] : error.formErrors;
if (errors != null) {
return errors;
}
}
function getFieldErrors(state, name) {
var _state$serverError2;
var result = {};
var error = (_state$serverError2 = state.serverError) !== null && _state$serverError2 !== void 0 ? _state$serverError2 : state.clientError;
if (error) {
var basePath = parsePath(name);
for (var field of Object.keys(error.fieldErrors)) {
var relativePath = getRelativePath(field, basePath);
// Only include errors for specified field's children
if (!relativePath || relativePath.length === 0) {
continue;
}
var _error = getErrors(state, field);
if (typeof _error !== 'undefined') {
result[formatPath(relativePath)] = _error;
}
}
}
return result;
}
/**
* Checks if fieldErrors contains any errors at the given name or any child path.
*/
function hasFieldError(error, name) {
var basePath = parsePath(name);
return Object.entries(error.fieldErrors).some(_ref6 => {
var [field, fieldError] = _ref6;
return getRelativePath(field, basePath) !== null && fieldError !== null;
});
}
function isValid(state, name) {
var _state$serverError3;
var error = (_state$serverError3 = state.serverError) !== null && _state$serverError3 !== void 0 ? _state$serverError3 : state.clientError;
// If there is no error, it must be valid
if (!error) {
return true;
}
var basePath = parsePath(name);
for (var field of Object.keys(error.fieldErrors)) {
// When checking a specific field, only check that field and its children
if (name && !getRelativePath(field, basePath)) {
continue;
}
// If the field is not touched, we don't consider its error
var _error2 = getErrors(state, field);
if (_error2) {
return false;
}
}
// Make sure there is no form error when checking the whole form
if (!name) {
return !getErrors(state);
}
return true;
}
function getFormMetadata(context, options) {
var _options$extendFormMe, _options$extendFormMe2;
var metadata = {
key: context.state.resetKey,
id: context.formId,
errorId: "".concat(context.formId, "-form-error"),
descriptionId: "".concat(context.formId, "-form-description"),
defaultValue: context.state.defaultValue,
get errors() {
return getErrors(context.state);
},
get fieldErrors() {
return getFieldErrors(context.state);
},
get touched() {
return isTouched(context.state);
},
get valid() {
return isValid(context.state);
},
get invalid() {
return !this.valid;
},
props: {
id: context.formId,
onSubmit: context.handleSubmit,
onInput: context.handleInput,
onBlur: context.handleBlur,
noValidate: true
},
context,
getField(name) {
return getField(context, {
name,
extendFieldMetadata: options === null || options === void 0 ? void 0 : options.extendFieldMetadata
});
},
getFieldset(name) {
return getFieldset(context, {
name,
extendFieldMetadata: options === null || options === void 0 ? void 0 : options.extendFieldMetadata
});
},
getFieldList(name) {
return getFieldList(context, {
name,
extendFieldMetadata: options === null || options === void 0 ? void 0 : options.extendFieldMetadata
});
}
};
var customMetadata = (_options$extendFormMe = options === null || options === void 0 || (_options$extendFormMe2 = options.extendFormMetadata) === null || _options$extendFormMe2 === void 0 ? void 0 : _options$extendFormMe2.call(options, metadata)) !== null && _options$extendFormMe !== void 0 ? _options$extendFormMe : {};
var descriptors = Object.getOwnPropertyDescriptors(customMetadata);
var extended = Object.create(metadata);
Object.defineProperties(extended, descriptors);
return extended;
}
function getField(context, options) {
var _context$constraint, _extendFieldMetadata;
var {
key,
name,
extendFieldMetadata,
form = getFormMetadata(context, {
extendFieldMetadata
})
} = options;
var id = "".concat(context.formId, "-field-").concat(name.replace(/[^a-zA-Z0-9._-]/g, '_'));
var constraint = (_context$constraint = context.constraint) === null || _context$constraint === void 0 ? void 0 : _context$constraint[name];
var metadata = {
key,
name,
id,
descriptionId: "".concat(id, "-description"),
errorId: "".concat(id, "-error"),
formId: context.formId,
required: constraint === null || constraint === void 0 ? void 0 : constraint.required,
minLength: constraint === null || constraint === void 0 ? void 0 : constraint.minLength,
maxLength: constraint === null || constraint === void 0 ? void 0 : constraint.maxLength,
pattern: constraint === null || constraint === void 0 ? void 0 : constraint.pattern,
min: constraint === null || constraint === void 0 ? void 0 : constraint.min,
max: constraint === null || constraint === void 0 ? void 0 : constraint.max,
step: constraint === null || constraint === void 0 ? void 0 : constraint.step,
multiple: constraint === null || constraint === void 0 ? void 0 : constraint.multiple,
accept: constraint === null || constraint === void 0 ? void 0 : constraint.accept,
get defaultValue() {
return getDefaultValue(context, name);
},
get defaultOptions() {
return getDefaultOptions(context, name);
},
get defaultChecked() {
return isDefaultChecked(context, name);
},
get defaultPayload() {
return getDefaultPayload(context, name);
},
get touched() {
return isTouched(context.state, name);
},
get valid() {
return isValid(context.state, name);
},
get invalid() {
return !this.valid;
},
get errors() {
return getErrors(context.state, name);
},
get fieldErrors() {
return getFieldErrors(context.state, name);
},
get ariaInvalid() {
return !this.valid ? true : undefined;
},
get ariaDescribedBy() {
return !this.valid ? this.errorId : undefined;
},
getFieldset() {
return getFieldset(context, {
name: name,
extendFieldMetadata
});
},
// @ts-expect-error The return type includes CustomFieldMetadata which BaseFieldMetadata
// doesn't account for. This is a type-level limitation; runtime behavior is correct.
getFieldList() {
return getFieldList(context, {
name,
extendFieldMetadata
});
}
};
var customMetadata = (_extendFieldMetadata = extendFieldMetadata === null || extendFieldMetadata === void 0 ? void 0 : extendFieldMetadata(metadata, {
form,
when
})) !== null && _extendFieldMetadata !== void 0 ? _extendFieldMetadata : {};
var descriptors = Object.getOwnPropertyDescriptors(customMetadata);
var extended = Object.create(metadata);
Object.defineProperties(extended, descriptors);
return extended;
}
/**
* Creates a proxy that dynamically generates field objects when properties are accessed.
*/
function getFieldset(context, options) {
return new Proxy({}, {
get(target, name, receiver) {
if (typeof name === 'string') {
var _options$form;
(_options$form = options.form) !== null && _options$form !== void 0 ? _options$form : options.form = getFormMetadata(context, {
extendFieldMetadata: options === null || options === void 0 ? void 0 : options.extendFieldMetadata
});
return getField(context, {
name: appendPath(options === null || options === void 0 ? void 0 : options.name, name),
extendFieldMetadata: options.extendFieldMetadata,
form: options.form
});
}
return Reflect.get(target, name, receiver);
}
});
}
/**
* Creates an array of field objects for list/array inputs
*/
function getFieldList(context, options) {
var keys = getListKey(context, options.name);
return keys.map((key, index) => {
return getField(context, {
name: appendPath(options.name, index),
extendFieldMetadata: options.extendFieldMetadata,
key
});
});
}
export { getDefaultListKey, getDefaultOptions, getDefaultPayload, getDefaultValue, getErrors, getField, getFieldErrors, getFieldList, getFieldset, getFormMetadata, getListKey, hasFieldError, initializeState, isDefaultChecked, isTouched, isValid, pruneListKeys, updateState };