|
1 | 1 | import React from 'react';
|
2 |
| -import { isFunction, isUndefined, isArray, isObject } from 'js-var-type'; |
| 2 | +import { isFunction, isUndefined, isArray, isObject, isEmptyStringLike, isBoolean } from 'js-var-type'; |
3 | 3 | import { getValueByPath } from '../../utils/getters-setters';
|
| 4 | +import { fromDatetimeLocal, toDatetimeLocal } from '../../utils/formatters'; |
4 | 5 |
|
5 | 6 | export const FormContext = React.createContext(null);
|
6 | 7 |
|
@@ -29,6 +30,34 @@ export function validateFormElement({ name, validations = [], formData, elementR
|
29 | 30 | return validationMessage;
|
30 | 31 | }
|
31 | 32 |
|
| 33 | +export function getTargetValue(target) { |
| 34 | + let value = target.type === 'checkbox' ? target.checked : target.value; |
| 35 | + |
| 36 | + if (target.type === 'number') { |
| 37 | + value = target.valueAsNumber; |
| 38 | + if (isNaN(value)) { |
| 39 | + value = undefined; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (target.type === 'datetime-local') { |
| 44 | + value = fromDatetimeLocal(target.value); |
| 45 | + } |
| 46 | + |
| 47 | + if (target.type === 'select-one') { |
| 48 | + if (value && ['{', '['].includes(value[0])) { |
| 49 | + try { |
| 50 | + value = JSON.parse(value); |
| 51 | + } catch (error) { |
| 52 | + // eslint-disable-next-line no-console |
| 53 | + console.error(error); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return value; |
| 59 | +} |
| 60 | + |
32 | 61 | export function handleInputChange(formState, event) {
|
33 | 62 | const target = event.target;
|
34 | 63 | const value = target.type === 'checkbox' ? target.checked : target.value;
|
@@ -85,3 +114,44 @@ export function getSelectedOption(value, options, trackBy) {
|
85 | 114 | export function getOptionsType(options) {
|
86 | 115 | return options.length > 0 ? typeof options[0].value : undefined;
|
87 | 116 | }
|
| 117 | + |
| 118 | +function getEmptyValue(type) { |
| 119 | + switch (type) { |
| 120 | + case 'boolean': |
| 121 | + return false; |
| 122 | + |
| 123 | + case 'array': |
| 124 | + return []; |
| 125 | + |
| 126 | + default: |
| 127 | + return ''; |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +export function encode(value, type) { |
| 132 | + if (isEmptyStringLike(value)) { |
| 133 | + return getEmptyValue(type); |
| 134 | + } |
| 135 | + |
| 136 | + if (type === 'datetime-local') { |
| 137 | + return toDatetimeLocal(value); |
| 138 | + } |
| 139 | + |
| 140 | + if (type === 'number' && isNaN(value)) { |
| 141 | + return; |
| 142 | + } |
| 143 | + |
| 144 | + return value; |
| 145 | +} |
| 146 | + |
| 147 | +export function decode(value, type) { |
| 148 | + if (type === 'number') { |
| 149 | + return parseFloat(value); |
| 150 | + } |
| 151 | + |
| 152 | + if (type === 'boolean') { |
| 153 | + return isBoolean(value) ? value : value === 'true'; |
| 154 | + } |
| 155 | + |
| 156 | + return value; |
| 157 | +} |
0 commit comments