All files / src helpers.js

100% Statements 141/141
100% Branches 81/81
100% Functions 32/32
100% Lines 132/132
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379                    9x                   18x             59x               20x 20x   20x 4x         16x 4x     12x 19x 2x                       23x 11x 12x 1x   11x               98x       98x 12x   98x                   21x 21x 21x 32x   31x         2x   29x 4x 4x     25x 14x 4x 4x     10x 1x 1x     20x   21x 12x   9x     21x       7x       7x 13x 12x     7x 7x 13x 2x             7x   7x               8x 8x 8x       6x       3x 3x   3x 3x     3x       6x 6x   6x 3x         6x 15x   4x 4x   11x 11x 8x     6x             38x 38x       89x     89x   6x     6x   3x       4x   4x 4x       89x         89x 30x     80x 80x   38x       4x 4x 4x 4x 4x 8x 8x 8x 8x   4x 4x                           86x 86x 86x 172x 89x                       47x                 86x 86x   86x 82x     86x                   86x 86x 80x 80x     6x 6x         6x 5x   1x     4x       4x                   87x   87x 1x     86x         86x       86x   39x   86x           2x 2x    
// @ts-check
/* eslint-disable no-param-reassign */
// This file contain any `private` method for the Veasy
 
import is from 'is_js';
import handlerMatcher, {
  RuleWhichNeedsArray,
  RuleWhichNeedsBoolean
} from './ruleHandlers/matchers';
 
export const FieldStatus = {
  ok: 'ok',
  error: 'error',
  normal: 'normal'
};
 
/**
 * Return error message for checking the parameters of the constructor.
 */
export function getConstructorErrorMessage(paramName, value) {
  return `[Veasy - ${paramName}] Expect: non empty object. Actual: ${value}`;
}
 
/**
 * Check if an object is a non-empty object
 */
function isNonEmptyObject(obj) {
  return is.object(obj) && is.not.empty(obj);
}
 
/**
 * Type check for 2 parameters of the constructor
 *
 */
export function typeCheck(component, schema) {
  const isComponentValid = isNonEmptyObject(component);
  const isSchemaValid = isNonEmptyObject(schema);
 
  if (!isComponentValid) {
    throw new Error(
      getConstructorErrorMessage('Parameter component', component)
    );
  }
 
  if (!isSchemaValid) {
    throw new Error(getConstructorErrorMessage('Parameter schema', schema));
  }
 
  Object.keys(schema).forEach(prop => {
    if (!isNonEmptyObject(schema[prop])) {
      throw new Error(
        getConstructorErrorMessage(`schema.${prop}`, schema[prop])
      );
    }
  });
}
 
/**
 * Create initial value for a field if no default is provided.
 *
 */
export function createInitialValue(schema) {
  if (is.propertyDefined(schema, 'default')) {
    return schema.default;
  } else if (is.propertyDefined(schema, 'min')) {
    return schema.min;
  }
  return '';
}
 
/**
 * Create a new state for a field in componentState.formStatus.fields.field
 *
 */
export function createNewFieldState(needValue = false, fieldSchema) {
  const result = {
    status: FieldStatus.normal,
    errorText: ''
  };
  if (needValue) {
    result.value = createInitialValue(fieldSchema);
  }
  return result;
}
 
/**
 * If all fields in the state has their status !== error
 * Then we will set the isFormOK to true then return the state.
 * Just mutate the value since it's already a new state object
 *
 */
export function checkIsFormOK(schema, componentState) {
  const properties = Object.keys(schema);
  let isError = false;
  properties.some(prop => {
    if (prop === 'collectValues') return false;
 
    if (
      is.propertyDefined(schema[prop], 'isRequired') &&
      schema[prop].isRequired === false &&
      componentState[prop].status !== FieldStatus.error
    )
      return false;
 
    if (componentState[prop].status === FieldStatus.error) {
      isError = true;
      return true;
    }
 
    if (componentState[prop].status === FieldStatus.normal) {
      if (is.not.propertyDefined(schema[prop], 'default')) {
        isError = true;
        return true;
      }        
 
      if (schema[prop].default !== componentState[prop].value) {
        isError = true;
        return true;
      }
    }
    return false;
  });
  if (!isError) {
    componentState.isFormOK = true;
  } else {
    componentState.isFormOK = false;
  }
 
  return componentState;
}
 
export function createInitialState(schema, userState) {
  const initialState = {
    ...userState
  };
 
  Object.keys(schema).forEach(prop => {
    if (prop === 'collectValues') return;
    initialState[prop] = createNewFieldState(true, schema[prop]);
  });
 
  const schemaItems = Object.keys(schema);
  schemaItems.forEach(name => {
    if (is.propertyDefined(userState, name)) {
      initialState[name] = {
        ...initialState[name],
        ...userState[name]
      };
    }
  });
 
  checkIsFormOK(schema, initialState);
 
  return initialState;
}
 
/**
 * Check if we should change the state or not.
 *
 */
export function shouldChange(oldState, newState) {
  const isErrorDifferent = oldState.status !== newState.status;
  const isValueDifferent = oldState.value !== newState.value;
  return isErrorDifferent || isValueDifferent;
}
 
function getNestedValue(key, obj) {
  return key.split('.').reduce((result1, key1) => result1[key1], obj);
}
 
function getCollectValues(collectSchema, state) {
  const fieldsToCollect = Object.keys(collectSchema);
  const result = {};
 
  fieldsToCollect.forEach(fieldName => {
    result[fieldName] = getNestedValue(collectSchema[fieldName], state);
  });
 
  return result;
}
 
export function getFieldsValue(schema, state, mustOK = true) {
  const fieldNames = Object.keys(schema);
  let result = {};
 
  if (is.propertyDefined(schema, 'collectValues')) {
    result = {
      ...getCollectValues(schema.collectValues, state)
    };
  }
 
  fieldNames.forEach(name => {
    if (is.not.propertyDefined(state, name)) {
      // eslint-disable-next-line no-console
      console.warn(`[veasy]: No ${name} found in state.`);
      return;
    }
    const fieldState = state[name];
    if (mustOK && fieldState.status !== FieldStatus.ok) return;
    result[name] = fieldState.value;
  });
 
  return result;
}
 
/**
 * throw an error with defined text, usually calls by ruleRunner().
 */
export function throwError(value, errorText) {
  const error = { value, errorText, status: FieldStatus.error };
  throw error;
}
 
function extractUserDefinedMsg(handlerName, schema) {
  const result = { schema, userErrorText: '' };
 
  // No user message, just return
  if (is.not.array(schema[handlerName])) return result;
 
  const currentSchema = schema[handlerName];
 
  // Handle the case where the value of rule is array
  if (RuleWhichNeedsArray.includes(handlerName)) {
    // No user message, just return
    if (is.not.array(currentSchema[0])) return result;
  }
 
  // The most common case: [0] is rule and [1] is errText
  result.schema = { [handlerName]: currentSchema[0] };
  // eslint-disable-next-line prefer-destructuring
  result.userErrorText = currentSchema[1];
  return result;
}
 
function ruleRunner(ruleName, ruleHandler, fieldName, value, pschema) {
  const { schema, userErrorText } = extractUserDefinedMsg(
    ruleName,
    pschema
  );
 
  if (RuleWhichNeedsBoolean.includes(ruleName)) {
    if (schema[ruleName] === false) return;
  }
 
  const result = ruleHandler(fieldName, value, schema);
  if (result.isValid) return;
 
  throwError(value, userErrorText || result.errorText);
}
 
export function resetForm(schema, state) {
  const newSchema = { ...schema };
  delete newSchema.collectValues;
  const newState = { ...state };
  const fieldNames = Object.keys(newSchema);
  fieldNames.forEach(name => {
    const newField = newState[name];
    newField.status = FieldStatus.normal;
    newField.errorText = '';
    newField.value = createInitialValue(schema[name]);
  });
  newState.isFormOK = false;
  return newState;
}
 
/**
 * It will run through the user's settings for a field,
 * and try matching to the matchers.js,
 * if according rule could be found,
 * it will then execute the according rule function.
 * For instance:
 * if user sets a `minLength` for a field,
 * This function will invoke the minLength()
 *
 */
function runMatchers(matcher, fieldState, fieldSchema) {
  const fieldName = Object.keys(fieldSchema)[0];
  const schema = fieldSchema[fieldName];
  Object.keys(schema).forEach(ruleInSchema => {
    if (is.propertyDefined(matcher, ruleInSchema)) {
      ruleRunner(
        ruleInSchema, 
        matcher[ruleInSchema], 
        fieldName, 
        fieldState.value, 
        schema
      );
    }
    // TODO: Do something when the rule is not match
    // else if (ruleInSchema !== 'default') {
    // }
  });
  return fieldState;
}
 
/**
 * This is the main entry for all validator.
 * It will generate the initial state to start with
 *
 */
export function rulesRunner(value, schema) {
  const fieldState = createNewFieldState();
  fieldState.value = value;
 
  if (is.existy(value) && is.not.empty(value)) {
    fieldState.status = FieldStatus.ok;
  }
 
  return runMatchers(handlerMatcher, fieldState, schema);
}
 
function updateWhenNeeded(
  newFieldState,
  propName,
  update,
  schema,
  formState = undefined
) {
  const fieldState = { [propName]: newFieldState };
  if (formState === undefined) {
    update(fieldState);
    return;
  }
 
  const oldFieldState = formState[propName];
  const newFieldState1 = {
    ...oldFieldState,
    ...fieldState[propName]
  };
 
  if (is.existy(oldFieldState) && is.existy(newFieldState)) {
    if (!shouldChange(oldFieldState, newFieldState)) return;
  } else {
    return;
  }
 
  const finalState = {
    ...formState,
    [propName]: { ...newFieldState1 }
  };
  update(checkIsFormOK(schema, finalState));
}
 
export function startValidating(
  target,
  schema,
  update,
  allState,
  targetName = undefined
) {
  const propName = targetName || target.name;
 
  if (is.not.existy(propName)) {
    throw new Error('target.name and targetName are both non-existy');
  }
 
  const fieldInfo = {
    value: target.value,
    schema: { [propName]: schema[propName] }
  };
 
  return (
    Promise.resolve(fieldInfo)
      // eslint-disable-next-line arrow-body-style
      .then(info => {
        return rulesRunner(info.value, info.schema);
      })
      .catch(errorState => errorState)
      .then(newFieldState =>
        updateWhenNeeded(newFieldState, propName, update, schema, allState)
      )
  );
}
 
export function validate(e, schema, allState, update, targetName) {
  e.persist();
  startValidating(e.target, schema, update, allState, targetName);
}