UNPKG

@conform-to/react

Version:

Conform view adapter for react

335 lines (322 loc) 14.1 kB
import { objectSpread2 as _objectSpread2 } from '../_virtual/_rollupPluginBabelHelpers.mjs'; import { getPathSegments, getRelativePath, appendPathSegment, deepEqual, getValueAtPath, formatPathSegments, serialize } from '@conform-to/dom/future'; import { generateUniqueKey, merge, getArrayAtPath } from './util.mjs'; function initializeState(resetKey) { return { resetKey: resetKey !== null && resetKey !== void 0 ? resetKey : generateUniqueKey(), listKeys: {}, clientIntendedValue: null, serverIntendedValue: null, serverError: null, clientError: null, touchedFields: [] }; } /** * Updates form state based on action type: * - Client actions: update intended value and client errors * - Server actions: update server errors and clear client errors * - Initialize: set initial intended value */ function updateState(state, action) { var _action$intendedValue, _action$intendedValue2; if (action.intendedValue === null) { return action.ctx.reset(); } var value = (_action$intendedValue = action.intendedValue) !== null && _action$intendedValue !== void 0 ? _action$intendedValue : action.submission.payload; // Apply the form error and intended value from the result first state = action.type === 'client' ? merge(state, { clientIntendedValue: (_action$intendedValue2 = action.intendedValue) !== null && _action$intendedValue2 !== void 0 ? _action$intendedValue2 : state.clientIntendedValue, serverIntendedValue: action.intendedValue ? null : state.serverIntendedValue, // 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.serverIntendedValue, 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, // Keep track of the value that the serverError is based on serverIntendedValue: !deepEqual(state.serverIntendedValue, value) ? value : state.serverIntendedValue }); if (action.type !== 'server' && typeof action.intent !== 'undefined') { var _action$intent, _action$ctx$handlers; // 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.onUpdate) === 'function') { var _handler$validatePayl, _handler$validatePayl2; if ((_handler$validatePayl = (_handler$validatePayl2 = handler.validatePayload) === null || _handler$validatePayl2 === void 0 ? void 0 : _handler$validatePayl2.call(handler, intent.payload)) !== null && _handler$validatePayl !== void 0 ? _handler$validatePayl : true) { return handler.onUpdate(state, _objectSpread2(_objectSpread2({}, action), {}, { intent: { type: intent.type, payload: intent.payload } })); } } } return state; } function getDefaultValue(context, name) { var _ref, _context$state$server; var serialize$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : serialize; var value = getValueAtPath((_ref = (_context$state$server = context.state.serverIntendedValue) !== null && _context$state$server !== void 0 ? _context$state$server : context.state.clientIntendedValue) !== null && _ref !== void 0 ? _ref : context.defaultValue, name); var serializedValue = serialize$1(value); if (typeof serializedValue === 'string') { return serializedValue; } } function getDefaultOptions(context, name) { var _ref2, _context$state$server2; var serialize$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : serialize; var value = getValueAtPath((_ref2 = (_context$state$server2 = context.state.serverIntendedValue) !== null && _context$state$server2 !== void 0 ? _context$state$server2 : context.state.clientIntendedValue) !== null && _ref2 !== void 0 ? _ref2 : context.defaultValue, name); var serializedValue = serialize$1(value); if (Array.isArray(serializedValue) && serializedValue.every(item => typeof item === 'string')) { return serializedValue; } if (typeof serializedValue === 'string') { return [serializedValue]; } } function isDefaultChecked(context, name) { var _ref3, _context$state$server3; var serialize$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : serialize; var value = getValueAtPath((_ref3 = (_context$state$server3 = context.state.serverIntendedValue) !== null && _context$state$server3 !== void 0 ? _context$state$server3 : context.state.clientIntendedValue) !== null && _ref3 !== void 0 ? _ref3 : context.defaultValue, name); var serializedValue = serialize$1(value); return serializedValue === 'on'; } /** * 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 = getPathSegments(name); return state.touchedFields.some(field => field !== name && getRelativePath(field, paths) !== null); } function getDefaultListKey(prefix, initialValue, name) { return getArrayAtPath(initialValue, name).map((_, index) => "".concat(prefix, "-").concat(appendPathSegment(name, index))); } function getListKey(context, name) { var _context$state$listKe, _context$state$listKe2, _ref4, _context$state$server4; 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, (_ref4 = (_context$state$server4 = context.state.serverIntendedValue) !== null && _context$state$server4 !== void 0 ? _context$state$server4 : context.state.clientIntendedValue) !== null && _ref4 !== void 0 ? _ref4 : context.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 && errors.length > 0) { 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 = getPathSegments(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[formatPathSegments(relativePath)] = _error; } } } return result; } 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 = getPathSegments(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; } /** * Gets validation constraint for a field, with fallback to parent array patterns. * e.g. "array[0].key" falls back to "array[].key" if specific constraint not found. */ function getConstraint(context, name) { var _context$constraint; var constraint = (_context$constraint = context.constraint) === null || _context$constraint === void 0 ? void 0 : _context$constraint[name]; if (!constraint) { var path = getPathSegments(name); for (var i = path.length - 1; i >= 0; i--) { var segment = path[i]; // Try searching a less specific path for the constraint // e.g. `array[0].anotherArray[1].key` -> `array[0].anotherArray[].key` -> `array[].anotherArray[].key` if (typeof segment === 'number') { // This overrides the current number segment with an empty string // which will be treated as an empty bracket path[i] = ''; break; } } var alternative = formatPathSegments(path); if (name !== alternative) { constraint = getConstraint(context, alternative); } } return constraint; } function getFormMetadata(context, options) { return { key: context.state.resetKey, id: context.formId, errorId: "".concat(context.formId, "-form-error"), descriptionId: "".concat(context.formId, "-form-description"), 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, _objectSpread2(_objectSpread2({}, options), {}, { name })); }, getFieldset(name) { return getFieldset(context, _objectSpread2(_objectSpread2({}, options), {}, { name })); }, getFieldList(name) { return getFieldList(context, _objectSpread2(_objectSpread2({}, options), {}, { name })); } }; } function getField(context, options) { var id = "".concat(context.formId, "-field-").concat(options.name.replace(/[^a-zA-Z0-9._-]/g, '_')); var constraint = getConstraint(context, options.name); var metadata = { id: 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, get defaultValue() { return getDefaultValue(context, options.name, options.serialize); }, get defaultOptions() { return getDefaultOptions(context, options.name, options.serialize); }, get defaultChecked() { return isDefaultChecked(context, options.name, options.serialize); }, get touched() { return isTouched(context.state, options.name); }, get valid() { return isValid(context.state, options.name); }, get invalid() { return !this.valid; }, get errors() { return getErrors(context.state, options.name); }, get fieldErrors() { return getFieldErrors(context.state, options.name); } }; return Object.assign(metadata, { key: options.key, name: options.name, getFieldset() { return getFieldset(context, options); }, getFieldList() { return getFieldList(context, options); } }); } /** * 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') { return getField(context, _objectSpread2(_objectSpread2({}, options), {}, { name: appendPathSegment(options === null || options === void 0 ? void 0 : options.name, name) })); } 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, _objectSpread2(_objectSpread2({}, options), {}, { name: appendPathSegment(options.name, index), key })); }); } export { getConstraint, getDefaultListKey, getDefaultOptions, getDefaultValue, getErrors, getField, getFieldErrors, getFieldList, getFieldset, getFormMetadata, getListKey, initializeState, isDefaultChecked, isTouched, isValid, updateState };