87 lines
2.6 KiB
TypeScript
87 lines
2.6 KiB
TypeScript
import type { FormElementDto, VisibilityConditionOperator } from '~~/.api-client'
|
|
import { VisibilityConditionOperator as VCOperator, VisibilityConditionType as VCType } from '~~/.api-client'
|
|
|
|
export function useFormElementVisibility() {
|
|
function evaluateVisibility(allFormElements: FormElementDto[]): Map<string, boolean> {
|
|
const formElementsByRef = buildFormElementsMap(allFormElements)
|
|
const visibilityMap = new Map<string, boolean>()
|
|
|
|
allFormElements.forEach((element) => {
|
|
const isVisible = isElementVisible(element, formElementsByRef, visibilityMap)
|
|
const key = element.id || element.reference
|
|
if (key) {
|
|
visibilityMap.set(key, isVisible)
|
|
}
|
|
})
|
|
|
|
return visibilityMap
|
|
}
|
|
|
|
function buildFormElementsMap(formElements: FormElementDto[]): Map<string, FormElementDto> {
|
|
const map = new Map<string, FormElementDto>()
|
|
formElements.forEach((element) => {
|
|
if (element.reference) {
|
|
map.set(element.reference, element)
|
|
}
|
|
})
|
|
return map
|
|
}
|
|
|
|
function isElementVisible(
|
|
element: FormElementDto,
|
|
formElementsByRef: Map<string, FormElementDto>,
|
|
_visibilityMap: Map<string, boolean>
|
|
): boolean {
|
|
if (!element.visibilityCondition) {
|
|
return true
|
|
}
|
|
|
|
const condition = element.visibilityCondition
|
|
|
|
const sourceElement = formElementsByRef.get(condition.sourceFormElementReference)
|
|
if (!sourceElement) {
|
|
return false
|
|
}
|
|
|
|
const sourceValue = getFormElementValue(sourceElement)
|
|
|
|
const operator = condition.formElementOperator || VCOperator.Equals
|
|
const conditionMet = evaluateCondition(sourceValue, condition.formElementExpectedValue, operator)
|
|
|
|
return condition.formElementConditionType === VCType.Show ? conditionMet : !conditionMet
|
|
}
|
|
|
|
function getFormElementValue(element: FormElementDto): string {
|
|
const selectedOption = element.options.find((option) => option.value === 'true')
|
|
return selectedOption?.label || ''
|
|
}
|
|
|
|
function evaluateCondition(
|
|
actualValue: string,
|
|
expectedValue: string,
|
|
operator: VisibilityConditionOperator
|
|
): boolean {
|
|
let result: boolean
|
|
switch (operator) {
|
|
case VCOperator.Equals:
|
|
result = actualValue.toLowerCase() === expectedValue.toLowerCase()
|
|
return result
|
|
case VCOperator.NotEquals:
|
|
result = actualValue.toLowerCase() !== expectedValue.toLowerCase()
|
|
return result
|
|
case VCOperator.IsEmpty:
|
|
result = actualValue === ''
|
|
return result
|
|
case VCOperator.IsNotEmpty:
|
|
result = actualValue !== ''
|
|
return result
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
return {
|
|
evaluateVisibility
|
|
}
|
|
}
|