@pega/cosmos-react-condition-builder 4.0.0-dev.14.0 → 4.0.0-dev.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -149,7 +149,7 @@ const AtomicCondition = forwardRef(({ condition, fields, indicateErrors, validCo
149
149
  _jsx(StyledAtomicCondition, { ...restProps, name: lhsMode === 'label' ? lhsLabel : undefined, "aria-label": lhsMode === 'hidden' ? lhsLabel : undefined, children: _jsxs(Grid, { sm: {
150
150
  container: {
151
151
  cols: itemDirection === 'column'
152
- ? '1fr'
152
+ ? 'minmax(0, 1fr)'
153
153
  : `repeat(${lhsMode !== 'input' ? 2 : 3}, minmax(0,1fr))`
154
154
  }
155
155
  }, container: {
@@ -1 +1 @@
1
- {"version":3,"file":"AtomicCondition.js","sourceRoot":"","sources":["../../../src/components/ConditionBuilder/AtomicCondition.tsx"],"names":[],"mappings":";AAAA,OAAO,EAGL,UAAU,EAEV,MAAM,EACN,QAAQ,EAER,mBAAmB,EACpB,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,IAAI,EACJ,MAAM,EACN,MAAM,EACN,OAAO,EACP,OAAO,EAIP,kBAAkB,EAClB,cAAc,EACd,qBAAqB,EACtB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC,OAAO,aAAa,MAAM,6BAA6B,CAAC;AACxD,OAAO,WAAW,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,oBAAoB,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE,4CAA4C;AAC5C,SAAS,YAAY,CAAC,SAAiB,EAAE,MAAe;IACtD,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACjD,OAAO,aAAa,IAAI,OAAO,CAAC,aAAa,EAAE,MAAM,CAA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AK,CAAC,GAAG,CAAC,KAAK,KAAK,EAAE;wBACtC,CAAC,CAAC,CAAC,CAAC,iDAAiD,CAAC;wBACtD,CAAC,CAAC,SAAS,GAEf,CACH,EAGD,KAAC,MAAM,IACL,KAAK,EAAE,KAAK,CAAC,UAAU,EACvB,QAAQ,EAAE,sBAAsB,EAChC,IAAI,EAAC,YAAY,EACjB,KAAK,EAAE,CAAC,CAAC,oCAAoC,CAAC,YAE7C,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAC/B,KAAC,MAAM,IAAiB,KAAK,EAAE,MAAM,CAAC,EAAE,YACrC,MAAM,CAAC,KAAK,IADF,MAAM,CAAC,EAAE,CAEb,CACV,CAAC,GACK,EAGT,KAAC,WAAW,IACV,GAAG,EAAE,KAAK,CAAC,GAAG,EACd,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,GAAG,EAAE,KAAK,CAAC,GAAG,EACd,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,eAAe,EACzB,cAAc,EAAE,cAAc,EAC9B,aAAa,EAAE,aAAa,EAC5B,aAAa,EAAE,aAAa,EAC5B,aAAa,EAAE,aAAa,IAAI,KAAK,EACrC,MAAM,EAAE,SAAS,GACjB,IACG,GACe,CACzB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,eAAe,CAAC","sourcesContent":["import {\n FunctionComponent,\n ChangeEvent,\n forwardRef,\n Ref,\n useRef,\n useState,\n PropsWithoutRef,\n useImperativeHandle\n} from 'react';\n\nimport {\n Grid,\n Select,\n Option,\n useI18n,\n hasProp,\n BaseProps,\n HandleValue,\n ForwardProps,\n useConsolidatedRef,\n useFocusWithin,\n useAfterInitialEffect\n} from '@pega/cosmos-react-core';\n\nimport { getItem } from './core/utils';\nimport { LeafCondition, Field, DateFunctionsByType } from './ConditionBuilder.types';\nimport FieldSelector from './RhsControls/FieldSelector';\nimport RhsControls, { getDefaultRhs, isValidRhs } from './RhsControls';\nimport getComparatorOptions from './core/comparators';\nimport { Comparator, ComparatorsByType, FieldType, RHSType } from './core/types';\nimport { StyledAtomicCondition } from './ConditionBuilder.styles';\n\n// Returns field-type for a given field-name\nfunction getFieldType(fieldName: string, fields: Field[]): FieldType | undefined {\n const matchingField = getItem(fields, fieldName);\n return matchingField && hasProp(matchingField, 'type') ? matchingField.type : undefined;\n}\n\n// Returns display label for a given field-name\nfunction getFieldLabel(fieldName: string, fields: Field[]): string | undefined {\n const matchingField = getItem(fields, fieldName);\n return matchingField?.primary;\n}\n\n/**\n * Upon changing the comparator, checks if the old RHS is valid for the new comparator\n * NOTE: This works under the assumption that the LHS doesn't change\n */\nfunction isRhsValidForComparator(rhs: LeafCondition['rhs'], comparator: Comparator): boolean {\n if (rhs === undefined) {\n return ['IS_NULL', 'IS_NOT_NULL', 'IS_TRUE', 'IS_FALSE'].includes(comparator);\n }\n if (hasProp(rhs, 'values')) {\n return ['IN', 'NOT_IN'].includes(comparator);\n }\n\n if (hasProp(rhs, 'parameterId')) {\n return ['EQ', 'NEQ'].includes(comparator);\n }\n\n if (hasProp(rhs, 'start')) {\n return ['BTW', 'NOT_BTW'].includes(comparator);\n }\n\n // `rhs.field` and `rhs.value` cases\n return [\n 'EQ',\n 'NEQ',\n 'GT',\n 'GTE',\n 'LT',\n 'LTE',\n 'STARTS_WITH',\n 'NOT_STARTS_WITH',\n 'ENDS_WITH',\n 'NOT_ENDS_WITH',\n 'CONTAINS',\n 'NOT_CONTAINS'\n ].includes(comparator);\n}\n\n/** Determines the default condition object for a given LHS value */\nexport function getInitConditionForLhs(\n lhs: LeafCondition['lhs'],\n fields: Field[],\n validRhsTypes: Set<RHSType>,\n validComparators?: ComparatorsByType[],\n dateFunctions?: DateFunctionsByType\n): LeafCondition {\n let comparator: Comparator;\n let rhs: LeafCondition['rhs'];\n if (lhs.field === '') {\n // If the empty option is selected, reset the comparator and rhs to their default values\n comparator = 'IS_NOT_NULL';\n rhs = undefined;\n } else {\n const newFieldType = getFieldType(lhs.field, fields) as FieldType;\n comparator = getComparatorOptions(newFieldType, validComparators)[0].id; // Find the applicable comparators and select the first among them\n rhs = getDefaultRhs(newFieldType, comparator, validRhsTypes, dateFunctions);\n }\n\n return { lhs, comparator, rhs };\n}\n\n/**\n * Verifies if all the values in the condition are valid.\n * NOTES:\n * - This is intended to be used only on conditions emitted by the components in this package.\n * - If a condition is manually constructed outside these components, this utility could miss some malformed conditions.\n */\nexport function isValidCondition(\n condition: LeafCondition,\n fields: Field[],\n trimValues: boolean = false\n): boolean {\n // If no field is yet selected on the LHS\n if (condition.lhs.field === '') {\n return false;\n }\n // If a field is present on the LHS, check if the RHS is valid\n // No need to check the comparator since the comparator is always assigned a valid value\n const fieldType = getFieldType(condition.lhs.field, fields);\n return isValidRhs(condition.rhs, condition.lhs, fields, fieldType, trimValues);\n}\n\n/** Type definition for the input props of AtomicCondition */\nexport interface AtomicConditionProps extends BaseProps {\n /** Condition to use in the component */\n condition: LeafCondition;\n\n /** Metadata (data-model) for the Fields to use in the Condition */\n fields: Field[];\n\n /** Used to enable inline error indicators on invalid inputs */\n indicateErrors: boolean;\n\n /** (Optional) Lookup used to limit the Comparators allowed in the Condition. */\n validComparators?: ComparatorsByType[];\n\n /** Callback for any modifications to the Condition */\n onChange?: (newCondition: LeafCondition, status?: 'error') => void;\n\n /** Callback fired when the condition changes. */\n onBlur?: (newCondition?: LeafCondition) => void;\n\n /** Item flow direction. Defaults to 'row' */\n itemDirection?: 'row' | 'column';\n\n /**\n * Allows presenting the LHS as a readonly text, input or hidden. Defaults presenting as 'input'.\n * NOTE: Make sure that a valid LHS is passed in the 'condition'\n */\n lhsMode?: 'input' | 'label' | 'hidden';\n\n /** Restricts RHS values to only specified types of values.\n * DEFAULT: Set(['LITERAL', 'FIELD']).\n * WARNING: There are LHS/Comparator pairings that require specific RHS types. Please be mindful of\n * these incompatibilities when limiting RHS value types using this prop. We do not support\n * limiting RHS field types to incompatible types and it will result in a validation error\n * if you do so. The pairings referred to here are as follows:\n * - BOOLEAN LHS Fields coupled with \"EQ\" or \"NEQ\" comparators, will always yield a Field RHS\n * - Any LHS Fields coupled with \"IN\" or \"NOT_IN\" comparators, will always yield a Literal RHS (Comma separated list)\n * If you would like to limit RHS value types and avoid these incompatibilities, you will need to exclude these\n * comparators using the validComparators prop.\n */\n validRhsTypes?: Set<RHSType>;\n\n /** (Optional) When enabling 'DATE_FUNCTION's via `validRhsTypes`, pass this to specify which all date functions are applicable per field type */\n dateFunctions?: DateFunctionsByType;\n\n /** Ref forwarded to the wrapping element. */\n ref?: Ref<HTMLDivElement>;\n /** Imperative handle */\n handle?: Ref<HandleValue>;\n}\n\n/** A controlled component for Atomic Conditions */\nconst AtomicCondition: FunctionComponent<AtomicConditionProps & ForwardProps> = forwardRef(\n (\n {\n condition,\n fields,\n indicateErrors,\n validComparators,\n onChange,\n onBlur,\n itemDirection,\n lhsMode = 'input',\n validRhsTypes = new Set<RHSType>(['LITERAL', 'FIELD']),\n dateFunctions,\n handle,\n ...restProps\n }: PropsWithoutRef<AtomicConditionProps>,\n ref: AtomicConditionProps['ref']\n ) => {\n const t = useI18n();\n\n // stores condition form state\n const [state, setState] = useState<LeafCondition>(condition);\n // ref needed to handle use case of onChange and onBlur being triggered at the same time\n // state is not updated by the time blur is invoked, ref is always set to newest value\n const newCondition = useRef(condition);\n\n const fieldType = getFieldType(condition.lhs.field, fields); // Can be `undefined` if no match or if no previous field\n const comparatorOptions = fieldType\n ? getComparatorOptions(fieldType, validComparators)\n : [{ id: '', label: t('condition_builder_select_placeholder') }];\n\n useAfterInitialEffect(() => {\n setState(condition);\n }, [condition]);\n\n const onFocusChange = (focused: boolean) => {\n if (!focused) {\n // newCondition is returned, as it stores newest value\n onBlur?.(\n newCondition.current && isValidCondition(newCondition.current, fields, true)\n ? newCondition.current\n : undefined\n );\n }\n };\n\n const containerRef = useConsolidatedRef(ref);\n useFocusWithin([containerRef], onFocusChange);\n\n // Handle condition update\n const handleConditionChange = (updatedCondition: LeafCondition, status?: 'error') => {\n newCondition.current = updatedCondition;\n // new condition is returned with status to allow recognizing errors and avoiding clearing wrong values from input\n onChange?.(updatedCondition, status);\n };\n\n // Handle change in the field-selector\n const handleFieldChange = (id: string) => {\n const lhs = { field: id };\n const initCondition = getInitConditionForLhs(\n lhs,\n fields,\n validRhsTypes,\n validComparators,\n dateFunctions\n ); // Determine comparator and rhs for the new lhs\n handleConditionChange(initCondition);\n };\n\n // Handle change in the comparator\n const handleComparatorChange = (e: ChangeEvent<HTMLSelectElement>) => {\n if (e.target.value === '') {\n return; // The option is shown only when an lhs is not yet selected. Ignore this selection for those cases\n }\n const comparator = e.target.value as Comparator;\n const rhs = isRhsValidForComparator(condition.rhs, comparator)\n ? condition.rhs\n : getDefaultRhs(fieldType as FieldType, comparator, validRhsTypes, dateFunctions);\n\n handleConditionChange({ ...condition, comparator, rhs });\n };\n\n // Handle change in the RHS\n const handleRHSChange = (rhs: LeafCondition['rhs'], status?: 'error') => {\n handleConditionChange({ ...condition, rhs }, status);\n };\n\n const rhsHandle = useRef<HandleValue>(null);\n\n const clear = () => {\n rhsHandle.current?.clear();\n if (newCondition.current) {\n handleConditionChange(\n getInitConditionForLhs(state.lhs, fields, validRhsTypes, validComparators, dateFunctions)\n );\n }\n };\n\n useImperativeHandle(\n handle,\n () => ({\n clear\n }),\n [clear]\n );\n\n const lhsLabel = getFieldLabel(condition.lhs.field, fields);\n\n return (\n // Using minmax() to get equal widths: https://stackoverflow.com/a/61240964/4247448\n <StyledAtomicCondition\n {...restProps}\n name={lhsMode === 'label' ? lhsLabel : undefined}\n aria-label={lhsMode === 'hidden' ? lhsLabel : undefined}\n >\n <Grid\n sm={{\n container: {\n cols:\n itemDirection === 'column'\n ? '1fr'\n : `repeat(${lhsMode !== 'input' ? 2 : 3}, minmax(0,1fr))`\n }\n }}\n container={{\n justifyItems: 'stretch',\n colGap: 0.5,\n rowGap: 0.5\n }}\n ref={containerRef}\n >\n {/* LHS selector */}\n {lhsMode === 'input' && (\n <FieldSelector\n value={state.lhs.field}\n onChange={handleFieldChange}\n fields={fields}\n status={indicateErrors && state.lhs.field === '' ? 'error' : undefined}\n info={\n indicateErrors && state.lhs.field === ''\n ? t('condition_builder_condition_select_info_default')\n : undefined\n }\n />\n )}\n\n {/* Comparator selector */}\n <Select\n value={state.comparator}\n onChange={handleComparatorChange}\n name='comparator'\n label={t('condition_builder_comparator_label')}\n >\n {comparatorOptions.map(option => (\n <Option key={option.id} value={option.id}>\n {option.label}\n </Option>\n ))}\n </Select>\n\n {/* RHS controls */}\n <RhsControls\n lhs={state.lhs}\n comparator={state.comparator}\n rhs={state.rhs}\n fields={fields}\n onChange={handleRHSChange}\n indicateErrors={indicateErrors}\n validRhsTypes={validRhsTypes}\n dateFunctions={dateFunctions}\n itemDirection={itemDirection || 'row'}\n handle={rhsHandle}\n />\n </Grid>\n </StyledAtomicCondition>\n );\n }\n);\n\nexport default AtomicCondition;\n"]}
1
+ {"version":3,"file":"AtomicCondition.js","sourceRoot":"","sources":["../../../src/components/ConditionBuilder/AtomicCondition.tsx"],"names":[],"mappings":";AAAA,OAAO,EAGL,UAAU,EAEV,MAAM,EACN,QAAQ,EAER,mBAAmB,EACpB,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,IAAI,EACJ,MAAM,EACN,MAAM,EACN,OAAO,EACP,OAAO,EAIP,kBAAkB,EAClB,cAAc,EACd,qBAAqB,EACtB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC,OAAO,aAAa,MAAM,6BAA6B,CAAC;AACxD,OAAO,WAAW,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,oBAAoB,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE,4CAA4C;AAC5C,SAAS,YAAY,CAAC,SAAiB,EAAE,MAAe;IACtD,MAAM,aAAa,GAAG,OAAO,CAAC,MAA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K,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,EACtE,IAAI,EACF,cAAc,IAAI,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,EAAE;wBACtC,CAAC,CAAC,CAAC,CAAC,iDAAiD,CAAC;wBACtD,CAAC,CAAC,SAAS,GAEf,CACH,EAGD,KAAC,MAAM,IACL,KAAK,EAAE,KAAK,CAAC,UAAU,EACvB,QAAQ,EAAE,sBAAsB,EAChC,IAAI,EAAC,YAAY,EACjB,KAAK,EAAE,CAAC,CAAC,oCAAoC,CAAC,YAE7C,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAC/B,KAAC,MAAM,IAAiB,KAAK,EAAE,MAAM,CAAC,EAAE,YACrC,MAAM,CAAC,KAAK,IADF,MAAM,CAAC,EAAE,CAEb,CACV,CAAC,GACK,EAGT,KAAC,WAAW,IACV,GAAG,EAAE,KAAK,CAAC,GAAG,EACd,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,GAAG,EAAE,KAAK,CAAC,GAAG,EACd,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,eAAe,EACzB,cAAc,EAAE,cAAc,EAC9B,aAAa,EAAE,aAAa,EAC5B,aAAa,EAAE,aAAa,EAC5B,aAAa,EAAE,aAAa,IAAI,KAAK,EACrC,MAAM,EAAE,SAAS,GACjB,IACG,GACe,CACzB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,eAAe,CAAC","sourcesContent":["import {\n FunctionComponent,\n ChangeEvent,\n forwardRef,\n Ref,\n useRef,\n useState,\n PropsWithoutRef,\n useImperativeHandle\n} from 'react';\n\nimport {\n Grid,\n Select,\n Option,\n useI18n,\n hasProp,\n BaseProps,\n HandleValue,\n ForwardProps,\n useConsolidatedRef,\n useFocusWithin,\n useAfterInitialEffect\n} from '@pega/cosmos-react-core';\n\nimport { getItem } from './core/utils';\nimport { LeafCondition, Field, DateFunctionsByType } from './ConditionBuilder.types';\nimport FieldSelector from './RhsControls/FieldSelector';\nimport RhsControls, { getDefaultRhs, isValidRhs } from './RhsControls';\nimport getComparatorOptions from './core/comparators';\nimport { Comparator, ComparatorsByType, FieldType, RHSType } from './core/types';\nimport { StyledAtomicCondition } from './ConditionBuilder.styles';\n\n// Returns field-type for a given field-name\nfunction getFieldType(fieldName: string, fields: Field[]): FieldType | undefined {\n const matchingField = getItem(fields, fieldName);\n return matchingField && hasProp(matchingField, 'type') ? matchingField.type : undefined;\n}\n\n// Returns display label for a given field-name\nfunction getFieldLabel(fieldName: string, fields: Field[]): string | undefined {\n const matchingField = getItem(fields, fieldName);\n return matchingField?.primary;\n}\n\n/**\n * Upon changing the comparator, checks if the old RHS is valid for the new comparator\n * NOTE: This works under the assumption that the LHS doesn't change\n */\nfunction isRhsValidForComparator(rhs: LeafCondition['rhs'], comparator: Comparator): boolean {\n if (rhs === undefined) {\n return ['IS_NULL', 'IS_NOT_NULL', 'IS_TRUE', 'IS_FALSE'].includes(comparator);\n }\n if (hasProp(rhs, 'values')) {\n return ['IN', 'NOT_IN'].includes(comparator);\n }\n\n if (hasProp(rhs, 'parameterId')) {\n return ['EQ', 'NEQ'].includes(comparator);\n }\n\n if (hasProp(rhs, 'start')) {\n return ['BTW', 'NOT_BTW'].includes(comparator);\n }\n\n // `rhs.field` and `rhs.value` cases\n return [\n 'EQ',\n 'NEQ',\n 'GT',\n 'GTE',\n 'LT',\n 'LTE',\n 'STARTS_WITH',\n 'NOT_STARTS_WITH',\n 'ENDS_WITH',\n 'NOT_ENDS_WITH',\n 'CONTAINS',\n 'NOT_CONTAINS'\n ].includes(comparator);\n}\n\n/** Determines the default condition object for a given LHS value */\nexport function getInitConditionForLhs(\n lhs: LeafCondition['lhs'],\n fields: Field[],\n validRhsTypes: Set<RHSType>,\n validComparators?: ComparatorsByType[],\n dateFunctions?: DateFunctionsByType\n): LeafCondition {\n let comparator: Comparator;\n let rhs: LeafCondition['rhs'];\n if (lhs.field === '') {\n // If the empty option is selected, reset the comparator and rhs to their default values\n comparator = 'IS_NOT_NULL';\n rhs = undefined;\n } else {\n const newFieldType = getFieldType(lhs.field, fields) as FieldType;\n comparator = getComparatorOptions(newFieldType, validComparators)[0].id; // Find the applicable comparators and select the first among them\n rhs = getDefaultRhs(newFieldType, comparator, validRhsTypes, dateFunctions);\n }\n\n return { lhs, comparator, rhs };\n}\n\n/**\n * Verifies if all the values in the condition are valid.\n * NOTES:\n * - This is intended to be used only on conditions emitted by the components in this package.\n * - If a condition is manually constructed outside these components, this utility could miss some malformed conditions.\n */\nexport function isValidCondition(\n condition: LeafCondition,\n fields: Field[],\n trimValues: boolean = false\n): boolean {\n // If no field is yet selected on the LHS\n if (condition.lhs.field === '') {\n return false;\n }\n // If a field is present on the LHS, check if the RHS is valid\n // No need to check the comparator since the comparator is always assigned a valid value\n const fieldType = getFieldType(condition.lhs.field, fields);\n return isValidRhs(condition.rhs, condition.lhs, fields, fieldType, trimValues);\n}\n\n/** Type definition for the input props of AtomicCondition */\nexport interface AtomicConditionProps extends BaseProps {\n /** Condition to use in the component */\n condition: LeafCondition;\n\n /** Metadata (data-model) for the Fields to use in the Condition */\n fields: Field[];\n\n /** Used to enable inline error indicators on invalid inputs */\n indicateErrors: boolean;\n\n /** (Optional) Lookup used to limit the Comparators allowed in the Condition. */\n validComparators?: ComparatorsByType[];\n\n /** Callback for any modifications to the Condition */\n onChange?: (newCondition: LeafCondition, status?: 'error') => void;\n\n /** Callback fired when the condition changes. */\n onBlur?: (newCondition?: LeafCondition) => void;\n\n /** Item flow direction. Defaults to 'row' */\n itemDirection?: 'row' | 'column';\n\n /**\n * Allows presenting the LHS as a readonly text, input or hidden. Defaults presenting as 'input'.\n * NOTE: Make sure that a valid LHS is passed in the 'condition'\n */\n lhsMode?: 'input' | 'label' | 'hidden';\n\n /** Restricts RHS values to only specified types of values.\n * DEFAULT: Set(['LITERAL', 'FIELD']).\n * WARNING: There are LHS/Comparator pairings that require specific RHS types. Please be mindful of\n * these incompatibilities when limiting RHS value types using this prop. We do not support\n * limiting RHS field types to incompatible types and it will result in a validation error\n * if you do so. The pairings referred to here are as follows:\n * - BOOLEAN LHS Fields coupled with \"EQ\" or \"NEQ\" comparators, will always yield a Field RHS\n * - Any LHS Fields coupled with \"IN\" or \"NOT_IN\" comparators, will always yield a Literal RHS (Comma separated list)\n * If you would like to limit RHS value types and avoid these incompatibilities, you will need to exclude these\n * comparators using the validComparators prop.\n */\n validRhsTypes?: Set<RHSType>;\n\n /** (Optional) When enabling 'DATE_FUNCTION's via `validRhsTypes`, pass this to specify which all date functions are applicable per field type */\n dateFunctions?: DateFunctionsByType;\n\n /** Ref forwarded to the wrapping element. */\n ref?: Ref<HTMLDivElement>;\n /** Imperative handle */\n handle?: Ref<HandleValue>;\n}\n\n/** A controlled component for Atomic Conditions */\nconst AtomicCondition: FunctionComponent<AtomicConditionProps & ForwardProps> = forwardRef(\n (\n {\n condition,\n fields,\n indicateErrors,\n validComparators,\n onChange,\n onBlur,\n itemDirection,\n lhsMode = 'input',\n validRhsTypes = new Set<RHSType>(['LITERAL', 'FIELD']),\n dateFunctions,\n handle,\n ...restProps\n }: PropsWithoutRef<AtomicConditionProps>,\n ref: AtomicConditionProps['ref']\n ) => {\n const t = useI18n();\n\n // stores condition form state\n const [state, setState] = useState<LeafCondition>(condition);\n // ref needed to handle use case of onChange and onBlur being triggered at the same time\n // state is not updated by the time blur is invoked, ref is always set to newest value\n const newCondition = useRef(condition);\n\n const fieldType = getFieldType(condition.lhs.field, fields); // Can be `undefined` if no match or if no previous field\n const comparatorOptions = fieldType\n ? getComparatorOptions(fieldType, validComparators)\n : [{ id: '', label: t('condition_builder_select_placeholder') }];\n\n useAfterInitialEffect(() => {\n setState(condition);\n }, [condition]);\n\n const onFocusChange = (focused: boolean) => {\n if (!focused) {\n // newCondition is returned, as it stores newest value\n onBlur?.(\n newCondition.current && isValidCondition(newCondition.current, fields, true)\n ? newCondition.current\n : undefined\n );\n }\n };\n\n const containerRef = useConsolidatedRef(ref);\n useFocusWithin([containerRef], onFocusChange);\n\n // Handle condition update\n const handleConditionChange = (updatedCondition: LeafCondition, status?: 'error') => {\n newCondition.current = updatedCondition;\n // new condition is returned with status to allow recognizing errors and avoiding clearing wrong values from input\n onChange?.(updatedCondition, status);\n };\n\n // Handle change in the field-selector\n const handleFieldChange = (id: string) => {\n const lhs = { field: id };\n const initCondition = getInitConditionForLhs(\n lhs,\n fields,\n validRhsTypes,\n validComparators,\n dateFunctions\n ); // Determine comparator and rhs for the new lhs\n handleConditionChange(initCondition);\n };\n\n // Handle change in the comparator\n const handleComparatorChange = (e: ChangeEvent<HTMLSelectElement>) => {\n if (e.target.value === '') {\n return; // The option is shown only when an lhs is not yet selected. Ignore this selection for those cases\n }\n const comparator = e.target.value as Comparator;\n const rhs = isRhsValidForComparator(condition.rhs, comparator)\n ? condition.rhs\n : getDefaultRhs(fieldType as FieldType, comparator, validRhsTypes, dateFunctions);\n\n handleConditionChange({ ...condition, comparator, rhs });\n };\n\n // Handle change in the RHS\n const handleRHSChange = (rhs: LeafCondition['rhs'], status?: 'error') => {\n handleConditionChange({ ...condition, rhs }, status);\n };\n\n const rhsHandle = useRef<HandleValue>(null);\n\n const clear = () => {\n rhsHandle.current?.clear();\n if (newCondition.current) {\n handleConditionChange(\n getInitConditionForLhs(state.lhs, fields, validRhsTypes, validComparators, dateFunctions)\n );\n }\n };\n\n useImperativeHandle(\n handle,\n () => ({\n clear\n }),\n [clear]\n );\n\n const lhsLabel = getFieldLabel(condition.lhs.field, fields);\n\n return (\n // Using minmax() to get equal widths: https://stackoverflow.com/a/61240964/4247448\n <StyledAtomicCondition\n {...restProps}\n name={lhsMode === 'label' ? lhsLabel : undefined}\n aria-label={lhsMode === 'hidden' ? lhsLabel : undefined}\n >\n <Grid\n sm={{\n container: {\n cols:\n itemDirection === 'column'\n ? 'minmax(0, 1fr)'\n : `repeat(${lhsMode !== 'input' ? 2 : 3}, minmax(0,1fr))`\n }\n }}\n container={{\n justifyItems: 'stretch',\n colGap: 0.5,\n rowGap: 0.5\n }}\n ref={containerRef}\n >\n {/* LHS selector */}\n {lhsMode === 'input' && (\n <FieldSelector\n value={state.lhs.field}\n onChange={handleFieldChange}\n fields={fields}\n status={indicateErrors && state.lhs.field === '' ? 'error' : undefined}\n info={\n indicateErrors && state.lhs.field === ''\n ? t('condition_builder_condition_select_info_default')\n : undefined\n }\n />\n )}\n\n {/* Comparator selector */}\n <Select\n value={state.comparator}\n onChange={handleComparatorChange}\n name='comparator'\n label={t('condition_builder_comparator_label')}\n >\n {comparatorOptions.map(option => (\n <Option key={option.id} value={option.id}>\n {option.label}\n </Option>\n ))}\n </Select>\n\n {/* RHS controls */}\n <RhsControls\n lhs={state.lhs}\n comparator={state.comparator}\n rhs={state.rhs}\n fields={fields}\n onChange={handleRHSChange}\n indicateErrors={indicateErrors}\n validRhsTypes={validRhsTypes}\n dateFunctions={dateFunctions}\n itemDirection={itemDirection || 'row'}\n handle={rhsHandle}\n />\n </Grid>\n </StyledAtomicCondition>\n );\n }\n);\n\nexport default AtomicCondition;\n"]}
@@ -3,9 +3,7 @@ import { BaseProps } from '@pega/cosmos-react-core';
3
3
  import { ComparatorsByType, RHSType } from './core/types';
4
4
  import { Field, LeafCondition, DateFunctionsByType } from './ConditionBuilder.types';
5
5
  export interface HandleValue {
6
- /**
7
- * Returns condition validity and condition if valid.
8
- */
6
+ /** Returns condition validity and condition if valid. */
9
7
  getCondition: () => [valid: false] | [valid: true, condition: LeafCondition];
10
8
  }
11
9
  /** Type definition for the input props of FieldCondition */
@@ -1 +1 @@
1
- {"version":3,"file":"FieldCondition.types.d.ts","sourceRoot":"","sources":["../../../src/components/ConditionBuilder/FieldCondition.types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;A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,CAAC,CAAC;CAC9E;AAED,4DAA4D;AAC5D,MAAM,CAAC,OAAO,WAAW,mBAAoB,SAAQ,SAAS;IAC5D,mEAAmE;IACnE,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAEzB,iFAAiF;IACjF,MAAM,EAAE,KAAK,EAAE,CAAC;IAEhB,2DAA2D;IAC3D,SAAS,CAAC,EAAE,aAAa,CAAC;IAE1B,yEAAyE;IACzE,gBAAgB,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAEvC;;;;OAIG;IACH,aAAa,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IAE7B,iJAAiJ;IACjJ,aAAa,CAAC,EAAE,mBAAmB,CAAC;IAEpC,2CAA2C;IAC3C,MAAM,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;CAC3B"}
@@ -1 +1 @@
1
- {"version":3,"file":"FieldCondition.types.js","sourceRoot":"","sources":["../../../src/components/ConditionBuilder/FieldCondition.types.ts"],"names":[],"mappings":"","sourcesContent":["import { Ref } from 'react';\n\nimport { BaseProps } from '@pega/cosmos-react-core';\n\nimport { ComparatorsByType, RHSType } from './core/types';\nimport { Field, LeafCondition, DateFunctionsByType } from './ConditionBuilder.types';\n\nexport interface HandleValue {\n /**\n * Returns condition validity and condition if valid.\n */\n getCondition: () => [valid: false] | [valid: true, condition: LeafCondition];\n}\n\n/** Type definition for the input props of FieldCondition */\nexport default interface FieldConditionProps extends BaseProps {\n /** Id of the field on which the condition should be constructed */\n targetField: Field['id'];\n\n /** Metadata (data-model) for the Fields to use in the RHS field-selector etc. */\n fields: Field[];\n\n /** (Optional) Passed when editing an existing condition */\n condition?: LeafCondition;\n\n /** (Optional) Used to limit the Comparators allowed in the component. */\n validComparators?: ComparatorsByType[];\n\n /**\n * (Optional) Pass this to control which all types of RHS are enabled in the component\n * DEFAULT: Set(['LITERAL', 'FIELD'])\n * NOTE: If enabling `DATE_FUNCTION`s, additionally pass a `dateFunctions` prop to specify which functions are enabled\n */\n validRhsTypes?: Set<RHSType>;\n\n /** (Optional) When enabling 'DATE_FUNCTION's via `validRhsTypes`, pass this to specify which all date functions are applicable per field type */\n dateFunctions?: DateFunctionsByType;\n\n /** Imperative handle for the component. */\n handle?: Ref<HandleValue>;\n}\n"]}
1
+ {"version":3,"file":"FieldCondition.types.js","sourceRoot":"","sources":["../../../src/components/ConditionBuilder/FieldCondition.types.ts"],"names":[],"mappings":"","sourcesContent":["import { Ref } from 'react';\n\nimport { BaseProps } from '@pega/cosmos-react-core';\n\nimport { ComparatorsByType, RHSType } from './core/types';\nimport { Field, LeafCondition, DateFunctionsByType } from './ConditionBuilder.types';\n\nexport interface HandleValue {\n /** Returns condition validity and condition if valid. */\n getCondition: () => [valid: false] | [valid: true, condition: LeafCondition];\n}\n\n/** Type definition for the input props of FieldCondition */\nexport default interface FieldConditionProps extends BaseProps {\n /** Id of the field on which the condition should be constructed */\n targetField: Field['id'];\n\n /** Metadata (data-model) for the Fields to use in the RHS field-selector etc. */\n fields: Field[];\n\n /** (Optional) Passed when editing an existing condition */\n condition?: LeafCondition;\n\n /** (Optional) Used to limit the Comparators allowed in the component. */\n validComparators?: ComparatorsByType[];\n\n /**\n * (Optional) Pass this to control which all types of RHS are enabled in the component\n * DEFAULT: Set(['LITERAL', 'FIELD'])\n * NOTE: If enabling `DATE_FUNCTION`s, additionally pass a `dateFunctions` prop to specify which functions are enabled\n */\n validRhsTypes?: Set<RHSType>;\n\n /** (Optional) When enabling 'DATE_FUNCTION's via `validRhsTypes`, pass this to specify which all date functions are applicable per field type */\n dateFunctions?: DateFunctionsByType;\n\n /** Imperative handle for the component. */\n handle?: Ref<HandleValue>;\n}\n"]}
@@ -3,6 +3,7 @@ import { BaseProps, NoChildrenProp, ComboBoxProps, HandleValue } from '@pega/cos
3
3
  import { LeafCondition, ParameterValue, ValueSelection } from '../ConditionBuilder.types';
4
4
  import { Comparator } from '../core/types';
5
5
  interface ValueSelectorProps<T extends {
6
+ id: string;
6
7
  possibleValues?: ValueSelection<T>;
7
8
  }> extends BaseProps, NoChildrenProp {
8
9
  mode: ComboBoxProps['mode'];
@@ -37,6 +38,7 @@ interface ValueSelectorProps<T extends {
37
38
  }
38
39
  /** A control for selecting multiple values using checkboxes in an overlay */
39
40
  declare const ValueSelector: <F extends object & {
41
+ id: string;
40
42
  possibleValues?: ValueSelection<F> | undefined;
41
43
  }>({ values, selectedField, comparator, rhs, onChange, onBlur, onClear, status, mode, parameters, placeholder, label, info, setApiError, handle }: ValueSelectorProps<F>) => JSX.Element;
42
44
  export default ValueSelector;
@@ -1 +1 @@
1
- {"version":3,"file":"ValueSelector.d.ts","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/RhsControls/ValueSelector.tsx"],"names":[],"mappings":"AAAA,OAAO,EAIL,QAAQ,EACR,cAAc,EAEd,GAAG,EAEJ,MAAM,OAAO,CAAC;AAEf,OAAO,EAEL,SAAS,EAIT,cAAc,EACd,aAAa,EAKb,WAAW,EACZ,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,aAAa,EACb,cAAc,EAEd,cAAc,EACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,UAAU,kBAAkB,CAAC,CAAC,SAAS;IAAE,cAAc,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,CAAA;CAAE,CAC3E,SAAQ,SAAS,EACf,cAAc;IAChB,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IAC5B,yBAAyB;IACzB,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAC1B,2BAA2B;IAC3B,aAAa,EAAE,CAAC,CAAC;IACjB,kCAAkC;IAClC,UAAU,EAAE,UAAU,CAAC;IACvB,4BAA4B;IAC5B,GAAG,EAAE,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;IACvC,oDAAoD;IACpD,UAAU,EAAE,cAAc,EAAE,CAAC;IAC7B,2BAA2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values, selectedField, comparator, rhs, onChange, onBlu
88
88
  subscribed = false;
89
89
  setApiError?.(null);
90
90
  };
91
- }, [filterValue, selectedField, comparator]);
91
+ }, [filterValue, selectedField.id, comparator]);
92
92
  useEffect(() => setFilterValue(''), [selectedField, comparator]);
93
93
  const getSelections = () => {
94
94
  if (typeof selections === 'string') {
@@ -1 +1 @@
1
- {"version":3,"file":"ValueSelector.js","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/RhsControls/ValueSelector.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,QAAQ,EACR,SAAS,EACT,MAAM,EAGN,WAAW,EAEX,mBAAmB,EACpB,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,OAAO,EAEP,QAAQ,EACR,mBAAmB,EACnB,qBAAqB,EAGrB,OAAO,EACP,MAAM,EACN,IAAI,EAGL,MAAM,yBAAyB,CAAC;AA4CjC,6EAA6E;AAC7E,MAAM,aAAa,GAAG,CAA4D,EAChF,MAAM,EACN,aAAa,EACb,UAAU,EACV,GAAG,EACH,QAAQ,EACR,MAAM,EACN,OAAO,EACP,MAAM,EACN,IAAI,EACJ,UAAU,EACV,WAAW,EACX,KAAK,EACL,IAAI,EACJ,WAAW,EACX,MAAM,EACgB,EAAE,EAAE;IAC1B,MAAM,CAAC,GAAG,OAAO,EAAE,CAAC;IAEpB,MAAM,QAAQ,GAAG,MAAM,CAAiB,IAAI,CAAC,CAAC;IAE9C,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,MAAM,CAAC,CAAC;IACxE,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC;IACnD,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAA+C,EAAE,CAAC,CAAC;IACzF,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAChD,EAAE,CACH,CAAC;IACF,MAAM,CAAC,OAAO,EAAE,UAA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AAC;oBACxD,OAAO,EAAE,KAAK,EAAE,CAAC;iBAClB;YACH,CAAC,YAED,KAAC,IAAI,IAAC,IAAI,EAAC,OAAO,GAAG,GACd,CACV,GAEH,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,aAAa,CAAC","sourcesContent":["import {\n useState,\n useEffect,\n useRef,\n Dispatch,\n SetStateAction,\n useCallback,\n Ref,\n useImperativeHandle\n} from 'react';\n\nimport {\n useI18n,\n BaseProps,\n ComboBox,\n createStringMatcher,\n useAfterInitialEffect,\n NoChildrenProp,\n ComboBoxProps,\n hasProp,\n Button,\n Icon,\n MenuProps,\n HandleValue\n} from '@pega/cosmos-react-core';\n\nimport {\n LeafCondition,\n ParameterValue,\n ReferenceValue,\n ValueSelection\n} from '../ConditionBuilder.types';\nimport { Comparator } from '../core/types';\n\ninterface ValueSelectorProps<T extends { possibleValues?: ValueSelection<T> }>\n extends BaseProps,\n NoChildrenProp {\n mode: ComboBoxProps['mode'];\n /** Previous selection */\n values: string[] | string;\n /** Current selected LHS */\n selectedField: T;\n /** Current selected comparator */\n comparator: Comparator;\n /** Rhs for the condition */\n rhs: NonNullable<LeafCondition['rhs']>;\n /** Passed Parameters array for Rhstype PARAMETER */\n parameters: ParameterValue[];\n /** Callback for changes */\n onChange: (selection: string[] | string) => void;\n /** Callback for blur */\n onBlur?: (selection?: string[] | string) => void;\n /** Callback for clear */\n onClear?: () => void;\n /** Used to indicate any errors on the control */\n status?: 'error';\n /** Placeholder text to display in empty control */\n placeholder?: ComboBoxProps['placeholder'];\n /** Custom label for input. Makes label visible if provided. */\n label?: ComboBoxProps['label'];\n /** Guidance text that apppears below the input. */\n info?: ComboBoxProps['info'];\n /** sets status and info */\n setApiError?: Dispatch<SetStateAction<string | null>>;\n /** Imperative handle */\n handle?: Ref<HandleValue>;\n}\n\n/** A control for selecting multiple values using checkboxes in an overlay */\nconst ValueSelector = <F extends object & { possibleValues?: ValueSelection<F> }>({\n values,\n selectedField,\n comparator,\n rhs,\n onChange,\n onBlur,\n onClear,\n status,\n mode,\n parameters,\n placeholder,\n label,\n info,\n setApiError,\n handle\n}: ValueSelectorProps<F>) => {\n const t = useI18n();\n\n const inputRef = useRef<HTMLDivElement>(null);\n\n const [selections, setSelections] = useState<string[] | string>(values);\n const [filterValue, setFilterValue] = useState('');\n const [options, setOptions] = useState<(string | ParameterValue | ReferenceValue)[]>([]);\n const [filterOptions, setFilterOptions] = useState<(string | ParameterValue | ReferenceValue)[]>(\n []\n );\n const [loading, setLoading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n const [items, setItems] = useState<MenuProps['items']>([]);\n\n const itemsToRender = (item: (string | ParameterValue | ReferenceValue)[]) => {\n return item.map(option => {\n if (typeof option === 'object') {\n return {\n ...option,\n selected: Array.isArray(selections)\n ? selections.includes(option.id)\n : selections === option.id\n };\n }\n return {\n id: option,\n primary: option,\n selected: Array.isArray(selections) ? selections.includes(option) : selections === option\n };\n });\n };\n\n useEffect(() => {\n const updatedItems = items.map(item => {\n const result = Array.isArray(selections)\n ? selections.includes(item.id)\n : selections === item.id;\n return { ...item, selected: result };\n });\n setItems(updatedItems);\n }, [selections]);\n\n useEffect(() => {\n const matcher = createStringMatcher(filterValue, 'boundary');\n setFilterOptions(\n options.filter(option => {\n if (typeof option === 'object') return matcher.test(option.primary);\n return matcher.test(option);\n })\n );\n }, [filterValue, options]);\n\n useAfterInitialEffect(() => {\n onChange(selections);\n }, [selections]);\n\n useEffect(() => {\n if (!selectedField) {\n return;\n }\n let subscribed = true;\n\n if (hasProp(rhs, 'parameterId')) {\n setOptions(parameters);\n } else if (hasProp(selectedField, 'possibleValues')) {\n const { possibleValues } = selectedField;\n if (typeof possibleValues === 'function') {\n setLoading(true);\n setOptions([]);\n possibleValues({ searchString: filterValue, comparator, lhs: selectedField })\n .then(response => {\n if (!subscribed) return;\n setOptions(response);\n setLoading(false);\n })\n .catch(err => {\n if (err && subscribed) {\n setApiError?.(t('condition_builder_possible_values_error'));\n setOptions([]);\n setLoading(false);\n }\n });\n } else if (Array.isArray(possibleValues)) {\n setOptions(possibleValues);\n } else {\n setOptions([]);\n }\n }\n\n return () => {\n subscribed = false;\n setApiError?.(null);\n };\n }, [filterValue, selectedField, comparator]);\n\n useEffect(() => setFilterValue(''), [selectedField, comparator]);\n\n const getSelections = () => {\n if (typeof selections === 'string') {\n let itemLabel;\n if (hasProp(rhs, 'parameterId')) {\n const selectedItem = parameters.find(item => item.id === selections);\n itemLabel = selectedItem !== undefined ? selectedItem.primary : selections;\n } else itemLabel = selections;\n\n return {\n items: { id: selections, text: itemLabel }\n };\n }\n if (selections.length > 0) {\n return {\n items: selections.map(s => {\n const optionLabel = options.find(opt => typeof opt === 'object' && opt.id === s) as\n | ParameterValue\n | ReferenceValue\n | undefined;\n return { id: s, text: optionLabel?.primary ?? s };\n }),\n onRemove: (value: string) => {\n setSelections(cur => {\n const current = cur as string[];\n return current.filter(selection => selection !== value);\n });\n }\n };\n }\n\n return undefined;\n };\n\n useEffect(() => {\n if (filterValue !== '') {\n setItems(itemsToRender(filterOptions.slice(0, 10)));\n } else {\n setItems(itemsToRender(options.slice(0, 10)));\n }\n }, [options, filterOptions]);\n\n const loadMore = useCallback(() => {\n if (!loading) {\n setLoading(true);\n\n let totalItem: (string | ParameterValue | ReferenceValue)[];\n if (filterOptions.length > 0) totalItem = filterOptions;\n else totalItem = options;\n\n const remItems = totalItem.length - items.length;\n let newItemsLength = 10;\n if (remItems <= newItemsLength) {\n setHasMore(false);\n newItemsLength = remItems;\n }\n\n setLoading(false);\n setItems(prev => {\n return [\n ...prev,\n ...itemsToRender(totalItem.slice(items.length, items.length + newItemsLength))\n ];\n });\n }\n }, [options, loading, filterOptions, items, hasMore]);\n\n useImperativeHandle(\n handle,\n () => ({\n clear: () => {\n setSelections([]);\n }\n }),\n [setSelections]\n );\n\n return (\n <ComboBox\n ref={inputRef}\n mode={mode}\n label={label ?? t('condition_builder_possible_values_label')}\n placeholder={\n placeholder ??\n (mode === 'single-select'\n ? t('condition_builder_single_selection_text_default')\n : t('condition_builder_multi_selection_text_default'))\n }\n value={filterValue}\n onChange={e => {\n setFilterValue(e.target.value);\n setHasMore(true);\n }}\n onBlur={() => {\n onBlur?.(selections);\n setFilterValue('');\n }}\n menu={{\n items,\n onItemClick: id => {\n setFilterValue('');\n if (mode === 'single-select') {\n setSelections(id);\n } else {\n setSelections(cur => {\n const current = cur as string[];\n return current.includes(id)\n ? current.filter(selection => selection !== id)\n : [...cur, id];\n });\n }\n },\n loading,\n loadMore: hasMore ? loadMore : undefined\n }}\n selected={getSelections()}\n status={status}\n info={info}\n actions={\n onClear &&\n selections.length > 0 && (\n <Button\n icon\n variant='simple'\n label={t('clear')}\n onClick={() => {\n setSelections([]);\n onClear();\n if (inputRef.current) {\n const inputEl = inputRef.current.querySelector('input');\n inputEl?.focus();\n }\n }}\n >\n <Icon name='times' />\n </Button>\n )\n }\n />\n );\n};\n\nexport default ValueSelector;\n"]}
1
+ {"version":3,"file":"ValueSelector.js","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/RhsControls/ValueSelector.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,QAAQ,EACR,SAAS,EACT,MAAM,EAGN,WAAW,EAEX,mBAAmB,EACpB,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,OAAO,EAEP,QAAQ,EACR,mBAAmB,EACnB,qBAAqB,EAGrB,OAAO,EACP,MAAM,EACN,IAAI,EAGL,MAAM,yBAAyB,CAAC;AA4CjC,6EAA6E;AAC7E,MAAM,aAAa,GAAG,CAAwE,EAC5F,MAAM,EACN,aAAa,EACb,UAAU,EACV,GAAG,EACH,QAAQ,EACR,MAAM,EACN,OAAO,EACP,MAAM,EACN,IAAI,EACJ,UAAU,EACV,WAAW,EACX,KAAK,EACL,IAAI,EACJ,WAAW,EACX,MAAM,EACgB,EAAE,EAAE;IAC1B,MAAM,CAAC,GAAG,OAAO,EAAE,CAAC;IAEpB,MAAM,QAAQ,GAAG,MAAM,CAAiB,IAA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AAI,EAAE,IAAI,EACV,OAAO,EACL,OAAO;YACP,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,CACvB,KAAC,MAAM,IACL,IAAI,QACJ,OAAO,EAAC,QAAQ,EAChB,KAAK,EAAE,CAAC,CAAC,OAAO,CAAC,EACjB,OAAO,EAAE,GAAG,EAAE;gBACZ,aAAa,CAAC,EAAE,CAAC,CAAC;gBAClB,OAAO,EAAE,CAAC;gBACV,IAAI,QAAQ,CAAC,OAAO,EAAE;oBACpB,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;oBACxD,OAAO,EAAE,KAAK,EAAE,CAAC;iBAClB;YACH,CAAC,YAED,KAAC,IAAI,IAAC,IAAI,EAAC,OAAO,GAAG,GACd,CACV,GAEH,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,aAAa,CAAC","sourcesContent":["import {\n useState,\n useEffect,\n useRef,\n Dispatch,\n SetStateAction,\n useCallback,\n Ref,\n useImperativeHandle\n} from 'react';\n\nimport {\n useI18n,\n BaseProps,\n ComboBox,\n createStringMatcher,\n useAfterInitialEffect,\n NoChildrenProp,\n ComboBoxProps,\n hasProp,\n Button,\n Icon,\n MenuProps,\n HandleValue\n} from '@pega/cosmos-react-core';\n\nimport {\n LeafCondition,\n ParameterValue,\n ReferenceValue,\n ValueSelection\n} from '../ConditionBuilder.types';\nimport { Comparator } from '../core/types';\n\ninterface ValueSelectorProps<T extends { id: string; possibleValues?: ValueSelection<T> }>\n extends BaseProps,\n NoChildrenProp {\n mode: ComboBoxProps['mode'];\n /** Previous selection */\n values: string[] | string;\n /** Current selected LHS */\n selectedField: T;\n /** Current selected comparator */\n comparator: Comparator;\n /** Rhs for the condition */\n rhs: NonNullable<LeafCondition['rhs']>;\n /** Passed Parameters array for Rhstype PARAMETER */\n parameters: ParameterValue[];\n /** Callback for changes */\n onChange: (selection: string[] | string) => void;\n /** Callback for blur */\n onBlur?: (selection?: string[] | string) => void;\n /** Callback for clear */\n onClear?: () => void;\n /** Used to indicate any errors on the control */\n status?: 'error';\n /** Placeholder text to display in empty control */\n placeholder?: ComboBoxProps['placeholder'];\n /** Custom label for input. Makes label visible if provided. */\n label?: ComboBoxProps['label'];\n /** Guidance text that apppears below the input. */\n info?: ComboBoxProps['info'];\n /** sets status and info */\n setApiError?: Dispatch<SetStateAction<string | null>>;\n /** Imperative handle */\n handle?: Ref<HandleValue>;\n}\n\n/** A control for selecting multiple values using checkboxes in an overlay */\nconst ValueSelector = <F extends object & { id: string; possibleValues?: ValueSelection<F> }>({\n values,\n selectedField,\n comparator,\n rhs,\n onChange,\n onBlur,\n onClear,\n status,\n mode,\n parameters,\n placeholder,\n label,\n info,\n setApiError,\n handle\n}: ValueSelectorProps<F>) => {\n const t = useI18n();\n\n const inputRef = useRef<HTMLDivElement>(null);\n\n const [selections, setSelections] = useState<string[] | string>(values);\n const [filterValue, setFilterValue] = useState('');\n const [options, setOptions] = useState<(string | ParameterValue | ReferenceValue)[]>([]);\n const [filterOptions, setFilterOptions] = useState<(string | ParameterValue | ReferenceValue)[]>(\n []\n );\n const [loading, setLoading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n const [items, setItems] = useState<MenuProps['items']>([]);\n\n const itemsToRender = (item: (string | ParameterValue | ReferenceValue)[]) => {\n return item.map(option => {\n if (typeof option === 'object') {\n return {\n ...option,\n selected: Array.isArray(selections)\n ? selections.includes(option.id)\n : selections === option.id\n };\n }\n return {\n id: option,\n primary: option,\n selected: Array.isArray(selections) ? selections.includes(option) : selections === option\n };\n });\n };\n\n useEffect(() => {\n const updatedItems = items.map(item => {\n const result = Array.isArray(selections)\n ? selections.includes(item.id)\n : selections === item.id;\n return { ...item, selected: result };\n });\n setItems(updatedItems);\n }, [selections]);\n\n useEffect(() => {\n const matcher = createStringMatcher(filterValue, 'boundary');\n setFilterOptions(\n options.filter(option => {\n if (typeof option === 'object') return matcher.test(option.primary);\n return matcher.test(option);\n })\n );\n }, [filterValue, options]);\n\n useAfterInitialEffect(() => {\n onChange(selections);\n }, [selections]);\n\n useEffect(() => {\n if (!selectedField) {\n return;\n }\n let subscribed = true;\n\n if (hasProp(rhs, 'parameterId')) {\n setOptions(parameters);\n } else if (hasProp(selectedField, 'possibleValues')) {\n const { possibleValues } = selectedField;\n if (typeof possibleValues === 'function') {\n setLoading(true);\n setOptions([]);\n possibleValues({ searchString: filterValue, comparator, lhs: selectedField })\n .then(response => {\n if (!subscribed) return;\n setOptions(response);\n setLoading(false);\n })\n .catch(err => {\n if (err && subscribed) {\n setApiError?.(t('condition_builder_possible_values_error'));\n setOptions([]);\n setLoading(false);\n }\n });\n } else if (Array.isArray(possibleValues)) {\n setOptions(possibleValues);\n } else {\n setOptions([]);\n }\n }\n\n return () => {\n subscribed = false;\n setApiError?.(null);\n };\n }, [filterValue, selectedField.id, comparator]);\n\n useEffect(() => setFilterValue(''), [selectedField, comparator]);\n\n const getSelections = () => {\n if (typeof selections === 'string') {\n let itemLabel;\n if (hasProp(rhs, 'parameterId')) {\n const selectedItem = parameters.find(item => item.id === selections);\n itemLabel = selectedItem !== undefined ? selectedItem.primary : selections;\n } else itemLabel = selections;\n\n return {\n items: { id: selections, text: itemLabel }\n };\n }\n if (selections.length > 0) {\n return {\n items: selections.map(s => {\n const optionLabel = options.find(opt => typeof opt === 'object' && opt.id === s) as\n | ParameterValue\n | ReferenceValue\n | undefined;\n return { id: s, text: optionLabel?.primary ?? s };\n }),\n onRemove: (value: string) => {\n setSelections(cur => {\n const current = cur as string[];\n return current.filter(selection => selection !== value);\n });\n }\n };\n }\n\n return undefined;\n };\n\n useEffect(() => {\n if (filterValue !== '') {\n setItems(itemsToRender(filterOptions.slice(0, 10)));\n } else {\n setItems(itemsToRender(options.slice(0, 10)));\n }\n }, [options, filterOptions]);\n\n const loadMore = useCallback(() => {\n if (!loading) {\n setLoading(true);\n\n let totalItem: (string | ParameterValue | ReferenceValue)[];\n if (filterOptions.length > 0) totalItem = filterOptions;\n else totalItem = options;\n\n const remItems = totalItem.length - items.length;\n let newItemsLength = 10;\n if (remItems <= newItemsLength) {\n setHasMore(false);\n newItemsLength = remItems;\n }\n\n setLoading(false);\n setItems(prev => {\n return [\n ...prev,\n ...itemsToRender(totalItem.slice(items.length, items.length + newItemsLength))\n ];\n });\n }\n }, [options, loading, filterOptions, items, hasMore]);\n\n useImperativeHandle(\n handle,\n () => ({\n clear: () => {\n setSelections([]);\n }\n }),\n [setSelections]\n );\n\n return (\n <ComboBox\n ref={inputRef}\n mode={mode}\n label={label ?? t('condition_builder_possible_values_label')}\n placeholder={\n placeholder ??\n (mode === 'single-select'\n ? t('condition_builder_single_selection_text_default')\n : t('condition_builder_multi_selection_text_default'))\n }\n value={filterValue}\n onChange={e => {\n setFilterValue(e.target.value);\n setHasMore(true);\n }}\n onBlur={() => {\n onBlur?.(selections);\n setFilterValue('');\n }}\n menu={{\n items,\n onItemClick: id => {\n setFilterValue('');\n if (mode === 'single-select') {\n setSelections(id);\n } else {\n setSelections(cur => {\n const current = cur as string[];\n return current.includes(id)\n ? current.filter(selection => selection !== id)\n : [...cur, id];\n });\n }\n },\n loading,\n loadMore: hasMore ? loadMore : undefined\n }}\n selected={getSelections()}\n status={status}\n info={info}\n actions={\n onClear &&\n selections.length > 0 && (\n <Button\n icon\n variant='simple'\n label={t('clear')}\n onClick={() => {\n setSelections([]);\n onClear();\n if (inputRef.current) {\n const inputEl = inputRef.current.querySelector('input');\n inputEl?.focus();\n }\n }}\n >\n <Icon name='times' />\n </Button>\n )\n }\n />\n );\n};\n\nexport default ValueSelector;\n"]}
@@ -30,12 +30,8 @@ export declare function splitConditionTree(tree: Condition, labelPrefix?: string
30
30
  export declare function isBasicModeApplicable(condition: Condition): boolean;
31
31
  /** Returns a list of operators to show in the Basic mode, using a logicString as the input */
32
32
  export declare function getBasicModeOperators(logic: string): ('AND' | 'OR')[];
33
- /**
34
- * Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them
35
- */
33
+ /** Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them */
36
34
  export declare function getLogicFromBasicMode(operatorsList: ('AND' | 'OR')[]): string;
37
- /**
38
- * Takes a list of objects and id of the object to be found and recursively finds and returns the object
39
- */
35
+ /** Takes a list of objects and id of the object to be found and recursively finds and returns the object */
40
36
  export declare function getItem(items: Field[], id: string): Field | undefined;
41
37
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/core/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AAiQ1F,yDAAyD;AACzD,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE;IAAE,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAA;CAAE,EAAE,4CAA4C;AACjG,WAAW,GAAE,OAAe,EAC5B,kBAAkB,GAAE,OAAe,GAClC;IAAE,SAAS,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAqB9C;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CA0D5D;AAkDD,uFAAuF;AACvF,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,SAAS,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,YAAY,EAAE,CAAA;CAAE,CAUjG;AAGD,mIAAmI;AACnI,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,SAAS,EACf,WAAW,GAAE,MAAW,GACvB;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAA;KAAE,CAAA;CAAE,CAkBnE;AAED,qHAAqH;AACrH,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,SAAS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,aAAa,CAAA;KAAE,CAAA;CAAE,CAkBnE;AAED,qHAAqH;AACrH,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAyBnE;AAED,8FAA8F;AAC9F,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE,CAMrE;AAED,2GAA2G;AAC3G,wBAAgB,qBAAqB,CAAC,aAAa,EAAE,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE,GAAG,MAAM,CAG7E;AAED,4GAA4G;AAC5G,wBAAgB,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS,CAiBrE"}
@@ -430,16 +430,12 @@ export function getBasicModeOperators(logic) {
430
430
  }
431
431
  return matches;
432
432
  }
433
- /**
434
- * Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them
435
- */
433
+ /** Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them */
436
434
  export function getLogicFromBasicMode(operatorsList) {
437
435
  const logicString = operatorsList.reduce((logic, op, i) => `${logic} ${op} ${i + 2}`, '1');
438
436
  return disambiguateLogic(logicString); // Disambiguating the logic string by placing parentheses at appropriate places
439
437
  }
440
- /**
441
- * Takes a list of objects and id of the object to be found and recursively finds and returns the object
442
- */
438
+ /** Takes a list of objects and id of the object to be found and recursively finds and returns the object */
443
439
  export function getItem(items, id) {
444
440
  let found;
445
441
  items.some(item => {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/core/utils.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAI7D,MAAM,GAAG,GAAG,KAAK,CAAC;AAClB,MAAM,EAAE,GAAG,IAAI,CAAC;AAChB,MAAM,GAAG,GAAG,KAAK,CAAC;AAClB,MAAM,MAAM,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CAAC;IAC7B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAChB,IAAI,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE;YAClB,KAAK,GAAG,IAAI,CAAC;YACb,OAAO,IAAI,CAAC;SACb;QAED,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;YAC1B,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAChC,OAAO,CAAC,CAAC,KAAK,CAAC;SAChB;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// cspell:words LPAREN LPARENs RPAREN RPARENs\nimport { createUID, hasProp } from '@pega/cosmos-react-core';\n\nimport { Condition, ConditionRow, LeafCondition, Field } from '../ConditionBuilder.types';\n\nconst AND = 'AND';\nconst OR = 'OR';\nconst NOT = 'NOT';\nconst LPAREN = '(';\nconst RPAREN = ')';\n\nconst precedenceMap: { [op: string]: number } = { OR: 1, AND: 2, NOT: 3 }; // Operator precedence. NOT has the highest precedence over the others\nconst operatorTokens = new Set([AND, OR, NOT]); // Valid logical operators\nconst validTokens = new Set([AND, OR, NOT, LPAREN, RPAREN]); // Other than these, integer tokens are valid\n\nconst isIntegerToken = (token: string): boolean => /^\\d+$/.test(token); // Checks if the input token is an integer\nconst isOperatorToken = (token: string): boolean => operatorTokens.has(token); // Checks if the input token is an operator\n\n/**\n * Tokenize the input expression.\n * Valid tokens are 'AND', 'OR', 'NOT', '(', ')' and any integer token.\n * Throws an error if an invalid token is found.\n */\nfunction tokenizeExpression(\n expression: string,\n disallowNOT: boolean = false\n): { tokens: string[] } | { error: string } {\n expression = expression.trim().toUpperCase(); // To simplify comparisons below; the tokens AND/OR/NOT are anyways expected to be in uppercase\n const words = expression.match(/[A-Z]+|[0-9]+|_|\\W/g); // Split contiguous alphabets and contiguous numbers into the same token. For all other characters, create a token for each character. Although `_` is not expected to be used, handling it just for completeness\n const tokens: string[] = []; // Final list of valid tokens\n const invalidWords: string[] = []; // Any invalid words are captured here\n\n // `words` will never be null because of the regex we used. Using `!` to indicate the same to TS\n words!.forEach(word => {\n // Ignore white-space characters\n if (word.trim().length > 0) {\n // If it's a token from the above Set or if it's an integer token\n if (isIntegerToken(word) || (validTokens.has(word) && !(word === NOT && disallowNOT))) {\n tokens.push(word);\n } else {\n invalidWords.push(word);\n }\n }\n });\n\n // Return an error if any invalid tokens are present\n if (invalidWords.length > 0) {\n return { error: `Unexpected words/characters: ${invalidWords.join(' ')}` }; // FIXME: TR\n }\n\n return { tokens };\n}\n\n/**\n * Captures any invalid/unexpected token patterns\n * NOTE: This does not expect any invalid tokens to be passed in the input\n * NOTE: This doesn't handle mismatched parentheses. That is handled separately in getPostfixFromInfix\n * Returns an error message about the first invalid sequence present in the input. Returns `null` if none found\n */\nfunction findInvalidPatterns(tokens: string[]): string | null {\n // These patterns are identified based on which token can precede/succeed which.\n // A table with all such permutations can be found in DOC-38200\n\n for (let i = 0; i < tokens.length; i += 1) {\n const NUMBER = 'NUMBER'; // To avoid repeating a string literal\n const token = tokens[i];\n const tokenType = isIntegerToken(token) ? NUMBER : token; // To simplify comparisons below\n\n // The expression can only start with NOT, LPAREN or NUMBER\n if (i === 0 && ![NOT, LPAREN, NUMBER].includes(tokenType)) {\n return `Unexpected \"${token}\" at the beginning.`; // FIXME: TR\n }\n\n // The expression can only end with RPAREN or NUMBER\n if (i === tokens.length - 1 && ![RPAREN, NUMBER].includes(tokenType)) {\n return `Unexpected \"${token}\" at the end.`; // FIXME: TR\n }\n\n // If there is a previous token, check if it is supposed to precede the current token\n if (i > 0) {\n const prevToken = tokens[i - 1];\n const prevTokenType = isIntegerToken(prevToken) ? NUMBER : prevToken; // To simplify comparisons below\n switch (tokenType) {\n // AND/OR/RPAREN can only be preceded by RPAREN or NUMBER\n case AND:\n case OR:\n case RPAREN:\n if (![RPAREN, NUMBER].includes(prevTokenType)) {\n return `Unexpected \"${token}\" after \"${prevToken}\"`; // FIXME: TR\n }\n break;\n\n // NOT/LPAREN/NUMBER can not be preceded by RPAREN or NUMBER\n case NOT:\n case LPAREN:\n case NUMBER:\n if ([RPAREN, NUMBER].includes(prevTokenType)) {\n return `Unexpected \"${token}\" after \"${prevToken}\"`; // FIXME: TR\n }\n break;\n default: // do nothing\n }\n }\n }\n\n // Return null if no invalid sequences\n return null;\n}\n\n/**\n * Converts an input array of Infix tokens into a Postfix array.\n * Uses the ShuntingYard algorithm.\n * NOTE: This does not expect any invalid tokens to be passed in the input\n */\nfunction getPostfixFromInfix(tokens: string[]): { postfixArr: string[] } | { error: string } {\n // Refer these for the ShuntingYard algorithm:\n // * https://brilliant.org/wiki/shunting-yard-algorithm/\n // * https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail\n const postfixQueue: string[] = []; // Output queue\n const stack: string[] = []; // Operations stack\n\n // While there are tokens to be read\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n\n if (isIntegerToken(token)) {\n // If it's a number add it to queue\n postfixQueue.push(token);\n } else if (isOperatorToken(token)) {\n // If it's an operator\n // While there's an operator on the top of the stack with greater precedence (or equal precedence and the token is left-associative), pop operators from the stack onto the output queue\n if (token !== NOT) {\n // Unary operators should not cause any operators to be popped from the stack.\n // See http://wcipeg.com/wiki/Shunting_yard_algorithm#Unary_operators\n while (stack.length > 0) {\n const stackTop = stack[stack.length - 1];\n if (isOperatorToken(stackTop) && precedenceMap[stackTop] >= precedenceMap[token]) {\n postfixQueue.push(stack.pop()!);\n } else {\n break;\n }\n }\n }\n // Push the current operator onto the stack\n stack.push(token);\n } else if (token === LPAREN) {\n // If it's a left parenthesis, push it onto the stack\n stack.push(token);\n } else {\n // If it's a right parenthesis (RPAREN)\n // While there's not a left parenthesis at the top of the stack, pop operators from the stack onto the output queue\n while (stack.length > 0) {\n const stackTop = stack[stack.length - 1];\n if (stackTop === LPAREN) break;\n postfixQueue.push(stack.pop()!);\n }\n\n // Pop the left parenthesis from the stack and discard it\n if (stack.length > 0) {\n stack.pop();\n } else {\n // FIXME: TR\n return { error: 'Please fix mismatched parentheses.' }; // If no LPAREN found for the current RPAREN\n }\n }\n }\n\n // While there are operators on the stack, pop them to the queue\n while (stack.length > 0) {\n if (stack[stack.length - 1] === LPAREN) {\n // FIXME: TR\n return { error: 'Please fix mismatched parentheses.' }; // If there were excess LPARENs. (Excess RPARENs are already handled in the above loop. Also, RPARENs are never pushed to the stack)\n }\n postfixQueue.push(stack.pop()!);\n }\n\n return { postfixArr: postfixQueue };\n}\n\n/**\n * Converts an input array of Postfix tokens into a Condition tree.\n * NOTE: This expects a properly formed Postfix array as input\n */\nfunction getConditionFromPostfix(\n postfixArr: string[],\n conditionLookup: { [label: string]: LeafCondition },\n ignoreUnusedLabels: boolean\n): { condition: Condition } | { error: string } {\n // To learn more about the below algorithm, refer this: https://brilliant.org/wiki/shunting-yard-algorithm/#reverse-polish\n const operandsStack: Condition[] = [];\n const labelsWithNoRows: string[] = []; // Labels for which there is no corresponding op in conditionLookup\n const usedLabels: string[] = []; // A list of all labels used in the condition. This is used to warn about any unused operations\n postfixArr.forEach(token => {\n if (isIntegerToken(token)) {\n // If it's a numeric token (leaf condition), push it to the stack\n const conditionRow = conditionLookup[token]; // Identify the corresponding condition row\n operandsStack.push({ condition: conditionRow }); // Push it even if null so that the conversion goes on smoothly and identifies any other issues\n if (!conditionRow) {\n labelsWithNoRows.push(token); // Mark it as missing\n } else {\n usedLabels.push(token); // Mark it as used\n }\n } else if (token === NOT) {\n // If it's the NOT operator\n // Pop an operand, perform the operation and push the result back to the stack\n const operand = operandsStack.pop()!;\n operandsStack.push({ NOT: operand });\n } else {\n // If it's the AND/OR operator\n // Pop two operands, perform the operation and push the result back to the stack\n const operand2 = operandsStack.pop()!;\n const operand1 = operandsStack.pop()!;\n\n // If the inner operation is the same as the current one, consolidate them\n // e.g. `1 AND (2 AND 3)` should be consolidated as `1 AND 2 AND 3`\n // e.g. `1 OR (2 OR 3)` should be consolidated as `1 OR 2 OR 3`\n if (token === 'AND') {\n const operands = [\n ...(hasProp(operand1, 'AND') ? operand1.AND : [operand1]),\n ...(hasProp(operand2, 'AND') ? operand2.AND : [operand2])\n ];\n operandsStack.push({ AND: operands });\n } else {\n const operands = [\n ...(hasProp(operand1, 'OR') ? operand1.OR : [operand1]),\n ...(hasProp(operand2, 'OR') ? operand2.OR : [operand2])\n ];\n operandsStack.push({ OR: operands });\n }\n }\n });\n\n // If any labels are used for which there are no corresponding condition-rows\n if (labelsWithNoRows.length > 0) {\n if (labelsWithNoRows.length === 1) {\n return {\n error: `Condition ${labelsWithNoRows[0]} used in the logical string is not defined.` // FIXME: TR\n };\n }\n return {\n error: `Conditions ${labelsWithNoRows.join(', ')} used in the logical string are not defined.` // FIXME: TR\n };\n }\n\n // Warn if any of the condition rows are unused\n if (!ignoreUnusedLabels) {\n const unusedLabels = Object.keys(conditionLookup).filter(l => !usedLabels.includes(l));\n if (unusedLabels.length > 0) {\n if (unusedLabels.length === 1) {\n return { error: `Condition ${unusedLabels[0]} is not used in the logic expression.` }; // FIXME: TR\n }\n return {\n error: `Conditions ${unusedLabels.join(', ')} are not used in the logic expression.` // FIXME: TR\n };\n }\n }\n\n return { condition: operandsStack[0] };\n}\n\n/** Parses a logic-expression into a condition object. */\nexport function parseLogicString(\n expression: string,\n conditionLookup: { [label: string]: LeafCondition }, // To look up condition-rows from the labels\n disallowNOT: boolean = false,\n ignoreUnusedLabels: boolean = false\n): { condition: Condition } | { error: string } {\n // Handle empty expressions\n if (!expression.trim().length) return { error: 'Please provide a logic expression.' }; // FIXME: TR\n\n // Split the expression into individual tokens\n const tokeningResult = tokenizeExpression(expression, disallowNOT);\n if (hasProp(tokeningResult, 'error')) return tokeningResult;\n const { tokens } = tokeningResult;\n\n // Capture any invalid/unexpected token patterns\n // NOTE: This doesn't handle mismatched parentheses. That is handled below in getPostfixFromInfix\n const badPatternError = findInvalidPatterns(tokens);\n if (badPatternError !== null) return { error: badPatternError };\n\n // Convert the Infix tokens to a Postfix notation using the ShuntingYard algorithm\n const postfixResult = getPostfixFromInfix(tokens);\n if (hasProp(postfixResult, 'error')) return postfixResult;\n const { postfixArr } = postfixResult;\n\n // Convert the Postfix token to a Condition tree\n return getConditionFromPostfix(postfixArr, conditionLookup, ignoreUnusedLabels);\n}\n\n/**\n * Takes a valid logic string and formats it with parentheses at appropriate places to keep things unambiguous\n * For example, `1 AND 2 OR 3` is disambiguated as `(1 AND 2) OR 3`\n * NOTE: This expects only valid logic strings to be passed as an input\n */\nexport function disambiguateLogic(expression: string): string {\n // Split the expression into individual tokens\n const tokeningResult = tokenizeExpression(expression);\n const { tokens } = tokeningResult as { tokens: string[] }; // Only valid expressions are expected as inputs\n\n // Convert the Infix tokens to a Postfix notation using the ShuntingYard algorithm\n const postfixResult = getPostfixFromInfix(tokens);\n const { postfixArr } = postfixResult as { postfixArr: string[] };\n\n // Convert the postfix back to infix with parentheses at appropriate places\n // To learn more about the below algorithm, refer this: https://brilliant.org/wiki/shunting-yard-algorithm/#reverse-polish\n const operandsStack: string[] = [];\n postfixArr.forEach(token => {\n if (isIntegerToken(token)) {\n // If it's a numeric token (leaf condition), push it to the stack\n operandsStack.push(token);\n } else if (token === NOT) {\n // If it's the NOT operator\n // Pop an operand, perform the operation and push the result back to the stack\n const operand = operandsStack.pop()!;\n operandsStack.push(`NOT ${operand}`);\n } else {\n // If it's the AND/OR operator\n // Pop two operands, perform the operation and push the result back to the stack\n let operand2 = operandsStack.pop()!;\n let operand1 = operandsStack.pop()!;\n\n // If the inner operation is the same as the current one, consolidate them\n // e.g. `1 AND (2 AND 3)` should be consolidated as `1 AND 2 AND 3`\n // e.g. `1 OR (2 OR 3)` should be consolidated as `1 OR 2 OR 3`\n if (token === 'AND') {\n // Remove any wrapping parentheses if an operand contains just AND(s)\n if (operand1.startsWith(LPAREN) && !operand1.includes(OR) && !operand1.includes(NOT)) {\n operand1 = operand1.slice(1, -1);\n }\n if (operand2.startsWith(LPAREN) && !operand2.includes(OR) && !operand2.includes(NOT)) {\n operand2 = operand2.slice(1, -1);\n }\n operandsStack.push(`(${operand1} AND ${operand2})`);\n } else {\n // Remove any wrapping parentheses if an operand contains just OR(s)\n if (operand1.startsWith(LPAREN) && !operand1.includes(AND) && !operand1.includes(NOT)) {\n operand1 = operand1.slice(1, -1);\n }\n if (operand2.startsWith(LPAREN) && !operand2.includes(AND) && !operand2.includes(NOT)) {\n operand2 = operand2.slice(1, -1);\n }\n operandsStack.push(`(${operand1} OR ${operand2})`);\n }\n }\n });\n\n // If the root node is AND/OR, there will be extra parentheses. Remove them\n let outputLogic = operandsStack[0];\n if (outputLogic.startsWith(LPAREN) && outputLogic.endsWith(RPAREN)) {\n outputLogic = outputLogic.slice(1, -1);\n }\n return outputLogic;\n}\n\n/**\n * Recursively splits the input condition node into a logic-string and a list of condition-rows\n * NOTE: Returns an empty string and an empty array if the condition is malformed\n */\nfunction splitConditionNode(\n node: Condition,\n labelsSoFar: string[]\n): { logic: string; rows: ConditionRow[] } {\n // Using a try-catch block for safety against any malformed conditions\n try {\n let logic: string;\n const rows: ConditionRow[] = [];\n\n if (hasProp(node, 'AND')) {\n const childStrings: string[] = [];\n node.AND.forEach(n => {\n const splitResult = splitConditionNode(n, labelsSoFar); // Recursively get child rows and logic\n childStrings.push(splitResult.logic);\n rows.push(...splitResult.rows);\n });\n logic = `(${childStrings.join(' AND ')})`;\n } else if (hasProp(node, 'OR')) {\n const childStrings: string[] = [];\n node.OR.forEach(n => {\n const splitResult = splitConditionNode(n, labelsSoFar); // Recursively get child rows and logic\n childStrings.push(splitResult.logic);\n rows.push(...splitResult.rows);\n });\n logic = `(${childStrings.join(' OR ')})`;\n } else if (hasProp(node, 'NOT')) {\n const splitResult = splitConditionNode(node.NOT, labelsSoFar); // Recursively get child rows and logic\n logic = `NOT ${splitResult.logic}`;\n rows.push(...splitResult.rows);\n } else {\n // If leaf-level is reached\n const newLabel = `${labelsSoFar.length + 1}`; // Get a new label for the node\n labelsSoFar.push(newLabel); // Update for the next time\n logic = newLabel;\n rows.push({ ...node.condition, label: newLabel, id: createUID() });\n }\n\n return { logic, rows };\n } catch {\n return { logic: '', rows: [] }; // For safety against any malformed conditions\n }\n}\n\n// Splitter for internal consumption\n/** Splits the input condition tree into a logic-string and a list of condition-rows */\nexport function splitConditionForBuilder(tree: Condition): { logic: string; rows: ConditionRow[] } {\n // Recursively split the tree, starting at the root node\n const splitResult = splitConditionNode(tree, []);\n\n // If the root node is AND/OR, there will be extra parentheses. Remove them\n if (splitResult.logic.startsWith(LPAREN) && splitResult.logic.endsWith(RPAREN)) {\n splitResult.logic = splitResult.logic.slice(1, -1);\n }\n\n return splitResult;\n}\n\n// Splitter for public consumption\n/** Converts the input nested condition into a flat tree with the leaf-conditions and a logic string representing the input tree */\nexport function splitConditionTree(\n tree: Condition,\n labelPrefix: string = ''\n): { logic: string; conditions: { [label: string]: LeafCondition } } {\n // Split using the internal splitter\n const { logic, rows } = splitConditionForBuilder(tree);\n\n // Build a condition-lookup from the ConditionRow objects\n const conditionLookup: { [label: string]: LeafCondition } = {};\n rows.forEach(row => {\n const { id, label, ...leaf } = row; // Discard the excess properties set up by ConditionRow when extending LeafCondition interface\n conditionLookup[`${labelPrefix}${label}`] = leaf;\n });\n\n // Prepend labelPrefix to all numeric tokens in the logic\n let outputLogic = logic;\n if (labelPrefix !== '') {\n outputLogic = logic.replace(/\\d+/g, `${labelPrefix}$&`);\n }\n\n return { logic: outputLogic, conditions: conditionLookup };\n}\n\n/** Checks if the input Condition is simple enough to be displayed in the `Basic mode` without loss of information */\nexport function isBasicModeApplicable(condition: Condition): boolean {\n // If an OR condition is present at the outer level,\n // each child should either be a leaf condition or an AND with all leaf nodes inside\n if (hasProp(condition, 'OR')) {\n return condition.OR.every(node => {\n if (hasProp(node, 'condition')) {\n return true;\n }\n if (hasProp(node, 'AND')) {\n return node.AND.every(subNode => hasProp(subNode, 'condition'));\n }\n return false;\n });\n }\n // If an AND condition is present at the outer level, it can't have any nested levels\n if (hasProp(condition, 'AND')) {\n return condition.AND.every(node => hasProp(node, 'condition'));\n }\n // NOT operator is not supported in Basic-mode\n // eslint-disable-next-line sonarjs/prefer-single-boolean-return\n if (hasProp(condition, 'NOT')) {\n return false;\n }\n // If a single leaf condition is present at the outer level\n return true;\n}\n\n/** Returns a list of operators to show in the Basic mode, using a logicString as the input */\nexport function getBasicModeOperators(logic: string): ('AND' | 'OR')[] {\n const matches = logic.match(/(AND|OR)/g);\n if (matches === null) {\n return [];\n }\n return matches as ('AND' | 'OR')[];\n}\n\n/**\n * Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them\n */\nexport function getLogicFromBasicMode(operatorsList: ('AND' | 'OR')[]): string {\n const logicString = operatorsList.reduce((logic, op, i) => `${logic} ${op} ${i + 2}`, '1');\n return disambiguateLogic(logicString); // Disambiguating the logic string by placing parentheses at appropriate places\n}\n\n/**\n * Takes a list of objects and id of the object to be found and recursively finds and returns the object\n */\nexport function getItem(items: Field[], id: string): Field | undefined {\n let found: Field | undefined;\n items.some(item => {\n if (item.id === id) {\n found = item;\n return true;\n }\n\n if (hasProp(item, 'items')) {\n found = getItem(item.items, id);\n return !!found;\n }\n\n return false;\n });\n\n return found;\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/components/ConditionBuilder/core/utils.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAI7D,MAAM,GAAG,GAAG,KAAK,CAAC;AAClB,MAAM,EAAE,GAAG,IAAI,CAAC;AAChB,MAAM,GAAG,GAAG,KAAK,CAAC;AAClB,MAAM,MAAM,GAAG,GAAG,CAAC;AACnB,MAAM,MAAM,GAAG,GAAG,CAAC;AAEnB,MAAM,aAAa,GAA6B,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,C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b;QAED,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;YAC1B,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAChC,OAAO,CAAC,CAAC,KAAK,CAAC;SAChB;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// cspell:words LPAREN LPARENs RPAREN RPARENs\nimport { createUID, hasProp } from '@pega/cosmos-react-core';\n\nimport { Condition, ConditionRow, LeafCondition, Field } from '../ConditionBuilder.types';\n\nconst AND = 'AND';\nconst OR = 'OR';\nconst NOT = 'NOT';\nconst LPAREN = '(';\nconst RPAREN = ')';\n\nconst precedenceMap: { [op: string]: number } = { OR: 1, AND: 2, NOT: 3 }; // Operator precedence. NOT has the highest precedence over the others\nconst operatorTokens = new Set([AND, OR, NOT]); // Valid logical operators\nconst validTokens = new Set([AND, OR, NOT, LPAREN, RPAREN]); // Other than these, integer tokens are valid\n\nconst isIntegerToken = (token: string): boolean => /^\\d+$/.test(token); // Checks if the input token is an integer\nconst isOperatorToken = (token: string): boolean => operatorTokens.has(token); // Checks if the input token is an operator\n\n/**\n * Tokenize the input expression.\n * Valid tokens are 'AND', 'OR', 'NOT', '(', ')' and any integer token.\n * Throws an error if an invalid token is found.\n */\nfunction tokenizeExpression(\n expression: string,\n disallowNOT: boolean = false\n): { tokens: string[] } | { error: string } {\n expression = expression.trim().toUpperCase(); // To simplify comparisons below; the tokens AND/OR/NOT are anyways expected to be in uppercase\n const words = expression.match(/[A-Z]+|[0-9]+|_|\\W/g); // Split contiguous alphabets and contiguous numbers into the same token. For all other characters, create a token for each character. Although `_` is not expected to be used, handling it just for completeness\n const tokens: string[] = []; // Final list of valid tokens\n const invalidWords: string[] = []; // Any invalid words are captured here\n\n // `words` will never be null because of the regex we used. Using `!` to indicate the same to TS\n words!.forEach(word => {\n // Ignore white-space characters\n if (word.trim().length > 0) {\n // If it's a token from the above Set or if it's an integer token\n if (isIntegerToken(word) || (validTokens.has(word) && !(word === NOT && disallowNOT))) {\n tokens.push(word);\n } else {\n invalidWords.push(word);\n }\n }\n });\n\n // Return an error if any invalid tokens are present\n if (invalidWords.length > 0) {\n return { error: `Unexpected words/characters: ${invalidWords.join(' ')}` }; // FIXME: TR\n }\n\n return { tokens };\n}\n\n/**\n * Captures any invalid/unexpected token patterns\n * NOTE: This does not expect any invalid tokens to be passed in the input\n * NOTE: This doesn't handle mismatched parentheses. That is handled separately in getPostfixFromInfix\n * Returns an error message about the first invalid sequence present in the input. Returns `null` if none found\n */\nfunction findInvalidPatterns(tokens: string[]): string | null {\n // These patterns are identified based on which token can precede/succeed which.\n // A table with all such permutations can be found in DOC-38200\n\n for (let i = 0; i < tokens.length; i += 1) {\n const NUMBER = 'NUMBER'; // To avoid repeating a string literal\n const token = tokens[i];\n const tokenType = isIntegerToken(token) ? NUMBER : token; // To simplify comparisons below\n\n // The expression can only start with NOT, LPAREN or NUMBER\n if (i === 0 && ![NOT, LPAREN, NUMBER].includes(tokenType)) {\n return `Unexpected \"${token}\" at the beginning.`; // FIXME: TR\n }\n\n // The expression can only end with RPAREN or NUMBER\n if (i === tokens.length - 1 && ![RPAREN, NUMBER].includes(tokenType)) {\n return `Unexpected \"${token}\" at the end.`; // FIXME: TR\n }\n\n // If there is a previous token, check if it is supposed to precede the current token\n if (i > 0) {\n const prevToken = tokens[i - 1];\n const prevTokenType = isIntegerToken(prevToken) ? NUMBER : prevToken; // To simplify comparisons below\n switch (tokenType) {\n // AND/OR/RPAREN can only be preceded by RPAREN or NUMBER\n case AND:\n case OR:\n case RPAREN:\n if (![RPAREN, NUMBER].includes(prevTokenType)) {\n return `Unexpected \"${token}\" after \"${prevToken}\"`; // FIXME: TR\n }\n break;\n\n // NOT/LPAREN/NUMBER can not be preceded by RPAREN or NUMBER\n case NOT:\n case LPAREN:\n case NUMBER:\n if ([RPAREN, NUMBER].includes(prevTokenType)) {\n return `Unexpected \"${token}\" after \"${prevToken}\"`; // FIXME: TR\n }\n break;\n default: // do nothing\n }\n }\n }\n\n // Return null if no invalid sequences\n return null;\n}\n\n/**\n * Converts an input array of Infix tokens into a Postfix array.\n * Uses the ShuntingYard algorithm.\n * NOTE: This does not expect any invalid tokens to be passed in the input\n */\nfunction getPostfixFromInfix(tokens: string[]): { postfixArr: string[] } | { error: string } {\n // Refer these for the ShuntingYard algorithm:\n // * https://brilliant.org/wiki/shunting-yard-algorithm/\n // * https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail\n const postfixQueue: string[] = []; // Output queue\n const stack: string[] = []; // Operations stack\n\n // While there are tokens to be read\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n\n if (isIntegerToken(token)) {\n // If it's a number add it to queue\n postfixQueue.push(token);\n } else if (isOperatorToken(token)) {\n // If it's an operator\n // While there's an operator on the top of the stack with greater precedence (or equal precedence and the token is left-associative), pop operators from the stack onto the output queue\n if (token !== NOT) {\n // Unary operators should not cause any operators to be popped from the stack.\n // See http://wcipeg.com/wiki/Shunting_yard_algorithm#Unary_operators\n while (stack.length > 0) {\n const stackTop = stack[stack.length - 1];\n if (isOperatorToken(stackTop) && precedenceMap[stackTop] >= precedenceMap[token]) {\n postfixQueue.push(stack.pop()!);\n } else {\n break;\n }\n }\n }\n // Push the current operator onto the stack\n stack.push(token);\n } else if (token === LPAREN) {\n // If it's a left parenthesis, push it onto the stack\n stack.push(token);\n } else {\n // If it's a right parenthesis (RPAREN)\n // While there's not a left parenthesis at the top of the stack, pop operators from the stack onto the output queue\n while (stack.length > 0) {\n const stackTop = stack[stack.length - 1];\n if (stackTop === LPAREN) break;\n postfixQueue.push(stack.pop()!);\n }\n\n // Pop the left parenthesis from the stack and discard it\n if (stack.length > 0) {\n stack.pop();\n } else {\n // FIXME: TR\n return { error: 'Please fix mismatched parentheses.' }; // If no LPAREN found for the current RPAREN\n }\n }\n }\n\n // While there are operators on the stack, pop them to the queue\n while (stack.length > 0) {\n if (stack[stack.length - 1] === LPAREN) {\n // FIXME: TR\n return { error: 'Please fix mismatched parentheses.' }; // If there were excess LPARENs. (Excess RPARENs are already handled in the above loop. Also, RPARENs are never pushed to the stack)\n }\n postfixQueue.push(stack.pop()!);\n }\n\n return { postfixArr: postfixQueue };\n}\n\n/**\n * Converts an input array of Postfix tokens into a Condition tree.\n * NOTE: This expects a properly formed Postfix array as input\n */\nfunction getConditionFromPostfix(\n postfixArr: string[],\n conditionLookup: { [label: string]: LeafCondition },\n ignoreUnusedLabels: boolean\n): { condition: Condition } | { error: string } {\n // To learn more about the below algorithm, refer this: https://brilliant.org/wiki/shunting-yard-algorithm/#reverse-polish\n const operandsStack: Condition[] = [];\n const labelsWithNoRows: string[] = []; // Labels for which there is no corresponding op in conditionLookup\n const usedLabels: string[] = []; // A list of all labels used in the condition. This is used to warn about any unused operations\n postfixArr.forEach(token => {\n if (isIntegerToken(token)) {\n // If it's a numeric token (leaf condition), push it to the stack\n const conditionRow = conditionLookup[token]; // Identify the corresponding condition row\n operandsStack.push({ condition: conditionRow }); // Push it even if null so that the conversion goes on smoothly and identifies any other issues\n if (!conditionRow) {\n labelsWithNoRows.push(token); // Mark it as missing\n } else {\n usedLabels.push(token); // Mark it as used\n }\n } else if (token === NOT) {\n // If it's the NOT operator\n // Pop an operand, perform the operation and push the result back to the stack\n const operand = operandsStack.pop()!;\n operandsStack.push({ NOT: operand });\n } else {\n // If it's the AND/OR operator\n // Pop two operands, perform the operation and push the result back to the stack\n const operand2 = operandsStack.pop()!;\n const operand1 = operandsStack.pop()!;\n\n // If the inner operation is the same as the current one, consolidate them\n // e.g. `1 AND (2 AND 3)` should be consolidated as `1 AND 2 AND 3`\n // e.g. `1 OR (2 OR 3)` should be consolidated as `1 OR 2 OR 3`\n if (token === 'AND') {\n const operands = [\n ...(hasProp(operand1, 'AND') ? operand1.AND : [operand1]),\n ...(hasProp(operand2, 'AND') ? operand2.AND : [operand2])\n ];\n operandsStack.push({ AND: operands });\n } else {\n const operands = [\n ...(hasProp(operand1, 'OR') ? operand1.OR : [operand1]),\n ...(hasProp(operand2, 'OR') ? operand2.OR : [operand2])\n ];\n operandsStack.push({ OR: operands });\n }\n }\n });\n\n // If any labels are used for which there are no corresponding condition-rows\n if (labelsWithNoRows.length > 0) {\n if (labelsWithNoRows.length === 1) {\n return {\n error: `Condition ${labelsWithNoRows[0]} used in the logical string is not defined.` // FIXME: TR\n };\n }\n return {\n error: `Conditions ${labelsWithNoRows.join(', ')} used in the logical string are not defined.` // FIXME: TR\n };\n }\n\n // Warn if any of the condition rows are unused\n if (!ignoreUnusedLabels) {\n const unusedLabels = Object.keys(conditionLookup).filter(l => !usedLabels.includes(l));\n if (unusedLabels.length > 0) {\n if (unusedLabels.length === 1) {\n return { error: `Condition ${unusedLabels[0]} is not used in the logic expression.` }; // FIXME: TR\n }\n return {\n error: `Conditions ${unusedLabels.join(', ')} are not used in the logic expression.` // FIXME: TR\n };\n }\n }\n\n return { condition: operandsStack[0] };\n}\n\n/** Parses a logic-expression into a condition object. */\nexport function parseLogicString(\n expression: string,\n conditionLookup: { [label: string]: LeafCondition }, // To look up condition-rows from the labels\n disallowNOT: boolean = false,\n ignoreUnusedLabels: boolean = false\n): { condition: Condition } | { error: string } {\n // Handle empty expressions\n if (!expression.trim().length) return { error: 'Please provide a logic expression.' }; // FIXME: TR\n\n // Split the expression into individual tokens\n const tokeningResult = tokenizeExpression(expression, disallowNOT);\n if (hasProp(tokeningResult, 'error')) return tokeningResult;\n const { tokens } = tokeningResult;\n\n // Capture any invalid/unexpected token patterns\n // NOTE: This doesn't handle mismatched parentheses. That is handled below in getPostfixFromInfix\n const badPatternError = findInvalidPatterns(tokens);\n if (badPatternError !== null) return { error: badPatternError };\n\n // Convert the Infix tokens to a Postfix notation using the ShuntingYard algorithm\n const postfixResult = getPostfixFromInfix(tokens);\n if (hasProp(postfixResult, 'error')) return postfixResult;\n const { postfixArr } = postfixResult;\n\n // Convert the Postfix token to a Condition tree\n return getConditionFromPostfix(postfixArr, conditionLookup, ignoreUnusedLabels);\n}\n\n/**\n * Takes a valid logic string and formats it with parentheses at appropriate places to keep things unambiguous\n * For example, `1 AND 2 OR 3` is disambiguated as `(1 AND 2) OR 3`\n * NOTE: This expects only valid logic strings to be passed as an input\n */\nexport function disambiguateLogic(expression: string): string {\n // Split the expression into individual tokens\n const tokeningResult = tokenizeExpression(expression);\n const { tokens } = tokeningResult as { tokens: string[] }; // Only valid expressions are expected as inputs\n\n // Convert the Infix tokens to a Postfix notation using the ShuntingYard algorithm\n const postfixResult = getPostfixFromInfix(tokens);\n const { postfixArr } = postfixResult as { postfixArr: string[] };\n\n // Convert the postfix back to infix with parentheses at appropriate places\n // To learn more about the below algorithm, refer this: https://brilliant.org/wiki/shunting-yard-algorithm/#reverse-polish\n const operandsStack: string[] = [];\n postfixArr.forEach(token => {\n if (isIntegerToken(token)) {\n // If it's a numeric token (leaf condition), push it to the stack\n operandsStack.push(token);\n } else if (token === NOT) {\n // If it's the NOT operator\n // Pop an operand, perform the operation and push the result back to the stack\n const operand = operandsStack.pop()!;\n operandsStack.push(`NOT ${operand}`);\n } else {\n // If it's the AND/OR operator\n // Pop two operands, perform the operation and push the result back to the stack\n let operand2 = operandsStack.pop()!;\n let operand1 = operandsStack.pop()!;\n\n // If the inner operation is the same as the current one, consolidate them\n // e.g. `1 AND (2 AND 3)` should be consolidated as `1 AND 2 AND 3`\n // e.g. `1 OR (2 OR 3)` should be consolidated as `1 OR 2 OR 3`\n if (token === 'AND') {\n // Remove any wrapping parentheses if an operand contains just AND(s)\n if (operand1.startsWith(LPAREN) && !operand1.includes(OR) && !operand1.includes(NOT)) {\n operand1 = operand1.slice(1, -1);\n }\n if (operand2.startsWith(LPAREN) && !operand2.includes(OR) && !operand2.includes(NOT)) {\n operand2 = operand2.slice(1, -1);\n }\n operandsStack.push(`(${operand1} AND ${operand2})`);\n } else {\n // Remove any wrapping parentheses if an operand contains just OR(s)\n if (operand1.startsWith(LPAREN) && !operand1.includes(AND) && !operand1.includes(NOT)) {\n operand1 = operand1.slice(1, -1);\n }\n if (operand2.startsWith(LPAREN) && !operand2.includes(AND) && !operand2.includes(NOT)) {\n operand2 = operand2.slice(1, -1);\n }\n operandsStack.push(`(${operand1} OR ${operand2})`);\n }\n }\n });\n\n // If the root node is AND/OR, there will be extra parentheses. Remove them\n let outputLogic = operandsStack[0];\n if (outputLogic.startsWith(LPAREN) && outputLogic.endsWith(RPAREN)) {\n outputLogic = outputLogic.slice(1, -1);\n }\n return outputLogic;\n}\n\n/**\n * Recursively splits the input condition node into a logic-string and a list of condition-rows\n * NOTE: Returns an empty string and an empty array if the condition is malformed\n */\nfunction splitConditionNode(\n node: Condition,\n labelsSoFar: string[]\n): { logic: string; rows: ConditionRow[] } {\n // Using a try-catch block for safety against any malformed conditions\n try {\n let logic: string;\n const rows: ConditionRow[] = [];\n\n if (hasProp(node, 'AND')) {\n const childStrings: string[] = [];\n node.AND.forEach(n => {\n const splitResult = splitConditionNode(n, labelsSoFar); // Recursively get child rows and logic\n childStrings.push(splitResult.logic);\n rows.push(...splitResult.rows);\n });\n logic = `(${childStrings.join(' AND ')})`;\n } else if (hasProp(node, 'OR')) {\n const childStrings: string[] = [];\n node.OR.forEach(n => {\n const splitResult = splitConditionNode(n, labelsSoFar); // Recursively get child rows and logic\n childStrings.push(splitResult.logic);\n rows.push(...splitResult.rows);\n });\n logic = `(${childStrings.join(' OR ')})`;\n } else if (hasProp(node, 'NOT')) {\n const splitResult = splitConditionNode(node.NOT, labelsSoFar); // Recursively get child rows and logic\n logic = `NOT ${splitResult.logic}`;\n rows.push(...splitResult.rows);\n } else {\n // If leaf-level is reached\n const newLabel = `${labelsSoFar.length + 1}`; // Get a new label for the node\n labelsSoFar.push(newLabel); // Update for the next time\n logic = newLabel;\n rows.push({ ...node.condition, label: newLabel, id: createUID() });\n }\n\n return { logic, rows };\n } catch {\n return { logic: '', rows: [] }; // For safety against any malformed conditions\n }\n}\n\n// Splitter for internal consumption\n/** Splits the input condition tree into a logic-string and a list of condition-rows */\nexport function splitConditionForBuilder(tree: Condition): { logic: string; rows: ConditionRow[] } {\n // Recursively split the tree, starting at the root node\n const splitResult = splitConditionNode(tree, []);\n\n // If the root node is AND/OR, there will be extra parentheses. Remove them\n if (splitResult.logic.startsWith(LPAREN) && splitResult.logic.endsWith(RPAREN)) {\n splitResult.logic = splitResult.logic.slice(1, -1);\n }\n\n return splitResult;\n}\n\n// Splitter for public consumption\n/** Converts the input nested condition into a flat tree with the leaf-conditions and a logic string representing the input tree */\nexport function splitConditionTree(\n tree: Condition,\n labelPrefix: string = ''\n): { logic: string; conditions: { [label: string]: LeafCondition } } {\n // Split using the internal splitter\n const { logic, rows } = splitConditionForBuilder(tree);\n\n // Build a condition-lookup from the ConditionRow objects\n const conditionLookup: { [label: string]: LeafCondition } = {};\n rows.forEach(row => {\n const { id, label, ...leaf } = row; // Discard the excess properties set up by ConditionRow when extending LeafCondition interface\n conditionLookup[`${labelPrefix}${label}`] = leaf;\n });\n\n // Prepend labelPrefix to all numeric tokens in the logic\n let outputLogic = logic;\n if (labelPrefix !== '') {\n outputLogic = logic.replace(/\\d+/g, `${labelPrefix}$&`);\n }\n\n return { logic: outputLogic, conditions: conditionLookup };\n}\n\n/** Checks if the input Condition is simple enough to be displayed in the `Basic mode` without loss of information */\nexport function isBasicModeApplicable(condition: Condition): boolean {\n // If an OR condition is present at the outer level,\n // each child should either be a leaf condition or an AND with all leaf nodes inside\n if (hasProp(condition, 'OR')) {\n return condition.OR.every(node => {\n if (hasProp(node, 'condition')) {\n return true;\n }\n if (hasProp(node, 'AND')) {\n return node.AND.every(subNode => hasProp(subNode, 'condition'));\n }\n return false;\n });\n }\n // If an AND condition is present at the outer level, it can't have any nested levels\n if (hasProp(condition, 'AND')) {\n return condition.AND.every(node => hasProp(node, 'condition'));\n }\n // NOT operator is not supported in Basic-mode\n // eslint-disable-next-line sonarjs/prefer-single-boolean-return\n if (hasProp(condition, 'NOT')) {\n return false;\n }\n // If a single leaf condition is present at the outer level\n return true;\n}\n\n/** Returns a list of operators to show in the Basic mode, using a logicString as the input */\nexport function getBasicModeOperators(logic: string): ('AND' | 'OR')[] {\n const matches = logic.match(/(AND|OR)/g);\n if (matches === null) {\n return [];\n }\n return matches as ('AND' | 'OR')[];\n}\n\n/** Takes a list of operators from between the Basic mode rows and constructs a logic-string out of them */\nexport function getLogicFromBasicMode(operatorsList: ('AND' | 'OR')[]): string {\n const logicString = operatorsList.reduce((logic, op, i) => `${logic} ${op} ${i + 2}`, '1');\n return disambiguateLogic(logicString); // Disambiguating the logic string by placing parentheses at appropriate places\n}\n\n/** Takes a list of objects and id of the object to be found and recursively finds and returns the object */\nexport function getItem(items: Field[], id: string): Field | undefined {\n let found: Field | undefined;\n items.some(item => {\n if (item.id === id) {\n found = item;\n return true;\n }\n\n if (hasProp(item, 'items')) {\n found = getItem(item.items, id);\n return !!found;\n }\n\n return false;\n });\n\n return found;\n}\n"]}
@@ -221,7 +221,7 @@ const ConditionInput = forwardRef(({ field: fieldProp, condition: conditionProp,
221
221
  : undefined, onChange: handleDateRangeValueChange, onBlur: handleDateRangeBlur, status: status, info: status === 'error' ? t('condition_builder_invalid_date_range') : undefined, handle: clearHandle }));
222
222
  break;
223
223
  case 'PICKLIST':
224
- defaultControl = (_jsx(ValueSelector, { label: flat ? undefined : label, mode: 'multi-select', values: inputValue ?? [], selectedField: fieldProp, comparator: condition?.comparator ?? defaultComparators[fieldType], onChange: value => {
224
+ defaultControl = (_jsx(ValueSelector, { label: flat ? undefined : label, mode: 'multi-select', values: inputValue ?? [], selectedField: { id: fieldName, ...fieldProp }, comparator: condition?.comparator ?? defaultComparators[fieldType], onChange: value => {
225
225
  setInputValue(value.length > 0 ? value : undefined);
226
226
  }, onBlur: handleBlur, onClear: clear, placeholder: t('all'), parameters: [], rhs: { values: [] }, handle: clearHandle }));
227
227
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"ConditionInput.js","sourceRoot":"","sources":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AC,KAAK,CAAC,EACrB,GAAG,EAAE,GAAG,GACR,CACH,CAAC;KACH;IAED,OAAO,cAAc,CAAC;AACxB,CAAC,CACF,CAAC;AAEF,eAAe,cAAc,CAAC","sourcesContent":["import {\n forwardRef,\n FunctionComponent,\n PropsWithoutRef,\n useState,\n ChangeEvent,\n useEffect,\n useImperativeHandle,\n useRef\n} from 'react';\n\nimport {\n CompositeInput,\n CompositeInputProps,\n ForwardProps,\n hasProp,\n Input,\n RadioButton,\n useI18n,\n useConfiguration,\n DateRangeInput,\n TimeRangeInput,\n useUID,\n NumberRangeInput,\n RadioButtonGroup,\n FormControlProps,\n HandleValue\n} from '@pega/cosmos-react-core';\nimport {\n DateRangeCallbackParameter,\n DateTimeCallbackParameter\n} from '@pega/cosmos-react-core/lib/components/DateTime/DateTime.types';\n\nimport type { ComparatorsByType, RHSType } from '../ConditionBuilder/core/types';\nimport AtomicCondition, {\n AtomicConditionProps,\n getInitConditionForLhs,\n isValidCondition\n} from '../ConditionBuilder/AtomicCondition';\nimport formatCondition from '../ConditionBuilder/core/formatter';\nimport type {\n DateFunctionsByType,\n Field,\n LeafCondition\n} from '../ConditionBuilder/ConditionBuilder.types';\nimport ValueSelector from '../ConditionBuilder/RhsControls/ValueSelector';\nimport { truncateISODateString } from '../ConditionBuilder/RhsControls';\nimport { convertTimeValueToMs } from '../ConditionBuilder/core/time-utils';\n\nimport type { ConditionInputProps } from './ConditionInput.types';\nimport {\n StyledVerticalAtomicCondition,\n StyledConditionRadioGroup,\n StyledVerticalFieldGroup\n} from './ConditionInput.styles';\nimport {\n basicFieldMap,\n defaultComparators,\n compareValues,\n compareRangeValues,\n compareCondition\n} from './utils';\n\nconst isDateValid = (dateTimeParam: DateTimeCallbackParameter) => {\n return dateTimeParam.valueAsISOString && !dateTimeParam.state;\n};\n\nconst validRhsTypes = new Set<RHSType>(['LITERAL', 'RELATIVE_DATE', 'DATE_FUNCTION']);\n\nconst dateFunctions: DateFunctionsByType = {\n DATE_TIME: [\n 'YEARS',\n 'QUARTERS',\n 'MONTHS',\n 'WEEKS',\n 'DAYS',\n 'HOURS',\n 'MINUTES',\n 'SECONDS',\n 'MONTHS_OF_YEAR',\n 'DAYS_OF_MONTH',\n 'DAYS_OF_WEEK',\n 'HOURS_OF_DAY'\n ],\n DATE_ONLY: [\n 'YEARS',\n 'QUARTERS',\n 'MONTHS',\n 'WEEKS',\n 'MONTHS_OF_YEAR',\n 'DAYS_OF_MONTH',\n 'DAYS_OF_WEEK'\n ]\n};\n\nconst ConditionInput: FunctionComponent<ConditionInputProps & ForwardProps> = forwardRef(\n (\n {\n field: fieldProp,\n condition: conditionProp,\n label,\n mode,\n onChange,\n flat = false,\n handle\n }: PropsWithoutRef<ConditionInputProps>,\n ref: ConditionInputProps['ref']\n ) => {\n const id = useUID();\n const t = useI18n();\n const { locale } = useConfiguration();\n\n const { name: fieldName, type: fieldType } = fieldProp;\n const basicType = basicFieldMap[fieldType] ?? fieldType;\n\n const field: Field = {\n id: fieldName,\n type: basicType,\n primary: label ?? fieldName\n };\n\n const fields: AtomicConditionProps['fields'] = [field];\n\n const createConditionForDefaultMode = (value: string | string[]): LeafCondition => {\n let valueObj: LeafCondition['rhs'];\n if (Array.isArray(value)) valueObj = { values: value };\n else valueObj = { value };\n\n return {\n lhs: { field: fieldName },\n comparator: defaultComparators[fieldType],\n rhs: valueObj\n };\n };\n\n const convertDateTimeValue = (range: DateRangeCallbackParameter) => {\n if (!isDateValid(range.start) || !isDateValid(range.end)) return undefined;\n\n const truncatedStartValue = truncateISODateString(\n range.start.valueAsISOString ?? '',\n basicType\n );\n const truncatedEndValue = truncateISODateString(range.end.valueAsISOString ?? '', basicType);\n return {\n start:\n fieldType === 'TIME_ONLY'\n ? convertTimeValueToMs(truncatedStartValue)\n : truncatedStartValue,\n end: fieldType === 'TIME_ONLY' ? convertTimeValueToMs(truncatedEndValue) : truncatedEndValue\n };\n };\n\n const createConditionForRange = (\n value:\n | {\n start: string | number | undefined;\n end: string | number | undefined;\n }\n | undefined\n ): LeafCondition | undefined => {\n if (!value || value.start === undefined || value.end === undefined) return;\n\n return {\n lhs: { field: fieldName },\n comparator: defaultComparators[fieldType],\n // undefined checked before, type added to satisfy typescript\n rhs: { ...value } as { start: string | number; end: string | number }\n };\n };\n\n const validComparators: ComparatorsByType[] | undefined =\n fieldType === 'PICKLIST' ? [{ type: 'TEXT', comparators: ['IN'] }] : undefined;\n\n const condition =\n conditionProp ??\n (fieldType === 'BOOLEAN'\n ? undefined\n : getInitConditionForLhs(\n { field: fieldName },\n fields,\n new Set(['LITERAL']),\n validComparators\n ));\n\n const [newCondition, setNewCondition] = useState<LeafCondition | undefined>(condition);\n\n // holds current status of condition to control if invalid values are kept in forms and errors are displaying\n const newConditionStatus = useRef<'error' | undefined>(undefined);\n\n // status of the form control\n const [status, setStatus] = useState<FormControlProps['status']>(undefined);\n\n let rhsValue: string | string[] | undefined = fieldType === 'PICKLIST' ? [] : undefined;\n let rhsRangeValue:\n | { start: string | number | undefined; end: string | number | undefined }\n | undefined;\n\n if (condition?.rhs) {\n if (hasProp(condition.rhs, 'value')) {\n rhsValue = condition.rhs.value.toString();\n } else if (hasProp(condition.rhs, 'values')) {\n rhsValue = condition.rhs.values.map(String);\n } else if (hasProp(condition.rhs, 'start')) {\n rhsRangeValue = { start: condition.rhs.start, end: condition.rhs.end };\n }\n }\n\n const [inputValue, setInputValue] = useState(rhsValue);\n const [rangeInputValue, setRangeInputValue] = useState(rhsRangeValue);\n\n useEffect(() => {\n // condition state is updated only when condition status is valid\n // allows to keep invalid values in inputs\n if (!newConditionStatus.current) setNewCondition(condition);\n setInputValue(rhsValue);\n setRangeInputValue(rhsRangeValue);\n }, [conditionProp]);\n\n const handleBlur = () => {\n const newValue = typeof inputValue === 'string' ? inputValue.trim() : inputValue;\n // trigger onChange only when value has changed\n if (!compareValues(rhsValue, newValue)) {\n onChange(newValue ? createConditionForDefaultMode(newValue) : undefined);\n }\n };\n\n const handleRangeUpdate = (newRangeValue?: {\n start: string | number | undefined;\n end: string | number | undefined;\n }) => {\n // trigger onChange only when value has changed\n if (!compareRangeValues(rhsRangeValue, newRangeValue)) {\n onChange(createConditionForRange(newRangeValue));\n }\n };\n\n const handleRangeBlur = (newRangeValue?: {\n start: string | number | undefined;\n end: string | number | undefined;\n }) => {\n // if both values are undefined, condition is treated as undefined\n // if only one value is undefined, condition is treated as invalid\n if (\n newRangeValue &&\n ((newRangeValue.start === undefined && newRangeValue.end !== undefined) ||\n (newRangeValue.end === undefined && newRangeValue.start !== undefined))\n ) {\n setStatus('error');\n } else {\n setStatus(undefined);\n }\n\n handleRangeUpdate(newRangeValue);\n };\n\n const handleDateRangeBlur = (newRangeValue: DateRangeCallbackParameter) => {\n // if both timestamps are undefined, condition is treated as undefined\n // if only one value is undefined, or any of them is invalid, then condition is treated as invalid\n if (\n (newRangeValue.start.valueAsTimestamp !== undefined ||\n newRangeValue.end.valueAsTimestamp !== undefined) &&\n (!isDateValid(newRangeValue.start) || !isDateValid(newRangeValue.end))\n ) {\n setStatus('error');\n } else {\n setStatus(undefined);\n }\n\n handleRangeUpdate(convertDateTimeValue(newRangeValue));\n };\n\n const onRadioButtonChange = (value?: boolean) => {\n const updatedCondition: LeafCondition | undefined =\n value === undefined\n ? undefined\n : {\n lhs: { field: fieldName },\n comparator: value ? 'IS_TRUE' : 'IS_FALSE'\n };\n onChange(updatedCondition);\n };\n\n const clearHandle = useRef<HandleValue>(null);\n\n const clear = () => {\n onChange(undefined);\n setNewCondition(undefined);\n setRangeInputValue(undefined);\n newConditionStatus.current = undefined;\n setStatus(undefined);\n if (clearHandle.current) clearHandle.current.clear();\n };\n\n useImperativeHandle(\n handle,\n () => ({\n clear\n }),\n [clear]\n );\n\n const handleDateRangeValueChange = (value: DateRangeCallbackParameter) => {\n setRangeInputValue({\n start: value.start.valueAsISOString || undefined,\n end: value.end.valueAsISOString || undefined\n });\n };\n\n const showAdvanced = mode === 'advanced' && fieldType !== 'BOOLEAN' && fieldType !== 'PICKLIST';\n\n let defaultControl: JSX.Element | null = null;\n\n const valueToSet = typeof inputValue === 'string' ? inputValue : undefined;\n\n if (!showAdvanced) {\n switch (fieldType) {\n case 'INTEGER':\n case 'DECIMAL':\n case 'PERCENTAGE':\n case 'CURRENCY':\n defaultControl = (\n <NumberRangeInput\n id={id}\n label={label}\n labelHidden={flat}\n ref={ref}\n value={{\n start: rangeInputValue?.start?.toString() ?? '',\n end: rangeInputValue?.end?.toString() ?? ''\n }}\n onChange={setRangeInputValue}\n onBlur={newRangeValue => {\n handleRangeBlur({\n start: newRangeValue.start ? Number(newRangeValue.start) : undefined,\n end: newRangeValue.end ? Number(newRangeValue.end) : undefined\n });\n }}\n numberOfDecimals={fieldType === 'INTEGER' ? 0 : undefined}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_number_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'BOOLEAN':\n defaultControl = (\n <RadioButtonGroup\n as={StyledConditionRadioGroup}\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n name={fieldName}\n inline\n >\n <RadioButton\n label={t('show_all')}\n checked={condition === undefined}\n onChange={() => onRadioButtonChange()}\n />\n <RadioButton\n label={t('boolean_display_true_label')}\n checked={condition?.comparator === 'IS_TRUE'}\n onChange={() => onRadioButtonChange(true)}\n />\n <RadioButton\n label={t('boolean_display_false_label')}\n checked={condition?.comparator === 'IS_FALSE'}\n onChange={() => onRadioButtonChange(false)}\n />\n </RadioButtonGroup>\n );\n break;\n case 'DATE_ONLY':\n defaultControl = (\n <DateRangeInput\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n fromLabel=''\n toLabel=''\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_date_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'TIME_ONLY':\n defaultControl = (\n <TimeRangeInput\n id={id}\n ref={ref}\n mode='time'\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_time_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'DATE_TIME':\n defaultControl = (\n <TimeRangeInput\n id={id}\n ref={ref}\n mode='datetime'\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_date_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'PICKLIST':\n defaultControl = (\n <ValueSelector\n label={flat ? undefined : label}\n mode='multi-select'\n values={inputValue ?? []}\n selectedField={fieldProp}\n comparator={condition?.comparator ?? defaultComparators[fieldType]}\n onChange={value => {\n setInputValue(value.length > 0 ? value : undefined);\n }}\n onBlur={handleBlur}\n onClear={clear}\n placeholder={t('all')}\n parameters={[]}\n rhs={{ values: [] }}\n handle={clearHandle}\n />\n );\n break;\n case 'TEXT':\n case 'EMAIL':\n case 'URL':\n case 'PHONE':\n default:\n defaultControl = (\n <Input\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n value={valueToSet}\n onChange={(e: ChangeEvent<HTMLInputElement>) => setInputValue(e.target.value)}\n onBlur={handleBlur}\n />\n );\n break;\n }\n }\n\n const dialog: CompositeInputProps<AtomicConditionProps & ForwardProps>['dialog'] = {\n renderer: AtomicCondition,\n rendererProps: {\n condition:\n newCondition ??\n getInitConditionForLhs({ field: fieldName }, fields, new Set(['LITERAL'])),\n fields,\n onChange: setNewCondition,\n itemDirection: 'column',\n lhsMode: 'hidden',\n validRhsTypes,\n dateFunctions,\n indicateErrors: !!status\n },\n onCancel: ({ close }) => {\n setNewCondition(condition);\n setStatus(undefined);\n close();\n },\n onApply: ({ close }) => {\n setStatus(undefined);\n\n if (newCondition === undefined || isValidCondition(newCondition, fields, true)) {\n onChange(newCondition);\n close();\n } else {\n setStatus('error');\n }\n }\n };\n\n if (flat) {\n return showAdvanced ? (\n <StyledVerticalAtomicCondition\n collapsible\n actions={[{ id: 'clear', text: t('clear'), onClick: clear }]}\n condition={\n newCondition ??\n getInitConditionForLhs({ field: fieldName }, fields, new Set(['LITERAL']))\n }\n onBlur={(value: LeafCondition) => {\n // comparing with conditionProp as it is not initialized as default condition\n if (!compareCondition(value, conditionProp)) {\n onChange(value);\n }\n\n setStatus(newConditionStatus.current);\n }}\n onChange={(value: LeafCondition, conditionStatus?: 'error') => {\n newConditionStatus.current = conditionStatus;\n setNewCondition(value);\n }}\n fields={fields}\n itemDirection='column'\n lhsMode='label'\n validRhsTypes={validRhsTypes}\n dateFunctions={dateFunctions}\n indicateErrors={status === 'error'}\n ref={ref}\n handle={clearHandle}\n />\n ) : (\n <StyledVerticalFieldGroup\n name={label}\n collapsible\n actions={[{ id: 'clear', text: t('clear'), onClick: clear }]}\n >\n {defaultControl}\n </StyledVerticalFieldGroup>\n );\n }\n\n if (showAdvanced) {\n return (\n <CompositeInput\n dialog={dialog}\n label={label}\n onClear={clear}\n value={\n conditionProp\n ? formatCondition({ condition: conditionProp }, fields, t, {\n locale,\n omitLhs: true\n })\n : undefined\n }\n placeholder={t('all')}\n ref={ref}\n />\n );\n }\n\n return defaultControl;\n }\n);\n\nexport default ConditionInput;\n"]}
1
+ {"version":3,"file":"ConditionInput.js","sourceRoot":"","sources":["../../../src/components/ConditionInput/ConditionInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,UAAU,EAGV,QAAQ,EAER,SAAS,EACT,mBAAmB,EACnB,MAAM,EACP,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,cAAc,EAGd,OAAO,EACP,KAAK,EACL,WAAW,EACX,OAAO,EACP,gBAAgB,EAChB,cAAc,EACd,cAAc,EACd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\n useImperativeHandle,\n useRef\n} from 'react';\n\nimport {\n CompositeInput,\n CompositeInputProps,\n ForwardProps,\n hasProp,\n Input,\n RadioButton,\n useI18n,\n useConfiguration,\n DateRangeInput,\n TimeRangeInput,\n useUID,\n NumberRangeInput,\n RadioButtonGroup,\n FormControlProps,\n HandleValue\n} from '@pega/cosmos-react-core';\nimport {\n DateRangeCallbackParameter,\n DateTimeCallbackParameter\n} from '@pega/cosmos-react-core/lib/components/DateTime/DateTime.types';\n\nimport type { ComparatorsByType, RHSType } from '../ConditionBuilder/core/types';\nimport AtomicCondition, {\n AtomicConditionProps,\n getInitConditionForLhs,\n isValidCondition\n} from '../ConditionBuilder/AtomicCondition';\nimport formatCondition from '../ConditionBuilder/core/formatter';\nimport type {\n DateFunctionsByType,\n Field,\n LeafCondition\n} from '../ConditionBuilder/ConditionBuilder.types';\nimport ValueSelector from '../ConditionBuilder/RhsControls/ValueSelector';\nimport { truncateISODateString } from '../ConditionBuilder/RhsControls';\nimport { convertTimeValueToMs } from '../ConditionBuilder/core/time-utils';\n\nimport type { ConditionInputProps } from './ConditionInput.types';\nimport {\n StyledVerticalAtomicCondition,\n StyledConditionRadioGroup,\n StyledVerticalFieldGroup\n} from './ConditionInput.styles';\nimport {\n basicFieldMap,\n defaultComparators,\n compareValues,\n compareRangeValues,\n compareCondition\n} from './utils';\n\nconst isDateValid = (dateTimeParam: DateTimeCallbackParameter) => {\n return dateTimeParam.valueAsISOString && !dateTimeParam.state;\n};\n\nconst validRhsTypes = new Set<RHSType>(['LITERAL', 'RELATIVE_DATE', 'DATE_FUNCTION']);\n\nconst dateFunctions: DateFunctionsByType = {\n DATE_TIME: [\n 'YEARS',\n 'QUARTERS',\n 'MONTHS',\n 'WEEKS',\n 'DAYS',\n 'HOURS',\n 'MINUTES',\n 'SECONDS',\n 'MONTHS_OF_YEAR',\n 'DAYS_OF_MONTH',\n 'DAYS_OF_WEEK',\n 'HOURS_OF_DAY'\n ],\n DATE_ONLY: [\n 'YEARS',\n 'QUARTERS',\n 'MONTHS',\n 'WEEKS',\n 'MONTHS_OF_YEAR',\n 'DAYS_OF_MONTH',\n 'DAYS_OF_WEEK'\n ]\n};\n\nconst ConditionInput: FunctionComponent<ConditionInputProps & ForwardProps> = forwardRef(\n (\n {\n field: fieldProp,\n condition: conditionProp,\n label,\n mode,\n onChange,\n flat = false,\n handle\n }: PropsWithoutRef<ConditionInputProps>,\n ref: ConditionInputProps['ref']\n ) => {\n const id = useUID();\n const t = useI18n();\n const { locale } = useConfiguration();\n\n const { name: fieldName, type: fieldType } = fieldProp;\n const basicType = basicFieldMap[fieldType] ?? fieldType;\n\n const field: Field = {\n id: fieldName,\n type: basicType,\n primary: label ?? fieldName\n };\n\n const fields: AtomicConditionProps['fields'] = [field];\n\n const createConditionForDefaultMode = (value: string | string[]): LeafCondition => {\n let valueObj: LeafCondition['rhs'];\n if (Array.isArray(value)) valueObj = { values: value };\n else valueObj = { value };\n\n return {\n lhs: { field: fieldName },\n comparator: defaultComparators[fieldType],\n rhs: valueObj\n };\n };\n\n const convertDateTimeValue = (range: DateRangeCallbackParameter) => {\n if (!isDateValid(range.start) || !isDateValid(range.end)) return undefined;\n\n const truncatedStartValue = truncateISODateString(\n range.start.valueAsISOString ?? '',\n basicType\n );\n const truncatedEndValue = truncateISODateString(range.end.valueAsISOString ?? '', basicType);\n return {\n start:\n fieldType === 'TIME_ONLY'\n ? convertTimeValueToMs(truncatedStartValue)\n : truncatedStartValue,\n end: fieldType === 'TIME_ONLY' ? convertTimeValueToMs(truncatedEndValue) : truncatedEndValue\n };\n };\n\n const createConditionForRange = (\n value:\n | {\n start: string | number | undefined;\n end: string | number | undefined;\n }\n | undefined\n ): LeafCondition | undefined => {\n if (!value || value.start === undefined || value.end === undefined) return;\n\n return {\n lhs: { field: fieldName },\n comparator: defaultComparators[fieldType],\n // undefined checked before, type added to satisfy typescript\n rhs: { ...value } as { start: string | number; end: string | number }\n };\n };\n\n const validComparators: ComparatorsByType[] | undefined =\n fieldType === 'PICKLIST' ? [{ type: 'TEXT', comparators: ['IN'] }] : undefined;\n\n const condition =\n conditionProp ??\n (fieldType === 'BOOLEAN'\n ? undefined\n : getInitConditionForLhs(\n { field: fieldName },\n fields,\n new Set(['LITERAL']),\n validComparators\n ));\n\n const [newCondition, setNewCondition] = useState<LeafCondition | undefined>(condition);\n\n // holds current status of condition to control if invalid values are kept in forms and errors are displaying\n const newConditionStatus = useRef<'error' | undefined>(undefined);\n\n // status of the form control\n const [status, setStatus] = useState<FormControlProps['status']>(undefined);\n\n let rhsValue: string | string[] | undefined = fieldType === 'PICKLIST' ? [] : undefined;\n let rhsRangeValue:\n | { start: string | number | undefined; end: string | number | undefined }\n | undefined;\n\n if (condition?.rhs) {\n if (hasProp(condition.rhs, 'value')) {\n rhsValue = condition.rhs.value.toString();\n } else if (hasProp(condition.rhs, 'values')) {\n rhsValue = condition.rhs.values.map(String);\n } else if (hasProp(condition.rhs, 'start')) {\n rhsRangeValue = { start: condition.rhs.start, end: condition.rhs.end };\n }\n }\n\n const [inputValue, setInputValue] = useState(rhsValue);\n const [rangeInputValue, setRangeInputValue] = useState(rhsRangeValue);\n\n useEffect(() => {\n // condition state is updated only when condition status is valid\n // allows to keep invalid values in inputs\n if (!newConditionStatus.current) setNewCondition(condition);\n setInputValue(rhsValue);\n setRangeInputValue(rhsRangeValue);\n }, [conditionProp]);\n\n const handleBlur = () => {\n const newValue = typeof inputValue === 'string' ? inputValue.trim() : inputValue;\n // trigger onChange only when value has changed\n if (!compareValues(rhsValue, newValue)) {\n onChange(newValue ? createConditionForDefaultMode(newValue) : undefined);\n }\n };\n\n const handleRangeUpdate = (newRangeValue?: {\n start: string | number | undefined;\n end: string | number | undefined;\n }) => {\n // trigger onChange only when value has changed\n if (!compareRangeValues(rhsRangeValue, newRangeValue)) {\n onChange(createConditionForRange(newRangeValue));\n }\n };\n\n const handleRangeBlur = (newRangeValue?: {\n start: string | number | undefined;\n end: string | number | undefined;\n }) => {\n // if both values are undefined, condition is treated as undefined\n // if only one value is undefined, condition is treated as invalid\n if (\n newRangeValue &&\n ((newRangeValue.start === undefined && newRangeValue.end !== undefined) ||\n (newRangeValue.end === undefined && newRangeValue.start !== undefined))\n ) {\n setStatus('error');\n } else {\n setStatus(undefined);\n }\n\n handleRangeUpdate(newRangeValue);\n };\n\n const handleDateRangeBlur = (newRangeValue: DateRangeCallbackParameter) => {\n // if both timestamps are undefined, condition is treated as undefined\n // if only one value is undefined, or any of them is invalid, then condition is treated as invalid\n if (\n (newRangeValue.start.valueAsTimestamp !== undefined ||\n newRangeValue.end.valueAsTimestamp !== undefined) &&\n (!isDateValid(newRangeValue.start) || !isDateValid(newRangeValue.end))\n ) {\n setStatus('error');\n } else {\n setStatus(undefined);\n }\n\n handleRangeUpdate(convertDateTimeValue(newRangeValue));\n };\n\n const onRadioButtonChange = (value?: boolean) => {\n const updatedCondition: LeafCondition | undefined =\n value === undefined\n ? undefined\n : {\n lhs: { field: fieldName },\n comparator: value ? 'IS_TRUE' : 'IS_FALSE'\n };\n onChange(updatedCondition);\n };\n\n const clearHandle = useRef<HandleValue>(null);\n\n const clear = () => {\n onChange(undefined);\n setNewCondition(undefined);\n setRangeInputValue(undefined);\n newConditionStatus.current = undefined;\n setStatus(undefined);\n if (clearHandle.current) clearHandle.current.clear();\n };\n\n useImperativeHandle(\n handle,\n () => ({\n clear\n }),\n [clear]\n );\n\n const handleDateRangeValueChange = (value: DateRangeCallbackParameter) => {\n setRangeInputValue({\n start: value.start.valueAsISOString || undefined,\n end: value.end.valueAsISOString || undefined\n });\n };\n\n const showAdvanced = mode === 'advanced' && fieldType !== 'BOOLEAN' && fieldType !== 'PICKLIST';\n\n let defaultControl: JSX.Element | null = null;\n\n const valueToSet = typeof inputValue === 'string' ? inputValue : undefined;\n\n if (!showAdvanced) {\n switch (fieldType) {\n case 'INTEGER':\n case 'DECIMAL':\n case 'PERCENTAGE':\n case 'CURRENCY':\n defaultControl = (\n <NumberRangeInput\n id={id}\n label={label}\n labelHidden={flat}\n ref={ref}\n value={{\n start: rangeInputValue?.start?.toString() ?? '',\n end: rangeInputValue?.end?.toString() ?? ''\n }}\n onChange={setRangeInputValue}\n onBlur={newRangeValue => {\n handleRangeBlur({\n start: newRangeValue.start ? Number(newRangeValue.start) : undefined,\n end: newRangeValue.end ? Number(newRangeValue.end) : undefined\n });\n }}\n numberOfDecimals={fieldType === 'INTEGER' ? 0 : undefined}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_number_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'BOOLEAN':\n defaultControl = (\n <RadioButtonGroup\n as={StyledConditionRadioGroup}\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n name={fieldName}\n inline\n >\n <RadioButton\n label={t('show_all')}\n checked={condition === undefined}\n onChange={() => onRadioButtonChange()}\n />\n <RadioButton\n label={t('boolean_display_true_label')}\n checked={condition?.comparator === 'IS_TRUE'}\n onChange={() => onRadioButtonChange(true)}\n />\n <RadioButton\n label={t('boolean_display_false_label')}\n checked={condition?.comparator === 'IS_FALSE'}\n onChange={() => onRadioButtonChange(false)}\n />\n </RadioButtonGroup>\n );\n break;\n case 'DATE_ONLY':\n defaultControl = (\n <DateRangeInput\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n fromLabel=''\n toLabel=''\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_date_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'TIME_ONLY':\n defaultControl = (\n <TimeRangeInput\n id={id}\n ref={ref}\n mode='time'\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_time_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'DATE_TIME':\n defaultControl = (\n <TimeRangeInput\n id={id}\n ref={ref}\n mode='datetime'\n label={label}\n labelHidden={flat}\n value={\n rangeInputValue\n ? { start: rangeInputValue.start, end: rangeInputValue.end }\n : undefined\n }\n onChange={handleDateRangeValueChange}\n onBlur={handleDateRangeBlur}\n status={status}\n info={status === 'error' ? t('condition_builder_invalid_date_range') : undefined}\n handle={clearHandle}\n />\n );\n break;\n case 'PICKLIST':\n defaultControl = (\n <ValueSelector\n label={flat ? undefined : label}\n mode='multi-select'\n values={inputValue ?? []}\n selectedField={{ id: fieldName, ...fieldProp }}\n comparator={condition?.comparator ?? defaultComparators[fieldType]}\n onChange={value => {\n setInputValue(value.length > 0 ? value : undefined);\n }}\n onBlur={handleBlur}\n onClear={clear}\n placeholder={t('all')}\n parameters={[]}\n rhs={{ values: [] }}\n handle={clearHandle}\n />\n );\n break;\n case 'TEXT':\n case 'EMAIL':\n case 'URL':\n case 'PHONE':\n default:\n defaultControl = (\n <Input\n id={id}\n ref={ref}\n label={label}\n labelHidden={flat}\n value={valueToSet}\n onChange={(e: ChangeEvent<HTMLInputElement>) => setInputValue(e.target.value)}\n onBlur={handleBlur}\n />\n );\n break;\n }\n }\n\n const dialog: CompositeInputProps<AtomicConditionProps & ForwardProps>['dialog'] = {\n renderer: AtomicCondition,\n rendererProps: {\n condition:\n newCondition ??\n getInitConditionForLhs({ field: fieldName }, fields, new Set(['LITERAL'])),\n fields,\n onChange: setNewCondition,\n itemDirection: 'column',\n lhsMode: 'hidden',\n validRhsTypes,\n dateFunctions,\n indicateErrors: !!status\n },\n onCancel: ({ close }) => {\n setNewCondition(condition);\n setStatus(undefined);\n close();\n },\n onApply: ({ close }) => {\n setStatus(undefined);\n\n if (newCondition === undefined || isValidCondition(newCondition, fields, true)) {\n onChange(newCondition);\n close();\n } else {\n setStatus('error');\n }\n }\n };\n\n if (flat) {\n return showAdvanced ? (\n <StyledVerticalAtomicCondition\n collapsible\n actions={[{ id: 'clear', text: t('clear'), onClick: clear }]}\n condition={\n newCondition ??\n getInitConditionForLhs({ field: fieldName }, fields, new Set(['LITERAL']))\n }\n onBlur={(value: LeafCondition) => {\n // comparing with conditionProp as it is not initialized as default condition\n if (!compareCondition(value, conditionProp)) {\n onChange(value);\n }\n\n setStatus(newConditionStatus.current);\n }}\n onChange={(value: LeafCondition, conditionStatus?: 'error') => {\n newConditionStatus.current = conditionStatus;\n setNewCondition(value);\n }}\n fields={fields}\n itemDirection='column'\n lhsMode='label'\n validRhsTypes={validRhsTypes}\n dateFunctions={dateFunctions}\n indicateErrors={status === 'error'}\n ref={ref}\n handle={clearHandle}\n />\n ) : (\n <StyledVerticalFieldGroup\n name={label}\n collapsible\n actions={[{ id: 'clear', text: t('clear'), onClick: clear }]}\n >\n {defaultControl}\n </StyledVerticalFieldGroup>\n );\n }\n\n if (showAdvanced) {\n return (\n <CompositeInput\n dialog={dialog}\n label={label}\n onClear={clear}\n value={\n conditionProp\n ? formatCondition({ condition: conditionProp }, fields, t, {\n locale,\n omitLhs: true\n })\n : undefined\n }\n placeholder={t('all')}\n ref={ref}\n />\n );\n }\n\n return defaultControl;\n }\n);\n\nexport default ConditionInput;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pega/cosmos-react-condition-builder",
3
- "version": "4.0.0-dev.14.0",
3
+ "version": "4.0.0-dev.14.1",
4
4
  "author": "Pegasystems",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -23,7 +23,7 @@
23
23
  "build": "tsc -b"
24
24
  },
25
25
  "dependencies": {
26
- "@pega/cosmos-react-core": "4.0.0-dev.14.0",
26
+ "@pega/cosmos-react-core": "4.0.0-dev.14.1",
27
27
  "@types/react": "^16.14.24 || ^17.0.38",
28
28
  "@types/react-dom": "^16.9.14 || ^17.0.11",
29
29
  "@types/styled-components": "^5.1.26",