repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch-control-center | src/components/MobileView.res | .res | @react.component
let make = (~children) => {
let isMobileView = MatchMedia.useMobileChecker()
<RenderIf condition=isMobileView> children </RenderIf>
}
| 39 | 10,021 |
hyperswitch-control-center | src/components/InputFields.res | .res | type customInputFn = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder: string,
) => React.element
type comboCustomInputFn = array<ReactFinalForm.fieldRenderProps> => React.element
type comboCustomInputRecord = {
fn: comboCustomInputFn,
names: array<string>,
}
let selectInput = (
~options: array<SelectBox.dropdownOption>,
~buttonText,
~deselectDisable=false,
~isHorizontal=true,
~disableSelect=false,
~fullLength=false,
~customButtonStyle="",
~textStyle="",
~marginTop="mt-12",
~customStyle="",
~searchable=?,
~showBorder=?,
~showToolTipOptions=false,
~textEllipsisForDropDownOptions=false,
~showCustomBtnAtEnd=false,
~dropDownCustomBtnClick=false,
~addDynamicValue=false,
~showMatchingRecordsText=true,
~fixedDropDownDirection=?,
~customButton=React.null,
~buttonType=Button.SecondaryFilled,
~dropdownCustomWidth="w-80",
~allowButtonTextMinWidth=?,
~setExtSearchString=_ => (),
~textStyleClass=?,
~ellipsisOnly=false,
~showBtnTextToolTip=false,
~dropdownClassName="",
~descriptionOnHover=false,
~buttonSize=Button.Large,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<SelectBox
input
options
buttonText
allowMultiSelect=false
deselectDisable
isHorizontal
disableSelect
fullLength
customButtonStyle
textStyle
marginTop
customStyle
?showBorder
showToolTipOptions
textEllipsisForDropDownOptions
?searchable
showCustomBtnAtEnd
dropDownCustomBtnClick
addDynamicValue
showMatchingRecordsText
?fixedDropDownDirection
customButton
buttonType
dropdownCustomWidth
?allowButtonTextMinWidth
setExtSearchString
?textStyleClass
ellipsisOnly
showBtnTextToolTip
dropdownClassName
descriptionOnHover
buttonSize
/>
}
let infraSelectInput = (
~options: array<SelectBox.dropdownOption>,
~deselectDisable=false,
~borderRadius="rounded-full",
~selectedClass="border-jp-gray-900 dark:border-jp-gray-300 text-jp-gray-900 dark:text-jp-gray-300 font-semibold",
~nonSelectedClass="border-jp-gray-600 dark:border-jp-gray-800 text-jp-gray-850 dark:text-jp-gray-400",
~showTickMark=true,
~allowMultiSelect=true,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<SelectBox.InfraSelectBox
input
options
deselectDisable
borderRadius
selectedClass
nonSelectedClass
showTickMark
allowMultiSelect
/>
}
let filterMultiSelectInput = (
~options: array<FilterSelectBox.dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~buttonText,
~buttonSize=?,
~hideMultiSelectButtons=false,
~allowMultiSelect=true,
~showSelectionAsChips=true,
~showToggle=false,
~isDropDown=true,
~searchable=false,
~showBorder=?,
~optionRigthElement=?,
~customStyle="",
~customMargin="",
~customButtonStyle=?,
~hideBorder=false,
~allSelectType=FilterSelectBox.Icon,
~showToolTip=false,
~showNameAsToolTip=false,
~buttonType=Button.SecondaryFilled,
~showSelectAll=true,
~isHorizontal=false,
~fullLength=?,
~fixedDropDownDirection=?,
~dropdownCustomWidth=?,
~customMarginStyle=?,
~buttonTextWeight=?,
~marginTop=?,
~customButtonLeftIcon=?,
~customButtonPaddingClass=?,
~customButtonIconMargin=?,
~customTextPaddingClass=?,
~listFlexDirection="",
~buttonClickFn=?,
~showDescriptionAsTool=true,
~optionClass="",
~selectClass="",
~toggleProps="",
~showSelectCountButton=false,
~showAllSelectedOptions=true,
~leftIcon=?,
~customBackColor=?,
~customSelectAllStyle=?,
~onItemSelect=(_, _) => (),
~wrapBasis="",
~dropdownClassName="",
~baseComponentMethod=?,
~disableSelect=false,
(),
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<FilterSelectBox
input
options
optionSize
buttonText
?buttonSize
allowMultiSelect
hideMultiSelectButtons
showSelectionAsChips
isDropDown
showToggle
searchable
?showBorder
customStyle
customMargin
?optionRigthElement
hideBorder
allSelectType
?customButtonStyle
?fixedDropDownDirection
showToolTip
showNameAsToolTip
disableSelect
buttonType
showSelectAll
?fullLength
isHorizontal
?customMarginStyle
?dropdownCustomWidth
?buttonTextWeight
?marginTop
?customButtonLeftIcon
?customButtonPaddingClass
?customButtonIconMargin
?customTextPaddingClass
listFlexDirection
?buttonClickFn
showDescriptionAsTool
optionClass
selectClass
toggleProps
showSelectCountButton
showAllSelectedOptions
?leftIcon
?customBackColor
?customSelectAllStyle
onItemSelect
wrapBasis
dropdownClassName
?baseComponentMethod
/>
}
let multiSelectInput = (
~options: array<SelectBox.dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~buttonText,
~buttonSize=?,
~hideMultiSelectButtons=false,
~showSelectionAsChips=true,
~showToggle=false,
~isDropDown=true,
~searchable=false,
~showBorder=?,
~optionRigthElement=?,
~customStyle="",
~customMargin="",
~customButtonStyle=?,
~hideBorder=false,
~allSelectType=SelectBox.Icon,
~showToolTip=false,
~showNameAsToolTip=false,
~buttonType=Button.SecondaryFilled,
~showSelectAll=true,
~isHorizontal=false,
~fullLength=?,
~fixedDropDownDirection=?,
~dropdownCustomWidth=?,
~customMarginStyle=?,
~buttonTextWeight=?,
~marginTop=?,
~customButtonLeftIcon=?,
~customButtonPaddingClass=?,
~customButtonIconMargin=?,
~customTextPaddingClass=?,
~listFlexDirection="",
~buttonClickFn=?,
~showDescriptionAsTool=true,
~optionClass="",
~selectClass="",
~toggleProps="",
~showSelectCountButton=false,
~showAllSelectedOptions=true,
~leftIcon=?,
~customBackColor=?,
~customSelectAllStyle=?,
~onItemSelect=(_, _) => (),
~wrapBasis="",
~dropdownClassName="",
~baseComponentMethod=?,
~disableSelect=false,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<SelectBox
input
options
optionSize
buttonText
?buttonSize
allowMultiSelect=true
hideMultiSelectButtons
showSelectionAsChips
isDropDown
showToggle
searchable
?showBorder
customStyle
customMargin
?optionRigthElement
hideBorder
allSelectType
?customButtonStyle
?fixedDropDownDirection
showToolTip
showNameAsToolTip
disableSelect
buttonType
showSelectAll
?fullLength
isHorizontal
?customMarginStyle
?dropdownCustomWidth
?buttonTextWeight
?marginTop
?customButtonLeftIcon
?customButtonPaddingClass
?customButtonIconMargin
?customTextPaddingClass
listFlexDirection
?buttonClickFn
showDescriptionAsTool
optionClass
selectClass
toggleProps
showSelectCountButton
showAllSelectedOptions
?leftIcon
?customBackColor
?customSelectAllStyle
onItemSelect
wrapBasis
dropdownClassName
?baseComponentMethod
/>
}
let radioInput = (
~options: array<SelectBox.dropdownOption>,
~buttonText,
~disableSelect=true,
~optionSize: CheckBoxIcon.size=Small,
~isHorizontal=false,
~deselectDisable=true,
~customStyle="",
~baseComponentCustomStyle="",
~customSelectStyle="",
~fill=?,
~maxHeight=?,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<SelectBox
input
disableSelect
optionSize
options
buttonText
allowMultiSelect=false
isDropDown=false
isHorizontal
deselectDisable
customStyle
baseComponentCustomStyle
customSelectStyle
?fill
?maxHeight
/>
}
let textInput = (
~description="",
~isDisabled=false,
~autoFocus=false,
~type_="text",
~inputMode="text",
~pattern=?,
~autoComplete=?,
~maxLength=?,
~leftIcon=?,
~rightIcon=?,
~rightIconOnClick=?,
~inputStyle="",
~customStyle="",
~customWidth="w-full",
~customPaddingClass="",
~iconOpacity="opacity-30",
~rightIconCustomStyle="",
~leftIconCustomStyle="",
~customDashboardClass=?,
~onHoverCss=?,
~onDisabledStyle=?,
~onActiveStyle=?,
~customDarkBackground=?,
~phoneInput=false,
~widthMatchwithPlaceholderLength=None,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder) => {
<TextInput
input
placeholder
description
isDisabled
type_
inputMode
?pattern
?autoComplete
?maxLength
?leftIcon
?rightIcon
?rightIconOnClick
inputStyle
customStyle
customWidth
autoFocus
iconOpacity
customPaddingClass
rightIconCustomStyle
leftIconCustomStyle
?customDashboardClass
?onHoverCss
?onDisabledStyle
?onActiveStyle
?customDarkBackground
phoneInput
widthMatchwithPlaceholderLength
/>
}
let textTagInput = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~name="",
~customStyle=?,
~disabled=false,
~seperateByComma=false,
~seperateBySpace=false,
~customButtonStyle=?,
) => {
<MultipleTextInput
input name disabled seperateByComma seperateBySpace ?customStyle ?customButtonStyle placeholder
/>
}
let fileInput = () => (~input: ReactFinalForm.fieldRenderPropsInput) => {
<MultipleFileUpload input />
}
let numericTextInput = (
~isDisabled=false,
~customStyle="",
~inputMode=?,
~precision=?,
~maxLength=?,
~removeLeadingZeroes=false,
~leftIcon=?,
~rightIcon=?,
~customPaddingClass=?,
~rightIconCustomStyle=?,
~leftIconCustomStyle=?,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder) => {
<NumericTextInput
customStyle
input
placeholder
isDisabled
?inputMode
?precision
?maxLength
removeLeadingZeroes
?leftIcon
?rightIcon
?customPaddingClass
?rightIconCustomStyle
?leftIconCustomStyle
/>
}
let singleDatePickerInput = (
~disablePastDates=true,
~disableFutureDates=false,
~customDisabledFutureDays=0.0,
~format="YYYY-MM-DDTHH:mm:ss",
~currentDateHourFormat="00",
~currentDateMinuteFormat="00",
~currentDateSecondsFormat="00",
~customButtonStyle=?,
~newThemeCustomButtonStyle=?,
~calendarContaierStyle=?,
~buttonSize=?,
~showTime=?,
~fullLength=?,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<DatePicker
input
disablePastDates
disableFutureDates
format
customDisabledFutureDays
currentDateHourFormat
currentDateMinuteFormat
currentDateSecondsFormat
?customButtonStyle
?newThemeCustomButtonStyle
?calendarContaierStyle
?buttonSize
?showTime
?fullLength
/>
}
let filterDateRangeField = (
~startKey: string,
~endKey: string,
~format,
~disablePastDates=false,
~disableFutureDates=false,
~showTime=false,
~predefinedDays=[],
~disableApply=false,
~numMonths=1,
~dateRangeLimit=?,
~removeFilterOption=?,
~optFieldKey=?,
~showSeconds=true,
~hideDate=false,
~selectStandardTime=false,
~isTooltipVisible=true,
~allowedDateRange=?,
~events=?,
): comboCustomInputRecord => {
let fn = (_fieldsArray: array<ReactFinalForm.fieldRenderProps>) => {
<DateRangeField
disablePastDates
disableFutureDates
format
predefinedDays
numMonths
showTime
disableApply
startKey
endKey
?dateRangeLimit
?removeFilterOption
?optFieldKey
showSeconds
hideDate
selectStandardTime
isTooltipVisible
?allowedDateRange
?events
/>
}
{fn, names: [startKey, endKey]}
}
let filterCompareDateRangeField = (
~startKey: string,
~endKey: string,
~comparisonKey: string,
~format,
~disablePastDates=false,
~disableFutureDates=false,
~showTime=false,
~predefinedDays=[],
~disableApply=false,
~numMonths=1,
~dateRangeLimit=?,
~removeFilterOption=?,
~optFieldKey=?,
~showSeconds=true,
~hideDate=false,
~selectStandardTime=false,
~isTooltipVisible=true,
~compareWithStartTime: string,
~compareWithEndTime: string,
): comboCustomInputRecord => {
let fn = (_fieldsArray: array<ReactFinalForm.fieldRenderProps>) => {
<DateRangeCompareFields
disablePastDates
disableFutureDates
format
predefinedDays
numMonths
showTime
disableApply
startKey
endKey
comparisonKey
?dateRangeLimit
?removeFilterOption
?optFieldKey
showSeconds
hideDate
selectStandardTime
isTooltipVisible
compareWithStartTime
compareWithEndTime
/>
}
{fn, names: [startKey, endKey]}
}
let dateRangeField = (
~startKey: string,
~endKey: string,
~format,
~disablePastDates=false,
~disableFutureDates=false,
~showTime=false,
~predefinedDays=[],
~disableApply=false,
~numMonths=1,
~dateRangeLimit=?,
~removeFilterOption=?,
~optFieldKey=?,
~showSeconds=true,
~hideDate=false,
~selectStandardTime=false,
~customButtonStyle=?,
~isTooltipVisible=true,
): comboCustomInputRecord => {
let fn = (_fieldsArray: array<ReactFinalForm.fieldRenderProps>) => {
<DateRangePicker
disablePastDates
disableFutureDates
format
predefinedDays
numMonths
showTime
disableApply
startKey
endKey
?dateRangeLimit
?removeFilterOption
?optFieldKey
showSeconds
hideDate
selectStandardTime
?customButtonStyle
isTooltipVisible
/>
}
{fn, names: [startKey, endKey]}
}
let multiLineTextInput = (
~isDisabled,
~rows,
~cols,
~customClass="text-lg",
~leftIcon=?,
~maxLength=?,
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder) => {
<MultiLineTextInput ?maxLength input placeholder isDisabled ?rows ?cols customClass ?leftIcon />
}
let iconFieldWithMessageDes = (mainInputField, ~description="") => (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
) => {
<div>
<div> {mainInputField(~input, ~placeholder)} </div>
<div>
{switch description {
| "" => React.null
| _ =>
<div
className="pt-2 pb-2 text-sm text-bold text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ">
{React.string(description)}
</div>
}}
</div>
</div>
}
let passwordMatchField = (~leftIcon=?) => (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
) => {
<PasswordStrengthInput input placeholder displayStatus=false ?leftIcon />
}
let checkboxInput = (
~isHorizontal=false,
~options: array<SelectBox.dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~disableSelect=false,
~buttonText="",
~maxHeight=?,
~searchable=?,
~searchInputPlaceHolder=?,
~dropdownCustomWidth=?,
~customSearchStyle="bg-jp-gray-100 dark:bg-jp-gray-950 p-2",
~customLabelStyle=?,
~customMarginStyle="mx-3 py-2 gap-2",
~customStyle="",
~checkboxDimension="",
~wrapBasis="",
) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) => {
<SelectBox
input
options
optionSize
isSelectedStateMinus
disableSelect
allowMultiSelect=true
isDropDown=false
showSelectAll=false
buttonText
isHorizontal
?maxHeight
?searchable
?searchInputPlaceHolder
?dropdownCustomWidth
customSearchStyle
?customLabelStyle
customMarginStyle
customStyle
checkboxDimension
wrapBasis
/>
}
let boolInput = (~isDisabled, ~isCheckBox=false, ~boolCustomClass="") => (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder as _,
) => {
<BoolInput input isDisabled isCheckBox boolCustomClass />
}
| 4,287 | 10,022 |
hyperswitch-control-center | src/components/NewThemeUtils.res | .res | type headingSize = XSmall | Small | Medium | Large
module NewThemeHeading = {
@react.component
let make = (
~heading,
~description=?,
~headingColor="",
~descriptionColor="",
~headingSize=Large,
~rightActions=?,
~headingRightElemnt=?,
~alignItems="items-end",
~outerMargin="desktop:mb-6 mb-4",
) => {
let descriptionSize = switch headingSize {
| XSmall => "text-fs-12"
| _ => "text-fs-14"
}
let headingSize = switch headingSize {
| Large => "text-fs-24"
| Medium => "text-fs-20"
| Small => "text-fs-18"
| XSmall => "text-fs-14"
}
let headingColor = headingColor->LogicUtils.isEmptyString ? "text-jp-gray-900" : headingColor
let descriptionColor =
descriptionColor->LogicUtils.isEmptyString ? "text-jp-2-light-gray-1000" : descriptionColor
<div className={`flex flex-col ${outerMargin} w-full items-start`}>
<div className={`flex w-full justify-between ${alignItems} gap-10`}>
<div className="flex flex-col flex-1 gap-1">
<AddDataAttributes attributes=[("data-header-text", heading)]>
<div
className={`flex items-center ${headingSize} mobile:text-fs-16 font-semibold ${headingColor} dark:text-white`}>
{heading->React.string}
{switch headingRightElemnt {
| Some(ele) => ele
| None => React.null
}}
</div>
</AddDataAttributes>
{switch description {
| Some(desc) =>
<AddDataAttributes attributes=[("data-description-text", desc)]>
<div className={`${descriptionSize} font-normal ${descriptionColor}`}>
{desc->React.string}
</div>
</AddDataAttributes>
| None => React.null
}}
</div>
{switch rightActions {
| Some(actions) => actions
| None => React.null
}}
</div>
</div>
}
}
module Badge = {
type color = Blue | Gray
@react.component
let make = (~number, ~color: color=Blue) => {
let (badgeColor, textColor) = switch color {
| Blue => ("bg-primary", " text-white/90")
| Gray => ("bg-jp-2-light-gray-300", "text-jp-2-light-gray-1800")
}
<AddDataAttributes attributes=[("data-badge-value", Int.toString(number))]>
<div
className={`w-4 h-4 flex justify-center items-center rounded-full ${badgeColor} ${textColor} font-medium text-xs`}>
{React.string(Int.toString(number))}
</div>
</AddDataAttributes>
}
}
| 663 | 10,023 |
hyperswitch-control-center | src/components/highcharts.css | .css | .highchart-sankey .highcharts-link {
fill: rgba(109, 115, 127, 0.2);
}
.highchart-sankey .highcharts-link:hover,
.highchart-sankey .highcharts-link.highcharts-point-hover {
fill: rgba(109, 115, 127, 0.6);
}
.highchart-sankey .highcharts-label-box.highcharts-tooltip-box {
stroke: none;
}
.highchart-sankey .highcharts-label tspan.highcharts-text-outline {
stroke: transparent;
}
span.highcharts-title {
width: 100% !important;
padding-right: 20px;
}
.highcharts-yaxis-grid .highcharts-grid-line {
stroke-dasharray: 4, 6;
}
| 173 | 10,024 |
hyperswitch-control-center | src/components/DragDropComponent.res | .res | type draggableDefaultDestination = {index: int, droppableId: string}
type draggableItem = React.element
let reorder = (currentState, startIndex, endIndex) => {
if startIndex !== endIndex {
let oldStateArray = Array.copy(currentState)
let removed = Js.Array.removeCountInPlace(~pos=startIndex, ~count=1, oldStateArray)
oldStateArray->Array.splice(~start=endIndex, ~remove=0, ~insert=removed)
(oldStateArray, true)
} else {
(currentState, false)
}
}
@react.component
let make = (~isHorizontal=true, ~listItems, ~gap="", ~setListItems, ~keyExtractor) => {
let onDragEnd = result => {
// dropped outside the list
let dest = Nullable.toOption(result["destination"])
switch dest {
| Some(a) => {
let res: draggableDefaultDestination = {
index: a.index,
droppableId: a.droppableId,
}
let (updatedList, hasChanged) = reorder(listItems, result["source"]["index"], res.index)
if hasChanged {
setListItems(updatedList)
}
}
| _ => ()
}
}
let directionClass = isHorizontal ? "flex-row" : "flex-col"
let droppableDirection = isHorizontal ? "horizontal" : "vertical"
<ReactBeautifulDND.DragDropContext onDragEnd={onDragEnd}>
<ReactBeautifulDND.Droppable droppableId="droppable" direction={droppableDirection}>
{(provided, _snapshot) => {
React.cloneElement(
<div className={`flex ${directionClass} ${gap} w-full`} ref={provided["innerRef"]}>
{listItems
->Array.mapWithIndex((item, index) => {
<ReactBeautifulDND.Draggable
key={`item-${Int.toString(index)}`}
index={index}
draggableId={`item-${Int.toString(index)}`}>
{(provided, snapshot) => {
let draggableElement =
<div onDragStart={provided["onDragStart"]} ref={provided["innerRef"]}>
{keyExtractor(index, item, snapshot["isDragging"])}
</div>
draggableElement
->React.cloneElement(provided["draggableProps"])
->React.cloneElement(provided["dragHandleProps"])
}}
</ReactBeautifulDND.Draggable>
})
->React.array}
{provided["placeholder"]}
</div>,
provided["droppableProps"],
)
}}
</ReactBeautifulDND.Droppable>
</ReactBeautifulDND.DragDropContext>
}
| 577 | 10,025 |
hyperswitch-control-center | src/components/ReactDebounce.res | .res | let useDebounced = (~wait=?, fn) => {
let ref = React.useRef(Debounce.make(~wait?, fn))
ref.current
}
let useControlled = (~wait=?, fn) => {
let ref = React.useRef(Debounce.makeControlled(~wait?, fn))
ref.current
}
| 69 | 10,026 |
hyperswitch-control-center | src/components/ErrorBoundary.res | .res | /*
? Reference - https://github.com/rescript-lang/rescript-react/blob/master/src/RescriptReactErrorBoundary.res
*/
let defaultFallback = _ =>
<div className="text-red-600 font-bold text-center flex flex-col items-center">
{"An error occured"->React.string}
<Button text="reset" buttonType=Primary onClick={_ => Window.Location.hardReload(true)} />
</div>
@react.component
let make = (~children, ~renderFallback=defaultFallback) => {
<RescriptReactErrorBoundary fallback={renderFallback}> {children} </RescriptReactErrorBoundary>
}
| 131 | 10,027 |
hyperswitch-control-center | src/components/AdvancedSearchModal.res | .res | module SearchActions = {
@react.component
let make = (~detailsKeyList, ~dictData, ~entity: EntityType.entityType<'colType, 't>) => {
<ShowDetails.EntityData dictData detailsKeyList entity />
}
}
module AdvanceSearch = {
@react.component
let make = (
~searchFields,
~url,
~entity: EntityType.entityType<'colType, 't>,
~setShowModal,
~setSearchDataDict,
~setShowSearchDetailsModal,
) => {
open LogicUtils
let {optionalSearchFieldsList, requiredSearchFieldsList, detailsKey} = entity
let fetchApi = AuthHooks.useApiFetcher()
let initialValueJson = JSON.Encode.object(Dict.make())
let showToast = ToastState.useShowToast()
let {xFeatureRoute, forceCookies} =
HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext)
let onSubmit = (values, _) => {
let otherQueries = switch values->JSON.Decode.object {
| Some(dict) =>
dict
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, value) = entry
let stringVal = getStringFromJson(value, "")
if stringVal->isNonEmptyString {
Some(`${key}=${stringVal}`)
} else {
None
}
})
->Array.joinWith("&")
| _ => ""
}
let finalUrl = otherQueries->isNonEmptyString ? `${url}?${otherQueries}` : url
open Promise
fetchApi(
finalUrl,
~bodyStr=JSON.stringify(initialValueJson),
~method_=Get,
~xFeatureRoute,
~forceCookies,
~merchantId,
~profileId,
)
->then(res => res->Fetch.Response.json)
->then(json => {
switch JSON.Classify.classify(json) {
| Object(jsonDict) => {
let statusStr = getString(jsonDict, "status", "FAILURE")
if statusStr === "SUCCESS" {
let payloadDict =
jsonDict->Dict.get(detailsKey)->Option.flatMap(obj => obj->JSON.Decode.object)
switch payloadDict {
| Some(dict) => {
setShowModal(_ => false)
setSearchDataDict(_ => Some(dict))
setShowSearchDetailsModal(_ => true)
}
| _ =>
showToast(~message="Something went wrong. Please try again", ~toastType=ToastError)
}
} else {
showToast(~message="Data Not Found", ~toastType=ToastWarning)
}
}
| _ => showToast(~message="Something went wrong. Please try again", ~toastType=ToastError)
}
json->Nullable.make->resolve
})
->catch(_err => {
showToast(~message="Something went wrong. Please try again", ~toastType=ToastError)
Nullable.null->resolve
})
}
let validateForm = (values: JSON.t) => {
let valuesDict = switch values->JSON.Decode.object {
| Some(dict) => dict->Dict.toArray->Dict.fromArray
| None => Dict.make()
}
let errors = Dict.make()
requiredSearchFieldsList->Array.forEach(key => {
if Dict.get(valuesDict, key)->Option.isNone {
Dict.set(errors, key, "Required"->JSON.Encode.string)
}
})
let isSubmitEnabled = optionalSearchFieldsList->Array.some(key => {
Dict.get(valuesDict, key)->Option.isSome
})
if !isSubmitEnabled {
Dict.set(
errors,
optionalSearchFieldsList->Array.joinWith(","),
"Atleast One of Optional fields is Required"->JSON.Encode.string,
)
}
errors->JSON.Encode.object
}
<FormRenderer
initialValues={initialValueJson}
onSubmit
validate=validateForm
formClass="md:justify-between p-2"
fields={searchFields}
/>
}
}
@react.component
let make = (~searchFields, ~url, ~entity) => {
let (showModal, setShowModal) = React.useState(_ => false)
let (searchDataDict, setSearchDataDict) = React.useState(_ => None)
let (showSearchDetailsModal, setShowSearchDetailsModal) = React.useState(_ => false)
<>
<Button
text={"Search"}
leftIcon={FontAwesome("search")}
buttonType=Primary
onClick={_ => setShowModal(_ => true)}
/>
<Modal modalHeading="Search" showModal setShowModal modalClass="w-full md:w-3/12 mx-auto">
<AdvanceSearch
searchFields url entity setShowModal setSearchDataDict setShowSearchDetailsModal
/>
</Modal>
{switch searchDataDict {
| Some(dictData) =>
<Modal
modalHeading="Search Details"
showModal=showSearchDetailsModal
setShowModal=setShowSearchDetailsModal
modalClass="w-full md:w-10/12 mx-auto">
<SearchActions detailsKeyList={entity.searchKeyList} dictData entity />
</Modal>
| None => React.null
}}
</>
}
| 1,137 | 10,028 |
hyperswitch-control-center | src/components/DynamicChart.res | .res | open LogicUtils
type cardinality = Top_5 | Top_10
type granularity =
| G_THIRTYSEC
| G_ONEMIN
| G_FIVEMIN
| G_FIFTEENMIN
| G_THIRTYMIN
| G_ONEHOUR
| G_ONEDAY
let getGranularityString = granularity => {
switch granularity {
| G_THIRTYSEC => "G_THIRTYSEC"
| G_ONEMIN => "G_ONEMIN"
| G_FIVEMIN => "G_FIVEMIN"
| G_FIFTEENMIN => "G_FIFTEENMIN"
| G_THIRTYMIN => "G_THIRTYMIN"
| G_ONEHOUR => "G_ONEHOUR"
| G_ONEDAY => "G_ONEDAY"
}
}
let getGranularityFormattedText = granularity => {
switch granularity {
| G_THIRTYSEC => "THIRTY SEC"
| G_ONEMIN => "ONE MIN"
| G_FIVEMIN => "FIVE MIN"
| G_FIFTEENMIN => "FIFTEEN MIN"
| G_THIRTYMIN => "THIRTY MIN"
| G_ONEHOUR => "ONE HOUR"
| G_ONEDAY => "ONE DAY"
}
}
let getGranularity = (~startTime, ~endTime) => {
let diff =
(endTime->DateTimeUtils.parseAsFloat -. startTime->DateTimeUtils.parseAsFloat) /. (1000. *. 60.) // in minutes
// startTime
if diff < 60. *. 6. {
// Smaller than 6 hour
[G_FIFTEENMIN, G_FIVEMIN]
} else if diff < 60. *. 24. {
// Smaller than 1 day
[G_ONEHOUR, G_THIRTYMIN, G_FIFTEENMIN, G_FIVEMIN]
} else {
[G_ONEDAY, G_ONEHOUR, G_THIRTYMIN, G_FIFTEENMIN, G_FIVEMIN]
}
}
type chartEntity = {
uri: string,
metrics: array<LineChartUtils.metricsConfig>,
groupByNames: option<array<string>>,
start_time: string,
end_time: string,
filters: option<JSON.t>,
granularityOpts: option<string>,
delta: bool,
startDateTime: string,
cardinality: option<string>,
mode: option<string>,
prefix?: string,
source: string,
customFilter?: string,
}
let getTimeSeriesChart = (chartEntity: chartEntity) => {
let metricsArr = chartEntity.metrics->Array.map(item => {
item.metric_name_db
})
[
AnalyticsUtils.getFilterRequestBody(
~groupByNames=chartEntity.groupByNames,
~granularity=chartEntity.granularityOpts,
~filter=chartEntity.filters,
~metrics=Some(metricsArr),
~delta=chartEntity.delta,
~startDateTime=chartEntity.start_time,
~endDateTime=chartEntity.end_time,
~cardinality=chartEntity.cardinality,
~mode=chartEntity.mode,
~customFilter=chartEntity.customFilter->Option.getOr(""),
~prefix=chartEntity.prefix,
~source=chartEntity.source,
)->JSON.Encode.object,
]
->JSON.Encode.array
->JSON.stringify
}
let getLegendBody = (chartEntity: chartEntity) => {
let metricsArr = chartEntity.metrics->Array.map(item => {
item.metric_name_db
})
[
AnalyticsUtils.getFilterRequestBody(
~groupByNames=chartEntity.groupByNames,
~filter=chartEntity.filters,
~metrics=Some(metricsArr),
~delta=chartEntity.delta,
~startDateTime=chartEntity.start_time,
~endDateTime=chartEntity.end_time,
~cardinality=chartEntity.cardinality,
~mode=chartEntity.mode,
~customFilter=chartEntity.customFilter->Option.getOr(""),
~prefix=chartEntity.prefix,
~source=chartEntity.source,
)->JSON.Encode.object,
]
->JSON.Encode.array
->JSON.stringify
}
type chartUrl = String(string) | Func(Dict.t<JSON.t> => string)
type chartType = Line | Bar | SemiDonut | HorizontalBar | Funnel
type uriConfig = {
uri: string,
timeSeriesBody: chartEntity => string,
legendBody?: chartEntity => string,
metrics: array<LineChartUtils.metricsConfig>,
timeCol: string,
filterKeys: array<string>,
prefix?: string,
domain?: string,
}
type urlToDataMap = {
metricsUrl: string,
rawData: array<JSON.t>,
legendData: array<JSON.t>,
}
type fetchDataConfig = {
url: string,
body: string,
legendBody?: string,
metrics: array<LineChartUtils.metricsConfig>,
timeCol: string,
}
// a will be of time (xAxis = time, yAxis = float)
type entity = {
uri: chartUrl,
chartConfig: option<chartEntity>,
allFilterDimension: array<string>,
dateFilterKeys: (string, string),
currentMetrics: (string, string),
cardinality?: array<cardinality>,
granularity: array<granularity>,
chartTypes: array<chartType>,
uriConfig: array<uriConfig>,
moduleName: string,
source: string,
customFilterKey?: string,
getGranularity?: (~startTime: string, ~endTime: string) => array<string>,
enableLoaders?: bool,
chartDescription?: string,
sortingColumnLegend?: string,
jsonTransformer?: (string, array<JSON.t>) => array<JSON.t>,
disableGranularity?: bool,
}
let chartMapper = str => {
switch str {
| Line => "Line chart"
| Bar => "Bar Chart"
| SemiDonut => "SemiDonut Chart"
| HorizontalBar => "Horizontal Bar Chart"
| Funnel => "Funnel Chart"
}
}
type chartDimension = OneDimension | TwoDimension | ThreeDimension | No_Dims
let chartReverseMappers = str => {
switch str {
| "Line Chart" => Line
| "Bar Chart" => Bar
| "SemiDonut Chart" => SemiDonut
| "Horizontal Bar Chart" => HorizontalBar
| "Funnel Chart" => Funnel
| _ => Line
}
}
let makeEntity = (
~uri,
~chartConfig=?,
~filterKeys: array<string>=[],
~dateFilterKeys: (string, string),
~currentMetrics: (string, string),
~cardinality: option<array<cardinality>>=?,
~granularity=[G_ONEDAY],
~chartTypes=[Line],
~uriConfig,
~moduleName: string,
~source: string="BATCH",
~customFilterKey: option<string>=?,
~getGranularity: option<(~startTime: string, ~endTime: string) => array<string>>=?,
~enableLoaders: bool=true,
~chartDescription: option<string>=?,
~sortingColumnLegend: option<string>=?,
~jsonTransformer: option<(string, array<JSON.t>) => array<JSON.t>>=?,
~disableGranularity=?,
) => {
let granularity = granularity->Array.length === 0 ? [G_ONEDAY] : granularity
let chartTypes = chartTypes->Array.length === 0 ? [Line] : chartTypes
{
uri,
chartConfig,
allFilterDimension: filterKeys,
dateFilterKeys,
currentMetrics,
?cardinality,
granularity,
chartTypes,
uriConfig,
moduleName,
source,
?customFilterKey,
?getGranularity,
enableLoaders,
?chartDescription,
?sortingColumnLegend,
?jsonTransformer,
?disableGranularity,
}
}
let useChartFetch = (~setStatusDict) => {
let fetchApi = AuthHooks.useApiFetcher()
let addLogsAroundFetch = AnalyticsLogUtilsHook.useAddLogsAroundFetch()
let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext)
let fetchChartData = (updatedChartBody: array<fetchDataConfig>, setState) => {
open Promise
updatedChartBody
->Array.map(item => {
fetchApi(
item.url,
~method_=Post,
~bodyStr=item.body,
~headers=[("QueryType", "Chart")]->Dict.fromArray,
~xFeatureRoute,
~forceCookies,
~merchantId,
~profileId,
)
->addLogsAroundFetch(~logTitle="Chart Data Api", ~setStatusDict)
->then(json => {
// get total volume and time series and pass that on
let dataRawTimeSeries =
json->getDictFromJsonObject->getJsonObjectFromDict("queryData")->getArrayFromJson([])
switch item {
| {legendBody} =>
fetchApi(
item.url,
~method_=Post,
~bodyStr=legendBody,
~headers=[("QueryType", "Chart")]->Dict.fromArray,
~xFeatureRoute,
~forceCookies,
~merchantId,
~profileId,
)
->addLogsAroundFetch(~logTitle="Chart Data Api", ~setStatusDict)
->then(
legendJson => {
let dataRawLegend =
legendJson
->getDictFromJsonObject
->getJsonObjectFromDict("queryData")
->getArrayFromJson([])
resolve(
Some({
metricsUrl: item.url,
rawData: dataRawTimeSeries,
legendData: dataRawLegend,
}),
)
},
)
->catch(
_err => {
resolve(None)
},
)
| _ =>
resolve(
Some({
metricsUrl: item.url,
rawData: dataRawTimeSeries,
legendData: [],
}),
)
}
})
->catch(_err => {
resolve(None)
})
})
->Promise.all
->thenResolve(dataArr => {
let data = dataArr->Belt.Array.keepMap(item => item)
setState(data)
})
->catch(_err => resolve())
->ignore
}
fetchChartData
}
let cardinalityArr = ["TOP_5", "TOP_10"]
let chartTypeArr = [
"Line chart",
"Bar Chart",
"SemiDonut Chart",
"Horizontal Bar Chart",
"Funnel Chart",
]
module GranularitySelectBox = {
@react.component
let make = (~selectedGranularity, ~setSelectedGranularity, ~startTime, ~endTime) => {
let options = getGranularity(~startTime, ~endTime)
open HeadlessUI
<>
<Menu \"as"="div" className="relative inline-block text-left">
{_ =>
<div>
<Menu.Button
className="inline-flex whitespace-pre leading-5 justify-center text-sm px-3 py-1 font-medium rounded-md hover:bg-opacity-80 bg-white border">
{props => {
let arrow = props["open"]
<>
{selectedGranularity->getGranularityFormattedText->React.string}
<Icon
className={arrow
? `rotate-0 transition duration-[250ms] ml-1 mt-1 opacity-60`
: `rotate-180 transition duration-[250ms] ml-1 mt-1 opacity-60`}
name="arrow-without-tail"
size=15
/>
</>
}}
</Menu.Button>
<Transition
\"as"="span"
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
{<Menu.Items
className="absolute right-0 z-50 w-36 mt-2 origin-top-right bg-white dark:bg-jp-gray-950 divide-y divide-gray-100 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
{_ => {
<>
<div className="px-1 py-1 ">
{options
->Array.mapWithIndex((option, i) =>
<Menu.Item key={i->Int.toString}>
{props =>
<div className="relative">
<button
onClick={_ => setSelectedGranularity(_ => option)}
className={
let activeClasses = if props["active"] {
"group flex rounded-md items-center w-full px-2 py-2 text-sm bg-gray-100 dark:bg-black"
} else {
"group flex rounded-md items-center w-full px-2 py-2 text-sm"
}
`${activeClasses} font-medium text-start`
}>
<div className="mr-5">
{option->getGranularityFormattedText->React.string}
</div>
</button>
</div>}
</Menu.Item>
)
->React.array}
</div>
</>
}}
</Menu.Items>}
</Transition>
</div>}
</Menu>
</>
}
}
@react.component
let make = (
~entity,
~selectedTab: option<array<string>>,
~modeKey=?,
~chartId="",
~updateUrl=?,
~tabTitleMapper=?,
~enableBottomChart=true,
~showTableLegend=true,
~showMarkers=false,
~legendType: HighchartTimeSeriesChart.legendType=Table,
~comparitionWidget=false,
) => {
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone()
let updateChartCompFilters = switch updateUrl {
| Some(fn) => fn
| None => _ => ()
}
let {filterValue} = React.useContext(FilterContext.filterContext)
let customFilterKey = switch entity {
| {customFilterKey} => customFilterKey
| _ => ""
}
let getAllFilter =
filterValue
->Dict.toArray
->Array.map(item => {
let (key, value) = item
(key, value->UrlFetchUtils.getFilterValue)
})
->Dict.fromArray
// with prefix only for charts
let getChartCompFilters = React.useMemo(() => {
getAllFilter
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
let keyArr = key->String.split(".")
let prefix = keyArr->Array.get(0)->Option.getOr("")
let fitlerName = keyArr->Array.get(1)->Option.getOr("")
// when chart id is not there then there won't be any prefix so the prefix will the filter name
if chartId->isEmptyString {
Some((prefix, value))
} else if prefix === chartId && fitlerName->isNonEmptyString {
Some((fitlerName, value))
} else {
None
}
})
->Dict.fromArray
}, [getAllFilter])
// without prefix only for charts
let getTopLevelFilter = React.useMemo(() => {
getAllFilter
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
let keyArr = key->String.split(".")
let prefix = keyArr->Array.get(0)->Option.getOr("")
if prefix === chartId && prefix->isNonEmptyString {
None
} else {
Some((prefix, value))
}
})
->Dict.fromArray
}, [getAllFilter])
let mode = switch modeKey {
| Some(modeKey) => Some(getTopLevelFilter->getString(modeKey, ""))
| None => Some("ORDER")
}
let {allFilterDimension, dateFilterKeys, currentMetrics, uriConfig, source} = entity
let enableLoaders = entity.enableLoaders->Option.getOr(true)
let entityAllMetrics = uriConfig->Array.reduce([], (acc, item) =>
Array.concat(
acc,
{
item.metrics
},
)
)
let (currentTopMatrix, currentBottomMetrix) = currentMetrics
// if we won't see anything in the url then we will update the url
React.useEffect(() => {
let cardinality = getChartCompFilters->getString("cardinality", "TOP_5")
let chartType =
getChartCompFilters->getString(
"chartType",
entity.chartTypes->Array.get(0)->Option.getOr(Line)->chartMapper,
)
let chartTopMetric = getChartCompFilters->getString("chartTopMetric", currentTopMatrix)
let chartBottomMetric = getChartCompFilters->getString("chartBottomMetric", currentBottomMetrix)
let dict = Dict.make()
let chartMatrixArr = entityAllMetrics->Array.map(item => item.metric_label)
if cardinalityArr->Array.includes(cardinality) {
dict->Dict.set("cardinality", cardinality)
} else if cardinalityArr->Array.includes("TOP_5") {
dict->Dict.set("cardinality", "TOP_5")
} else {
dict->Dict.set("cardinality", cardinalityArr->Array.get(0)->Option.getOr(""))
}
chartTypeArr->Array.includes(chartType)
? dict->Dict.set("chartType", chartType)
: dict->Dict.set("chartType", "Line chart")
if chartMatrixArr->Array.includes(chartTopMetric) {
dict->Dict.set("chartTopMetric", chartTopMetric)
} else if chartMatrixArr->Array.includes(currentTopMatrix) {
dict->Dict.set("chartTopMetric", currentTopMatrix)
} else {
dict->Dict.set("chartTopMetric", chartMatrixArr->Array.get(0)->Option.getOr(""))
}
if chartMatrixArr->Array.includes(chartBottomMetric) {
dict->Dict.set("chartBottomMetric", chartBottomMetric)
} else if chartMatrixArr->Array.includes(currentBottomMetrix) {
dict->Dict.set("chartBottomMetric", currentBottomMetrix)
} else {
dict->Dict.set("chartBottomMetric", chartMatrixArr->Array.get(0)->Option.getOr(""))
}
updateChartCompFilters(dict)
None
}, [])
let cardinalityFromUrl = getChartCompFilters->getString("cardinality", "TOP_5")
let (rawChartData, setRawChartData) = React.useState(_ => None)
let (groupKey, setGroupKey) = React.useState(_ => "")
let (startTimeFilterKey, endTimeFilterKey) = dateFilterKeys
let defaultFilters = switch modeKey {
| Some(modeKey) => [startTimeFilterKey, endTimeFilterKey, modeKey]
| None => [startTimeFilterKey, endTimeFilterKey]
}
let allFilterKeys = Array.concat(defaultFilters, allFilterDimension)
let (topFiltersToSearchParam, customFilter) = React.useMemo(() => {
let filterSearchParam =
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, value) = entry
if allFilterKeys->Array.includes(key) {
switch value->JSON.Classify.classify {
| String(str) => `${key}=${str}`->Some
| Number(num) => `${key}=${num->String.make}`->Some
| Array(arr) => `${key}=[${arr->String.make}]`->Some
| _ => None
}
} else {
None
}
})
->Array.joinWith("&")
(filterSearchParam, getTopLevelFilter->getString(customFilterKey, ""))
}, [getTopLevelFilter])
let (startTimeFilterKey, endTimeFilterKey) = dateFilterKeys
let (chartLoading, setChartLoading) = React.useState(_ => true)
// By default, total_volume metric will always be there
let (statusDict, setStatusDict) = React.useState(_ => Dict.make())
let fetchChartData = useChartFetch(~setStatusDict)
let startTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(startTimeFilterKey, "")
}, [topFiltersToSearchParam])
let endTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(endTimeFilterKey, "")
}, [topFiltersToSearchParam])
let defaultGranularity = switch getGranularity(
~startTime={startTimeFromUrl},
~endTime={endTimeFromUrl},
)->Array.get(0) {
| Some(val) => val
| _ => G_FIVEMIN
}
let (selectedGranularity, setSelectedGranularity) = React.useState(_ => defaultGranularity)
let topFiltersToSearchParam = React.useMemo(() => {
let filterSearchParam =
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, value) = entry
switch value->JSON.Classify.classify {
| String(str) => `${key}=${str}`->Some
| Number(num) => `${key}=${num->String.make}`->Some
| Array(arr) => `${key}=[${arr->String.make}]`->Some
| _ => None
}
})
->Array.joinWith("&")
filterSearchParam
}, [topFiltersToSearchParam])
React.useEffect(() => {
setSelectedGranularity(_ => defaultGranularity)
None
}, (startTimeFromUrl, endTimeFromUrl))
let selectedTabStr = selectedTab->Option.getOr([])->Array.joinWith("")
let updatedChartConfigArr = React.useMemo(() => {
uriConfig->Array.map(item => {
let filterKeys =
item.filterKeys->Array.filter(item => allFilterDimension->Array.includes(item))
let filterValue =
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(
entries => {
let (key, value) = entries
filterKeys->Array.includes(key) ? Some((key, value)) : None
},
)
->Dict.fromArray
let granularityOpts =
entity.disableGranularity->Option.getOr(false)
? None
: selectedGranularity->getGranularityString->Some
{
uri: item.uri,
metrics: item.metrics,
groupByNames: selectedTab,
start_time: startTimeFromUrl,
end_time: endTimeFromUrl,
filters: Some(JSON.Encode.object(filterValue)),
granularityOpts,
delta: false,
startDateTime: startTimeFromUrl,
cardinality: Some(cardinalityFromUrl),
customFilter,
mode,
prefix: ?item.prefix,
source,
}
})
}, (
startTimeFromUrl,
endTimeFromUrl,
customFilter,
topFiltersToSearchParam,
cardinalityFromUrl,
selectedTabStr,
selectedGranularity,
))
let updatedChartBody = React.useMemo(() => {
uriConfig->Belt.Array.keepMap(item => {
switch updatedChartConfigArr->Array.find(config => config.uri === item.uri) {
| Some(chartconfig) => {
let legendBody = switch item {
| {legendBody} => Some(legendBody(chartconfig))
| _ => None
}
let value: fetchDataConfig = {
url: item.uri,
body: item.timeSeriesBody(chartconfig),
legendBody: ?(
chartconfig.groupByNames->Option.getOr([])->Array.length === 1 ? legendBody : None
),
metrics: item.metrics,
timeCol: item.timeCol,
}
Some(value)
}
| None => None
}
})
}, [updatedChartConfigArr])
let (groupKeyFromTab, titleKey) = React.useMemo(() => {
switch (tabTitleMapper, selectedTab) {
| (Some(dict), Some(arr)) => {
let groupKey = arr->Array.get(0)->Option.getOr("")
(groupKey, dict->Dict.get(groupKey)->Option.getOr(groupKey))
}
| (None, Some(arr)) => (
arr->Array.get(0)->Option.getOr(""),
arr->Array.get(0)->Option.getOr(""),
)
| _ => ("", "")
}
}, [selectedTab])
let setRawChartData = (data: array<urlToDataMap>) => {
let chartData = data->Array.map(mappedData => {
let rawdata = mappedData.rawData->Array.map(item => {
let dict = item->JSON.Decode.object->Option.getOr(Dict.make())
switch dict->Dict.get("time_range") {
| Some(jsonObj) => {
let timeDict = jsonObj->getDictFromJsonObject
switch timeDict->Dict.get("startTime") {
| Some(startValue) => {
let sTime = startValue->JSON.Decode.string->Option.getOr("")
if sTime->isNonEmptyString {
let {date, hour, minute, month, second, year} =
sTime->Date.fromString->Date.toISOString->isoStringToCustomTimeZone
dict->Dict.set(
"time_bucket",
`${year}-${month}-${date} ${hour}:${minute}:${second}`->JSON.Encode.string,
)
}
}
| None => ()
}
}
| None => ()
}
selectedTab
->Option.getOr([])
->Array.forEach(
tabName => {
let metric =
Dict.get(dict, tabName)
->Option.getOr(""->JSON.Encode.string)
->JSON.Decode.string
->Option.getOr("")
let label = metric->isEmptyString ? "NA" : metric
Dict.set(dict, tabName, label->JSON.Encode.string)
Dict.keysToArray(dict)->Array.forEach(
key => {
if key->String.includes("amount") {
let amount =
Dict.get(dict, key)
->Option.getOr(JSON.Encode.float(0.0))
->JSON.Decode.float
->Option.getOr(0.0)
let amount = (amount /. 100.0)->Float.toFixedWithPrecision(~digits=2)
Dict.set(dict, key, amount->Js.Float.fromString->JSON.Encode.float)
} else if !(key->String.includes("time")) && key != tabName {
switch Dict.get(dict, key) {
| Some(val) =>
switch val->JSON.Decode.float {
| Some(val2) =>
Dict.set(
dict,
key,
val2->Float.toFixedWithPrecision(~digits=2)->JSON.Encode.string,
)
| None => ()
}
| None => ()
}
}
},
)
},
)
dict->JSON.Encode.object
})
{
metricsUrl: mappedData.metricsUrl,
rawData: rawdata,
legendData: mappedData.legendData,
}
})
setGroupKey(_ => groupKeyFromTab)
setRawChartData(_ => Some(chartData))
setChartLoading(_ => false)
}
let chartTypeFromUrl = getChartCompFilters->getString("chartType", "Line chart")
let chartTopMetricFromUrl = getChartCompFilters->getString("chartTopMetric", currentTopMatrix)
React.useEffect(() => {
if startTimeFromUrl->isNonEmptyString && endTimeFilterKey->isNonEmptyString {
setChartLoading(_ => enableLoaders)
fetchChartData(updatedChartBody, setRawChartData)
}
None
}, [updatedChartBody])
if statusDict->Dict.valuesToArray->Array.includes(504) {
<AnalyticsUtils.NoDataFoundPage />
} else {
<div>
<ReactFinalForm.Form
subscription=ReactFinalForm.subscribeToValues
onSubmit={(_, _) => Nullable.null->Promise.resolve}
render={({handleSubmit}) => {
<form onSubmit={handleSubmit}>
<AddDataAttributes attributes=[("data-chart-segment", "Chart-1")]>
<div
className="border rounded bg-white border-jp-gray-500 dark:border-jp-gray-960 dark:bg-jp-gray-950 dynamicChart">
{if chartLoading {
<Shimmer styleClass="w-full h-96 dark:bg-black bg-white" shimmerType={Big} />
} else if comparitionWidget {
<div>
<RenderIf condition={featureFlagDetails.granularity}>
<div className="w-full flex justify-end p-2">
<GranularitySelectBox
selectedGranularity
setSelectedGranularity
startTime={startTimeFromUrl}
endTime={endTimeFromUrl}
/>
</div>
</RenderIf>
{entityAllMetrics
->Array.mapWithIndex((selectedMetrics, index) => {
switch uriConfig->Array.get(0) {
| Some(metricsUri) => {
let (data, legendData, timeCol) = switch rawChartData
->Option.getOr([])
->Array.find(item => item.metricsUrl === metricsUri.uri) {
| Some(dataVal) => (
dataVal.rawData,
dataVal.legendData,
metricsUri.timeCol,
)
| None => ([], [], "")
}
<HighchartTimeSeriesChart.LineChart1D
key={index->Int.toString}
class="flex overflow-scroll"
rawChartData=data
selectedMetrics
chartTitleText={selectedMetrics.metric_label}
xAxis=timeCol
groupKey
chartTitle=true
key={""}
legendData
showTableLegend
showMarkers
legendType
comparitionWidget
selectedTab={selectedTab->Option.getOr([])}
/>
}
| _ => React.null
}
})
->React.array}
</div>
} else {
switch entityAllMetrics
->Array.filter(item => item.metric_label === chartTopMetricFromUrl)
->Array.get(0) {
| Some(selectedMetrics) =>
let metricsUri = uriConfig->Array.find(uriMetrics => {
uriMetrics.metrics
->Array.map(item => {item.metric_label})
->Array.includes(selectedMetrics.metric_label)
})
let (data, legendData, timeCol) = switch metricsUri {
| Some(val) =>
switch rawChartData
->Option.getOr([])
->Array.find(item => item.metricsUrl === val.uri) {
| Some(dataVal) => (dataVal.rawData, dataVal.legendData, val.timeCol)
| None => ([], [], "")
}
| None => ([], [], "")
}
switch chartTypeFromUrl->chartReverseMappers {
| Line =>
<HighchartTimeSeriesChart.LineChart1D
class="flex overflow-scroll"
rawChartData=data
selectedMetrics
chartPlace="top_"
xAxis=timeCol
groupKey
chartTitle=false
key={"0"}
legendData
showTableLegend
showMarkers
legendType
/>
| Bar =>
<div className="">
<HighchartBarChart.HighBarChart1D
rawData=data groupKey selectedMetrics key={"0"}
/>
</div>
| SemiDonut =>
<div className="m-4">
<HighchartPieChart
rawData=data groupKey titleKey selectedMetrics key={"0"}
/>
</div>
| HorizontalBar =>
<div className="m-4">
<HighchartHorizontalBarChart
rawData=data groupKey titleKey selectedMetrics key={"0"}
/>
</div>
| Funnel =>
<FunnelChart
data
metrics={entityAllMetrics}
moduleName={entity.moduleName}
description={entity.chartDescription}
/>
}
| None => React.null
}
}}
</div>
</AddDataAttributes>
</form>
}}
/>
</div>
}
}
| 7,055 | 10,029 |
hyperswitch-control-center | src/components/HyperSwitchLogo.res | .res | type theme = Light | Dark
@react.component
let make = (
~logoClass="",
~handleClick=?,
~logoVariant=CommonAuthTypes.IconWithText,
~logoHeight="h-6",
~theme=Dark,
~iconUrl=None,
) => {
let iconFolder = switch theme {
| Dark => "Dark"
| Light => "Light"
}
let handleClickEvent = ev => {
switch handleClick {
| Some(fn) => fn(ev)
| None => ()
}
}
let iconImagePath = switch logoVariant {
| Icon => `/assets/${iconFolder}/hyperswitchLogoIcon.svg`
| Text => `/assets/${iconFolder}/hyperswitchLogoText.svg`
| IconWithText => `/assets/${iconFolder}/hyperswitchLogoIconWithText.svg`
| IconWithURL => `${iconUrl->Option.getOr("")}`
}
<div className={`${logoClass}`} onClick={handleClickEvent}>
<img alt="image" src=iconImagePath className=logoHeight />
</div>
}
| 232 | 10,030 |
hyperswitch-control-center | src/components/Pagination.res | .res | external formEventToInt: ReactEvent.Form.t => int = "%identity"
@react.component
let make = (~resultsPerPage, ~totalResults, ~currentPage, ~paginate, ~btnCount=4) => {
let pageNumbers = []
let isMobileView = MatchMedia.useMobileChecker()
let (dropDownVal, setDropDownVal) = React.useState(_ => "1-10")
let total = Math.ceil(Int.toFloat(totalResults) /. Int.toFloat(resultsPerPage))->Float.toInt
for x in 1 to total {
Array.push(pageNumbers, x)->ignore
}
let pageToLeft =
btnCount - (total - currentPage) < btnCount / 2
? btnCount / 2
: btnCount - (total - currentPage)
let arr = []
for x in 1 to totalResults {
arr->Array.push(x)->ignore
}
let rangeNum =
arr
->Array.map(ele => {
mod(ele, 10) === 0 ? Array.indexOf(arr, ele + 1) : 0
})
->Array.filter(i => i !== 0)
let ranges = []
rangeNum->Array.forEach(ele => {
ranges->Array.push((ele - 9)->Int.toString ++ "-" ++ ele->Int.toString)->ignore
})
let lastNum = rangeNum->Array.get(Array.length(rangeNum) - 1)->Option.getOr(0)
if totalResults > lastNum {
let start = lastNum + (totalResults - lastNum)
start === totalResults
? ranges->Array.push(start->Int.toString)->ignore
: ranges->Array.push(start->Int.toString ++ "-" ++ totalResults->Int.toString)->ignore
}
let startIndex = Math.Int.max(1, currentPage - pageToLeft)
let endIndex = Math.Int.min(startIndex + btnCount, total)
let nonEmpty = s => s >= startIndex && s <= endIndex
let leftIcon: Button.iconType = CustomIcon(<Icon name="angle-left" />)
let rightIcon: Button.iconType = CustomIcon(<Icon name="angle-right" />)
let buttonType: Button.buttonType = Pagination
{
if !isMobileView {
<ButtonGroup wrapperClass="flex flex-row gap-x-2 items-center">
<Button
leftIcon
buttonType
buttonState={if currentPage > 1 {
Normal
} else {
Disabled
}}
customButtonStyle="!w-6 !h-7 py-2 px-3.5 border-0 m-1 !min-w-0 !rounded-lg"
onClick={_ => paginate(Math.Int.max(1, currentPage - 1))}
/>
{pageNumbers
->Array.filter(nonEmpty)
->Array.mapWithIndex((number, idx) => {
let isSelected = number == currentPage
<Button
key={idx->Int.toString}
text={number->Int.toString}
onClick={_ => paginate(number)}
buttonType
customButtonStyle="!w-6 fs-12 !h-8 py-2 px-3.5 m-1 !min-w-0 "
buttonState={if isSelected {
NoHover
} else {
Normal
}}
/>
})
->React.array}
<Button
rightIcon
buttonType
onClick={_ => paginate(currentPage + 1)}
customButtonStyle="!w-6 !h-7 py-2 px-3.5 border-0 m-1 !min-w-0 !rounded-lg"
buttonState={if currentPage < Array.length(pageNumbers) {
Normal
} else {
Disabled
}}
/>
</ButtonGroup>
} else {
let dropDownOptions = ranges->Array.mapWithIndex((item, idx): SelectBox.dropdownOption => {
{
label: item,
value: (idx + 1)->Int.toString,
}
})
let selectInput: ReactFinalForm.fieldRenderPropsInput = {
name: "dummy-name",
onBlur: _ev => (),
onChange: ev => {
let val = ranges->Array.get(ev->formEventToInt - 1)->Option.getOr("1-10")
setDropDownVal(_ => val)
paginate(ev->formEventToInt)
},
onFocus: _ev => (),
value: ""->JSON.Encode.string,
checked: true,
}
<SelectBox.BaseDropdown
options=dropDownOptions
searchable=false
input=selectInput
hideMultiSelectButtons=true
deselectDisable=true
buttonType
allowMultiSelect=false
buttonText=dropDownVal
/>
}
}
}
| 1,012 | 10,031 |
hyperswitch-control-center | src/components/CopyFieldValue.res | .res | @react.component
let make = (~fieldkey) => {
let data = ReactFinalForm.useField(fieldkey).input.value
<Clipboard.Copy data />
}
| 35 | 10,032 |
hyperswitch-control-center | src/components/LoadedTable.res | .res | open DynamicTableUtils
open NewThemeUtils
type sortTyp = ASC | DSC
type sortOb = {
sortKey: string,
sortType: sortTyp,
}
type checkBoxProps = {
showCheckBox: bool,
selectedData: array<JSON.t>,
setSelectedData: (array<JSON.t> => array<JSON.t>) => unit,
}
let checkBoxPropDefaultVal: checkBoxProps = {
showCheckBox: false,
selectedData: [],
setSelectedData: _ => (),
}
let sortAtom: Recoil.recoilAtom<Dict.t<sortOb>> = Recoil.atom("sortAtom", Dict.make())
let backgroundClass = "dark:bg-jp-gray-darkgray_background"
let useSortedObj = (title: string, defaultSort) => {
let (dict, setDict) = Recoil.useRecoilState(sortAtom)
let filters = Dict.get(dict, title)
let (sortedObj, setSortedObj) = React.useState(_ => defaultSort)
React.useEffect(() => {
switch filters {
| Some(filt) =>
let sortObj: Table.sortedObject = {
key: filt.sortKey,
order: switch filt.sortType {
| DSC => Table.DEC
| _ => Table.INC
},
}
setSortedObj(_ => Some(sortObj))
| None => ()
}
None
}, [])
// Adding new
React.useEffect(() => {
switch sortedObj {
| Some(obj: Table.sortedObject) =>
let sortOb = {
sortKey: obj.key,
sortType: switch obj.order {
| Table.DEC => DSC
| _ => ASC
},
}
setDict(dict => {
let nDict = Dict.fromArray(Dict.toArray(dict))
Dict.set(nDict, title, sortOb)
nDict
})
| _ => ()
}
None
}, [sortedObj])
(sortedObj, setSortedObj)
}
let sortArray = (originalData, key, sortOrder: Table.sortOrder) => {
let getValue = val => {
switch val {
| Some(x) =>
switch x->JSON.Classify.classify {
| String(str) => str->String.toLowerCase->JSON.Encode.string
| Number(_num) => x
| Bool(val) => val ? "true"->JSON.Encode.string : "false"->JSON.Encode.string
| _ => ""->JSON.Encode.string
}
| None => ""->JSON.Encode.string
}
}
let sortedArrayByOrder = {
originalData->Array.toSorted((i1, i2) => {
let item1 = i1->JSON.stringifyAny->Option.getOr("")->LogicUtils.safeParse
let item2 = i2->JSON.stringifyAny->Option.getOr("")->LogicUtils.safeParse
// flatten items and get data
let val1 =
JsonFlattenUtils.flattenObject(item1, true)
->JSON.Encode.object
->JSON.Decode.object
->Option.flatMap(dict => dict->Dict.get(key))
let val2 =
JsonFlattenUtils.flattenObject(item2, true)
->JSON.Encode.object
->JSON.Decode.object
->Option.flatMap(dict => dict->Dict.get(key))
let value1 = getValue(val1)
let value2 = getValue(val2)
if value1 === ""->JSON.Encode.string || value2 === ""->JSON.Encode.string {
if value1 === value2 {
0.
} else if value2 === ""->JSON.Encode.string {
sortOrder === DEC ? 1. : -1.
} else if sortOrder === DEC {
-1.
} else {
1.
}
} else if value1 === value2 {
0.
} else if value1 > value2 {
sortOrder === DEC ? 1. : -1.
} else if sortOrder === DEC {
-1.
} else {
1.
}
})
}
sortedArrayByOrder
}
type pageDetails = {
offset: int,
resultsPerPage: int,
}
let table_pageDetails: Recoil.recoilAtom<Dict.t<pageDetails>> = Recoil.atom(
"table_pageDetails",
Dict.make(),
)
@react.component
let make = (
~hideCustomisableColumnButton=false,
~visibleColumns=?,
~defaultSort=?,
~title,
~titleSize: NewThemeUtils.headingSize=Large,
~description=?,
~tableActions=?,
~isTableActionBesideFilters=false,
~hideFilterTopPortals=true,
~rightTitleElement=React.null,
~clearFormattedDataButton=?,
~bottomActions=?,
~showSerialNumber=false,
~actualData,
~totalResults,
~resultsPerPage,
~offset,
~setOffset,
~handleRefetch=?,
~entity: EntityType.entityType<'colType, 't>,
~onEntityClick=?,
~onEntityDoubleClick=?,
~onExpandClickData=?,
~currrentFetchCount,
~filters=?,
~showFilterBorder=false,
~headBottomMargin="mb-6 mobile:mb-4",
~removeVerticalLines: option<bool>=?,
~removeHorizontalLines=false,
~evenVertivalLines=false,
~showPagination=true,
~downloadCsv=?,
~ignoreUrlUpdate=false,
~hideTitle=false,
~ignoreHeaderBg=false,
~tableDataLoading=false,
~dataLoading=false,
~advancedSearchComponent=?,
~setData=?,
~setSummary=?,
~dataNotFoundComponent=?,
~renderCard=?,
~tableLocalFilter=false,
~tableheadingClass="",
~tableBorderClass="",
~tableDataBorderClass="",
~collapseTableRow=false,
~getRowDetails=?,
~onMouseEnter=?,
~onMouseLeave=?,
~frozenUpto=?,
~heightHeadingClass=?,
~highlightText="",
~enableEqualWidthCol=false,
~clearFormatting=false,
~rowHeightClass="",
~allowNullableRows=false,
~titleTooltip=false,
~isAnalyticsModule=false,
~rowCustomClass="",
~isHighchartLegend=false,
~filterObj=?,
~setFilterObj=?,
~headingCenter=false,
~filterIcon=?,
~filterDropdownClass=?,
~maxTableHeight="",
~showTableOnMobileView=false,
~labelMargin="",
~customFilterRowStyle="",
~noDataMsg="No Data Available",
~tableActionBorder="",
~isEllipsisTextRelative=true,
~customMoneyStyle="",
~ellipseClass="",
~checkBoxProps: checkBoxProps=checkBoxPropDefaultVal,
~selectedRowColor=?,
~paginationClass="",
~lastHeadingClass="",
~lastColClass="",
~fixLastCol=false,
~headerCustomBgColor=?,
~alignCellContent=?,
~minTableHeightClass="",
~setExtFilteredDataLength=?,
~filterDropdownMaxHeight=?,
~showResultsPerPageSelector=true,
~customCellColor=?,
~defaultResultsPerPage=true,
~noScrollbar=false,
~tableDataBackgroundClass="",
~customBorderClass=?,
~showborderColor=?,
~tableHeadingTextClass="",
~nonFrozenTableParentClass="",
~loadedTableParentClass="",
~remoteSortEnabled=false,
~showAutoScroll=false,
~highlightSelectedRow=false,
) => {
open LogicUtils
let showPopUp = PopUpState.useShowPopUp()
React.useEffect(_ => {
if title->isEmptyString && GlobalVars.isLocalhost {
showPopUp({
popUpType: (Denied, WithIcon),
heading: `Title cannot be empty!`,
description: React.string(`Please put valid title and use hideTitle prop to hide the title as offset recoil uses title`),
handleConfirm: {text: "OK"},
})
}
None
}, [])
let customizeColumnNewTheme = None
let defaultValue: pageDetails = {offset, resultsPerPage}
let (firstRender, setFirstRender) = React.useState(_ => true)
let setPageDetails = Recoil.useSetRecoilState(table_pageDetails)
let pageDetailDict = Recoil.useRecoilValueFromAtom(table_pageDetails)
let pageDetail = pageDetailDict->Dict.get(title)->Option.getOr(defaultValue)
let (
selectAllCheckBox: option<TableUtils.multipleSelectRows>,
setSelectAllCheckBox,
) = React.useState(_ => None)
let newSetOffset = offsetVal => {
let value = switch pageDetailDict->Dict.get(title) {
| Some(val) => {offset: offsetVal(0), resultsPerPage: val.resultsPerPage}
| None => {offset: offsetVal(0), resultsPerPage: defaultValue.resultsPerPage}
}
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(title, value)
setOffset(_ => offsetVal(0))
setPageDetails(_ => newDict)
}
let url = RescriptReactRouter.useUrl()
React.useEffect(_ => {
setFirstRender(_ => false)
setOffset(_ => pageDetail.offset)
None
}, [url.path->List.toArray->Array.joinWith("/")])
React.useEffect(_ => {
if pageDetail.offset !== offset && !firstRender {
let value = switch pageDetailDict->Dict.get(title) {
| Some(val) => {offset, resultsPerPage: val.resultsPerPage}
| None => {offset, resultsPerPage: defaultValue.resultsPerPage}
}
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(title, value)
setPageDetails(_ => newDict)
}
None
}, [offset])
let setLocalResultsPerPageOrig = localResultsPerPage => {
let value = switch pageDetailDict->Dict.get(title) {
| Some(val) =>
if totalResults > val.offset || tableDataLoading {
{offset: val.offset, resultsPerPage: localResultsPerPage(0)}
} else {
{offset: 0, resultsPerPage}
}
| None => {offset: defaultValue.offset, resultsPerPage: localResultsPerPage(0)}
}
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(title, value)
setPageDetails(_ => newDict)
}
let (columnFilter, setColumnFilterOrig) = React.useState(_ => Dict.make())
let isMobileView = MatchMedia.useMobileChecker()
let url = RescriptReactRouter.useUrl()
let dateFormatConvertor = useDateFormatConvertor()
let (dataView, setDataView) = React.useState(_ =>
isMobileView && !showTableOnMobileView ? Card : Table
)
let localResultsPerPage = pageDetail.resultsPerPage
let setColumnFilter = React.useMemo(() => {
(filterKey, filterValue: array<JSON.t>) => {
setColumnFilterOrig(oldFitlers => {
let newObj = oldFitlers->Dict.toArray->Dict.fromArray
let filterValue = filterValue->Array.filter(
item => {
let updatedItem = item->String.make
updatedItem->isNonEmptyString
},
)
if filterValue->Array.length === 0 {
newObj
->Dict.toArray
->Array.filter(
entry => {
let (key, _value) = entry
key !== filterKey
},
)
->Dict.fromArray
} else {
Dict.set(newObj, filterKey, filterValue)
newObj
}
})
}
}, [setColumnFilterOrig])
React.useEffect(_ => {
if columnFilter != Dict.make() {
newSetOffset(_ => 0)
}
None
}, [columnFilter])
let filterValue = React.useMemo(() => {
(columnFilter, setColumnFilter)
}, (columnFilter, setColumnFilter))
let (isFilterOpen, setIsFilterOpenOrig) = React.useState(_ => Dict.make())
let setIsFilterOpen = React.useMemo(() => {
(filterKey, value: bool) => {
setIsFilterOpenOrig(oldFitlers => {
let newObj = oldFitlers->DictionaryUtils.copyOfDict
newObj->Dict.set(filterKey, value)
newObj
})
}
}, [setColumnFilterOrig])
let filterOpenValue = React.useMemo(() => {
(isFilterOpen, setIsFilterOpen)
}, (isFilterOpen, setIsFilterOpen))
let heading = visibleColumns->Option.getOr(entity.defaultColumns)->Array.map(entity.getHeading)
let handleRemoveLines = removeVerticalLines->Option.getOr(true)
if showSerialNumber {
heading
->Array.unshift(
Table.makeHeaderInfo(~key="serial_number", ~title="S.No", ~dataType=NumericType),
)
->ignore
}
if checkBoxProps.showCheckBox {
heading
->Array.unshift(Table.makeHeaderInfo(~key="select", ~title="", ~showMultiSelectCheckBox=true))
->ignore
}
let setLocalResultsPerPage = React.useCallback(fn => {
setLocalResultsPerPageOrig(prev => {
let newVal = prev->fn
if newVal == 0 {
localResultsPerPage
} else {
newVal
}
})
}, [setLocalResultsPerPageOrig])
let {getShowLink, searchFields, searchUrl} = entity
let (sortedObj, setSortedObj) = useSortedObj(title, defaultSort)
React.useEffect(() => {
setDataView(_prev => isMobileView && !showTableOnMobileView ? Card : Table)
None
}, [isMobileView])
let defaultOffset = totalResults / localResultsPerPage * localResultsPerPage
let offsetVal = offset < totalResults ? offset : defaultOffset
let offsetVal = ignoreUrlUpdate ? offset : offsetVal
React.useEffect(() => {
if offset > currrentFetchCount && offset <= totalResults && !tableDataLoading {
switch handleRefetch {
| Some(fun) => fun()
| None => ()
}
}
None
}, (offset, currrentFetchCount, totalResults, tableDataLoading))
let originalActualData = actualData
let actualData = React.useMemo(() => {
if tableLocalFilter {
filteredData(actualData, columnFilter, visibleColumns, entity, dateFormatConvertor)
} else {
actualData
}
}, (actualData, columnFilter, visibleColumns, entity, dateFormatConvertor))
let columnFilterRow = React.useMemo(() => {
if tableLocalFilter {
let columnFilterRow =
visibleColumns
->Option.getOr(entity.defaultColumns)
->Array.map(item => {
let headingEntity = entity.getHeading(item)
let key = headingEntity.key
let dataType = headingEntity.dataType
let filterValueArray = []
let columnFilterCopy = columnFilter->DictionaryUtils.deleteKey(key)
let actualData =
columnFilter->Dict.keysToArray->Array.includes(headingEntity.key)
? originalActualData
: actualData
actualData
->filteredData(columnFilterCopy, visibleColumns, entity, dateFormatConvertor)
->Array.forEach(
rows => {
switch rows->Nullable.toOption {
| Some(rows) =>
let value = switch entity.getCell(rows, item) {
| CustomCell(_, str)
| DisplayCopyCell(str)
| EllipsisText(str, _)
| Link(str)
| Date(str)
| DateWithoutTime(str)
| DateWithCustomDateStyle(str, _)
| Text(str) =>
convertStrCellToFloat(dataType, str)
| Label(x)
| ColoredText(x) =>
convertStrCellToFloat(dataType, x.title)
| DeltaPercentage(num, _) | Currency(num, _) | Numeric(num, _) =>
convertFloatCellToStr(dataType, num)
| Progress(num) => convertFloatCellToStr(dataType, num->Int.toFloat)
| StartEndDate(_) | InputField(_) | TrimmedText(_) | DropDown(_) =>
convertStrCellToFloat(dataType, "")
}
filterValueArray->Array.push(value)->ignore
| None => ()
}
},
)
switch dataType {
| DropDown => Table.DropDownFilter(key, filterValueArray) // TextDropDownColumn
| LabelType | TextType => Table.TextFilter(key)
| MoneyType | NumericType | ProgressType => {
let newArr =
filterValueArray->Array.map(item => item->JSON.Decode.float->Option.getOr(0.))
if newArr->Array.length >= 1 {
Table.Range(key, Math.minMany(newArr), Math.maxMany(newArr))
} else {
Table.Range(key, 0.0, 0.0)
}
}
}
})
Some(
showSerialNumber && tableLocalFilter
? Array.concat(
[Table.Range("s_no", 0., actualData->Array.length->Int.toFloat)],
columnFilterRow,
)
: columnFilterRow,
)
} else {
None
}
}, (actualData, totalResults, visibleColumns, columnFilter))
let filteredDataLength =
columnFilter->Dict.keysToArray->Array.length !== 0 ? actualData->Array.length : totalResults
React.useEffect(() => {
switch setExtFilteredDataLength {
| Some(fn) => fn(_ => filteredDataLength)
| _ => ()
}
None
}, [filteredDataLength])
let filteredData = React.useMemo(() => {
if !remoteSortEnabled {
switch sortedObj {
| Some(obj: Table.sortedObject) => sortArray(actualData, obj.key, obj.order)
| None => actualData
}
} else {
actualData
}
}, (sortedObj, actualData))
React.useEffect(() => {
let selectedRowDataLength = checkBoxProps.selectedData->Array.length
let isCompleteDataSelected = selectedRowDataLength === filteredData->Array.length
if isCompleteDataSelected {
setSelectAllCheckBox(_ => Some(ALL))
} else if checkBoxProps.selectedData->Array.length === 0 {
setSelectAllCheckBox(_ => None)
} else {
setSelectAllCheckBox(_ => Some(PARTIAL))
}
None
}, (checkBoxProps.selectedData, filteredData))
React.useEffect(() => {
if selectAllCheckBox === Some(ALL) {
checkBoxProps.setSelectedData(_ => {
filteredData->Array.map(
ele => {
ele->Identity.nullableOfAnyTypeToJsonType
},
)
})
} else if selectAllCheckBox === None {
checkBoxProps.setSelectedData(_ => [])
}
None
}, [selectAllCheckBox])
let sNoArr = Dict.get(columnFilter, "s_no")->Option.getOr([])
// filtering for SNO
let nullableRows = filteredData->Array.mapWithIndex((nullableItem, index) => {
let actualRows = switch nullableItem->Nullable.toOption {
| Some(item) => {
let visibleCell =
visibleColumns
->Option.getOr(entity.defaultColumns)
->Array.map(colType => {
entity.getCell(item, colType)
})
let startPoint = sNoArr->Array.get(0)->Option.getOr(1.->JSON.Encode.float)
let endPoint = sNoArr->Array.get(1)->Option.getOr(1.->JSON.Encode.float)
let jsonIndex = (index + 1)->Int.toFloat->JSON.Encode.float
sNoArr->Array.length > 0
? {
startPoint <= jsonIndex && endPoint >= jsonIndex ? visibleCell : []
}
: visibleCell
}
| None => []
}
let setIsSelected = isSelected => {
if isSelected {
checkBoxProps.setSelectedData(prev =>
prev->Array.concat([nullableItem->Identity.nullableOfAnyTypeToJsonType])
)
} else {
checkBoxProps.setSelectedData(prev =>
prev->Array.filter(item => item !== nullableItem->Identity.nullableOfAnyTypeToJsonType)
)
}
}
if actualRows->Array.length > 0 {
if showSerialNumber {
actualRows
->Array.unshift(
Numeric(
(1 + index)->Int.toFloat,
(val: float) => {
val->Float.toString
},
),
)
->ignore
}
if checkBoxProps.showCheckBox {
let selectedRowIndex =
checkBoxProps.selectedData->Array.findIndex(item =>
item === nullableItem->Identity.nullableOfAnyTypeToJsonType
)
actualRows
->Array.unshift(
CustomCell(
<div onClick={ev => ev->ReactEvent.Mouse.stopPropagation}>
<CheckBoxIcon
isSelected={selectedRowIndex !== -1} setIsSelected checkboxDimension="h-4 w-4"
/>
</div>,
(selectedRowIndex !== -1)->getStringFromBool,
),
)
->ignore
}
}
actualRows
})
let rows = if allowNullableRows {
nullableRows
} else {
nullableRows->Belt.Array.keepMap(item => {
item->Array.length == 0 ? None : Some(item)
})
}
let paginatedData =
filteredData->Array.slice(~start=offsetVal, ~end={offsetVal + localResultsPerPage})
let rows = rows->Array.slice(~start=offsetVal, ~end={offsetVal + localResultsPerPage})
let handleRowClick = React.useCallback(index => {
let actualVal = switch filteredData[index] {
| Some(ele) => ele->Nullable.toOption
| None => None
}
switch actualVal {
| Some(value) =>
switch onEntityClick {
| Some(fn) => fn(value)
| None =>
switch getShowLink {
| Some(fn) => {
let link = fn(value)
let finalUrl = url.search->isNonEmptyString ? `${link}?${url.search}` : link
RescriptReactRouter.push(finalUrl)
}
| None => ()
}
}
| None => ()
}
}, (filteredData, getShowLink, onEntityClick, url.search))
let onRowDoubleClick = React.useCallback(index => {
let actualVal = switch filteredData[index] {
| Some(ele) => ele->Nullable.toOption
| None => None
}
switch actualVal {
| Some(value) =>
switch onEntityDoubleClick {
| Some(fn) => fn(value)
| None =>
switch getShowLink {
| Some(fn) => {
let link = fn(value)
let finalUrl = url.search->isNonEmptyString ? `${link}?${url.search}` : link
RescriptReactRouter.push(finalUrl)
}
| None => ()
}
}
| None => ()
}
}, (filteredData, getShowLink, onEntityDoubleClick, url.search))
let handleMouseEnter = React.useCallback(index => {
let actualVal = switch filteredData[index] {
| Some(ele) => ele->Nullable.toOption
| None => None
}
switch actualVal {
| Some(value) =>
switch onMouseEnter {
| Some(fn) => fn(value)
| None => ()
}
| None => ()
}
}, (filteredData, getShowLink, onMouseEnter, url.search))
let handleMouseLeaeve = React.useCallback(index => {
let actualVal = switch filteredData[index] {
| Some(ele) => ele->Nullable.toOption
| None => None
}
switch actualVal {
| Some(value) =>
switch onMouseLeave {
| Some(fn) => fn(value)
| None => ()
}
| None => ()
}
}, (filteredData, getShowLink, onMouseLeave, url.search))
let filterBottomPadding = isMobileView ? "" : "pb-4"
let paddingClass = {rightTitleElement != React.null ? filterBottomPadding : ""}
let customizeColumsButtons = {
switch clearFormattedDataButton {
| Some(clearFormattedDataButton) =>
<div className={`flex flex-row mobile:gap-7 desktop:gap-10 ${filterBottomPadding}`}>
clearFormattedDataButton
{rightTitleElement}
</div>
| _ => <div className={paddingClass}> {rightTitleElement} </div>
}
}
let (loadedTableUI, paginationUI) = if totalResults > 0 {
let paginationUI = if showPagination {
<AddDataAttributes attributes=[("data-paginator", "dynamicTablePaginator")]>
<Paginator
totalResults=filteredDataLength
offset=offsetVal
resultsPerPage=localResultsPerPage
setOffset=newSetOffset
?handleRefetch
currrentFetchCount
?downloadCsv
actualData
tableDataLoading
setResultsPerPage=setLocalResultsPerPage
paginationClass
showResultsPerPageSelector
/>
</AddDataAttributes>
} else {
React.null
}
let isMinHeightRequired =
noScrollbar || (tableLocalFilter && rows->Array.length <= 5 && frozenUpto->Option.isNone)
let scrollBarClass =
isFilterOpen->Dict.valuesToArray->Array.reduce(false, (acc, item) => item || acc)
? ""
: `${isMinHeightRequired ? noScrollbar ? "" : "overflow-x-scroll" : "overflow-scroll"}`
let loadedTable =
<div className={`no-scrollbar ${scrollBarClass}`}>
{switch dataView {
| Table => {
let children =
<Table
title
heading
rows
?filterObj
?setFilterObj
onRowClick=handleRowClick
onRowDoubleClick
onRowClickPresent={onEntityClick->Option.isSome || getShowLink->Option.isSome}
offset=offsetVal
setSortedObj
?sortedObj
removeVerticalLines=handleRemoveLines
evenVertivalLines
?columnFilterRow
tableheadingClass
tableBorderClass
tableDataBorderClass
enableEqualWidthCol
collapseTableRow
?getRowDetails
?onExpandClickData
actualData
onMouseEnter=handleMouseEnter
onMouseLeave=handleMouseLeaeve
highlightText
clearFormatting
?heightHeadingClass
?frozenUpto
rowHeightClass
isMinHeightRequired
rowCustomClass
isHighchartLegend
headingCenter
?filterIcon
?filterDropdownClass
maxTableHeight
labelMargin
customFilterRowStyle
?selectAllCheckBox
setSelectAllCheckBox
isEllipsisTextRelative
customMoneyStyle
ellipseClass
?selectedRowColor
lastHeadingClass
showCheckbox={checkBoxProps.showCheckBox}
lastColClass
fixLastCol
?headerCustomBgColor
?alignCellContent
?customCellColor
minTableHeightClass
?filterDropdownMaxHeight
?customizeColumnNewTheme
removeHorizontalLines
?customBorderClass
?showborderColor
tableHeadingTextClass
nonFrozenTableParentClass
showAutoScroll
showPagination
highlightSelectedRow
/>
switch tableLocalFilter {
| true =>
<DatatableContext value={filterValue}>
<DataTableFilterOpenContext value={filterOpenValue}>
children
</DataTableFilterOpenContext>
</DatatableContext>
| false => children
}
}
| Card =>
switch renderCard {
| Some(renderer) =>
<div className="overflow-auto flex flex-col">
{paginatedData
->Belt.Array.keepMap(Nullable.toOption)
->Array.mapWithIndex((item, rowIndex) => {
renderer(~index={rowIndex + offset}, ~item, ~onRowClick=handleRowClick)
})
->React.array}
</div>
| None =>
<CardTable heading rows onRowClick=handleRowClick offset=offsetVal isAnalyticsModule />
}
}}
</div>
(loadedTable, paginationUI)
} else if totalResults === 0 && !tableDataLoading {
let noDataTable = switch dataNotFoundComponent {
| Some(comp) => comp
| None => <NoDataFound customCssClass={"my-6"} message=noDataMsg renderType=Painting />
}
(noDataTable, React.null)
} else {
(React.null, React.null)
}
let tableActionBorder = if !isMobileView {
if showFilterBorder {
"p-2 bg-white dark:bg-black border border-jp-2-light-gray-400 rounded-lg"
} else {
""
}
} else {
tableActionBorder
}
let filtersOuterMargin = if hideTitle {
""
} else {
"my-2"
}
let tableActionElements =
<div className="flex flex-row">
{switch advancedSearchComponent {
| Some(x) =>
<AdvancedSearchComponent entity ?setData ?setSummary> {x} </AdvancedSearchComponent>
| None =>
<RenderIf condition={searchFields->Array.length > 0}>
<AdvancedSearchModal searchFields url=searchUrl entity />
</RenderIf>
}}
{switch tableActions {
| Some(actions) =>
<LoadedTableContext value={actualData->LoadedTableContext.toInfoData}>
<div className=filterBottomPadding> actions </div>
</LoadedTableContext>
| None => React.null
}}
</div>
let addDataAttributesClass = if isHighchartLegend {
`visibility: hidden`
} else {
`${ignoreHeaderBg ? "" : backgroundClass} empty:hidden`
}
let dataId = title->String.split("-")->Array.get(0)->Option.getOr("")
<AddDataAttributes attributes=[("data-loaded-table", dataId)]>
<div className={`w-full ${loadedTableParentClass}`}>
<div className=addDataAttributesClass style={zIndex: "2"}>
//removed "sticky" -> to be tested with master
<div
className={`flex flex-row justify-between items-center` ++ (
hideTitle ? "" : ` mt-4 mb-2`
)}>
<div className="w-full">
<RenderIf condition={!hideTitle}>
<NewThemeHeading
headingColor="text-nd_gray-600"
heading=title
headingSize=titleSize
outerMargin=""
?description
rightActions={<RenderIf condition={!isMobileView && !isTableActionBesideFilters}>
{tableActionElements}
</RenderIf>}
/>
</RenderIf>
</div>
</div>
<RenderIf condition={!hideFilterTopPortals}>
<div className="flex justify-between items-center">
<PortalCapture
key={`tableFilterTopLeft-${title}`}
name={`tableFilterTopLeft-${title}`}
customStyle="flex items-center gap-x-2"
/>
<PortalCapture
key={`tableFilterTopRight-${title}`}
name={`tableFilterTopRight-${title}`}
customStyle="flex flex-row-reverse items-center gap-x-2"
/>
</div>
</RenderIf>
<div
className={`flex flex-row mobile:flex-wrap items-center ${tableActionBorder} ${filtersOuterMargin}`}>
<TableFilterSectionContext isFilterSection=true>
<div className={`flex-1 ${tableDataBackgroundClass}`}>
{switch filters {
| Some(filterSection) =>
filterSection->React.Children.map(element => {
if element === React.null {
React.null
} else {
<div className=filterBottomPadding> element </div>
}
})
| None => React.null
}}
<PortalCapture key={`extraFilters-${title}`} name={`extraFilters-${title}`} />
</div>
</TableFilterSectionContext>
<RenderIf condition={isTableActionBesideFilters || isMobileView || hideTitle}>
{tableActionElements}
</RenderIf>
<RenderIf condition={!hideCustomisableColumnButton}> customizeColumsButtons </RenderIf>
</div>
</div>
{if dataLoading {
<TableDataLoadingIndicator showWithData={rows->Array.length !== 0} />
} else {
loadedTableUI
}}
<RenderIf condition={tableDataLoading && !dataLoading}>
<TableDataLoadingIndicator showWithData={rows->Array.length !== 0} />
</RenderIf>
<div
className={`${tableActions->Option.isSome && isMobileView
? `flex flex-row-reverse justify-between mb-10 ${tableDataBackgroundClass}`
: tableDataBackgroundClass}`}>
paginationUI
{
let topBottomActions = if bottomActions->Option.isSome {
bottomActions
} else {
None
}
switch topBottomActions {
| Some(actions) =>
<LoadedTableContext value={actualData->LoadedTableContext.toInfoData}>
actions
</LoadedTableContext>
| None => React.null
}
}
</div>
</div>
</AddDataAttributes>
}
| 7,254 | 10,033 |
hyperswitch-control-center | src/components/RippleEffectBackground.res | .res | type styleObj
type event
type domObj = {
clientWidth: int,
clientHeight: int,
}
@get external style: Dom.element => styleObj = "style"
@send external setAttribute: (Dom.element, string, string) => unit = "setAttribute"
@val external document: 'a = "document"
@set external setWidth: (styleObj, string) => unit = "width"
@send external prepend: ('a, Dom.element) => unit = "prepend"
@set external setHeight: (styleObj, string) => unit = "height"
@send external removeChild: ('a, Dom.element) => unit = "removeChild"
@set external setOpacity: (styleObj, string) => unit = "opacity"
@set external setTransitionDuration: (styleObj, string) => unit = "transitionDuration"
@set external setaAnimationTimingFunction: (styleObj, string) => unit = "animationTimingFunction"
@send external addEventListener: (Dom.element, string, event => unit) => unit = "addEventListener"
@send
external removeEventListener: (Dom.element, string, event => unit) => unit = "removeEventListener"
let useLinearRippleHook = (ref: React.ref<Nullable.t<Dom.element>>, shouldRipple) => {
React.useEffect(() => {
let handleMouseOver = _ => {
switch ref.current->Nullable.toOption {
| Some(splash) => {
let link = document->DOMUtils.createElement("div")
link->setAttribute(
"class",
"absolute bg-[#0000000a] dark:bg-[#ffffff1f] w-0 h-0 animate-textTransitionSideBar ",
)
splash->prepend(link)
link->style->setOpacity("60")
link->style->setHeight(`70px`)
link->style->setWidth(`400px`)
link->style->setaAnimationTimingFunction("linear")
setTimeout(() => {
splash->removeChild(link)
}, 300)->ignore
}
| None => ()
}
}
switch ref.current->Nullable.toOption {
| Some(elem) =>
if shouldRipple {
elem->addEventListener("mousedown", handleMouseOver)
Some(
() => {
elem->removeEventListener("mousedown", handleMouseOver)
},
)
} else {
None
}
| None => None
}
}, [ref])
}
let useHorizontalRippleHook = (ref: React.ref<Nullable.t<Dom.element>>) => {
React.useEffect(() => {
let handleMouseOver = _ => {
switch ref.current->Nullable.toOption {
| Some(splash) => {
let link = document->DOMUtils.createElement("div")
link->setAttribute(
"class",
"absolute bg-[#00000014] dark:bg-[#ffffff1f] top-1/2 left-1/2 -translate-x-2/4 -translate-y-2/4 rounded-full",
)
splash->prepend(link)
link->style->setOpacity("20")
link->style->setTransitionDuration(".4s")
link->style->setHeight("70px")
link->style->setWidth("70px")
setTimeout(() => {
link->style->setHeight("400px")
link->style->setWidth("400px")
link->style->setOpacity("20")
link->style->setaAnimationTimingFunction("cubic-bezier(0.25, 0.1, 0.25, 1)")
}, 0)->ignore
setTimeout(() => {
splash->removeChild(link)
}, 400)->ignore
}
| None => ()
}
}
switch ref.current->Nullable.toOption {
| Some(elem) =>
elem->addEventListener("mousedown", handleMouseOver)
Some(
() => {
elem->removeEventListener("mousedown", handleMouseOver)
},
)
| None => None
}
}, [ref])
}
| 886 | 10,034 |
hyperswitch-control-center | src/components/ToastContainer.res | .res | module ToastHeading = {
@react.component
let make = (~toastProps: ToastState.toastProps, ~hideToast, ~toastDuration=0) => {
React.useEffect(() => {
let duration = if toastDuration == 0 {
3000
} else {
toastDuration
}
let timeout = {
setTimeout(() => {
hideToast(toastProps.toastKey)
}, duration)
}
Some(
() => {
clearTimeout(timeout)
},
)
}, (hideToast, toastProps))
let toastColorClasses = switch toastProps.toastType {
| ToastError => "border-l-red-status"
| ToastWarning => "border-l-orange-500"
| ToastInfo => "border-l-blue-600"
| ToastSuccess => "border-l-green-status"
}
let toastIconName = switch toastProps.toastType {
| ToastSuccess => "nd-toast-success"
| ToastError
| ToastWarning => "nd-toast-warning"
| ToastInfo => "nd-toast-info"
}
let toastIconColorClass = switch toastProps.toastType {
| ToastSuccess => "text-green-status"
| ToastError => "text-red-status"
| ToastWarning => "text-orange-400"
| ToastInfo => "text-nd_primary_blue-500"
}
let onClickButtonText = () => {
RescriptReactRouter.push(
switch toastProps.helpLink {
| Some(str) => GlobalVars.appendDashboardPath(~url=str)
| None => GlobalVars.appendDashboardPath(~url="")
},
)
}
<div
className={`${toastColorClasses} rounded-lg shadow-sm bg-white border border-l-4 p-4 flex items-center justify-between`}>
<div className="flex items-center">
<Icon className={`${toastIconColorClass} mr-3`} name=toastIconName />
<AddDataAttributes attributes=[("data-toast", toastProps.message)]>
<div className="text-gray-800 font-medium"> {toastProps.message->React.string} </div>
</AddDataAttributes>
</div>
{switch toastProps.buttonText {
| Some(text) =>
<div className="ml-4">
<button
onClick={_ => onClickButtonText()}
className="text-sm text-gray-600 hover:text-gray-800 font-medium">
{React.string(text)}
</button>
</div>
| None => React.null
}}
</div>
}
}
module Toast = {
external convertToWebapiEvent: ReactEvent.Mouse.t => Webapi.Dom.Event.t = "%identity"
@react.component
let make = (~toastProps: ToastState.toastProps, ~hideToast, ~toastDuration) => {
let stopPropagation = React.useCallback(ev => {
ev->convertToWebapiEvent->Webapi.Dom.Event.stopPropagation
}, [])
<div className="m-2 shadow-lg rounded-lg pointer-events-auto z-50" onClick=stopPropagation>
<ToastHeading toastProps hideToast toastDuration />
</div>
}
}
@react.component
let make = (~children) => {
let (openToasts, setOpenToasts) = Recoil.useRecoilState(ToastState.openToasts)
let hideToast = React.useCallback(key => {
setOpenToasts(prevArr => {
Array.filter(
prevArr,
(toastProps: ToastState.toastProps) => {
toastProps.toastKey !== key
},
)
})
}, [setOpenToasts])
<div className="relative">
{children}
<div>
<div
className="fixed top-4 left-1/2 transform -translate-x-1/2 flex flex-col gap-2 pointer-events-none max-w-md z-50">
{openToasts
->Array.map(toastProps => {
if toastProps.toastElement != React.null {
toastProps.toastElement
} else {
<Toast
key={toastProps.toastKey}
toastProps
hideToast
toastDuration={toastProps.toastDuration}
/>
}
})
->React.array}
</div>
</div>
</div>
}
| 917 | 10,035 |
hyperswitch-control-center | src/components/HSwitchSingleStatWidget.res | .res | type statChartColor = [#blue | #grey]
open ApexCharts
@react.component
let make = (
~title,
~tooltipText,
~deltaTooltipComponent=React.null,
~value: float,
~data,
~statType="",
~borderRounded="rounded-lg",
~singleStatLoading=false,
~showPercentage=true,
~loaderType: AnalyticsUtils.loaderType=Shimmer,
~statChartColor: statChartColor=#blue,
~filterNullVals: bool=false,
~statSentiment: Dict.t<AnalyticsUtils.statSentiment>=Dict.make(),
~statThreshold: Dict.t<float>=Dict.make(),
~fullWidth=false,
) => {
let percentFormat = value => {
`${Float.toFixedWithPrecision(value, ~digits=2)}%`
}
// if day > then only date else time
let statValue = statType => {
open LogicUtils
if statType === "Amount" {
value->indianShortNum
} else if statType === "Rate" || statType === "NegativeRate" {
value->Js.Float.isNaN ? "-" : value->percentFormat
} else if statType === "Volume" {
value->indianShortNum
} else if statType === "Latency" {
latencyShortNum(~labelValue=value)
} else if statType === "LatencyMs" {
latencyShortNum(~labelValue=value, ~includeMilliseconds=true)
} else {
value->Float.toString
}
}
let isMobileWidth = MatchMedia.useMatchMedia("(max-width: 700px)")
let sortedData1 = React.useMemo(() => {
data
->Array.toSorted((item1, item2) => {
let (x1, _y1) = item1
let (x2, _y2) = item2
if x1 > x2 {
-1.
} else if x1 == x2 {
0.
} else {
1.
}
})
->Array.map(item => {
let (x, y) = item
{
x,
y,
}
})
}, [data])
let _options1 = {
chart: {
height: 10,
toolbar: {
show: false,
},
},
legend: {show: false},
stroke: {curve: "smooth"},
dataLabels: {enabled: false},
grid: {show: false},
xaxis: {
labels: {
show: false, // Hide x-axis labels
},
axisBorder: {
show: false, // Hide x-axis border
},
axisTicks: {
show: false, // Hide x-axis ticks
},
},
yaxis: {
labels: {
show: false, // Hide x-axis labels
},
axisBorder: {
show: false, // Hide x-axis border
},
axisTicks: {
show: false, // Hide x-axis ticks
},
},
tooltip: {
enabled: false,
},
colors: ["#006DF9"],
}
let _series = [
{
\"type": "area",
data: sortedData1,
},
]
if singleStatLoading && loaderType === Shimmer {
<div className={`p-4`} style={width: fullWidth ? "100%" : isMobileWidth ? "100%" : "33.33%"}>
<Shimmer styleClass="w-full h-28" />
</div>
} else {
<div
className="h-full mt-4" style={width: fullWidth ? "100%" : isMobileWidth ? "100%" : "33.33%"}>
<div
className={`h-full flex flex-col border ${borderRounded} dark:border-jp-gray-850 bg-white dark:bg-jp-gray-lightgray_background overflow-hidden singlestatBox p-2 md:mr-4`}>
<div className="p-4 flex flex-col justify-between h-full gap-auto">
<RenderIf condition={singleStatLoading && loaderType === SideLoader}>
<div className="animate-spin self-end absolute">
<Icon name="spinner" size=16 />
</div>
</RenderIf>
<div className="flex justify-between w-full h-1/2 items-end">
<div className="font-bold text-3xl w-1/3">
{statValue(statType)->String.toLowerCase->React.string}
</div>
// <div className="h-16 w-2/3 scale-[0.4]">
// <ApexCharts.ReactApexChart
// \"type"="area"
// options={options1}
// series={series->objToJson}
// height={"170"}
// width="380"
// />
// </div>
</div>
<div
className={"flex gap-2 items-center pt-4 text-jp-gray-700 font-bold self-start h-1/2"}>
<div className="font-semibold text-base text-black dark:text-white">
{title->React.string}
</div>
<ToolTip
description=tooltipText
toolTipFor={<div className="cursor-pointer">
<Icon name="info-vacent" size=13 />
</div>}
toolTipPosition=ToolTip.Top
newDesign=true
/>
</div>
</div>
</div>
</div>
}
}
| 1,229 | 10,036 |
hyperswitch-control-center | src/components/UnauthorizedPage.res | .res | @react.component
let make = (
~message="You don't have access to this module. Contact admin for access",
~url="unauthorized",
) => {
let {setDashboardPageState} = React.useContext(GlobalProvider.defaultContext)
<NoDataFound message renderType={Locked}>
<Button
text={"Go to Home"}
buttonType=Primary
buttonSize=Small
onClick={_ => {
setDashboardPageState(_ => #HOME)
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/home"))
}}
customButtonStyle="mt-4"
/>
</NoDataFound>
}
| 139 | 10,037 |
hyperswitch-control-center | src/components/RemoteFiltersUtils.res | .res | open LogicUtils
type urlKEyType = Boolean | Float | Int
let getFinalDict = (
~filterJson,
~filtersFromUrl,
~options: array<EntityType.optionType<'t>>,
~isEulerOrderEntity,
~dropdownSearchKeyValueNames,
~searchkeysDict,
~isSearchKeyArray,
~defaultKeysAllowed=["offset", "order", "orderType", "merchantId"],
~urlKeyTypeDict,
(),
) => {
let unflattenDict = filtersFromUrl->JsonFlattenUtils.unflattenObject
let filterDict = Dict.make()
switch filterJson->JSON.Decode.object {
| Some(dict) => {
// Hack for admin service config entity
let allowedDefaultKeys = if dict->Dict.get("sourceObject")->Option.isSome {
Dict.keysToArray(dict)
} else {
defaultKeysAllowed
}
// Hack for orders entity
dict
->Dict.toArray
->Array.forEach(entry => {
let (key, val) = entry
if Array.includes(allowedDefaultKeys, key) {
filterDict->Dict.set(key, val)
}
})
}
| None => ()
}
unflattenDict
->Dict.toArray
->Array.forEach(entry => {
let (key, val) = entry
let parser = switch options->Array.find(option => {
option.urlKey === key
}) {
| Some(selectedOption) => selectedOption.parser
| None => x => x
}
filterDict->Dict.set(key, parser(val))
let val = switch urlKeyTypeDict->Dict.toArray->Array.find(((urlKey, _)) => key === urlKey) {
| Some((_, value)) =>
let getExpectedType = ele => {
switch value {
| Boolean => ele->getBoolFromString(false)->JSON.Encode.bool
| Float => ele->getFloatFromString(0.)->JSON.Encode.float
| Int => ele->getIntFromString(0)->Int.toFloat->JSON.Encode.float
}
}
switch val->JSON.Classify.classify {
| Array(stringValueArr) =>
stringValueArr
->Array.map(ele => {
getExpectedType(ele->JSON.Decode.string->Option.getOr(""))
})
->JSON.Encode.array
| String(ele) => getExpectedType(ele)
| _ => val
}
| None => val
}
filterDict->Dict.set(key, val)
})
if filterDict->Dict.keysToArray->Array.length === 0 {
filterJson
} else {
if dropdownSearchKeyValueNames->Array.length === 2 {
if !isSearchKeyArray {
let key =
filterDict->getString(dropdownSearchKeyValueNames[0]->Option.getOr(""), "")->toCamelCase
let value = filterDict->getString(dropdownSearchKeyValueNames[1]->Option.getOr(""), "")
if value->isNonEmptyString {
let isformat = searchkeysDict !== Dict.make()
let value = if isformat {
let intSearchKeys = searchkeysDict->getArrayFromDict("intSearchKeys", [])
let arrSearchKeys = searchkeysDict->getArrayFromDict("arrSearchKeys", [])
if intSearchKeys->Array.includes(key->JSON.Encode.string) {
value->getFloatFromString(0.00)->JSON.Encode.float
} else if arrSearchKeys->Array.includes(key->JSON.Encode.string) {
value->String.split(",")->Array.map(str => str->JSON.Encode.string)->JSON.Encode.array
} else {
value->JSON.Encode.string
}
} else {
value->JSON.Encode.string
}
filterDict->Dict.set(key, value)
}
} else {
let key =
filterDict
->getArrayFromDict(dropdownSearchKeyValueNames[0]->Option.getOr(""), [])
->Array.map(item => item->getStringFromJson("")->toCamelCase)
let value =
filterDict
->getString(dropdownSearchKeyValueNames[1]->Option.getOr(""), "")
->String.split(", ")
value->Array.forEachWithIndex((value, indx) => {
let key = key->Array.length > indx ? key[indx]->Option.getOr("") : ""
if value->isNonEmptyString && key->isNonEmptyString {
let isformat = searchkeysDict !== Dict.make()
let value = if isformat {
let intSearchKeys = searchkeysDict->getArrayFromDict("intSearchKeys", [])
let arrSearchKeys = searchkeysDict->getArrayFromDict("arrSearchKeys", [])
if intSearchKeys->Array.includes(key->JSON.Encode.string) {
value->getFloatFromString(0.00)->JSON.Encode.float
} else if arrSearchKeys->Array.includes(key->JSON.Encode.string) {
value
->String.split(",")
->Array.map(str => str->JSON.Encode.string)
->JSON.Encode.array
} else {
value->JSON.Encode.string
}
} else {
value->JSON.Encode.string
}
filterDict->Dict.set(key, value)
}
})
}
}
if isEulerOrderEntity {
let arr = if filterDict->Dict.get("customerId")->Option.isSome {
[["date_created", "DESC"]->getJsonFromArrayOfString]
} else {
[]
}
filterDict->Dict.set("order", arr->JSON.Encode.array)
}
filterDict->JSON.Encode.object
}
}
let getStrFromJson = (key, val) => {
switch val->JSON.Classify.classify {
| String(str) => str
| Array(array) => array->Array.length > 0 ? `[${array->Array.joinWithUnsafe(",")}]` : ""
| Number(num) => key === "offset" ? "0" : num->Float.toString
| _ => ""
}
}
let getInitialValuesFromUrl = (
~searchParams,
~initialFilters: array<EntityType.initialFilters<'t>>,
~options: array<EntityType.optionType<'t>>=[],
~mandatoryRemoteKeys: array<string>=[],
(),
) => {
let initialFilters = initialFilters->Array.map(item => item.field)
let dict = Dict.make()
let searchParams = searchParams->stringReplaceAll("%20", " ")
if String.length(searchParams) > 0 {
let splitUrlArray = String.split(searchParams, "&")
let entriesList = []
let keyList = []
let valueList = []
splitUrlArray->Array.forEach(filterKeyVal => {
let splitArray = String.split(filterKeyVal, "=")
let keyStartIndex = String.lastIndexOf(splitArray[0]->Option.getOr(""), "-") + 1
let key = String.sliceToEnd(splitArray[0]->Option.getOr(""), ~start=keyStartIndex)
Array.push(keyList, key)->ignore
splitArray->Array.shift->ignore
let value = splitArray->Array.joinWith("=")
Array.push(valueList, value)->ignore
entriesList->Array.push((key, value))->ignore
})
entriesList->Array.forEach(entry => {
let (key, value) = entry
initialFilters->Array.forEach((filter: FormRenderer.fieldInfoType) => {
filter.inputNames->Array.forEach(
name => {
if name === key || OrderUIUtils.isParentChildFilterMatch(name, key) {
Dict.set(dict, key, value->UrlFetchUtils.getFilterValue)
}
},
)
})
options->Array.forEach(option => {
let fieldName = option.urlKey
if fieldName === key {
Dict.set(dict, key, value->UrlFetchUtils.getFilterValue)
}
})
mandatoryRemoteKeys->Array.forEach(searchKey => {
if searchKey === key {
Dict.set(dict, key, value->UrlFetchUtils.getFilterValue)
}
})
})
}
JSON.Encode.object(dict)
}
let getLocalFiltersData = (
~resArr: array<Nullable.t<'t>>,
~searchParams,
~initialFilters: array<EntityType.initialFilters<'t>>,
~dateRangeFilterDict: Dict.t<JSON.t>,
~options: array<EntityType.optionType<'t>>,
(),
) => {
let res = ref(resArr)
if String.length(searchParams) > 0 {
let splitUrlArray = String.split(searchParams, "&")
let keyList = []
let valueList = []
splitUrlArray->Array.forEach(filterKeyVal => {
let splitArray = String.split(filterKeyVal, "=")
let keyStartIndex = String.lastIndexOf(splitArray[0]->Option.getOr(""), `-`) + 1
let key = String.sliceToEnd(splitArray[0]->Option.getOr(""), ~start=keyStartIndex)
Array.push(keyList, key)->ignore
Array.push(valueList, splitArray[1]->Option.getOr(""))->ignore
})
let dateRange = dateRangeFilterDict->getArrayFromDict("dateRange", [])
let startKey =
dateRange->Array.get(0)->Option.getOr(""->JSON.Encode.string)->getStringFromJson("")
let endKey =
dateRange->Array.get(1)->Option.getOr(""->JSON.Encode.string)->getStringFromJson("")
let (keyList, valueList) = if (
dateRangeFilterDict != Dict.make() &&
startKey->isNonEmptyString &&
endKey->isNonEmptyString &&
keyList->Array.includes(startKey) &&
keyList->Array.includes(endKey)
) {
let start_Date = valueList[keyList->Array.indexOf(startKey)]->Option.getOr("")
let end_Date = valueList[keyList->Array.indexOf(endKey)]->Option.getOr("")
let keyList = keyList->Array.filter(item => item != startKey && item != endKey)
let valueList = valueList->Array.filter(item => item != start_Date && item != end_Date)
keyList->Array.push(startKey)->ignore
valueList->Array.push(`${start_Date}&${end_Date}`)->ignore
(keyList, valueList)
} else {
(keyList, valueList)
}
keyList->Array.forEachWithIndex((key, idx) => {
initialFilters->Array.forEach(filter => {
let field: FormRenderer.fieldInfoType = filter.field
let localFilter = filter.localFilter
field.inputNames->Array.forEach(
name => {
if name === key {
let value = valueList[idx]->Option.getOr("")
if String.includes(value, "[") {
let str = String.slice(~start=1, ~end=value->String.length - 1, value)
let splitArray = String.split(str, ",")
let jsonarr = splitArray->Array.map(val => JSON.Encode.string(val))
res.contents = switch localFilter {
| Some(localFilter) => localFilter(res.contents, JSON.Encode.array(jsonarr))
| None => res.contents
}
} else {
res.contents = switch localFilter {
| Some(localFilter) => localFilter(res.contents, JSON.Encode.string(value))
| None => res.contents
}
}
}
},
)
})
options->Array.forEach(option => {
let fieldName = option.urlKey
let localFilter = option.localFilter
if fieldName === key {
res.contents = switch localFilter {
| Some(localFilter) =>
localFilter(res.contents, JSON.Encode.string(valueList[idx]->Option.getOr("")))
| None => res.contents
}
}
})
})
}
res.contents
}
let generateUrlFromDict = (~dict, ~options: array<EntityType.optionType<'t>>, tableName) => {
dict
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, val) = entry
let strValue = getStrFromJson(key, val)
if strValue->isNonEmptyString {
let requiredOption = options->Array.find(option => option.urlKey === key)
switch requiredOption {
| Some(option) => {
let finalVal = option.parser(val)
Dict.set(dict, key, finalVal)
}
| None => Dict.set(dict, key, val)
}
let finalKey = switch tableName {
| Some(val) => val->String.concat(`-${key}`)
| None => key
}
Some(`${finalKey}=${strValue}`)
} else {
None
}
})
->Array.joinWith("&")
}
let applyFilters = (
~currentFilterDict,
~defaultFilters,
~setOffset,
~path,
~existingFilterDict,
~options,
~ignoreUrlUpdate=false,
~setLocalSearchFilters=?,
~tableName,
~updateUrlWith=?,
(),
) => {
let dict = Dict.make()
let currentFilterUrl = generateUrlFromDict(~dict=currentFilterDict, ~options, tableName)
let existingFilterUrl = generateUrlFromDict(~dict=existingFilterDict, ~options, tableName)
switch defaultFilters->JSON.Decode.object {
| Some(originalDict) =>
originalDict
->Dict.toArray
->Array.forEach(entry => {
let (key, value) = entry
Dict.set(dict, key, value)
})
| None => ()
}
switch setOffset {
| Some(fn) => fn(_ => 0)
| None => ()
}
let (localSearchUrl, localSearchDict) = if (
existingFilterUrl->isNonEmptyString && currentFilterUrl->isNonEmptyString
) {
(
`${existingFilterUrl}&${currentFilterUrl}`,
Dict.fromArray(
Array.concat(existingFilterDict->Dict.toArray, currentFilterDict->Dict.toArray),
),
)
} else if existingFilterUrl->isNonEmptyString {
(existingFilterUrl, existingFilterDict)
} else if currentFilterUrl->isNonEmptyString {
(currentFilterUrl, currentFilterDict)
} else {
("", Dict.make())
}
if ignoreUrlUpdate {
switch setLocalSearchFilters {
| Some(fn) => fn(_ => localSearchUrl)
| _ => ()
}
} else {
let finalCompleteUrl = localSearchUrl->isNonEmptyString ? `${path}?${localSearchUrl}` : path
switch updateUrlWith {
| Some(fn) =>
fn(
localSearchDict
->Dict.toArray
->Array.map(item => {
let (key, value) = item
(key, getStrFromJson(key, value))
})
->Dict.fromArray,
)
| None => RescriptReactRouter.push(finalCompleteUrl)
}
}
}
| 3,177 | 10,038 |
hyperswitch-control-center | src/components/Tabs.resi | .resi | type tabView = Compress | Expand
type tab = {
title: string,
tabElement?: React.element,
renderContent: unit => React.element,
onTabSelection?: unit => unit,
}
type activeButton = {left: bool, right: bool}
type boundingClient = {x: int, right: int}
type scrollIntoViewParams = {behavior: string, block: string, inline: string}
@send external scrollIntoView: (Dom.element, scrollIntoViewParams) => unit = "scrollIntoView"
@send external getBoundingClientRect: Dom.element => boundingClient = "getBoundingClientRect"
module TabInfo: {
@react.component
let make: (
~title: string,
~tabElement: option<React.element>=?,
~isSelected: bool,
~isScrollIntoViewRequired: bool=?,
~index: 'index,
~handleSelectedIndex: 'index => unit,
~isDisabled: bool=?,
~disabledTab: array<string>=?,
~textStyle: string=?,
~tabsCustomClass: string=?,
~borderBottomStyle: string=?,
~lightThemeColor: string=?,
~darkThemeColor: string=?,
~backgroundStyle: string=?,
~tabView: tabView=?,
~showRedDot: bool=?,
~visitedTabs: array<string>=?,
~borderSelectionStyle: string=?,
~borderDefaultStyle: string=?,
~showBottomBorder: bool=?,
~onTabSelection: unit => unit=?,
~selectTabBottomBorderColor: string=?,
) => React.element
}
module IndicationArrow: {
@react.component
let make: (
~iconName: string,
~side: string,
~refElement: React.ref<Js.nullable<Dom.element>>,
~isVisible: bool,
) => React.element
}
let getBoundingRectInfo: (React.ref<Nullable.t<Dom.element>>, boundingClient => int) => int
@react.component
let make: (
~tabs: array<tab>,
~tabsCustomClass: string=?,
~initialIndex: int=?,
~onTitleClick: int => unit=?,
~disableIndicationArrow: bool=?,
~tabContainerClass: string=?,
~borderBottomStyle: string=?,
~isScrollIntoViewRequired: bool=?,
~textStyle: string=?,
~isDisabled: bool=?,
~showRedDot: bool=?,
~visitedTabs: array<string>=?,
~disabledTab: array<string>=?,
~tabBottomShadow: string=?,
~lightThemeColor: string=?,
~darkThemeColor: string=?,
~defaultClasses: string=?,
~showBorder: bool=?,
~renderedTabClassName: string=?,
~bottomMargin: string=?,
~topPadding: string=?,
~includeMargin: bool=?,
~backgroundStyle: string=?,
~tabView: tabView=?,
~gapBetweenTabs: string=?,
~borderSelectionStyle: string=?,
~borderDefaultStyle: string=?,
~showBottomBorder: bool=?,
~showStickyHeader: bool=?,
~contentHeight: string=?,
~selectTabBottomBorderColor: string=?,
~customBottomBorderColor: string=?,
) => React.element
| 726 | 10,039 |
hyperswitch-control-center | src/components/Table.resi | .resi | let regex: string => RescriptCore.RegExp.t
let highlightedText: (Js.String.t, string) => React.element
type labelColor = TableUtils.labelColor =
| LabelGreen
| LabelRed
| LabelBlue
| LabelGray
| LabelOrange
| LabelYellow
| LabelLightGray
type filterDataType = TableUtils.filterDataType = Float(float, float) | String | DateTime
type disableField = TableUtils.disableField = {key: string, values: array<string>}
type customiseColumnConfig = TableUtils.customiseColumnConfig = {
showDropDown: bool,
customizeColumnUi: React.element,
}
type selectAllSubmitActions = TableUtils.selectAllSubmitActions = {
btnText: string,
showMultiSelectCheckBox: bool,
onClick: array<RescriptCore.JSON.t> => unit,
disableParam: disableField,
}
type hideItem = TableUtils.hideItem = {key: string, value: string}
external jsonToStr: RescriptCore.JSON.t => string = "%identity"
type textAlign = TableUtils.textAlign = Left | Right
type fontBold = bool
type labelMargin = string
type sortOrder = TableUtils.sortOrder = INC | DEC | NONE
type sortedObject = TableUtils.sortedObject = {key: string, order: sortOrder}
type multipleSelectRows = TableUtils.multipleSelectRows = ALL | PARTIAL
type filterObject = TableUtils.filterObject = {
key: string,
options: array<string>,
selected: array<string>,
}
let getSortOrderString: sortOrder => string
type label = TableUtils.label = {title: string, color: labelColor, showIcon?: bool}
type currency = string
type filterRow = TableUtils.filterRow =
| DropDownFilter(string, array<RescriptCore.JSON.t>)
| TextFilter(string)
| Range(string, float, float)
type cell = TableUtils.cell =
| Label(label)
| Text(string)
| EllipsisText(string, string)
| Currency(float, currency)
| Date(string)
| DateWithoutTime(string)
| DateWithCustomDateStyle(string, string)
| StartEndDate(string, string)
| InputField(React.element)
| Link(string)
| Progress(int)
| CustomCell(React.element, string)
| DisplayCopyCell(string)
| TrimmedText(string, string)
| DeltaPercentage(float, float)
| DropDown(string)
| Numeric(float, float => string)
| ColoredText(label)
type cellType = TableUtils.cellType =
| LabelType
| TextType
| MoneyType
| NumericType
| ProgressType
| DropDown
type header = TableUtils.header = {
key: string,
title: string,
dataType: cellType,
showSort: bool,
showFilter: bool,
highlightCellOnHover: bool,
headerElement: option<React.element>,
description: option<string>,
data: option<string>,
isMandatory: option<bool>,
showMultiSelectCheckBox: option<bool>,
hideOnShrink: option<bool>,
customWidth: option<string>,
}
let makeHeaderInfo: (
~key: string,
~title: string,
~dataType: cellType=?,
~showSort: bool=?,
~showFilter: bool=?,
~highlightCellOnHover: bool=?,
~headerElement: React.element=?,
~description: string=?,
~data: string=?,
~isMandatory: bool=?,
~showMultiSelectCheckBox: bool=?,
~hideOnShrink: bool=?,
~customWidth: string=?,
) => header
let getCell: string => cell
module ProgressCell = TableUtils.ProgressCell
let getTextAlignmentClass: textAlign => string
module BaseComponentMethod = TableUtils.BaseComponentMethod
module LabelCell = TableUtils.LabelCell
module NewLabelCell = TableUtils.NewLabelCell
module ColoredTextCell = TableUtils.ColoredTextCell
module Numeric = TableUtils.Numeric
module MoneyCell = TableUtils.MoneyCell
module LinkCell = TableUtils.LinkCell
module DateCell = TableUtils.DateCell
module StartEndDateCell = TableUtils.StartEndDateCell
module EllipsisText = TableUtils.EllipsisText
module TrimmedText = TableUtils.TrimmedText
module TableFilterCell = TableUtils.TableFilterCell
module DeltaColumn = TableUtils.DeltaColumn
module TableCell = TableUtils.TableCell
module NewTableCell = TableUtils.NewTableCell
type rowType = TableUtils.rowType = Filter | Row
let getTableCellValue: cell => string
module SortIcons = TableUtils.SortIcons
module HeaderActions = TableUtils.HeaderActions
module TableFilterRow: {
@react.component
let make: (
~item: array<filterRow>,
~removeVerticalLines: bool,
~removeHorizontalLines: bool,
~evenVertivalLines: bool,
~tableDataBorderClass: string,
~customFilterRowStyle: string,
~showCheckbox: bool,
) => React.element
}
module TableRow: {
@react.component
let make: (
~title: string,
~item: array<cell>,
~rowIndex: int,
~onRowClick: option<int => unit>,
~onRowDoubleClick: option<int => unit>,
~onRowClickPresent: bool,
~offset: int,
~removeVerticalLines: bool,
~removeHorizontalLines: bool,
~evenVertivalLines: bool,
~highlightEnabledFieldsArray: array<int>,
~tableDataBorderClass: string=?,
~collapseTableRow: bool=?,
~expandedRow: unit => React.element,
~onMouseEnter: option<int => unit>,
~onMouseLeave: option<int => unit>,
~highlightText: string,
~clearFormatting: bool=?,
~rowHeightClass: string=?,
~rowCustomClass: string=?,
~fixedWidthClass: string,
~isHighchartLegend: bool=?,
~labelMargin: TableUtils.labelMargin=?,
~isEllipsisTextRelative: bool=?,
~customMoneyStyle: string=?,
~ellipseClass: string=?,
~selectedRowColor: string=?,
~lastColClass: string=?,
~fixLastCol: bool=?,
~alignCellContent: string=?,
~customCellColor: string=?,
~highlightSelectedRow: bool=?,
~selectedIndex: int,
~setSelectedIndex: ('a => int) => unit,
) => React.element
}
module SortAction: {
@react.component
let make: (
~item: TableUtils.header,
~sortedObj: option<TableUtils.sortedObject>,
~setSortedObj: option<('a => option<sortedObject>) => unit>,
~sortIconSize: int,
~isLastCol: bool=?,
~filterRow: option<filterRow>,
) => React.element
}
module TableHeadingCell: {
@react.component
let make: (
~item: header,
~index: int,
~headingArray: array<'a>,
~isHighchartLegend: bool,
~frozenUpto: int,
~heightHeadingClass: string,
~tableheadingClass: string,
~sortedObj: option<TableUtils.sortedObject>,
~setSortedObj: option<('b => option<sortedObject>) => unit>,
~filterObj: option<array<filterObject>>,
~fixedWidthClass: string,
~setFilterObj: option<(array<filterObject> => array<filterObject>) => unit>,
~headingCenter: bool,
~filterIcon: React.element=?,
~filterDropdownClass: string=?,
~filterDropdownMaxHeight: string=?,
~selectAllCheckBox: option<multipleSelectRows>,
~setSelectAllCheckBox: option<('c => option<multipleSelectRows>) => unit>,
~isFrozen: bool=?,
~lastHeadingClass: string=?,
~fixLastCol: bool=?,
~headerCustomBgColor: string=?,
~filterRow: option<filterRow>,
~customizeColumnNewTheme: customiseColumnConfig=?,
~tableHeadingTextClass: string=?,
) => React.element
}
module TableHeadingRow: {
@react.component
let make: (
~headingArray: array<header>,
~isHighchartLegend: bool,
~frozenUpto: int,
~heightHeadingClass: string,
~tableheadingClass: string,
~sortedObj: option<TableUtils.sortedObject>,
~setSortedObj: option<('a => option<sortedObject>) => unit>,
~filterObj: option<array<filterObject>>,
~fixedWidthClass: string,
~setFilterObj: option<(array<filterObject> => array<filterObject>) => unit>,
~headingCenter: bool,
~filterIcon: React.element=?,
~filterDropdownClass: string=?,
~selectAllCheckBox: option<multipleSelectRows>,
~setSelectAllCheckBox: option<('b => option<multipleSelectRows>) => unit>,
~isFrozen: bool=?,
~lastHeadingClass: string=?,
~fixLastCol: bool=?,
~headerCustomBgColor: string=?,
~filterDropdownMaxHeight: string=?,
~columnFilterRow: option<array<filterRow>>,
~customizeColumnNewTheme: customiseColumnConfig=?,
~tableHeadingTextClass: string=?,
) => React.element
}
@react.component
let make: (
~title: string=?,
~heading: array<header>=?,
~rows: array<array<cell>>,
~offset: int=?,
~onRowClick: int => unit=?,
~onRowDoubleClick: int => unit=?,
~onRowClickPresent: bool=?,
~fullWidth: bool=?,
~removeVerticalLines: bool=?,
~removeHorizontalLines: bool=?,
~evenVertivalLines: bool=?,
~showScrollBar: bool=?,
~setSortedObj: ('a => option<sortedObject>) => unit=?,
~sortedObj: TableUtils.sortedObject=?,
~setFilterObj: (array<filterObject> => array<filterObject>) => unit=?,
~filterObj: array<filterObject>=?,
~columnFilterRow: array<filterRow>=?,
~tableheadingClass: string=?,
~tableBorderClass: string=?,
~tableDataBorderClass: string=?,
~collapseTableRow: bool=?,
~getRowDetails: RescriptCore.Nullable.t<'b> => React.element=?,
~actualData: array<RescriptCore.Nullable.t<'b>>=?,
~onExpandClickData: 'c=?,
~onMouseEnter: int => unit=?,
~onMouseLeave: int => unit=?,
~highlightText: string=?,
~heightHeadingClass: string=?,
~frozenUpto: int=?,
~clearFormatting: bool=?,
~rowHeightClass: string=?,
~isMinHeightRequired: bool=?,
~rowCustomClass: string=?,
~enableEqualWidthCol: bool=?,
~isHighchartLegend: bool=?,
~headingCenter: bool=?,
~filterIcon: React.element=?,
~filterDropdownClass: string=?,
~showHeading: bool=?,
~maxTableHeight: string=?,
~labelMargin: TableUtils.labelMargin=?,
~customFilterRowStyle: string=?,
~selectAllCheckBox: multipleSelectRows=?,
~setSelectAllCheckBox: ('d => option<multipleSelectRows>) => unit=?,
~isEllipsisTextRelative: bool=?,
~customMoneyStyle: string=?,
~ellipseClass: string=?,
~selectedRowColor: string=?,
~lastHeadingClass: string=?,
~showCheckbox: bool=?,
~lastColClass: string=?,
~fixLastCol: bool=?,
~headerCustomBgColor: string=?,
~alignCellContent: string=?,
~minTableHeightClass: string=?,
~filterDropdownMaxHeight: string=?,
~customizeColumnNewTheme: customiseColumnConfig=?,
~customCellColor: string=?,
~customBorderClass: string=?,
~showborderColor: bool=?,
~tableHeadingTextClass: string=?,
~nonFrozenTableParentClass: string=?,
~showAutoScroll: bool=?,
~showVerticalScroll: bool=?,
~showPagination: bool=?,
~highlightSelectedRow: bool=?,
) => React.element
| 2,753 | 10,040 |
hyperswitch-control-center | src/components/InlineEditInput.res | .res | module HoverInline = {
@react.component
let make = (
~customStyle="",
~leftIcon,
~value,
~subText,
~showEditIconOnHover,
~leftActionButtons,
~labelTextCustomStyle,
~customWidth,
) => {
<div
className={`group/inlineHover relative font-medium flex flex-row items-center p-2 justify-center gap-x-2 w-full bg-white rounded-md ${customWidth} ${customStyle}`}>
<RenderIf condition={leftIcon->Option.isSome}>
{leftIcon->Option.getOr(React.null)}
</RenderIf>
<div className="flex flex-col w-full gap-1">
<div className="flex justify-between items-center w-full">
<div className={`text-sm ${labelTextCustomStyle}`}> {React.string(value)} </div>
<div
className={`${showEditIconOnHover ? "invisible group-hover/inlineHover:visible" : ""}`}
onClick={ReactEvent.Mouse.stopPropagation}>
leftActionButtons
</div>
</div>
<RenderIf condition={subText->LogicUtils.isNonEmptyString}>
<div className="text-xs text-nd_gray-400"> {React.string(subText)} </div>
</RenderIf>
</div>
</div>
}
}
@react.component
let make = (
~index=0,
~labelText="",
~subText="",
~customStyle="",
~showEditIconOnHover=true,
~leftIcon=?,
~onSubmit=?,
~customIconComponent=?,
~customInputStyle="",
~customIconStyle="",
~showEditIcon=true,
~handleEdit: option<int> => unit,
~isUnderEdit=false,
~displayHoverOnEdit=true,
~validateInput,
~labelTextCustomStyle="",
~customWidth="",
~handleClick=?,
) => {
let (value, setValue) = React.useState(_ => labelText)
let (inputErrors, setInputErrors) = React.useState(_ => Dict.make())
let enterKeyCode = 13
let escapeKeyCode = 27
let handleCancel = () => {
setValue(_ => labelText)
setInputErrors(_ => Dict.make())
handleEdit(None)
}
let handleSave = () => {
setValue(_ => value)
if !{inputErrors->LogicUtils.isEmptyDict} || value == labelText {
handleCancel()
} else {
switch onSubmit {
| Some(func) => {
func(value)->ignore
handleEdit(None)
}
| None => ()
}
handleEdit(None)
}
}
React.useEffect(() => {
if labelText->LogicUtils.isNonEmptyString {
setValue(_ => labelText)
}
None
}, [labelText])
let handleKeyDown = e => {
let key = e->ReactEvent.Keyboard.key
let keyCode = e->ReactEvent.Keyboard.keyCode
if key === "Enter" || keyCode === enterKeyCode {
if inputErrors->LogicUtils.isEmptyDict {
handleSave()
} else {
handleCancel()
}
}
if key === "Escape" || keyCode === escapeKeyCode {
handleCancel()
}
}
let isDisabled = !{inputErrors->LogicUtils.isEmptyDict}
let isDisabledCss = {isDisabled ? "!cursor-not-allowed" : "cursor-pointer"}
let dropdownRef = React.useRef(Nullable.null)
OutsideClick.useOutsideClick(
~refs={ArrayOfRef([dropdownRef])},
~isActive=isUnderEdit,
~callback=() => {
handleEdit(None)
handleCancel()
},
)
let submitButtons =
<div
className="flex items-center gap-2 pr-4 cursor-pointer"
onClick={ReactEvent.Mouse.stopPropagation}>
<button onClick={_ => handleCancel()} className={`cursor-pointer ${customIconStyle}`}>
<Icon name="nd-cross" size=16 />
</button>
<button
onClick={_ => handleSave()}
className={`cursor-pointer !text-blue-500 ${customIconStyle} ${isDisabledCss}`}
disabled={isDisabled}>
<Icon name="nd-check" size=16 />
</button>
</div>
let leftActionButtons =
<div className="gap-2 flex cursor-pointer">
<RenderIf condition={showEditIcon}>
<button
onClick={_ => {
handleEdit(Some(index))
}}
className={`${customIconStyle}`}
ariaLabel="Edit">
<Icon name="nd-pencil" size=14 />
</button>
</RenderIf>
<RenderIf condition={customIconComponent->Option.isSome}>
<div className="flex items-center justify-center w-4 h-4">
{customIconComponent->Option.getOr(React.null)}
</div>
</RenderIf>
</div>
let handleInputChange = e => {
let value = ReactEvent.Form.target(e)["value"]
setValue(_ => value)
let errors = validateInput(value)
setInputErrors(_ => errors)
}
<div
className="relative inline-block w-full"
onClick={e => {
switch handleClick {
| Some(fn) => fn()
| None =>
()
e->ReactEvent.Mouse.stopPropagation
}
}}>
{if isUnderEdit {
//TODO: validation error message has to be displayed
<div
className={`flex items-center p-1 ${customWidth}`}
onClick={ReactEvent.Mouse.stopPropagation}>
<RenderIf condition={leftIcon->Option.isSome}>
{leftIcon->Option.getOr(React.null)}
</RenderIf>
<div
className={`group relative flex items-center bg-white ${inputErrors->LogicUtils.isEmptyDict
? "focus-within:ring-1 focus-within:ring-blue-400"
: "ring-1 ring-red-300"} rounded-md text-md !py-2 ${customStyle} `}>
<div className={`flex-1 `}>
<input
type_="text"
value
onChange=handleInputChange
onKeyDown=handleKeyDown
autoFocus=true
className={`w-full p-2 bg-transparent focus:outline-none text-md ${customInputStyle}`}
/>
</div>
{submitButtons}
</div>
</div>
} else {
<RenderIf condition={displayHoverOnEdit}>
<HoverInline
customStyle
leftIcon
value
subText
showEditIconOnHover
leftActionButtons
labelTextCustomStyle
customWidth
/>
</RenderIf>
}}
</div>
}
| 1,456 | 10,041 |
hyperswitch-control-center | src/components/SelectModal.res | .res | @react.component
let make = (
~modalHeading="Select Options",
~modalHeadingDescription="",
~showModal,
~setShowModal,
~isModalView=true,
~onSubmit,
~initialValues,
~options,
~revealFrom=Reveal.Right,
~closeOnOutsideClick=true,
~title="Columns",
~submitButtonText=?,
~disableSelect=false,
~showDeSelectAll=false,
~showSelectAll=true,
~maxSelection=-1,
~enableSelect=false,
~sortingBasedOnDisabled=true,
~showSerialNumber=true,
~showConversionRate=false,
~headerTextClass="text-3xl font-semibold tracking-tight",
~headerClass="",
) => {
let maxLengthArray = (arr, setValues) => {
switch maxSelection {
| -1 => setValues(_ => arr)
| _ =>
if arr->Array.length > maxSelection {
let temp = arr->Array.sliceToEnd(~start=arr->Array.length - maxSelection)
setValues(_ => temp)
} else {
setValues(_ => arr)
}
}
}
let (values, setValues) = React.useState(_ => initialValues)
let onClick = _ => values->onSubmit
let disableSelectBtn = React.useMemo(
() =>
(initialValues->Array.toString === values->Array.toString && !enableSelect) ||
values->Array.length === 0,
(values, initialValues),
)
let len = values->Array.length
let buttonText =
submitButtonText->Option.getOr(len > 0 ? `${len->Int.toString} ${title} Selected` : "Select")
React.useEffect(() => {
if !showModal {
setValues(_ => initialValues)
}
None
}, (showModal, initialValues))
let applyBtnStyle = "w-full mx-5"
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "cutomixedColumnsInput",
onBlur: _ => (),
onChange: ev => {
let target = ev->Identity.formReactEventToArrayOfString
maxLengthArray(target, setValues)
},
onFocus: _ => (),
value: values->LogicUtils.getJsonFromArrayOfString,
checked: false,
}
if isModalView {
<Modal
modalHeading
modalHeadingDescription
paddingClass=""
showModal
setShowModal
closeOnOutsideClick
revealFrom
modalClass="w-full h-screen md:w-96 float-right overflow-hidden !bg-white dark:!bg-jp-gray-lightgray_background"
headingClass={`${headerClass} py-6 px-2.5 h-24 border-b border-solid flex flex-col justify-center !bg-white dark:!bg-black border-slate-300`}
headerTextClass
childClass="p-0 m-0">
<div
className={`overflow-hidden p-6 pb-12 border-b border-solid ${showConversionRate
? "border-slate-100"
: "border-slate-300"} dark:border-slate-500`}
style={
height: `${showConversionRate ? "calc(100vh - 17rem)" : "calc(100vh - 12rem)"}`,
}>
<SelectBox.BaseSelect
isDropDown=false
options
onSelect={arr => maxLengthArray(arr, setValues)}
value={values->LogicUtils.getJsonFromArrayOfString}
showSelectAll={showSelectAll}
showSerialNumber
maxHeight="max-h-full"
searchable=true
searchInputPlaceHolder={`Search in ${options->Array.length->Int.toString} options`}
customStyle="px-2 py-1"
customSearchStyle="bg-white dark:bg-jp-gray-lightgray_background"
disableSelect
isModalView
sortingBasedOnDisabled
/>
</div>
{showConversionRate
? <div className="bg-[#F6F6F6] p-4 border-b border-slate-300 text-center text-[#868686]">
{React.string(
`Conversion rate = ${options
->Array.filter(itm => values->Array.get(0)->Option.getOr("") == itm.value)
->Array.map(item => item.label)
->Array.get(0)
->Option.getOr("Factor 1")} / ${options
->Array.filter(itm => values->Array.get(1)->Option.getOr("") == itm.value)
->Array.map(item => item.label)
->Array.get(0)
->Option.getOr("Factor 2")}`,
)}
</div>
: React.null}
<div
className="flex flex-row items-center overflow-hidden justify-center mt-1.5 mb-1 h-20 gap-2">
{if showDeSelectAll && values->Array.length > 0 {
<Button
text="DESELECT ALL"
customButtonStyle=applyBtnStyle
buttonState={disableSelect ? Disabled : Normal}
onClick={_ => setValues(_ => [])}
/>
} else {
React.null
}}
<Button
text=buttonText
buttonType=Primary
onClick
customButtonStyle=applyBtnStyle
buttonState={disableSelectBtn ? Disabled : Normal}
buttonVariant={Fit}
/>
</div>
</Modal>
} else {
<SelectBox.BaseDropdown
input
options
buttonText="Columns"
showBorder=false
allowMultiSelect=true
hasApplyButton=true
showSelectAll=false
hideMultiSelectButtons=true
onApply=onClick
/>
}
}
| 1,249 | 10,042 |
hyperswitch-control-center | src/components/HeadlessUISelectBox.res | .res | open HeadlessUI
type updatedOptionWithIcons = {
label: string,
value: string,
isDisabled: bool,
leftIcon: Button.iconType,
customTextStyle: option<string>,
customIconStyle: option<string>,
rightIcon: Button.iconType,
description: option<string>,
}
@react.component
let make = (
~value: value=String(""),
~setValue,
~options: array<updatedOptionWithIcons>,
~children,
~dropdownPosition=Left,
~className="",
~dropDownClass="w-52",
~deSelectAllowed=true,
~showBottomUp=false,
~textClass="text-sm",
~closeListOnClick=false,
) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let dropdownPositionClass = switch dropdownPosition {
| Left => "right-0"
| _ => "left-0"
}
let (showList, setShowList) = React.useState(_ => false)
let closeClick = _ => {
setShowList(_ => !showList)
}
<div className="text-left">
<AddDataAttributes attributes=[("data-testid", "profile")]>
<Menu \"as"="div" className="relative inline-block text-left">
{_ =>
<div>
<Menu.Button className> {_ => children} </Menu.Button>
<Transition
\"as"="span"
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
{if showBottomUp {
<BottomModal headerText="Select Action" onCloseClick=closeClick>
<Menu.Items
className={`w-full p-1 origin-top-right bg-white dark:bg-jp-gray-950 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none`}>
{_ =>
options
->Array.mapWithIndex((option, index) => {
let selected = switch value {
| String(v) => v === option.value
| Array(arr) => arr->Array.includes(option.value)
}
let disabledClass = option.isDisabled ? "disabled cursor-not-allowed" : ""
<Menu.Item key={index->Int.toString}>
{props => {
let isCloseIcon = props["active"] && deSelectAllowed
<div
onClick={ev => {
if !closeListOnClick {
ev->ReactEvent.Mouse.stopPropagation
ev->ReactEvent.Mouse.preventDefault
}
setValue(option.value)
}}
className={`group flex flex-row items-center justify-between rounded-md w-full p-3 text-fs-14 font-normal cursor-pointer ${props["active"]
? "bg-gray-100 dark:bg-gray-700"
: ""} ${disabledClass}`}
disabled={option.isDisabled}>
<div className="flex flex-row items-center gap-2">
{switch option.leftIcon {
| FontAwesome(iconName) =>
<Icon
className={`align-middle ${option.customIconStyle->Option.getOr(
"",
)}`}
size=14
name=iconName
/>
| CustomIcon(element) => element
| Euler(iconName) =>
<Icon className="align-middle" size=12 name=iconName />
| _ => React.null
}}
<AddDataAttributes attributes=[("data-options", option.label)]>
<div className={option.customTextStyle->Option.getOr("")}>
<span
className={selected
? `${textColor.primaryNormal} font-semibold`
: ""}>
{React.string(option.label)}
</span>
</div>
</AddDataAttributes>
{switch option.rightIcon {
| FontAwesome(iconName) =>
<Icon
className={`align-middle ${option.customIconStyle->Option.getOr(
"",
)}`}
size=12
name=iconName
/>
| CustomIcon(element) => element
| Euler(iconName) =>
<Icon className="align-middle" size=12 name=iconName />
| _ => React.null
}}
</div>
<RenderIf condition=selected>
{if isCloseIcon {
<Icon name="close" size=10 className="text-red-500 mr-1" />
} else {
<Tick isSelected=selected />
}}
</RenderIf>
</div>
}}
</Menu.Item>
})
->React.array}
</Menu.Items>
</BottomModal>
} else {
<Menu.Items
className={`absolute z-10 ${dropdownPositionClass} mt-2 p-1 origin-top-right bg-white dark:bg-jp-gray-950 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none ${dropDownClass}`}>
{_ =>
options
->Array.mapWithIndex((option, index) => {
let selected = switch value {
| String(v) => v === option.value
| Array(arr) => arr->Array.includes(option.value)
}
let disabledClass = option.isDisabled ? "disabled cursor-not-allowed" : ""
<Menu.Item key={index->Int.toString}>
{props =>
<div
onClick={ev => {
if !closeListOnClick {
ev->ReactEvent.Mouse.stopPropagation
ev->ReactEvent.Mouse.preventDefault
}
setValue(option.value)
}}
className={`group flex flex-row items-center justify-between rounded-md w-full p-2 ${textClass} cursor-pointer ${props["active"]
? "bg-gray-100 dark:bg-gray-700"
: ""} ${disabledClass}`}
disabled={option.isDisabled}>
<div className="flex flex-row items-center gap-2">
{switch option.leftIcon {
| FontAwesome(iconName) =>
<Icon
className={`align-middle ${option.customIconStyle->Option.getOr(
"",
)}`}
size=12
name=iconName
/>
| CustomIcon(element) => element
| Euler(iconName) =>
<Icon className="align-middle" size=12 name=iconName />
| _ => React.null
}}
<AddDataAttributes attributes=[("data-options", option.label)]>
<div className={option.customTextStyle->Option.getOr("")}>
<span
className={selected
? `${textColor.primaryNormal} font-semibold`
: ""}>
{React.string(option.label)}
</span>
</div>
</AddDataAttributes>
{switch option.rightIcon {
| FontAwesome(iconName) =>
<Icon
className={`align-middle ${option.customIconStyle->Option.getOr(
"",
)}`}
size=12
name=iconName
/>
| CustomIcon(element) => element
| Euler(iconName) =>
<Icon className="align-middle" size=12 name=iconName />
| _ => React.null
}}
</div>
{selected
? props["active"] && deSelectAllowed
? <Icon name="close" size=10 className="text-red-500 mr-1" />
: <Tick isSelected=selected />
: React.null}
</div>}
</Menu.Item>
})
->React.array}
</Menu.Items>
}}
</Transition>
</div>}
</Menu>
</AddDataAttributes>
</div>
}
| 1,671 | 10,043 |
hyperswitch-control-center | src/components/SnackBarContainer.res | .res | module Snackbar = {
@react.component
let make = (~snackbarProps: SnackBarState.snackbarProps, ~hideSnackbar) => {
let borderCss = snackbarProps.snackbarType != General ? "border-l-4" : ""
let borderColor = switch snackbarProps.snackbarType {
| General
| Information => "border-jp-2-primary-300"
| Success => "border-jp-2-light-green-700"
| Error => "border-jp-2-light-red-700"
| Warning => "border-jp-2-light-orange-600"
}
let snackbarIconName = switch snackbarProps.snackbarType {
| Success => "success-snackbar"
| Warning => "warning-snackbar"
| Information => "info-snackbar"
| Error => "error-snackbar"
| General => ""
}
let leftIcon = if snackbarProps.snackbarType != General {
<div>
<Icon name=snackbarIconName size=24 />
</div>
} else {
React.null
}
let handleClick = React.useCallback(_ => {
switch snackbarProps.onClose {
| Some(fn) => fn()
| _ => ()
}
hideSnackbar(snackbarProps.snackbarKey)
}, [hideSnackbar])
<div
className={`p-3 pr-4 m-2 mr-3 shadow-lg z-50 pointer-events-auto bg-jp-2-light-gray-1800 max-w-md rounded ${borderCss} ${borderColor}`}>
<div className="flex flex-row gap-2">
{leftIcon}
<div className="flex flex-col gap-4">
<div className="gap-0">
<div className="font-semibold text-fs-16 mb-2 text-jp-2-dark-gray-2000">
{React.string(snackbarProps.heading)}
</div>
<div className="font-normal text-fs-14 leading-5 text-jp-2-light-gray-600">
{React.string(snackbarProps.body)}
</div>
</div>
{snackbarProps.actionElement}
</div>
<div>
<button className=" hover:text-jp-gray-900 pl-5" onClick={handleClick}>
<Icon size=16 name="close-snackbar" />
</button>
</div>
</div>
</div>
}
}
@react.component
let make = (~children) => {
let (openSnackbar, setOpenSnackbar) = Recoil.useRecoilState(SnackBarState.openSnackbar)
let hideSnackbar = React.useCallback(key => {
setOpenSnackbar(prevArr => {
Array.filter(
prevArr,
(snackbarProps: SnackBarState.snackbarProps) => {
snackbarProps.snackbarKey !== key
},
)
})
}, [setOpenSnackbar])
<div className="relative">
children
<div>
<div
className={`absolute inset-0 overflow-scroll flex flex-col pointer-events-none m-4 items-end grid justify-end content-end no-scrollbar`}>
<div
className={`flex flex-col font-inter-style pointer-events-auto w-auto self-start w-max max-w-4xl`}>
{openSnackbar
->Array.map(snackbarProps => {
<Snackbar key={snackbarProps.snackbarKey} snackbarProps hideSnackbar />
})
->React.array}
</div>
</div>
</div>
</div>
}
| 772 | 10,044 |
hyperswitch-control-center | src/components/Chip.res | .res | @react.component
let make = (~values=[], ~showButton=false, ~onButtonClick=_ => (), ~converterFn=str => str) => {
<RenderIf condition={values->Array.length !== 0}>
<div className="flex flex-wrap flex-row">
{values
->Array.map(value => {
let onClick = _ => {
onButtonClick(value)
}
<div
className="px-4 py-2 m-2 mr-0.5 rounded-full border border-gray-300 bg-gradient-to-b from-jp-gray-200 to-jp-gray-300 dark:from-jp-gray-950 dark:to-jp-gray-950 text-gray-500 hover:shadow dark:text-jp-gray-text_darktheme dark:text-opacity-50 flex align-center w-max cursor-pointer transition duration-300 ease">
{React.string(value->converterFn)}
<RenderIf condition={showButton}>
<div className="float-right cursor-pointer mt-0.5 ml-0.5 opacity-50">
<Icon className="align-middle" size=14 name="times" onClick />
</div>
</RenderIf>
</div>
})
->React.array}
</div>
</RenderIf>
}
| 281 | 10,045 |
hyperswitch-control-center | src/components/Debounce.res | .res | type debounced<'a> = {
invoke: 'a => unit,
schedule: 'a => unit,
scheduled: unit => bool,
cancel: unit => unit,
}
let makeControlled = (~wait=100, fn: 'a => unit): debounced<'a> => {
let timerId = ref(None)
let lastArg = ref(None)
let lastCallTime = ref(None)
let shouldCall = time =>
switch lastCallTime.contents {
| None => true
| Some(lastCallTime) =>
let timeSinceLastCall = time - lastCallTime
timeSinceLastCall >= wait || timeSinceLastCall < 0
}
let remainingWait = time =>
switch lastCallTime.contents {
| None => wait
| Some(lastCallTime) =>
let timeSinceLastCall = time - lastCallTime
wait - timeSinceLastCall
}
let rec timerExpired = () => {
switch timerId.contents {
| Some(timerId) => timerId->clearTimeout
| None => ()
}
let time = Date.now()->Int.fromFloat
if time->shouldCall {
call()
} else {
timerId := Some(time->remainingWait->(setTimeout(timerExpired, _)))
}
}
and call = () => {
let x = lastArg.contents
switch x {
| Some(x) =>
lastArg := None
timerId := None
x->fn
| None => timerId := None
}
}
let schedule = x => {
let time = Date.now()->Int.fromFloat
lastArg := Some(x)
lastCallTime := Some(time)
timerId := Some(wait->(setTimeout(timerExpired, _)))
}
let scheduled = () =>
switch timerId.contents {
| Some(_) => true
| None => false
}
let cancel = () =>
switch timerId.contents {
| Some(timerId') =>
timerId'->clearTimeout
timerId := None
lastArg := None
lastCallTime := None
| None => ()
}
let invoke = x => {
cancel()
x->fn
}
{
invoke,
schedule,
scheduled,
cancel,
}
}
let make = (~wait=?, fn) => makeControlled(~wait?, fn).schedule
| 518 | 10,046 |
hyperswitch-control-center | src/components/CardTable.res | .res | module TextCard = {
@react.component
let make = (~text) => {
if text->LogicUtils.isNonEmptyString {
<p className="break-words font-semibold">
<HelperComponents.EllipsisText
endValue=10 displayValue={text->LogicUtils.isNonEmptyString ? text : "N/A"} showCopy=false
/>
</p>
} else {
React.string("-")
}
}
}
module ItemValue = {
@react.component
let make = (~cell: Table.cell, ~customMoneyStyle="", ~fontStyle="") => {
open Table
switch cell {
| Label(x) => <LabelCell labelColor=x.color text=x.title fontStyle />
| Text(x) => <TextCard text=x />
| Currency(amount, currency) => <MoneyCell amount currency customMoneyStyle />
| Date(timestamp) => <DateCell timestamp isCard=true textStyle=fontStyle hideTime=true />
| StartEndDate(startDate, endDate) => <StartEndDateCell startDate endDate isCard=true />
| Link(x) => <LinkCell data=x />
| CustomCell(ele, _) => ele
| Numeric(num, mapper) => <Numeric num mapper clearFormatting=false />
| DeltaPercentage(value, delta) => <DeltaColumn value delta />
| TrimmedText(text, width) => <TrimmedText text width highlightText="" hideShowMore=false />
| _ => React.null
}
}
}
module CardDetails = {
@react.component
let make = (
~itemArray,
~heading: array<Table.header>,
~onRowClick,
~rowIndex,
~size=4,
~offset=0,
~isBorderEnabled=true,
~isAnalyticsModule,
) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let onCardClick = _ => {
switch onRowClick {
| Some(fn) => fn(rowIndex + offset)
| None => ()
}
}
let (show, setshow) = React.useState(_ => true)
let showMore = _ => {
setshow(prev => !prev)
}
<div className="w-full lg:w-1/4 md:w-1/2" onClick=onCardClick>
<div
className={`flex justify-between flex-wrap dark:bg-jp-gray-lightgray_background bg-white my-2 px-4 ${isBorderEnabled
? "border border-jp-gray-500 dark:border-jp-gray-960 p-4 rounded"
: ""} `}>
{
let itemArray = !show ? itemArray : Array.slice(itemArray, ~start=0, ~end=size)
itemArray
->Array.mapWithIndex((cell, cellIndex) => {
let key = Int.toString(cellIndex + offset) //webhooks UI
switch heading[cellIndex] {
| Some(label) =>
if isAnalyticsModule {
<div className="w-full flex jutify-end" key={cellIndex->Int.toString}>
<p className="mt-2 md:inline inline-block w-1/2 ">
{React.string(label.title)}
</p>
<div className="md:inline flex justify-end w-1/2 break-all">
<ItemValue key cell />
</div>
</div>
} else {
<div className="w-full" key={cellIndex->Int.toString}>
<p className="mt-2 md:inline inline-block w-1/2 ">
{React.string(label.title)}
</p>
<div className="md:inline inline-block w-1/2 ">
<ItemValue key cell />
</div>
</div>
}
| None => React.null
}
})
->React.array
}
{if isAnalyticsModule {
<div
className={`flex justify-end ${textColor.primaryNormal} cursor-pointer`}
onClick=showMore>
{if itemArray->Array.length > size {
show ? React.string("More") : React.string("Less")
} else {
React.null
}}
</div>
} else {
React.null
}}
</div>
</div>
}
}
@react.component
let make = (
~heading: array<Table.header>,
~rows,
~offset=0,
~onRowClick=?,
~size=4,
~isBorderEnabled=true,
~isAnalyticsModule=false,
) => {
<div>
<div className="overflow-auto flex flex-wrap">
{rows
->Array.mapWithIndex((itemArray, rowIndex) => {
<AddDataAttributes attributes=[("data-card-details", "cardDetails")]>
<CardDetails
key={(rowIndex + offset)->Int.toString}
size
itemArray
isBorderEnabled
heading
onRowClick
rowIndex
offset
isAnalyticsModule
/>
</AddDataAttributes>
})
->React.array}
</div>
</div>
}
| 1,098 | 10,047 |
hyperswitch-control-center | src/components/Navbar.res | .res | let bgClass = "bg-white hover:bg-jp-gray-100"
module MenuOption = {
@react.component
let make = (~text=?, ~children=?, ~onClick=?) => {
<AddDataAttributes attributes=[("data-testid", text->Option.getOr("")->String.toLowerCase)]>
<button
className={`px-4 py-3 flex text-sm w-full text-gray-700 cursor-pointer ${bgClass}`}
?onClick>
{switch text {
| Some(str) => React.string(str)
| None => React.null
}}
{switch children {
| Some(elem) => elem
| None => React.null
}}
</button>
</AddDataAttributes>
}
}
@react.component
let make = (
~headerActions=?,
~midUiActions=?,
~notificationActions=?,
~faqsActions as _=?,
~outageActions=?,
~liveMode=?,
~customHeight="",
~portalStyle="",
~homeLink="/",
~popOverPanelCustomClass="",
~headerLeftActions=?,
) => {
let isMobileView = MatchMedia.useMobileChecker()
let (showModal, setShowModal) = React.useState(_ => false)
let (isAppearancePopupOpen, setIsAppearancePopupOpen) = React.useState(_ => false)
let {setIsSidebarExpanded} = React.useContext(SidebarProvider.defaultContext)
let {authStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let mobileMargin = isMobileView ? "" : "mr-7"
let leftPortalName = isMobileView ? "mobileNavbarTitle" : "desktopNavbarLeft"
let ref = React.useRef(Nullable.null)
OutsideClick.useOutsideClick(
~refs=ArrayOfRef([ref]),
~isActive=isAppearancePopupOpen,
~callback=() => {
setIsAppearancePopupOpen(_ => false)
},
)
let leftMarginOnNav = "ml-0"
switch authStatus {
| LoggedIn(_info) =>
<div id="navbar" className={`w-full mx-auto`}>
<div className={`flex flex-row min-h-16 items-center justify-between ${customHeight}`}>
{switch headerLeftActions {
| Some(actions) => actions
| None => React.null
}}
<div className={`flex flex-wrap ml-2 md:ml-5 justify-between items-center w-full`}>
<PortalCapture key=leftPortalName name=leftPortalName customStyle={`${portalStyle}`} />
<div className="flex flex-row place-content-centerx">
<PortalCapture key="desktopNavbarCenter" name="desktopNavbarCenter" />
</div>
<div className="flex flex-row items-center">
<PortalCapture key="desktopNavbarRight" name="desktopNavbarRight" />
<PortalCapture key="desktopNavYoutubeLink" name="desktopNavYoutubeLink" />
</div>
</div>
<div className="flex-1 flex items-center justify-center sm:items-stretch sm:justify-start">
<div className="flex-shrink-0 flex items-center" />
</div>
{switch midUiActions {
| Some(actions) => actions
| None => React.null
}}
<div
className={` inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0 ${mobileMargin}`}>
{switch headerActions {
| Some(actions) => actions
| None => React.null
}}
{switch outageActions {
| Some(actions) => actions
| None => React.null
}}
{if isMobileView {
switch liveMode {
| Some(actions) => actions
| None => React.null
}
} else {
React.null
}}
{switch notificationActions {
| Some(actions) => actions
| None => React.null
}}
<div className={`mt-2 ${leftMarginOnNav}`}>
<PortalCapture key="onboarding" name="onboarding" />
</div>
<div
onClick={_ => {
setIsSidebarExpanded(prev => !prev)
}}
className={`h-full px-1.5 flex items-center focus:outline-none cursor-pointer transform transition duration-500 ease-in-out md:hidden`}>
<Icon className="align-middle" name="bars" />
</div>
</div>
</div>
<div className="md:ml-5 ml-2">
<PortalCapture key="navbarSecondRow" name="navbarSecondRow" />
</div>
<HSwitchFeedBackModal modalHeading="We'd love to hear from you!" setShowModal showModal />
</div>
| LoggedOut => React.null
| PreLogin(_)
| CheckingAuthStatus =>
React.string("...")
}
}
| 1,056 | 10,048 |
hyperswitch-control-center | src/components/PopUpConfirm.res | .res | open PopUpState
open PopUpConfirmUtils
external toMouseEvent: JsxEvent.synthetic<ReactEvent.Keyboard.tag> => JsxEvent.synthetic<
JsxEvent.Mouse.tag,
> = "%identity"
module Close = {
@react.component
let make = (~onClick) => {
<AddDataAttributes attributes=[("data-component", `popUpConfirmClose`)]>
{onClick->getCloseIcon}
</AddDataAttributes>
}
}
@react.component
let make = (
~handlePopUp,
~handleConfirm=?,
~handleCancel=?,
~confirmType,
~confirmText: React.element,
~confirmButtonDisabled=false,
~buttonText: option<string>=?,
~confirmButtonIcon: Button.iconType=NoIcon,
~cancelButtonIcon: Button.iconType=NoIcon,
~popUpType: popUpType=Warning,
~cancelButtonText: option<string>=?,
~showIcon: bool=false,
~showPopUp,
~showCloseIcon=true,
~popUpSize: popUpSize=Large,
) => {
let isMobileView = MatchMedia.useMobileChecker()
let (popUpHeadingColor, topBorderColor) = switch popUpType {
| Success => ("bg-green-700", "border-t-green-700")
| Primary => ("bg-primary", "border-t-primary")
| Secondary => ("bg-yellow-300", "border-t-yellow-300")
| Danger | Denied => ("bg-red-600", "border-t-red-600")
| Warning => ("bg-orange-960", "border-t-orange-960")
}
let appPrefix = LogicUtils.useUrlPrefix()
let rounded_top_border = "rounded-t-xl"
let btnWidthClass = isMobileView ? "w-full" : ""
let customButtonStyle = `${btnWidthClass}`
let textStyle = "font-medium text-fs-13"
let showModal = showPopUp ? "flex" : "hidden"
let popupMargin = isMobileView ? "pt-4 pl-4" : "pr-4 pl-8 pt-6"
let btnPosition = isMobileView ? "gap-6 justify-between" : "gap-4 justify-end"
let paddingCss = isMobileView ? "px-4" : "px-8"
let handleOverlayClick = ev => {
open ReactEvent.Mouse
ev->stopPropagation
}
let actionButton = switch buttonText {
| Some(text) =>
let buttonType: Button.buttonType = switch popUpType {
| Success
| Primary
| Secondary
| Warning =>
Primary
| Danger | Denied => Delete
}
let buttonState: Button.buttonState = confirmButtonDisabled ? Button.Disabled : Button.Normal
switch handleConfirm {
| Some(onClick) =>
<Button
leftIcon=confirmButtonIcon buttonType text onClick textStyle customButtonStyle buttonState
/>
| None =>
<Button
leftIcon=confirmButtonIcon
buttonType
text
textStyle
customButtonStyle
type_="submit"
buttonState
/>
}
| _ => React.null
}
let cancelButton = switch cancelButtonText {
| Some(text) =>
let buttonType: Button.buttonType = SecondaryFilled
switch handleCancel {
| Some(onClick) =>
<Button buttonType text onClick textStyle customButtonStyle leftIcon=cancelButtonIcon />
| None =>
<Button
buttonType text onClick=handlePopUp textStyle customButtonStyle leftIcon=cancelButtonIcon
/>
}
| None => React.null
}
let handleKeyUp = ev => {
open ReactEvent.Keyboard
let key = ev->key
let keyCode = ev->keyCode
if key === "Escape" || keyCode === 27 {
switch handleCancel {
| Some(onClick) => onClick(ev->toMouseEvent)
| None => ()
}
}
}
React.useEffect(() => {
if showPopUp {
Window.addEventListener("keyup", handleKeyUp)
} else {
Window.removeEventListener("keyup", handleKeyUp)
}
Some(
() => {
Window.removeEventListener("keyup", handleKeyUp)
},
)
}, [showPopUp])
<AddDataAttributes attributes=[("data-component", `popUpConfirm ${confirmType}`)]>
<div
className={`${showModal} ${overlayStyle} fixed cursor-default h-screen w-screen z-50 inset-0 overflow-auto`}
onClick=handleOverlayClick>
// <Reveal showReveal=showPopUp revealFrom=Reveal.Top>
<div
className={`${topBorderColor} absolute lg:top-1/3 md:top-1/3 left-0 lg:left-1/3 border border-jp-gray-500 dark:border-jp-gray-960 w-full bottom-0 md:bottom-auto ${modalWidth} bg-jp-gray-100 dark:bg-jp-gray-lightgray_background shadow ${containerBorderRadius} z-20 dark:text-opacity-75 ${rounded_top_border}`}>
<div className={`h-2 w-12/12 p-0 mt-0 ${popUpHeadingColor} ${rounded_top_border}`} />
<div className={`flex flex-row ${popupMargin} justify-between`}>
<div className="flex flex-row gap-5 pt-4 items-center w-full">
<RenderIf condition=showIcon>
{switch popUpType {
| Warning =>
<img className=imageStyle src={`${appPrefix}/icons/warning.svg`} alt="warning" />
| Danger =>
<img className=imageStyle src={`${appPrefix}/icons/error.svg`} alt="danger" />
| Success => <Icon className=iconStyle size=40 name="check-circle" />
| Primary => <Icon className=iconStyle size=40 name="info-circle" />
| Secondary => <Icon className=iconStyle size=40 name="info-circle" />
| Denied => <Icon name="denied" size=50 className=iconStyle />
}}
</RenderIf>
<div className="w-full">
<AddDataAttributes attributes=[("data-header-text", confirmType)]>
<div className=headerStyle> {confirmType->React.string} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-description-text", "popUp Confirmation")]>
<div className=subHeaderStyle> {confirmText} </div>
</AddDataAttributes>
</div>
</div>
<div className="flex justify-end ">
<RenderIf condition=showCloseIcon>
<Close onClick=handlePopUp />
</RenderIf>
</div>
</div>
<div className={`flex justify-between items-center flex-row ${paddingCss} py-4 mt-4`}>
<div className={`flex flex-row items-center w-full ${btnPosition}`}>
{cancelButton}
{actionButton}
</div>
</div>
</div>
// </Reveal>
</div>
</AddDataAttributes>
}
| 1,554 | 10,049 |
hyperswitch-control-center | src/components/HandlingEvents.res | .res | type jsonData = {data: JSON.t}
external convertToCustomEvent: Webapi.Dom.Event.t => jsonData = "%identity"
type cookieData = {changed: array<JSON.t>}
external convertToCookieCustomEvent: Webapi.Dom.Event.t => cookieData = "%identity"
let getEventDict = (ev: Dom.event) => {
let objData = ev->convertToCustomEvent
try {
objData.data
->JSON.Decode.string
->Option.map(JSON.parseExn)
->Option.flatMap(parsedMsg => {
parsedMsg->JSON.Decode.object
})
} catch {
| _ => None
}
}
| 136 | 10,050 |
hyperswitch-control-center | src/components/Tabs.res | .res | type tabView = Compress | Expand
type tab = {
title: string,
tabElement?: React.element,
renderContent: unit => React.element,
onTabSelection?: unit => unit,
}
type activeButton = {
left: bool,
right: bool,
}
type boundingClient = {x: int, right: int}
type scrollIntoViewParams = {behavior: string, block: string, inline: string}
@send external scrollIntoView: (Dom.element, scrollIntoViewParams) => unit = "scrollIntoView"
@send external getBoundingClientRect: Dom.element => boundingClient = "getBoundingClientRect"
module TabInfo = {
@react.component
let make = (
~title,
~tabElement=None,
~isSelected,
~isScrollIntoViewRequired=false,
~index,
~handleSelectedIndex,
~isDisabled=false,
~disabledTab=[],
~textStyle="",
~tabsCustomClass="",
~borderBottomStyle="",
~lightThemeColor="primary",
~darkThemeColor="primary",
~backgroundStyle="bg-gradient-to-b",
~tabView=Compress,
~showRedDot=false,
~visitedTabs=[],
~borderSelectionStyle="",
~borderDefaultStyle="",
~showBottomBorder=true,
~onTabSelection=() => (),
~selectTabBottomBorderColor="",
) => {
let tabRef = React.useRef(Nullable.null)
let fontClass = "font-inter-style"
let defaultBorderClass = "border-0"
let tabTextPadding = "px-6"
let backgroundStyle = backgroundStyle
let tabDisabledStyle = "from-white to-white dark:from-jp-gray-950 dark:to-jp-gray-950 border-b-0 border-jp-gray-500 dark:border-jp-gray-960"
let roundedClass = "rounded-t-md"
let displayElement = switch tabElement {
| Some(ele) => ele
| None => React.string(title)
}
let defaultClasses = if isDisabled && disabledTab->Array.includes(title) {
`cursor-not-allowed ${fontClass} w-max flex flex-auto flex-row items-center justify-center ${roundedClass} ${tabTextPadding} ${backgroundStyle} ${tabDisabledStyle} ${defaultBorderClass} font-semibold dark:text-jp-gray-text_darktheme dark:text-opacity-50 text-opacity-50 hover:text-opacity-50 dark:hover:text-opacity-50`
} else {
`${fontClass} w-max flex flex-auto flex-row items-center justify-center ${tabTextPadding} ${roundedClass} ${defaultBorderClass} font-semibold text-body`
}
let selectionClasses = if isSelected {
`font-semibold text-${lightThemeColor} dark:text-${darkThemeColor} ${textStyle} ${borderSelectionStyle} `
} else {
`text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-75 text-opacity-50 hover:text-opacity-75 dark:hover:text-opacity-100 ${borderDefaultStyle}`
}
let handleClick = React.useCallback2(_ => {
if isDisabled && disabledTab->Array.includes(title) {
()
} else {
handleSelectedIndex(index)
}
onTabSelection()
}, (index, handleSelectedIndex))
let lineStyle = showBottomBorder
? `bg-black w-full h-0.5 rounded-full z-10 ${selectTabBottomBorderColor}`
: ""
React.useEffect(() => {
if isSelected && isScrollIntoViewRequired {
tabRef.current
->Nullable.toOption
->Option.forEach(input =>
input->(scrollIntoView(_, {behavior: "smooth", block: "nearest", inline: "nearest"}))
)
}
None
}, (isSelected, isScrollIntoViewRequired))
let tab =
<div className={"flex flex-col cursor-pointer w-max"}>
<div
className={`${defaultClasses} ${selectionClasses} select-none pb-2 `}
onClick={handleClick}>
{displayElement}
</div>
{if isSelected {
<FramerMotion.Motion.Div className=lineStyle layoutId="underline" />
} else {
<div className="h-0.5" />
}}
</div>
{tab}
}
}
module IndicationArrow = {
@react.component
let make = (~iconName, ~side, ~refElement: React.ref<Js.nullable<Dom.element>>, ~isVisible) => {
let onClick = {
_ =>
refElement.current
->Nullable.toOption
->Option.forEach(input =>
input->(scrollIntoView(_, {behavior: "smooth", block: "nearest", inline: "start"}))
)
}
let roundness = side == "left" ? "rounded-tr-md" : "rounded-tl-md"
let className = if isVisible {
`absolute ${side}-0 bottom-0 shadow-side_shadow 2xl:hidden ${roundness} bg-gray-50`
} else {
`hidden`
}
<div className>
<Button buttonType=Secondary leftIcon={FontAwesome(iconName)} onClick flattenBottom=true />
</div>
}
}
let getBoundingRectInfo = (ref: React.ref<Nullable.t<Dom.element>>, getter) => {
ref.current->Nullable.toOption->Option.map(getBoundingClientRect)->Option.mapOr(0, getter)
}
@react.component
let make = (
~tabs: array<tab>,
~tabsCustomClass="",
~initialIndex=?,
~onTitleClick=?,
~disableIndicationArrow=false,
~tabContainerClass="",
~borderBottomStyle="",
~isScrollIntoViewRequired=false,
~textStyle="",
~isDisabled=false,
~showRedDot=false,
~visitedTabs=[],
~disabledTab=[],
~tabBottomShadow="shadow-md",
~lightThemeColor="primary",
~darkThemeColor="primary",
~defaultClasses="font-ibm-plex w-max flex flex-auto flex-row items-center justify-center px-6 rounded-t-md bg-gradient-to-b from-white to-white hover:from-jp-gray-250 hover:to-jp-gray-200 hover:bg-jp-gray-100 dark:from-jp-gray-950 dark:to-jp-gray-950 border border-b-0 border-jp-gray-500 dark:border-jp-gray-960 font-semibold text-body",
~showBorder=true,
~renderedTabClassName="",
~bottomMargin="pb-8",
~topPadding="",
~includeMargin=true,
~backgroundStyle="bg-gradient-to-b",
~tabView=Compress,
~gapBetweenTabs="gap-1.5",
~borderSelectionStyle="",
~borderDefaultStyle="",
~showBottomBorder=true,
~showStickyHeader=false,
~contentHeight="",
~selectTabBottomBorderColor="",
~customBottomBorderColor=?,
) => {
let _ = defaultClasses
let initialIndex = initialIndex->Option.getOr(0)
let (selectedIndex, setSelectedIndex) = React.useState(() => initialIndex)
let tabOuterClass = `${tabBottomShadow} ${gapBetweenTabs}`
let bottomBorderColor = switch customBottomBorderColor {
| Some(val) => val
| None => "bg-nd_gray-150"
}
let bottomBorderClass = `${bottomBorderColor}
w-full h-0.5 rounded-full -mt-0.5`
let renderedTabClassName = renderedTabClassName
React.useEffect(() => {
setSelectedIndex(_ => initialIndex)
None
}, [initialIndex])
let (_isLeftArrowVisible, setIsLeftArrowVisible) = React.useState(() => false)
let (_isRightArrowVisible, setIsRightArrowVisible) = React.useState(() => true)
let firstTabRef = React.useRef(Nullable.null)
let scrollRef = React.useRef(Nullable.null)
let lastTabRef = React.useRef(Nullable.null)
let numberOfTabs = Array.length(tabs)
let onScroll = _ => {
let leftVal = firstTabRef->getBoundingRectInfo(val => val.x)
let rightVal = lastTabRef->getBoundingRectInfo(val => val.right)
let scrollValLeft = scrollRef->getBoundingRectInfo(val => val.x)
let scrollValRight = scrollRef->getBoundingRectInfo(val => val.right)
let newIsLeftArrowVisible = leftVal - scrollValLeft < 0
let newIsRightArrowVisible = rightVal - scrollValRight >= 10
setIsLeftArrowVisible(_ => newIsLeftArrowVisible)
setIsRightArrowVisible(_ => newIsRightArrowVisible)
}
let handleSelectedIndex = index => {
switch onTitleClick {
| Some(fn) => fn(index)
| None => ()
}
setSelectedIndex(_ => index)
}
let tabClass = switch tabView {
| Compress => ""
| Expand => "w-full"
}
let topMargin = "mt-5"
let stickyHeader = showStickyHeader
? `top-0 height-50 sticky bg-white border-b dark:bg-black border-jp-gray-500 dark:border-jp-gray-960`
: ""
<ErrorBoundary>
<div className={`flex flex-col ${contentHeight}`}>
<div className={`py-0 ${stickyHeader}`}>
<div
className="overflow-x-auto no-scrollbar overflow-y-hidden"
ref={scrollRef->ReactDOM.Ref.domRef}
onScroll>
<div
className={`flex flex-row ${topMargin} pr-8 ${tabOuterClass}
${showBorder && includeMargin ? "ml-5" : ""} ${tabContainerClass}`}>
{tabs
->Array.mapWithIndex((tab, i) => {
let ref = if i == 0 {
firstTabRef->ReactDOM.Ref.domRef->Some
} else if i == numberOfTabs - 1 {
lastTabRef->ReactDOM.Ref.domRef->Some
} else {
None
}
<div className=tabClass ?ref key={Int.toString(i)}>
<TabInfo
title={tab.title}
tabElement=tab.tabElement
isSelected={selectedIndex === i}
index={i}
tabsCustomClass
handleSelectedIndex
borderBottomStyle
isScrollIntoViewRequired
textStyle
lightThemeColor
darkThemeColor
backgroundStyle
disabledTab
isDisabled
tabView
borderSelectionStyle
borderDefaultStyle
showBottomBorder
onTabSelection=?{tab.onTabSelection}
selectTabBottomBorderColor
/>
</div>
})
->React.array}
</div>
</div>
</div>
<RenderIf condition={!showStickyHeader && showBorder}>
<div className=bottomBorderClass />
</RenderIf>
<div className=renderedTabClassName>
<ErrorBoundary key={Int.toString(selectedIndex)}>
{switch tabs->Array.get(selectedIndex) {
| Some(selectedTab) => {
let component = selectedTab.renderContent()
<FramerMotion.TransitionComponent
id={Int.toString(selectedIndex)} className=contentHeight>
{component}
</FramerMotion.TransitionComponent>
}
| None => React.string("No tabs found")
}}
</ErrorBoundary>
</div>
</div>
</ErrorBoundary>
}
| 2,510 | 10,051 |
hyperswitch-control-center | src/components/CustomInputSelectBox.res | .res | @react.component
let make = (
~onChange,
~value,
~buttonText,
~showBorder=?,
~options,
~allowMultiSelect=false,
~isDropDown=true,
~hideMultiSelectButtons=false,
~isHorizontal=false,
~deselectDisable=false,
~buttonType=Button.SecondaryFilled,
~customButtonStyle="",
~customStyle="",
~textStyle="",
~disableSelect=false,
~searchable=?,
~baseComponent=?,
~isPhoneDropdown=false,
~marginTop=?,
~searchInputPlaceHolder=?,
~showSearchIcon=true,
) => {
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "dummy-name",
onBlur: _ => (),
onChange,
onFocus: _ => (),
value,
checked: true,
}
<SelectBox
isDropDown
allowMultiSelect
hideMultiSelectButtons
buttonText
customStyle
textStyle
?showBorder
input
options
deselectDisable
isHorizontal
buttonType
disableSelect
customButtonStyle
?searchable
?baseComponent
isPhoneDropdown
?marginTop
?searchInputPlaceHolder
showSearchIcon
/>
}
| 283 | 10,052 |
hyperswitch-control-center | src/components/SelectBox.resi | .resi | type retType = CheckBox(array<string>) | Radiobox(string)
external toDict: 'a => RescriptCore.Dict.t<'t> = "%identity"
@send external getClientRects: Dom.element => Dom.domRect = "getClientRects"
@send external focus: Dom.element => unit = "focus"
external ffInputToSelectInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput<
array<string>,
> = "%identity"
external ffInputToRadioInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput<
string,
> = "%identity"
let regex: (string, string) => RescriptCore.RegExp.t
module ListItem: {
@react.component
let make: (
~isDropDown: bool,
~searchString: string,
~multiSelect: bool,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~isSelected: bool,
~isPrevSelected: bool=?,
~isNextSelected: bool=?,
~onClick: JsxEventU.Mouse.t => unit,
~text: Js.String2.t,
~fill: string=?,
~labelValue: Js.String2.t=?,
~isDisabled: bool=?,
~icon: Button.iconType,
~leftVacennt: bool=?,
~showToggle: bool=?,
~customStyle: string=?,
~serialNumber: option<string>=?,
~isMobileView: bool=?,
~description: option<string>=?,
~customLabelStyle: option<string>=?,
~customMarginStyle: string=?,
~listFlexDirection: string=?,
~customSelectStyle: string=?,
~textOverflowClass: string=?,
~dataId: int,
~showDescriptionAsTool: bool=?,
~optionClass: string=?,
~selectClass: string=?,
~toggleProps: string=?,
~checkboxDimension: string=?,
~iconStroke: string=?,
~showToolTipOptions: bool=?,
~textEllipsisForDropDownOptions: bool=?,
~textColorClass: string=?,
~customRowClass: string=?,
~labelDescription: option<string>=?,
~labelDescriptionClass: string=?,
~customSelectionIcon: Button.iconType=?,
) => React.element
}
type dropdownOptionWithoutOptional = {
label: string,
value: string,
isDisabled: bool,
icon: Button.iconType,
description: option<string>,
labelDescription: option<string>,
iconStroke: string,
textColor: string,
optGroup: string,
customRowClass: string,
customComponent: option<React.element>,
}
type dropdownOption = {
label: string,
value: string,
labelDescription?: string,
optGroup?: string,
isDisabled?: bool,
icon?: Button.iconType,
description?: string,
iconStroke?: string,
textColor?: string,
customRowClass?: string,
customComponent?: React.element,
}
let makeNonOptional: dropdownOption => dropdownOptionWithoutOptional
let useTransformed: array<dropdownOption> => array<dropdownOptionWithoutOptional>
type allSelectType = Icon | Text
type opt = {name_: string}
let makeOptions: array<string> => array<dropdownOption>
module BaseSelect: {
@react.component
let make: (
~showSelectAll: bool=?,
~showDropDown: bool=?,
~isDropDown: bool=?,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~onSelect: array<string> => unit,
~value: RescriptCore.JSON.t,
~onBlur: ReactEvent.Focus.t => unit=?,
~showClearAll: bool=?,
~isHorizontal: bool=?,
~insertselectBtnRef: ReactDOM.Ref.callbackDomRef=?,
~insertclearBtnRef: ReactDOM.Ref.callbackDomRef=?,
~customLabelStyle: string=?,
~showToggle: bool=?,
~showSerialNumber: bool=?,
~heading: string=?,
~showSelectionAsChips: bool=?,
~maxHeight: string=?,
~searchable: bool=?,
~optionRigthElement: React.element=?,
~searchInputPlaceHolder: string=?,
~showSearchIcon: bool=?,
~customStyle: string=?,
~customMargin: string=?,
~disableSelect: bool=?,
~deselectDisable: bool=?,
~hideBorder: bool=?,
~allSelectType: allSelectType=?,
~isMobileView: bool=?,
~isModalView: bool=?,
~customSearchStyle: string=?,
~hasApplyButton: bool=?,
~setShowDropDown: ('a => bool) => unit=?,
~dropdownCustomWidth: string=?,
~sortingBasedOnDisabled: bool=?,
~customMarginStyle: string=?,
~listFlexDirection: string=?,
~onApply: JsxEvent.Mouse.t => unit=?,
~showAllSelectedOptions: bool=?,
~showDescriptionAsTool: bool=?,
~optionClass: string=?,
~selectClass: string=?,
~toggleProps: string=?,
~showSelectCountButton: bool=?,
~customSelectAllStyle: string=?,
~checkboxDimension: string=?,
~dropdownClassName: string=?,
~onItemSelect: (JsxEventU.Mouse.t, string) => unit=?,
~wrapBasis: string=?,
~preservedAppliedOptions: array<string>=?,
~customComponent: option<React.element>=?,
) => React.element
}
module BaseSelectButton: {
@react.component
let make: (
~showDropDown: bool=?,
~isDropDown: bool=?,
~isHorizontal: bool=?,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~onSelect: string => unit,
~value: RescriptCore.JSON.t,
~deselectDisable: bool=?,
~onBlur: ReactEvent.Focus.t => unit=?,
~setShowDropDown: ('a => bool) => unit=?,
~onAssignClick: string => unit=?,
~customSearchStyle: string,
~disableSelect: bool=?,
~isMobileView: bool=?,
~hideAssignBtn: bool=?,
~searchInputPlaceHolder: string=?,
~showSearchIcon: bool=?,
~allowButtonTextMinWidth: bool=?,
) => React.element
}
module RenderListItemInBaseRadio: {
@react.component
let make: (
~newOptions: array<dropdownOptionWithoutOptional>,
~value: Core__JSON.t,
~descriptionOnHover: bool,
~isDropDown: bool,
~textIconPresent: bool,
~searchString: string,
~optionSize: CheckBoxIcon.size,
~isSelectedStateMinus: bool,
~onItemClick: (string, bool) => JsxEventU.Mouse.t => unit,
~fill: string,
~customStyle: string,
~isMobileView: bool,
~listFlexDirection: string,
~customSelectStyle: string,
~textOverflowClass: option<string>,
~showToolTipOptions: bool,
~textEllipsisForDropDownOptions: bool,
~isHorizontal: bool,
~customMarginStyleOfListItem: string=?,
~bottomComponent: React.element=?,
~optionClass: string=?,
~selectClass: string=?,
~customScrollStyle: string=?,
~shouldDisplaySelectedOnTop: bool,
~labelDescriptionClass: string=?,
~customSelectionIcon: Button.iconType=?,
) => React.element
}
let getHashMappedOptionValues: array<dropdownOptionWithoutOptional> => RescriptCore.Dict.t<
array<dropdownOptionWithoutOptional>,
>
let getSortedKeys: RescriptCore.Dict.t<'a> => array<string>
module BaseRadio: {
@react.component
let make: (
~showDropDown: bool=?,
~isDropDown: bool=?,
~isHorizontal: bool=?,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~onSelect: string => unit,
~value: RescriptCore.JSON.t,
~deselectDisable: bool=?,
~onBlur: ReactEvent.Focus.t => unit=?,
~fill: string=?,
~customStyle: string=?,
~searchable: bool=?,
~isMobileView: bool=?,
~customSearchStyle: string=?,
~descriptionOnHover: bool=?,
~addDynamicValue: bool=?,
~dropdownCustomWidth: string=?,
~dropdownRef: React.ref<RescriptCore.Nullable.t<Dom.element>>=?,
~showMatchingRecordsText: bool=?,
~fullLength: bool=?,
~selectedString: string=?,
~setSelectedString: ('a => string) => unit=?,
~setExtSearchString: ('b => string) => unit=?,
~listFlexDirection: string=?,
~baseComponentCustomStyle: string=?,
~customSelectStyle: string=?,
~maxHeight: string=?,
~textOverflowClass: string=?,
~searchInputPlaceHolder: string=?,
~showSearchIcon: bool=?,
~showToolTipOptions: bool=?,
~textEllipsisForDropDownOptions: bool=?,
~bottomComponent: React.element=?,
~optionClass: string=?,
~selectClass: string=?,
~customScrollStyle: string=?,
~dropdownContainerStyle: string=?,
~shouldDisplaySelectedOnTop: bool=?,
~labelDescriptionClass: string=?,
~customSelectionIcon: Button.iconType=?,
~placeholderCss: string=?,
) => React.element
}
type direction = BottomLeft | BottomMiddle | BottomRight | TopLeft | TopMiddle | TopRight
module BaseDropdown: {
@react.component
let make: (
~buttonText: string,
~buttonSize: Button.buttonSize=?,
~allowMultiSelect: bool,
~input: ReactFinalForm.fieldRenderPropsInput,
~showClearAll: bool=?,
~showSelectAll: bool=?,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~hideMultiSelectButtons: bool,
~deselectDisable: bool=?,
~buttonType: Button.buttonType=?,
~baseComponent: React.element=?,
~baseComponentMethod: bool => React.element=?,
~disableSelect: bool=?,
~textStyle: string=?,
~buttonTextWeight: string=?,
~defaultLeftIcon: Button.iconType=?,
~autoApply: bool=?,
~fullLength: bool=?,
~customButtonStyle: string=?,
~onAssignClick: string => unit=?,
~fixedDropDownDirection: direction=?,
~addButton: bool=?,
~marginTop: string=?,
~customStyle: string=?,
~customSearchStyle: string=?,
~showSelectionAsChips: bool=?,
~showToolTip: bool=?,
~showNameAsToolTip: bool=?,
~searchable: bool=?,
~showBorder: bool=?,
~dropDownCustomBtnClick: bool=?,
~showCustomBtnAtEnd: bool=?,
~customButton: React.element=?,
~descriptionOnHover: bool=?,
~addDynamicValue: bool=?,
~showMatchingRecordsText: bool=?,
~hasApplyButton: bool=?,
~dropdownCustomWidth: string=?,
~allowButtonTextMinWidth: bool=?,
~customMarginStyle: string=?,
~customButtonLeftIcon: Button.iconType=?,
~customTextPaddingClass: string=?,
~customButtonPaddingClass: string=?,
~customButtonIconMargin: string=?,
~textStyleClass: string=?,
~buttonStyleOnDropDownOpened: string=?,
~selectedString: string=?,
~setSelectedString: ('a => string) => unit=?,
~setExtSearchString: ('b => string) => unit=?,
~listFlexDirection: string=?,
~ellipsisOnly: bool=?,
~isPhoneDropdown: bool=?,
~onApply: JsxEvent.Mouse.t => unit=?,
~showAllSelectedOptions: bool=?,
~buttonClickFn: string => unit=?,
~toggleChevronState: unit => unit=?,
~showSelectCountButton: bool=?,
~maxHeight: string=?,
~customBackColor: string=?,
~showToolTipOptions: bool=?,
~textEllipsisForDropDownOptions: bool=?,
~showBtnTextToolTip: bool=?,
~dropdownClassName: string=?,
~searchInputPlaceHolder: string=?,
~showSearchIcon: bool=?,
~sortingBasedOnDisabled: bool=?,
~customSelectStyle: string=?,
~baseComponentCustomStyle: string=?,
~bottomComponent: React.element=?,
~optionClass: string=?,
~selectClass: string=?,
~customDropdownOuterClass: string=?,
~customScrollStyle: string=?,
~dropdownContainerStyle: string=?,
~shouldDisplaySelectedOnTop: bool=?,
~labelDescriptionClass: string=?,
~customSelectionIcon: Button.iconType=?,
~placeholderCss: string=?,
) => React.element
}
module InfraSelectBox: {
@react.component
let make: (
~options: array<dropdownOption>,
~input: ReactFinalForm.fieldRenderPropsInput,
~deselectDisable: bool=?,
~allowMultiSelect: bool=?,
~borderRadius: string=?,
~selectedClass: string=?,
~nonSelectedClass: string=?,
~showTickMark: bool=?,
) => React.element
}
module ChipFilterSelectBox: {
@react.component
let make: (
~options: array<dropdownOption>,
~input: ReactFinalForm.fieldRenderPropsInput,
~deselectDisable: bool=?,
~allowMultiSelect: bool=?,
~isTickRequired: bool=?,
~customStyleForChips: string=?,
) => React.element
}
@react.component
let make: (
~input: ReactFinalForm.fieldRenderPropsInput,
~buttonText: string=?,
~buttonSize: Button.buttonSize=?,
~allowMultiSelect: bool=?,
~isDropDown: bool=?,
~hideMultiSelectButtons: bool=?,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=?,
~isSelectedStateMinus: bool=?,
~isHorizontal: bool=?,
~deselectDisable: bool=?,
~showClearAll: bool=?,
~showSelectAll: bool=?,
~buttonType: Button.buttonType=?,
~disableSelect: bool=?,
~fullLength: bool=?,
~customButtonStyle: string=?,
~textStyle: string=?,
~marginTop: string=?,
~customStyle: string=?,
~showSelectionAsChips: bool=?,
~showToggle: bool=?,
~maxHeight: string=?,
~searchable: bool=?,
~fill: string=?,
~optionRigthElement: React.element=?,
~hideBorder: bool=?,
~allSelectType: allSelectType=?,
~customSearchStyle: string=?,
~searchInputPlaceHolder: string=?,
~showSearchIcon: bool=?,
~customLabelStyle: string=?,
~customMargin: string=?,
~showToolTip: bool=?,
~showNameAsToolTip: bool=?,
~showBorder: bool=?,
~showCustomBtnAtEnd: bool=?,
~dropDownCustomBtnClick: bool=?,
~addDynamicValue: bool=?,
~showMatchingRecordsText: bool=?,
~customButton: React.element=?,
~descriptionOnHover: bool=?,
~fixedDropDownDirection: direction=?,
~dropdownCustomWidth: string=?,
~allowButtonTextMinWidth: bool=?,
~baseComponent: React.element=?,
~baseComponentMethod: bool => React.element=?,
~customMarginStyle: string=?,
~buttonTextWeight: string=?,
~customButtonLeftIcon: Button.iconType=?,
~customTextPaddingClass: string=?,
~customButtonPaddingClass: string=?,
~customButtonIconMargin: string=?,
~textStyleClass: string=?,
~setExtSearchString: ('a => string) => unit=?,
~buttonStyleOnDropDownOpened: string=?,
~listFlexDirection: string=?,
~baseComponentCustomStyle: string=?,
~ellipsisOnly: bool=?,
~customSelectStyle: string=?,
~isPhoneDropdown: bool=?,
~hasApplyButton: bool=?,
~onApply: JsxEvent.Mouse.t => unit=?,
~showAllSelectedOptions: bool=?,
~buttonClickFn: string => unit=?,
~showDescriptionAsTool: bool=?,
~optionClass: string=?,
~selectClass: string=?,
~toggleProps: string=?,
~showSelectCountButton: bool=?,
~leftIcon: Button.iconType=?,
~customBackColor: string=?,
~customSelectAllStyle: string=?,
~checkboxDimension: string=?,
~showToolTipOptions: bool=?,
~textEllipsisForDropDownOptions: bool=?,
~showBtnTextToolTip: bool=?,
~dropdownClassName: string=?,
~onItemSelect: (JsxEventU.Mouse.t, string) => unit=?,
~wrapBasis: string=?,
~customScrollStyle: string=?,
~shouldDisplaySelectedOnTop: bool=?,
~placeholderCss: string=?,
) => React.element
| 3,976 | 10,053 |
hyperswitch-control-center | src/components/LocalFilters.res | .res | module CheckLocalFilters = {
@react.component
let make = (
~options: array<EntityType.optionType<'t>>,
~checkedFilters,
~removeFilters,
~addFilters,
~applyFilters,
~selectedFiltersList,
~addFilterStyle,
~showSelectFiltersSearch,
) => {
let isMobileView = MatchMedia.useMobileChecker()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let values = formState.values
React.useEffect(() => {
if formState.dirty {
switch formState.values->JSON.Decode.object {
| Some(valuesDict) => valuesDict->applyFilters
| None => ()
}
}
None
}, [values])
let onChangeSelect = ev => {
let fieldNameArr = ev->Identity.formReactEventToArrayOfString
let newlyAdded = Array.filter(fieldNameArr, newVal => !Array.includes(checkedFilters, newVal))
if Array.length(newlyAdded) > 0 {
addFilters(newlyAdded)
} else {
removeFilters(fieldNameArr, values)
}
}
let labelClass = ""
let labelPadding = ""
let innerClass = ""
let fieldWrapperClass = !isMobileView ? "px-1 flex flex-col" : ""
let selectOptions = options->Array.map(obj => obj.urlKey)
<div className={`flex flex-row flex-wrap ${innerClass}`}>
<FormRenderer.FieldsRenderer
fields={selectedFiltersList} fieldWrapperClass labelClass labelPadding
/>
<div className={`md:justify-between flex flex-row items-center flex-wrap ${addFilterStyle}`}>
{if Array.length(options) > 0 {
<div className={`flex`}>
<CustomInputSelectBox
onChange=onChangeSelect
options={selectOptions->SelectBox.makeOptions}
allowMultiSelect=true
buttonText="Add Filters"
isDropDown=true
hideMultiSelectButtons=true
buttonType=Button.FilterAdd
value={checkedFilters->Array.map(JSON.Encode.string)->JSON.Encode.array}
searchable=showSelectFiltersSearch
/>
</div>
} else {
React.null
}}
</div>
</div>
}
}
@react.component
let make = (
~entity: EntityType.entityType<'colType, 't>,
~setOffset=?,
~localFilters: array<EntityType.initialFilters<'t>>,
~localOptions: array<EntityType.optionType<'t>>,
~remoteOptions: array<EntityType.optionType<'t>>,
~remoteFilters: array<EntityType.initialFilters<'t>>,
~mandatoryRemoteKeys=[],
~path="",
~ignoreUrlUpdate=false,
~setLocalSearchFilters=?,
~localSearchFilters="",
~tableName=?,
~addFilterStyle="",
~customLocalFilterStyle="",
~showSelectFiltersSearch=false,
~disableURIdecode=false,
) => {
let {defaultFilters} = entity
let (selectedFiltersList, setSelectedFiltersList) = React.useState(_ =>
localFilters->Array.map(item => item.field)
)
let (checkedFilters, setCheckedFilters) = React.useState(_ => [])
let url = RescriptReactRouter.useUrl()
let searchParams = disableURIdecode ? url.search : url.search->decodeURI
let (initialValueJson, setInitialValueJson) = React.useState(_ => JSON.Encode.object(Dict.make()))
let remoteFiltersJson = RemoteFiltersUtils.getInitialValuesFromUrl(
~searchParams,
~initialFilters=remoteFilters,
~options=remoteOptions,
~mandatoryRemoteKeys,
(),
)
let remoteFilterDict = remoteFiltersJson->JsonFlattenUtils.flattenObject(false)
React.useEffect(() => {
let searchValues = ignoreUrlUpdate ? localSearchFilters : searchParams
let initialValues = RemoteFiltersUtils.getInitialValuesFromUrl(
~searchParams=searchValues,
~initialFilters=localFilters,
~options=localOptions,
(),
)
let localCheckedFilters = checkedFilters->Array.copy
let localSelectedFiltersList = selectedFiltersList->Array.copy
initialValues
->JSON.Decode.object
->Option.getOr(Dict.make())
->Dict.toArray
->Array.forEach(entry => {
let (key, _value) = entry
let includes = Array.includes(checkedFilters, key)
if !includes {
let optionalOption = localOptions->Array.find(option => option.urlKey === key)
switch optionalOption {
| Some(optionObj) => {
localSelectedFiltersList->Array.push(optionObj.field)->ignore
localCheckedFilters->Array.push(key)->ignore
}
| None => ()
}
}
})
setCheckedFilters(_prev => localCheckedFilters)
setSelectedFiltersList(_prev => localSelectedFiltersList)
setInitialValueJson(_ => initialValues)
None
}, (searchParams, localSearchFilters))
let applyFilters = valuesDict => {
RemoteFiltersUtils.applyFilters(
~currentFilterDict=valuesDict,
~options=localOptions,
~defaultFilters,
~setOffset,
~path,
~existingFilterDict=remoteFilterDict,
~ignoreUrlUpdate,
~setLocalSearchFilters?,
~tableName,
(),
)
}
let addFilters = newlyAdded => {
let localCheckedFilters = checkedFilters->Array.copy
let localSelectedFiltersList = selectedFiltersList->Array.copy
newlyAdded->Array.forEach(value => {
let optionObjArry = localOptions->Array.filter(option => option.urlKey === value)
let defaultEntityOptionType: EntityType.optionType<
't,
> = EntityType.getDefaultEntityOptionType()
let optionObj = optionObjArry[0]->Option.getOr(defaultEntityOptionType)
localSelectedFiltersList->Array.push(optionObj.field)->ignore
localCheckedFilters->Array.push(value)->ignore
})
setCheckedFilters(_prev => localCheckedFilters)
setSelectedFiltersList(_prev => localSelectedFiltersList)
}
let removeFilters = (fieldNameArr, values) => {
let toBeRemoved = checkedFilters->Array.filter(oldVal => !Array.includes(fieldNameArr, oldVal))
let finalFieldList = selectedFiltersList->Array.filter(val => {
val.inputNames
->Array.get(0)
->Option.map(name => !{toBeRemoved->Array.includes(name)})
->Option.getOr(false)
})
let filtersAfterRemoving =
checkedFilters->Array.filter(val => !Array.includes(toBeRemoved, val))
let newInitialValues =
initialValueJson
->JSON.Decode.object
->Option.getOr(Dict.make())
->Dict.toArray
->Array.filter(entry => {
let (key, _value) = entry
!Array.includes(toBeRemoved, key)
})
->Dict.fromArray
->JSON.Encode.object
switch values->JSON.Decode.object {
| Some(dict) =>
dict
->Dict.toArray
->Array.forEach(entry => {
let (key, _val) = entry
if toBeRemoved->Array.includes(key) {
dict->Dict.set(key, JSON.Encode.string(""))
}
dict->applyFilters
})
| None => ()
}
setInitialValueJson(_ => newInitialValues)
setCheckedFilters(_prev => filtersAfterRemoving)
setSelectedFiltersList(_prev => finalFieldList)
}
<div className={`bg-transparent flex flex-row ${customLocalFilterStyle}`}>
<div>
<Form initialValues=initialValueJson>
<CheckLocalFilters
options={localOptions}
checkedFilters
addFilters
removeFilters
applyFilters
selectedFiltersList
addFilterStyle
showSelectFiltersSearch
/>
</Form>
</div>
</div>
}
| 1,700 | 10,054 |
hyperswitch-control-center | src/components/RangeSlider.res | .res | @react.component
let make = (
~max="5000",
~min="1200",
~width="200px",
~maxSlide: ReactFinalForm.fieldRenderPropsInput,
~minSlide: ReactFinalForm.fieldRenderPropsInput,
) => {
let max = Math.ceil(max->Js.Float.fromString)
let min = Math.floor(min->Js.Float.fromString)
let (minSlideVal, setMinSlideVal) = React.useState(_ =>
minSlide.value->LogicUtils.getFloatFromJson(min)
)
let (maxSlideVal, setMaxSlideVal) = React.useState(_ =>
maxSlide.value->LogicUtils.getFloatFromJson(max)
)
let (hasError, setHasError) = React.useState(_ => (false, false))
let (isFocused, setIsFocused) = React.useState(_ => (false, false))
let (isInputFocused, setIsInputFocused) = React.useState(_ => (false, false))
let (isMinFocused, isMaxFocused) = isFocused
let (isMinInputFocused, isMaxInputFocused) = isInputFocused
let (hasMinError, hasMaxError) = hasError
let maxSlide = {
...maxSlide,
value: maxSlide.value <= minSlide.value
? minSlide.value
: maxSlide.value > max->JSON.Encode.float
? max->JSON.Encode.float
: maxSlide.value,
}
let minSlide = {
...minSlide,
value: minSlide.value >= maxSlide.value
? maxSlide.value
: minSlide.value < min->JSON.Encode.float
? min->JSON.Encode.float
: minSlide.value,
}
let diff = React.useMemo(() => {
Math.max(max -. min, 1.)
}, (max, min))
let maxsliderVal = React.useMemo(() => {
switch maxSlide.value->JSON.Decode.float {
| Some(num) => Math.ceil(num)->Float.toString
| None => "0"
}
}, [maxSlide.value])
let minsliderVal = React.useMemo(() => {
switch minSlide.value->JSON.Decode.float {
| Some(num) => Math.floor(num)->Float.toString
| None => "0"
}
}, [minSlide.value])
let minborderClass = hasMinError
? "border-jp-2-light-red-600"
: `${isMinFocused || isMinInputFocused ? "border-jp-2-light-primary-600" : ""}`
let maxborderClass = hasMaxError
? "border-jp-2-light-red-600"
: `${isMaxFocused || isMaxInputFocused ? "border-jp-2-light-primary-600" : ""}`
let inputClassname = (hasError, isFocused) => {
let bg = hasError
? "bg-jp-2-red-100"
: `${isFocused
? "bg-jp-2-light-primary-200"
: "focus:bg-jp-2-light-primary-200 hover:bg-jp-2-light-gray-100"}`
`w-max numberInput outline-none p-1 ${bg} `
}
let bgClass = isMinFocused || isMaxFocused ? "bg-primary" : "bg-jp-2-light-gray-2000"
<div className="relative pt-1 w-max">
<div className={`h-1 rounded relative bg-gray-200`} style={width: width}>
<div
className={`h-1 rounded absolute ${bgClass}`}
style={
width: ((maxsliderVal->LogicUtils.getFloatFromString(0.) -.
minsliderVal->LogicUtils.getFloatFromString(0.)) *.
100. /.
diff)->Float.toString ++ "%",
left: ((minsliderVal->LogicUtils.getFloatFromString(0.) -. min) *. 100. /. diff)
->Float.toString ++ "%",
right: ((max -. maxsliderVal->LogicUtils.getFloatFromString(0.)) *. 100. /. diff)
->Float.toString ++ "%",
}
/>
</div>
<div className={`absolute top-0`}>
<input
style={width: width}
className={`absolute bg-transparent pointer-events-none appearance-none slider hover:sliderFocus active:sliderFocus outline-none`}
type_="range"
value=minsliderVal
min={min->Float.toString}
max={max->Float.toString}
onBlur={minSlide.onBlur}
onChange={ev => {
minSlide.onChange(ev)
setHasError(((_, max)) => (false, max))
setMinSlideVal(_ => ReactEvent.Form.target(ev)["value"])
}}
onFocus={ev => {
minSlide.onFocus(ev)
}}
onMouseEnter={_ => setIsFocused(((_, max)) => (true, max))}
onMouseLeave={_ => setIsFocused(((_, max)) => (false, max))}
/>
<input
style={width: width}
className={`absolute bg-transparent pointer-events-none appearance-none slider hover:sliderFocus active:sliderFocus outline-none`}
type_="range"
value=maxsliderVal
min={min->Float.toString}
max={max->Float.toString}
onBlur={maxSlide.onBlur}
onChange={ev => {
maxSlide.onChange(ev)
setHasError(((min, _)) => (min, false))
setMaxSlideVal(_ => ReactEvent.Form.target(ev)["value"])
}}
onFocus={ev => {
minSlide.onFocus(ev)
}}
onMouseEnter={_ => setIsFocused(((min, _)) => (min, true))}
onMouseLeave={_ => setIsFocused(((min, _)) => (min, false))}
/>
</div>
<div className="mt-4 flex flex-row justify-between w-full">
<span className={`font-bold p-1 border-b ${minborderClass}`}>
<input
type_="number"
className={inputClassname(hasMinError, isMinFocused)}
value={minSlideVal->Float.toString}
min={min->Float.toString}
max={max->Float.toString}
onBlur={ev => {
let minVal = minSlideVal
let maxSliderValue = maxSlide.value->JSON.Decode.float->Option.getOr(0.)
if minVal >= min && minVal < maxSliderValue {
setHasError(((_, max)) => (false, max))
minSlide.onChange(ev->Identity.anyTypeToReactEvent)
} else {
setHasError(((_, max)) => (true, max))
}
setIsInputFocused(((_, max)) => (false, max))
}}
onChange={ev => {
setMinSlideVal(_ => ReactEvent.Form.target(ev)["value"])
}}
onKeyUp={ev => {
let key = ev->ReactEvent.Keyboard.key
let keyCode = ev->ReactEvent.Keyboard.keyCode
if key === "Enter" || keyCode === 13 {
let minVal = minSlideVal
let maxSliderValue = maxSlide.value->JSON.Decode.float->Option.getOr(0.)
if minVal >= min && minVal <= maxSliderValue {
setHasError(((_, max)) => (false, max))
minSlide.onChange(ev->Identity.anyTypeToReactEvent)
} else {
setHasError(((_, max)) => (true, max))
}
}
}}
onFocus={_ => setIsInputFocused(((_, max)) => (true, max))}
/>
</span>
<span className={`font-bold p-1 border-b ${maxborderClass}`}>
<input
className={inputClassname(hasMaxError, isMaxFocused)}
type_="number"
value={maxSlideVal->Float.toString}
min={min->Float.toString}
max={max->Float.toString}
onBlur={ev => {
let maxVal = maxSlideVal
let minSliderValue = minSlide.value->JSON.Decode.float->Option.getOr(0.)
if maxVal <= max && maxVal > minSliderValue {
setHasError(((min, _)) => (min, false))
maxSlide.onChange(ev->Identity.anyTypeToReactEvent)
} else {
setHasError(((min, _)) => (min, true))
}
setIsInputFocused(((min, _)) => (min, false))
}}
onChange={ev => {
setMaxSlideVal(_ => ReactEvent.Form.target(ev)["value"])
}}
onKeyUp={ev => {
let key = ev->ReactEvent.Keyboard.key
let keyCode = ev->ReactEvent.Keyboard.keyCode
let maxVal = maxSlideVal
let minSliderValue = minSlide.value->JSON.Decode.float->Option.getOr(0.)
if key === "Enter" || keyCode === 13 {
if maxVal <= max && maxVal >= minSliderValue {
setHasError(((min, _)) => (min, false))
maxSlide.onChange(ev->Identity.anyTypeToReactEvent)
} else {
setHasError(((min, _)) => (min, true))
}
}
}}
onFocus={_ => setIsInputFocused(((min, _)) => (min, true))}
/>
</span>
</div>
</div>
}
| 2,027 | 10,055 |
hyperswitch-control-center | src/components/TableUtils.res | .res | let regex = searchString => {
RegExp.fromStringWithFlags(`` ++ searchString ++ ``, ~flags="gi")
}
let highlightedText = (str, searchedText) => {
let shouldHighlight =
searchedText->LogicUtils.isNonEmptyString &&
String.includes(str->String.toLowerCase, searchedText->String.toLowerCase)
if shouldHighlight {
let re = regex(searchedText)
let matchFn = (matchPart, _offset, _wholeString) => `@@${matchPart}@@`
let listText = Js.String.unsafeReplaceBy0(re, matchFn, str)->String.split("@@")
{
listText
->Array.mapWithIndex((item, i) => {
if (
String.toLowerCase(item) == String.toLowerCase(searchedText) &&
String.length(searchedText) > 0
) {
<mark key={i->Int.toString} className="bg-yellow"> {item->React.string} </mark>
} else {
let className = ""
<span key={i->Int.toString} className value=str> {item->React.string} </span>
}
})
->React.array
}
} else {
React.string(str)
}
}
type labelColor =
| LabelGreen
| LabelRed
| LabelBlue
| LabelGray
| LabelOrange
| LabelYellow
| LabelLightGray
type filterDataType =
| Float(float, float)
| String
| DateTime
type disableField = {
key: string,
values: array<string>,
}
type customiseColumnConfig = {
showDropDown: bool,
customizeColumnUi: React.element,
}
type selectAllSubmitActions = {
btnText: string,
showMultiSelectCheckBox: bool,
onClick: array<JSON.t> => unit,
disableParam: disableField,
}
type hideItem = {
key: string,
value: string,
}
external jsonToStr: JSON.t => string = "%identity"
type textAlign = Left | Right
type fontBold = bool
type labelMargin = string
type sortOrder = INC | DEC | NONE
type sortedObject = {
key: string,
order: sortOrder,
}
type multipleSelectRows = ALL | PARTIAL
type filterObject = {
key: string,
options: array<string>,
selected: array<string>,
}
let getSortOrderString = (order: sortOrder) => {
switch order {
| INC => "desc"
| DEC => "asc"
| NONE => ""
}
}
type label = {
title: string,
color: labelColor,
showIcon?: bool,
}
type currency = string
type filterRow =
| DropDownFilter(string, array<JSON.t>)
| TextFilter(string)
| Range(string, float, float)
type cell =
| Label(label)
| Text(string)
| EllipsisText(string, string)
| Currency(float, currency)
| Date(string)
| DateWithoutTime(string)
| DateWithCustomDateStyle(string, string)
| StartEndDate(string, string)
| InputField(React.element)
| Link(string)
| Progress(int)
| CustomCell(React.element, string)
| DisplayCopyCell(string)
| TrimmedText(string, string)
| DeltaPercentage(float, float)
| DropDown(string)
| Numeric(float, float => string) // value and mapper
| ColoredText(label)
type cellType = LabelType | TextType | MoneyType | NumericType | ProgressType | DropDown
type header = {
key: string,
title: string,
dataType: cellType,
showSort: bool,
showFilter: bool,
highlightCellOnHover: bool,
headerElement: option<React.element>,
description: option<string>,
data: option<string>,
isMandatory: option<bool>,
showMultiSelectCheckBox: option<bool>,
hideOnShrink: option<bool>,
customWidth: option<string>,
}
let makeHeaderInfo = (
~key,
~title,
~dataType=TextType,
~showSort=false,
~showFilter=false,
~highlightCellOnHover=false,
~headerElement=?,
~description=?,
~data=?,
~isMandatory=?,
~showMultiSelectCheckBox=?,
~hideOnShrink=?,
~customWidth=?,
) => {
{
key,
title,
dataType,
showSort,
showFilter,
highlightCellOnHover,
headerElement,
description,
data,
isMandatory,
showMultiSelectCheckBox,
hideOnShrink,
customWidth,
}
}
let getCell = (item): cell => {
Text(item)
}
module ProgressCell = {
@react.component
let make = (~progressPercentage) => {
<div className="w-full bg-gray-200 rounded-full">
<div
className="bg-green-700 text font-medium text-blue-100 text-left pl-5 p-0.5 leading-none rounded-full"
style={width: `${Int.toString(progressPercentage)}%`}>
{React.string(Int.toString(progressPercentage) ++ "%")}
</div>
</div>
}
}
let getTextAlignmentClass = textAlign => {
switch textAlign {
| Left => "text-left"
| Right => "text-right px-2"
}
}
module BaseComponentMethod = {
@react.component
let make = (~showDropDown, ~filterKey) => {
let (_, setLclFilterOpen) = React.useContext(DataTableFilterOpenContext.filterOpenContext)
React.useEffect(() => {
setLclFilterOpen(filterKey, showDropDown)
None
}, [showDropDown])
<div
className={`flex px-1 pt-1 pb-0.5 items-center rounded-sm ${showDropDown
? "bg-jp-2-light-primary-100 !text-jp-2-light-primary-600"
: ""}`}>
<Icon name="bars-filter" size=12 parentClass="cursor-pointer" />
</div>
}
}
module LabelCell = {
@react.component
let make = (
~labelColor: labelColor,
~text,
~labelMargin="",
~highlightText="",
~fontStyle="font-ibm-plex",
~showIcon=true,
) => {
let isMobileView = MatchMedia.useMobileChecker()
let bgOpacity = isMobileView ? "bg-opacity-12 dark:!bg-opacity-12" : ""
let borderColor = switch labelColor {
| LabelGreen => `bg-nd_green-50 ${bgOpacity} dark:bg-opacity-50`
| LabelRed => `bg-nd_red-50 ${bgOpacity} dark:bg-opacity-50`
| LabelBlue => `bg-nd_primary_blue-50 bg-opacity-50`
| LabelGray => "bg-nd_gray-150"
| LabelOrange => `bg-nd_orange-50 ${bgOpacity} dark:bg-opacity-50`
| LabelYellow => "bg-nd_yellow-100"
| LabelLightGray => "bg-nd_gray-50"
}
let textColor = switch labelColor {
| LabelGreen => "text-nd_green-600"
| LabelRed => "text-nd_red-600"
| LabelOrange => "text-nd_orange-600"
| LabelYellow => "text-nd_yellow-800"
| LabelGray => "text-nd_gray-600"
| LabelLightGray => "text-nd_gray_600"
| LabelBlue => "text-nd_primary_blue-600"
| _ => "text-white"
}
let mobileTextColor = switch labelColor {
| LabelGreen => "text-green-950"
| LabelOrange => "text-orange-950"
| LabelRed => "text-red-960"
| _ => "text-white"
}
let textColor = isMobileView ? mobileTextColor : textColor
let fontStyle = "font-inter-style"
<div className="flex">
<div className="flex-initial ">
<div className={`rounded ${borderColor}`}>
<div
className={`${labelMargin} ${fontStyle} ${textColor} text-fs-10 font-bold px-2 py-0.5`}>
<AddDataAttributes attributes=[("data-label", text)]>
<div> {highlightedText(text, highlightText)} </div>
</AddDataAttributes>
</div>
</div>
</div>
</div>
}
}
module NewLabelCell = {
@react.component
let make = (
~labelColor: labelColor,
~text,
~labelMargin="",
~highlightText="",
~fontStyle="font-ibm-plex",
) => {
let _borderColor = switch labelColor {
| LabelGreen => "bg-green-950 dark:bg-opacity-50"
| LabelRed => "bg-red-960 dark:bg-opacity-50"
| LabelBlue => "bg-primary dark:bg-opacity-50"
| LabelGray => "bg-blue-table_gray"
| LabelOrange => "bg-orange-950 dark:bg-opacity-50"
| LabelYellow => "bg-blue-table_yellow"
| LabelLightGray => "bg-nd_gray-50"
}
let bgColor = switch labelColor {
| LabelGreen => "bg-[#ECFDF3]"
| LabelYellow => "bg-[#FFF9E2]"
| LabelRed => "bg-[#FEECEB]"
| _ => "bg-[#FFF9E2]"
}
let textColor = switch labelColor {
| LabelGreen => "text-[#027A48]"
| LabelYellow => "text-[#333333]"
| LabelRed => "text-[#A83027]"
| _ => "text-[#333333]"
}
let dotColor = switch labelColor {
| LabelGreen => "fill-[#12B76A]"
| LabelYellow => "fill-[#FDD744]"
| LabelRed => "fill-[#F04438]"
| _ => "fill-[#FDD744]"
}
<div className="flex">
<div className="flex-initial ">
<div
className={`flex flex-row px-2 py-0.5 ${bgColor} rounded-[16px] text-fs-10 font-bold ${textColor}`}>
<Icon className={`${dotColor} mr-2`} name="circle_unfilled" size=6 />
<div className={`${textColor} font-medium text-xs`}> {React.string(text)} </div>
</div>
</div>
</div>
}
}
module ColoredTextCell = {
@react.component
let make = (~labelColor: labelColor, ~text, ~customPadding="px-2") => {
let textColor = switch labelColor {
| LabelGreen => "text-status-green"
| LabelRed => "text-red-980"
| LabelBlue => "text-sky-500"
| LabelOrange => "text-status-text-orange"
| LabelGray => "text-grey-500"
| LabelYellow => "text-yellow-400"
| LabelLightGray => "text-nd_gray-600"
}
<div className="flex">
<div className="flex-initial ">
<p className={`py-0.5 fira-code text-fs-13 font-semibold ${textColor} ${customPadding}`}>
{React.string(text)}
</p>
</div>
</div>
}
}
module Numeric = {
@react.component
let make = (~num: float, ~mapper, ~clearFormatting) => {
if clearFormatting {
<AddDataAttributes attributes=[("data-numeric", num->Float.toString)]>
<div> {React.string(num->Float.toString)} </div>
</AddDataAttributes>
} else {
<AddDataAttributes attributes=[("data-numeric", num->mapper)]>
<div> {React.string(num->mapper)} </div>
</AddDataAttributes>
}
}
}
module MoneyCell = {
let getAmountValue = (amount, currency) => {
let amountSplitArr = Float.toFixedWithPrecision(amount, ~digits=2)->String.split(".")
let decimal = amountSplitArr[1]->Option.getOr("00")
let receivedValue = amountSplitArr->Array.get(0)->Option.getOr("")
let formattedAmount = if receivedValue->String.includes("e") {
receivedValue
} else if currency === "INR" {
receivedValue->String.replaceRegExp(%re("/(\d)(?=(?:(\d\d)+(\d)(?!\d))+(?!\d))/g"), "$1,")
} else {
receivedValue->String.replaceRegExp(%re("/(\d)(?=(\d{3})+(?!\d))/g"), "$1,")
}
let formatted_amount = `${formattedAmount}.${decimal}`
`${formatted_amount} ${currency}`
}
@react.component
let make = (
~amount: float,
~currency,
~isCard=false,
~textAlign=Right,
~fontBold=false,
~customMoneyStyle="",
) => {
let textAlignClass = textAlign->getTextAlignmentClass
let boldClass = fontBold
? `text-fs-20 font-bold text-jp-gray-900`
: `text-fs-13 text-jp-gray-dark_disable_border_color`
let wrapperClass = isCard
? `font-semibold font-fira-code`
: `${boldClass} text-start dark:text-white ${textAlignClass} ${customMoneyStyle}`
let amountValue = getAmountValue(amount, currency)
<AddDataAttributes attributes=[("data-money-cell", amountValue)]>
<div className=wrapperClass> {React.string(amountValue)} </div>
</AddDataAttributes>
}
}
module LinkCell = {
@react.component
let make = (~data, ~trimLength=?) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (showCopy, setShowCopy) = React.useState(() => false)
let isMobileView = MatchMedia.useMobileChecker()
let trimData = switch trimLength {
| Some(length) => {
let length = isMobileView ? 36 : length
String.concat("..", Js.String.substrAtMost(~from=0, ~length, data))
}
| None => data
}
let mouseOver = _ => {
setShowCopy(_ => true)
}
let mouseOut = _ => {
setShowCopy(_ => false)
}
let visibility = showCopy && !isMobileView ? "visible" : "invisible"
let preventEvent = ev => {
ev->ReactEvent.Mouse.stopPropagation
}
<div className="flex flex-row items-center" onMouseOver={mouseOver} onMouseOut={mouseOut}>
<div
className={`whitespace-pre text-sm font-fira-code dark:text-opacity-75 text-right p-1 ${textColor.primaryNormal} text-ellipsis overflow-hidden`}>
<a href=data target="_blank" onClick=preventEvent> {React.string(trimData)} </a>
</div>
<div className=visibility>
<Clipboard.Copy data toolTipPosition={Top} />
</div>
</div>
}
}
module DateCell = {
@react.component
let make = (
~timestamp,
~isCard=false,
~textStyle=?,
~textAlign=Right,
~customDateStyle="",
~hideTime=false,
~hideTimeZone=false,
) => {
let isMobileView = MatchMedia.useMobileChecker()
let dateFormat = React.useContext(DateFormatProvider.dateFormatContext)
let dateFormat = isMobileView
? "DD MMM HH:mm"
: customDateStyle->LogicUtils.isNonEmptyString
? customDateStyle
: dateFormat
let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat()
let getFormattedDate = dateStr => {
try {
let customTimeZone = isoStringToCustomTimeZone(dateStr)
TimeZoneHook.formattedDateTimeFloat(customTimeZone, dateFormat)
} catch {
| _ => `${dateStr} - unable to parse`
}
}
let fontType = switch textStyle {
| Some(font) => font
| None => "font-semibold"
}
let fontStyle = "font-inter-style"
let (zone, _setZone) = React.useContext(UserTimeZoneProvider.userTimeContext)
let selectedTimeZoneData = TimeZoneData.getTimeZoneData(zone)
let selectedTimeZoneAlias = selectedTimeZoneData.title
let textAlignClass = textAlign->getTextAlignmentClass
let wrapperClass = isCard
? fontType
: `dark:text-jp-gray-text_darktheme dark:text-opacity-75 ${textAlignClass} ${fontStyle}`
<AddDataAttributes attributes=[("data-date", timestamp->getFormattedDate)]>
<div className={`${wrapperClass} whitespace-nowrap`}>
{hideTime
? React.string(timestamp->getFormattedDate->String.slice(~start=0, ~end=12))
: hideTimeZone
? React.string(`${timestamp->getFormattedDate}`)
: React.string(`${timestamp->getFormattedDate} ${selectedTimeZoneAlias}`)}
</div>
</AddDataAttributes>
}
}
module StartEndDateCell = {
@react.component
let make = (~startDate, ~endDate, ~isCard=false) => {
let _ = isCard
<div>
<div className="flex justify-between">
{React.string("Start: ")}
<DateCell timestamp=startDate />
</div>
<div className="flex justify-between">
{React.string("End: ")}
<DateCell timestamp=endDate />
</div>
</div>
}
}
module EllipsisText = {
@react.component
let make = (
~text,
~width,
~highlightText="",
~isEllipsisTextRelative=true,
~ellipseClass="",
~ellipsisIdentifier="",
~ellipsisThreshold=20,
~toolTipPosition: ToolTip.toolTipPosition=ToolTip.Right,
) => {
open LogicUtils
let modifiedText =
ellipsisIdentifier->isNonEmptyString
? {
text->String.split(ellipsisIdentifier)->Array.get(0)->Option.getOr("") ++ "..."
}
: text
let ellipsesCondition =
ellipsisIdentifier->isNonEmptyString
? String.includes(ellipsisIdentifier, text)
: text->String.length > ellipsisThreshold
// If text character count is greater than ellipsisThreshold, it will render tooltip else we will have whole text in cell
if ellipsesCondition {
<ToolTip
contentAlign=Left
description=text
toolTipPosition
tooltipForWidthClass=ellipseClass
isRelative=isEllipsisTextRelative
toolTipFor={<div className={`whitespace-pre text-ellipsis overflow-x-hidden ${width}`}>
{highlightedText(modifiedText, highlightText)}
</div>}
/>
} else {
<div className={`whitespace-pre text-ellipsis ${ellipseClass} ${width}`}>
{highlightedText(text, highlightText)}
</div>
}
}
}
module TrimmedText = {
@react.component
let make = (~text, ~width, ~highlightText="", ~hideShowMore=false) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (show, setshow) = React.useState(_ => true)
let breakWords = hideShowMore ? "" : "whitespace-nowrap text-ellipsis overflow-x-hidden"
if text->String.length > 40 {
<div className={show ? `${breakWords} justify-content ${width}` : "justify-content"}>
<AddDataAttributes attributes=[("data-trimmed-text", text)]>
<div className={hideShowMore ? "truncate" : ""}>
{highlightedText(text, highlightText)}
</div>
</AddDataAttributes>
{if !hideShowMore {
<div
className={`${textColor.primaryNormal} cursor-pointer`}
onClick={_ => setshow(show => !show)}>
{show ? React.string("More") : React.string("Less")}
</div>
} else {
React.null
}}
</div>
} else {
<div>
<AddDataAttributes attributes=[("data-trimmed-text", text)]>
<div className={hideShowMore ? `justify-content ${width} truncate` : ""}>
{highlightedText(text, highlightText)}
</div>
</AddDataAttributes>
</div>
}
}
}
module TableFilterCell = {
@react.component
let make = (~cell: filterRow) => {
open TableLocalFilters
switch cell {
| DropDownFilter(val, arr) => <FilterDropDown val arr />
| TextFilter(val) => <TextFilterCell val />
| Range(val, minVal, maxVal) => <RangeFilterCell minVal maxVal val />
}
}
}
module DeltaColumn = {
@react.component
let make = (~value, ~delta) => {
let detlaStr = Float.toFixedWithPrecision(delta, ~digits=2) ++ "%"
let (deltaText, textColor, _, _, _) = if delta == 0. {
let textColor = ""
("", textColor, "", "", "bg-jp-2-gray-30")
} else if delta < 0. {
let textColor = "text-red-980"
("", textColor, "text-jp-2-red-100", "arrow-down", "bg-jp-2-red-100")
} else {
let textColor = "text-green-950"
("+", textColor, "text-jp-2-green-300", "arrow-up", "bg-jp-2-green-50")
}
let detlaStr = deltaText ++ detlaStr
let paraparentCss = "flex items-center rounded"
// font-style can be changed acc to the module fira-code
<div className="flex">
<div className="flex justify-between">
<div className=paraparentCss>
<p className="px-2 py-0.5 fira-code text-fs-13">
{React.string(Float.toFixedWithPrecision(value, ~digits=2) ++ "%")}
</p>
</div>
<RenderIf condition={delta !== value}>
<div className=paraparentCss>
<p className={`px-2 py-0.5 fira-code text-fs-10 ${textColor}`}>
{React.string(detlaStr)}
</p>
</div>
</RenderIf>
</div>
</div>
}
}
module TableCell = {
@react.component
let make = (
~cell,
~textAlign: option<textAlign>=?,
~fontBold=false,
~labelMargin: option<labelMargin>=?,
~customMoneyStyle="",
~customDateStyle="",
~highlightText="",
~hideShowMore=false,
~clearFormatting=false,
~fontStyle="",
~isEllipsisTextRelative=true,
~ellipseClass="",
) => {
open LogicUtils
switch cell {
| Label(x) =>
<AddDataAttributes attributes=[("data-testid", x.title->String.toLowerCase)]>
<LabelCell
labelColor=x.color
text=x.title
showIcon=?{x.showIcon}
?labelMargin
highlightText
fontStyle
/>
</AddDataAttributes>
| Text(x) | DropDown(x) => {
let x = x->isEmptyString ? "NA" : x
<AddDataAttributes attributes=[("data-desc", x), ("data-testid", x->String.toLowerCase)]>
<div> {highlightedText(x, highlightText)} </div>
</AddDataAttributes>
}
| EllipsisText(text, width) =>
<AddDataAttributes attributes=[("data-testid", text->String.toLowerCase)]>
<EllipsisText text width highlightText isEllipsisTextRelative ellipseClass />
</AddDataAttributes>
| TrimmedText(text, width) => <TrimmedText text width highlightText hideShowMore />
| Currency(amount, currency) =>
<MoneyCell amount currency ?textAlign fontBold customMoneyStyle />
| Date(timestamp) =>
timestamp->isNonEmptyString
? <DateCell timestamp textAlign=Left customDateStyle />
: <div> {React.string("-")} </div>
| DateWithoutTime(timestamp) =>
timestamp->isNonEmptyString
? <DateCell timestamp textAlign=Left customDateStyle hideTime=true />
: <div> {React.string("-")} </div>
| DateWithCustomDateStyle(timestamp, dateFormat) =>
timestamp->isNonEmptyString
? <DateCell
timestamp textAlign=Left hideTime=false hideTimeZone=true customDateStyle=dateFormat
/>
: <div> {React.string("-")} </div>
| StartEndDate(startDate, endDate) => <StartEndDateCell startDate endDate />
| InputField(fieldElement) => fieldElement
| Link(ele) => <LinkCell data=ele trimLength=55 />
| Progress(percent) => <ProgressCell progressPercentage=percent />
| CustomCell(ele, _) => ele
| DisplayCopyCell(string) => <HelperComponents.CopyTextCustomComp displayValue=Some(string) />
| DeltaPercentage(value, delta) => <DeltaColumn value delta />
| Numeric(num, mapper) => <Numeric num mapper clearFormatting />
| ColoredText(x) => <ColoredTextCell labelColor=x.color text=x.title />
}
}
}
module NewTableCell = {
@react.component
let make = (
~cell,
~textAlign: option<textAlign>=?,
~fontBold=false,
~labelMargin: option<labelMargin>=?,
~customMoneyStyle="",
~customDateStyle="",
~highlightText="",
~hideShowMore=false,
~clearFormatting=false,
~fontStyle="",
) => {
open LogicUtils
switch cell {
| Label(x) =>
<NewLabelCell labelColor=x.color text=x.title ?labelMargin highlightText fontStyle />
| Text(x) | DropDown(x) => {
let x = x->isEmptyString ? "NA" : x
<AddDataAttributes attributes=[("data-desc", x)]>
<div> {highlightedText(x, highlightText)} </div>
</AddDataAttributes>
}
| EllipsisText(text, width) => <EllipsisText text width highlightText />
| TrimmedText(text, width) => <TrimmedText text width highlightText hideShowMore />
| Currency(amount, currency) =>
<MoneyCell amount currency ?textAlign fontBold customMoneyStyle />
| Date(timestamp) =>
timestamp->isNonEmptyString
? <DateCell timestamp textAlign=Left customDateStyle />
: <div> {React.string("-")} </div>
| DateWithoutTime(timestamp) =>
timestamp->isNonEmptyString
? <DateCell timestamp textAlign=Left customDateStyle hideTime=true />
: <div> {React.string("-")} </div>
| DateWithCustomDateStyle(timestamp, dateFormat) =>
timestamp->isNonEmptyString
? <DateCell
timestamp textAlign=Left hideTime=false hideTimeZone=true customDateStyle=dateFormat
/>
: <div> {React.string("-")} </div>
| StartEndDate(startDate, endDate) => <StartEndDateCell startDate endDate />
| InputField(fieldElement) => fieldElement
| Link(ele) => <LinkCell data=ele trimLength=55 />
| Progress(percent) => <ProgressCell progressPercentage=percent />
| CustomCell(ele, _) => ele
| DisplayCopyCell(string) => <HelperComponents.CopyTextCustomComp displayValue=Some(string) />
| DeltaPercentage(value, delta) => <DeltaColumn value delta />
| Numeric(num, mapper) => <Numeric num mapper clearFormatting />
| ColoredText(x) => <ColoredTextCell labelColor=x.color text=x.title />
}
}
}
type rowType = Filter | Row
let getTableCellValue = cell => {
switch cell {
| Label(x) => x.title
| Text(x) => x
| Date(x) => x
| DateWithoutTime(x) => x
| Currency(val, _) => val->Float.toString
| Link(str) => str
| CustomCell(_, value) => value
| DisplayCopyCell(str) => str
| EllipsisText(x, _) => x
| DeltaPercentage(x, _) | Numeric(x, _) => x->Float.toString
| ColoredText(x) => x.title
| _ => ""
}
}
module SortIcons = {
@react.component
let make = (~order: sortOrder, ~size: int) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (iconColor1, iconColor2) = switch order {
| INC => ("text-gray-300", textColor.primaryNormal)
| DEC => (textColor.primaryNormal, "text-gray-300")
| NONE => ("text-gray-300", "text-gray-300")
}
<div className="flex flex-col justify-center">
<Icon className={`-mb-0.5 ${iconColor1}`} name="caret-up" size />
<Icon className={`-mt-0.5 ${iconColor2}`} name="caret-down" size />
</div>
}
}
module HeaderActions = {
@react.component
let make = (
~order: sortOrder,
~actionOptions: array<SelectBox.dropdownOption>=[
{
label: "Sort Ascending",
value: "DEC",
icon: Euler("sortAscending"),
},
{
label: "Sort Descending",
value: "INC",
icon: Euler("sortDescending"),
},
],
~onChange,
~filterRow: option<filterRow>,
~isLastCol=false,
~filterKey: string,
) => {
let (toggleDropdownState, _) = React.useState(_ => false)
let getSortOrderToString = order =>
switch order {
| INC => "INC"
| DEC => "DEC"
| NONE => ""
}
let actionInput: ReactFinalForm.fieldRenderPropsInput = {
name: "heading",
onBlur: _ => (),
onChange,
onFocus: _ => (),
value: order->getSortOrderToString->JSON.Encode.string,
checked: true,
}
let customButton = switch filterRow {
| Some(obj) =>
<div className="flex relative flex-col w-full bg-white rounded-b-lg">
<div className="w-full h-[1px] bg-jp-2-light-gray-400 px-1" />
<TableFilterCell cell=obj />
</div>
| None => React.null
}
<SelectBox.BaseDropdown
allowMultiSelect=false
hideMultiSelectButtons=true
fixedDropDownDirection={isLastCol ? BottomLeft : BottomRight}
buttonText=""
input={actionInput}
options=actionOptions
baseComponentMethod={showDropDown => {
<BaseComponentMethod showDropDown filterKey />
}}
dropDownCustomBtnClick=toggleDropdownState
autoApply=true
showClearAll=false
showSelectAll=false
marginTop="mt-5.5"
customButton
showCustomBtnAtEnd=true
/>
}
}
| 7,017 | 10,056 |
hyperswitch-control-center | src/components/InlineEditInput.resi | .resi | module HoverInline: {
@react.component
let make: (
~customStyle: string=?,
~leftIcon: option<React.element>,
~value: string,
~subText: string,
~showEditIconOnHover: bool,
~leftActionButtons: React.element,
~labelTextCustomStyle: string,
~customWidth: string,
) => React.element
}
@react.component
let make: (
~index: int=?,
~labelText: string=?,
~subText: string=?,
~customStyle: string=?,
~showEditIconOnHover: bool=?,
~leftIcon: React.element=?,
~onSubmit: string => 'a=?,
~customIconComponent: React.element=?,
~customInputStyle: string=?,
~customIconStyle: string=?,
~showEditIcon: bool=?,
~handleEdit: option<int> => unit,
~isUnderEdit: bool=?,
~displayHoverOnEdit: bool=?,
~validateInput: 'b => RescriptCore.Dict.t<'c>,
~labelTextCustomStyle: string=?,
~customWidth: string=?,
~handleClick: unit => unit=?,
) => React.element
| 274 | 10,057 |
hyperswitch-control-center | src/components/PopUpConfirmUtils.res | .res | let containerBorderRadius = "rounded-xl"
let overlayStyle = "bg-grey-700 bg-opacity-70 backdrop-blur-sm"
let headerStyle = "text-2xl font-semibold"
let subHeaderStyle = "text-md font-medium leading-7 opacity-50 mt-2 w-full"
let modalWidth = "md:w-4/12 md:left-1/3"
let imageStyle = "w-12 h-12 my-auto border-gray-100"
let iconStyle = "align-middle fill-blue-600 self-center"
let getCloseIcon = onClick =>
<div className="-mt-3 -mr-1" onClick>
<Icon name="close" className="border-2 p-2 rounded-2xl bg-gray-100 cursor-pointer" size=30 />
</div>
| 181 | 10,058 |
hyperswitch-control-center | src/components/ShowDetails.res | .res | open LogicUtils
type loadDataType = Loading | Loaded(Dict.t<JSON.t>, Dict.t<JSON.t>) | LoadError(string)
type errorType = {
error: bool,
errorMessage: string,
userMessage: string,
}
module EntityData = {
@react.component
let make = (
~dictData: Dict.t<JSON.t>,
~syncData=Dict.make(),
~detailsKeyList,
~entity: EntityType.entityType<'colType, 't>,
) => {
<div className="flex flex-1 flex-col overflow-scroll pl-1 pr-2">
{detailsKeyList
->Array.mapWithIndex((key: string, idx) => {
switch Dict.get(syncData, key) {
| Some(json) => <div key={idx->Int.toString}> {entity.detailsPageLayout(json, key)} </div>
| _ =>
switch Dict.get(dictData, key) {
| Some(json) => <div key={idx->Int.toString}> {entity.detailsPageLayout(json, key)} </div>
| _ => React.null
}
}
})
->React.array}
</div>
}
}
module MerchantDetails = {
@react.component
let make = (~dictData, ~syncData, ~detailsKeyList, ~entity) => {
let merchantId = dictData->getString("merchantId", "-")
let parentMerchantId = dictData->getString("parentMerchantId", "-")
let (isExpanded, setIsExpanded) = React.useState(_ => true)
<div className="flex flex-col border border-jp-gray-500 mt-4 dark:border-jp-gray-960">
<div className="flex flex-col justify-between">
<div
className="flex flex-row justify-between p-4 font-bold border-4 border-jp-gray-500 from-gray-100 bg-gradient-to-b from-jp-gray-200 to-jp-gray-300 dark:from-jp-gray-950 dark:to-jp-gray-950 text-jp-gray-800 dark:text-jp-gray-text_darktheme dark:text-opacity-75 whitespace-pre">
<div className="justify-items-center font-bold text-2xl">
{React.string("Merchant Details")}
</div>
<div
className="flex flex-row cursor-pointer justify-items-center"
onClick={_ => setIsExpanded(prev => !prev)}>
<div className="mt-1">
<Icon name={isExpanded ? "compress-alt" : "expand-alt"} size=13 />
</div>
<div className="font-normal ml-1">
{React.string(isExpanded ? "Collapse" : "Expand")}
</div>
</div>
</div>
</div>
{if isExpanded {
<>
<div className="p-4 grid grid-cols-2">
<div className="flex flex-row justify-between">
<div>
<span> {React.string("Merchant ID :")} </span>
<span className="ml-2 font-bold"> {React.string(merchantId)} </span>
</div>
<div>
<span> {React.string("Parent Merchant ID :")} </span>
<span className="ml-2 font-bold"> {React.string(parentMerchantId)} </span>
</div>
</div>
</div>
<EntityData dictData syncData detailsKeyList entity />
</>
} else {
React.null
}}
</div>
}
}
| 772 | 10,059 |
hyperswitch-control-center | src/components/CustomizeTableColumns.res | .res | @react.component
let make = (
~allHeadersArray=[],
~visibleColumns=[],
~setColumns,
~getHeading: 'colType => Table.header,
~defaultColumns,
~showModal,
~setShowModal,
~isModalView=true,
~orderdColumnBasedOnDefaultCol: bool=false,
~sortingBasedOnDisabled=true,
~showSerialNumber=true,
) => {
let heading = allHeadersArray
let headingDict =
heading
->Array.mapWithIndex((item, index) => (
getHeading(item).title,
index->Int.toFloat->JSON.Encode.float,
))
->Dict.fromArray
let sortByOrderOderedArr = (a, b) => {
let positionInHeader = headingDict->LogicUtils.getInt(getHeading(a).title, 0)
let positionInHeading = headingDict->LogicUtils.getInt(getHeading(b).title, 0)
if positionInHeader < positionInHeading {
-1.
} else if positionInHeader > positionInHeading {
1.
} else {
0.
}
}
let defaultColumnsString = defaultColumns->Array.map(head => getHeading(head).title)
let initalHeadingData = heading->Array.map(head => {
let columnName = getHeading(head).title
let isDisabled = defaultColumnsString->Array.includes(columnName)
let options: SelectBox.dropdownOption = {
label: columnName,
value: columnName,
isDisabled,
}
options
})
let initialValues = visibleColumns->Array.map(head => getHeading(head).title)
let onSubmit = values => {
let getHeadingCol = text => {
let index = heading->Array.map(head => getHeading(head).title)->Array.indexOf(text)
heading[index]
}
let headers = values->Belt.Array.keepMap(getHeadingCol)
let headers = orderdColumnBasedOnDefaultCol
? headers->Array.copy->Array.toSorted(sortByOrderOderedArr)
: headers
setColumns(_ => headers)
}
<SelectModal
modalHeading="Table Columns"
showModal
setShowModal
onSubmit
initialValues
isModalView
options=initalHeadingData
sortingBasedOnDisabled
showSerialNumber
/>
}
| 502 | 10,060 |
hyperswitch-control-center | src/components/HSwitchFeedBackModalUtils.res | .res | type modalType = FeedBackModal | RequestConnectorModal
let makeFieldInfo = FormRenderer.makeFieldInfo
let feedbackTextBox = makeFieldInfo(
~label="",
~name="feedbacks",
~placeholder="Tell us in words...",
~customInput=InputFields.multiLineTextInput(~isDisabled=false, ~rows=Some(6), ~cols=Some(4)),
)
type feedbackType = Suggestion | Bugs | RequestConnector | Other
let feedbackTypeList = [Suggestion, Bugs, Other]
let getFeedBackStringFromVariant = feedbackType => {
switch feedbackType {
| Suggestion => "Suggestion"
| Bugs => "Bugs"
| RequestConnector => "Request A Connector"
| Other => "Other"
}
}
let selectFeedbackType = makeFieldInfo(
~name="category",
~label="",
~customInput=InputFields.radioInput(
~options=feedbackTypeList->Array.map(getFeedBackStringFromVariant)->SelectBox.makeOptions,
~buttonText="options",
~isHorizontal=false,
),
)
let connectorNameField = makeFieldInfo(
~label="Processor Name",
~name="connector_name",
~placeholder="Enter a processor name",
~customInput=InputFields.textInput(),
)
let connectorDescription = makeFieldInfo(
~label="Description",
~name="description",
~placeholder="Write here...",
~customInput=InputFields.multiLineTextInput(~isDisabled=false, ~rows=Some(6), ~cols=Some(4)),
)
let validateFields = (values, ~modalType) => {
open LogicUtils
let errors = Dict.make()
let values = values->getDictFromJsonObject
switch modalType {
| FeedBackModal => {
if values->getInt("rating", -1) === -1 {
errors->Dict.set("rating", "Please rate"->JSON.Encode.string)
}
if (
values->getString("category", "")->LogicUtils.isNonEmptyString &&
values->getString("feedbacks", "")->LogicUtils.isEmptyString
) {
errors->Dict.set("feedbacks", "Please give the feedback"->JSON.Encode.string)
}
}
| RequestConnectorModal =>
if values->getString("connector_name", "")->String.length <= 0 {
errors->Dict.set("connector_name", "Please enter a connector name"->JSON.Encode.string)
}
}
errors->JSON.Encode.object
}
| 530 | 10,061 |
hyperswitch-control-center | src/components/FilterSelectBox.res | .res | type retType = CheckBox(array<string>) | Radiobox(string)
external toDict: 'a => Dict.t<'t> = "%identity"
@send external getClientRects: Dom.element => Dom.domRect = "getClientRects"
@send external focus: Dom.element => unit = "focus"
external ffInputToSelectInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput<
array<string>,
> = "%identity"
external ffInputToRadioInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput<
string,
> = "%identity"
let regex = (a, searchString) => {
let searchStringNew =
searchString
->String.replaceRegExp(%re("/[<>\[\]';|?*\\]/g"), "")
->String.replaceRegExp(%re("/\(/g"), "\\(")
->String.replaceRegExp(%re("/\+/g"), "\\+")
->String.replaceRegExp(%re("/\)/g"), "\\)")
->String.replaceRegExp(%re("/\./g"), "")
RegExp.fromStringWithFlags("(.*)(" ++ a ++ "" ++ searchStringNew ++ ")(.*)", ~flags="i")
}
module ListItem = {
@react.component
let make = (
~isDropDown,
~searchString,
~multiSelect,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~isSelected,
~isPrevSelected=false,
~isNextSelected=false,
~onClick,
~text,
~fill="#0EB025",
~labelValue="",
~isDisabled=false,
~icon: Button.iconType,
~leftVacennt=false,
~showToggle=false,
~customStyle="",
~serialNumber=None,
~isMobileView=false,
~description=None,
~customLabelStyle=None,
~customMarginStyle="mx-3 py-2 gap-2",
~listFlexDirection="",
~customSelectStyle="",
~textOverflowClass=?,
~dataId,
~showDescriptionAsTool=true,
~optionClass="",
~selectClass="",
~toggleProps="",
~checkboxDimension="",
~iconStroke="",
~showToolTipOptions=false,
~textEllipsisForDropDownOptions=false,
~textColorClass="",
) => {
let {globalUIConfig: {font}} = React.useContext(ThemeProvider.themeContext)
let labelText = switch labelValue->String.length {
| 0 => text
| _ => labelValue
}
let (toggleSelect, setToggleSelect) = React.useState(() => isSelected)
let listText =
searchString->LogicUtils.isEmptyString
? [text]
: {
switch Js.String2.match_(text, regex("\\b", searchString)) {
| Some(r) => r->Array.sliceToEnd(~start=1)->Belt.Array.keepMap(x => x)
| None =>
switch Js.String2.match_(text, regex("_", searchString)) {
| Some(a) => a->Array.sliceToEnd(~start=1)->Belt.Array.keepMap(x => x)
| None => [text]
}
}
}
let bgClass = "md:bg-jp-gray-100 md:dark:bg-jp-gray-text_darktheme md:dark:bg-opacity-3 dark:hover:text-white dark:text-white"
let hoverClass = "hover:bg-jp-gray-100 dark:hover:bg-jp-gray-text_darktheme dark:hover:bg-opacity-10 dark:hover:text-white dark:text-white"
let customMarginStyle = if isMobileView {
"py-2 gap-2"
} else if !isDropDown {
"mr-3 py-2 gap-2"
} else {
customMarginStyle
}
let backgroundClass = if showToggle {
""
} else if isSelected && customStyle->LogicUtils.isNonEmptyString {
customSelectStyle
} else if isDropDown && isSelected && !isDisabled {
`${bgClass} transition ease-[cubic-bezier(0.33, 1, 0.68, 1)]`
} else {
hoverClass
}
let justifyClass = if isDropDown {
"justify-between"
} else {
""
}
let selectedClass = if isSelected {
"text-opacity-100 dark:text-opacity-100"
} else if isDisabled {
"text-opacity-50 dark:text-opacity-50"
} else {
"text-opacity-75 dark:text-opacity-75"
}
let leftElementClass = if leftVacennt {
"px-4 "
} else {
""
}
let labelStyle = customLabelStyle->Option.isSome ? customLabelStyle->Option.getOr("") : ""
let onToggleSelect = val => {
if !isDisabled {
setToggleSelect(_ => val)
}
}
React.useEffect(() => {
setToggleSelect(_ => isSelected)
None
}, [isSelected])
let cursorClass = if showToggle || !isDropDown {
""
} else if isDisabled {
"cursor-not-allowed"
} else {
"cursor-pointer"
}
let paddingClass = showToggle ? "pr-6 mr-4" : "pr-2"
let onClickTemp = if showToggle {
_ => ()
} else {
onClick
}
let parentRef = React.useRef(Nullable.null)
let textColor = "text-jp-2-gray-300"
let textColor = if textColorClass->LogicUtils.isNonEmptyString {
textColorClass
} else {
textColor
}
let itemRoundedClass = ""
let toggleClass = if showToggle {
""
} else if multiSelect {
"pr-2"
} else {
"pl-2"
}
let textGap = ""
let selectedNoBadgeColor = "bg-primary"
let optionIconStroke = ""
let optionTextSize = "text-fs-14"
let searchMatchTextColor = `dark:${font.textColor.primaryNormal} ${font.textColor.primaryNormal}`
let optionDescPadding = if optionSize === Small {
showToggle ? "pl-12" : "pl-7"
} else if showToggle {
"pl-15"
} else {
"pl-9"
}
let overFlowTextCustomClass = switch textOverflowClass {
| Some(val) => val
| None => "overflow-hidden"
}
let customCss =
listFlexDirection->LogicUtils.isEmptyString ? `flex-row ${paddingClass}` : listFlexDirection
RippleEffectBackground.useLinearRippleHook(parentRef, isDropDown)
let comp =
<AddDataAttributes
attributes=[
("data-dropdown-numeric", (dataId + 1)->Int.toString),
("data-dropdown-value", labelText),
("data-dropdown-value-selected", {isSelected} ? "True" : "False"),
]>
<div
ref={parentRef->ReactDOM.Ref.domRef}
onClick=onClickTemp
className={`flex relative mx-2 md:mx-0 my-3 md:my-0 pr-2 md:pr-0 md:w-full items-center font-medium ${overFlowTextCustomClass} ${itemRoundedClass} ${textColor} ${justifyClass} ${cursorClass} ${backgroundClass} ${selectedClass} ${customStyle} ${customCss} `}>
{if !isDropDown {
if showToggle {
<div className={toggleClass ++ toggleProps} onClick>
<BoolInput.BaseComponent
isSelected=toggleSelect size=optionSize setIsSelected=onToggleSelect isDisabled
/>
</div>
} else if multiSelect {
<span className=toggleClass>
{checkboxDimension->LogicUtils.isNonEmptyString
? <CheckBoxIcon
isSelected isDisabled size=optionSize isSelectedStateMinus checkboxDimension
/>
: <CheckBoxIcon isSelected isDisabled size=optionSize isSelectedStateMinus />}
</span>
} else {
<div className=toggleClass>
<RadioIcon isSelected size=optionSize fill isDisabled />
</div>
}
} else if multiSelect && !isMobileView {
<span className="pl-3">
<CheckBoxIcon isSelected isDisabled isSelectedStateMinus />
</span>
} else {
React.null
}}
<div
className={`flex flex-row group ${optionTextSize} w-full text-left items-center ${customMarginStyle} overflow-hidden`}>
<div
className={`${leftElementClass} ${textGap} flex w-full overflow-x-auto whitespace-pre ${labelStyle}`}>
{switch icon {
| FontAwesome(iconName) =>
<Icon
className={`align-middle ${iconStroke->LogicUtils.isEmptyString
? optionIconStroke
: iconStroke} `}
size={20}
name=iconName
/>
| CustomIcon(ele) => ele
| Euler(iconName) =>
<Icon className={`align-middle ${optionIconStroke}`} size={12} name=iconName />
| _ => React.null
}}
<div className="w-full">
{listText
->Array.filter(str => str->LogicUtils.isNonEmptyString)
->Array.mapWithIndex((item, i) => {
if (
(String.toLowerCase(item) == String.toLowerCase(searchString) ||
String.toLowerCase(item) == String.toLowerCase("_" ++ searchString)) &&
String.length(searchString) > 0
) {
<AddDataAttributes
key={i->Int.toString} attributes=[("data-searched-text", item)]>
<mark
key={i->Int.toString} className={`${searchMatchTextColor} bg-transparent`}>
{item->React.string}
</mark>
</AddDataAttributes>
} else {
let className = isSelected ? `${selectClass}` : `${optionClass}`
let textClass = if textEllipsisForDropDownOptions {
`${className} text-ellipsis overflow-hidden `
} else {
className
}
let selectOptions =
<AddDataAttributes
attributes=[("data-text", labelText)] key={i->Int.toString}>
<span key={i->Int.toString} className=textClass value=labelText>
{item->React.string}
</span>
</AddDataAttributes>
{
if showToolTipOptions {
<ToolTip
key={i->Int.toString}
description=item
toolTipFor=selectOptions
contentAlign=Default
justifyClass="justify-start"
/>
} else {
selectOptions
}
}
}
})
->React.array}
</div>
</div>
{switch icon {
| CustomRightIcon(ele) => ele
| _ => React.null
}}
</div>
{if isMobileView && isDropDown {
if multiSelect {
<CheckBoxIcon isSelected />
} else {
<RadioIcon isSelected isDisabled />
}
} else if isDropDown {
<div className="mr-2">
<Tick isSelected />
</div>
} else {
React.null
}}
{switch serialNumber {
| Some(sn) =>
<AddDataAttributes attributes=[("data-badge-value", sn)]>
<div
className={`mr-2 py-0.5 px-2 ${selectedNoBadgeColor} text-white font-semibold rounded-full`}>
{React.string(sn)}
</div>
</AddDataAttributes>
| None => React.null
}}
</div>
</AddDataAttributes>
<>
{switch description {
| Some(str) =>
if isDropDown {
showDescriptionAsTool
? {
<ToolTip
description={str}
toolTipFor=comp
contentAlign=Default
justifyClass="justify-start"
/>
}
: {
<div>
comp
<div> {React.string(str)} </div>
</div>
}
} else {
<>
comp
<div
className={`text-jp-2-light-gray-1100 font-normal -mt-2 ${optionDescPadding} ${optionTextSize}`}>
{str->React.string}
</div>
</>
}
| None => comp
}}
</>
}
}
type dropdownOptionWithoutOptional = {
label: string,
value: string,
isDisabled: bool,
icon: Button.iconType,
description: option<string>,
iconStroke: string,
textColor: string,
optGroup: string,
customRowClass: string,
}
type dropdownOption = {
label: string,
value: string,
optGroup?: string,
isDisabled?: bool,
icon?: Button.iconType,
description?: string,
iconStroke?: string,
textColor?: string,
customRowClass?: string,
}
let makeNonOptional = (dropdownOption: dropdownOption): dropdownOptionWithoutOptional => {
{
label: dropdownOption.label,
value: dropdownOption.value,
isDisabled: dropdownOption.isDisabled->Option.getOr(false),
icon: dropdownOption.icon->Option.getOr(NoIcon),
description: dropdownOption.description,
iconStroke: dropdownOption.iconStroke->Option.getOr(""),
textColor: dropdownOption.textColor->Option.getOr(""),
optGroup: dropdownOption.optGroup->Option.getOr("-"),
customRowClass: dropdownOption.customRowClass->Option.getOr(""),
}
}
let useTransformed = options => {
React.useMemo(() => {
options->Array.map(makeNonOptional)
}, [options])
}
type allSelectType = Icon | Text
type opt = {name_: string}
let makeOptions = (options: array<string>): array<dropdownOption> => {
options->Array.map(str => {label: str, value: str})
}
module BaseSelect = {
@react.component
let make = (
~showSelectAll=true,
~showDropDown=false,
~isDropDown=true,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~onSelect: array<string> => unit,
~value as values: JSON.t,
~onBlur=?,
~showClearAll=true,
~isHorizontal=false,
~customLabelStyle=?,
~showToggle=false,
~showSerialNumber=false,
~heading="Some heading",
~showSelectionAsChips=true,
~maxHeight="md:max-h-72",
~searchable=?,
~optionRigthElement=?,
~searchInputPlaceHolder="",
~showSearchIcon=true,
~customStyle="",
~customMargin="",
~disableSelect=false,
~deselectDisable=?,
~hideBorder=false,
~allSelectType=Icon,
~isMobileView=false,
~isModalView=false,
~customSearchStyle="bg-jp-gray-100 dark:bg-jp-gray-950 p-2",
~hasApplyButton=false,
~setShowDropDown=?,
~dropdownCustomWidth="w-full md:max-w-md min-w-[10rem]",
~sortingBasedOnDisabled=true,
~customMarginStyle="mx-3 py-2 gap-2",
~listFlexDirection="",
~onApply=?,
~showAllSelectedOptions=true,
~showDescriptionAsTool=true,
~optionClass="",
~selectClass="",
~toggleProps="",
~showSelectCountButton=false,
~customSelectAllStyle="",
~checkboxDimension="",
~dropdownClassName="",
~onItemSelect=(_, _) => (),
~wrapBasis="",
~preservedAppliedOptions=[],
) => {
let customSearchStyle = "bg-white p-2 border-b-2"
let {globalUIConfig: {font}} = React.useContext(ThemeProvider.themeContext)
let (searchString, setSearchString) = React.useState(() => "")
let maxHeight = if maxHeight->String.includes("72") {
"md:max-h-66.5"
} else {
maxHeight
}
let saneValue = React.useMemo(() =>
switch values->JSON.Decode.array {
| Some(jsonArr) => jsonArr->LogicUtils.getStrArrayFromJsonArray
| _ => []
}
, [values])
let initialSelectedOptions = React.useMemo(() => {
options->Array.filter(item => saneValue->Array.includes(item.value))
}, [])
options->Array.sort((item1, item2) => {
let item1Index = initialSelectedOptions->Array.findIndex(item => item.label === item1.label)
let item2Index = initialSelectedOptions->Array.findIndex(item => item.label === item2.label)
item1Index <= item2Index ? 1. : -1.
})
let transformedOptions = useTransformed(options)
let (filteredOptions, setFilteredOptions) = React.useState(() => transformedOptions)
React.useEffect(() => {
setFilteredOptions(_ => transformedOptions)
None
}, [transformedOptions])
React.useEffect(() => {
let shouldDisplay = (option: dropdownOption) => {
switch Js.String2.match_(option.label, regex("\\b", searchString)) {
| Some(_) => true
| None =>
switch Js.String2.match_(option.label, regex("_", searchString)) {
| Some(_) => true
| None => false
}
}
}
let filterOptions = options->Array.filter(shouldDisplay)->Array.map(makeNonOptional)
setFilteredOptions(_ => filterOptions)
None
}, [searchString])
let onItemClick = (itemDataValue, isDisabled) => e => {
if !isDisabled {
let data = if Array.includes(saneValue, itemDataValue) {
let values =
deselectDisable->Option.getOr(false)
? saneValue
: saneValue->Array.filter(x => x !== itemDataValue)
onItemSelect(e, itemDataValue)->ignore
values
} else {
Array.concat(saneValue, [itemDataValue])
}
onSelect(data)
switch onBlur {
| Some(fn) =>
"blur"->Webapi.Dom.FocusEvent.make->Identity.webAPIFocusEventToReactEventFocus->fn
| None => ()
}
}
}
let handleSearch = str => {
setSearchString(_ => str)
}
let selectAll = select => _ => {
let newValues = if select {
let newVal =
filteredOptions
->Array.filter(x => !x.isDisabled && !(saneValue->Array.includes(x.value)))
->Array.map(x => x.value)
Array.concat(saneValue, newVal)
} else {
[]
}
onSelect(newValues)
switch onBlur {
| Some(fn) =>
"blur"->Webapi.Dom.FocusEvent.make->Identity.webAPIFocusEventToReactEventFocus->fn
| None => ()
}
}
let borderClass = if !hideBorder {
if isDropDown {
`bg-white border dark:bg-jp-gray-lightgray_background border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960
rounded-lg rounded-b-none animate-textTransition transition duration-400`
} else if showToggle {
"bg-white border rounded rounded-b-none dark:bg-jp-gray-darkgray_background border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960"
} else {
""
}
} else {
""
}
let minWidth = isDropDown ? "min-w-65" : ""
let widthClass = if showToggle {
""
} else if isMobileView {
"w-full"
} else {
`${minWidth} ${dropdownCustomWidth}`
}
let textIconPresent = options->Array.some(op => op.icon->Option.getOr(NoIcon) !== NoIcon)
let _ = if sortingBasedOnDisabled {
options->Array.toSorted((m1, m2) => {
let m1Disabled = m1.isDisabled->Option.getOr(false)
let m2Disabled = m2.isDisabled->Option.getOr(false)
if m1Disabled === m2Disabled {
0.
} else if m1Disabled {
1.
} else {
-1.
}
})
} else {
options
}
let noOfSelected = saneValue->Array.length
let applyBtnDisabled =
noOfSelected === preservedAppliedOptions->Array.length &&
saneValue->Array.reduce(true, (acc, val) => {
preservedAppliedOptions->Array.includes(val) && acc
})
let searchRef = React.useRef(Nullable.null)
let (isChooseAllToggleSelected, setChooseAllToggleSelected) = React.useState(() => false)
let gapClass = switch optionRigthElement {
| Some(_) => "flex gap-4"
| None => ""
}
let form = ReactFinalForm.useForm()
let onClick = ev => {
form.submit()->ignore
switch setShowDropDown {
| Some(fn) => fn(_ => false)
| None => ()
}
switch onApply {
| Some(fn) => fn(ev)
| None => ()
}
}
React.useEffect(() => {
searchRef.current->Nullable.toOption->Option.forEach(input => input->focus)
None
}, (searchRef.current, showDropDown))
let listPadding = ""
React.useEffect(() => {
if noOfSelected === options->Array.length {
setChooseAllToggleSelected(_ => true)
} else {
setChooseAllToggleSelected(_ => false)
}
None
}, (noOfSelected, options))
let toggleSelectAll = val => {
if !disableSelect {
selectAll(val)("")
setChooseAllToggleSelected(_ => val)
}
}
let disabledClass = disableSelect ? "cursor-not-allowed" : ""
let marginClass = if customMargin->LogicUtils.isEmptyString {
"mt-4"
} else {
customMargin
}
let dropdownAnimation = showDropDown
? "animate-textTransition transition duration-400"
: "animate-textTransitionOff transition duration-400"
let searchInputUI =
<div className={`${customSearchStyle} pb-0`}>
<div className="pb-2 z-50">
<SearchInput
inputText=searchString
searchRef
onChange=handleSearch
placeholder={searchInputPlaceHolder->LogicUtils.isEmptyString
? "Search..."
: searchInputPlaceHolder}
showSearchIcon
/>
</div>
</div>
let animationClass = isModalView ? `` : dropdownAnimation
let outerClass = if isModalView {
"h-full"
} else if isDropDown {
"overflow-auto"
} else {
""
}
<div>
<div
id="neglectTopbarTheme"
className={`${widthClass} ${outerClass} ${borderClass} ${animationClass} ${dropdownClassName} max-h-80`}>
{switch searchable {
| Some(val) =>
if val {
searchInputUI
} else {
React.null
}
| None =>
if isDropDown && options->Array.length > 5 {
searchInputUI
} else {
React.null
}
}}
{if showSelectAll && isDropDown {
if !isMobileView {
let clearAllCondition = noOfSelected > 0
<RenderIf
condition={filteredOptions->Array.length > 1 &&
filteredOptions->Array.find(item => item.value === "Loading...")->Option.isNone}>
<div
onClick={selectAll(noOfSelected === 0)}
className={`flex px-3 py-2 border-b-2 gap-3 text-jp-2-gray-300 items-center text-fs-14 font-medium cursor-pointer`}>
<CheckBoxIcon
isSelected={noOfSelected !== 0}
size=optionSize
isSelectedStateMinus=clearAllCondition
/>
{{clearAllCondition ? "Clear All" : "Select All"}->React.string}
</div>
</RenderIf>
} else {
<div
onClick={selectAll(noOfSelected !== options->Array.length)}
className={`flex ${isHorizontal
? "flex-col"
: "flex-row"} justify-between pr-4 pl-5 pt-6 pb-1 text-base font-semibold ${font.textColor.primaryNormal} cursor-pointer`}>
{"SELECT ALL"->React.string}
<CheckBoxIcon isSelected={noOfSelected === options->Array.length} />
</div>
}
} else {
React.null
}}
{if showToggle {
<div>
<div className={`grid grid-cols-2 items-center ${marginClass}`}>
<div
className="ml-5 font-bold text-fs-16 text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{React.string(heading)}
</div>
{if showSelectAll {
<div className="flex mr-5 justify-end">
{switch allSelectType {
| Icon =>
<BoolInput.BaseComponent
isSelected=isChooseAllToggleSelected
setIsSelected=toggleSelectAll
isDisabled=disableSelect
size=optionSize
/>
| Text =>
<AddDataAttributes
attributes=[
(
"data-select-box",
{isChooseAllToggleSelected ? "deselectAll" : "selectAll"},
),
]>
<div
className={`font-semibold ${font.textColor.primaryNormal} ${disabledClass} ${customSelectAllStyle}`}
onClick={_ => {
toggleSelectAll(!isChooseAllToggleSelected)
}}>
{if isChooseAllToggleSelected {
"Deselect All"->React.string
} else {
"Select All"->React.string
}}
</div>
</AddDataAttributes>
}}
</div>
} else {
React.null
}}
</div>
{if !hideBorder {
<div
className="my-2 bg-jp-gray-lightmode_steelgray dark:bg-jp-gray-960 "
style={height: "1px"}
/>
} else {
React.null
}}
</div>
} else {
React.null
}}
<div
className={`overflow-auto ${listPadding} ${isHorizontal
? "flex flex-row grow"
: ""} ${showToggle ? "ml-3" : maxHeight}` ++ {
wrapBasis->LogicUtils.isEmptyString ? "" : " flex flex-wrap justify-between"
}}>
{if filteredOptions->Array.length === 0 {
<div className="flex justify-center items-center m-4">
{React.string("No matching records found")}
</div>
} else if (
filteredOptions->Array.find(item => item.value === "Loading...")->Option.isSome
) {
<Loader />
} else {
{
filteredOptions
->Array.mapWithIndex((item, indx) => {
let valueToConsider = item.value
let index = Array.findIndex(saneValue, sv => sv === valueToConsider)
let isPrevSelected = switch filteredOptions->Array.get(indx - 1) {
| Some(prevItem) => Array.findIndex(saneValue, sv => sv === prevItem.value) > -1
| None => false
}
let isNextSelected = switch filteredOptions->Array.get(indx + 1) {
| Some(nextItem) => Array.findIndex(saneValue, sv => sv === nextItem.value) > -1
| None => false
}
let isSelected = index > -1
let serialNumber =
isSelected && showSerialNumber ? Some(Int.toString(index + 1)) : None
let leftVacennt = isDropDown && textIconPresent && item.icon === NoIcon
<div className={`${gapClass} ${wrapBasis}`} key={item.value}>
<ListItem
isDropDown
isSelected
optionSize
isSelectedStateMinus
isPrevSelected
isNextSelected
searchString
onClick={onItemClick(valueToConsider, item.isDisabled || disableSelect)}
text=item.label
labelValue=item.label
multiSelect=true
customLabelStyle
icon=item.icon
leftVacennt
isDisabled={item.isDisabled || disableSelect}
showToggle
customStyle
serialNumber
isMobileView
description=item.description
customMarginStyle
listFlexDirection
dataId=indx
showDescriptionAsTool
optionClass
selectClass
toggleProps
checkboxDimension
iconStroke=item.iconStroke
/>
{switch optionRigthElement {
| Some(rightElement) => rightElement
| None => React.null
}}
</div>
})
->React.array
}
}}
</div>
<button type_="submit" className="hidden" />
</div>
<Button
buttonType=Primary
text="Apply"
flattenTop=false
customButtonStyle="w-full items-center sticky bottom-0 !rounded-none"
buttonState={applyBtnDisabled ? Disabled : Normal}
onClick
/>
</div>
}
}
module BaseSelectButton = {
@react.component
let make = (
~showDropDown=false,
~isDropDown=true,
~isHorizontal=false,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~onSelect: string => unit,
~value: JSON.t,
~deselectDisable=false,
~onBlur=?,
~setShowDropDown=?,
~onAssignClick=?,
~customSearchStyle,
~disableSelect=false,
~isMobileView=false,
~hideAssignBtn=false,
~searchInputPlaceHolder="",
~showSearchIcon=true,
~allowButtonTextMinWidth=?,
) => {
let options = useTransformed(options)
let (searchString, setSearchString) = React.useState(() => "")
let (itemdata, setItemData) = React.useState(() => "")
let (assignButtonState, setAssignButtonState) = React.useState(_ => false)
let searchRef = React.useRef(Nullable.null)
let onItemClick = itemData => _ => {
if !disableSelect {
let isSelected = value->JSON.Decode.string->Option.mapOr(false, str => itemData === str)
if isSelected && !deselectDisable {
onSelect("")
} else {
setItemData(_ => itemData)
onSelect(itemData)
}
setAssignButtonState(_ => true)
switch onBlur {
| Some(fn) =>
"blur"->Webapi.Dom.FocusEvent.make->Identity.webAPIFocusEventToReactEventFocus->fn
| None => ()
}
}
}
React.useEffect(() => {
searchRef.current->Nullable.toOption->Option.forEach(input => input->focus)
None
}, (searchRef.current, showDropDown))
let handleSearch = str => {
setSearchString(_ => str)
}
let searchable = isDropDown && options->Array.length > 5
let width = isHorizontal ? "w-auto" : "w-full md:w-72"
let inlineClass = isHorizontal ? "inline-flex" : ""
let textIconPresent = options->Array.some(op => op.icon !== NoIcon)
let onButtonClick = itemdata => {
switch onAssignClick {
| Some(fn) => fn(itemdata)
| None => ()
}
switch setShowDropDown {
| Some(fn) => fn(_ => false)
| None => ()
}
}
let listPadding = ""
let optionsOuterClass = !isDropDown ? "" : "md:max-h-72 overflow-auto"
let overflowClass = !isDropDown ? "" : "overflow-auto"
<div
className={`bg-white dark:bg-jp-gray-lightgray_background ${width} ${overflowClass} font-medium flex flex-col ${showDropDown
? "animate-textTransition transition duration-400"
: "animate-textTransitionOff transition duration-400"}`}>
{if searchable {
<div
className={`${customSearchStyle} border-b border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 `}>
<div className="pb-2">
<SearchInput
inputText=searchString
onChange=handleSearch
searchRef
placeholder={searchInputPlaceHolder->LogicUtils.isEmptyString
? "Search..."
: searchInputPlaceHolder}
showSearchIcon
/>
</div>
</div>
} else {
React.null
}}
<div className={`${optionsOuterClass} ${listPadding} ${inlineClass}`}>
{options
->Array.mapWithIndex((option, i) => {
let isSelected = switch value->JSON.Decode.string {
| Some(str) => option.value === str
| None => false
}
let shouldDisplay = {
switch Js.String2.match_(option.label, regex("\\b", searchString)) {
| Some(_) => true
| None =>
switch Js.String2.match_(option.label, regex("_", searchString)) {
| Some(_) => true
| None => false
}
}
}
let leftVacennt = isDropDown && textIconPresent && option.icon === NoIcon
if shouldDisplay {
<ListItem
key={Int.toString(i)}
isDropDown
isSelected
optionSize
isSelectedStateMinus
searchString
onClick={onItemClick(option.value)}
text=option.label
labelValue=option.label
multiSelect=false
icon=option.icon
leftVacennt
isMobileView
dataId=i
iconStroke=option.iconStroke
/>
} else {
React.null
}
})
->React.array}
</div>
{if !hideAssignBtn {
<div id="neglectTopbarTheme" className="px-3 py-3">
<Button
text="Assign"
buttonType=Primary
buttonSize=Small
isSelectBoxButton=isDropDown
buttonState={assignButtonState ? Normal : Disabled}
onClick={_ => onButtonClick(itemdata)}
?allowButtonTextMinWidth
/>
</div>
} else {
React.null
}}
</div>
}
}
module RenderListItemInBaseRadio = {
@react.component
let make = (
~newOptions: array<dropdownOptionWithoutOptional>,
~value,
~descriptionOnHover,
~isDropDown,
~textIconPresent,
~searchString,
~optionSize,
~isSelectedStateMinus,
~onItemClick,
~fill,
~customStyle,
~isMobileView,
~listFlexDirection,
~customSelectStyle,
~textOverflowClass,
~showToolTipOptions,
~textEllipsisForDropDownOptions,
~isHorizontal,
~customMarginStyleOfListItem="mx-3 py-2 gap-2",
) => {
newOptions
->Array.mapWithIndex((option, i) => {
let isSelected = switch value->JSON.Decode.string {
| Some(str) => option.value === str
| None => false
}
let description = descriptionOnHover ? option.description : None
let leftVacennt = isDropDown && textIconPresent && option.icon === NoIcon
let listItemComponent =
<ListItem
key={Int.toString(i)}
isDropDown
isSelected
fill
searchString
onClick={onItemClick(option.value, option.isDisabled)}
text=option.label
optionSize
isSelectedStateMinus
labelValue=option.label
multiSelect=false
icon=option.icon
leftVacennt
isDisabled=option.isDisabled
isMobileView
description
listFlexDirection
customStyle
customSelectStyle
?textOverflowClass
dataId=i
iconStroke=option.iconStroke
showToolTipOptions
textEllipsisForDropDownOptions
textColorClass={option.textColor}
customMarginStyle=customMarginStyleOfListItem
/>
if !descriptionOnHover {
switch option.description {
| Some(str) =>
<div key={i->Int.toString} className="flex flex-row">
listItemComponent
<RenderIf condition={!isHorizontal}>
<ToolTip
description={str}
toolTipFor={<div className="py-4 px-4">
<Icon size=12 name="info-circle" />
</div>}
/>
</RenderIf>
</div>
| None => listItemComponent
}
} else {
listItemComponent
}
})
->React.array
}
}
let getHashMappedOptionValues = (options: array<dropdownOptionWithoutOptional>) => {
let hashMappedOptions = options->Array.reduce(Dict.make(), (
acc,
ele: dropdownOptionWithoutOptional,
) => {
if acc->Dict.get(ele.optGroup)->Option.isNone {
acc->Dict.set(ele.optGroup, [ele])
} else {
acc->Dict.get(ele.optGroup)->Option.getOr([])->Array.push(ele)->ignore
}
acc
})
hashMappedOptions
}
let getSortedKeys = hashMappedOptions => {
hashMappedOptions
->Dict.keysToArray
->Array.toSorted((a, b) => {
switch (a, b) {
| ("-", _) => 1.
| (_, "-") => -1.
| (_, _) => String.compare(a, b)
}
})
}
module BaseRadio = {
@react.component
let make = (
~showDropDown=false,
~isDropDown=true,
~isHorizontal=false,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~onSelect: string => unit,
~value: JSON.t,
~deselectDisable=false,
~onBlur=?,
~fill="#0EB025",
~customStyle="",
~searchable=?,
~isMobileView=false,
~customSearchStyle="bg-jp-gray-100 dark:bg-jp-gray-950 p-2",
~descriptionOnHover=false,
~addDynamicValue=false,
~dropdownCustomWidth="w-80",
~dropdownRef=?,
~showMatchingRecordsText=true,
~fullLength=false,
~selectedString="",
~setSelectedString=_ => (),
~setExtSearchString=_ => (),
~listFlexDirection="",
~baseComponentCustomStyle="",
~customSelectStyle="",
~maxHeight="md:max-h-72",
~textOverflowClass=?,
~searchInputPlaceHolder="",
~showSearchIcon=true,
~showToolTipOptions=false,
~textEllipsisForDropDownOptions=false,
) => {
let options = React.useMemo(() => {
options->Array.map(makeNonOptional)
}, [options])
let hashMappedOptions = getHashMappedOptionValues(options)
let isNonGrouped =
hashMappedOptions->Dict.get("-")->Option.getOr([])->Array.length === options->Array.length
let (optgroupKeys, setOptgroupKeys) = React.useState(_ => getSortedKeys(hashMappedOptions))
let (searchString, setSearchString) = React.useState(() => "")
React.useEffect(() => {
setExtSearchString(_ => searchString)
None
}, [searchString])
OutsideClick.useOutsideClick(
~refs={ArrayOfRef([dropdownRef->Option.getOr(React.useRef(Nullable.null))])},
~isActive=showDropDown,
~callback=() => {
setSearchString(_ => "")
},
)
let form = ReactFinalForm.useForm()
let onItemClick = (itemData, isDisabled) => _ => {
if !isDisabled {
let isSelected = value->JSON.Decode.string->Option.mapOr(false, str => itemData === str)
if isSelected && !deselectDisable {
setSelectedString(_ => "")
onSelect("")
} else {
if (
addDynamicValue && !(options->Array.map(item => item.value)->Array.includes(itemData))
) {
setSelectedString(_ => itemData)
} else if selectedString->LogicUtils.isNonEmptyString {
setSelectedString(_ => "")
}
onSelect(itemData)
}
setSearchString(_ => "")
switch onBlur {
| Some(fn) =>
"blur"->Webapi.Dom.FocusEvent.make->Identity.webAPIFocusEventToReactEventFocus->fn
| None => ()
}
}
form.submit()->ignore
}
let handleSearch = str => {
setSearchString(_ => str)
}
let isSearchable =
isDropDown &&
switch searchable {
| Some(isSearch) => isSearch
| None => options->Array.length > 5
}
let widthClass =
isMobileView || !isSearchable ? "w-auto" : fullLength ? "w-full" : dropdownCustomWidth
let searchRef = React.useRef(Nullable.null)
let width =
isHorizontal || !isDropDown || customStyle->LogicUtils.isEmptyString
? widthClass
: customStyle
let inlineClass = isHorizontal ? "inline-flex" : ""
let textIconPresent = options->Array.some(op => op.icon !== NoIcon)
React.useEffect(() => {
searchRef.current->Nullable.toOption->Option.forEach(input => input->focus)
None
}, (searchRef.current, showDropDown))
let roundedClass = ""
let listPadding = ""
let dropDownbgClass = isDropDown ? "bg-white" : ""
let shouldDisplay = (option: dropdownOptionWithoutOptional) => {
switch Js.String2.match_(option.label, regex("\\b", searchString)) {
| Some(_) => true
| None =>
switch Js.String2.match_(option.label, regex("_", searchString)) {
| Some(_) => true
| None => false
}
}
}
let newOptions = React.useMemo(() => {
let options = if selectedString->LogicUtils.isNonEmptyString {
options->Array.concat([selectedString]->makeOptions->Array.map(makeNonOptional))
} else {
options
}
if searchString->String.length != 0 {
let options = options->Array.filter(option => {
shouldDisplay(option)
})
if (
addDynamicValue && !(options->Array.map(item => item.value)->Array.includes(searchString))
) {
if isNonGrouped {
options->Array.concat([searchString]->makeOptions->Array.map(makeNonOptional))
} else {
options
}
} else {
let hashMappedSearchedOptions = getHashMappedOptionValues(options)
let optgroupKeysForSearch = getSortedKeys(hashMappedSearchedOptions)
setOptgroupKeys(_ => optgroupKeysForSearch)
options
}
} else {
setOptgroupKeys(_ => getSortedKeys(hashMappedOptions))
options
}
}, (searchString, options, selectedString))
let overflowClass = !isDropDown ? "" : "overflow-auto"
let searchInputUI =
<div
className={`${customSearchStyle} border-b border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 `}>
<div>
<SearchInput
inputText=searchString
onChange=handleSearch
searchRef
placeholder={searchInputPlaceHolder->LogicUtils.isEmptyString
? "Search..."
: searchInputPlaceHolder}
showSearchIcon
/>
</div>
</div>
<div
className={`${dropDownbgClass} ${roundedClass} dark:bg-jp-gray-lightgray_background ${width} ${overflowClass} font-medium flex flex-col ${showDropDown
? "animate-textTransition transition duration-400"
: "animate-textTransitionOff transition duration-400"}`}>
{switch searchable {
| Some(val) => <RenderIf condition={val}> searchInputUI </RenderIf>
| None =>
<RenderIf condition={isDropDown && (options->Array.length > 5 || addDynamicValue)}>
searchInputUI
</RenderIf>
}}
<div
className={`${maxHeight} ${listPadding} ${overflowClass} text-jp-2-gray-300 text-fs-14 font-medium"
${inlineClass} ${baseComponentCustomStyle}`}>
{if newOptions->Array.length === 0 && showMatchingRecordsText {
<div className="flex justify-center items-center m-4">
{React.string("No matching records found")}
</div>
} else if isNonGrouped {
<RenderListItemInBaseRadio
newOptions
value
descriptionOnHover
isDropDown
textIconPresent
searchString
optionSize
isSelectedStateMinus
onItemClick
fill
customStyle
isMobileView
listFlexDirection
customSelectStyle
textOverflowClass
showToolTipOptions
textEllipsisForDropDownOptions
isHorizontal
/>
} else {
{
optgroupKeys
->Array.mapWithIndex((ele, index) => {
<React.Fragment key={index->Int.toString}>
<h2 className="p-3 font-bold"> {ele->React.string} </h2>
<RenderListItemInBaseRadio
newOptions={getHashMappedOptionValues(newOptions)
->Dict.get(ele)
->Option.getOr([])}
value
descriptionOnHover
isDropDown
textIconPresent
searchString
optionSize
isSelectedStateMinus
onItemClick
fill
customStyle
isMobileView
listFlexDirection
customSelectStyle
textOverflowClass
showToolTipOptions
textEllipsisForDropDownOptions
isHorizontal
customMarginStyleOfListItem="ml-8 mx-3 py-2 gap-2"
/>
</React.Fragment>
})
->React.array
}
}}
</div>
</div>
}
}
module InfraSelectBox = {
@react.component
let make = (
~options: array<dropdownOption>,
~input: ReactFinalForm.fieldRenderPropsInput,
~deselectDisable=false,
~allowMultiSelect=true,
~borderRadius="rounded-full",
~selectedClass="border-jp-gray-600 dark:border-jp-gray-800 text-jp-gray-850 dark:text-jp-gray-400",
~nonSelectedClass="border-jp-gray-900 dark:border-jp-gray-300 text-jp-gray-900 dark:text-jp-gray-300 font-semibold",
~showTickMark=true,
) => {
let transformedOptions = useTransformed(options)
let newInputSelect = input->ffInputToSelectInput
let values = newInputSelect.value
let saneValue = React.useMemo(() =>
switch values->JSON.Decode.array {
| Some(jsonArr) => jsonArr->LogicUtils.getStrArrayFromJsonArray
| _ => []
}
, [values])
let onItemClick = (itemDataValue, isDisabled) => {
if !isDisabled {
if allowMultiSelect {
let data = if Array.includes(saneValue, itemDataValue) {
if deselectDisable {
saneValue
} else {
saneValue->Array.filter(x => x !== itemDataValue)
}
} else {
Array.concat(saneValue, [itemDataValue])
}
newInputSelect.onChange(data)
} else {
newInputSelect.onChange([itemDataValue])
}
}
}
<div className={`md:max-h-72 overflow-auto font-medium flex flex-wrap gap-y-4 gap-x-2.5`}>
{transformedOptions
->Array.mapWithIndex((option, i) => {
let isSelected = saneValue->Array.includes(option.value)
let selectedClass = isSelected ? selectedClass : nonSelectedClass
<div
key={Int.toString(i)}
onClick={_ => onItemClick(option.value, option.isDisabled)}
className={`px-4 py-1 border ${borderRadius} flex flex-row gap-2 items-center cursor-pointer ${selectedClass}`}>
{if isSelected && showTickMark {
<Icon
className="align-middle font-thin text-jp-gray-900 dark:text-jp-gray-300"
size=12
name="check"
/>
} else {
React.null
}}
{React.string(option.label)}
</div>
})
->React.array}
</div>
}
}
type direction =
| BottomLeft
| BottomMiddle
| BottomRight
| TopLeft
| TopMiddle
| TopRight
module BaseDropdown = {
@react.component
let make = (
~buttonText,
~buttonSize=Button.Small,
~allowMultiSelect,
~input,
~showClearAll=true,
~showSelectAll=true,
~options: array<dropdownOption>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~hideMultiSelectButtons,
~deselectDisable=?,
~buttonType=Button.SecondaryFilled,
~baseComponent=?,
~baseComponentMethod=?,
~disableSelect=false,
~textStyle=?,
~buttonTextWeight=?,
~defaultLeftIcon: Button.iconType=NoIcon,
~autoApply=true,
~fullLength=false,
~customButtonStyle="",
~onAssignClick=?,
~fixedDropDownDirection=?,
~addButton=false,
~marginTop="mt-12", //to position dropdown below the button,
~customStyle="",
~customSearchStyle="bg-jp-gray-100 dark:bg-jp-gray-950 p-2",
~showSelectionAsChips=true,
~showToolTip=false,
~showNameAsToolTip=false,
~searchable=?,
~showBorder=?,
~dropDownCustomBtnClick=false,
~showCustomBtnAtEnd=false,
~customButton=React.null,
~descriptionOnHover=false,
~addDynamicValue=false,
~showMatchingRecordsText=true,
~hasApplyButton=false,
~dropdownCustomWidth=?,
~customMarginStyle=?,
~customButtonLeftIcon: option<Button.iconType>=?,
~customTextPaddingClass=?,
~customButtonPaddingClass=?,
~customButtonIconMargin=?,
~buttonStyleOnDropDownOpened="",
~selectedString="",
~setSelectedString=_ => (),
~setExtSearchString=_ => (),
~listFlexDirection="",
~ellipsisOnly=false,
~isPhoneDropdown=false,
~onApply=?,
~showAllSelectedOptions=true,
~buttonClickFn=?,
~showSelectCountButton=false,
~maxHeight=?,
~customBackColor=?,
~showToolTipOptions=false,
~textEllipsisForDropDownOptions=false,
~showBtnTextToolTip=false,
~dropdownClassName="",
~searchInputPlaceHolder="",
~showSearchIcon=true,
~sortingBasedOnDisabled=?,
) => {
let transformedOptions = useTransformed(options)
let isMobileView = MatchMedia.useMobileChecker()
let isSelectTextDark = React.useContext(
DropdownTextWeighContextWrapper.selectedTextWeightContext,
)
let isFilterSection = React.useContext(TableFilterSectionContext.filterSectionContext)
let {removeKeys, filterKeys, setfilterKeys, filterValueJson} = React.useContext(
FilterContext.filterContext,
)
let showBorder = isFilterSection && !isMobileView ? Some(false) : showBorder
let dropdownOuterClass = "bg-white dark:bg-jp-gray-950 rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
let newInputSelect = input->ffInputToSelectInput
let newInputRadio = input->ffInputToRadioInput
let isMobileView = MatchMedia.useMobileChecker()
let (showDropDown, setShowDropDown) = React.useState(() => false)
let (isGrowDown, setIsGrowDown) = React.useState(_ => false)
let (isInitialRender, setIsInitialRender) = React.useState(_ => true)
let selectBoxRef = React.useRef(Nullable.null)
let dropdownRef = React.useRef(Nullable.null)
let selectBtnRef = React.useRef(Nullable.null)
let (preservedAppliedOptions, setPreservedAppliedOptions) = React.useState(_ =>
newInputSelect.value->LogicUtils.getStrArryFromJson
)
// this useEffect enables communication between transaction view changes and the filter dropdown options via filterValueJson
React.useEffect(() => {
open LogicUtils
let nonStatusFilters =
filterValueJson
->Dict.keysToArray
->Array.filter(item => item != "start_time" && item != "end_time" && item != "status")
if nonStatusFilters->Array.length == 0 {
setPreservedAppliedOptions(_ =>
filterValueJson
->getArrayFromDict("status", [])
->getStrArrayFromJsonArray
)
}
None
}, [filterValueJson])
let onApply = ev => {
switch onApply {
| Some(fn) => fn(ev)
| None => ()
}
setPreservedAppliedOptions(_ => newInputSelect.value->LogicUtils.getStrArryFromJson)
}
let clearBtnRef = React.useRef(Nullable.null)
React.useEffect(() => {
setShowDropDown(_ => false)
None
}, [dropDownCustomBtnClick])
let refs = autoApply
? [selectBoxRef, dropdownRef]
: [selectBoxRef, dropdownRef, selectBtnRef, clearBtnRef]
OutsideClick.useOutsideClick(~refs=ArrayOfRef(refs), ~isActive=showDropDown, ~callback=() => {
setShowDropDown(_ => false)
hasApplyButton ? newInputSelect.onChange(preservedAppliedOptions) : ()
})
let onClick = _ => {
switch buttonClickFn {
| Some(fn) => fn(input.name)
| None => ()
}
setShowDropDown(_ => !showDropDown)
setIsGrowDown(_ => true)
let _id = setTimeout(() => setIsGrowDown(_ => false), 250)
if isInitialRender {
setIsInitialRender(_ => false)
}
}
let removeOption = text => _ => {
let actualValue = switch Array.find(transformedOptions, option => option.value == text) {
| Some(str) => str.value
| None => ""
}
newInputSelect.onChange(
switch newInputSelect.value->JSON.Decode.array {
| Some(jsonArr) =>
jsonArr->LogicUtils.getStrArrayFromJsonArray->Array.filter(str => str !== actualValue)
| _ => []
},
)
}
let downArrowIcon = "angle-down-outline"
let arrowIconSize = 24
let dropDowntext = allowMultiSelect
? buttonText
: switch newInputRadio.value->JSON.Decode.string {
| Some(str) =>
switch transformedOptions->Array.find(x => x.value === str) {
| Some(x) => x.label
| None => buttonText
}
| None => buttonText
}
let dropDirection = React.useMemo(() => {
switch fixedDropDownDirection {
| Some(dropDownDirection) => dropDownDirection
| None =>
selectBoxRef.current
->Nullable.toOption
->Option.flatMap(elem => elem->getClientRects->toDict->Dict.get("0"))
->Option.flatMap(firstEl => {
let bottomVacent = Window.innerHeight - firstEl["bottom"]->Float.toInt > 375
let topVacent = firstEl["top"]->Float.toInt > 470
let rightVacent = Window.innerWidth - firstEl["left"]->Float.toInt > 270
let leftVacent = firstEl["right"]->Float.toInt > 270
if bottomVacent {
rightVacent ? BottomRight : leftVacent ? BottomLeft : BottomMiddle
} else if topVacent {
rightVacent ? TopRight : leftVacent ? TopLeft : TopMiddle
} else if rightVacent {
BottomRight
} else if leftVacent {
BottomLeft
} else {
BottomMiddle
}->Some
})
->Option.getOr(BottomMiddle)
}
}, [showDropDown])
let flexWrapper = switch dropDirection {
| BottomLeft => "flex-row-reverse flex-wrap"
| BottomRight => "flex-row flex-wrap"
| BottomMiddle => "flex-row flex-wrap justify-center"
| TopLeft => "flex-row-reverse flex-wrap-reverse"
| TopRight => "flex-row flex-wrap-reverse"
| TopMiddle => "flex-row flex-wrap-reverse justify-center"
}
let marginBottom = switch dropDirection {
| BottomLeft | BottomRight | BottomMiddle | TopMiddle => ""
| TopLeft | TopRight => "mb-12"
}
let onRadioOptionSelect = ev => {
newInputRadio.onChange(ev)
addButton ? setShowDropDown(_ => true) : setShowDropDown(_ => false)
}
let allSellectedOptions = React.useMemo(() => {
newInputSelect.value
->JSON.Decode.array
->Option.getOr([])
->Belt.Array.keepMap(JSON.Decode.string)
->Belt.Array.keepMap(str => {
transformedOptions->Array.find(x => x.value == str)->Option.map(x => x.label)
})
->Array.joinWith(", ")
->LogicUtils.getNonEmptyString
->Option.getOr(buttonText)
}, (transformedOptions, newInputSelect.value))
let title = showAllSelectedOptions ? allSellectedOptions : dropDowntext
let badgeForSelect = React.useMemo((): Button.badge => {
let count = newInputSelect.value->JSON.Decode.array->Option.getOr([])->Array.length
let condition = count > 1
{
value: count->Int.toString,
color: condition ? BadgeBlue : NoBadge,
}
}, [newInputSelect.value])
let widthClass = isMobileView ? "w-full" : dropdownCustomWidth->Option.getOr("")
let optionsElement = if allowMultiSelect {
<BaseSelect
options
optionSize
showDropDown
onSelect=newInputSelect.onChange
value={newInputSelect.value}
isDropDown=true
showClearAll
onBlur=newInputSelect.onBlur
showSelectAll
showSelectionAsChips
?searchable
disableSelect
?dropdownCustomWidth
?deselectDisable
isMobileView
hasApplyButton
setShowDropDown
?customMarginStyle
listFlexDirection
onApply
showSelectCountButton
?maxHeight
dropdownClassName
customStyle
searchInputPlaceHolder
showSearchIcon
?sortingBasedOnDisabled
preservedAppliedOptions
/>
} else if addButton {
<BaseSelectButton
options
optionSize
isSelectedStateMinus
showDropDown
onSelect=onRadioOptionSelect
onBlur=newInputRadio.onBlur
value=newInputRadio.value
isDropDown=true
?deselectDisable
isHorizontal=false
setShowDropDown
?onAssignClick
isMobileView
customSearchStyle
disableSelect
hideAssignBtn={true}
searchInputPlaceHolder
showSearchIcon
/>
} else {
<BaseRadio
options
optionSize
isSelectedStateMinus
showDropDown
onSelect=onRadioOptionSelect
onBlur=newInputRadio.onBlur
value=newInputRadio.value
isDropDown=true
?deselectDisable
isHorizontal=false
customStyle
?searchable
isMobileView
descriptionOnHover
showMatchingRecordsText
?dropdownCustomWidth
addDynamicValue
dropdownRef
fullLength
selectedString
setSelectedString
setExtSearchString
listFlexDirection
showToolTipOptions
textEllipsisForDropDownOptions
searchInputPlaceHolder
showSearchIcon
/>
}
let selectButtonText = if !showSelectionAsChips {
title
} else if selectedString->LogicUtils.isNonEmptyString {
selectedString
} else {
dropDowntext
}
let buttonIcon =
<Icon
name=downArrowIcon
size=arrowIconSize
className={`transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)] ${showDropDown
? "-rotate-180"
: ""}`}
/>
let textStyle = if isSelectTextDark && selectButtonText !== buttonText {
Some("text-black dark:text-white")
} else {
textStyle
}
let onDeleteClick = name => {
[name]->removeKeys
setfilterKeys(_ => filterKeys->Array.filter(item => item !== name))
}
<div className={`flex relative flex-row flex-wrap`}>
<div className={`flex relative ${flexWrapper} ${fullLength ? "w-full" : ""}`}>
<div
ref={selectBoxRef->ReactDOM.Ref.domRef}
className={`text-opacity-50 ${fullLength ? "w-full" : ""}`}>
{switch baseComponent {
| Some(comp) => <span onClick> {comp} </span>
| None =>
switch baseComponentMethod {
| Some(compFn) => <span onClick> {compFn(showDropDown)} </span>
| None =>
switch buttonType {
| FilterAdd =>
<Button
text=buttonText
leftIcon={customButtonLeftIcon->Option.getOr(FontAwesome({"plus"}))}
buttonType
isSelectBoxButton=true
buttonSize
onClick
?textStyle
textWeight=?buttonTextWeight
buttonState={disableSelect ? Disabled : Normal}
fullLength
?showBorder
customButtonStyle
?customTextPaddingClass
customPaddingClass=?customButtonPaddingClass
customIconMargin=?customButtonIconMargin
?customBackColor
/>
| _ => {
let selectButton =
<div
onClick
className={`${textStyle->Option.getOr(
"",
)} flex justify-center items-center whitespace-pre leading-5 text-sm font-medium hover:bg-opacity-80 cursor-pointer mr-2 pr-1`}>
<div className="text-ellipsis overflow-hidden w-full max-w-sm h-fit">
{selectButtonText->React.string}
</div>
{buttonIcon}
<RenderIf condition={badgeForSelect.color === BadgeBlue}>
<div
className="px-2 py-0.5 bg-primary rounded-lg text-white text-sm font-medium leading-5 mx-1 h-fit">
{badgeForSelect.value->React.string}
</div>
</RenderIf>
</div>
<div
className={`flex ${customButtonStyle} ${showDropDown
? buttonStyleOnDropDownOpened
: ""} transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)] justify-between border`}>
{if (
showToolTip &&
newInputSelect.value !== ""->JSON.Encode.string &&
!showDropDown &&
showNameAsToolTip
) {
<ToolTip
description={showNameAsToolTip
? `Select ${LogicUtils.snakeToTitle(newInputSelect.name)}`
: newInputSelect.value
->LogicUtils.getStrArryFromJson
->Array.joinWith(",\n")}
toolTipFor=selectButton
toolTipPosition=Bottom
tooltipWidthClass=""
/>
} else {
selectButton
}}
<div
className="p-1 hover:bg-gray-200 cursor-pointer border-l-2 "
onClick={_ => newInputSelect.name->onDeleteClick}>
<Icon size={13} name="cross-outline" />
</div>
</div>
}
}
}
}}
</div>
{if showDropDown {
if !isMobileView {
<AddDataAttributes attributes=[("data-dropdown", "dropdown")]>
<div
className={`${marginTop} absolute ${isGrowDown
? "animate-growDown"
: ""} ${dropDirection == BottomLeft ||
dropDirection == BottomMiddle ||
dropDirection == BottomRight
? "origin-top"
: "origin-bottom"} ${dropdownOuterClass} z-20 ${marginBottom} bg-gray-50 dark:bg-jp-gray-950 ${fullLength
? "w-full"
: ""}`}
ref={dropdownRef->ReactDOM.Ref.domRef}>
optionsElement
{showCustomBtnAtEnd ? customButton : React.null}
</div>
</AddDataAttributes>
} else {
<BottomModal headerText={buttonText} onCloseClick={onClick}>
optionsElement
</BottomModal>
}
} else if !isInitialRender && isGrowDown && !isMobileView {
<div
className={`${marginTop} absolute animate-growUp ${widthClass} ${dropDirection ==
BottomLeft ||
dropDirection == BottomMiddle ||
dropDirection == BottomRight
? "origin-top"
: "origin-bottom"} ${dropdownOuterClass} z-20 ${marginBottom} bg-gray-50 dark:bg-jp-gray-950`}
ref={dropdownRef->ReactDOM.Ref.domRef}>
optionsElement
</div>
} else {
React.null
}}
</div>
{if allowMultiSelect && !hideMultiSelectButtons && showSelectionAsChips {
switch newInputSelect.value->JSON.Decode.array {
| Some(jsonArr) =>
jsonArr
->LogicUtils.getStrArrayFromJsonArray
->Array.mapWithIndex((str, i) => {
let actualValueIndex = Array.findIndex(options->Array.map(x => x.value), item =>
item == str
)
if actualValueIndex !== -1 {
let (text, leftIcon) = switch options[actualValueIndex] {
| Some(ele) => (ele.label, ele.icon->Option.getOr(NoIcon))
| None => ("", NoIcon)
}
<div key={Int.toString(i)} className="m-2">
<Button
buttonFor=buttonText
buttonSize=Small
isSelectBoxButton=true
leftIcon
rightIcon={FontAwesome("times")}
text
onClick={removeOption(str)}
/>
</div>
} else {
React.null
}
})
->React.array
| _ => React.null
}
} else {
React.null
}}
</div>
}
}
module ChipFilterSelectBox = {
@react.component
let make = (
~options: array<dropdownOption>,
~input: ReactFinalForm.fieldRenderPropsInput,
~deselectDisable=false,
~allowMultiSelect=true,
~isTickRequired=true,
~customStyleForChips="",
) => {
let transformedOptions = useTransformed(options)
let initalClassName = " m-2 bg-gray-200 dark:text-gray-800 border-jp-gray-800 inline-block text-s px-2 py-1 rounded-2xl"
let passedClassName = "flex items-center m-2 bg-blue-400 dark:text-gray-800 border-gray-300 inline-block text-s px-2 py-1 rounded-2xl"
let newInputSelect = input->ffInputToSelectInput
let values = newInputSelect.value
let saneValue = React.useMemo(() => {
values->LogicUtils.getArrayFromJson([])->LogicUtils.getStrArrayFromJsonArray
}, [values])
let onItemClick = (itemDataValue, isDisabled) => {
if !isDisabled {
if allowMultiSelect {
let data = if Array.includes(saneValue, itemDataValue) {
if deselectDisable {
saneValue
} else {
saneValue->Array.filter(x => x !== itemDataValue)
}
} else {
Array.concat(saneValue, [itemDataValue])
}
newInputSelect.onChange(data)
} else {
newInputSelect.onChange([itemDataValue])
}
}
}
<div className={`md:max-h-72 overflow-auto font-medium flex flex-wrap gap-4 `}>
{transformedOptions
->Array.mapWithIndex((option, i) => {
let isSelected = saneValue->Array.includes(option.value)
let selectedClass = isSelected ? passedClassName : initalClassName
let chipsCss =
customStyleForChips->LogicUtils.isEmptyString ? selectedClass : customStyleForChips
<div
key={Int.toString(i)}
onClick={_ => onItemClick(option.value, option.isDisabled)}
className={`px-4 py-1 mr-1 mt-0.5 border rounded-full flex flex-row gap-2 items-center cursor-pointer ${chipsCss}`}>
{if isTickRequired {
if isSelected {
<Icon name="check-circle" size=9 className="fill-blue-150 mr-1 mt-0.5" />
} else {
<Icon name="check-circle" size=9 className="fill-gray-150 mr-1 mt-0.5" />
}
} else {
React.null
}}
{React.string(option.label)}
</div>
})
->React.array}
</div>
}
}
@react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~buttonText="Normal Selection",
~buttonSize=?,
~allowMultiSelect=false,
~isDropDown=true,
~hideMultiSelectButtons=false,
~options: array<'a>,
~optionSize: CheckBoxIcon.size=Small,
~isSelectedStateMinus=false,
~isHorizontal=false,
~deselectDisable=false,
~showClearAll=true,
~showSelectAll=true,
~buttonType=Button.SecondaryFilled,
~disableSelect=false,
~fullLength=false,
~customButtonStyle="",
~textStyle="",
~marginTop="mt-12",
~customStyle="",
~showSelectionAsChips=true,
~showToggle=false,
~maxHeight=?,
~searchable=?,
~fill="#0EB025",
~optionRigthElement=?,
~hideBorder=false,
~allSelectType=Icon,
~customSearchStyle="bg-jp-gray-100 dark:bg-jp-gray-950 p-2",
~searchInputPlaceHolder=?,
~showSearchIcon=true,
~customLabelStyle=?,
~customMargin="",
~showToolTip=false,
~showNameAsToolTip=false,
~showBorder=?,
~showCustomBtnAtEnd=false,
~dropDownCustomBtnClick=false,
~addDynamicValue=false,
~showMatchingRecordsText=true,
~customButton=React.null,
~descriptionOnHover=false,
~fixedDropDownDirection=?,
~dropdownCustomWidth=?,
~baseComponent=?,
~baseComponentMethod=?,
~customMarginStyle=?,
~buttonTextWeight=?,
~customButtonLeftIcon=?,
~customTextPaddingClass=?,
~customButtonPaddingClass=?,
~customButtonIconMargin=?,
~setExtSearchString=_ => (),
~buttonStyleOnDropDownOpened="",
~listFlexDirection="",
~baseComponentCustomStyle="",
~ellipsisOnly=false,
~customSelectStyle="",
~isPhoneDropdown=false,
~hasApplyButton=?,
~onApply=?,
~showAllSelectedOptions=?,
~buttonClickFn=?,
~showDescriptionAsTool=true,
~optionClass="",
~selectClass="",
~toggleProps="",
~showSelectCountButton=false,
~leftIcon=?,
~customBackColor=?,
~customSelectAllStyle=?,
~checkboxDimension="",
~showToolTipOptions=false,
~textEllipsisForDropDownOptions=false,
~showBtnTextToolTip=false,
~dropdownClassName="",
~onItemSelect=(_, _) => (),
~wrapBasis="",
(),
) => {
let isMobileView = MatchMedia.useMobileChecker()
let (selectedString, setSelectedString) = React.useState(_ => "")
let newInputSelect = input->ffInputToSelectInput
let newInputRadio = input->ffInputToRadioInput
let customButtonStyle = "bg-white rounded-lg !px-4 !py-2 !h-10"
if isDropDown {
<BaseDropdown
buttonText
?buttonSize
allowMultiSelect
input
options
optionSize
isSelectedStateMinus
showClearAll
showSelectAll
hideMultiSelectButtons
deselectDisable
buttonType
disableSelect
fullLength
customButtonStyle
textStyle // to change style of text inside dropdown
marginTop
customStyle
showSelectionAsChips
addDynamicValue
showMatchingRecordsText
?searchable
customSearchStyle
showToolTip
showNameAsToolTip
?showBorder
dropDownCustomBtnClick
showCustomBtnAtEnd
customButton
descriptionOnHover
?dropdownCustomWidth
?fixedDropDownDirection
?baseComponent
?baseComponentMethod
?customMarginStyle
?buttonTextWeight
?customButtonLeftIcon
?customTextPaddingClass
?customButtonPaddingClass
?customButtonIconMargin
buttonStyleOnDropDownOpened
selectedString
setSelectedString
setExtSearchString
listFlexDirection
ellipsisOnly
isPhoneDropdown
?hasApplyButton
?onApply
?showAllSelectedOptions
?buttonClickFn
showSelectCountButton
defaultLeftIcon=?leftIcon
?maxHeight
?customBackColor
showToolTipOptions
textEllipsisForDropDownOptions
showBtnTextToolTip
dropdownClassName
?searchInputPlaceHolder
showSearchIcon
/>
} else if allowMultiSelect {
<BaseSelect
options
optionSize
isSelectedStateMinus
?optionRigthElement
onSelect=newInputSelect.onChange
value=newInputSelect.value
isDropDown
showClearAll
showSelectAll
onBlur=newInputSelect.onBlur
isHorizontal
showToggle
heading=buttonText
?maxHeight
?searchable
isMobileView
hideBorder
allSelectType
showSelectionAsChips
?searchInputPlaceHolder
showSearchIcon
?customLabelStyle
customStyle
customMargin
customSearchStyle
disableSelect
?customMarginStyle
?dropdownCustomWidth
listFlexDirection
?hasApplyButton
?onApply
?showAllSelectedOptions
showDescriptionAsTool
optionClass
selectClass
toggleProps
?customSelectAllStyle
checkboxDimension
dropdownClassName
onItemSelect
wrapBasis
/>
} else {
<BaseRadio
options
optionSize
isSelectedStateMinus
onSelect=newInputRadio.onChange
value=newInputRadio.value
onBlur=newInputRadio.onBlur
isDropDown
fill
isHorizontal
deselectDisable
?searchable
customSearchStyle
isMobileView
listFlexDirection
customStyle
baseComponentCustomStyle
customSelectStyle
?maxHeight
?searchInputPlaceHolder
showSearchIcon
descriptionOnHover
showToolTipOptions
/>
}
}
| 16,692 | 10,062 |
hyperswitch-control-center | src/components/EntityScaffold.res | .res | @react.component
let make = (
~entityName="",
~remainingPath,
~isAdminAccount=false,
~access: CommonAuthTypes.authorization=Access,
~renderList,
~renderNewForm=_ => React.null,
~renderShow=(_, _) => React.null,
~renderCustomWithOMP: (string, option<string>, option<string>, option<string>) => React.element=(
_,
_,
_,
_,
) => React.null,
) => {
if access === NoAccess {
<UnauthorizedPage />
} else {
switch remainingPath {
| list{"new"} => renderNewForm()
| list{id} => renderShow(id, None)
| list{id, key} => renderShow(id, Some(key))
| list{id, profileId, merchantId, orgId} =>
renderCustomWithOMP(id, Some(profileId), Some(merchantId), Some(orgId))
| list{} => renderList()
| _ => <NotFoundPage />
}
}
}
| 221 | 10,063 |
hyperswitch-control-center | src/components/LegacySwitch.res | .res | 1 | 10,064 | |
hyperswitch-control-center | src/components/LoadedTable.resi | .resi | type sortTyp = ASC | DSC
type sortOb = {sortKey: string, sortType: sortTyp}
type checkBoxProps = {
showCheckBox: bool,
selectedData: array<JSON.t>,
setSelectedData: (array<JSON.t> => array<JSON.t>) => unit,
}
let checkBoxPropDefaultVal: checkBoxProps
let sortAtom: Recoil.recoilAtom<RescriptCore.Dict.t<sortOb>>
let backgroundClass: string
let useSortedObj: (
string,
option<Table.sortedObject>,
) => (
option<Table.sortedObject>,
(option<Table.sortedObject> => option<Table.sortedObject>) => unit,
)
let sortArray: (array<'a>, string, Table.sortOrder) => array<'a>
type pageDetails = {offset: int, resultsPerPage: int}
let table_pageDetails: Recoil.recoilAtom<RescriptCore.Dict.t<pageDetails>>
@react.component
let make: (
~hideCustomisableColumnButton: bool=?,
~visibleColumns: array<'a>=?,
~defaultSort: Table.sortedObject=?,
~title: string,
~titleSize: NewThemeUtils.headingSize=?,
~description: string=?,
~tableActions: React.element=?,
~isTableActionBesideFilters: bool=?,
~hideFilterTopPortals: bool=?,
~rightTitleElement: React.element=?,
~clearFormattedDataButton: React.element=?,
~bottomActions: React.element=?,
~showSerialNumber: bool=?,
~actualData: array<Nullable.t<'b>>,
~totalResults: int,
~resultsPerPage: int,
~offset: int,
~setOffset: ('c => int) => unit,
~handleRefetch: unit => unit=?,
~entity: EntityType.entityType<'a, 'b>,
~onEntityClick: 'b => unit=?,
~onEntityDoubleClick: 'b => unit=?,
~onExpandClickData: 'd=?,
~currrentFetchCount: int,
~filters: React.element=?,
~showFilterBorder: bool=?,
~headBottomMargin: string=?,
~removeVerticalLines: bool=?,
~removeHorizontalLines: bool=?,
~evenVertivalLines: bool=?,
~showPagination: bool=?,
~downloadCsv: React.element=?,
~ignoreUrlUpdate: bool=?,
~hideTitle: bool=?,
~ignoreHeaderBg: bool=?,
~tableDataLoading: bool=?,
~dataLoading: bool=?,
~advancedSearchComponent: React.element=?,
~setData: ('e => option<array<Nullable.t<'b>>>) => unit=?,
~setSummary: ('f => EntityType.summary) => unit=?,
~dataNotFoundComponent: React.element=?,
~renderCard: (~index: int, ~item: 'b, ~onRowClick: int => unit) => React.element=?,
~tableLocalFilter: bool=?,
~tableheadingClass: string=?,
~tableBorderClass: string=?,
~tableDataBorderClass: string=?,
~collapseTableRow: bool=?,
~getRowDetails: Nullable.t<'b> => React.element=?,
~onMouseEnter: 'b => unit=?,
~onMouseLeave: 'b => unit=?,
~frozenUpto: int=?,
~heightHeadingClass: string=?,
~highlightText: string=?,
~enableEqualWidthCol: bool=?,
~clearFormatting: bool=?,
~rowHeightClass: string=?,
~allowNullableRows: bool=?,
~titleTooltip: bool=?,
~isAnalyticsModule: bool=?,
~rowCustomClass: string=?,
~isHighchartLegend: bool=?,
~filterObj: array<Table.filterObject>=?,
~setFilterObj: (array<Table.filterObject> => array<Table.filterObject>) => unit=?,
~headingCenter: bool=?,
~filterIcon: React.element=?,
~filterDropdownClass: string=?,
~maxTableHeight: string=?,
~showTableOnMobileView: bool=?,
~labelMargin: string=?,
~customFilterRowStyle: string=?,
~noDataMsg: string=?,
~tableActionBorder: string=?,
~isEllipsisTextRelative: bool=?,
~customMoneyStyle: string=?,
~ellipseClass: string=?,
~checkBoxProps: checkBoxProps=?,
~selectedRowColor: string=?,
~paginationClass: string=?,
~lastHeadingClass: string=?,
~lastColClass: string=?,
~fixLastCol: bool=?,
~headerCustomBgColor: string=?,
~alignCellContent: string=?,
~minTableHeightClass: string=?,
~setExtFilteredDataLength: ('h => int) => unit=?,
~filterDropdownMaxHeight: string=?,
~showResultsPerPageSelector: bool=?,
~customCellColor: string=?,
~defaultResultsPerPage: bool=?,
~noScrollbar: bool=?,
~tableDataBackgroundClass: string=?,
~customBorderClass: string=?,
~showborderColor: bool=?,
~tableHeadingTextClass: string=?,
~nonFrozenTableParentClass: string=?,
~loadedTableParentClass: string=?,
~remoteSortEnabled: bool=?,
~showAutoScroll: bool=?,
~highlightSelectedRow: bool=?,
) => React.element
| 1,211 | 10,065 |
hyperswitch-control-center | src/components/MultiLineTextInput.res | .res | @react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~isDisabled,
~rows=?,
~cols=?,
~customClass="",
~leftIcon=?,
~readOnly=?,
~maxLength=?,
~autoFocus=?,
) => {
let showPopUp = PopUpState.useShowPopUp()
let cursorClass = if isDisabled {
"cursor-not-allowed"
} else {
""
}
React.useEffect(() => {
let val = input.value->JSON.Decode.string->Option.getOr("")
if val->String.includes("<script>") || val->String.includes("</script>") {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Script Tags are not allowed`,
description: React.string(`Input cannot contain <script>, </script> tags`),
handleConfirm: {text: "OK"},
})
input.onChange(
val
->String.replace("<script>", "")
->String.replace("</script>", "")
->Identity.stringToFormReactEvent,
)
}
None
}, [input.value])
let className = `rounded-md border border-jp-gray-lightmode_steelgray border-opacity-75 font-normal pl-4 pt-3 pb-3 text-sm text-jp-gray-900 text-opacity-75 placeholder-jp-gray-900 placeholder-opacity-25 hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-20 hover:border-jp-gray-900 hover:border-opacity-20 focus:text-opacity-100 focus:outline-none focus:border-primary focus:border-opacity-100 dark:text-jp-gray-text_darktheme dark:text-opacity-75 dark:border-jp-gray-960 dark:hover:border-jp-gray-960 dark:hover:bg-jp-gray-970 dark:bg-jp-gray-darkgray_background dark:placeholder-jp-gray-text_darktheme dark:placeholder-opacity-25 dark:focus:text-opacity-100 dark:focus:border-primary ${cursorClass} ${customClass}`
let value = switch input.value->JSON.Classify.classify {
| String(str) => str
| Number(num) => num->Float.toString
| _ => ""
}
let textAreaComponent =
<textarea
className
name={input.name}
onBlur={input.onBlur}
onChange={input.onChange}
onFocus={input.onFocus}
value
disabled={isDisabled}
placeholder={placeholder}
?autoFocus
?maxLength
?rows
?cols
?readOnly
/>
switch leftIcon {
| Some(icon) =>
<div className="flex flex-row md:relative">
<div className="absolute self-start p-3"> icon </div>
{textAreaComponent}
</div>
| None => textAreaComponent
}
}
| 624 | 10,066 |
hyperswitch-control-center | src/components/OrderUtils.res | .res | module Section = {
@react.component
let make = (
~children,
~customCssClass="border border-jp-gray-500 dark:border-jp-gray-960 bg-white dark:bg-jp-gray-950 rounded-md p-0 m-3",
) => {
<div className=customCssClass> children </div>
}
}
module DisplayKeyValueParams = {
@react.component
let make = (
~showTitle: bool=true,
~heading: Table.header,
~value: Table.cell,
~isInHeader=false,
~isHorizontal=false,
~customMoneyStyle="",
~labelMargin="",
~customDateStyle="",
~wordBreak=true,
~textColor="",
~overiddingHeadingStyles="",
) => {
let marginClass = if labelMargin->LogicUtils.isEmptyString {
"mt-4 py-0"
} else {
labelMargin
}
let fontClass = if isInHeader {
"text-fs-20"
} else {
"text-fs-13"
}
let breakWords = if wordBreak {
"break-all"
} else {
""
}
let textColor =
textColor->LogicUtils.isEmptyString ? "text-jp-gray-900 dark:text-white" : textColor
let description = heading.description->Option.getOr("")
{
<AddDataAttributes attributes=[("data-label", heading.title)]>
<div className={`flex ${isHorizontal ? "flex-row gap-3" : "flex-col gap-1"} py-4`}>
<div
className="flex flex-row text-fs-11 leading-3 text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 items-center">
<div className={`${overiddingHeadingStyles}`}>
{React.string(showTitle ? heading.title : "")}
</div>
<RenderIf condition={description->LogicUtils.isNonEmptyString}>
<div className="text-sm text-gray-500 mx-2 -mt-1">
<ToolTip description={description} toolTipPosition={ToolTip.Top} />
</div>
</RenderIf>
</div>
<div className={`${fontClass} font-semibold text-left mr-5 ${textColor} ${breakWords}`}>
<Table.TableCell
cell=value
textAlign=Table.Left
fontBold=true
customMoneyStyle
labelMargin=marginClass
customDateStyle
/>
</div>
</div>
</AddDataAttributes>
}
}
}
type topic =
| String(string)
| ReactElement(React.element)
module Heading = {
@react.component
let make = (~topic: topic, ~children=?, ~borderClass="border-b", ~headingCss="") => {
let widthClass = headingCss->LogicUtils.isEmptyString ? "" : "w-full"
<div
className={`${borderClass} border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960 flex justify justify-between dark:bg-jp-gray-lightgray_background ${headingCss}`}>
<div className={`p-2 m-2 flex flex-row justify-start ${widthClass}`}>
{switch topic {
| String(string) =>
<AddDataAttributes attributes=[("data-heading", string)]>
<span className="text-gray-600 dark:text-gray-400 font-bold text-base text-fs-16">
{React.string({string})}
</span>
</AddDataAttributes>
| ReactElement(element) => element
}}
</div>
<div className="p-2 m-2 flex flex-row justify-end ">
<span>
{switch children {
| Some(element) => element
| None => React.null
}}
</span>
</div>
</div>
}
}
module Details = {
// open PreviewDetails
@react.component
let make = (
~heading,
~data,
~getHeading,
~getCell,
~excludeColKeys=[],
~detailsFields,
~justifyClassName="justify-start",
~widthClass="w-3/12",
~chargeBackField=None,
~bgColor="bg-white dark:bg-jp-gray-lightgray_background",
~children=?,
~headRightElement=React.null,
~borderRequired=true,
~isHeadingRequired=true,
~cardView=false,
~showDetails=true,
~headingCss="",
~showTitle=true,
~flexClass="flex flex-wrap",
) => {
if !cardView {
<Section
customCssClass={`${borderRequired
? "border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960"
: ""} ${bgColor} rounded-md `}>
<RenderIf condition=isHeadingRequired>
<Heading topic=heading headingCss> {headRightElement} </Heading>
</RenderIf>
<RenderIf condition=showDetails>
<FormRenderer.DesktopRow>
<div
className={`${flexClass} ${justifyClassName} lg:flex-row flex-col dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border`}>
{detailsFields
->Array.mapWithIndex((colType, i) => {
if !(excludeColKeys->Array.includes(colType)) {
<div className=widthClass key={Int.toString(i)}>
<DisplayKeyValueParams
heading={getHeading(colType)}
value={getCell(data, colType)}
customMoneyStyle="!text-fs-13"
labelMargin="!py-0 mt-2"
customDateStyle="!font-fira-code"
showTitle
/>
<div />
</div>
} else {
React.null
}
})
->React.array}
{switch chargeBackField {
| Some(field) =>
<div className="flex flex-col py-4">
<div
className="text-fs-11 leading-3 text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{React.string("Chargeback Amount")}
</div>
<div
className="text-fs-13 font-semibold text-left dark:text-white text-jp-gray-900 break-all">
<Table.TableCell
cell=field
textAlign=Table.Left
fontBold=true
customDateStyle="!font-fira-code"
customMoneyStyle="!text-fs-13"
labelMargin="!py-0 mt-2 h-6"
/>
</div>
</div>
| None => React.null
}}
</div>
</FormRenderer.DesktopRow>
</RenderIf>
{switch children {
| Some(ele) => ele
| None => React.null
}}
</Section>
} else {
<div
className="flex flex-col w-full pt-4 gap-4 bg-white rounded-md dark:bg-jp-gray-lightgray_background">
{detailsFields
->Array.map(item => {
<div className="flex justify-between">
<div className="text-jp-gray-900 dark:text-white opacity-50 font-medium">
{getHeading(item).title->React.string}
</div>
<div className="font-semibold break-all">
<Table.TableCell cell={getCell(data, item)} />
</div>
</div>
})
->React.array}
</div>
}
}
}
| 1,666 | 10,067 |
hyperswitch-control-center | src/components/Icon.res | .res | @react.component
let make = (
~name,
~size=20,
~className=?,
~themeBased=false,
~onClick=?,
~parentClass=?,
~customIconColor="",
~customWidth=?,
~customHeight=?,
) => {
let urlPrefix = ""
let useUrl =
<use
className={`fill-current ${customIconColor}`}
xlinkHref={`${urlPrefix}/icons/solid.svg#${name}`}
/>
let otherClasses = switch className {
| Some(str) => str
| None => ""
}
let handleClick = ev => {
switch onClick {
| Some(fn) => fn(ev)
| None => ()
}
}
<AddDataAttributes attributes=[("data-icon", name)]>
<div
className={switch parentClass {
| Some(class) => class
| None => "flex flex-col justify-center"
}}>
<svg
onClick=handleClick
fill=customIconColor
className={`fill-current ${otherClasses}`}
width={{
customWidth->Option.isSome ? customWidth->Option.getOr("") : Int.toString(size)
} ++ "px"}
height={{
customHeight->Option.isSome ? customHeight->Option.getOr("") : Int.toString(size)
} ++ "px"}>
useUrl
</svg>
</div>
</AddDataAttributes>
}
| 305 | 10,068 |
hyperswitch-control-center | src/components/ACLButton.res | .res | open Button
@react.component
let make = (
~text=?,
~buttonState: buttonState=Normal,
~buttonType: buttonType=SecondaryFilled,
~buttonVariant: buttonVariant=Fit,
~buttonSize: option<buttonSize>=?,
~leftIcon: iconType=NoIcon,
~rightIcon: iconType=NoIcon,
~showBorder=true,
~type_="button",
~onClick=?,
~textStyle="",
~customIconMargin=?,
~customTextSize=?,
~customIconSize=?,
~textWeight=?,
~fullLength=false,
~disableRipple=false,
~customButtonStyle="",
~textStyleClass=?,
~customTextPaddingClass=?,
~allowButtonTextMinWidth=true,
~customPaddingClass=?,
~customRoundedClass=?,
~customHeightClass=?,
~customBackColor=?,
~showBtnTextToolTip=false,
~authorization=CommonAuthTypes.Access,
~tooltipText=HSwitchUtils.noAccessControlText,
~toolTipPosition=?,
) => {
let buttonState = switch authorization {
| Access => buttonState
| NoAccess => Button.Disabled
}
let showBtnTextToolTip = authorization === NoAccess
<Button
buttonState
?text
buttonType
buttonVariant
?buttonSize
leftIcon
rightIcon
showBorder
type_
?onClick
textStyle
?customIconMargin
?customTextSize
?customIconSize
?textWeight
fullLength
disableRipple
customButtonStyle
?textStyleClass
?customTextPaddingClass
allowButtonTextMinWidth
?customPaddingClass
?customRoundedClass
?customHeightClass
?customBackColor
showBtnTextToolTip
tooltipText
?toolTipPosition
/>
}
| 424 | 10,069 |
hyperswitch-control-center | src/components/NewPagination.res | .res | @react.component
let make = (~resultsPerPage, ~totalResults, ~currentPage, ~paginate, ~btnCount=4) => {
let pageNumbers = []
let total = Math.ceil(Int.toFloat(totalResults) /. Int.toFloat(resultsPerPage))->Float.toInt
for x in 1 to total {
Array.push(pageNumbers, x)->ignore
}
let pageToLeft =
btnCount - (total - currentPage) < btnCount / 2
? btnCount / 2
: btnCount - (total - currentPage)
let startIndex = Math.Int.max(1, currentPage - pageToLeft)
let endIndex = Math.Int.min(startIndex + btnCount, total)
let nonEmpty = s => s >= startIndex && s <= endIndex
<ButtonGroup>
{if currentPage > 1 {
<Icon
name="chevron-left"
className="fill-ardra-secondary-300"
size=16
onClick={_ => paginate(Math.Int.max(1, currentPage - 1))}
/>
} else {
<Icon
name="leftDisabledPaginator"
size=16
onClick={_ => paginate(Math.Int.max(1, currentPage - 1))}
/>
}}
{pageNumbers
->Array.filter(nonEmpty)
->Array.mapWithIndex((number, idx) => {
<div className="p-2">
<Button
key={idx->Int.toString}
text={number->Int.toString}
onClick={_ => paginate(number)}
buttonType={Pill}
customButtonStyle="rounded-[4px] w-[39px] h-[36px]"
textStyle="text-[#0E111E] text-[14px]"
textWeight="font-light"
/>
</div>
})
->React.array}
{if currentPage < Array.length(pageNumbers) {
<Icon name="chevron-right" size=16 onClick={_ => paginate(currentPage + 1)} />
} else {
<Icon name="rightDisabledPaginator" size=16 onClick={_ => paginate(currentPage + 1)} />
}}
</ButtonGroup>
}
| 467 | 10,070 |
hyperswitch-control-center | src/components/Calendar.res | .res | type month = Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
type highlighter = {
highlightSelf: bool,
highlightLeft: bool,
highlightRight: bool,
}
type dateObj = {
startDate: string,
endDate: string,
}
module TableRow = {
let defaultCellHighlighter = _ => {
highlightSelf: false,
highlightLeft: false,
highlightRight: false,
}
let defaultCellRenderer = obj => {
switch obj {
| Some(a) => {
let day = String.split(a, "-")
React.string(day[2]->Option.getOr(""))
}
| None => React.string("")
}
}
@react.component
let make = (
~changeHighlightCellStyle="",
~item,
~month,
~year,
~rowIndex as _rowIndex,
~onDateClick,
~cellHighlighter=defaultCellHighlighter,
~cellRenderer=defaultCellRenderer,
~startDate="",
~endDate="",
~hoverdDate,
~setHoverdDate,
~disablePastDates=true,
~disableFutureDates=false,
~customDisabledFutureDays=0.0,
~dateRangeLimit=?,
~setShowMsg=?,
~allowedDateRange: option<dateObj>=?,
) => {
open LogicUtils
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString()
let highlight = cellHighlighter
{
if item == Array.make(~length=7, "") {
<tr className="h-0" />
} else {
<tr className="transition duration-300 ease-in-out">
{item
->Array.mapWithIndex((obj, cellIndex) => {
let date =
customTimezoneToISOString(
String.make(year),
String.make(month +. 1.0),
String.make(obj->isEmptyString ? "01" : obj),
"00",
"00",
"00",
)->Date.fromString
let dateToday = Date.make()
let todayInitial = Js.Date.setHoursMSMs(
dateToday,
~hours=0.0,
~minutes=0.0,
~seconds=0.0,
~milliseconds=0.0,
(),
)
let isInCustomDisable = if customDisabledFutureDays > 0.0 {
date->Date.getTime -. todayInitial <=
customDisabledFutureDays *. 24.0 *. 3600.0 *. 1000.0
} else {
false
}
let dateNotInRange = switch allowedDateRange {
| Some(obj) =>
if obj.startDate->isNonEmptyString && obj.endDate->isNonEmptyString {
!(
date->Date.getTime -. obj.startDate->Date.fromString->Date.getTime >= 0.0 &&
obj.endDate->Date.fromString->Date.getTime -. date->Date.getTime >= 0.0
)
} else {
false
}
| None => false
}
let isFutureDate = if disablePastDates {
todayInitial -. date->Date.getTime <= 0.0
} else {
todayInitial -. date->Date.getTime < 0.0
}
let isInLimit = switch dateRangeLimit {
| Some(limit) =>
if startDate->isNonEmptyString {
date->Date.getTime -. startDate->Date.fromString->Date.getTime <
((limit->Int.toFloat -. 1.) *. 24. *. 60. *. 60. -. 60.) *. 1000.
} else {
true
}
| None => true
}
let onClick = _ => {
let isClickDisabled =
(endDate->isEmptyString && !isInLimit) ||
(isFutureDate ? disableFutureDates : disablePastDates) ||
customDisabledFutureDays > 0.0 && isInCustomDisable ||
dateNotInRange
switch !isClickDisabled {
| true =>
switch onDateClick {
| Some(fn) =>
fn((Date.toISOString(date)->DayJs.getDayJsForString).format("YYYY-MM-DD"))
| None => ()
}
| false => ()
}
}
let hSelf = highlight(
(Date.toString(date)->DayJs.getDayJsForString).format("YYYY-MM-DD"),
)
let dayClass = if (
(isFutureDate && disableFutureDates) ||
customDisabledFutureDays > 0.0 && isInCustomDisable ||
!isFutureDate && disablePastDates ||
endDate->isEmptyString && !isInLimit ||
dateNotInRange
) {
"cursor-not-allowed"
} else {
"cursor-pointer"
}
let getDate = date => {
let datevalue = Js.Date.makeWithYMD(
~year=Js.Float.fromString(date[0]->Option.getOr("")),
~month=Js.Float.fromString(
String.make(Js.Float.fromString(date[1]->Option.getOr("")) -. 1.0),
),
~date=Js.Float.fromString(date[2]->Option.getOr("")),
(),
)
datevalue
}
let today = (Date.make()->Date.toString->DayJs.getDayJsForString).format("YYYY-MM-DD")
let renderingDate = (
getDate([Float.toString(year), Float.toString(month +. 1.0), obj])
->Date.toString
->DayJs.getDayJsForString
).format("YYYY-MM-DD")
let textColor =
today == renderingDate
? `${textColor.primaryNormal}`
: "text-jp-gray-900 text-opacity-75 dark:text-opacity-75"
let classN = if obj->isEmptyString || hSelf.highlightSelf {
`h-9 p-0 w-9 font-semibold font-fira-code text-center ${textColor} dark:text-jp-gray-text_darktheme ${dayClass}`
} else {
`h-9 p-0 w-9 font-semibold text-center font-fira-code ${textColor} dark:text-jp-gray-text_darktheme hover:text-opacity-100 dark:hover:text-opacity-100 hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-75 hover:rounded-lg dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 ${dayClass} `
}
let c2 =
obj->isNonEmptyString && hSelf.highlightSelf
? "h-full w-full flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary dark:bg-opacity-100 text-white rounded-full"
: "h-full w-full"
let shouldHighlight = (startDate, endDate, obj, month, year) => {
if startDate->isNonEmptyString && obj->isNonEmptyString {
let parsedStartDate = getDate(String.split(startDate, "-"))
let z = getDate([year, month, obj])
if endDate->isNonEmptyString {
let parsedEndDate = getDate(String.split(endDate, "-"))
z == parsedStartDate
? `h-full w-full flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary dark:bg-opacity-100 text-white rounded-l-lg `
: z == parsedEndDate
? "h-full w-full flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary dark:bg-opacity-100 text-white rounded-r-lg "
: z > parsedStartDate && z < parsedEndDate
? "h-full w-full flex flex-1 justify-center items-center bg-blue-100 dark:bg-gray-700 dark:bg-opacity-100 text-gray-600 dark:text-gray-400"
: "h-full w-full"
} else if z == parsedStartDate {
`h-full w-full flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary dark:bg-opacity-100 text-white rounded-lg ${changeHighlightCellStyle}`
} else if (
hoverdDate->isNonEmptyString &&
endDate->isEmptyString &&
z > parsedStartDate &&
z <= hoverdDate->Date.fromString &&
!(
(isFutureDate && disableFutureDates) ||
!isFutureDate && disablePastDates ||
(endDate->isEmptyString && !isInLimit)
)
) {
"h-full w-full flex flex-1 justify-center items-center bg-blue-100 dark:bg-gray-700 dark:bg-opacity-100"
} else {
"h-full w-full"
}
} else {
"h-full w-full"
}
}
let c3 = {
shouldHighlight(
startDate,
endDate,
obj,
Float.toString(month +. 1.0),
Float.toString(year),
)
}
let handleHover = () => {
let date = (Date.toString(date)->DayJs.getDayJsForString).format("YYYY-MM-DD")
let parsedDate = getDate(String.split(date, "-"))
setHoverdDate(_ => parsedDate->Date.toString)
switch setShowMsg {
| Some(setMsg) =>
if (
hoverdDate->isNonEmptyString &&
((!isInLimit &&
endDate->isEmptyString &&
!isFutureDate &&
disableFutureDates) ||
(!disableFutureDates && !isInLimit && endDate->isEmptyString))
) {
setMsg(_ => true)
} else {
setMsg(_ => false)
}
| None => ()
}
}
<td
key={Int.toString(cellIndex)}
className={classN}
onClick
onMouseOver={_ => handleHover()}
onMouseOut={_ => setHoverdDate(_ => "")}>
<AddDataAttributes
attributes=[
(
"data-calender-date",
hSelf.highlightSelf || startDate->isNonEmptyString ? "selected" : "normal",
),
(
"data-calender-date-disabled",
(isFutureDate && disableFutureDates) ||
customDisabledFutureDays > 0.0 && isInCustomDisable ||
!isFutureDate && disablePastDates ||
endDate->isEmptyString && !isInLimit ||
dateNotInRange
? "disabled"
: "enabled",
),
(
"data-testid",
(Date.toString(date)->DayJs.getDayJsForString).format("MMM D, YYYY"),
),
]>
<span className={startDate->isEmptyString ? c2 : c3}>
{cellRenderer(
obj->isEmptyString
? None
: Some((Date.toString(date)->DayJs.getDayJsForString).format("YYYY-MM-DD")),
)}
</span>
</AddDataAttributes>
</td>
})
->React.array}
</tr>
}
}
}
}
@react.component
let make = (
~changeHighlightCellStyle="",
~month,
~year,
~onDateClick=?,
~hoverdDate,
~setHoverdDate,
~showTitle=true,
~cellHighlighter=?,
~cellRenderer=?,
~highLightList=?,
~startDate="",
~endDate="",
~disablePastDates=true,
~disableFutureDates=false,
~dateRangeLimit=?,
~setShowMsg=?,
~showHead=true,
~customDisabledFutureDays=0.0,
~allowedDateRange=?,
) => {
let _ = highLightList
let months = [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
let heading = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
let isMobileView = MatchMedia.useMobileChecker()
let getMonthInFloat = mon => Array.indexOf(months, mon)->Float.fromInt
let getMonthInStr = mon => {
switch mon {
| Jan => "January, "
| Feb => "February, "
| Mar => "March, "
| Apr => "April, "
| May => "May, "
| Jun => "June, "
| Jul => "July, "
| Aug => "August, "
| Sep => "September, "
| Oct => "October, "
| Nov => "November, "
| Dec => "December, "
}
}
// get first day
let firstDay = Js.Date.getDay(
Js.Date.makeWithYM(~year=Int.toFloat(year), ~month=getMonthInFloat(month), ()),
)
// get Days in month
let daysInMonth = switch month {
| Jan => 31
| Feb => LogicUtils.checkLeapYear(year) ? 29 : 28
| Mar => 31
| Apr => 30
| May => 31
| Jun => 30
| Jul => 31
| Aug => 31
| Sep => 30
| Oct => 31
| Nov => 30
| Dec => 31
}
// creating row info
let dummyRow = Array.make(~length=6, Array.make(~length=7, ""))
let rowMapper = (row, indexRow) => {
Array.mapWithIndex(row, (_item, index) => {
let subFactor = Float.toInt(firstDay)
if indexRow == 0 && index < Float.toInt(firstDay) {
""
} else if indexRow == 0 {
Int.toString(indexRow + (index + 1) - subFactor)
} else if indexRow * 7 + (index + 1) - subFactor > daysInMonth {
""
} else {
Int.toString(indexRow * 7 + (index + 1) - subFactor)
}
})
}
let rowInfo = Array.mapWithIndex(dummyRow, rowMapper)
<div className="text-sm px-2 pb-2">
{showTitle
? {
<h3 className="text-center font-bold text-lg text-gray-500 ">
{React.string(month->getMonthInStr)}
<span className="font-fira-code"> {React.string(year->Int.toString)} </span>
</h3>
}
: {
<span />
}}
<table className="table-auto min-w-full">
<thead>
{if showHead {
<tr>
{heading
->Array.mapWithIndex((item, i) => {
<th key={Int.toString(i)}>
<div
className="flex flex-1 justify-center py-1 text-jp-gray-700 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{React.string(isMobileView ? item->String.charAt(0) : item)}
</div>
</th>
})
->React.array}
</tr>
} else {
React.null
}}
</thead>
<tbody>
{rowInfo
->Array.mapWithIndex((item, rowIndex) => {
<TableRow
key={Int.toString(rowIndex)}
item
rowIndex
onDateClick
hoverdDate
setHoverdDate
?cellHighlighter
?cellRenderer
month={getMonthInFloat(month)}
year={Int.toFloat(year)}
startDate
endDate
disablePastDates
disableFutureDates
changeHighlightCellStyle
?dateRangeLimit
?setShowMsg
customDisabledFutureDays
?allowedDateRange
/>
})
->React.array}
</tbody>
</table>
</div>
}
| 3,441 | 10,071 |
hyperswitch-control-center | src/components/Accordion.res | .res | type accordion = {
title: string,
renderContent: unit => React.element,
renderContentOnTop: option<unit => React.element>,
}
type arrowPosition = Left | Right
type mobileRenderType = Modal | Accordion
module SectionAccordion = {
@react.component
let make = (
~title="",
~subtext="",
~children,
~headerBg="md:bg-jp-gray-100 dark:bg-transparent",
~headingClass="",
~mobileRenderType: mobileRenderType=Accordion,
~hideHeaderWeb=false,
~setShow=_ => (),
) => {
let isMobileView = MatchMedia.useMobileChecker()
let (isExpanded, setIsExpanded) = React.useState(_ => !isMobileView)
let titleClass = "md:font-bold font-semibold md:text-fs-16 text-fs-13 text-jp-gray-900 text-opacity-75 dark:text-white dark:text-opacity-75"
<AddDataAttributes attributes=[("data-section", title)]>
<div className={`border md:border-0 dark:border-jp-gray-950 ${headerBg}`}>
<DesktopView>
<RenderIf condition={!hideHeaderWeb}>
<h3 className={`text-base ${headingClass}`}> {title->React.string} </h3>
</RenderIf>
<p
className="text-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{subtext->React.string}
</p>
<AddDataAttributes attributes=[("data-section", title)]> children </AddDataAttributes>
</DesktopView>
<MobileView>
<div
className={`${titleClass} bg-white dark:bg-jp-gray-lightgray_background px-4 py-3 flex justify-start text-jp-gray-900 text-opacity-75 `}
onClick={_ => {
setIsExpanded(prev => !prev)
setShow(_ => title)
}}>
<div className="py-1 !text-lg"> {title->React.string} </div>
<div
className="cursor-pointer flex justify-center align-center text-jp-gray-900 text-right text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ml-auto">
<Icon name={isExpanded ? "angle-down" : "angle-right"} size=15 />
</div>
</div>
{switch mobileRenderType {
| Modal =>
<Modal
modalHeading=title
showModal=isExpanded
setShowModal=setIsExpanded
borderBottom=true
childClass="">
<div className="mx-4 mb-4"> {children} </div>
</Modal>
| Accordion =>
<div
className={`${!isExpanded
? "hidden"
: ""} border-t-2 dark:border-jp-gray-950 md:border-0`}>
{children}
</div>
}}
</MobileView>
</div>
</AddDataAttributes>
}
}
module AccordionInfo = {
@react.component
let make = (
~accordion,
~arrowFillColor="",
~arrowPosition=Left,
~accordianTopContainerCss="",
~accordianBottomContainerCss="",
~expanded=false,
~contentExpandCss="",
~titleStyle="",
) => {
let (isExpanded, setIsExpanded) = React.useState(() => expanded)
let handleClick = _ => {
setIsExpanded(prevExpanded => !prevExpanded)
}
let contentClasses = if isExpanded {
`flex-wrap bg-white dark:bg-jp-gray-lightgray_background text-lg ${contentExpandCss}`
} else {
"hidden"
}
let svgDeg = if isExpanded {
"90"
} else {
"0"
}
<div
className={`overflow-hidden border bg-white border-jp-gray-500 dark:border-jp-gray-960 dark:bg-jp-gray-950 ${accordianTopContainerCss}`}>
<div
onClick={handleClick}
className={`flex cursor-pointer items-center font-ibm-plex bg-white hover:bg-jp-gray-100 dark:bg-jp-gray-950 dark:border-jp-gray-960 ${titleStyle} ${accordianBottomContainerCss}`}>
{if arrowPosition == Left {
<svg
width="7"
height="11"
viewBox="0 0 7 11"
fill="none"
transform={`rotate(${svgDeg})`}
xmlns="http://www.w3.org/2000/svg">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M-0.000107288 0L6.01489 5.013L-0.000107288 10.025V0Z"
fill=arrowFillColor
/>
</svg>
} else {
React.null
}}
{switch accordion.renderContentOnTop {
| Some(ui) => ui()
| None => <div className="ml-5"> {React.string(accordion.title)} </div>
}}
{if arrowPosition == Right {
<svg
width="7"
height="11"
viewBox="0 0 7 11"
fill="none"
transform={`rotate(${svgDeg})`}
xmlns="http://www.w3.org/2000/svg">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M-0.000107288 0L6.01489 5.013L-0.000107288 10.025V0Z"
fill=arrowFillColor
/>
</svg>
} else {
React.null
}}
</div>
<div
className={`flex flex-col dark:border-jp-gray-960 border-t dark:hover:bg-jp-gray-900 dark:hover:bg-opacity-25 ${contentClasses}`}>
{accordion.renderContent()}
</div>
</div>
}
}
@react.component
let make = (
~accordion: array<accordion>,
~arrowFillColor: string="#CED0DA",
~accordianTopContainerCss: string="mt-5 rounded-lg",
~accordianBottomContainerCss: string="p-4",
~contentExpandCss="px-8 font-bold",
~arrowPosition=Left,
~initialExpandedArray=[],
~gapClass="",
~titleStyle="font-bold text-lg text-jp-gray-700 dark:text-jp-gray-text_darktheme dark:text-opacity-50 hover:text-jp-gray-800 dark:hover:text-opacity-100",
) => {
<div className={`w-full ${gapClass}`}>
{accordion
->Array.mapWithIndex((accordion, i) => {
<AccordionInfo
key={Int.toString(i)}
accordion
arrowFillColor
arrowPosition
accordianTopContainerCss
accordianBottomContainerCss
contentExpandCss
expanded={initialExpandedArray->Array.includes(i)}
titleStyle
/>
})
->React.array}
</div>
}
| 1,619 | 10,072 |
hyperswitch-control-center | src/components/CustomizeNotificationsModal.res | .res | @react.component
let make = (
~modalHeading="Select Options",
~showModal,
~setShowModal,
~headerTextClass="text-2xl font-extrabold tracking-tight ml-3.5",
~element,
~revealFrom=Reveal.Right,
~closeOnOutsideClick=true,
~submitButtonText="Update",
~onSubmitModal,
~showLoderButton=false,
~totalNotifications=0,
~setNotificationCount=?,
~notificationCount=0,
~onBackClick,
~showBackIcon,
~modalWidth="w-[430px] !border-none",
~btnRequired=false,
~iconName="",
~showCloseIcon=true,
~onMarkAllAsReadClick=?,
~showMarkAllRead=false,
~refreshOutages=false,
~refresh=false,
~showModalHeadingIconName="",
~onCloseClickCustomFun=_ => (),
~iscollapasableSidebar=false,
~headingClassOverride="",
~overlayBG="!shadow-xl !blur-none !bg-none !backdrop-blur-none !rounded-none !border-transparent",
~isBackdropBlurReq=true,
~headerAlignmentClass="flex-row",
~customIcon=None,
) => {
let customHeight = btnRequired ? `h-screen` : `h-full`
let customButton =
<Button
text=submitButtonText
buttonType=Primary
buttonState={if refreshOutages {
if refresh {
Normal
} else {
Disabled
}
} else {
Normal
}}
leftIcon={CustomIcon(
<Icon
name=iconName
size=17
className="-mr-1 jp-gray-900 fill-opacity-50 dark:jp-gray-text_darktheme ml-3"
/>,
)}
onClick={onSubmitModal}
/>
<Modal
modalHeading
showModal
setShowModal
closeOnOutsideClick
revealFrom
showBackIcon
showCloseIcon
showModalHeadingIconName
onBackClick
onCloseClickCustomFun
isBackdropBlurReq
overlayBG
modalClass={`${modalWidth} ${customHeight} float-right overflow-hidden !bg-white dark:!bg-jp-gray-lightgray_background !rounded-none !shadow-xl !backdrop-blur-none`}
headingClass={`py-6 px-2.5 border-b border-solid border-slate-300 dark:border-slate-500 ${headingClassOverride}`}
headerTextClass
childClass="p-0 m-0"
customIcon
headerAlignmentClass
paddingClass="pt-0 overflow-hidden">
{showLoderButton && showMarkAllRead
? <div
className="text-xs text-sky-500 relative -top-10 left-64 w-fit cursor-pointer"
onClick={_ => {
switch onMarkAllAsReadClick {
| Some(onMarkAllAsReadClick) => onMarkAllAsReadClick()
| _ => ()
}
}}>
{React.string("Mark all as read")}
</div>
: React.null}
<div
className="overflow-auto p-6 border-b border-solid border-slate-300 dark:border-slate-500 relative"
style={height: btnRequired ? "calc(100vh - 9.6rem)" : "100vh"}>
element
<RenderIf condition={showLoderButton && notificationCount > 10}>
<div
className="flex fixed items-center justify-center" style={top: "100px", right: "100px"}>
<Button
text="Load Previous"
buttonType=Secondary
buttonSize=Medium
rightIcon={FontAwesome("arrow-up")}
onClick={_ => {
switch setNotificationCount {
| Some(setNotificationCount) => setNotificationCount(_ => notificationCount - 10)
| _ => ()
}
}}
/>
</div>
</RenderIf>
<RenderIf condition={totalNotifications - notificationCount > 0 && showLoderButton}>
<div className="sticky bottom-20 flex items-center justify-center">
<Button
text="Load More"
buttonType=Primary
buttonSize=Medium
rightIcon={FontAwesome("arrow-down")}
onClick={_ => {
switch setNotificationCount {
| Some(setNotificationCount) => setNotificationCount(_ => notificationCount + 10)
| _ => ()
}
}}
/>
</div>
</RenderIf>
</div>
<RenderIf condition={btnRequired}>
<div className="flex items-center justify-center my-5">
{if refreshOutages {
if refresh {
customButton
} else {
<ToolTip
description="kindly wait at least 1 minute to make a refresh"
toolTipFor=customButton
toolTipPosition=ToolTip.Top
/>
}
} else {
customButton
}}
</div>
</RenderIf>
</Modal>
}
| 1,121 | 10,073 |
hyperswitch-control-center | src/components/Paginator.res | .res | @react.component
let make = (
~totalResults,
~offset,
~resultsPerPage,
~setOffset,
~handleRefetch=?,
~currrentFetchCount,
~downloadCsv=?,
~isNewPaginator=false,
~actualData,
~tableDataLoading=false,
~setResultsPerPage=_ => (),
~paginationClass="",
~showResultsPerPageSelector=true,
) => {
let url = RescriptReactRouter.useUrl()
let currentPage = offset / resultsPerPage + 1
let start = offset + 1
let isMobileView = MatchMedia.useMobileChecker()
let isTabView = MatchMedia.useMatchMedia("(max-width: 800px)") && !isMobileView
let mobileFlexDirection = isMobileView ? "flex-row" : "flex-col md:flex-row"
let (flexDirection, btnCount, justify) = switch downloadCsv {
| Some(_) => (mobileFlexDirection, isTabView ? 2 : 4, "items-center justify-between")
| None => ("flex-row", isMobileView ? 2 : 4, "justify-start")
}
let toNum = resultsPerPage + start > totalResults ? totalResults : resultsPerPage + start - 1
let shouldRefetch = toNum > currrentFetchCount && toNum <= totalResults && !tableDataLoading
React.useEffect(() => {
if shouldRefetch {
switch handleRefetch {
| Some(fun) => fun()
| None => ()
}
}
None
}, (shouldRefetch, handleRefetch))
let selectInputOption = {
[5, 10, 15, 20, 50]
->Array.filter(val => val <= totalResults)
->Array.map(Int.toString)
->SelectBox.makeOptions
}
let selectInput: ReactFinalForm.fieldRenderPropsInput = {
name: "dummy-name",
onBlur: _ => (),
onChange: ev => {
setResultsPerPage(_ => {
ev->Identity.formReactEventToString->Int.fromString->Option.getOr(15)
})
},
onFocus: _ => (),
value: resultsPerPage->Int.toString->JSON.Encode.string,
checked: true,
}
let paginate = React.useCallback(pageNumber => {
let total = Math.ceil(Int.toFloat(totalResults) /. Int.toFloat(resultsPerPage))->Float.toInt
// for handling page count
let defaultPageNumber = Math.Int.min(total, pageNumber)
let page = defaultPageNumber
let newOffset = (page - 1) * resultsPerPage
setOffset(_ => newOffset)
}, (setOffset, resultsPerPage, currrentFetchCount, url.search, totalResults))
let marginClass = "md:mr-0"
if totalResults >= resultsPerPage {
<div
className={`flex ${flexDirection} bg-nd_gray-25 border border-t-0 rounded-b-lg border-nd_br_gray-300 px-6 py-2 justify-between ${marginClass} ${paginationClass} `}>
<div className={`flex flex-row w-full ${justify} text-sm`}>
<RenderIf condition={!isMobileView && showResultsPerPageSelector}>
<div
className="flex self-center gap-2 items-center text-center text-nd_gray-500 dark:text-gray-500 font-medium whitespace-pre">
<span>
{React.string("Showing ")}
<span className="text-nd_gray-700"> {React.string(toNum->Int.toString)} </span>
</span>
<SelectBox.BaseDropdown
options=selectInputOption
fixedDropDownDirection={TopLeft}
buttonText=""
searchable=false
marginTop="mb-8"
allowMultiSelect=false
input=selectInput
hideMultiSelectButtons=true
deselectDisable=true
buttonType=Button.Primary
baseComponent={<Icon size=20 name="nd-chevron-down" />}
/>
<span>
{React.string(" of")}
<span className="text-nd_gray-700">
{React.string(` ${totalResults->Int.toString}`)}
</span>
</span>
</div>
</RenderIf>
{switch downloadCsv {
| Some(actionData) =>
<div className="md:mr-2 lg:mr-5 mb-2">
<LoadedTableContext value={actualData->LoadedTableContext.toInfoData}>
actionData
</LoadedTableContext>
</div>
| None => React.null
}}
</div>
<div className="flex justify-end sm:justify-center tablePagination p-1 select-none">
{if isNewPaginator {
<NewPagination totalResults currentPage resultsPerPage paginate btnCount />
} else {
<Pagination totalResults currentPage resultsPerPage paginate btnCount />
}}
</div>
</div>
} else {
switch downloadCsv {
| Some(actionData) =>
<div className="flex justify-end mt-4">
<LoadedTableContext value={actualData->LoadedTableContext.toInfoData}>
actionData
</LoadedTableContext>
</div>
| None => React.null
}
}
}
| 1,133 | 10,074 |
hyperswitch-control-center | src/components/AuthWrapperUtils.res | .res | let getValidToken = oStr => {
if oStr !== Some("__failed") && oStr !== Some("") {
oStr
} else {
None
}
}
type tokenType = Default | Original | SwitchOnly
let useLocalStorageToken = tokenType => {
let lcToken = LocalStorage.useStorageValue("login")->getValidToken
let switchToken = LocalStorage.useStorageValue("switchToken")->getValidToken
if switchToken->Option.isSome && switchToken !== Some("__failed") && tokenType !== Original {
switchToken
} else if lcToken->Option.isSome && lcToken !== Some("__failed") && tokenType !== SwitchOnly {
lcToken
} else {
None
}
}
let useTokenParent = (tokenType: tokenType) => {
useLocalStorageToken(tokenType)
}
| 181 | 10,075 |
hyperswitch-control-center | src/components/CustomCharts/LineChartUtils.res | .res | external legendItemAsBool: Highcharts.legendItem => Highcharts.element = "%identity"
open LogicUtils
open Highcharts
open Identity
let defaultColor = "#7cb5ec"
let legendColor = [
defaultColor,
"#90ed7d",
"#f7a35c",
"#8085e9",
"#f15c80",
"#e4d354",
"#2b908f",
"#f45b5b",
"#91e8e1",
]
let defaultLegendColorGradients = (topGradient, bottomGradient) => {
{
linearGradient: (0, 0, 0, 300),
color: "#7cb5ec",
stops: ((0, `rgba(124,181,236, ${topGradient})`), (1, `rgba(124,170,236, ${bottomGradient})`)),
}
}
let legendColorGradients = (topGradient, bottomGradient) => {
[
defaultLegendColorGradients(topGradient, bottomGradient),
{
linearGradient: (0, 0, 0, 300),
color: "#434348",
stops: (
(0, `rgba(141, 103, 203, ${topGradient})`),
(1, `rgba(141, 93, 203, ${bottomGradient})`),
), //# 434348
},
{
linearGradient: (0, 0, 0, 300),
color: "#90ed7d",
stops: (
(0, `rgba(144, 237, 125, ${topGradient})`),
(1, `rgba(144, 227, 125, ${bottomGradient})`),
), //# 90ed7d
},
{
linearGradient: (0, 0, 0, 300),
color: "#f7a35c",
stops: ((0, `rgba(247,163,92, ${topGradient})`), (1, `rgba(247,153,92, ${bottomGradient})`)), //# f7a35c
},
{
linearGradient: (0, 0, 0, 300),
color: "#8085e9",
stops: (
(0, `rgba(128, 133, 233, ${topGradient})`),
(1, `rgba(128, 123, 233, ${bottomGradient})`),
), //# 8085e9
},
{
linearGradient: (0, 0, 0, 300),
color: "#f15c80",
stops: (
(0, `rgba(241, 92, 128, ${topGradient})`),
(1, `rgba(241, 82, 128, ${bottomGradient})`),
), //# f15c80
},
{
linearGradient: (0, 0, 0, 300),
color: "#e4d354",
stops: (
(0, `rgba(228, 211, 84, ${topGradient})`),
(1, `rgba(228, 201, 84, ${bottomGradient})`),
), //# e4d354
},
{
linearGradient: (0, 0, 0, 300),
color: "#2b908f",
stops: (
(0, `rgba(43, 144, 143, ${topGradient})`),
(1, `rgba(43, 134, 143, ${bottomGradient})`),
), //# 2b908f
},
{
linearGradient: (0, 0, 0, 300),
color: "#f45b5b",
stops: (
(0, `rgba(244, 91, 91, ${topGradient})`),
(1, `rgba(244, 81, 91, ${bottomGradient})`),
), //# f45b5b
},
{
linearGradient: (0, 0, 0, 300),
color: "#91e8e1",
stops: (
(0, `rgba(145, 232, 225, ${topGradient})`),
(1, `rgba(145, 222, 225, ${bottomGradient})`),
), //# 91e8e1
},
]
}
type hexToRgb = {
r: int,
g: int,
b: int,
}
//Takes rgba value and reduces opacity by 10
let reduceOpacity = str => {
let match = str->Js.String2.match_(%re("/rgba\(\d+,\s*\d+,\s*\d+,\s*([\d.]+)\)/"))
switch match {
| Some(val) => {
let opacity = val->Array.get(1)->Option.flatMap(a => a)->Option.getOr("0")
let newOpacity = opacity->Float.fromString->Option.getOr(0.0) /. 10.0
str->String.replace(opacity, newOpacity->Float.toString)
}
| None => "0"
}
}
type chartData<'a> = {
name: string,
color: string,
data: array<('a, float, option<float>)>,
legendIndex: int,
fillColor?: Highcharts.fillColorSeries,
}
let removeDuplicates = (arr: array<chartData<'a>>) => {
let uniqueItemsMap = Dict.make()
arr->Array.forEach(item => {
let value = item.name
if uniqueItemsMap->Dict.get(value)->Option.isNone {
uniqueItemsMap->Dict.set(value, item)
}
})
uniqueItemsMap->Dict.valuesToArray
}
let calculateOpacity = (~length, ~originalOpacity) => {
let reducedOpacity = originalOpacity *. Math.pow(0.4, ~exp=length->Int.toFloat /. 13.0)
// Calculate the reduced opacity based on the formula: originalOpacity * (0.4 ^ (length / 13))
Math.max(reducedOpacity, 0.0)->Float.toString
}
type dropDownMetricType = Latency | Volume | Rate | Amount | Traffic // traffic string can be any column which is of type Volume, Amount
type chartLegendStatsType =
| GroupBY
| Overall
| Average
| Current
| Emoji
| NO_COL
type legenedType = Heading | LegendData
type secondryMetrics = {
metric_name_db: string,
metric_label: string,
metric_type: dropDownMetricType,
}
type metricsConfig = {
metric_name_db: string,
metric_label: string,
metric_type: dropDownMetricType,
thresholdVal: option<float>,
step_up_threshold: option<float>,
legendOption?: (chartLegendStatsType, chartLegendStatsType),
secondryMetrics?: secondryMetrics,
disabled?: bool,
description?: string,
data_transformation_func?: Dict.t<JSON.t> => Dict.t<JSON.t>,
}
type legendTableData = {
groupByName: string,
overall: float,
average: float,
current: float,
index?: int,
}
let legendTypeBasedOnMetric = (metric_type: dropDownMetricType) => {
switch metric_type {
| Latency | Rate | Traffic => (Current, Average)
| Volume => (Overall, Average)
| Amount => (Average, Overall)
}
}
let appendToDictValue = (dict, key, value) => {
let updatedValue = switch dict->Dict.get(key) {
| Some(val) => Array.concat(val, [value])
| None => [value]
}
dict->Dict.set(key, updatedValue)
}
let addToDictValueFloat = (dict, key, value) => {
let updatedValue = switch dict->Dict.get(key) {
| Some(val) => val +. value
| None => value
}
dict->Dict.set(key, updatedValue)
}
let chartDataSortBasedOnTime = (
a: (float, float, option<float>),
b: (float, float, option<float>),
) => {
let (time, _, _) = a
let (timeb, _, _) = b
if time < timeb {
-1.
} else if time > timeb {
1.
} else {
0.
}
}
let sortBasedOnTimeLegend = (a: (string, float), b: (string, float)) => {
let (time, _) = a
let (timeb, _) = b
if time < timeb {
-1.
} else if time > timeb {
1.
} else {
0.
}
}
let sortBasedOnArr = arr => {
let func = (a: legendTableData, b: legendTableData) => {
if arr->Array.indexOf(a.groupByName) < arr->Array.indexOf(b.groupByName) {
-1.
} else if arr->Array.indexOf(a.groupByName) > arr->Array.indexOf(b.groupByName) {
1.
} else {
0.
}
}
func
}
let legendIndexFunc = (name: string) => {
let index = name === "Others" ? 30 : 0
index
}
type timeSeriesDictWithSecondryMetrics<'a> = {
color: option<string>,
name: string,
data: array<('a, float, option<float>)>,
legendIndex: int,
fillColor?: Highcharts.fillColorSeries,
}
let timeSeriesDataMaker = (
~data: array<JSON.t>,
~groupKey,
~xAxis,
~metricsConfig: metricsConfig,
~commonColors: option<array<chartData<'a>>>=?,
~selectedTab: option<array<string>>=?,
(),
) => {
let colors = switch commonColors {
| Some(value) => value
| None => []
}
let yAxis = metricsConfig.metric_name_db
let metrixType = metricsConfig.metric_type
let secondryMetrics = metricsConfig.secondryMetrics
let timeSeriesDict = Dict.make() // { name : groupByName, data: array<(value1, value2)>}
let groupedByTime = Dict.make() // {time : [values at that time]}
let _ = data->Array.map(item => {
let dict = item->getDictFromJsonObject
let groupByName = switch selectedTab {
| Some(keys) =>
keys
->Array.map(key =>
dict->getString(
key,
Dict.get(dict, key)->Option.getOr(""->JSON.Encode.string)->JSON.stringify,
)
)
->Array.map(LogicUtils.snakeToTitle)
->Array.joinWith(" : ")
| None =>
dict->getString(
groupKey,
Dict.get(dict, groupKey)->Option.getOr(""->JSON.Encode.string)->JSON.stringify,
)
}
let xAxisDataPoint = dict->getString(xAxis, "")->String.split(" ")->Array.joinWith("T") ++ "Z" // right now it is time string
let yAxisDataPoint = dict->getFloat(yAxis, 0.)
let secondryAxisPoint = switch secondryMetrics {
| Some(secondryMetrics) => Some(dict->getFloat(secondryMetrics.metric_name_db, 0.))
| None => None
}
if dict->getString(xAxis, "")->LogicUtils.isNonEmptyString {
timeSeriesDict->appendToDictValue(
groupByName,
(xAxisDataPoint->DateTimeUtils.parseAsFloat, yAxisDataPoint, secondryAxisPoint),
)
groupedByTime->addToDictValueFloat(
xAxisDataPoint->DateTimeUtils.parseAsFloat->Float.toString,
yAxisDataPoint,
)
}
})
let timeSeriesArr = timeSeriesDict->Dict.toArray
let chartOverlapping = timeSeriesArr->Array.length
let topGradient = calculateOpacity(~length=chartOverlapping, ~originalOpacity=0.50)
let bottomGradient = calculateOpacity(~length=chartOverlapping, ~originalOpacity=0.05)
timeSeriesArr->Array.mapWithIndex((item, index) => {
let (key, value) = item
let sortedValBasedOnTime = switch metrixType {
| Traffic =>
value
->Array.map(item => {
let (key, value, secondryMetrix) = item
let trafficValue =
value *. 100. /. groupedByTime->Dict.get(key->Float.toString)->Option.getOr(1.)
(key, trafficValue, secondryMetrix)
})
->Array.toSorted(chartDataSortBasedOnTime)
| _ => value->Array.toSorted(chartDataSortBasedOnTime)
}
let color = switch colors->Array.find(item => item.name == key) {
| Some(val) => val.color
| None => legendColor[mod(index, legendColor->Array.length)]->Option.getOr(defaultColor)
}
let fillColor = switch legendColorGradients(topGradient, bottomGradient)->Array.find(item =>
item.color->Option.getOr("#000000") == color
) {
| Some(val) => val
| None =>
legendColorGradients(topGradient, bottomGradient)[
mod(index, legendColor->Array.length)
]->Option.getOr(defaultLegendColorGradients(topGradient, bottomGradient))
}
let value: timeSeriesDictWithSecondryMetrics<float> = {
color: Some(color),
name: key,
data: sortedValBasedOnTime,
legendIndex: legendIndexFunc(key),
fillColor,
}
value
})
}
let getLegendDataForCurrentMetrix = (
~yAxis: string,
~timeSeriesData: array<JSON.t>,
~groupedData: array<JSON.t>,
~activeTab: string,
~xAxis: string,
~metrixType: dropDownMetricType,
) => {
let currentAvgDict = Dict.make()
let orderedDims = groupedData->Array.map(item => {
let dict = item->getDictFromJsonObject
getString(
dict,
activeTab,
Dict.get(dict, activeTab)->Option.getOr(""->JSON.Encode.string)->JSON.stringify,
)
})
timeSeriesData->Array.forEach(item => {
let dict = item->getDictFromJsonObject
let time_overall_statsAtTime = (getString(dict, xAxis, ""), getFloat(dict, yAxis, 0.)) // time_bucket // current value of the metrics will be used for calculation of avg and the current
currentAvgDict->appendToDictValue(
getString(
dict,
activeTab,
Dict.get(dict, activeTab)->Option.getOr(""->JSON.Encode.string)->JSON.stringify,
),
time_overall_statsAtTime,
)
})
let currentAvgSortedDict =
currentAvgDict
->Dict.toArray
->Array.map(item => {
let (key, value) = item
(key, value->Array.toSorted(sortBasedOnTimeLegend))
})
let currentValueOverallSum =
currentAvgSortedDict
->Array.map(item => {
let (_, value) = item
let (_, currentVal) = value->Array.get(value->Array.length - 1)->Option.getOr(("", 0.))
currentVal
})
->AnalyticsUtils.sumOfArrFloat
let currentAvgDict = if groupedData->Array.length === 0 {
currentAvgDict
->Dict.toArray
->Array.map(item => {
let (key, value) = item
let sortedValueBasedOnTime = value->Array.toSorted(sortBasedOnTimeLegend)
let arrLen = sortedValueBasedOnTime->Array.length
let (_, currentVal) = sortedValueBasedOnTime->Array.get(arrLen - 1)->Option.getOr(("", 1.0))
let overall =
sortedValueBasedOnTime
->Array.map(item => {
let (_, value) = item
value
})
->Array.reduce(0., (acc, value) => acc +. value)
let value: legendTableData = {
groupByName: key,
overall,
average: overall /. arrLen->Int.toFloat,
current: currentVal,
}
value
})
} else {
let currentOverall = Dict.make()
groupedData->Array.forEach(item => {
let dict = item->getDictFromJsonObject
currentOverall->Dict.set(getString(dict, activeTab, ""), getFloat(dict, yAxis, 0.))
})
let totalOverall =
currentOverall
->Dict.toArray
->Array.map(item => {
let (_, value) = item
value
})
->AnalyticsUtils.sumOfArrFloat
currentAvgDict
->Dict.toArray
->Array.map(item => {
let (metricsName, value) = item
let sortedValueBasedOnTime = value->Array.toSorted(sortBasedOnTimeLegend)
let arrLen = sortedValueBasedOnTime->Array.length
let (_, currentVal) = sortedValueBasedOnTime[arrLen - 1]->Option.getOr(("", 0.))
// the avg stat won't work correct for Sr case have to find another way or avoid using the avg for Sr
let overall = if metrixType === Traffic {
(currentOverall->Dict.get(metricsName)->Option.getOr(0.) *.
100. /.
Math.max(totalOverall, 1.))
->Float.toFixedWithPrecision(~digits=2)
->removeTrailingZero
->Float.fromString
->Option.getOr(0.)
} else {
currentOverall->Dict.get(metricsName)->Option.getOr(0.)
}
let currentVal = if metrixType === Traffic {
currentVal *. 100. /. currentValueOverallSum
} else {
currentVal
}
let value: legendTableData = {
groupByName: metricsName,
overall,
average: overall /. arrLen->Int.toFloat,
current: currentVal,
}
value
})
}
let sortBasedOnArr = sortBasedOnArr(orderedDims)
currentAvgDict
->Array.toSorted(sortBasedOnArr)
->Array.mapWithIndex((item, index) => {
{...item, index}
})
}
let barChartDataMaker = (~yAxis: string, ~rawData: array<JSON.t>, ~activeTab: string) => {
let value = rawData->Belt.Array.keepMap(item => {
let dict = item->getDictFromJsonObject
let selectedSegmentVal = getString(
dict,
activeTab,
Dict.get(dict, activeTab)->Option.getOr(""->JSON.Encode.string)->JSON.stringify,
) // groupby/ selected segment
let stats = getFloat(dict, yAxis, 0.) // overall metrics
selectedSegmentVal->LogicUtils.isNonEmptyString ? Some(selectedSegmentVal, stats) : None
})
let val: Highcharts.barChartSeries = {
color: "#4C8CFB",
data: value->Array.map(item => {
let (_, data) = item
data
}),
}
(
value->Array.map(item => {
let (categories, _) = item
categories
}),
[val],
)
}
let chartLegendTypeToStr = (chartLegendType: chartLegendStatsType) => {
switch chartLegendType {
| Overall => "Overall"
| Average => "Average"
| Current => "Current"
| _ => "" // this is not been used
}
}
let legendClickItem = (s: Highcharts.legendItem, e, setState) => {
open ReactEvent.Keyboard
e->preventDefault
// cases
// add the selected item in the array and update the array i.e
// if item is already present remove it from array
// if not add the item to the array
// whatever is there in selected array make it visible
// edge case when nothing is selected make everyone visible
Array.forEach(s.chart.series, x => {
if x === legendItemAsBool(s) {
setState(prev => {
let value =
prev->Array.includes(x) ? prev->Array.filter(item => item !== x) : Array.concat(prev, [x])
if value->Array.length === 0 {
Array.forEach(
s.chart.series,
y => {
y->Highcharts.show
},
)
} else {
Array.forEach(
s.chart.series,
y => {
value->Array.includes(y) ? y->Highcharts.show : y->Highcharts.hide
},
)
}
value
})
}
})
}
let formatStatsAccToMetrix = (metric: dropDownMetricType, value: float) => {
switch metric {
| Latency => latencyShortNum(~labelValue=value)
| Volume => shortNum(~labelValue=value, ~numberFormat=getDefaultNumberFormat())
| Rate | Traffic => value->Float.toFixedWithPrecision(~digits=2)->removeTrailingZero ++ "%"
| Amount => shortNum(~labelValue=value, ~numberFormat=getDefaultNumberFormat())
}
}
let formatLabels = (metric: metricsConfig, value: float) => {
let formattedValue = formatStatsAccToMetrix(metric.metric_type, value)
switch metric.thresholdVal {
| Some(val) =>
val === value
? `<span style="font-size: 11px; color: white; cursor: default; background-color: #EE6E73;padding: 2px 10px;border-radius: 10px; display: flex">
${formattedValue}
</span>`
: formattedValue
| None => formattedValue
}
}
let getTooltipHTML = (metrics, data, onCursorName, index, length) => {
let metric_type = metrics.metric_type
let (name, color, y_axis, secondry_metrix) = data
let secondry_metrix_val = switch metrics.secondryMetrics {
| Some(secondryMetrics) =>
`${formatStatsAccToMetrix(secondryMetrics.metric_type, secondry_metrix->Option.getOr(0.))}`
| None => ""
}
let spacing = index !== length - 1 ? "<tr style='height: 10px;'></tr>" : ""
let highlight = onCursorName == name ? "font-weight:900;font-size:13px;" : "opacity:60%;"
`<tr>
<td><span style='height:10px; width:10px;margin-top:5px;display:inline-block; background-color:${color};border-radius:3px;margin-right:3px;fontFamily:"Inter"'/></td>
<td><span style='${highlight};padding-right: 10px;'>${name->LogicUtils.snakeToTitle}</span></td>
<td><span style=${highlight}>${formatStatsAccToMetrix(metric_type, y_axis)}</span></td>
<td><span style=${highlight}>${secondry_metrix_val}</span></td>
</tr>
${spacing}`
}
let tooltipFormatter = (
metrics: metricsConfig,
xAxisMapInfo: Dict.t<array<(Js_string.t, string, float, option<float>)>>,
groupKey: string,
) => @this
(points: JSON.t) => {
let points = points->getDictFromJsonObject
let series = points->getJsonObjectFromDict("series")->getDictFromJsonObject
let dataArr = if ["run_date", "run_month", "run_week"]->Array.includes(groupKey) {
let x = points->getString("name", "")
xAxisMapInfo->Dict.get(x)->Option.getOr([])
} else {
let x = points->getFloat("x", 0.)
xAxisMapInfo->Dict.get(x->Float.toString)->Option.getOr([])
}
let onCursorName = series->getString("name", "")
let htmlStr =
dataArr
->Array.mapWithIndex((data, i) => {
getTooltipHTML(metrics, data, onCursorName, i, dataArr->Array.length)
})
->Array.joinWith("")
`<table>${htmlStr}</table>`
}
let legendItemStyle = legendFontSizeClass => {
{
"color": "rgba(53, 64, 82, 0.8)",
"cursor": "pointer",
"fontSize": legendFontSizeClass,
"fontWeight": "500",
"fontFamily": "Inter",
"fontStyle": "normal",
}->genericObjectOrRecordToJson
}
let legendHiddenStyle = (theme: ThemeProvider.theme) => (
legendFontFamilyClass,
legendFontSizeClass,
) => {
switch theme {
| Dark =>
{
"color": "#c7cad020",
"cursor": "pointer",
"fontSize": legendFontSizeClass,
"fontWeight": "500",
"fontFamily": legendFontFamilyClass,
"fontStyle": "normal",
}->genericObjectOrRecordToJson
| Light =>
{
"color": "rgba(53, 64, 82, 0.2)",
"cursor": "pointer",
"fontSize": legendFontSizeClass,
"fontWeight": "500",
"fontFamily": legendFontFamilyClass,
"fontStyle": "normal",
}->genericObjectOrRecordToJson
}
}
let chartTitleStyle = (theme: ThemeProvider.theme) => {
switch theme {
| Dark =>
{
"color": "#f6f8f9",
"fontSize": "13px",
"fontWeight": "500",
"fontStyle": "normal",
}->genericObjectOrRecordToJson
| Light =>
{
"color": "#474D59",
"fontSize": "16px",
"fontWeight": "500",
"fontStyle": "normal",
}->genericObjectOrRecordToJson
}
}
let getGranularityNew = (~startTime, ~endTime) => {
let diff =
(endTime->DateTimeUtils.parseAsFloat -. startTime->DateTimeUtils.parseAsFloat) /. (1000. *. 60.) // in minutes
// can be improved a lot we can have flexibitlity to show data 3 hour wise as well so some kind of adhoc logic we can have
// second | minute | hour | day | week | month
// less than 6 hour
if diff < 60. *. 6. {
[(15, "minute"), (5, "minute")]
} else if diff < 60. *. 24. {
// Smaller than 1 day
[(1, "hour"), (30, "minute"), (15, "minute")]
} else if diff < 60. *. 24. *. 7. {
// Smaller than 7 day
[(1, "day"), (3, "hour")]
} else if diff <= 60. *. 24. *. 62. {
// Smaller than 60 day
[(1, "week"), (1, "day")]
} else {
[(1, "week")]
}
}
let getGranularityNewStr = (~startTime, ~endTime) => {
getGranularityNew(~startTime, ~endTime)->Array.map(item => {
let (val, unit) = item
if val === 1 {
if unit === "day" {
"Daily"
} else if unit === "week" {
"Weekly"
} else if unit === "hour" {
"Hourly"
} else {
unit
}
} else {
`${val->Int.toString} ${unit}`
}
})
}
let chartDataMaker = (~filterNull=false, rawData, groupKey, metric) => {
let sortDescending = (obj1, obj2) => {
let (_key, val1) = obj1
let (_key, val2) = obj2
if val1 > val2 {
-1.
} else if val1 === val2 {
0.
} else {
1.
}
}
rawData
->Array.filter(dataPoint => {
!filterNull || {
let dataPointDict = dataPoint->getDictFromJsonObject
dataPointDict->getString(groupKey, "") !== "NA"
}
})
->Array.map(dataPoint => {
let dataPointDict = dataPoint->getDictFromJsonObject
(
dataPointDict->getString(groupKey, "")->String.toLowerCase->snakeToTitle,
dataPointDict->getString(metric, "")->Js.Float.fromString,
)
})
->Array.toSorted(sortDescending)
}
| 6,476 | 10,076 |
hyperswitch-control-center | src/components/CustomCharts/HighchartHorizontalBarChart.res | .res | module RawHBarChart = {
@react.component
let make = (~options: JSON.t) => {
<HighchartsHorizontalBarChart.HBarChart
highcharts={HighchartsHorizontalBarChart.highchartsModule} options
/>
}
}
open HighchartsHorizontalBarChart
let valueFormatter = (
@this
(this: tooltipRecord) => {
`<div class='text-white'>${this.category} count: <b>${this.y->Int.toString}</b></div>`
}
)->asTooltipPointFormatter
let dataLabelFormatter: yAxisRecord => string = (
@this
_param => {
""
}
)->asDataLabelFormatter
let xLabelFormatter: xAxisRecord => string = (
@this
param => {
let axis = param.axis
let series = axis.series
let value = param.value
let seriesSum =
series
->Array.map(series => {
let options = series.options
switch options {
| Some(options) => options.data
| None => []
}->Array.reduce(0, (acc, num) => {acc + num})
})
->Array.reduce(0, (acc, num) => {acc + num})
let index = Array.findIndex(axis.categories, x => {x === value})
let firstSeries = series->Array.get(0)
let y = switch firstSeries {
| Some(series) => {
let options = series.options
switch options {
| Some(options) => options.data->Array.get(index)->Option.getOr(0)
| None => 0
}
}
| None => 0
}
`<div style="display: inline-block; margin-left: 10px;" class="text-black dark:text-white"><div class="font-semibold"> ${value} </div><div class="font-medium" style="display: inline-block;">` ++
(y->Float.fromInt *. 100. /. seriesSum->Float.fromInt)
->Float.toFixedWithPrecision(~digits=2) ++ `%</div></div>`
}
)->asXLabelFormatter
@react.component
let make = (
~rawData: array<JSON.t>,
~groupKey,
~titleKey=?,
~selectedMetrics: LineChartUtils.metricsConfig,
) => {
let {theme} = React.useContext(ThemeProvider.themeContext)
let barChartData = React.useMemo(() => {
LineChartUtils.chartDataMaker(
~filterNull=true,
rawData,
groupKey,
selectedMetrics.metric_name_db,
)
}, (rawData, groupKey, selectedMetrics.metric_name_db))
let titleKey = titleKey->Option.getOr(groupKey)
let barOption: JSON.t = React.useMemo(() => {
let colors = {
let length = barChartData->Array.length->Int.toFloat
barChartData->Array.mapWithIndex((_data, i) => {
let i = i->Int.toFloat
let opacity = (length -. i +. 1.) /. (length +. 1.)
`rgb(0,109,249,${opacity->Float.toString})`
})
}
let defaultOptions: HighchartsHorizontalBarChart.options = {
title: {
text: `<div class='font-semibold text-lg font-inter-style text-black dark:text-white'>${titleKey->LogicUtils.snakeToTitle}</div>`,
align: "Left",
useHTML: true,
},
subtitle: {
text: `<div class='font-medium text-sm font-inter-style text-jp-gray-800 dark:text-dark_theme'>Distribution across ${titleKey->LogicUtils.snakeToTitle}s</div>`,
align: "Left",
useHTML: true,
},
series: [
{
name: `${titleKey->LogicUtils.snakeToTitle} Share`,
data: barChartData->Array.map(data => {
let (_, y) = data
y
}),
\"type": "bar",
},
],
plotOptions: Some({
bar: {
dataLabels: {
enabled: true,
formatter: dataLabelFormatter,
useHTML: true,
},
colors,
colorByPoint: true,
borderColor: theme === Dark ? "black" : "white",
},
}),
credits: {enabled: false},
tooltip: {
pointFormatter: valueFormatter,
useHTML: true,
backgroundColor: "rgba(25, 26, 26, 1)",
borderColor: "rgba(25, 26, 26, 1)",
headerFormat: "",
},
chart: {
\"type": "bar",
backgroundColor: theme === Dark ? "#202124" : "white",
},
xAxis: {
categories: barChartData->Array.map(data => {
let (x, _) = data
x
}),
lineWidth: 0,
opposite: true,
labels: {
enabled: true,
formatter: xLabelFormatter,
useHTML: true,
},
},
yAxis: {
min: 0,
title: {
text: "category",
},
labels: {
enabled: false,
},
gridLineWidth: 0,
visible: false,
},
legend: {
enabled: false,
},
}
defaultOptions->Identity.genericTypeToJson
}, (barChartData, theme))
<RawHBarChart options=barOption />
}
| 1,192 | 10,077 |
hyperswitch-control-center | src/components/CustomCharts/HighchartPieChart.res | .res | %%raw(`require("./highcharts.css")`)
module RawPieChart = {
@react.component
let make = (~options: JSON.t) => {
<HighchartsPieChart.PieChart highcharts={HighchartsPieChart.highchartsModule} options />
}
}
open HighchartsPieChart
let valueFormatter = (
@this
(this: tooltipRecord) => {
`<div class='text-white'>${this.name} count: <b>${this.y->Int.toString}</b></div>`
}
)->asTooltipPointFormatter
let formatter: yAxisRecord => string =
(
@this
param =>
`<div class="font-semibold text-black dark:text-white">` ++
param.point.name ++
`</div><br><div class="font-medium text-black dark:text-white">` ++
param.point.percentage->Float.toFixedWithPrecision(~digits=2) ++ `%</div>`
)->asDataLabelFormatter
@react.component
let make = (
~rawData: array<JSON.t>,
~groupKey,
~titleKey=?,
~selectedMetrics: LineChartUtils.metricsConfig,
) => {
let {theme} = React.useContext(ThemeProvider.themeContext)
let pieSeriesData = React.useMemo(() => {
LineChartUtils.chartDataMaker(
~filterNull=true,
rawData,
groupKey,
selectedMetrics.metric_name_db,
)
}, (rawData, groupKey, selectedMetrics.metric_name_db))
let color = theme === Dark ? "white" : "black"
let borderColor = theme === Dark ? "black" : "white"
let opacity = theme === Dark ? "0.5" : "1"
let titleKey = titleKey->Option.getOr(groupKey)
let barOption: JSON.t = React.useMemo(() => {
let colors = {
let length = pieSeriesData->Array.length->Int.toFloat
pieSeriesData->Array.mapWithIndex((_data, i) => {
let i = i->Int.toFloat
let opacity = (length -. i +. 1.) /. (length +. 1.)
`rgb(0,109,249,${opacity->Float.toString})`
})
}
let defaultOptions: HighchartsPieChart.options = {
title: {
text: `<div class='font-semibold text-lg font-inter-style text-black dark:text-white'>${titleKey->LogicUtils.snakeToTitle}</div>`,
align: "Left",
useHTML: true,
},
subtitle: {
text: `<div class='font-medium text-sm font-inter-style text-jp-gray-800 dark:text-dark_theme'>Distribution across ${titleKey->LogicUtils.snakeToTitle}s</div>`,
align: "Left",
useHTML: true,
},
series: [
{
\"type": "pie",
name: `${titleKey->LogicUtils.snakeToTitle} Share`,
innerSize: "58%",
data: pieSeriesData,
},
],
plotOptions: Some({
pie: {
dataLabels: {
enabled: true,
connectorShape: "straight",
formatter,
style: {
color,
opacity,
},
useHTML: true,
},
startAngle: -90,
endAngle: 90,
center: ["50%", "75%"],
size: "100%",
colors,
borderColor,
},
}),
credits: {enabled: false},
tooltip: {
pointFormatter: valueFormatter,
useHTML: true,
backgroundColor: "rgba(25, 26, 26, 1)",
borderColor: "rgba(25, 26, 26, 1)",
headerFormat: "",
},
chart: {
backgroundColor: theme === Dark ? "#202124" : "white",
},
}
defaultOptions->Identity.genericTypeToJson
}, (pieSeriesData, theme))
<RawPieChart options=barOption />
}
| 878 | 10,078 |
hyperswitch-control-center | src/components/CustomCharts/highcharts.css | .css | .highcharts-data-label-connector {
stroke-dasharray: 2, 2;
stroke: #151a1f;
opacity: 0.3;
stroke-width: 2px;
}
| 47 | 10,079 |
hyperswitch-control-center | src/components/CustomCharts/HighchartBarChart.res | .res | module RawBarChart = {
@react.component
let make = (~options: JSON.t) => {
<Highcharts.BarChart highcharts={Highcharts.highchartsModule} options />
}
}
module HighBarChart1D = {
@react.component
let make = (
~rawData: array<JSON.t>,
~groupKey,
~isHrizonatalBar: bool=true,
~selectedMetrics: LineChartUtils.metricsConfig,
) => {
let {theme} = React.useContext(ThemeProvider.themeContext)
let gridLineColor = switch theme {
| Light => "#2e2f39"
| Dark => "#e6e6e6"
}
let (categories, barSeries) = React.useMemo(() => {
LineChartUtils.barChartDataMaker(
~rawData,
~activeTab=groupKey,
~yAxis=selectedMetrics.metric_name_db,
)
}, (rawData, groupKey, selectedMetrics.metric_name_db))
let barOption: JSON.t = React.useMemo(() => {
let barOption: JSON.t = {
"chart": Highcharts.makebarChart(
~chartType={isHrizonatalBar ? "bar" : "column"},
~backgroundColor=Nullable.null,
(),
),
"title": {
"text": "",
"style": JSON.Encode.object(Dict.make()),
},
"xAxis": {
"categories": categories,
},
"yAxis": {
"gridLineColor": gridLineColor,
"title": {"text": selectedMetrics.metric_label},
"labels": {
"formatter": Some(
@this
(param: Highcharts.yAxisRecord) =>
LineChartUtils.formatLabels(selectedMetrics, param.value),
),
}->Some,
},
"credits": {
"enabled": false,
},
"series": barSeries,
"legend": {"enabled": false},
}->Identity.genericObjectOrRecordToJson
barOption
}, (barSeries, gridLineColor))
if barSeries->Array.length > 0 {
<RawBarChart options=barOption />
} else {
React.null
}
}
}
| 474 | 10,080 |
hyperswitch-control-center | src/components/CustomCharts/HighchartTimeSeriesChart.res | .res | open Highcharts
open LogicUtils
open DictionaryUtils
module TooltipString = {
@react.component
let make = (~text, ~showTableBelow) => {
let isMobileView = MatchMedia.useMobileChecker()
let class = showTableBelow ? "w-fit" : "w-20"
if text->String.length > 15 && !showTableBelow {
<ToolTip
contentAlign=Left
description=text
toolTipPosition={isMobileView ? TopRight : Top}
tooltipWidthClass={isMobileView ? "w-fit" : ""}
toolTipFor={<div className={`whitespace-pre text-ellipsis overflow-x-hidden w-15`}>
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(`${String.slice(~start=0, ~end=12, text)}...`)} </div>
</AddDataAttributes>
</div>}
/>
} else {
<div className={`whitespace-pre text-ellipsis ${class}`}>
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
</div>
}
}
}
type legendType = Table | Points
module LineChart1D = {
open Identity
@react.component
let make = (
~class: string="",
~rawChartData: array<JSON.t>,
~selectedMetrics: LineChartUtils.metricsConfig,
~commonColorsArr: array<LineChartUtils.chartData<'a>>=[],
~chartPlace="",
~xAxis: string,
~groupKey: string,
~chartTitle: bool=false,
~chartTitleText: string="",
~showLegend: bool=false,
~chartType="area",
~showTableLegend: bool=true,
~legendType: legendType=Table,
~isMultiDimensional: bool=false,
~chartKey: string="0",
~legendData: array<JSON.t>=[],
~chartdataMaxRows: int=-1,
~selectedRow=None,
~showTableBelow: bool=false,
~gradient: bool=true,
~isPartners=false,
~showIndicator=false,
~showMarkers=false,
~comparitionWidget=false,
~selectedTab: option<array<string>>=?,
) => {
let {theme} = React.useContext(ThemeProvider.themeContext)
let (_, setLegendState) = React.useState(_ => [])
let isMobileView = MatchMedia.useMobileChecker()
let (hideLegend, setHideLegend) = React.useState(_ => isMobileView)
let (fistLegend, secondLegend) = switch selectedMetrics {
| {legendOption} =>
legendData->Array.length > 0
? legendOption
: LineChartUtils.legendTypeBasedOnMetric(selectedMetrics.metric_type)
| _ => LineChartUtils.legendTypeBasedOnMetric(selectedMetrics.metric_type)
}
let (clickedRowNames, setClickedRowNamesOrig) = React.useState(_ => [])
let (hoverOnRows, setHoverOnRows) = React.useState(_ => None)
let chartHeight = isMobileView ? 250 : 400
let setClickedRowNames = React.useMemo(() => {
(legendData: LineChartUtils.legendTableData) => {
setClickedRowNamesOrig(prev => {
prev->Array.includes(legendData.groupByName)
? prev->Array.filter(item => item !== legendData.groupByName)
: [legendData.groupByName]
})
}
}, [setClickedRowNamesOrig])
let (chartData, xAxisMapInfo, chartDataOrig) = React.useMemo(() => {
let chartdata: array<
LineChartUtils.timeSeriesDictWithSecondryMetrics<JSON.t>,
> = LineChartUtils.timeSeriesDataMaker(
~data=rawChartData,
~groupKey,
~xAxis,
~metricsConfig=selectedMetrics,
~commonColors=commonColorsArr,
~selectedTab=selectedTab->Option.getOr([]),
(),
)->Belt.Array.keepMap(item => {
if (
["run_date", "run_month", "run_week"]->Array.includes(groupKey) && item.name === "Others"
) {
None
} else {
Some({
...item,
data: item.data->Array.map(
dataItem => {
let (xAxis, yAxis, xY) = dataItem
let updatedXAxis = if "run_date" === groupKey {
`0${xAxis
->Js.Date.fromFloat
->DateTimeUtils.toUtc
->Js.Date.getHours
->Float.toString}:00`
->String.sliceToEnd(~start=-5)
->JSON.Encode.string
} else if "run_month" === groupKey {
xAxis
->Js.Date.fromFloat
->DateTimeUtils.toUtc
->Js.Date.getDate
->Float.toString
->JSON.Encode.string
} else if "run_week" === groupKey {
switch DateTimeUtils.daysArr[
xAxis->Js.Date.fromFloat->DateTimeUtils.toUtc->Js.Date.getDay->Float.toInt
] {
| Some(ele) => DateTimeUtils.dayMapper(ele)
| None => ""
}->JSON.Encode.string
} else {
xAxis->JSON.Encode.float
}
(updatedXAxis, yAxis, xY)
},
),
})
}
})
let chartDataOrig = chartdata
let selectedChartData = switch selectedRow {
| Some(data: LineChartUtils.chartData<JSON.t>) =>
chartdata->Array.filter(item => data.name == item.name)
| None =>
clickedRowNames->Array.length > 0
? chartdata->Array.filter(item => clickedRowNames->Array.includes(item.name))
: chartdata
}
let xAxisMapInfo = Dict.make()
selectedChartData->Array.forEach(item => {
item.data->Array.forEach(
axes => {
let (x, y, secondryMetrics) = axes
xAxisMapInfo->LineChartUtils.appendToDictValue(
["run_date", "run_month", "run_week"]->Array.includes(groupKey)
? x->JSON.Decode.string->Option.getOr("")
: x->JSON.stringify,
(
item.name,
{
item.color->Option.getOr("#000000")
},
y,
secondryMetrics,
),
)
},
)
})
let data = if clickedRowNames->Array.length === 0 {
switch hoverOnRows {
| Some(hoverOnRows) =>
chartdata->Array.map(item => {
let color = switch item.color {
| Some(color) => Some(item.name !== hoverOnRows ? `${color}20` : color)
| None => None
}
let fillColor = switch item.fillColor {
| Some(color) =>
Some(
item.name !== hoverOnRows
? {
let ((c1, f1), (c2, f2)) = color.stops
{
...color,
stops: (
(c1, LineChartUtils.reduceOpacity(f1)),
(c2, LineChartUtils.reduceOpacity(f2)),
),
}
}
: color,
)
| None => None
}
{
...item,
color,
?fillColor,
}
})
| None => selectedChartData
}
} else {
selectedChartData
}
let chartData = data->Belt.Array.keepMap(chartDataItem => {
let (fillColor, color) = (chartDataItem.fillColor, chartDataItem.color) // normal
//always uses same color for same entity Upi live mode
let val: option<seriesLine<JSON.t>> = if (
!(clickedRowNames->Array.includes(chartDataItem.name)) &&
clickedRowNames->Array.length > 0
) {
None
} else {
let value: Highcharts.seriesLine<JSON.t> = {
color,
name: chartDataItem.name,
data: chartDataItem.data->Array.map(
item => {
let (x, y, _) = item
(x, y->Nullable.make)
},
),
legendIndex: chartDataItem.legendIndex,
}
Some({...value, ?fillColor})
}
val
})
(chartData, xAxisMapInfo, chartDataOrig)
}, (xAxis, selectedMetrics, rawChartData, groupKey, clickedRowNames, hoverOnRows, selectedRow))
let chartData = if chartdataMaxRows !== -1 {
chartData->Array.slice(~start=0, ~end=chartdataMaxRows)
} else {
chartData
}
let legendData = React.useMemo(() => {
let data = LineChartUtils.getLegendDataForCurrentMetrix(
~yAxis=selectedMetrics.metric_name_db,
~xAxis,
~timeSeriesData=rawChartData,
~groupedData=legendData,
~metrixType=selectedMetrics.metric_type,
~activeTab=groupKey,
)->Belt.Array.keepMap(item => {
if (
["run_date", "run_month", "run_week"]->Array.includes(groupKey) &&
item.groupByName === "Others"
) {
None
} else {
Some(item)
}
})
if chartdataMaxRows !== -1 {
data->Array.slice(~start=0, ~end=chartdataMaxRows)
} else {
data
}
}, (selectedMetrics, rawChartData, groupKey, xAxis, legendData))
let getCell = (
transactionTable: LineChartUtils.legendTableData,
colType: LineChartUtils.chartLegendStatsType,
): Table.cell => {
let formatter = value => {
LineChartUtils.formatStatsAccToMetrix(selectedMetrics.metric_type, value)
}
let colorOrig =
chartDataOrig
->Belt.Array.keepMap(item => {
switch item.color {
| Some(color) => transactionTable.groupByName === item.name ? Some(color) : None
| None => None
}
})
->Array.get(0)
->Option.getOr("")
let color =
chartData
->Belt.Array.keepMap(item => {
switch item.color {
| Some(color) => transactionTable.groupByName === item.name ? Some(color) : None
| None => None
}
})
->Array.get(0)
->Option.getOr(`${colorOrig}`)
let transformValue = num => {
num->HSAnalyticsUtils.setPrecision
}
let (nonSelectedClass, backgroundColor) =
clickedRowNames->Array.length === 0 ||
clickedRowNames->Array.includes(transactionTable.groupByName)
? ("", `${color}`)
: ("opacity-40", `${color}50`)
switch colType {
| GroupBY =>
CustomCell(
<div className="flex items-stretch justify-start select-none">
<span
className={`flex h-3 w-3 rounded-full self-center mr-2`}
style={backgroundColor: backgroundColor}
/>
<span className={`flex justify-self-start ${nonSelectedClass}`}>
<TooltipString text=transactionTable.groupByName showTableBelow />
</span>
</div>,
transactionTable.groupByName,
)
| Overall =>
let value = transactionTable.overall->transformValue->formatter
CustomCell(
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className=nonSelectedClass> {React.string(value)} </div>
</AddDataAttributes>,
value,
)
| Average =>
let value = transactionTable.average->transformValue->formatter
CustomCell(
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className=nonSelectedClass> {React.string(value)} </div>
</AddDataAttributes>,
value,
)
| Current =>
let value = transactionTable.current->transformValue->formatter
CustomCell(
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className=nonSelectedClass> {React.string(value)} </div>
</AddDataAttributes>,
value,
)
| Emoji =>
CustomCell(
{
if (
!(transactionTable.groupByName->String.includes("Mid")) && isPartners && showIndicator
) {
<div className="flex items-stretch justify-start">
{if transactionTable.current < 20. {
<div className="flex items-stretch justify-start">
<Icon name="sad-tear" className="text-red-500" size=18 />
</div>
} else if transactionTable.current < 40. {
<Icon name="sad-tear" className="text-red-100" size=18 />
} else if transactionTable.current < 50. {
<Icon name="sad-tear" className="text-red-100" size=18 />
} else if transactionTable.current < 60. {
<Icon name="smile" className="text-green-200" size=18 />
} else if transactionTable.current < 90. {
<Icon name="smile" className="text-green-500" size=18 />
} else {
<Icon name="smile" className="text-green-700" size=18 />
}}
</div>
} else {
React.null
}
},
transactionTable.groupByName,
)
| NO_COL =>
CustomCell(
{
React.null
},
transactionTable.groupByName,
)
}
}
let getHeading = (colType: LineChartUtils.chartLegendStatsType) => {
switch colType {
| GroupBY =>
Table.makeHeaderInfo(~key="groupByName", ~title=snakeToTitle(groupKey), ~dataType=LabelType)
| val =>
Table.makeHeaderInfo(
~key=val->LineChartUtils.chartLegendTypeToStr->String.toLowerCase,
~title=val->LineChartUtils.chartLegendTypeToStr,
~dataType=NumericType,
)
}
}
let defaultSort: Table.sortedObject = {
key: "index",
order: Table.DEC,
}
open LineChartUtils
let legendTableEntity = EntityType.makeEntity(
~defaultColumns=[GroupBY, fistLegend, secondLegend],
~allColumns=[GroupBY, fistLegend, secondLegend],
~getCell,
~getHeading,
~uri="",
~getObjects=_ => {[]},
)
let {isSidebarExpanded} = React.useContext(SidebarProvider.defaultContext)
React.useEffect(() => {
setTimeout(_ => {
DOMUtils.window->DOMUtils.dispatchEvent(DOMUtils.event("resize"))
}, 150)->ignore
None
}, [isSidebarExpanded])
let options = React.useMemo(() => {
let chartTitleStyle = chartTitleStyle(theme)
let thresholdVal = selectedMetrics.thresholdVal
let stepUpFromThreshold = selectedMetrics.step_up_threshold
let legend = switch legendType {
| Table =>
{
"enabled": {isMobileView ? false : showLegend},
}->genericObjectOrRecordToJson
| Points =>
{
"enabled": !isMultiDimensional,
"itemStyle": legendItemStyle("12px"),
"itemHiddenStyle": legendHiddenStyle(theme),
"itemHoverStyle": legendItemStyle("12px"),
"symbolRadius": 4,
"symbolPaddingTop": 5,
"itemMarginBottom": 10,
}->genericObjectOrRecordToJson
}
let a: options<JSON.t> = {
chart: {
Some(
{
"type": chartType,
"margin": None,
"zoomType": "x",
"backgroundColor": Nullable.null,
"height": Some(chartHeight),
"events": {
render: () => {
let this = thisChartEventOnLoad
let strokeColor = switch theme {
| Dark => "#2e2f39"
| Light => "#e6e6e6"
}
switch this.yAxis[0] {
| Some(ele) =>
Highcharts.objectEach(ele.ticks, tick => {
if Some(tick.pos) === thresholdVal {
tick.gridLine.attr(
{
"stroke-width": "0",
}->genericObjectOrRecordToJson,
)
} else {
tick.gridLine.attr(
{
"stroke": strokeColor,
}->genericObjectOrRecordToJson,
)
}
})
| None => ()
}
},
}->Some,
}->genericObjectOrRecordToJson,
)
},
title: {
"text": chartTitle ? chartTitleText : "",
"style": chartTitleStyle,
}->genericObjectOrRecordToJson,
credits: {
"enabled": false,
},
legend,
tooltip: {
"shared": false,
"enabled": true,
"useHTML": true,
"formatter": tooltipFormatter(selectedMetrics, xAxisMapInfo, groupKey)->Some,
"hideDelay": 0,
"outside": true,
"borderRadius": 20,
"backgroundColor": "#ffffff",
"borderColor": "#E5E5E5",
"shadow": {
"color": "rgba(0, 0, 0, 0.15)",
"offsetX": 0,
"offsetY": 0,
"opacity": 0.07,
"width": 10,
},
"style": {
"color": "#333333",
},
}->genericObjectOrRecordToJson,
plotOptions: Some(
{
"area": {
"pointStart": None,
"fillColor": None,
"fillOpacity": 0.,
"states": {
"hover": {
"lineWidth": 1.,
},
},
"lineWidth": 1.2,
"threshold": Nullable.null,
}->genericObjectOrRecordToJson,
"line": {
"pointStart": None,
"fillColor": None,
"fillOpacity": 0.,
"states": {
"hover": {
"lineWidth": 1.,
},
},
"lineWidth": 1.2,
"threshold": Nullable.null,
}->genericObjectOrRecordToJson,
"boxplot": {
"visible": false,
},
"series": {
"marker": {
"enabled": Some(showMarkers),
"radius": Some(showMarkers ? 5 : 1),
"symbol": Some("circle"),
},
"states": Some({
"hover": Some({
"enabled": Some(true),
"halo": Some({
"size": Some(10),
}),
}),
}),
"events": Some({
"legendItemClick": Some(
@this
(s: legendItem, e: ReactEvent.Keyboard.t) => {
legendClickItem(s, e, setLegendState)
},
),
"mouseOver": None,
}),
}->genericObjectOrRecordToJson,
}->genericObjectOrRecordToJson,
),
xAxis: {
let defaultValue = {
"type": "datetime",
}->genericObjectOrRecordToJson
let defaultValue = if ["run_date", "run_month", "run_week"]->Array.includes(groupKey) {
{
"type": "category",
"tickWidth": 0,
}->genericObjectOrRecordToJson
} else {
defaultValue
}
defaultValue
},
yAxis: {
"gridLineWidth": 1,
"tickWidth": 0,
"min": 0.,
"gridLineColor": "#DDE3EE",
"gridLineDashStyle": "Dot",
"tickPositioner": Some(
@this
param => {
let positions = switch thresholdVal {
| Some(threshold) => {
let upper_bound = param.dataMax
let lower_bound = 0.
let upper_bound =
upper_bound <= threshold
? threshold +. stepUpFromThreshold->Option.getOr(0.)
: upper_bound
let lower_bound =
lower_bound >= threshold
? threshold -. stepUpFromThreshold->Option.getOr(0.)
: lower_bound
let positions = NumericUtils.pretty([lower_bound, upper_bound], 5)
let positionArr =
Array.concat(positions, [threshold])->Array.toSorted(numericArraySortComperator)
positionArr
}
| None => NumericUtils.pretty([0., param.dataMax], 5)
}
//NOTE have to implment the NumericUtils.pretty perfactly to make it work
positions
},
),
"plotLines": [
{
label: {
align: "right"->Some,
style: {
color: "blue"->Some,
fontWeight: "bold"->Some,
background: "red"->Some,
}->Some,
}->Some,
dashStyle: "Dash"->Some,
value: thresholdVal,
width: 1->Some,
color: "#ff0000"->Some,
},
]->Some,
"visible": true,
"title": {
"text": "",
"style": chartTitleStyle,
}->genericObjectOrRecordToJson,
"labels": {
let labelsValue = {
"formatter": Some(
@this param => formatLabels(selectedMetrics, param.value->Option.getOr(0.0)),
),
"enabled": true,
"style": {
"fontFamily": "Inter",
"fontSize": "12px",
"fontStyle": "normal",
"fontWeight": 500,
"lineHeight": "20px",
"letterSpacing": "1px",
"color": theme === Light ? "#4B5468" : "rgba(246, 248, 249, 0.25)",
},
}->genericObjectOrRecordToJson
labelsValue->getDictFromJsonObject->deleteKey("style")->JSON.Encode.object
},
}->genericObjectOrRecordToJson,
series: chartData,
}
a
}, (chartData, selectedMetrics, theme, isMobileView))
let (offset, setOffset) = React.useState(_ => 0)
let (flexClass, tableWidth, chartWidth) = if showTableBelow || isMobileView {
("flex flex-col", "w-full", "w-full")
} else {
("flex flex-row", "w-1/5", "w-4/5")
}
if chartData->Array.length > 0 {
<div className={isMobileView ? "w-full" : isMultiDimensional ? "w-1/3" : ""}>
<div className={`${flexClass} ${class} px-4 pb-3`}>
<AddDataAttributes attributes=[("data-chart", chartTitleText)]>
<div className={showTableLegend ? chartWidth : "w-full"}>
<HighchartsReact highcharts={highchartsModule} options key={chartKey} />
</div>
</AddDataAttributes>
<RenderIf condition={showTableLegend && isMobileView}>
<div
className="flex flex-row items-center gap-2 w-fit self-end cursor-pointer mr-5 mb-2"
onClick={_ => {setHideLegend(prev => !prev)}}>
<Icon
name={hideLegend ? "collpase-alt" : "expand-alt"}
size=12
className="text-neutral-400"
/>
</div>
</RenderIf>
{if showTableLegend && !hideLegend {
<div className={`${tableWidth} pl-5 pt-0 min-w-max`}>
<LoadedTable
visibleColumns={isPartners
? [GroupBY, fistLegend, secondLegend, Emoji]
: [GroupBY, fistLegend, secondLegend]}
title="High Chart Time Series Chart"
hideTitle=true
actualData={legendData->Array.map(Nullable.make)}
entity=legendTableEntity
resultsPerPage=15
totalResults={legendData->Array.length}
offset
setOffset
defaultSort
showPagination=false
currrentFetchCount={legendData->Array.length}
onEntityClick={val => {
setClickedRowNames(val)
}}
onEntityDoubleClick={_val => {
setClickedRowNamesOrig(_ => [])
clickedRowNames->Array.length > 0 ? setHoverOnRows(_ => None) : ()
}}
onMouseEnter={val => {
clickedRowNames->Array.length === 0
? setHoverOnRows(_ => Some(val.groupByName))
: ()
}}
onMouseLeave={_val => {
clickedRowNames->Array.length === 0 ? setHoverOnRows(_ => None) : ()
}}
isHighchartLegend=true
showTableOnMobileView=true
/>
</div>
} else {
React.null
}}
</div>
</div>
} else {
React.null
}
}
}
module LegendItem = {
@react.component
let make = (
~chartNames,
~selectedRow: option<LineChartUtils.chartData<'a>>,
~setSelectedRow: (
option<LineChartUtils.chartData<'a>> => option<LineChartUtils.chartData<'a>>
) => unit,
) => {
let opacity = name =>
switch selectedRow {
| Some(val) => val.name !== name ? "opacity-40" : ""
| None => ""
}
<div className="flex flex-row m-5 gap-6 font-inter-style mobile:flex-wrap">
{LineChartUtils.removeDuplicates(chartNames)
->Array.map(legendItem => {
let opacity = opacity(legendItem.name)
<AddDataAttributes attributes=[("data-chart-legend", legendItem.name)]>
<div
className={`flex flex-row gap-2 justify-center items-center cursor-pointer ${opacity} select-none`}
onDoubleClick={_ => selectedRow->Option.isSome ? setSelectedRow(_ => None) : ()}
onClick={_ =>
setSelectedRow(prev => {
switch prev {
| Some(val) => val.name === legendItem.name ? None : Some(legendItem)
| None => Some(legendItem)
}
})}>
<div
className={`w-[0.9375rem] h-[0.9375rem] rounded`} style={background: legendItem.color}
/>
<div className="font-medium text-fs-14 text-[#3B424F]">
{React.string(legendItem.name)}
</div>
</div>
</AddDataAttributes>
})
->React.array}
</div>
}
}
module RenderMultiDimensionalChart = {
type config = {
chartDictData: Dict.t<array<JSON.t>>,
class: string,
selectedMetrics: LineChartUtils.metricsConfig,
groupBy: string,
xAxis: string,
chartKey: string,
legendType: legendType,
chartType: string,
}
@react.component
let make = (~config: config) => {
let (selectedRow, setSelectedRow) = React.useState(_ => None)
let chartNames =
config.chartDictData
->Dict.toArray
->Array.reduce([], (acc: array<LineChartUtils.chartData<JSON.t>>, (_, value)) => {
let chartdata = LineChartUtils.timeSeriesDataMaker(
~data=value,
~groupKey=config.groupBy,
~xAxis=config.xAxis,
~metricsConfig=config.selectedMetrics,
(),
)
chartdata
->Array.map(i =>
acc->Array.push({
data: i.data->Array.map(
item => {
let (val1, val2, val3) = item
(val1->JSON.Encode.float, val2, val3)
},
),
legendIndex: i.legendIndex,
name: i.name,
color: i.color->Option.getOr("#000000"),
})
)
->ignore
acc
})
<div className="flex flex-col">
<LegendItem chartNames selectedRow setSelectedRow />
<div className="flex flex-wrap">
{
let chartArr = {
config.chartDictData
->Dict.toArray
->Array.mapWithIndex((item, index) => {
let (key, value) = item
<LineChart1D
key={index->Int.toString}
class=config.class
rawChartData=value
commonColorsArr={LineChartUtils.removeDuplicates(chartNames)}
selectedMetrics=config.selectedMetrics
xAxis=config.xAxis
groupKey=config.groupBy
chartTitle=true
chartTitleText=key
showTableLegend=false
showLegend=false
legendType=config.legendType
isMultiDimensional=true
chartKey=config.chartKey
selectedRow={selectedRow}
chartType=config.chartType
/>
})
}
chartArr->React.array
}
</div>
</div>
}
}
module LineChart2D = {
@react.component
let make = (
~groupBy: option<array<string>>,
~rawChartData: array<JSON.t>,
~selectedMetrics: LineChartUtils.metricsConfig,
~xAxis: string,
~legendType=Points,
~class="",
~chartKey: string="0",
~chartType: string="area",
) => {
let (groupBy1, groupBy2) = switch groupBy {
| Some(value) => (value->Array.get(0)->Option.getOr(""), value->Array.get(1)->Option.getOr(""))
| None => ("", "")
}
let (groupBy1, groupBy2) = (groupBy2, groupBy1)
let chartDictData = Dict.make()
rawChartData->Array.forEach(item => {
let dict = item->getDictFromJsonObject
let groupBy = dict->getString(groupBy1, "")
let groupBy = groupBy->LogicUtils.isEmptyString ? "NA" : groupBy
chartDictData->LineChartUtils.appendToDictValue(groupBy, item)
})
let compProps: RenderMultiDimensionalChart.config = {
chartDictData,
class,
selectedMetrics,
groupBy: groupBy2,
xAxis,
chartKey,
legendType,
chartType,
}
<RenderMultiDimensionalChart config={compProps} />
}
}
module LineChart3D = {
@react.component
let make = (
~groupBy: option<array<string>>,
~rawChartData: array<JSON.t>,
~selectedMetrics: LineChartUtils.metricsConfig,
~xAxis: string,
~legendType=Points,
~class="",
~chartKey: string="0",
~chartType: string="area",
) => {
let (groupBy1, groupBy2, groupby3) = switch groupBy {
| Some(value) => (
value->Array.get(0)->Option.getOr(""),
value->Array.get(1)->Option.getOr(""),
value->Array.get(2)->Option.getOr(""),
)
| None => ("", "", "")
}
let (groupBy1, groupBy2, groupby3) = (groupBy2, groupby3, groupBy1)
let chartDictData = Dict.make()
rawChartData->Array.forEach(item => {
let dict = item->getDictFromJsonObject
let groupBy1 = dict->getString(groupBy1, "")
let groupBy1 = groupBy1->LogicUtils.isEmptyString ? "NA" : groupBy1
let groupBy2 = dict->getString(groupBy2, "")
let groupBy2 = groupBy2->LogicUtils.isEmptyString ? "NA" : groupBy2
chartDictData->LineChartUtils.appendToDictValue(groupBy1 ++ " / " ++ groupBy2, item)
})
let compProps: RenderMultiDimensionalChart.config = {
chartDictData,
class,
selectedMetrics,
groupBy: groupby3,
xAxis,
chartKey,
legendType,
chartType,
}
<RenderMultiDimensionalChart config=compProps />
}
}
| 7,111 | 10,081 |
hyperswitch-control-center | src/components/CustomCharts/FunnelChart.res | .res | type funnelMetric = Volume | Rate
@react.component
let make = (
~data,
~metrics: array<LineChartUtils.metricsConfig>,
~size: float=0.24, // to scale
~moduleName,
~description,
) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let isMobileView = MatchMedia.useMobileChecker()
let (size, widthClass, flexDirectionClass) = React.useMemo(() => {
isMobileView ? (0.16, "w-full", "flex-col") : (size, "w-1/2", "flex-row")
}, [isMobileView])
let funnelData =
data->Array.get(0)->Option.getOr(JSON.Encode.null)->LogicUtils.getDictFromJsonObject
let metrics = metrics->Array.filter(metric => {
!(metric.disabled->Option.getOr(false))
})
let (hoverIndex, setHoverIndex) = React.useState(_ => -1.)
let (selectedMetric, setSelectedMetric) = React.useState(_ => Rate)
let length = metrics->Array.length->Float.fromInt
let widths = React.useMemo(() => {
metrics->Array.mapWithIndex((metric, i) => {
let previousMetric = metrics->Array.get(i - 1)
let previousMetric = switch previousMetric {
| Some(prevMetric) => prevMetric.metric_name_db
| None => ""
}
let funnelData = switch metric.data_transformation_func {
| Some(func) => func(funnelData)
| None => funnelData
}
let currentVol = funnelData->LogicUtils.getInt(metric.metric_name_db, 0)->Float.fromInt
let previousVol =
funnelData->LogicUtils.getInt(previousMetric, currentVol->Float.toInt)->Float.fromInt
Math.log10(currentVol *. 100. /. previousVol) /. 2.0
})
}, [funnelData])
let fixedWidth = ref(size *. 70.)
let prevMetricVol = ref(None)
let someData =
funnelData
->Dict.toArray
->Array.filter(entry => {
let (_key, value) = entry
value->LogicUtils.getIntFromJson(0) !== 0
})
->Array.length > 0
<div className="block m-6 mb-2">
<div className="font-semibold text-lg text-black dark:text-white">
{moduleName->LogicUtils.camelToSnake->LogicUtils.snakeToTitle->React.string}
</div>
{switch description {
| Some(description) =>
<div className="font-medium text-sm text-jp-gray-800 dark:text-dark_theme my-2">
{description->React.string}
</div>
| None => React.null
}}
<RenderIf condition={someData}>
<div className="flex flex-col">
<div className="flex gap-6 justify-end">
<div className={`flex flex-col ${widthClass}`} />
<div
className={`flex flex-row items-start ml-6 ${widthClass} font-medium text-sm text-jp-gray-800 dark:text-dark_theme cursor-pointer`}>
// <div
// className={selectedMetric === Volume ? "font-bold" : ""}
// onClick={_ => setSelectedMetric(_ => Volume)}>
// {React.string("Volume")}
// </div>
// {React.string("/")}
<div
className={selectedMetric === Rate ? "font-bold" : ""}
onClick={_ => setSelectedMetric(_ => Rate)}>
{React.string("Percentage")}
</div>
</div>
</div>
<div className={`flex ${flexDirectionClass} gap-6 mt-5 mb-10 delay-75 animate-slideUp`}>
<div className={`flex flex-col items-center my-auto ${widthClass}`}>
{metrics
->Array.mapWithIndex((_metric, i) => {
let i = i->Float.fromInt
let opacity = (i +. 1.) /. length
let borderTop = `${(size *. 14.)
->Float.toString}rem solid rgb(0,109,249,${opacity->Float.toString})`
let currentWidthRatio = switch widths->Array.get(i->Float.toInt) {
| Some(width) => width
| None => size *. 70.
}
let nextWidthRatio = switch widths->Array.get(i->Float.toInt + 1) {
| Some(width) => width
| None => widths->Array.get(i->Float.toInt)->Option.getOr(size *. 70.)
}
fixedWidth := currentWidthRatio *. fixedWidth.contents
let borderXFloat = (1. -. nextWidthRatio) *. fixedWidth.contents /. 2.
let borderX = `${borderXFloat->Float.toString}rem solid transparent`
let width = `${fixedWidth.contents->Float.toString}rem`
let marginBottom = `${(size *. 1.4)->Float.toString}rem`
let funnelElement =
<div
key={`${i->Float.toString}funnelStage`}
className="flex hover:cursor-pointer transition ease-in-out hover:scale-110 duration-300"
style={
borderTop,
borderLeft: borderX,
borderRight: borderX,
width,
marginBottom,
}
onMouseOver={_ => setHoverIndex(_ => i)}
onMouseOut={_ => setHoverIndex(_ => -1.)}
/>
funnelElement
})
->React.array}
</div>
<div className="flex flex-row justify-center gap-6">
<div className="flex flex-col items-start">
{
open LogicUtils
metrics
->Array.mapWithIndex((metric, i) => {
let marginBottom = `${(size *. 1.4)->Float.toString}rem`
let paddingTop = `${(size *. 4.2)->Float.toString}rem`
let metricVal = funnelData->getFloat(metric.metric_name_db, 0.0)
let prevMetricVolume = switch prevMetricVol.contents {
| Some(vol) => vol
| None => metricVal
}
prevMetricVol :=
switch prevMetricVol.contents {
| Some(val) => Some(val)
| None => Some(metricVal)
}
<div
key={`${i->Int.toString}funnelStageVol`}
className={`flex flex-row gap-4 h-full items-center w-max`}
style={marginBottom, paddingTop}>
<div
className={`flex font-semibold text-xl ${metricVal <= 0.
? "text-red-400"
: "text-black dark:text-white"} w-max items-start`}>
{switch selectedMetric {
| Volume =>
shortNum(~labelValue=metricVal, ~numberFormat=getDefaultNumberFormat())
| Rate =>
(metricVal *. 100. /. prevMetricVolume)
->Float.toFixedWithPrecision(~digits=2) ++ "%"
}->React.string}
</div>
</div>
})
->React.array
}
</div>
<div className="flex flex-col items-start">
{metrics
->Array.mapWithIndex((metric, i) => {
let marginBottom = `${(size *. 2.1)->Float.toString}rem`
let paddingTop = `${(size *. 3.4 *. 1.4)->Float.toString}rem`
<div
key={`${i->Int.toString}funnelStageDesc`}
className={`flex flex-row gap-4 h-full items-center w-max `}
style={marginBottom, paddingTop}>
<div
className={`transition ease-in-out duration-300 font-medium text-base ${hoverIndex ===
i->Float.fromInt
? `${textColor.primaryNormal} scale-110`
: "text-jp-gray-800 dark:text-dark_theme"}`}>
{metric.metric_label->React.string}
</div>
</div>
})
->React.array}
</div>
</div>
</div>
</div>
</RenderIf>
</div>
}
| 1,774 | 10,082 |
hyperswitch-control-center | src/components/custom-icons/RadioIcon.res | .res | @react.component
let make = (~isSelected, ~size: CheckBoxIcon.size=Small, ~fill="#0EB025", ~isDisabled=false) => {
<AddDataAttributes attributes=[("data-radio", LogicUtils.getStringFromBool(isSelected))]>
{if isSelected {
<svg
width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="16" height="16" rx="8" className={`fill-current ${fill}`} fill />
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 11C9.65685 11 11 9.65685 11 8C11 6.34315 9.65685 5 8 5C6.34315 5 5 6.34315 5 8C5 9.65685 6.34315 11 8 11Z"
fill="white"
/>
</svg>
} else {
<svg
width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="16" height="16" rx="8" fill="url(#paint0_linear)" />
<rect
x="0.5" y="0.5" width="15" height="15" rx="7.5" stroke="#CCD2E2" strokeOpacity="0.75"
/>
<defs>
<linearGradient
id="paint0_linear" x1="16" y1="16" x2="16" y2="0" gradientUnits="userSpaceOnUse">
<stop stopColor="#F1F5FA" />
<stop offset="1" stopColor="#FDFEFF" />
</linearGradient>
</defs>
</svg>
}}
</AddDataAttributes>
}
| 495 | 10,083 |
hyperswitch-control-center | src/components/custom-icons/CheckBoxIcon.resi | .resi | type size = Small | Large
@react.component
let make: (
~isSelected: bool,
~isDisabled: bool=?,
~setIsSelected: bool => unit=?,
~size: size=?,
~isSelectedStateMinus: bool=?,
~checkboxDimension: string=?,
~isCheckboxSelectedClass: bool=?,
~stopPropagationNeeded: bool=?,
) => React.element
| 88 | 10,084 |
hyperswitch-control-center | src/components/custom-icons/Tick.res | .res | open LottieFiles
@react.component
let make = (~isSelected) => {
/* let selectedTickJson = useSelectedTickJson()
let deselectTickJson = useDeselectTickJson() */
let selectedTickJson = useLottieJson(selectedTick)
let deselectTickJson = useLottieJson(deselectTick)
let (defaultState, autoplay) = LottieIcons.useLottieIcon(
isSelected,
selectedTickJson,
deselectTickJson,
)
<div className="h-4 w-4">
<ReactSuspenseWrapper loadingText="">
<Lottie
key={autoplay ? "true" : "false"}
animationData={defaultState}
autoplay={autoplay}
loop=false
/>
</ReactSuspenseWrapper>
</div>
}
| 169 | 10,085 |
hyperswitch-control-center | src/components/custom-icons/LottieFiles.res | .res | open Promise
type lottieFileJson = Loading(Promise.t<JSON.t>) | Loaded(JSON.t)
let selectedTick = "selectedTick.json"
let deselectTick = "deselectTick.json"
let enterCheckBox = "checkbox.json"
let exitCheckBox = "uncheckbox.json"
let enterSearchCross = "enterCross.json"
let exitSearchCross = "exitCross.json"
let lottieDict: Dict.t<lottieFileJson> = Dict.make()
let useLottieJson = lottieFileName => {
let (lottieJson, setlottieJson) = React.useState(_ => JSON.Encode.null)
let fetchApi = AuthHooks.useApiFetcher()
let uriPrefix = LogicUtils.useUrlPrefix()
let showToast = ToastState.useShowToast()
let prefix = `${Window.Location.origin}${uriPrefix}`
React.useEffect(() => {
switch lottieDict->Dict.get(lottieFileName) {
| Some(val) =>
switch val {
| Loaded(json) => setlottieJson(_ => json)
| Loading(promiseJson) => promiseJson->thenResolve(json => setlottieJson(_ => json))->ignore
}
| None => {
let fetchLottie =
fetchApi(
`${prefix}/lottie-files/${lottieFileName}`,
~method_=Get,
~xFeatureRoute=false,
~forceCookies=false,
)
->then(res => res->Fetch.Response.json)
->then(json => {
setlottieJson(_ => json)
lottieDict->Dict.set(lottieFileName, Loaded(json))
json->resolve
})
->catch(_err => {
showToast(~message="Error!", ~toastType=ToastError)
JSON.Encode.null->resolve
})
lottieDict->Dict.set(lottieFileName, Loading(fetchLottie))
}
}
None
}, [lottieFileName])
lottieJson
}
| 402 | 10,086 |
hyperswitch-control-center | src/components/custom-icons/GatewayIcon.res | .res | @react.component
let make = (~gateway, ~className="w-14 h-14") => {
let imagePath = `/Gateway`
<img alt={`${gateway}`} className src={`${imagePath}/${gateway}.svg`} />
}
| 50 | 10,087 |
hyperswitch-control-center | src/components/custom-icons/FormErrorIcon.res | .res | @react.component
let make = (~size=10) => {
<AddDataAttributes attributes=[("data-icon", "formErrorIcon")]>
<svg
className={`fill-red-500 mr-1.5`}
width={Int.toString(size) ++ "px"}
height={Int.toString(size) ++ "px"}
viewBox="0 0 8 9"
xmlns="http://www.w3.org/2000/svg">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M6.83 7.33C7.55406 6.60594 8 5.6044 8 4.5C8 3.39592 7.55406 2.39408 6.83 1.67C6.10594 0.94592 5.1044 0.5 4 0.5C2.89592 0.5 1.89408 0.945936 1.17 1.67C0.44592 2.39406 0 3.3956 0 4.5C0 5.60408 0.445936 6.60592 1.17 7.33C1.89406 8.05408 2.8956 8.5 4 8.5C5.10408 8.5 6.10592 8.05406 6.83 7.33ZM4.54128 6.04312C4.54128 5.74343 4.30003 5.50187 4.00003 5.50187C3.70034 5.50187 3.45159 5.74312 3.45159 6.04312C3.45159 6.34281 3.70034 6.59156 4.00003 6.59156C4.29972 6.59156 4.54128 6.34281 4.54128 6.04312ZM4.00003 4.95344C3.80253 4.95344 3.65628 4.7925 3.63441 4.58782L3.45159 2.95718C3.42222 2.67186 3.72222 2.40874 4.00003 2.40874C4.27785 2.40874 4.57785 2.67186 4.54128 2.95718L4.36566 4.58782C4.34378 4.7925 4.19753 4.95344 4.00003 4.95344Z"
/>
</svg>
</AddDataAttributes>
}
| 870 | 10,088 |
hyperswitch-control-center | src/components/custom-icons/Loadericon.res | .res | @react.component
let make = (~iconColor=?, ~size=16) => {
let theme = ThemeProvider.useTheme()
let svgColor = switch iconColor {
| Some(color) => color
| None =>
switch theme {
| Light => "text-jp-gray-900"
| Dark => "text-white"
}
}
<svg
width={Int.toString(size)}
height={Int.toString(size)}
viewBox="0 0 12 12"
className={`fill-current ${svgColor}`}
xmlns="http://www.w3.org/2000/svg">
<path
opacity="0.7"
d="M6.67955 9.44017C6.67955 9.0647 6.37533 8.76001 5.99986 8.76001C5.62393 8.76001 5.3197 9.0647 5.3197 9.44017V11.3203C5.3197 11.6953 5.62393 12 5.99986 12C6.37533 12 6.67955 11.6953 6.67955 11.3203V11.3189V9.44017Z"
/>
<path
d="M6.67956 0.664712C6.67065 0.296744 6.37018 0.000488281 5.99986 0.000488281C5.62954 0.000488281 5.32861 0.296732 5.32017 0.664712H5.3197V2.56083C5.3197 2.9363 5.62393 3.24099 5.99986 3.24099C6.37533 3.24099 6.67955 2.9363 6.67955 2.56083V0.680672V0.679266L6.67956 0.664712Z"
/>
<path
opacity="0.5"
d="M10.2416 9.27992L8.91364 7.952C8.91317 7.95153 8.91317 7.95153 8.9127 7.95153C8.6474 7.68575 8.21661 7.68575 7.9513 7.95153C7.68599 8.21684 7.68599 8.64716 7.9513 8.91293L9.28066 10.2423C9.54597 10.5076 9.97675 10.5076 10.2421 10.2423C10.5074 9.97652 10.5074 9.54573 10.2421 9.28089C10.2421 9.27995 10.2421 9.27995 10.2416 9.27995L10.2416 9.27992Z"
/>
<path
d="M1.74587 2.70848L3.08602 4.04816V4.0491C3.3518 4.31441 3.78259 4.31441 4.04743 4.04863C4.3132 3.78332 4.3132 3.35254 4.04743 3.08676L2.71903 1.75836C2.71903 1.75742 2.71903 1.75742 2.71809 1.75742C2.71809 1.75742 2.71762 1.75695 2.71715 1.75649L2.70684 1.74617V1.74664C2.44012 1.49164 2.01825 1.49539 1.75621 1.75742C1.49465 2.01946 1.49091 2.44133 1.74543 2.70758L1.74587 2.70848Z"
/>
<path
opacity="0.3"
d="M11.3196 5.32043H11.3191H9.44135H9.44041C9.06495 5.32043 8.76025 5.62466 8.76025 6.00012C8.76025 6.37606 9.06495 6.68075 9.44041 6.68075H11.3201C11.696 6.68075 12.0003 6.37606 12.0003 6.00012C11.9998 5.62466 11.6951 5.32043 11.3196 5.32043H11.3196Z"
/>
<path
d="M2.55996 6.68075H2.56043C2.9359 6.68075 3.24059 6.37606 3.24059 6.00012C3.24059 5.62466 2.93636 5.32043 2.56043 5.32043H0.681709H0.680771H0.679365H0.664834C0.296398 5.32934 0.000610352 5.62981 0.000610352 6.00012C0.000610352 6.3709 0.296386 6.6709 0.664834 6.67982V6.68075L2.55996 6.68075Z"
/>
<path
opacity="0.1"
d="M8.91316 4.04857L10.2425 2.71969C10.5078 2.45392 10.5078 2.02313 10.2425 1.75782C9.97721 1.49251 9.54642 1.49251 9.28111 1.75782L9.28018 1.75876L7.95226 3.0862C7.95179 3.08667 7.95179 3.08667 7.95179 3.08713C7.68648 3.35244 7.68648 3.78323 7.95179 4.04901C8.2171 4.31385 8.64742 4.31385 8.91319 4.04854L8.91316 4.04857Z"
/>
<path
d="M3.08665 7.95151L1.75825 9.27991C1.75825 9.27991 1.75778 9.27991 1.75731 9.28085C1.75731 9.28085 1.75684 9.28085 1.75637 9.28179L1.74606 9.2921H1.74653C1.492 9.55882 1.49575 9.98069 1.75731 10.2427C2.01934 10.5043 2.44122 10.508 2.70794 10.2535L4.0481 8.91335C4.31388 8.64757 4.31388 8.21679 4.0481 7.95195C3.78326 7.68569 3.35247 7.68569 3.0867 7.95148L3.08665 7.95151Z"
/>
</svg>
}
| 2,687 | 10,089 |
hyperswitch-control-center | src/components/custom-icons/LottieIcons.res | .res | let useLottieIcon = (isSelected, selectedLottieJson, deselectLottieJson) => {
let hasRendered = React.useRef(false)
let (defaultState, setDefaultState) = React.useState(() =>
isSelected ? deselectLottieJson : selectedLottieJson
)
let (autoplay, setAutoplay) = React.useState(() => false)
React.useEffect(() => {
if hasRendered.current {
setAutoplay(_ => true)
let newVal = isSelected ? selectedLottieJson : deselectLottieJson
setDefaultState(_ => newVal)
} else if selectedLottieJson != JSON.Encode.null && deselectLottieJson != JSON.Encode.null {
setDefaultState(_ => isSelected ? deselectLottieJson : selectedLottieJson)
hasRendered.current = true
}
None
}, (isSelected, selectedLottieJson, deselectLottieJson))
(defaultState, autoplay)
}
| 200 | 10,090 |
hyperswitch-control-center | src/components/custom-icons/CheckBoxIcon.res | .res | type size = Small | Large
open LottieFiles
@react.component
let make = (
~isSelected,
~isDisabled=false,
~setIsSelected=?,
~size: size=Small,
~isSelectedStateMinus=false,
~checkboxDimension="w-4 h-4",
~isCheckboxSelectedClass=false,
~stopPropagationNeeded=false,
) => {
let onClick = ev => {
if stopPropagationNeeded {
ev->ReactEvent.Mouse.stopPropagation
}
switch setIsSelected {
| Some(fn) => fn(!isSelected)
| None => ()
}
}
let enterCheckBoxJson = useLottieJson(enterCheckBox)
let exitCheckBoxJson = useLottieJson(exitCheckBox)
let (defaultState, autoplay) = LottieIcons.useLottieIcon(
isSelected,
enterCheckBoxJson,
exitCheckBoxJson,
)
let checkboxUpiClass = isCheckboxSelectedClass ? "border-2" : "border"
let checkboxBorderClass = `rounded-md ${checkboxUpiClass} border-gray-300 dark:border-gray-600`
<AddDataAttributes
attributes=[("data-selected-checkbox", isSelected ? "Selected" : "NotSelected")]>
{if isDisabled {
if isSelected {
<svg
width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="16" height="16" rx="4" fill="#b0b0b0" />
<path
fillRule="evenodd"
clipRule="evenodd"
d="M11.3135 5.29325C10.9225 4.90225 10.2895 4.90225 9.8995 5.29325L6.5355 8.65725L5.7065 7.82925C5.3165 7.43825 4.6835 7.43825 4.2925 7.82925C3.9025 8.21925 3.9025 8.85225 4.2925 9.24325L5.8285 10.7783C6.2185 11.1693 6.8515 11.1693 7.2425 10.7783L11.3135 6.70725C11.7045 6.31725 11.7045 5.68425 11.3135 5.29325Z"
fill="white"
/>
</svg>
} else {
<svg
width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="16" height="16" rx="4" fill="url(#paint0_linear)" />
<rect
x="0.5" y="0.5" width="15" height="15" rx="3.5" stroke="#CCD2E2" strokeOpacity="0.75"
/>
<defs>
<linearGradient
id="paint0_linear" x1="16" y1="16" x2="16" y2="0" gradientUnits="userSpaceOnUse">
<stop stopColor="#F1F5FA" />
<stop offset="1" stopColor="#FDFEFF" />
</linearGradient>
</defs>
</svg>
}
} else if isSelectedStateMinus {
if isSelected {
<div className={`${checkboxDimension}`} onClick>
<svg viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.5" width="16" height="16" rx="4" fill="#0EB025" />
<rect x="4" y="7.5" width="8" height="2" rx="1" fill="white" />
</svg>
</div>
} else {
<div className={`${checkboxDimension} ${checkboxBorderClass}`} onClick />
}
} else {
<div className={`${checkboxDimension} ${!isSelected ? checkboxBorderClass : ""}`} onClick>
<ReactSuspenseWrapper>
<Lottie
key={autoplay ? "true" : "false"}
animationData={defaultState}
autoplay={autoplay}
loop=false
/>
</ReactSuspenseWrapper>
</div>
}}
</AddDataAttributes>
}
| 1,135 | 10,091 |
hyperswitch-control-center | src/components/router/Link.res | .res | @react.component
let make = (~to_, ~children, ~openInNewTab=false, ~className=?, ~onClick=?) => {
let handleClick = React.useCallback(ev => {
ReactEvent.Mouse.stopPropagation(ev)
ReactEvent.Mouse.preventDefault(ev)
switch onClick {
| Some(fn) => fn(to_)
| None => ()
}
to_->RescriptReactRouter.push
}, [to_])
if openInNewTab {
if to_->String.trim->LogicUtils.isEmptyString {
children
} else {
<a href=to_ onClick={ev => ev->ReactEvent.Mouse.stopPropagation} target="_blank" ?className>
children
</a>
}
} else {
<a href=to_ onClick=handleClick ?className> children </a>
}
}
| 173 | 10,092 |
hyperswitch-control-center | src/components/form/YesNoRadioInput.res | .res | @react.component
let make = (~input: ReactFinalForm.fieldRenderPropsInput) => {
<div className="flex items-center gap-5">
<div className="flex items-center gap-2">
<input
name={input.name}
label="Yes"
value="yes"
type_="radio"
checked={input.value == "yes"->JSON.Encode.string}
onChange=input.onChange
/>
<label className="text-sm text-jp-gray-800"> {"Yes"->React.string} </label>
</div>
<div className="flex items-center gap-2">
<input
name={input.name}
label="No"
value="no"
type_="radio"
checked={input.value == "no"->JSON.Encode.string}
onChange=input.onChange
/>
<label className="text-sm text-jp-gray-800"> {"No"->React.string} </label>
</div>
</div>
}
| 215 | 10,093 |
hyperswitch-control-center | src/components/form/TextInput.res | .res | @send external focus: Dom.element => unit = "focus"
@send @return(nullable) external closest: (Dom.element, string) => option<Dom.element> = "closest"
@react.component
let make = (
~focusOnKeyPress=?,
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~description="",
~isDisabled=false,
~type_="text",
~inputMode="text",
~pattern=?,
~autoComplete=?,
~shouldSubmitForm=true,
~min=?,
~max=?,
~maxLength=?,
~autoFocus=false,
~leftIcon=?,
~rightIcon=?,
~rightIconOnClick=?,
~customDashboardClass=?,
~inputStyle="",
~onKeyUp=?,
~customStyle="",
~customWidth="w-full",
~readOnly=?,
~iconOpacity="opacity-30",
~customPaddingClass="",
~widthMatchwithPlaceholderLength=None,
~rightIconCustomStyle="",
~leftIconCustomStyle="",
~onHoverCss="",
~onDisabledStyle="",
~onActiveStyle="",
~customDarkBackground="dark:bg-jp-gray-darkgray_background",
~phoneInput=false,
~removeValidationCheck=false,
) => {
let {globalUIConfig: {shadow: {shadowColor}, border: {borderColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let showPopUp = PopUpState.useShowPopUp()
let isInValid = try {
let {meta} = ReactFinalForm.useField(input.name)
if !removeValidationCheck {
let bool = if !meta.valid && meta.touched {
// if there is a submission error and field value hasn't been updated after last submit, field is invalid
// or if there is any field error, field is invalid
(!(meta.submitError->Js.Nullable.isNullable) && !meta.dirtySinceLastSubmit) ||
!(meta.error->Js.Nullable.isNullable)
} else {
false
}
bool
} else {
false
}
} catch {
| _ => false
}
let {isFirst, isLast} = React.useContext(ButtonGroupContext.buttonGroupContext)
let (showPassword, setShowPassword) = React.useState(_ => false)
let inputRef = React.useRef(Nullable.null)
React.useEffect(() => {
switch widthMatchwithPlaceholderLength {
| Some(length) =>
switch inputRef.current->Nullable.toOption {
| Some(elem) =>
let size =
elem
->Webapi.Dom.Element.getAttribute("placeholder")
->Option.mapOr(length, str => Math.Int.max(length, str->String.length))
->Int.toString
elem->Webapi.Dom.Element.setAttribute("size", size)
| None => ()
}
| None => ()
}
None
}, (inputRef.current, input.name))
React.useEffect(() => {
let val = input.value->JSON.Decode.string->Option.getOr("")
if val->String.includes("<script>") || val->String.includes("</script>") {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Script Tags are not allowed`,
description: React.string(`Input cannot contain <script>, </script> tags`),
handleConfirm: {text: "OK"},
})
input.onChange(
val
->String.replace("<script>", "")
->String.replace("</script>", "")
->Identity.stringToFormReactEvent,
)
}
None
}, [input.value])
React.useEffect(() => {
switch focusOnKeyPress {
| Some(func) => {
let keyDownFn = ev => {
if func(ev) {
ev->ReactEvent.Keyboard.preventDefault
switch inputRef.current->Nullable.toOption {
| Some(elem) => elem->focus
| None => ()
}
}
}
Window.addEventListener("keydown", keyDownFn)
Some(() => Window.removeEventListener("keydown", keyDownFn))
}
| None => None
}
}, [focusOnKeyPress])
let cursorClass = isDisabled ? "cursor-not-allowed" : ""
let roundingClass = if isFirst && isLast {
"rounded"
} else if isFirst {
"rounded-l"
} else if isLast {
"rounded-r"
} else {
""
}
let borderClass = isInValid
? "border-red-500 focus:border-red-500 dark:border-red-500 dark:hover:border-red-500 dark:focus:border-red-500 focus:shadow-text_input_shadow focus:shadow-red-500"
: `border-jp-gray-lightmode_steelgray ${borderColor.primaryFocused} dark:border-jp-gray-960 dark:hover:border-jp-gray-960 dark:${borderColor.primaryFocused} focus:shadow-text_input_shadow ${shadowColor.primaryFocused}`
let dashboardClass = customDashboardClass->Option.getOr("h-10 text-sm font-normal")
let rightPaddingClass = if description->LogicUtils.isNonEmptyString || isInValid {
"pr-10"
} else {
switch rightIcon {
| Some(_) => "pr-10"
| None => "pr-2"
}
}
let leftPaddingClass = switch leftIcon {
| Some(_) => "pl-10"
| None => "pl-2"
}
let verticalPadding = ""
let placeholderClass = "placeholder-opacity-50"
let textAndBgClass = `${customDarkBackground} text-jp-gray-900 text-opacity-75 focus:text-opacity-100 dark:text-jp-gray-text_darktheme dark:text-opacity-75 dark:placeholder-jp-gray-text_darktheme dark:placeholder-opacity-25 dark:focus:text-opacity-100`
let width = widthMatchwithPlaceholderLength->Option.isSome ? "" : customWidth
let textPaddingClass =
type_ !== "range" && customPaddingClass->LogicUtils.isEmptyString
? `${rightPaddingClass} ${leftPaddingClass} ${verticalPadding}`
: customPaddingClass
let hoverCss = if onHoverCss->LogicUtils.isEmptyString {
"hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-20 hover:border-opacity-20 dark:hover:bg-jp-gray-970"
} else {
onHoverCss
}
let className = `${width} border border-opacity-75 ${textPaddingClass} ${textAndBgClass} placeholder-jp-gray-900 placeholder-opacity-25 focus:outline-none
focus:border-opacity-100 ${hoverCss} ${roundingClass} ${cursorClass} ${dashboardClass} ${inputStyle} ${borderClass} ${customStyle} ${placeholderClass} ${isDisabled
? onDisabledStyle
: onActiveStyle}`
let value = switch input.value->JSON.Classify.classify {
| String(str) => str
| Number(num) => num->Float.toString
| _ => ""
}
let passwordVisiblity = _ => {
setShowPassword(prev => !prev)
}
let leftIconClass = `absolute self-center p-3 ${iconOpacity} ${leftIconCustomStyle}`
let leftIconElement = switch leftIcon {
| Some(icon) => <div id="leftIcon" className=leftIconClass> icon </div>
| None => React.null
}
let rightIconCursorClass = switch rightIconOnClick {
| Some(_) => "cursor-pointer"
| None => ""
}
let rightIconStyle =
rightIconCustomStyle->LogicUtils.isEmptyString
? `-ml-10 ${rightIconCursorClass}`
: rightIconCustomStyle
let rightIconClick = ev => {
switch rightIconOnClick {
| Some(fn) => fn(ev)
| None => ()
}
}
let rightIconElement = switch rightIcon {
| Some(icon) =>
<div id="rightIcon" className={`${rightIconStyle}`} onClick=rightIconClick> icon </div>
| None => React.null
}
let inputName = if autoComplete === Some("off") {
None
} else {
Some(input.name)
}
let form = switch shouldSubmitForm {
| true => None
| false => Some("fakeForm")
}
let className = if rightIconElement != React.null {
`${className} pr-10`
} else if leftIconElement != React.null {
let padding = phoneInput ? "pl-20" : "pl-10"
`${className} ${padding}`
} else {
className
}
let eyeIcon = if showPassword {
"eye"
} else {
"eye-slash"
}
let eyeIconSize = 15
let eyeClassName = "fill-jp-gray-700"
if type_ == "password" || type_ == "password_without_icon" {
<AddDataAttributes
attributes=[
("data-id-password", input.name),
("data-input-name", input.name),
("data-testid", input.name),
]>
<div className="flex flex-row items-center relative">
leftIconElement
<input
ref={inputRef->ReactDOM.Ref.domRef}
className={`${className} pr-10`}
name=?inputName
onBlur={input.onBlur}
onChange={input.onChange}
onFocus={input.onFocus}
value
disabled={isDisabled}
placeholder={placeholder}
type_={showPassword ? "text" : "password"}
inputMode
?pattern
?autoComplete
?min
?max
?maxLength
?onKeyUp
?readOnly
?form
/>
{if type_ !== "password_without_icon" {
<div className="cursor-pointer select-none -ml-8" onClick={passwordVisiblity}>
<Icon name=eyeIcon size=eyeIconSize className=eyeClassName />
</div>
} else {
React.null
}}
</div>
</AddDataAttributes>
} else {
<AddDataAttributes
attributes=[
("data-id", placeholder),
("data-input-name", input.name),
("data-testid", input.name),
]>
<div className="flex flex-row relative items-center grow">
leftIconElement
<input
ref={inputRef->ReactDOM.Ref.domRef}
className
name=?inputName
onBlur={input.onBlur}
onChange={input.onChange}
onFocus={input.onFocus}
value
disabled={isDisabled}
placeholder={placeholder}
type_
inputMode
?pattern
?autoComplete
?min
?max
?maxLength
?onKeyUp
?readOnly
autoFocus
?form
/>
{description->LogicUtils.isNonEmptyString
? <ToolTip
description
toolTipPosition=Right
height="h-min"
toolTipFor={<div className="cursor-pointer select-none -ml-8">
<Icon name="new-question-circle" size=16 className="stroke-jp-2-light-gray-1000" />
</div>}
/>
: rightIconElement}
</div>
</AddDataAttributes>
}
}
| 2,478 | 10,094 |
hyperswitch-control-center | src/components/form/FormRenderer.res | .res | open InputFields
type inputFieldType = {
name: string,
placeholder: string,
format: option<(~value: JSON.t, ~name: string) => JSON.t>,
parse: option<(~value: JSON.t, ~name: string) => JSON.t>,
disabled: bool,
isRequired: bool,
@as("type") type_: string,
customInput: customInputFn,
validate: option<(option<string>, JSON.t) => Promise.t<Nullable.t<string>>>,
}
type fieldInfoType = {
label: string,
customLabelIcon: option<React.element>,
subHeading: option<string>,
subHeadingIcon: option<string>,
description: option<string>,
descriptionComponent: option<React.element>,
subText: option<string>,
isRequired: bool,
toolTipPosition: option<ToolTip.toolTipPosition>,
comboCustomInput: option<comboCustomInputFn>,
inputFields: array<inputFieldType>,
inputNames: array<string>,
fieldPortalKey?: string,
}
let makeInputFieldInfo = (
~label=?,
~name,
~customInput=?,
~placeholder=?,
~format=?,
~disabled=false,
~parse=?,
~type_="text",
~isRequired=false,
~validate: option<(option<string>, JSON.t) => Promise.t<Nullable.t<string>>>=?,
) => {
let label = label->Option.getOr(name)
let newCustomInput = customInput->Option.getOr(InputFields.textInput(~isDisabled=disabled))
{
name,
placeholder: placeholder->Option.getOr(label),
customInput: newCustomInput,
disabled,
format,
parse,
type_,
isRequired,
validate,
}
}
let makeMultiInputFieldInfoOld = (
~label,
~customLabelIcon=?,
~subHeading=?,
~subHeadingIcon=?,
~description=?,
~toolTipPosition=?,
~descriptionComponent=?,
~subText=?,
~isRequired=false,
~comboCustomInput=?,
~inputFields,
(),
) => {
{
label,
customLabelIcon,
subHeading,
subHeadingIcon,
description,
toolTipPosition,
descriptionComponent,
subText,
isRequired,
comboCustomInput,
inputFields,
inputNames: inputFields->Array.map(x => x.name),
}
}
let makeMultiInputFieldInfo = (
~label,
~customLabelIcon=?,
~subHeading=?,
~subHeadingIcon=?,
~description=?,
~toolTipPosition=?,
~descriptionComponent=?,
~subText=?,
~isRequired=false,
~comboCustomInput: option<comboCustomInputRecord>=?,
~fieldPortalKey: option<string>=?,
~inputFields,
) => {
let inputNames =
comboCustomInput
->Option.mapOr([], x => x.names)
->Array.concat(inputFields->Array.map(x => x.name))
{
label,
customLabelIcon,
subHeading,
subHeadingIcon,
description,
toolTipPosition,
descriptionComponent,
subText,
isRequired,
comboCustomInput: comboCustomInput->Option.map(x => x.fn),
inputFields,
inputNames,
?fieldPortalKey,
}
}
let makeFieldInfo = (
~label=?,
~customLabelIcon=?,
~name,
~customInput=?,
~description=?,
~toolTipPosition=?,
~descriptionComponent=?,
~subText=?,
~placeholder=?,
~subHeading=?,
~subHeadingIcon=?,
~format=?,
~disabled=false,
~parse=?,
~type_="text",
~isRequired=false,
~fieldPortalKey: option<string>=?,
~validate: option<(option<string>, JSON.t) => Promise.t<Nullable.t<string>>>=?,
) => {
let label = label->Option.getOr(name)
let newCustomInput = customInput->Option.getOr(InputFields.textInput(~isDisabled=disabled))
makeMultiInputFieldInfo(
~label,
~customLabelIcon?,
~description?,
~toolTipPosition?,
~descriptionComponent?,
~subHeading?,
~subText?,
~subHeadingIcon?,
~isRequired,
~fieldPortalKey?,
~inputFields=[
makeInputFieldInfo(
~label,
~name,
~customInput=newCustomInput,
~placeholder?,
~format?,
~disabled,
~parse?,
~type_,
~isRequired,
~validate?,
),
],
)
}
module FieldWrapper = {
@react.component
let make = (
~label,
~customLabelIcon=?,
~labelClass="",
~labelTextStyleClass="",
~labelPadding="",
~subHeading=?,
~subHeadingIcon=?,
~description=?,
~toolTipPosition=ToolTip.Bottom,
~descriptionComponent=?,
~subText=?,
~isRequired=false,
~fieldWrapperClass="",
~children,
~dataId="",
~subTextClass="",
~subHeadingClass="",
) => {
let showLabel = React.useContext(LabelVisibilityContext.formLabelRenderContext)
let fieldWrapperClass = if fieldWrapperClass->LogicUtils.isEmptyString {
"p-1 flex flex-col"
} else {
fieldWrapperClass
}
let subTextClass = `pt-2 pb-2 text-sm text-bold text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ${subTextClass}`
let labelPadding = labelPadding->LogicUtils.isEmptyString ? "pt-2 pb-2" : labelPadding
let labelTextClass =
labelTextStyleClass->LogicUtils.isNonEmptyString
? labelTextStyleClass
: "text-fs-13 text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ml-1"
<AddDataAttributes attributes=[("data-component-field-wrapper", `field-${dataId}`)]>
<div className={fieldWrapperClass}>
{<>
<div className="flex items-center">
<RenderIf condition=showLabel>
<AddDataAttributes attributes=[("data-form-label", label)]>
<label className={`${labelPadding} ${labelTextClass} ${labelClass}`}>
{React.string(label)}
<RenderIf condition=isRequired>
<span className="text-red-950"> {React.string(" *")} </span>
</RenderIf>
</label>
</AddDataAttributes>
</RenderIf>
{switch description {
| Some(description) =>
<RenderIf condition={description->LogicUtils.isNonEmptyString}>
<div className="text-sm text-gray-500 mx-2">
<ToolTip description toolTipPosition />
</div>
</RenderIf>
| None => React.null
}}
{switch descriptionComponent {
| Some(descriptionComponent) =>
<div className="text-sm text-gray-500 mx-2">
<ToolTip descriptionComponent toolTipPosition tooltipWidthClass="w-80" />
</div>
| None => React.null
}}
{switch customLabelIcon {
| Some(customLabelIcon) => <div className="pl-2"> {customLabelIcon} </div>
| None => React.null
}}
</div>
{switch subHeading {
| Some(sb) =>
<div className="flex flex-row items-center">
{switch subHeadingIcon {
| Some(iconName) =>
<Icon size=13 name=iconName className=" opacity-60 mr-2 ml-1 mb-2" />
| None => React.null
}}
<div
className={`text-sm text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 mb-2 ${subHeadingClass}`}>
{React.string(sb)}
</div>
</div>
| None => React.null
}}
</>}
children
{switch subText->Option.flatMap(val => val->LogicUtils.getNonEmptyString) {
| Some(subText) => <div className=subTextClass> {React.string(subText)} </div>
| None => React.null
}}
</div>
</AddDataAttributes>
}
}
module FieldError = {
@react.component
let make = (
~meta: ReactFinalForm.fieldRenderPropsMeta,
~alwaysShow=false,
~errorClass="",
~showErrorOnChange=false,
) => {
let errorTextStyle = "text-red-950 dark:text-red-400 text-fs-10 font-medium ml-1"
let error = if meta.touched || alwaysShow || (showErrorOnChange && meta.modified) {
if !(meta.submitError->Js.Nullable.isNullable) && !meta.dirtySinceLastSubmit {
Nullable.toOption(meta.submitError)
} else {
Nullable.toOption(meta.error)
}
} else {
None
}
switch error {
| Some(err) =>
<AddDataAttributes attributes=[("data-form-error", err)]>
<div
className={`flex flex-row items-center ${errorTextStyle} pt-2 leading-4 text-start ${errorClass}`}>
<FormErrorIcon />
{React.string(err)}
</div>
</AddDataAttributes>
| None => React.null
}
}
}
module FieldErrorRenderer = {
@react.component
let make = (~field: inputFieldType, ~errorClass="") => {
<ReactFinalForm.Field
name={field.name}
validate=?{field.validate}
render={({meta}) => <FieldError meta errorClass />}
/>
}
}
module FieldInputRenderer = {
@react.component
let make = (
~field: inputFieldType,
~customRender=?,
~showError=true,
~errorClass="",
~showErrorOnChange=false,
) => {
React.cloneElement(
<ReactFinalForm.Field
name={field.name}
format=?{field.format}
parse=?{field.parse}
validate=?{field.validate}
render={switch customRender {
| Some(fn) => fn
| None =>
({input, meta}) => {
<>
{field.customInput(~input, ~placeholder=field.placeholder)}
{if showError {
<FieldError meta errorClass showErrorOnChange />
} else {
React.null
}}
</>
}
}}
/>,
{"type": field.type_},
)
}
}
module ComboFieldsRenderer = {
@react.component
let make = (~field: fieldInfoType) => {
<div>
<ButtonGroup wrapperClass="flex flex-row items-center">
{field.inputFields
->Array.mapWithIndex((field, i) => {
<ErrorBoundary key={Int.toString(i)}>
<FieldInputRenderer field showError=false />
</ErrorBoundary>
})
->React.array}
</ButtonGroup>
<div>
{field.inputFields
->Array.mapWithIndex((field, i) => {
<ErrorBoundary key={Int.toString(i)}>
<FieldErrorRenderer field />
</ErrorBoundary>
})
->React.array}
</div>
</div>
}
}
module ComboFieldsRenderer3 = {
module ComboFieldsRecursive = {
@react.component
let make = (
~inputFields,
~fieldsState=[],
~renderInputs: array<ReactFinalForm.fieldRenderProps> => React.element,
~renderComboFields: (
~inputFields: array<inputFieldType>,
~fieldsState: array<ReactFinalForm.fieldRenderProps>,
~renderInputs: array<ReactFinalForm.fieldRenderProps> => React.element,
) => React.element,
) => {
if inputFields->Array.length === 0 {
renderInputs(fieldsState)
} else {
let inputField = inputFields[0]->Option.getOr(makeInputFieldInfo(~name=""))
let restInputFields = inputFields->Array.sliceToEnd(~start=1)
<ReactFinalForm.Field
name=inputField.name
parse=?inputField.parse
format=?inputField.format
validate=?{inputField.validate}>
{fieldState => {
let newFieldsState = Array.concatMany([], [fieldsState, [fieldState]])
renderComboFields(
~inputFields=restInputFields,
~renderInputs,
~fieldsState=newFieldsState,
)
}}
</ReactFinalForm.Field>
}
}
}
let rec renderComboFields = (~inputFields, ~fieldsState, ~renderInputs) => {
<ComboFieldsRecursive inputFields fieldsState renderComboFields renderInputs />
}
@react.component
let make = (
~inputFields,
~fieldsState=[],
~renderInputs: array<ReactFinalForm.fieldRenderProps> => React.element,
) => {
<ComboFieldsRecursive inputFields fieldsState renderComboFields renderInputs />
}
}
module DesktopRow = {
@react.component
let make = (~children, ~wrapperClass="", ~itemWrapperClass="mx-4", ~backgroundColor="") => {
<div className={`flex flex-col md:flex-row md:flex-wrap ${backgroundColor} ${wrapperClass}`}>
{children->React.Children.map(element => {
if element !== React.null {
<AddDataAttributes attributes=[("data-component", "desktopRow")]>
<div className={`flex-1 space-y-2 ${itemWrapperClass}`}> element </div>
</AddDataAttributes>
} else {
React.null
}
})}
</div>
}
}
module FieldRenderer = {
@react.component
let make = (
~field: fieldInfoType,
~fieldWrapperClass="",
~labelClass="",
~labelTextStyleClass="",
~labelPadding="",
~errorClass="",
~subTextClass="",
~subHeadingClass="",
~showErrorOnChange=false,
) => {
let portalKey = ""
let isVisible = true
if isVisible {
let names = field.inputNames->Array.joinWith("-")
<Portal to=portalKey>
<AddDataAttributes attributes=[("data-component", "fieldRenderer")]>
<ErrorBoundary>
<FieldWrapper
label=field.label
customLabelIcon=?field.customLabelIcon
labelClass
labelTextStyleClass
labelPadding
subHeading=?field.subHeading
subHeadingIcon=?field.subHeadingIcon
subText=?field.subText
description=?field.description
descriptionComponent=?field.descriptionComponent
isRequired=field.isRequired
toolTipPosition=?field.toolTipPosition
fieldWrapperClass
subTextClass
subHeadingClass
dataId=names>
{if field.inputFields->Array.length === 1 {
let field = field.inputFields[0]->Option.getOr(makeInputFieldInfo(~name=""))
<ErrorBoundary>
<FieldInputRenderer field errorClass showErrorOnChange />
</ErrorBoundary>
} else {
switch field.comboCustomInput {
| Some(renderInputs) =>
<ComboFieldsRenderer3 inputFields=field.inputFields renderInputs />
| None => <ComboFieldsRenderer field />
}
}}
</FieldWrapper>
</ErrorBoundary>
</AddDataAttributes>
</Portal>
} else {
React.null
}
}
}
module FormError = {
@react.component
let make = (~form: ReactFinalForm.formApi) => {
let (submitErrors, setSubmitErrors) = React.useState(() => None)
let subscriptionJson = {
let subscriptionDict = Dict.make()
Dict.set(subscriptionDict, "submitErrors", JSON.Encode.bool(true))
JSON.Encode.object(subscriptionDict)
}
React.useEffect(() => {
let unsubscribe = form.subscribe(formState => {
setSubmitErrors(_ => formState.submitErrors->Nullable.toOption)
()
}, subscriptionJson)
Some(unsubscribe)
}, [])
switch submitErrors {
| Some(errorsJson) =>
switch errorsJson->JSON.Decode.object {
| Some(dict) =>
let errStr = switch Dict.get(dict, "FORM_ERROR") {
| Some(err) => LogicUtils.getStringFromJson(err, "")
| None => "Error occurred on submit"
}
<div className="text-red-950"> {React.string(errStr)} </div>
| None => React.null
}
| None => React.null
}
}
}
type modalObj = {
confirmType: string,
confirmText: React.element,
buttonText: string,
cancelButtonText: string,
popUpType: PopUpState.popUpType,
}
module SubmitButton = {
@react.component
let make = (
~text="Submit",
~disabledParamter=false,
~icon=Button.NoIcon,
~rightIcon=Button.NoIcon,
~loginPageValidator=false,
~customSumbitButtonStyle="",
~showToolTip=true,
~buttonType=Button.Primary,
~loadingText="",
~buttonSize=?,
~toolTipPosition=ToolTip.Top,
~tooltipPositioning: ToolTip.tooltipPositioning=#fixed,
~withDialog=false,
~modalObj: option<modalObj>=?,
~tooltipWidthClass="w-auto",
~tooltipForWidthClass="",
~tooltipForHeight="h-full",
~userInteractionRequired=false,
~customTextSize=?,
~customPaddingClass=?,
~textStyle=?,
~textWeight=?,
~customHeightClass=?,
~dataTestId=?,
) => {
let dict = Dict.make()
[
"hasSubmitErrors",
"hasValidationErrors",
"errors",
"submitErrors",
"submitting",
]->Array.forEach(item => {
Dict.set(dict, item, JSON.Encode.bool(true))
})
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
dict->JSON.Encode.object->Nullable.make,
)
let {hasValidationErrors, hasSubmitErrors, submitting, dirtySinceLastSubmit, errors} = formState
let errorsList = JsonFlattenUtils.flattenObject(errors, false)->Dict.toArray
let hasError = {
if loginPageValidator {
hasValidationErrors
} else {
(hasValidationErrors || hasSubmitErrors || submitting) && !dirtySinceLastSubmit
}
}
let disabled = hasError || disabledParamter
let showPopUp = PopUpState.useShowPopUp()
let (avoidDisable, setAvoidDisable) = React.useState(_ => userInteractionRequired)
React.useEffect(() => {
let onClick = {
_ => {
setAvoidDisable(_ => false)
}
}
Window.addEventListener("click", onClick)
Some(
() => {
Window.removeEventListener("click", onClick)
},
)
}, [])
let form = ReactFinalForm.useForm()
let openPopUp = (confirmType, confirmText, buttonText, cancelButtonText, popUpType) => {
showPopUp({
popUpType: (popUpType, WithIcon),
heading: confirmType,
description: confirmText,
handleConfirm: {text: buttonText, onClick: _ => form.submit()->ignore},
handleCancel: {text: cancelButtonText},
})
}
let popUpBtn =
<Button
text
buttonType
buttonState={disabled ? Disabled : Normal}
onClick={_ => {
if !disabled {
switch modalObj {
| Some({confirmType, confirmText, buttonText, cancelButtonText, popUpType}) =>
openPopUp(confirmType, confirmText, buttonText, cancelButtonText, popUpType)
| None => ()
}
}
}}
leftIcon=icon
rightIcon
customButtonStyle={customSumbitButtonStyle}
?buttonSize
?customTextSize
?customPaddingClass
?textStyle
?textWeight
?dataTestId
/>
let buttonState: Button.buttonState =
loadingText->LogicUtils.isNonEmptyString && submitting
? Loading
: !avoidDisable && disabled
? Disabled
: Normal
let submitBtn =
<>
<button type_="submit" className="hidden" />
<Button
text
buttonType
buttonState
loadingText
onClick={_ => {
form.submit()->ignore
}} //either onclick or type_should be called #warning
leftIcon=icon
rightIcon
customButtonStyle={customSumbitButtonStyle}
?buttonSize
?customHeightClass
?textStyle
?dataTestId
/>
</>
let button = withDialog ? popUpBtn : submitBtn
if errorsList->Array.length === 0 {
button
} else {
let description =
errorsList
->Array.map(entry => {
let (key, jsonValue) = entry
let value = LogicUtils.getStringFromJson(jsonValue, "Error")
`${key->LogicUtils.snakeToTitle}: ${value}`
})
->Array.joinWith("\n")
if showToolTip && !avoidDisable {
<ToolTip
description
toolTipFor=button
toolTipPosition
tooltipPositioning
tooltipWidthClass
height=tooltipForHeight
tooltipForWidthClass
/>
} else {
button
}
}
}
}
module FieldsRenderer = {
@react.component
let make = (
~fields,
~fieldWrapperClass="",
~labelClass="",
~labelPadding="",
~errorClass="",
~subTextClass="",
~subHeadingClass="",
) => {
Array.mapWithIndex(fields, (field, i) => {
<FieldRenderer
key={Int.toString(i)}
field
fieldWrapperClass
labelClass
labelPadding
errorClass
subTextClass
subHeadingClass
/>
})->React.array
}
}
module FormContent = {
@react.component
let make = (
~form: ReactFinalForm.formApi,
~title,
~fields,
~handleSubmit,
~fieldsWrapperClass="",
~fieldWrapperClass="",
~formClass="",
~showFormSpy=false,
~submitButtonText=?,
) => {
<form onSubmit={handleSubmit}>
<div className=formClass>
{switch title {
| Some(str) => <div> {React.string(str)} </div>
| None => React.null
}}
<div className={`p-2 ${fieldsWrapperClass}`}>
{if showFormSpy {
<div className="flex flex-1 flex-row overflow-hidden">
<div className="flex flex-1 flex-col overflow-scroll p-4">
<FieldsRenderer fields fieldWrapperClass />
</div>
<FormValuesSpy wrapperClass="h-full w-1/3" restrictToLocal=false />
</div>
} else {
<FieldsRenderer fields fieldWrapperClass />
}}
</div>
<div className="p-3">
<FormError form />
</div>
<div className="flex justify-center mb-2">
<SubmitButton text=?submitButtonText />
</div>
</div>
</form>
}
}
@react.component
let make = (
~title=?,
~fields: array<fieldInfoType>,
~initialValues,
~validate=?,
~submitButtonText=?,
~onSubmit: (ReactFinalForm.formValues, ReactFinalForm.formApi) => Promise.t<Nullable.t<JSON.t>>,
~fieldsWrapperClass="",
~fieldWrapperClass="",
~formClass="",
~showFormSpy=false,
) => {
<ReactFinalForm.Form
onSubmit
validate=?{validate}
initialValues
subscription=ReactFinalForm.subscribeToValues
render={({form, handleSubmit}) => {
<FormContent
form
title
fields
handleSubmit
fieldsWrapperClass
fieldWrapperClass
formClass
showFormSpy
?submitButtonText
/>
}}
/>
}
| 5,294 | 10,095 |
hyperswitch-control-center | src/components/form/LabelVisibilityContext.res | .res | let formLabelRenderContext = React.createContext(true)
module Provider = {
let make = React.Context.provider(formLabelRenderContext)
}
@react.component
let make = (~children, ~showLabel) => {
<Provider value=showLabel>
<div> children </div>
</Provider>
}
| 65 | 10,096 |
hyperswitch-control-center | src/components/form/NumericTextInput.res | .res | let getFloat = strJson => strJson->JSON.Decode.string->Option.flatMap(val => val->Float.fromString)
@react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~isDisabled=false,
~type_="text",
~inputMode="number",
~customStyle="",
~pattern=?,
~autoComplete=?,
~min=?,
~max=?,
~precision=?,
~maxLength=?,
~removeLeadingZeroes=false,
~shouldSubmitForm=true,
~widthMatchwithPlaceholderLength=None,
~leftIcon=?,
~rightIcon=?,
~iconOpacity=?,
~customPaddingClass=?,
~rightIconCustomStyle=?,
~leftIconCustomStyle=?,
~removeValidationCheck=?,
) => {
let (localStrValue, setLocalStrValue) = React.useState(() => input.value)
let inputRef = React.useRef(Nullable.null)
React.useEffect(() => {
switch widthMatchwithPlaceholderLength {
| Some(length) =>
switch inputRef.current->Nullable.toOption {
| Some(elem) =>
let size =
elem
->Webapi.Dom.Element.getAttribute("placeholder")
->Option.mapOr(length, str => Math.Int.max(length, str->String.length))
->Int.toString
elem->Webapi.Dom.Element.setAttribute("size", size)
| None => ()
}
| None => ()
}
None
}, (inputRef.current, input.name))
let modifiedInput = React.useMemo(() => {
{
...input,
value: localStrValue,
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
let strValue = value->JSON.Decode.string->Option.getOr("")
let cleanedValue = switch strValue->Js.String2.match_(%re("/[\d\.]/g")) {
| Some(strArr) =>
let str =
strArr->Array.joinWithUnsafe("")->String.split(".")->Array.slice(~start=0, ~end=2)
let result = if removeLeadingZeroes {
str[0] = str[0]->Option.getOr("")->String.replaceRegExp(%re("/\b0+/g"), "")
str[0] =
str[0]->Option.getOr("")->LogicUtils.isEmptyString ? "0" : str[0]->Option.getOr("")
str->Array.joinWith(".")
} else {
str->Array.joinWith(".")
}
result
| None => ""
}
let indexOfDec = cleanedValue->String.indexOf(".")
let precisionCheckedVal = switch precision {
| Some(val) =>
if indexOfDec > 0 {
cleanedValue->String.slice(~start=0, ~end={indexOfDec + val + 1})
} else {
""
}
| None => ""
}
let finalVal =
precisionCheckedVal->LogicUtils.isNonEmptyString ? precisionCheckedVal : cleanedValue
setLocalStrValue(_ => finalVal->JSON.Encode.string)
switch finalVal->JSON.Encode.string->getFloat {
| Some(num) => input.onChange(num->Identity.anyTypeToReactEvent)
| None =>
if value->LogicUtils.isEmptyString {
input.onChange(JSON.Encode.null->Identity.anyTypeToReactEvent)
}
}
},
}
}, (localStrValue, input))
React.useEffect(() => {
setLocalStrValue(prevLocalStr => {
let numericPrevLocalValue =
prevLocalStr
->JSON.Decode.string
->Option.flatMap(Float.fromString)
->Option.map(JSON.Encode.float)
->Option.getOr(JSON.Encode.null)
if input.value === numericPrevLocalValue {
prevLocalStr
} else {
input.value
}
})
None
}, [input.value])
<TextInput
input=modifiedInput
customStyle
placeholder
isDisabled
type_
inputMode
?maxLength
?pattern
?autoComplete
?min
?max
shouldSubmitForm
widthMatchwithPlaceholderLength
?leftIcon
?rightIcon
?iconOpacity
?customPaddingClass
?rightIconCustomStyle
?leftIconCustomStyle
?removeValidationCheck
/>
}
| 934 | 10,097 |
hyperswitch-control-center | src/components/form/FormValuesSpy.res | .res | module JsonBox = {
@react.component
let make = (~json) => {
<div
className="flex-1 border border-purple-500 m-2 overflow-scroll whitespace-pre font-fira-code">
{json->JSON.stringifyWithIndent(2)->React.string}
</div>
}
}
@react.component
let make = (~wrapperClass="", ~jsonModifier=?, ~restrictToLocal=true, ~displayProps=true) => {
let subs = ReactFinalForm.useFormSubscription(["values"])
let canRender = if restrictToLocal {
Window.Location.hostname === "localhost"
} else {
true
}
if canRender {
<div className={`${wrapperClass} flex flex-col overflow-hidden`}>
<ReactFinalForm.FormSpy subscription=subs>
{props => {
<>
{if displayProps {
<JsonBox json=props.values />
} else {
React.null
}}
{switch jsonModifier {
| Some(modifierFn) => <JsonBox json={modifierFn(props.values)} />
| None => React.null
}}
</>
}}
</ReactFinalForm.FormSpy>
</div>
} else {
React.null
}
}
| 260 | 10,098 |
hyperswitch-control-center | src/components/form/PillInput.res | .res | @send external focus: Dom.element => unit = "focus"
@react.component
let make = (~name, ~initialItems: array<string>=[], ~placeholder, ~duplicateCheck=true) => {
let form = ReactFinalForm.useForm()
let (items, setItems) = React.useState(_ => initialItems)
let (inputValue, setInputValue) = React.useState(_ => "")
let (editInput, setEditInput) = React.useState(_ => "")
let (editingItem, setEditingItem) = React.useState(_ => None)
let (error, setError) = React.useState(_ => "")
let (suggestion, setSuggestion) = React.useState(_ => None)
let enterKeyCode = 14
let handleInputChange = e => {
let value = ReactEvent.Form.target(e)["value"]
setInputValue(_ => value)
setError(_ => "")
if !CommonAuthUtils.isValidEmail(value) {
setSuggestion(_ => Some(value))
} else {
setSuggestion(_ => None)
}
}
let handleEditChange = e => {
let value = ReactEvent.Form.target(e)["value"]
setEditInput(_ => value)
setError(_ => "")
}
let addItem = elem => {
let trimmedItem = String.trim(elem)
if trimmedItem->LogicUtils.isEmptyString {
setInputValue(_ => "")
setError(_ => "")
setSuggestion(_ => None)
}
if duplicateCheck && Array.some(items, existingItem => existingItem == trimmedItem) {
setError(_ => "Email already exists")
setSuggestion(_ => None)
} else if !CommonAuthUtils.isValidEmail(trimmedItem) {
setItems(prev => Array.concat(prev, [trimmedItem]))
form.change(name, [...items, elem]->Identity.genericTypeToJson)
setInputValue(_ => "")
setError(_ => "")
setSuggestion(_ => None)
} else {
setError(_ => "Invalid Email")
setSuggestion(_ => None)
}
}
let handleSuggestionClick = () => {
switch suggestion {
| Some(suggestedEmail) => addItem(suggestedEmail)
| None => ()
}
}
let removeItem = itemToRemove => {
form.change(name, items->Array.filter(ele => ele !== itemToRemove)->Identity.genericTypeToJson)
setItems(prev => prev->Array.filter(item => item != itemToRemove))
}
let saveItem = itemToSave => {
let trimmedEditInput = String.trim(editInput)
let isDuplicate =
duplicateCheck &&
trimmedEditInput != itemToSave &&
Array.some(items, existingItem => existingItem == trimmedEditInput)
if isDuplicate {
setError(_ => "Email already exists")
setEditInput(_ => itemToSave)
} else if !CommonAuthUtils.isValidEmail(trimmedEditInput) {
setItems(prev => prev->Array.map(item => item == itemToSave ? trimmedEditInput : item))
let updatedArray =
items
->Array.filter(ele => ele !== itemToSave)
->Array.concat([trimmedEditInput])
form.change(name, updatedArray->Identity.genericTypeToJson)
setEditingItem(_ => None)
setEditInput(_ => "")
setError(_ => "")
} else {
setEditInput(_ => itemToSave)
setError(_ => "Invalid Email")
}
}
let handleKeyDown = e => {
let key = e->ReactEvent.Keyboard.key
let keyCode = e->ReactEvent.Keyboard.keyCode
if key === "Enter" || keyCode === enterKeyCode {
ReactEvent.Keyboard.preventDefault(e)
switch suggestion {
| Some(suggestedEmail) => addItem(suggestedEmail)
| None => addItem(inputValue)
}
}
}
let handleEditKeydown = (item, ev) => {
let key = ev->ReactEvent.Keyboard.key
let keyCode = ev->ReactEvent.Keyboard.keyCode
if key === "Enter" || keyCode === enterKeyCode {
ReactEvent.Keyboard.preventDefault(ev)
saveItem(item)
}
}
let toggleEditingItem = (item, event) => {
event->ReactEvent.Mouse.stopPropagation
setEditingItem(_ => Some(item))
setEditInput(_ => item)
}
let inputRef = React.useRef(Nullable.null)
let handleContainerClick = () => {
switch inputRef.current->Nullable.toOption {
| Some(inputElement) => inputElement->focus
| None => ()
}
}
<div className="w-full cursor-text" onClick={_ => handleContainerClick()}>
<div className="w-full flex flex-wrap gap-2 border p-2 text-sm rounded-md">
{items
->Array.mapWithIndex((item, i) =>
<div key={Int.toString(i)} className="flex flex-wrap gap-1 p-1 border rounded-md">
<RenderIf condition={editingItem == Some(item)}>
<input
onClick={event => event->ReactEvent.Mouse.stopPropagation}
type_="text"
value={editInput}
onBlur={_ => saveItem(item)}
onInput=handleEditChange
onKeyDown={ev => handleEditKeydown(item, ev)}
className="rounded-md p-1 flex-grow"
/>
</RenderIf>
<RenderIf condition={editingItem != Some(item)}>
<div
className="cursor-pointer px-2 py-1 flex-grow"
onClick={event => toggleEditingItem(item, event)}>
{React.string(item)}
</div>
</RenderIf>
<button onClick={_ => removeItem(item)} className="hover:bg-gray-300 rounded-md p-1">
<Icon name="cross-outline" size=14 />
</button>
</div>
)
->React.array}
<div className="relative">
<input
ref={inputRef->ReactDOM.Ref.domRef}
type_="text"
value={inputValue}
placeholder
onChange=handleInputChange
onKeyDown=handleKeyDown
className="outline-none p-2 flex-grow"
name
/>
<RenderIf condition={suggestion->Option.isSome}>
<div
onClick={_ => handleSuggestionClick()}
className="absolute z-10 min-w-80 bg-white border rounded-md shadow-lg mt-1 cursor-pointer top-10 h-16">
<div className="bg-gray-200 w-full h-[calc(100%-16px)] my-2 flex items-center px-4">
<div className="flex items-center gap-2">
<Icon name="user" size=14 className="text-blue-600" />
<span className="font-medium"> {React.string(suggestion->Option.getOr(""))} </span>
</div>
</div>
</div>
</RenderIf>
</div>
</div>
<RenderIf condition={!(error->LogicUtils.isEmptyString)}>
<div className="flex gap-1 mt-2">
<Icon name="exclamation-circle" size=12 className="text-red-600" />
<p className="text-red-600 text-xs"> {React.string(error)} </p>
</div>
</RenderIf>
</div>
}
| 1,560 | 10,099 |
hyperswitch-control-center | src/components/form/MultipleTextInput.res | .res | module Tag = {
@react.component
let make = (~text, ~remove, ~customButtonStyle=?, ~disabled=false) => {
let handleOnRemove = e => {
e->ReactEvent.Mouse.stopPropagation
remove(text)
}
let buttonStyle = switch customButtonStyle {
| Some(buttonStyle) => buttonStyle
| None => ""
}
if !disabled {
<Button
customButtonStyle={`h-8 ${buttonStyle}`}
text
textWeight="font-bold"
disableRipple=true
textStyle="text-inherit dark:text-white"
rightIcon={CustomIcon(
<Icon name="close" size=10 className="mr-1" onClick={handleOnRemove} />,
)}
/>
} else {
React.null
}
}
}
@react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~name="tag_value",
~disabled=false,
~seperateByComma=false,
~seperateBySpace=false,
~customStyle=?,
~placeholder="",
~autoComplete=?,
~customButtonStyle=?,
) => {
let showPopUp = PopUpState.useShowPopUp()
let currentTags = React.useMemo(() => {
input.value->JSON.Decode.array->Option.getOr([])->Belt.Array.keepMap(JSON.Decode.string)
}, [input.value])
let setTags = tags => {
tags->Identity.arrayOfGenericTypeToFormReactEvent->input.onChange
}
let (text, setText) = React.useState(_ => "")
let customStyleClass = customStyle->Option.getOr("gap-2 w-full px-1 py-1")
let onTagRemove = text => {
setTags(currentTags->Array.filter(tag => tag !== text))
}
let keyDownCondition = React.useMemo(() => {
open ReactEvent.Keyboard
ev => {
if ev->keyCode === 13 {
ev->preventDefault
ev->stopPropagation
}
ev->keyCode === 9
}
}, [])
let handleKeyDown = e => {
open ReactEvent.Keyboard
let isEmpty = text->LogicUtils.isEmptyString
if isEmpty && (e->key === "Backspace" || e->keyCode === 8) && currentTags->Array.length > 0 {
setText(_ => currentTags[currentTags->Array.length - 1]->Option.getOr(""))
setTags(currentTags->Array.slice(~start=0, ~end=-1))
} else if text->String.length !== 0 {
if e->key === "Enter" || e->keyCode === 13 || e->key === "Tab" || e->keyCode === 9 {
if seperateByComma {
let arr = text->String.split(",")
let newArr = []
arr->Array.forEach(ele => {
if (
!(newArr->Array.includes(ele->String.trim)) &&
!(currentTags->Array.includes(ele->String.trim))
) {
if ele->String.trim->LogicUtils.isNonEmptyString {
newArr->Array.push(ele->String.trim)->ignore
}
}
})
setTags(currentTags->Array.concat(newArr))
} else if seperateBySpace {
let arr = text->String.split(" ")
let newArr = []
arr->Array.forEach(ele => {
if (
!(newArr->Array.includes(ele->String.trim)) &&
!(currentTags->Array.includes(ele->String.trim))
) {
if ele->String.trim->LogicUtils.isNonEmptyString {
newArr->Array.push(ele->String.trim)->ignore
}
}
})
setTags(currentTags->Array.concat(newArr))
} else if !(currentTags->Array.includes(text->String.trim)) {
setTags(currentTags->Array.concat([text->String.trim]))
}
setText(_ => "")
}
}
}
let input1: ReactFinalForm.fieldRenderPropsInput = {
{
name,
onBlur: _ => (),
onChange: ev => {
let value = {ev->ReactEvent.Form.target}["value"]
if value->String.includes("<script>") || value->String.includes("</script>") {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Script Tags are not allowed`,
description: React.string(`Input cannot contain <script>, </script> tags`),
handleConfirm: {text: "OK"},
})
}
let val = value->String.replace("<script>", "")->String.replace("</script>", "")
setText(_ => val)
},
onFocus: _ => (),
value: JSON.Encode.string(text),
checked: false,
}
}
let className = `flex flex-wrap items-center ${customStyleClass} bg-transparent
text-jp-gray-900 text-opacity-75 dark:text-jp-gray-text_darktheme dark:text-opacity-75 text-sm font-semibold
placeholder-jp-gray-900 placeholder-opacity-25 dark:placeholder-jp-gray-text_darktheme dark:placeholder-opacity-25
border rounded border-opacity-75 border-jp-gray-lightmode_steelgray hover:border-jp-gray-600 dark:border-jp-gray-960 dark:hover:border-jp-gray-900`
<div className>
{currentTags
->Array.map(tag => {
if tag->LogicUtils.isNonEmptyString && tag !== "<script>" && tag !== "</script>" {
<Tag key=tag text=tag remove=onTagRemove disabled ?customButtonStyle />
} else {
React.null
}
})
->React.array}
<TextInput
input=input1
focusOnKeyPress={keyDownCondition}
placeholder
?autoComplete
onKeyUp=handleKeyDown
isDisabled=disabled
customStyle="dark:bg-jp-gray-970 border-none"
/>
</div>
}
| 1,279 | 10,100 |
hyperswitch-control-center | src/components/form/PasswordStrengthInput.res | .res | type regexTest = {
regex: Js.Re.t,
weight: float,
}
type warningColor = Red | Yellow | Green
type warningMessage = {
message: string,
color: warningColor,
}
@react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~displayStatus=true,
~leftIcon=?,
(),
) => {
let tests = [
{
regex: %re("/[0-9]/g"),
weight: 1.0,
},
{
regex: %re("/[a-z]/g"),
weight: 1.0,
},
{
regex: %re("/[A-Z]/g"),
weight: 1.0,
},
{
regex: %re("/[$@$!%*#?&]/g"),
weight: 2.0,
},
]
let (passwordStatus, setPasswordStatus) = React.useState(() => {message: "", color: Red})
let newInput = {
...input,
onChange: ev => {
input.onChange(ev)
let strVal = ReactEvent.Form.target(ev)["value"]
let (variety, score) = tests->Array.reduce((0, 0.0), (acc, test) => {
let (accVariety, accScore) = acc
let res = Js.Re.exec_(test.regex, strVal)
let result = switch res {
| Some(val) => Js.Re.captures(val)
| None => []
}
let nonEmptyResult = result->Array.length != 0
let localVariety = nonEmptyResult ? accVariety + 1 : 0
let localScore =
accScore +.
(test.weight *. result->Array.length->Int.toFloat +.
strVal->String.length->Int.toFloat *. 1.2)
(localVariety, localScore)
})
let newPasswordStatus = if strVal->String.length <= 1 {
{message: "", color: Red}
} else if variety != 4 {
{message: "Too Simple", color: Red}
} else if score >= 90.0 {
{message: "Strong", color: Green}
} else if score >= 65.0 {
{message: "Good", color: Green}
} else if score >= 40.0 {
{message: "Average", color: Yellow}
} else {
{message: "Bad", color: Red}
}
setPasswordStatus(_ => newPasswordStatus)
},
}
let displayColor = if passwordStatus.color == Red {
"text-red-500"
} else if passwordStatus.color == Yellow {
"text-yellow-500"
} else {
"text-green-700"
}
<div>
<div>
<TextInput input=newInput placeholder type_="password" ?leftIcon />
</div>
{displayStatus
? <div className=displayColor> {React.string(passwordStatus.message)} </div>
: React.null}
</div>
}
| 677 | 10,101 |
hyperswitch-control-center | src/components/form/BoolInput.res | .res | external ffInputToBoolInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput<
bool,
> = "%identity"
module BaseComponent = {
@react.component
let make = (
~isSelected,
~setIsSelected,
~size: CheckBoxIcon.size=Small,
~isDisabled=false,
~boolCustomClass="",
~addAttributeId="",
~toggleBorder="border-green-950",
~toggleEnableColor="bg-green-950",
~customToggleHeight="16px",
~customToggleWidth="30px",
~customInnerCircleHeight="12px",
~transformValue="14px",
) => {
let toggleSelect = React.useCallback(_ => {
if !isDisabled {
setIsSelected(!isSelected)
}
}, (isDisabled, isSelected, setIsSelected))
let isMobileView = MatchMedia.useMobileChecker()
let toggleEnableColor = ` ${toggleEnableColor} border dark:bg-green-950 `
let toggleBorder = `border ${toggleBorder}`
let toggleColor = "bg-gradient-to-t from-jp-gray-200 to-jp-gray-250 dark:from-jp-gray-darkgray_background dark:to-jp-gray-darkgray_background"
let boolCustomClass = if boolCustomClass->LogicUtils.isEmptyString {
if isMobileView {
""
} else {
"mx-4"
}
} else {
boolCustomClass
}
let selectedClass = `${boolCustomClass} ${toggleEnableColor}`
let borderSelectedClass = `${toggleBorder}`
let defaultInputClass = `${boolCustomClass} ${toggleColor}`
let defaultBorder = "border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960"
let backgroundClass = if isSelected {
selectedClass
} else {
defaultInputClass
}
let borderClass = if isSelected && !isDisabled {
borderSelectedClass
} else {
defaultBorder
}
let shadowClass = ""
let transformValue = if isSelected {
`translateX(${transformValue})`
} else {
"translateX(0px)"
}
let cursorClass = if isDisabled {
"cursor-not-allowed"
} else {
"cursor-pointer"
}
let circleColor = if isSelected {
"bg-white"
} else if isDisabled {
"bg-jp-gray-900 bg-opacity-50 dark:bg-jp-gray-900 dark:bg-opacity-40"
} else {
"bg-jp-gray-900 bg-opacity-50 dark:bg-white dark:bg-opacity-100"
}
let innerShadow = ""
let roundedClass = "rounded-2.5"
let toggleHeight = `${customToggleHeight}`
let toggleWidth = `${customToggleWidth}`
let innerCircleHeight = `${customInnerCircleHeight}`
let innerCircleWidth = innerCircleHeight
<AddDataAttributes
attributes=[
("data-bool-value", isSelected ? "on" : "off"),
("data-bool-for", addAttributeId),
]>
<div
style={
width: toggleWidth,
height: toggleHeight,
minWidth: toggleWidth,
}
onClick=toggleSelect
className={`flex items-center transition ${roundedClass} ${backgroundClass} ${borderClass} ${cursorClass} ${shadowClass}`}>
<div
style={
width: innerCircleWidth,
height: innerCircleHeight,
transform: transformValue,
}
className={`transition rounded-full ${circleColor} ${innerShadow}`}
/>
</div>
</AddDataAttributes>
}
}
@react.component
let make = (
~input as baseInput: ReactFinalForm.fieldRenderPropsInput,
~isDisabled=false,
~isCheckBox=false,
~boolCustomClass="",
~addAttributeId="",
) => {
let boolInput = baseInput->ffInputToBoolInput
let boolValue: JSON.t = boolInput.value
let isSelected = switch boolValue->JSON.Classify.classify {
| Bool(true) => true
| String(str) => str === "true"
| _ => false
}
let setIsSelected = boolInput.onChange
isCheckBox
? <CheckBoxIcon isSelected setIsSelected isDisabled={isDisabled} />
: <BaseComponent
isSelected setIsSelected isDisabled={isDisabled} boolCustomClass addAttributeId
/>
}
| 986 | 10,102 |
hyperswitch-control-center | src/components/form/PasswordStrengthInputAsChips.res | .res | type passwordCheck = {
number: bool,
lowercase: bool,
uppercase: bool,
specialChar: bool,
minEightChars: bool,
}
type chipType = Number | Lowercase | Uppercase | SpecialChar | MinEightChars
module PasswordChip = {
@react.component
let make = (~passwordChecks: passwordCheck, ~chipType: chipType, ~customTextStyle="") => {
let initalClassName = " bg-gray-50 dark:bg-jp-gray-960/75 border-gray-300 inline-block text-xs p-2 border-0.5 dark:border-0 border-gray-300 rounded-2xl"
let passedClassName = "flex items-center bg-green-50 dark:bg-green-700/25 border-gray-300 inline-block text-xs p-2 border-0.5 border-green-700 rounded-2xl gap-1"
let (isCheckPassed, checkName) = switch chipType {
| Number => (passwordChecks.number, "Numbers")
| Lowercase => (passwordChecks.lowercase, "Lowercase Letters")
| Uppercase => (passwordChecks.uppercase, "Uppercase Letters")
| SpecialChar => (passwordChecks.specialChar, "Special Characters")
| MinEightChars => (passwordChecks.minEightChars, "8 Characters")
}
let textClass = isCheckPassed ? "text-green-700 font-medium" : "font-base dark:text-gray-100"
<p className={isCheckPassed ? passedClassName : initalClassName}>
<RenderIf condition=isCheckPassed>
<Icon name="check" size=9 />
</RenderIf>
<span className={`${textClass} ${customTextStyle}`}> {React.string(checkName)} </span>
</p>
}
}
@react.component
let make = (
~input: ReactFinalForm.fieldRenderPropsInput,
~placeholder,
~leftIcon=?,
~autoComplete="new-password",
~customStyle="",
~customPaddingClass="",
~customTextStyle="",
~specialCharatersInfoText="",
~customDashboardClass=?,
) => {
let initialPasswordState = {
number: false,
lowercase: false,
uppercase: false,
specialChar: false,
minEightChars: false,
}
let (passwordChecks, setPasswordChecks) = React.useState(_ => initialPasswordState)
let (showValidation, setShowValidation) = React.useState(_ => false)
let modalRef = React.useRef(Nullable.null)
OutsideClick.useOutsideClick(
~refs={ArrayOfRef([modalRef])},
~isActive=showValidation,
~callback=() => {
setShowValidation(_ => false)
},
)
let validateFunc = strVal => {
if strVal->String.length >= 8 {
setPasswordChecks(prev => {
...prev,
minEightChars: true,
})
}
if RegExp.test(%re("/^(?=.*[A-Z])/"), strVal) {
setPasswordChecks(prev => {
...prev,
uppercase: true,
})
}
if RegExp.test(%re("/^(?=.*[a-z])/"), strVal) {
setPasswordChecks(prev => {
...prev,
lowercase: true,
})
}
if RegExp.test(%re("/^(?=.*[0-9])/"), strVal) {
setPasswordChecks(prev => {
...prev,
number: true,
})
}
let specialCharCheck = RegExp.test(%re("/^(?=.*[!@#$%^&*_])/"), strVal)
if specialCharCheck {
setPasswordChecks(prev => {
...prev,
specialChar: true,
})
}
}
let newInput = {
...input,
onChange: ev => {
input.onChange(ev)
setPasswordChecks(_ => initialPasswordState)
let strVal = ReactEvent.Form.target(ev)["value"]
strVal->LogicUtils.isNonEmptyString
? setShowValidation(_ => true)
: setShowValidation(_ => false)
strVal->validateFunc
},
onBlur: ev => {
setShowValidation(_ => false)
input.onBlur(ev)
},
}
let passwordChips = [MinEightChars, Lowercase, Number, SpecialChar, Uppercase]
<>
<TextInput
input=newInput
placeholder
type_="password"
autoComplete
?leftIcon
customStyle
customPaddingClass
?customDashboardClass
/>
<div
className={`${showValidation
? "block"
: "hidden"} flex flex-row flex-wrap gap-y-3 gap-x-2 mt-3`}>
{passwordChips
->Array.mapWithIndex((chipType, index) => {
if specialCharatersInfoText->LogicUtils.isNonEmptyString && chipType === SpecialChar {
<ToolTip
tooltipWidthClass="w-fit"
description=specialCharatersInfoText
toolTipFor={<PasswordChip
key={`check_${index->Int.toString}`} passwordChecks chipType customTextStyle
/>}
/>
} else {
<PasswordChip
key={`check_${index->Int.toString}`} passwordChecks chipType customTextStyle
/>
}
})
->React.array}
</div>
</>
}
| 1,153 | 10,103 |
hyperswitch-control-center | src/components/portal/PortalCapture.res | .res | @react.component
let make = React.memo((~name: string, ~customStyle="") => {
let setPortalNodes = Recoil.useSetRecoilState(PortalState.portalNodes)
let setDiv = React.useCallback2((elem: Nullable.t<Dom.element>) => {
setPortalNodes(
prevDict => {
let clonedDict =
prevDict
->Dict.toArray
->Array.filter(
entry => {
let (key, _val) = entry
key !== name
},
)
->Dict.fromArray
switch elem->Nullable.toOption {
| Some(elem) => Dict.set(clonedDict, name, elem)
| None => ()
}
clonedDict
},
)
}, (setPortalNodes, name))
<div className={`${customStyle}`} ref={ReactDOM.Ref.callbackDomRef(setDiv)} />
})
| 188 | 10,104 |
hyperswitch-control-center | src/components/portal/Portal.res | .res | @react.component
let make = (~to, ~children) => {
let portalNodes = Recoil.useRecoilValueFromAtom(PortalState.portalNodes)
let portalNode = Dict.get(portalNodes, to)
switch portalNode {
| Some(domNode) => ReactDOM.createPortal(children, domNode)
| None => children
}
}
| 76 | 10,105 |
hyperswitch-control-center | src/components/portal/PortalState.res | .res | let defaultDict: Dict.t<Dom.element> = Dict.make()
let portalNodes = Recoil.atom("portalNodes", defaultDict)
| 28 | 10,106 |
hyperswitch-control-center | src/components/Graphs/LineAndColumn/LineAndColumnGraph.res | .res | external lineColumnGraphOptionsToJson: LineAndColumnGraphTypes.lineColumnGraphOptions => JSON.t =
"%identity"
@react.component
let make = (~options: LineAndColumnGraphTypes.lineColumnGraphOptions, ~className="") => {
<div className>
<Highcharts.Chart
options={options->lineColumnGraphOptionsToJson} highcharts={Highcharts.highcharts}
/>
</div>
}
| 87 | 10,107 |
hyperswitch-control-center | src/components/Graphs/LineAndColumn/LineAndColumnGraphUtils.res | .res | open LineAndColumnGraphTypes
let darkGray = "#525866"
let lightGray = "#999999"
let gridLineColor = "#e6e6e6"
let fontFamily = "InterDisplay"
let labelFormatter = (
@this
this => {
`<div style="display: flex; align-items: center;">
<div style="width: 13px; height: 13px; background-color:${this.color}; border-radius:3px;"></div>
<div style="margin-left: 5px;">${this.name}</div>
</div>`
}
)->asLegendsFormatter
let getLineColumnGraphOptions = (lineColumnGraphOptions: lineColumnGraphPayload) => {
let {
categories,
data,
tooltipFormatter,
yAxisFormatter,
titleObj,
minValY2,
maxValY2,
legend,
} = lineColumnGraphOptions
let stepInterval = Js.Math.max_int(
Js.Math.ceil_int(categories->Array.length->Int.toFloat /. 10.0),
1,
)
let yAxis: LineAndColumnGraphTypes.yAxis = [
{
title: titleObj.oppositeYAxisTitle,
opposite: true,
gridLineWidth: 1,
gridLineColor,
gridLineDashStyle: "Dash",
labels: {
align: "center",
style: {
color: lightGray,
fontFamily,
},
x: 5,
formatter: yAxisFormatter,
},
min: minValY2,
max: Some(maxValY2),
},
{
title: titleObj.yAxisTitle,
opposite: false,
gridLineWidth: 1,
gridLineColor,
gridLineDashStyle: "Dash",
labels: {
align: "center",
style: {
color: lightGray,
fontFamily,
},
x: 5,
},
min: 0,
},
]
{
chart: {
zoomType: "xy",
spacingLeft: 20,
spacingRight: 20,
style: {
color: darkGray,
fontFamily,
fontSize: "12px",
},
},
title: titleObj.chartTitle,
xAxis: {
title: titleObj.xAxisTitle,
categories,
crosshair: true,
lineWidth: 1,
tickWidth: 1,
labels: {
align: "center",
style: {
color: lightGray,
fontFamily,
},
y: 35,
},
tickInterval: stepInterval,
gridLineWidth: 1,
gridLineColor,
gridLineDashStyle: "Dash",
tickmarkPlacement: "on",
endOnTick: false,
startOnTick: false,
},
tooltip: {
style: {
padding: "0px",
fontFamily,
fontSize: "14px",
},
shape: "square",
shadow: false,
backgroundColor: "transparent",
borderColor: "transparent",
borderWidth: 0.0,
formatter: tooltipFormatter,
useHTML: true,
shared: true, // Allows multiple series' data to be shown in a single tooltip
},
yAxis,
legend: {
...legend,
useHTML: true,
labelFormatter,
symbolPadding: -7,
symbolWidth: 0,
symbolHeight: 0,
symbolRadius: 4,
itemStyle: {
fontFamily,
fontSize: "12px",
color: darkGray,
fontWeight: "400",
},
},
plotOptions: {
line: {
marker: {
enabled: false,
},
},
column: {
pointWidth: 10, // Adjust width of bars
borderRadius: 3, // Rounds the top corners
},
},
series: data,
credits: {
enabled: false,
},
}
}
let lineColumnGraphTooltipFormatter = (
~title,
~metricType: LogicUtilsTypes.valueType,
~currency="$",
~showNameInTooltip=false,
) => {
open LogicUtils
(
@this
(this: pointFormatter) => {
let title = `<div style="font-size: 16px; font-weight: bold;">${title}</div>`
let defaultValue = {color: "", x: "", y: 0.0, point: {index: 0}, key: "", series: {name: ""}}
let primartPoint = this.points->getValueFromArray(0, defaultValue)
let line1Point = this.points->getValueFromArray(1, defaultValue)
let line2Point = this.points->getValueFromArray(2, defaultValue)
let getRowsHtml = (~iconColor, ~date, ~value, ~comparisionComponent="", ~name="") => {
let formattedValue = LogicUtils.valueFormatter(value, metricType, ~currency)
let key = showNameInTooltip ? name : date
`<div style="display: flex; align-items: center;">
<div style="width: 10px; height: 10px; background-color:${iconColor}; border-radius:3px;"></div>
<div style="margin-left: 8px;">${key}${comparisionComponent}</div>
<div style="flex: 1; text-align: right; font-weight: bold;margin-left: 25px;">${formattedValue}</div>
</div>`
}
let tableItems =
[
getRowsHtml(
~iconColor=primartPoint.color,
~date=primartPoint.key,
~value=primartPoint.y,
~name=primartPoint.series.name,
),
getRowsHtml(
~iconColor=line1Point.color,
~date=line1Point.key,
~value=line1Point.y,
~name=line1Point.series.name,
),
getRowsHtml(
~iconColor=line2Point.color,
~date=line2Point.key,
~value=line2Point.y,
~name=line2Point.series.name,
),
]->Array.joinWith("")
let content = `
<div style="
padding:5px 12px;
display:flex;
flex-direction:column;
justify-content: space-between;
gap: 7px;">
${title}
<div style="
margin-top: 5px;
display:flex;
flex-direction:column;
gap: 7px;">
${tableItems}
</div>
</div>`
`<div style="
padding: 10px;
width:fit-content;
border-radius: 7px;
background-color:#FFFFFF;
padding:10px;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
border: 1px solid #E5E5E5;
position:relative;">
${content}
</div>`
}
)->asTooltipPointFormatter
}
let lineColumnGraphYAxisFormatter = (
~statType: LogicUtilsTypes.valueType,
~currency="",
~suffix="",
~scaleFactor=1.0,
) => {
(
@this
(this: yAxisFormatter) => {
let value = this.value->Int.toFloat /. scaleFactor
let formattedValue = LogicUtils.valueFormatter(value, statType, ~currency, ~suffix)
formattedValue
}
)->asTooltipPointFormatter
}
| 1,638 | 10,108 |
hyperswitch-control-center | src/components/Graphs/LineAndColumn/LineAndColumnGraphTypes.res | .res | type \"type" = string
type zoomType = string
type spacingLeft = int
type spacingRight = int
type info = {index: int}
type series = {name: string}
type point = {color: string, x: string, y: float, point: info, key: string, series: series}
type pointFormatter = {points: array<point>}
type yAxisFormatter = {value: int}
external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string =
"%identity"
type categories = array<string>
type crosshair = bool
type lineWidth = int
type tickWidth = int
type align = string
type color = string
type y = int
type gridLineWidth = int
type gridLineColor = string
type gridLineDashStyle = string
type tickmarkPlacement = string
type endOnTick = bool
type startOnTick = bool
type min = int
type showInLegend = bool
type name = string
type pointWidth = int
type borderRadius = int
type style = {
color: color,
fontFamily?: string,
fontSize?: string,
fontWeight?: string,
}
type title = {text: string, style?: style, align?: align, x?: int, y?: int}
type enabled = {enabled: bool}
type credits = {
...enabled,
}
type exporting = {
...enabled,
}
type marker = {
...enabled,
}
type line = {marker: marker}
type column = {
pointWidth: pointWidth,
borderRadius: borderRadius,
}
type plotOptions = {line: line, column: column}
type labels = {
align: align,
style: style,
y?: y,
x?: int,
formatter?: pointFormatter => string,
}
type chart = {
zoomType: zoomType,
spacingLeft: spacingLeft,
spacingRight: spacingRight,
style: style,
}
type dataObj = {
showInLegend: showInLegend,
\"type": \"type",
name: name,
data: array<float>,
color: color,
yAxis: int,
}
type data = array<dataObj>
type yAxisObj = {
title: title,
opposite: bool,
labels: labels,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
gridLineDashStyle: gridLineDashStyle,
min: min,
max?: option<int>,
}
type yAxis = array<yAxisObj>
type xAxis = {
title: title,
categories: categories,
crosshair: crosshair,
lineWidth: lineWidth,
tickWidth: tickWidth,
labels: labels,
tickInterval: int,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
gridLineDashStyle: gridLineDashStyle,
tickmarkPlacement: tickmarkPlacement,
endOnTick: endOnTick,
startOnTick: startOnTick,
}
type cssStyle = {
fontFamily: string,
fontSize: string,
padding: string,
}
type tooltip = {
shape: string,
backgroundColor: string,
borderColor: string,
useHTML: bool,
formatter: pointFormatter => string,
shared: bool,
style: cssStyle,
borderWidth: float,
shadow: bool,
}
type itemStyle = {
fontFamily: string,
fontSize: string,
color: string,
fontWeight?: string,
}
type legendPoint = {
color: string,
name: string,
}
external asLegendsFormatter: Js_OO.Callback.arity1<'a> => legendPoint => string = "%identity"
type legend = {
useHTML: bool,
labelFormatter: legendPoint => string,
symbolPadding?: int,
symbolWidth?: int,
symbolHeight?: int,
symbolRadius?: int,
align?: string,
verticalAlign?: string,
itemStyle?: itemStyle,
itemDistance?: int,
floating?: bool,
x?: int,
y?: int,
margin?: int,
}
type lineColumnGraphOptions = {
chart: chart,
legend: legend,
title: title,
xAxis: xAxis,
yAxis: yAxis,
plotOptions: plotOptions,
series: data,
credits: credits,
tooltip: tooltip,
}
type titleObj = {
chartTitle: title,
xAxisTitle: title,
yAxisTitle: title,
oppositeYAxisTitle: title,
}
type lineColumnGraphPayload = {
categories: categories,
data: data,
titleObj: titleObj,
tooltipFormatter: pointFormatter => string,
yAxisFormatter: pointFormatter => string,
minValY2: int,
maxValY2: int,
legend: legend,
}
| 1,002 | 10,109 |
hyperswitch-control-center | src/components/Graphs/LineGraph/LineGraphTypes.res | .res | type \"type" = string
type spacingLeft = int
type spacingRight = int
type info = {index: int}
type pointSeries = {name: string}
type point = {color: string, x: string, y: float, point: info, series: pointSeries}
type pointFormatter = {points: array<point>}
type yAxisFormatter = {value: int}
external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string =
"%identity"
type categories = array<string>
type crosshair = bool
type lineWidth = int
type tickWidth = int
type align = string
type color = string
type y = int
type gridLineWidth = int
type gridLineColor = string
type gridLineDashStyle = string
type tickmarkPlacement = string
type endOnTick = bool
type startOnTick = bool
type min = int
type showInLegend = bool
type name = string
type style = {
color: color,
fontFamily?: string,
fontSize?: string,
fontWeight?: string,
}
type title = {text: string, style?: style, align?: align, x?: int, y?: int}
type enabled = {enabled: bool}
type credits = {
...enabled,
}
type exporting = {
...enabled,
}
type inactive = {...enabled, opacity: float}
type states = {inactive: inactive}
type plotSeries = {states: states}
type marker = {
...enabled,
}
type line = {marker: marker}
type plotOptions = {line: line, series: plotSeries}
type labels = {
formatter: pointFormatter => string,
align: align,
style: style,
y?: y,
x?: int,
}
type xAxisLabels = {
align: align,
style: style,
y?: y,
x?: int,
}
type chart = {
\"type": \"type",
height: int,
spacingLeft: spacingLeft,
spacingRight: spacingRight,
style: style,
}
type dataObj = {
showInLegend: showInLegend,
name: name,
data: array<float>,
color: color,
}
type data = array<dataObj>
type yAxis = {
title: title,
labels: labels,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
gridLineDashStyle: gridLineDashStyle,
min?: option<int>,
max?: option<int>,
}
type xAxis = {
categories: categories,
crosshair: crosshair,
lineWidth: lineWidth,
tickWidth: tickWidth,
labels: xAxisLabels,
tickInterval: int,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
tickmarkPlacement: tickmarkPlacement,
endOnTick: endOnTick,
startOnTick: startOnTick,
}
type cssStyle = {
fontFamily: string,
fontSize: string,
padding: string,
}
type tooltip = {
...enabled,
shape: string,
backgroundColor: string,
borderColor: string,
useHTML: bool,
formatter: pointFormatter => string,
shared: bool,
style: cssStyle,
borderWidth: float,
shadow: bool,
}
type itemStyle = {
fontFamily: string,
fontSize: string,
color: string,
fontWeight?: string,
}
type legendPoint = {
color: string,
name: string,
}
external asLegendsFormatter: Js_OO.Callback.arity1<'a> => legendPoint => string = "%identity"
type legend = {
useHTML: bool,
labelFormatter: legendPoint => string,
symbolPadding?: int,
symbolWidth?: int,
itemStyle?: itemStyle,
align?: string,
verticalAlign?: string,
floating?: bool,
x?: int,
y?: int,
margin?: int,
}
type lineGraphOptions = {
chart: chart,
legend: legend,
title: title,
xAxis: xAxis,
yAxis: yAxis,
plotOptions: plotOptions,
series: data,
credits: credits,
tooltip: tooltip,
}
type chartHeight = DefaultHeight | Custom(int)
type chartLeftSpacing = DefaultLeftSpacing | Custom(int)
type lineGraphPayload = {
chartHeight: chartHeight,
chartLeftSpacing: chartLeftSpacing,
categories: categories,
data: data,
title: title,
yAxisMaxValue: option<int>,
yAxisMinValue: option<int>,
tooltipFormatter: pointFormatter => string,
yAxisFormatter: pointFormatter => string,
legend: legend,
}
| 973 | 10,110 |
hyperswitch-control-center | src/components/Graphs/LineGraph/LineGraph.res | .res | external lineGraphOptionsToJson: LineGraphTypes.lineGraphOptions => JSON.t = "%identity"
@react.component
let make = (~options: LineGraphTypes.lineGraphOptions, ~className="") => {
<div className>
<Highcharts.Chart
options={options->lineGraphOptionsToJson} highcharts={Highcharts.highcharts}
/>
</div>
}
| 78 | 10,111 |
hyperswitch-control-center | src/components/Graphs/LineGraph/LineGraphUtils.res | .res | open LineGraphTypes
// colors
let darkGray = "#525866"
let lightGray = "#999999"
let gridLineColor = "#e6e6e6"
let fontFamily = "InterDisplay"
let valueFormatter = (
@this
this => {
`<div style="display: flex; align-items: center;">
<div style="width: 13px; height: 13px; background-color:${this.color}; border-radius:3px;"></div>
<div style="margin-left: 5px;">${this.name}</div>
</div>`
}
)->asLegendsFormatter
let lineGraphYAxisFormatter = (
~statType: LogicUtilsTypes.valueType,
~currency="",
~suffix="",
~scaleFactor=1.0,
) => {
(
@this
(this: yAxisFormatter) => {
let value = this.value->Int.toFloat /. scaleFactor
let formattedValue = LogicUtils.valueFormatter(value, statType, ~currency, ~suffix)
formattedValue
}
)->asTooltipPointFormatter
}
let getLineGraphOptions = (lineGraphOptions: lineGraphPayload) => {
let {
chartHeight,
chartLeftSpacing,
categories,
data,
title,
tooltipFormatter,
yAxisMaxValue,
yAxisMinValue,
yAxisFormatter,
legend,
} = lineGraphOptions
let stepInterval = Js.Math.max_int(
Js.Math.ceil_int(categories->Array.length->Int.toFloat /. 10.0),
1,
)
let yAxis: LineGraphTypes.yAxis = {
title: {
...title,
style: {
color: darkGray,
fontFamily, // Set the desired font family
fontSize: "12px", // Set the font size
},
},
gridLineWidth: 1,
gridLineColor,
gridLineDashStyle: "Dash",
labels: {
formatter: yAxisFormatter,
align: "center",
style: {
color: lightGray,
fontFamily, // Set the desired font family
},
x: 5,
},
}
{
chart: {
\"type": "line",
height: switch chartHeight {
| Custom(chartHeight) => chartHeight
| DefaultHeight => 400
},
spacingLeft: switch chartLeftSpacing {
| Custom(chartLeftSpacing) => chartLeftSpacing
| DefaultLeftSpacing => 20
},
spacingRight: 20,
style: {
color: darkGray,
fontFamily,
},
},
title,
xAxis: {
categories,
crosshair: true,
lineWidth: 1,
tickWidth: 1,
labels: {
align: "center",
style: {
color: lightGray,
fontFamily, // Set the desired font family
},
y: 35,
},
tickInterval: stepInterval,
gridLineWidth: 1,
gridLineColor,
tickmarkPlacement: "on",
endOnTick: false,
startOnTick: false,
},
tooltip: {
enabled: true,
style: {
padding: "0px",
fontFamily, // Set the desired font family
fontSize: "14px", // Optional: Set the font size
},
shape: "square",
shadow: false,
backgroundColor: "transparent",
borderColor: "transparent",
borderWidth: 0.0,
formatter: tooltipFormatter,
useHTML: true,
shared: true, // Allows multiple series' data to be shown in a single tooltip
},
yAxis: {
switch (yAxisMaxValue, yAxisMinValue) {
| (Some(maxVal), Some(minVal)) => {
...yAxis,
max: Some(maxVal),
min: Some(minVal),
}
| (Some(maxVal), None) => {
...yAxis,
max: Some(maxVal),
}
| (None, Some(minVal)) => {
...yAxis,
min: Some(minVal),
}
| (None, None) => yAxis
}
},
legend: {
...legend,
useHTML: true,
labelFormatter: valueFormatter,
symbolPadding: 0,
symbolWidth: 0,
itemStyle: {
fontFamily,
fontSize: "12px",
color: darkGray,
fontWeight: "400",
},
},
plotOptions: {
line: {
marker: {
enabled: false,
},
},
series: {
states: {
inactive: {
enabled: false,
opacity: 0.2,
},
},
},
},
series: data,
credits: {
enabled: false,
},
}
}
| 1,051 | 10,112 |
hyperswitch-control-center | src/components/Graphs/SankyGraph/SankeyGraph.res | .res | external sankeyGraphOptionsToJson: SankeyGraphTypes.sankeyGraphOptions => JSON.t = "%identity"
@react.component
let make = (~options: SankeyGraphTypes.sankeyGraphOptions, ~className="") => {
Highcharts.sankeyChartModule(Highcharts.highchartsModule)
<div className>
<Highcharts.Chart
options={options->sankeyGraphOptionsToJson} highcharts={Highcharts.highcharts}
/>
</div>
}
| 101 | 10,113 |
hyperswitch-control-center | src/components/Graphs/SankyGraph/SankeyGraphTypes.res | .res | type temp = {name: int}
type options = {dataLabels: temp}
type point = {sum: string, id: string, options: options}
type nodeFormatter = {point: point}
type tooltipType = Node | Link
type fromNode = {options: options}
type toNode = {options: options}
type pointFormat = {
sum: string,
id: string,
options: options,
color: string,
formatPrefix: string,
to: string,
from: string,
fromNode: fromNode,
toNode: toNode,
}
type pointFormatter = {point: pointFormat, key: string}
external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => nodeFormatter => string = "%identity"
type enabled = {enabled: bool}
type exporting = {
...enabled,
}
type credits = {...enabled}
type colors = array<string>
type keys = array<string>
type sankeyGraphData = (string, string, int, string)
type data = array<sankeyGraphData>
type \"type" = string
type name = string
type nodePadding = int
type borderRadius = int
type fontWeight = string
type fontSize = string
type color = string
type allowOverlap = bool
type crop = bool
type overflow = string
type align = string
type verticalAlign = string
type x = int
type nodeDataLabels = {
align: align,
x: x,
name: int,
}
type node = {
id: string,
dataLabels: nodeDataLabels,
}
type style = {
fontWeight: fontWeight,
fontSize: fontSize,
color: color,
fontFamily: string,
}
type dataLabels = {
style: style,
allowOverlap: allowOverlap,
crop: crop,
overflow: overflow,
align: align,
verticalAlign: verticalAlign,
nodeFormatter: nodeFormatter => string,
}
type nodes = array<node>
type chart = {
spacingLeft: int,
spacingRight: int,
}
type tooltip = {
style: style,
enabled: bool,
useHTML: bool,
formatter: nodeFormatter => string,
crosshairs: bool,
shadow: bool,
shape: string,
backgroundColor: string,
borderColor: string,
borderWidth: float,
}
type series = {
exporting: exporting,
credits: credits,
colors: colors,
keys: keys,
data: data,
\"type": \"type",
nodePadding: nodePadding,
borderRadius: borderRadius,
dataLabels: dataLabels,
nodes: nodes,
}
type title = {text: string}
type sankeyGraphOptions = {
title: title,
series: array<series>,
chart: chart,
credits: credits,
tooltip: tooltip,
}
type sankeyPayload = {
title: title,
data: data,
nodes: nodes,
colors: colors,
}
| 623 | 10,114 |
hyperswitch-control-center | src/components/Graphs/SankyGraph/SankeyGraphUtils.res | .res | open SankeyGraphTypes
// contants
let textColor = "#333333"
let fontFamily = "Arial, sans-serif"
let valueFormatter = (
@this
(this: nodeFormatter) => {
let weight = this.point.options.dataLabels.name
let sum = weight->Int.toFloat->LogicUtils.valueFormatter(Volume)
let label = `<span style="font-size: 20px; font-weight: bold;">${sum}</span><br/> <span style="font-size: 14px;">${this.point.id}</span>`
label
}
)->asTooltipPointFormatter
let tooltipFormatter = (
@this
(this: pointFormatter) => {
let pointType = this.point.formatPrefix == "node" ? Node : Link
let format = value => value->Int.toFloat->LogicUtils.valueFormatter(Volume)
let arrowIcon = "→"
let titleString = switch pointType {
| Node => this.key
| Link => `${this.point.from} ${arrowIcon} ${this.point.to}`
}
let info = switch pointType {
| Node => this.point.options.dataLabels.name->format
| Link =>
let fromValue = this.point.fromNode.options.dataLabels.name
let toValue = this.point.toNode.options.dataLabels.name
let (fraction, percentage) = if toValue > fromValue {
(`${fromValue->format} to ${toValue->format}`, "100%")
} else {
let percentage = toValue->Int.toFloat /. fromValue->Int.toFloat *. 100.0
(
`${toValue->format} of ${fromValue->format}`,
`${percentage->LogicUtils.valueFormatter(Rate)}`,
)
}
`${fraction} (${percentage})`
}
let title = `<div style="font-size: 16px; font-weight: bold;">${info}</div>`
let content = `
<div style="
padding:5px 12px;
border-left: 4px solid ${this.point.color};
display:flex;
flex-direction:column;
justify-content: space-between;
gap: 7px;">
${title}
<div style="
display:flex;
flex-direction:column;
gap: 7px;">
${titleString}
</div>
</div>`
`<div style="
padding: 10px;
width:fit-content;
border-radius: 7px;
background-color:#FFFFFF;
padding:10px;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
border: 1px solid #E5E5E5;
position:relative;">
${content}
</div>`
}
)->asTooltipPointFormatter
let getSankyGraphOptions = (payload: sankeyPayload) => {
let {data, nodes, title, colors} = payload
let style = {
fontWeight: "normal",
fontSize: "14px",
color: textColor,
fontFamily,
}
let options = {
title,
series: [
{
\"type": "sankey",
exporting: {
enabled: false,
},
credits: {
enabled: false,
},
colors,
keys: ["from", "to", "weight", "color"],
data,
nodePadding: 35,
borderRadius: 3,
dataLabels: {
nodeFormatter: valueFormatter,
style,
allowOverlap: true, // Allow labels to overlap
crop: false, // Prevent labels from being cropped
overflow: "allow", // Allow labels to overflow the chart area
align: "left",
verticalAlign: "middle",
},
nodes,
},
],
tooltip: {
enabled: true,
useHTML: true,
style,
formatter: tooltipFormatter,
crosshairs: false,
shape: "square",
shadow: false,
backgroundColor: "transparent",
borderColor: "transparent",
borderWidth: 0.0,
},
chart: {
spacingLeft: 150,
spacingRight: 150,
},
credits: {
enabled: false,
},
}
options
}
| 938 | 10,115 |
hyperswitch-control-center | src/components/Graphs/ColumnGraph/ColumnGraph.res | .res | external barGraphOptionsToJson: ColumnGraphTypes.columnGraphOptions => JSON.t = "%identity"
@react.component
let make = (~options: ColumnGraphTypes.columnGraphOptions, ~className="") => {
<div className>
<Highcharts.Chart options={options->barGraphOptionsToJson} highcharts={Highcharts.highcharts} />
</div>
}
| 75 | 10,116 |
hyperswitch-control-center | src/components/Graphs/ColumnGraph/ColumnGraphTypes.res | .res | type \"type" = string
type spacingLeft = int
type spacingRight = int
type categories = array<string>
type align = string
type color = string
type gridLineWidth = int
type gridLineColor = string
type gridLineDashStyle = string
type tickmarkPlacement = string
type endOnTick = bool
type startOnTick = bool
type tickInterval = int
type tickWidth = int
type min = int
type max = int
type showInLegend = bool
type name = string
type title = {text: string, align?: align, x?: int, y?: int}
type style = {
color: color,
fontFamily: string,
fontSize: string,
fill: string,
}
type enabled = {enabled: bool}
type credits = {
...enabled,
}
type itemStyle = {
fontFamily: string,
fontSize: string,
color: string,
}
type legendPoint = {
color: string,
name: string,
}
type legend = {
itemStyle: itemStyle,
useHTML: bool,
labelFormatter: legendPoint => string,
symbolPadding: int,
symbolWidth: int,
symbolHeight: int,
symbolRadius: int,
align: string,
verticalAlign: string,
x: int,
y: int,
}
type marker = {
...enabled,
}
type pointPadding = float
type column = {
borderWidth: int,
borderRadius: int,
stacking: string,
pointWidth: int,
grouping: bool,
}
type plotOptions = {series: column}
type chart = {
\"type": string,
height: int,
style: style,
spacingRight: spacingRight,
spacingLeft: spacingLeft,
}
type dataObj = {
name: string,
y: float,
color: string,
}
type seriesObj = {
showInLegend: bool,
name: name,
colorByPoint: bool,
data: array<dataObj>,
color: color,
}
type series = array<seriesObj>
type info = {index: int}
type point = {color: string, x: string, y: float, point: info, key: string}
type pointFormatter = {points: array<point>}
type yAxisFormatter = {value: int}
type labels = {formatter: pointFormatter => string}
type yAxis = {title: title, labels: labels, gridLineDashStyle: gridLineDashStyle}
type xAxis = {\"type": string}
external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string =
"%identity"
external asLegendsFormatter: Js_OO.Callback.arity1<'a> => legendPoint => string = "%identity"
type cssStyle = {
fontFamily: string,
fontSize: string,
padding: string,
}
type tooltip = {
shape: string,
backgroundColor: string,
borderColor: string,
useHTML: bool,
formatter: pointFormatter => string,
shared: bool,
style: cssStyle,
borderWidth: float,
shadow: bool,
}
type columnGraphOptions = {
chart: chart,
title: title,
xAxis: xAxis,
yAxis: yAxis,
legend: legend,
plotOptions: plotOptions,
series: series,
credits: credits,
tooltip: tooltip,
}
type columnGraphPayload = {
data: series,
title: title,
tooltipFormatter: pointFormatter => string,
yAxisFormatter: pointFormatter => string,
}
| 747 | 10,117 |
hyperswitch-control-center | src/components/Graphs/ColumnGraph/ColumnGraphUtils.res | .res | // constants
let fontFamily = "InterDisplay"
let darkGray = "#525866"
open ColumnGraphTypes
let labelFormatter = (
@this
(this: legendPoint) => {
`<div style="display: flex; align-items: center;">
<div style="width: 13px; height: 13px; background-color:${this.color}; border-radius:3px;"></div>
<div style="margin-left: 5px;">${this.name}</div>
</div>`
}
)->asLegendsFormatter
let getColumnGraphOptions = (columnGraphOptions: columnGraphPayload) => {
let {data, title, tooltipFormatter, yAxisFormatter} = columnGraphOptions
let style = {
fontFamily,
fontSize: "12px",
color: darkGray,
fill: darkGray,
}
{
chart: {
\"type": "column",
spacingLeft: 0,
spacingRight: 0,
height: 300,
style,
},
title,
xAxis: {
\"type": "category",
},
yAxis: {
labels: {
formatter: yAxisFormatter,
},
title: {
text: "",
},
gridLineDashStyle: "Dash",
},
tooltip: {
style: {
padding: "0px",
fontFamily,
fontSize: "14px",
},
shape: "square",
shadow: false,
backgroundColor: "transparent",
borderColor: "transparent",
borderWidth: 0.0,
formatter: tooltipFormatter,
useHTML: true,
shared: true,
},
legend: {
useHTML: false,
labelFormatter,
symbolPadding: 12,
symbolWidth: 0,
symbolHeight: 0,
symbolRadius: 3,
itemStyle: {
fontFamily,
fontSize: "12px",
color: darkGray,
},
align: "right",
verticalAlign: "top",
x: 0,
y: 0,
},
plotOptions: {
series: {
borderWidth: 0,
borderRadius: 5,
stacking: "",
grouping: true,
pointWidth: 30,
},
},
series: data,
credits: {
enabled: false,
},
}
}
let columnGraphTooltipFormatter = (
~title,
~metricType: LogicUtilsTypes.valueType,
~comparison: option<DateRangeUtils.comparison>=None,
) => {
(
@this
(this: pointFormatter) => {
let title = `<div style="font-size: 16px; font-weight: bold;">${title}</div>`
let _defaultValue = {color: "", x: "", y: 0.0, point: {index: 0}, key: ""}
let getRowsHtml = (~iconColor, ~date, ~value, ~comparisionComponent="") => {
let formattedValue = LogicUtils.valueFormatter(value, metricType, ~currency="$")
`<div style="display: flex; align-items: center;">
<div style="width: 10px; height: 10px; background-color:${iconColor}; border-radius:3px;"></div>
<div style="margin-left: 8px;">${date}${comparisionComponent}</div>
<div style="flex: 1; text-align: right; font-weight: bold;margin-left: 25px;">${formattedValue}</div>
</div>`
}
let tableItems = {
this.points->Array.reverse
this.points
->Array.mapWithIndex((point, index) => {
let defaultValue = {color: "", x: "", y: 0.0, point: {index: 0}, key: ""}
let {color, key, y} = point
let showComparison = index == 0 ? true : false
let secondaryPoint =
this.points->LogicUtils.getValueFromArray(index == 1 ? 0 : 1, defaultValue)
getRowsHtml(
~iconColor=color,
~date=key,
~value=y,
~comparisionComponent={
switch comparison {
| Some(value) =>
value == DateRangeUtils.EnableComparison && showComparison
? NewAnalyticsUtils.getToolTipConparision(
~primaryValue=y,
~secondaryValue=secondaryPoint.y,
)
: ""
| None => ""
}
},
)
})
->Array.joinWith("")
}
let content = `
<div style="
padding:5px 12px;
display:flex;
flex-direction:column;
justify-content: space-between;
gap: 7px;">
${title}
<div style="
margin-top: 5px;
display:flex;
flex-direction:column;
gap: 7px;">
${tableItems}
</div>
</div>`
`<div style="
padding: 10px;
width:fit-content;
border-radius: 7px;
background-color:#FFFFFF;
padding:10px;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
border: 1px solid #E5E5E5;
position:relative;">
${content}
</div>`
}
)->asTooltipPointFormatter
}
let columnGraphYAxisFormatter = (
~statType: LogicUtilsTypes.valueType,
~currency="",
~suffix="",
~scaleFactor=1.0,
) => {
(
@this
(this: yAxisFormatter) => {
let value = this.value->Int.toFloat /. scaleFactor
let formattedValue = LogicUtils.valueFormatter(value, statType, ~currency, ~suffix)
formattedValue
}
)->asTooltipPointFormatter
}
| 1,286 | 10,118 |
hyperswitch-control-center | src/components/Graphs/BarGraph/BarGraph.res | .res | external barGraphOptionsToJson: BarGraphTypes.barGraphOptions => JSON.t = "%identity"
@react.component
let make = (~options: BarGraphTypes.barGraphOptions, ~className="") => {
<div className>
<Highcharts.Chart options={options->barGraphOptionsToJson} highcharts={Highcharts.highcharts} />
</div>
}
| 75 | 10,119 |
hyperswitch-control-center | src/components/Graphs/BarGraph/BarGraphTypes.res | .res | type \"type" = string
type spacingLeft = int
type spacingRight = int
type categories = array<string>
type align = string
type color = string
type gridLineWidth = int
type gridLineColor = string
type gridLineDashStyle = string
type tickmarkPlacement = string
type endOnTick = bool
type startOnTick = bool
type tickInterval = int
type tickWidth = int
type min = int
type max = int
type showInLegend = bool
type name = string
type title = {text: string}
type style = {
color: color,
fontFamily: string,
fontSize: string,
}
type enabled = {enabled: bool}
type credits = {
...enabled,
}
type marker = {
...enabled,
}
type pointPadding = float
type bar = {marker: marker, pointPadding: pointPadding}
type plotOptions = {bar: bar}
type labels = {
align: align,
style: style,
}
type chart = {
\"type": \"type",
spacingLeft: spacingLeft,
spacingRight: spacingRight,
}
type dataObj = {
showInLegend: showInLegend,
name: name,
data: array<float>,
color: color,
}
type data = array<dataObj>
type yAxis = {
title: title,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
gridLineDashStyle: gridLineDashStyle,
tickInterval: tickInterval,
min: min,
max: max,
labels: labels,
}
type xAxis = {
categories: categories,
labels: labels,
tickWidth: tickWidth,
tickmarkPlacement: tickmarkPlacement,
endOnTick: endOnTick,
startOnTick: startOnTick,
gridLineDashStyle: gridLineDashStyle,
gridLineWidth: gridLineWidth,
gridLineColor: gridLineColor,
min: min,
}
type info = {index: int}
type point = {color: string, x: string, y: float, point: info}
type pointFormatter = {points: array<point>}
external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string =
"%identity"
type cssStyle = {
fontFamily: string,
fontSize: string,
padding: string,
}
type tooltip = {
shape: string,
backgroundColor: string,
borderColor: string,
useHTML: bool,
formatter: pointFormatter => string,
shared: bool,
style: cssStyle,
borderWidth: float,
shadow: bool,
}
type barGraphOptions = {
chart: chart,
title: title,
xAxis: xAxis,
yAxis: yAxis,
plotOptions: plotOptions,
series: data,
credits: credits,
tooltip: tooltip,
}
type barGraphPayload = {
categories: categories,
data: data,
title: title,
tooltipFormatter: pointFormatter => string,
}
| 630 | 10,120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.