Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dependecies for forms #36

Merged
merged 4 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 46 additions & 44 deletions src/@optimizely/forms-react/src/hooks/useElement.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
import { useEffect, useRef, useState } from "react";
import { useForms, useFormsDispatch } from "../context/store";
import { ActionType } from "../context/reducer";
import {
import {
//models
ConditionProperties,
DataElementBlockBaseProperties,
FormElementBase,
ValidatableElementBaseProperties,
ConditionProperties,
DataElementBlockBaseProperties,
FormElementBase,
ValidatableElementBaseProperties,
ValidatorType,
SatisfiedActionType,
FormValidationResult,
//functions
equals,
getDefaultValue,
isNull,
equals,
getDefaultValue,
isNull,
isNullOrEmpty,
isInArray,
//class
FormValidator
FormValidator,
FormSubmission,
FormDependConditions,
} from "@optimizely/forms-sdk";
import { initState } from "../context/initState";

export interface ElementContext{
export interface ElementContext {
value: any,
defaultValue: any,
isDependenciesSatisfied: boolean
validationResults: FormValidationResult[]
}

Expand All @@ -33,16 +34,16 @@ export const useElement = (element: FormElementBase) => {
const dispatch = useFormsDispatch();
const extraAttr = useRef<any>({});
const formValidation = new FormValidator(element);
const formCondition = new FormDependConditions(element)
const defaultValue = getDefaultValue(element);
const failClass = "ValidationFail";

//build element state
const value = (formContext?.formSubmissions ?? [])
.filter(s => equals(s.elementKey, element.key))[0]?.value ?? defaultValue ?? "";
.filter(s => equals(s.elementKey, element.key))[0]?.value ?? defaultValue ?? "";
const validationResults = (formContext?.formValidations ?? [])
.filter(s => equals(s.elementKey, element.key))[0]?.results ?? [];
const isDependenciesSatisfied = (formContext?.formDependencies ?? [])
.filter(s => equals(s.elementKey, element.key))[0]?.isSatisfied ?? false;
.filter(s => equals(s.elementKey, element.key))[0]?.results ?? [];


const [elementContext, setElementContext] = useState<ElementContext>({ value } as ElementContext);

Expand All @@ -51,29 +52,28 @@ export const useElement = (element: FormElementBase) => {
const isRequire = validatableProps.validators?.some(v => v.type === ValidatorType.RequiredValidator);
const validatorClasses = useRef<string>(validatableProps.validators?.reduce((acc, obj) => `${acc} ${obj.model.validationCssClass ?? ""}`, "") ?? "");

if(isRequire){
extraAttr.current = {...extraAttr.current, required: isRequire, "aria-required": isRequire };
if (isRequire) {
extraAttr.current = { ...extraAttr.current, required: isRequire, "aria-required": isRequire };
}

if(!isNullOrEmpty(element.properties.description)){
extraAttr.current = {...extraAttr.current, title: element.properties.description }
if (!isNullOrEmpty(element.properties.description)) {
extraAttr.current = { ...extraAttr.current, title: element.properties.description }
}

const dataProps = element.properties as DataElementBlockBaseProperties;
if(dataProps.forms_ExternalSystemsFieldMappings?.length > 0){
extraAttr.current = {...extraAttr.current, list: `${element.key}_datalist` }
if (dataProps.forms_ExternalSystemsFieldMappings?.length > 0) {
extraAttr.current = { ...extraAttr.current, list: `${element.key}_datalist` }
}

//init element state
useEffect(()=>{
useEffect(() => {
setElementContext({
...elementContext,
value,
defaultValue,
validationResults,
isDependenciesSatisfied
validationResults
} as ElementContext);
},[element.key]);
}, [element.key]);

//reset form
useEffect(()=>{
Expand All @@ -86,7 +86,6 @@ export const useElement = (element: FormElementBase) => {
value,
defaultValue,
validationResults,
isDependenciesSatisfied
} as ElementContext);
//update form state
dispatch({
Expand All @@ -102,26 +101,27 @@ export const useElement = (element: FormElementBase) => {
validationResults
});
}

const dispatchUpdateValue = (value: any) => {
dispatch({
type: ActionType.UpdateValue,
elementKey: element.key,
value
});
}

const handleChange = (e: any) => {
const {name, value, type, checked, files} = e.target;
const { name, value, type, checked, files } = e.target;
let submissionValue = value;
let validationResults = [...elementContext.validationResults];

//get selected value for choice
if(/checkbox|radio/.test(type)){
let arrayValue = isNull(elementContext.value) || /radio/.test(type)
? []
if (/checkbox|radio/.test(type)) {
let arrayValue = isNull(elementContext.value) || /radio/.test(type)
? []
: (elementContext.value as string).split(",");

if(checked) {
if (checked) {
arrayValue.push(value);
}
else {
Expand All @@ -130,8 +130,8 @@ export const useElement = (element: FormElementBase) => {

submissionValue = arrayValue.length > 0 ? arrayValue.join(",") : null;
}
if(/file/.test(type)){

if (/file/.test(type)) {
submissionValue = files;
validationResults = doValidate(files);
dispatchUpdateValidation(validationResults);
Expand All @@ -142,14 +142,14 @@ export const useElement = (element: FormElementBase) => {

//update element state
setElementContext({
...elementContext,
...elementContext,
value: submissionValue,
validationResults
} as ElementContext);
}

const handleBlur = (e: any) => {
const {name} = e.target;
const { name } = e.target;
//call validation from form-sdk
let validationResults = doValidate(elementContext.value);

Expand All @@ -160,7 +160,7 @@ export const useElement = (element: FormElementBase) => {

//update element state
setElementContext({
...elementContext,
...elementContext,
validationResults
} as ElementContext);
}
Expand All @@ -180,30 +180,32 @@ export const useElement = (element: FormElementBase) => {

let isValidationFail = !isNull(validationResults) && validationResults.some(r => !r.valid);
let arrClass = validatorClasses.current.split(" ");
if(isValidationFail){
if(!isInArray(failClass, arrClass)){

if (isValidationFail) {
if (!isInArray(failClass, arrClass)) {
arrClass.push(failClass);
}
}
else {
if(isInArray(failClass, arrClass)){
if (isInArray(failClass, arrClass)) {
arrClass = arrClass.filter(c => c !== failClass);
}
}

validatorClasses.current = arrClass.join(" ");

return validationResults;
}

const checkVisible = (): boolean => {
const conditionProps = (element.properties as unknown) as ConditionProperties;
if(isNull(conditionProps.satisfiedAction)
|| isNull(elementContext.isDependenciesSatisfied)){

if (isNull(conditionProps.satisfiedAction)) {
return true;
}

if(elementContext.isDependenciesSatisfied) {
const checkConditions = formCondition.checkConditions(formContext?.formSubmissions as FormSubmission[]);
if (checkConditions) {
//if isDependenciesSatisfied = true, and if SatisfiedAction = show, then show element. otherwise hide element.
return equals(conditionProps.satisfiedAction, SatisfiedActionType.Show);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { equals, isNull, isNullOrEmpty } from "../helpers";
import { getConcatString } from "../helpers/dependencyHelper";
import { ConditionCombinationType, ConditionFunctionType, ConditionProperties, FormElementBase, FormSubmission } from "../models";

export class FormDependConditions {
epi-qang2 marked this conversation as resolved.
Show resolved Hide resolved
readonly _element: FormElementBase;
constructor(element: FormElementBase) {
this._element = element;
}
checkConditions = (formSubmissions: FormSubmission[]): boolean => {
epi-qang2 marked this conversation as resolved.
Show resolved Hide resolved
if (!isNull(formSubmissions)) {
const conditionProps = (this._element.properties as unknown) as ConditionProperties;

if (isNull(conditionProps?.conditions)) {
return false;
}

let conditionArr = conditionProps.conditions.map(condition => {
const fieldValue = formSubmissions.filter(s => equals(s.elementKey, condition.field))[0]?.value as string
if (!isNull(fieldValue)) {
switch (condition.operator) {
case ConditionFunctionType.Contains:
return this.Contains(fieldValue, condition.fieldValue)
case ConditionFunctionType.NotContains:
return this.NotContains(fieldValue, condition.fieldValue)
case ConditionFunctionType.Equals:
return this.Equals(fieldValue, condition.fieldValue)
case ConditionFunctionType.NotEquals:
return this.NotEquals(fieldValue, condition.fieldValue)
case ConditionFunctionType.MatchRegularExpression:
return this.MatchRegularExpression(fieldValue, condition.fieldValue)
}
}
return false
});

for (let i = 0; i < conditionArr.length; i++) {
const result = conditionArr[i]
if (conditionProps.conditionCombination === ConditionCombinationType.Any && result) {
return true
}
if (conditionProps.conditionCombination === ConditionCombinationType.All && !result) {
return false
}
}

// when reach here, there are two cases
// 1 : Not all conditions are statisfied and ConditionCombination === ConditionCombinations.All
// 2 : None condition is statisfied and ConditionCombination === ConditionCombinations.Any
return !(conditionProps.conditionCombination === ConditionCombinationType.Any);
}
return false
}
/**
* Compare whether user input data equals depend value or not.
*/
Equals(actualValue: Object, dependencyFieldValue: string): boolean {
const _actualValue = !actualValue ? "" : getConcatString(actualValue, ",");
dependencyFieldValue = !dependencyFieldValue ? "" : dependencyFieldValue.toUpperCase();
return _actualValue === dependencyFieldValue;
}
/**
* Compare whether user input data does NOT equal depend value or not.
*/
NotEquals(actualValue: Object, dependencyFieldValue: string): boolean {
const _actualValue = !actualValue ? "" : getConcatString(actualValue, ",");
dependencyFieldValue = !dependencyFieldValue ? "" : dependencyFieldValue.toUpperCase();
return _actualValue !== dependencyFieldValue;
}
/**
* Compare whether user input data contains depend value or not.
*/
Contains(actualValue: Object, dependencyFieldValue: string): boolean {
const _actualValue = isNull(actualValue) ? "" : getConcatString(actualValue, ",").toUpperCase();
dependencyFieldValue = !dependencyFieldValue ? "" : dependencyFieldValue.toUpperCase();
return _actualValue.indexOf(dependencyFieldValue) >= 0;
}
/**
* Compare whether user input data does NOT contain depend value or not.
*/
NotContains(actualValue: Object, dependencyFieldValue: string): boolean {
const _actualValue = !actualValue ? "" : getConcatString(actualValue, ",");
const actualValueNull = isNullOrEmpty(_actualValue)
const dependencyFieldValueNull = isNullOrEmpty(dependencyFieldValue)
return (!actualValueNull && dependencyFieldValueNull) ||
(actualValueNull && !dependencyFieldValueNull) ||
(!actualValueNull && !dependencyFieldValueNull && _actualValue.toUpperCase().indexOf(dependencyFieldValue.toUpperCase()) < 0);
}
/**
* Compare user input with a pattern. Return true if actualValue matchs patternOfExpected
*/
MatchRegularExpression(actualValue: Object, patternOfExpected: string): boolean {
epi-qang2 marked this conversation as resolved.
Show resolved Hide resolved
var regex = new RegExp(patternOfExpected, "igm");
const _actualValue = !actualValue ? "" : getConcatString(actualValue, ",");
return isNullOrEmpty(patternOfExpected) || (!isNullOrEmpty(patternOfExpected) && regex.test(_actualValue));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./formDependConditions"
3 changes: 3 additions & 0 deletions src/@optimizely/forms-sdk/src/helpers/dependencyHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getConcatString(srcObject: any, seperator: string): string {
return (srcObject instanceof Array) ? srcObject.join(seperator) : srcObject as string;
}
1 change: 1 addition & 0 deletions src/@optimizely/forms-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from "./models";
export * from "./form-step";
export * from "./helpers";
export * from "./form-validator";
export * from "./form-depend-conditions";
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export enum ConditionFunctionType {
MatchRegularExpression = "MatchRegularExpression",
NotApplicable = "NotApplicable",
Contains = "Contains",
NotContains = "NotContains",
Equals = "Equals",
NotEquals = "NotEquals",
}
3 changes: 2 additions & 1 deletion src/@optimizely/forms-sdk/src/models/enums/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./ValidatorType";
export * from "./ConditionCombinationType";
export * from "./SatisfiedActionType";
export * from "./SatisfiedActionType";
export * from "./ConditionFunctionType"