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/utils/GlobalVars.res
.res
@val external appVersion: string = "appVersion" type appName = [ | #hyperswitch ] type appEnv = [#production | #sandbox | #integration | #development] let isLocalhost = Window.Location.hostname === "localhost" || Window.Location.hostname === "127.0.0.1" let dashboardPrefix = "dashboard" let dashboardBasePath = Some(`/${dashboardPrefix}`) let appendTrailingSlash = url => { url->String.startsWith("/") ? url : `/${url}` } let appendDashboardPath = (~url) => { switch dashboardBasePath { | Some(dashboardBaseUrl) => if url->String.length === 0 { dashboardBaseUrl } else { `${dashboardBaseUrl}${url->appendTrailingSlash}` } | None => url } } let extractModulePath = (~path: list<string>, ~query="", ~end) => { open LogicUtils let currentPathList = path->List.toArray let slicedPath = currentPathList->Array.slice(~start=0, ~end) let pathString = slicedPath->Array.joinWith("/")->appendTrailingSlash switch query->getNonEmptyString { | Some(q) => `${pathString}?${q}` | None => pathString } } type hostType = Live | Sandbox | Local | Integ let hostName = Window.Location.hostname let hostType = switch hostName { | "live.hyperswitch.io" => Live | "app.hyperswitch.io" => Sandbox | "integ.hyperswitch.io" => Integ | _ => Local } let getEnvironment = hostType => switch hostType { | Live => "production" | Sandbox => "sandbox" | Integ => "integ" | Local => "localhost" } let getHostUrlWithBasePath = `${Window.Location.origin}${appendDashboardPath(~url="")}` let getHostUrl = Window.Location.origin let playgroundUserEmail = "dummyuser@dummymerchant.com" let playgroundUserPassword = "Dummy@1234" let maximumRecoveryCodes = 8
463
9,921
hyperswitch-control-center
src/utils/AccessControl.res
.res
open CommonAuthTypes @react.component let make = (~isEnabled=true, ~authorization, ~children) => { let isAccessAllowed = authorization === Access isEnabled && isAccessAllowed ? children : <UnauthorizedPage /> }
48
9,922
hyperswitch-control-center
src/utils/MapTypes.res
.res
type rec map = {entries: unit => map} @new external create: 't => map = "Map" type object = {fromEntries: map => JSON.t} external object: object = "Object"
44
9,923
hyperswitch-control-center
src/utils/DateTimeUtils.res
.res
type days = Sunday | Monday | Tuesday | Wednesday | Thrusday | Friday | Saturday let daysArr = [Sunday, Monday, Tuesday, Wednesday, Thrusday, Friday, Saturday] let dayMapper = (days: days) => { switch days { | Sunday => "Sunday" | Monday => "Monday" | Tuesday => "Tuesda" | Wednesday => "Wednesday" | Thrusday => "Thrusday" | Friday => "Friday" | Saturday => "Saturday" } } let cloneDate = date => date->Date.getTime->Js.Date.fromFloat let makeStartOfDayDate = date => { let date = Js.Date.setHoursMSMs( cloneDate(date), ~hours=0., ~minutes=0., ~seconds=0., ~milliseconds=0., (), ) Js.Date.fromFloat(date) } let getStartOfWeek = (dayJs: Date.t, startOfday: days) => { let day = Js.Date.getDay(dayJs) let startWeekDay = daysArr->Array.indexOf(startOfday)->Int.toFloat let diff = (day < startWeekDay ? 7. : 0.) +. day -. startWeekDay Js.Date.setDate(cloneDate(dayJs), Js.Date.getDate(dayJs) -. diff) ->Js.Date.fromFloat ->makeStartOfDayDate ->DayJs.getDayJsForJsDate } let utcToIST = timeStr => { let isEU = false let updatedHour = Js.Date.getHours(timeStr) +. 5.0 let updatedMin = Js.Date.getMinutes(timeStr) +. 30.0 let istTime = Js.Date.setHoursM(timeStr, ~hours=updatedHour, ~minutes=updatedMin, ()) if isEU { timeStr->Date.toISOString } else { Js.Date.fromFloat(istTime)->Date.toISOString } } let utcToISTDate = timeStr => { let isEU = false let updatedHour = Js.Date.getHours(timeStr) +. 5.0 let updatedMin = Js.Date.getMinutes(timeStr) +. 30.0 let istTime = Js.Date.setHoursM(timeStr, ~hours=updatedHour, ~minutes=updatedMin, ()) if isEU { timeStr } else { Js.Date.fromFloat(istTime) } } let parseAsFloat = (dateStr: string) => { let date = (dateStr->DayJs.getDayJsForString).toDate() Js.Date.makeWithYMDHMS( ~year=date->Js.Date.getFullYear, ~month=date->Js.Date.getMonth, ~date=date->Js.Date.getDate, ~hours=date->Js.Date.getHours, ~minutes=date->Js.Date.getMinutes, ~seconds=date->Js.Date.getSeconds, (), )->Js.Date.valueOf } let toUnixTimestamp = (dateStr: string) => { let date = (dateStr->DayJs.getDayJsForString).toDate() Date.UTC.makeWithYMDHMS( ~year=date->Js.Date.getFullYear->Int.fromFloat, ~month=date->Js.Date.getMonth->Int.fromFloat, ~date=date->Js.Date.getDate->Int.fromFloat, ~hours=date->Js.Date.getHours->Int.fromFloat, ~minutes=date->Js.Date.getMinutes->Int.fromFloat, ~seconds=date->Js.Date.getSeconds->Int.fromFloat, ) } let toUtc = (datetime: Date.t) => { let offset = Js.Date.getTimezoneOffset(Date.now()->Js.Date.fromFloat)->Int.fromFloat (datetime->DayJs.getDayJsForJsDate).add(offset, "minute").toDate() } let getStartEndDiff = (startDate, endDate) => { let diffTime = Math.abs( endDate->Date.fromString->Date.getTime -. startDate->Date.fromString->Date.getTime, ) diffTime } let isStartBeforeEndDate = (start, end) => { 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 startDate = getDate(String.split(start, "-")) let endDate = getDate(String.split(end, "-")) startDate < endDate } let getFormattedDate = (date, format) => { date->Date.fromString->Date.toISOString->TimeZoneHook.formattedISOString(format) } type month = Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec let months = [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] let timeOptions = [ "12:00 am", "12:15 am", "12:30 am", "12:45 am", "1:00 am", "1:15 am", "1:30 am", "1:45 am", "2:00 am", "2:15 am", "2:30 am", "2:45 am", "3:00 am", "3:15 am", "3:30 am", "3:45 am", "4:00 am", "4:15 am", "4:30 am", "4:45 am", "5:00 am", "5:15 am", "5:30 am", "5:45 am", "6:00 am", "6:15 am", "6:30 am", "6:45 am", "7:00 am", "7:15 am", "7:30 am", "7:45 am", "8:00 am", "8:15 am", "8:30 am", "8:45 am", "9:00 am", "9:15 am", "9:30 am", "9:45 am", "10:00 am", "10:15 am", "10:30 am", "10:45 am", "11:00 am", "11:15 am", "11:30 am", "11:45 am", "12:00 pm", "12:15 pm", "12:30 pm", "12:45 pm", "1:00 pm", "1:15 pm", "1:30 pm", "1:45 pm", "2:00 pm", "2:15 pm", "2:30 pm", "2:45 pm", "3:00 pm", "3:15 pm", "3:30 pm", "3:45 pm", "4:00 pm", "4:15 pm", "4:30 pm", "4:45 pm", "5:00 pm", "5:15 pm", "5:30 pm", "5:45 pm", "6:00 pm", "6:15 pm", "6:30 pm", "6:45 pm", "7:00 pm", "7:15 pm", "7:30 pm", "7:45 pm", "8:00 pm", "8:15 pm", "8:30 pm", "8:45 pm", "9:00 pm", "9:15 pm", "9:30 pm", "9:45 pm", "10:00 pm", "10:15 pm", "10:30 pm", "10:45 pm", "11:00 pm", "11:15 pm", "11:30 pm", "11:45 pm", ]
1,863
9,924
hyperswitch-control-center
src/utils/ModalCloseIcon.res
.res
@react.component let make = (~fill="#7c7d82", ~onClick) => { <AddDataAttributes attributes=[("data-component", `modalCloseIcon`)]> <div className="" onClick> <Icon name="close" className="border-2 p-2 rounded-2xl bg-gray-100 cursor-pointer" size=30 /> </div> </AddDataAttributes> }
91
9,925
hyperswitch-control-center
src/utils/Identity.res
.res
external formReactEventToString: ReactEvent.Form.t => string = "%identity" external stringToFormReactEvent: string => ReactEvent.Form.t = "%identity" external anyTypeToReactEvent: 'a => ReactEvent.Form.t = "%identity" external arrofStringToReactEvent: array<string> => ReactEvent.Form.t = "%identity" external jsonToNullableJson: JSON.t => Nullable.t<JSON.t> = "%identity" external jsonToReactDOMStyle: JSON.t => ReactDOM.style = "%identity" external genericTypeToJson: 'a => JSON.t = "%identity" external genericTypeToBool: 'a => bool = "%identity" external formReactEventToBool: ReactEvent.Form.t => bool = "%identity" external genericObjectOrRecordToJson: {..} => JSON.t = "%identity" external genericTypeToDictOfJson: 't => Dict.t<JSON.t> = "%identity" external formReactEventToArrayOfString: ReactEvent.Form.t => array<string> = "%identity" external jsonToFormReactEvent: JSON.t => ReactEvent.Form.t = "%identity" external arrayOfGenericTypeToFormReactEvent: array<'a> => ReactEvent.Form.t = "%identity" external webAPIFocusEventToReactEventFocus: Webapi.Dom.FocusEvent.t => ReactEvent.Focus.t = "%identity" external toWasm: Dict.t<JSON.t> => RoutingTypes.wasmModule = "%identity" external jsonToAnyType: JSON.t => 't = "%identity" external nullableOfAnyTypeToJsonType: Nullable.t<'a> => JSON.t = "%identity" external dictOfAnyTypeToObj: Dict.t<'a> => {..} = "%identity"
350
9,926
hyperswitch-control-center
src/utils/ModalUtils.res
.res
let getHeaderTextClass = _ => "text-lg font-semibold leading-6" let getAnimationClass = showModal => switch showModal { | true => "animate-slideUp animate-fadeIn" | _ => "" } let getCloseIcon = onClick => { <Icon name="modal-close-icon" className="cursor-pointer" size=30 onClick /> }
76
9,927
hyperswitch-control-center
src/utils/CurrencyUtils.res
.res
type currencyCode = | AED | ALL | AMD | ANG | ARS | AUD | AWG | AZN | BBD | BDT | BHD | BMD | BND | BOB | BRL | BSD | BWP | BZD | CAD | CHF | COP | CRC | CUP | CZK | DKK | DOP | DZD | EGP | ETB | EUR | FJD | GBP | GHS | GIP | GMD | GTQ | GYD | HKD | HNL | HTG | HUF | IDR | ILS | INR | JMD | JOD | JPY | KES | KGS | KHR | KRW | KWD | KYD | KZT | LAK | LBP | LKR | LRD | LSL | MAD | MDL | MKD | MMK | MNT | MOP | MUR | MVR | MWK | MXN | MYR | NAD | NGN | NIO | NOK | NPR | NZD | OMR | PEN | PGK | PHP | PKR | PLN | QAR | RON | CNY | RUB | SAR | SCR | SEK | SGD | SLL | SOS | SSP | SVC | SZL | THB | TRY | TTD | TWD | TZS | USD let currencyList = [ AED, ALL, AMD, ANG, ARS, AUD, AWG, AZN, BBD, BDT, BHD, BMD, BND, BOB, BRL, BSD, BWP, BZD, CAD, CHF, COP, CRC, CUP, CZK, DKK, DOP, DZD, EGP, ETB, EUR, FJD, GBP, GHS, GIP, GMD, GTQ, GYD, HKD, HNL, HTG, HUF, IDR, ILS, INR, JMD, JOD, JPY, KES, KGS, KHR, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, MAD, MDL, MKD, MMK, MNT, MOP, MUR, MVR, MWK, MXN, MYR, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, QAR, RON, CNY, RUB, SAR, SCR, SEK, SGD, SLL, SOS, SSP, SVC, SZL, THB, TRY, TTD, TWD, TZS, USD, ] let getCurrencyCodeStringFromVariant = currencyCode => { switch currencyCode { | AED => "AED" | ALL => "ALL" | AMD => "AMD" | ANG => "ANG" | ARS => "ARS" | AUD => "AUD" | AWG => "AWG" | AZN => "AZN" | BBD => "BBD" | BDT => "BDT" | BHD => "BHD" | BMD => "BMD" | BND => "BND" | BOB => "BOB" | BRL => "BRL" | BSD => "BSD" | BWP => "BWP" | BZD => "BZD" | CAD => "CAD" | CHF => "CHF" | COP => "COP" | CRC => "CRC" | CUP => "CUP" | CZK => "CZK" | DKK => "DKK" | DOP => "DOP" | DZD => "DZD" | EGP => "EGP" | ETB => "ETB" | EUR => "EUR" | FJD => "FJD" | GBP => "GBP" | GHS => "GHS" | GIP => "GIP" | GMD => "GMD" | GTQ => "GTQ" | GYD => "GYD" | HKD => "HKD" | HNL => "HNL" | HTG => "HTG" | HUF => "HUF" | IDR => "IDR" | ILS => "ILS" | INR => "INR" | JMD => "JMD" | JOD => "JOD" | JPY => "JPY" | KES => "KES" | KGS => "KGS" | KHR => "KHR" | KRW => "KRW" | KWD => "KWD" | KYD => "KYD" | KZT => "KZT" | LAK => "LAK" | LBP => "LBP" | LKR => "LKR" | LRD => "LRD" | LSL => "LSL" | MAD => "MAD" | MDL => "MDL" | MKD => "MKD" | MMK => "MMK" | MNT => "MNT" | MOP => "MOP" | MUR => "MUR" | MVR => "MVR" | MWK => "MWK" | MXN => "MXN" | MYR => "MYR" | NAD => "NAD" | NGN => "NGN" | NIO => "NIO" | NOK => "NOK" | NPR => "NPR" | NZD => "NZD" | OMR => "OMR" | PEN => "PEN" | PGK => "PGK" | PHP => "PHP" | PKR => "PKR" | PLN => "PLN" | QAR => "QAR" | RON => "RON" | CNY => "CNY" | RUB => "RUB" | SAR => "SAR" | SCR => "SCR" | SEK => "SEK" | SGD => "SGD" | SLL => "SLL" | SOS => "SOS" | SSP => "SSP" | SVC => "SVC" | SZL => "SZL" | THB => "THB" | TRY => "TRY" | TTD => "TTD" | TWD => "TWD" | TZS => "TZS" | USD => "USD" } } let getCurrencyCodeFromString: string => currencyCode = currencyCode => { switch currencyCode { | "AED" => AED | "ALL" => ALL | "AMD" => AMD | "ANG" => ANG | "ARS" => ARS | "AUD" => AUD | "AWG" => AWG | "AZN" => AZN | "BBD" => BBD | "BDT" => BDT | "BHD" => BHD | "BMD" => BMD | "BND" => BND | "BOB" => BOB | "BRL" => BRL | "BSD" => BSD | "BWP" => BWP | "BZD" => BZD | "CAD" => CAD | "CHF" => CHF | "COP" => COP | "CRC" => CRC | "CUP" => CUP | "CZK" => CZK | "DKK" => DKK | "DOP" => DOP | "DZD" => DZD | "EGP" => EGP | "ETB" => ETB | "EUR" => EUR | "FJD" => FJD | "GBP" => GBP | "GHS" => GHS | "GIP" => GIP | "GMD" => GMD | "GTQ" => GTQ | "GYD" => GYD | "HKD" => HKD | "HNL" => HNL | "HTG" => HTG | "HUF" => HUF | "IDR" => IDR | "ILS" => ILS | "INR" => INR | "JMD" => JMD | "JOD" => JOD | "JPY" => JPY | "KES" => KES | "KGS" => KGS | "KHR" => KHR | "KRW" => KRW | "KWD" => KWD | "KYD" => KYD | "KZT" => KZT | "LAK" => LAK | "LBP" => LBP | "LKR" => LKR | "LRD" => LRD | "LSL" => LSL | "MAD" => MAD | "MDL" => MDL | "MKD" => MKD | "MMK" => MMK | "MNT" => MNT | "MOP" => MOP | "MUR" => MUR | "MVR" => MVR | "MWK" => MWK | "MXN" => MXN | "MYR" => MYR | "NAD" => NAD | "NGN" => NGN | "NIO" => NIO | "NOK" => NOK | "NPR" => NPR | "NZD" => NZD | "OMR" => OMR | "PEN" => PEN | "PGK" => PGK | "PHP" => PHP | "PKR" => PKR | "PLN" => PLN | "QAR" => QAR | "RON" => RON | "CNY" => CNY | "RUB" => RUB | "SAR" => SAR | "SCR" => SCR | "SEK" => SEK | "SGD" => SGD | "SLL" => SLL | "SOS" => SOS | "SSP" => SSP | "SVC" => SVC | "SZL" => SZL | "THB" => THB | "TRY" => TRY | "TTD" => TTD | "TWD" => TWD | "TZS" => TZS | _ => USD } } let getCurrencyNameFromCode = currencyCode => { switch currencyCode { | AED => "United Arab Emirates dirham" | ALL => "Albanian lek" | AMD => "Armenian dram" | ANG => "Netherlands Antillean guilder" | ARS => "Argentine peso" | AUD => "Australian dollar" | AWG => "Aruban florin" | AZN => "Azerbaijani manat" | BBD => "Barbados dollar" | BDT => "Bangladeshi taka" | BHD => "Bahraini dinar" | BMD => "Bermudian dollar" | BND => "Brunei dollar" | BOB => "Boliviano" | BRL => "Brazilian real" | BSD => "Bahamian dollar" | BWP => "Botswana pula" | BZD => "Belize dollar" | CAD => "Canadian dollar" | CHF => "Swiss franc" | COP => "Colombian peso" | CRC => "Costa Rican colon" | CUP => "Cuban peso" | CZK => "Czech koruna" | DKK => "Danish krone" | DOP => "Dominican peso" | DZD => "Algerian dinar" | EGP => "Egyptian pound" | ETB => "Ethiopian birr" | EUR => "Euro" | FJD => "Fiji dollar" | GBP => "Pound sterling" | GHS => "Ghanaian cedi" | GIP => "Gibraltar pound" | GMD => "Gambian dalasi" | GTQ => "Guatemalan quetzal" | GYD => "Guyanese dollar" | HKD => "Hong Kong dollar" | HNL => "Honduran lempira" | HTG => "Haitian gourde" | HUF => "Hungarian forint" | IDR => "Indonesian rupiah" | ILS => "Israeli new shekel" | INR => "Indian rupee" | JMD => "Jamaican dollar" | JOD => "Jordanian dinar" | JPY => "Japanese yen" | KES => "Kenyan shilling" | KGS => "Kyrgyzstani som" | KHR => "Cambodian riel" | KRW => "South Korean won" | KWD => "Kuwaiti dinar" | KYD => "Cayman Islands dollar" | KZT => "Kazakhstani tenge" | LAK => "Lao kip" | LBP => "Lebanese pound" | LKR => "Sri Lankan rupee" | LRD => "Liberian dollar" | LSL => "Lesotho loti" | MAD => "Moroccan dirham" | MDL => "Moldovan leu" | MKD => "Macedonian denar" | MMK => "Myanmar kyat" | MNT => "Mongolian tögrög" | MOP => "Macanese pataca" | MUR => "Mauritian rupee" | MVR => "Maldivian rufiyaa" | MWK => "Malawian kwacha" | MXN => "Mexican peso" | MYR => "Malaysian ringgit" | NAD => "Namibian dollar" | NGN => "Nigerian naira" | NIO => "Nicaraguan córdoba" | NOK => "Norwegian krone" | NPR => "Nepalese rupee" | NZD => "New Zealand dollar" | OMR => "Omani rial" | PEN => "Peruvian sol" | PGK => "Papua New Guinean kina" | PHP => "Philippine peso" | PKR => "Pakistani rupee" | PLN => "Polish złoty" | QAR => "Qatari riyal" | RON => "Romanian leu" | CNY => "Renminbi" | RUB => "Russian ruble" | SAR => "Saudi riyal" | SCR => "Seychelles rupee" | SEK => "Swedish krona" | SGD => "Singapore dollar" | SLL => "Sierra Leonean leone" | SOS => "Somali shilling" | SSP => "South Sudanese pound" | SVC => "Salvadoran colón" | SZL => "Swazi lilangeni" | THB => "Thai baht" | TRY => "Turkish lira" | TTD => "Trinidad and Tobago dollar" | TWD => "New Taiwan dollar" | TZS => "Tanzanian shilling" | USD => "United States dollar" } } let getCountryListFromCurrency = currencyCode => { open CountryUtils switch currencyCode { | AED => [AE] | ALL => [AL] | AMD => [AM] | ANG => [CW, SX] | ARS => [AR] | AUD => [AU, CX, CC] | AWG => [AW] | AZN => [AZ] | BBD => [BB] | BDT => [BD] | BHD => [BH] | BMD => [BM] | BND => [BN] | BOB => [BO] | BRL => [BR] | BSD => [BS] | BWP => [BW] | BZD => [BZ] | CAD => [CA] | CHF => [LI, CH] | COP => [CO] | CRC => [CR] | CUP => [CU] | CZK => [CZ] | DKK => [DK, FO, GL] | DOP => [DO] | DZD => [DZ] | EGP => [EG] | ETB => [ET] | EUR => [ AD, AT, AX, BE, CY, EE, FI, FR, DE, GR, GP, IE, IT, LV, LT, LU, MT, MQ, YT, MC, ME, NL, PT, RE, BL, MF, PM, SM, SK, SI, ES, VA, GF, TF, MF, ] | FJD => [FJ] | GBP => [GB, GG, IM, JE] | GHS => [GH] | GIP => [GI] | GMD => [GM] | GTQ => [GT] | GYD => [GY] | HKD => [HK] | HNL => [HN] | HTG => [HT] | HUF => [HU] | IDR => [ID] | ILS => [IL, PS] | INR => [IN] | JMD => [JM] | JOD => [JO] | JPY => [JP] | KES => [KE] | KGS => [KG] | KHR => [KH] | KRW => [KP, KR] | KWD => [KW] | KYD => [KY] | KZT => [KZ] | LAK => [LA] | LBP => [LB] | LKR => [LK] | LRD => [LR] | LSL => [LS] | MAD => [MA, EH] | MDL => [MD] | MKD => [MK] | MMK => [MM] | MNT => [MN] | MOP => [MO] | MUR => [MU] | MVR => [MV] | MWK => [MW] | MXN => [MX] | MYR => [MY] | NAD => [NA] | NGN => [NG] | NIO => [NI] | NOK => [BV, NO, SJ] | NPR => [NP] | NZD => [NZ, CK, NU, PN, TK] | OMR => [OM] | PEN => [PE] | PGK => [PG] | PHP => [PH] | PKR => [PK] | PLN => [PL] | QAR => [QA] | RON => [RO] | CNY => [CN] | RUB => [RU] | SAR => [SA] | SCR => [SC] | SEK => [SE] | SGD => [SG] | SLL => [SL] | SOS => [SO] | SSP => [SS] | SVC => [SV] | SZL => [SZ] | THB => [TH] | TRY => [TR] | TTD => [TT] | TWD => [TW] | TZS => [TZ] | USD => [AS, BQ, IO, EC, SV, GU, HT, MH, FM, MP, PW, PA, PR, TL, TC, US, VG, VI] } }
4,929
9,928
hyperswitch-control-center
src/utils/AnalyticsNewUtils.res
.res
open DateTimeUtils open LogicUtils type timeZone = UTC | IST let calculateHistoricTime = ( ~startTime: string, ~endTime: string, ~format: string="YYYY-MM-DDTHH:mm:ss[Z]", ~timeZone: timeZone=UTC, ) => { let toUtc = switch timeZone { | UTC => toUtc | IST => val => val } if startTime->LogicUtils.isNonEmptyString && endTime->LogicUtils.isNonEmptyString { let startDateTime = startTime->DateTimeUtils.parseAsFloat->Js.Date.fromFloat->toUtc let startTimeDayJs = startDateTime->DayJs.getDayJsForJsDate let endDateTime = endTime->DateTimeUtils.parseAsFloat->Js.Date.fromFloat->toUtc let endDateTimeJs = endDateTime->DayJs.getDayJsForJsDate let timediff = endDateTimeJs.diff(Date.toString(startDateTime), "hours") if timediff < 24 { ( startTimeDayJs.subtract(24, "hours").format(format), endDateTimeJs.subtract(24, "hours").format(format), ) } else { let fromTime = startDateTime->Js.Date.valueOf let toTime = endDateTime->Js.Date.valueOf let (startTime, endTime) = ( (fromTime -. (toTime -. fromTime) -. 1.)->Js.Date.fromFloat->DayJs.getDayJsForJsDate, (fromTime -. 1.)->Js.Date.fromFloat->DayJs.getDayJsForJsDate, ) (startTime.format(format), endTime.format(format)) } } else { ("", "") } } let makeFilters = (~filters: JSON.t, ~cardinalityArr) => { let decodeFilter = filters->getDictFromJsonObject let expressionArr = decodeFilter ->Dict.toArray ->Array.map(item => { let (key, value) = item Dict.fromArray([ ("field", key->JSON.Encode.string), ("condition", "In"->JSON.Encode.string), ("val", value), ]) }) let expressionArr = Array.concat(cardinalityArr, expressionArr) if expressionArr->Array.length === 1 { expressionArr->Array.get(0) } else if expressionArr->Array.length > 1 { let leftInitial = Array.pop(expressionArr)->Option.getOr(Dict.make())->JSON.Encode.object let rightInitial = Array.pop(expressionArr)->Option.getOr(Dict.make())->JSON.Encode.object let complexFilterDict = Dict.fromArray([ ("and", Dict.fromArray([("left", leftInitial), ("right", rightInitial)])->JSON.Encode.object), ]) expressionArr->Array.forEach(item => { let complextFilterDictCopy = complexFilterDict->Dict.toArray->Array.copy->Dict.fromArray complexFilterDict->Dict.set( "and", Dict.fromArray([ ("left", complextFilterDictCopy->JSON.Encode.object), ("right", item->JSON.Encode.object), ])->JSON.Encode.object, ) }) Some(complexFilterDict) } else { None } } let getFilterBody = ( filterValueFromUrl, customFilterValue, jsonFormattedFilter, cardinalityArrFilter, ) => { let customFilterBuild = switch customFilterValue { | Some(customFilterValue) => { let value = String.replaceRegExp(customFilterValue, %re("/ AND /gi"), "@@") ->String.replaceRegExp(%re("/ OR /gi"), "@@") ->String.split("@@") let strAr = ["or", "and"] let andAndOr = String.split(customFilterValue, " ")->Array.filter(item => { strAr->Array.includes(item->String.toLocaleLowerCase) }) let filterValueArr = value ->Array.mapWithIndex((item, _index) => { if item->String.match(%re("/ != /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ != /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "NotEquals"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if String.match(item, %re("/ > /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ > /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "Greater"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if item->String.match(%re("/ < /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ < /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "Less"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if item->String.match(%re("/ >= /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ >= /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "GreaterThanEquall"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if item->String.match(%re("/ <= /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ <= /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "LessThanEqual"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if item->String.match(%re("/ = /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ = /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "Equals"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else if item->String.match(%re("/ IN /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ IN /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "In"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->String.replaceRegExp(%re("/\(/g"), "") ->String.replaceRegExp(%re("/\)/g"), "") ->String.split(",") ->Array.map(item => item->String.trim) ->LogicUtils.getJsonFromArrayOfString, ), ]), ) } else { None } } else if item->String.match(%re("/ NOT IN /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ NOT IN /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "NotIn"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->String.replaceRegExp(%re("/\(/g"), "") ->String.replaceRegExp(%re("/\)/g"), "") ->String.split(",") ->Array.map(item => item->String.trim) ->LogicUtils.getJsonFromArrayOfString, ), ]), ) } else { None } } else if item->String.match(%re("/ LIKE /gi"))->Option.isSome { let value = String.replaceRegExp(item, %re("/ LIKE /gi"), "@@") ->String.split("@@") ->Array.map(item => item->String.trim) if value->Array.length >= 2 { Some( Dict.fromArray([ ("field", value[0]->Option.getOr("")->JSON.Encode.string), ("condition", "Like"->JSON.Encode.string), ( "val", value[1] ->Option.getOr("") ->String.replaceRegExp(%re("/'/gi"), "") ->JSON.Encode.string, ), ]), ) } else { None } } else { None } }) ->Belt.Array.keepMap(item => item) if filterValueArr->Array.length === 1 { filterValueArr->Array.get(0) } else if filterValueArr->Array.length >= 2 { let leftInitial = filterValueArr[0]->Option.getOr(Dict.make()) let rightInitial = filterValueArr[1]->Option.getOr(Dict.make()) let conditionInitital = andAndOr->Array.get(0)->Option.getOr("and") let complexFilterDict = Dict.fromArray([ ( conditionInitital, Dict.fromArray([ ("left", leftInitial->JSON.Encode.object), ("right", rightInitial->JSON.Encode.object), ])->JSON.Encode.object, ), ]) let filterValueArr = filterValueArr->Array.copy->Array.sliceToEnd(~start=2) let andAndOr = andAndOr->Array.copy->Array.sliceToEnd(~start=1) filterValueArr->Array.forEachWithIndex((item, index) => { let complextFilterDictCopy = complexFilterDict->Dict.toArray->Array.copy->Dict.fromArray complexFilterDict->Dict.set( andAndOr->Array.get(index)->Option.getOr("and"), Dict.fromArray([ ("left", complextFilterDictCopy->JSON.Encode.object), ("right", item->JSON.Encode.object), ])->JSON.Encode.object, ) }) Some(complexFilterDict) } else { None } } | None => None } let filterValue = switch (filterValueFromUrl, customFilterBuild) { | (Some(value), Some(customFilter)) => switch makeFilters(~filters=value, ~cardinalityArr=cardinalityArrFilter) { | Some(formattedFilters) => { let overallFilters = Dict.fromArray([ ( "and", Dict.fromArray([ ("left", formattedFilters->JSON.Encode.object), ("right", customFilter->JSON.Encode.object), ])->JSON.Encode.object, ), ]) overallFilters } | None => customFilter } | (Some(value), None) => switch makeFilters(~filters=value, ~cardinalityArr=cardinalityArrFilter) { | Some(formattedFilters) => formattedFilters | None => Dict.make() } | (None, Some(customFilter)) => customFilter | (None, None) => Dict.make() } switch jsonFormattedFilter { | Some(jsonFormattedFilter) => switch filterValue->Dict.toArray->Array.length > 0 { | true => Dict.fromArray([ ( "and", Dict.fromArray([ ("left", filterValue->JSON.Encode.object), ("right", jsonFormattedFilter), ])->JSON.Encode.object, ), ]) | false => jsonFormattedFilter->JSON.Decode.object->Option.getOr(Dict.make()) } | None => filterValue } } type ordering = [#Desc | #Asc] type sortedBasedOn = { sortDimension: string, ordering: ordering, } let timeZoneMapper = timeZone => { switch timeZone { | IST => "Asia/Kolkata" | UTC => "UTC" } } let apiBodyMaker = ( ~timeObj, ~metric, ~groupBy=?, ~granularityConfig=?, ~cardinality=?, ~filterValueFromUrl=?, ~customFilterValue=?, ~sortingParams: option<sortedBasedOn>=?, ~jsonFormattedFilter: option<JSON.t>=?, ~cardinalitySortDims="total_volume", ~timeZone: timeZone=IST, ~timeCol: string="txn_initiated", ~domain: string, ~dataLimit: option<float>=?, ) => { let finalBody = Dict.make() let cardinalityArrFilter = switch (cardinality, groupBy) { | (Some(cardinality), Some(groupBy)) => groupBy->Array.map(item => { Dict.fromArray([ ("field", item->JSON.Encode.string), ("condition", "In"->JSON.Encode.string), ( "val", Dict.fromArray([ ( "sortedOn", Dict.fromArray([ ("sortDimension", cardinalitySortDims->JSON.Encode.string), ("ordering", "Desc"->JSON.Encode.string), ])->JSON.Encode.object, ), ("limit", cardinality->JSON.Encode.float), ])->JSON.Encode.object, ), ]) }) | _ => [] } let activeTabArr = groupBy->Option.getOr([])->Array.map(JSON.Encode.string) finalBody->Dict.set("metric", metric->JSON.Encode.string) let filterVal = getFilterBody( filterValueFromUrl, customFilterValue, jsonFormattedFilter, cardinalityArrFilter, ) if filterVal->Dict.toArray->Array.length !== 0 { finalBody->Dict.set("filters", filterVal->JSON.Encode.object) } switch granularityConfig { | Some(config) => { let (granularityDuration, granularityUnit) = config let granularityDimension = Dict.make() let granularity = Dict.make() Dict.set(granularityDimension, "timeZone", timeZone->timeZoneMapper->JSON.Encode.string) Dict.set(granularityDimension, "intervalCol", timeCol->JSON.Encode.string) Dict.set(granularity, "unit", granularityUnit->JSON.Encode.string) Dict.set(granularity, "duration", granularityDuration->Int.toFloat->JSON.Encode.float) Dict.set(granularityDimension, "granularity", granularity->JSON.Encode.object) finalBody->Dict.set( "dimensions", Array.concat(activeTabArr, [granularityDimension->JSON.Encode.object])->JSON.Encode.array, ) } | None => finalBody->Dict.set("dimensions", activeTabArr->JSON.Encode.array) } switch sortingParams { | Some(val) => finalBody->Dict.set( "sortedOn", Dict.fromArray([ ("sortDimension", val.sortDimension->JSON.Encode.string), ( "ordering", val.ordering === #Desc ? "Desc"->JSON.Encode.string : "Asc"->JSON.Encode.string, ), ])->JSON.Encode.object, ) | None => () } switch dataLimit { | Some(dataLimit) => finalBody->Dict.set("limit", dataLimit->JSON.Encode.float) | None => () } finalBody->Dict.set("domain", domain->JSON.Encode.string) finalBody->Dict.set("interval", timeObj->JSON.Encode.object) finalBody->JSON.Encode.object }
3,767
9,929
hyperswitch-control-center
src/utils/Modal.resi
.resi
type modalData = {heading: string, content: React.element} module ModalHeading: { @react.component let make: ( ~headingClass: string, ~headerTextClass: string, ~headerAlignmentClass: string, ~modalHeading: string, ~showCloseIcon: bool, ~showCloseOnLeft: bool, ~showBackIcon: bool, ~leftHeadingIcon: option<React.element>, ~rightHeading: option<React.element>, ~onCloseClick: JsxEvent.Mouse.t => unit, ~onBackClick: ReactEvent.Mouse.t => unit, ~modalHeadingDescription: string, ~modalSubInfo: string, ~showBorderBottom: bool, ~centerHeading: bool=?, ~headBgClass: string, ~modalHeadingDescriptionElement: React.element, ~showModalHeadingIconName: string, ~modalHeadingClass: string, ~modalParentHeadingClass: string, ~customIcon: option<React.element>, ~modalHeaderIconSize: int, ) => React.element } module ModalContent: { @react.component let make: ( ~handleContainerClick: JsxEvent.Mouse.t => unit, ~bgClass: string, ~modalClass: string, ~children: React.element, ~customHeight: string=?, ) => React.element } module ModalOverlay: { @react.component let make: ( ~handleOverlayClick: JsxEvent.Mouse.t => unit, ~showModal: bool, ~children: React.element, ~paddingClass: string, ~modalHeading: option<string>, ~modalPosition: string=?, ~noBackDrop: bool=?, ~isBackdropBlurReq: bool=?, ~addAttributeId: string=?, ~alignModal: string, ) => React.element } @react.component let make: ( ~showModal: bool, ~setShowModal: (bool => bool) => unit, ~children: React.element, ~modalHeading: string=?, ~customModalHeading: React.element=?, ~bgClass: string=?, ~modalClass: string=?, ~childClass: string=?, ~headingClass: string=?, ~paddingClass: string=?, ~centerHeading: bool=?, ~modalHeadingDescription: string=?, ~modalSubInfo: string=?, ~closeOnOutsideClick: bool=?, ~headerTextClass: string=?, ~borderBottom: bool=?, ~showCloseIcon: bool=?, ~showCloseOnLeft: bool=?, ~showBackIcon: bool=?, ~leftHeadingIcon: React.element=?, ~rightHeading: React.element=?, ~onBackClick: unit => unit=?, ~headBgClass: string=?, ~revealFrom: Reveal.postion=?, ~modalHeadingDescriptionElement: React.element=?, ~onCloseClickCustomFun: unit => unit=?, ~modalFooter: React.element=?, ~overlayBG: string=?, ~showModalHeadingIconName: string=?, ~customHeight: string=?, ~modalHeadingClass: string=?, ~modalPosition: string=?, ~modalParentHeadingClass: string=?, ~headerAlignmentClass: string=?, ~noBackDrop: bool=?, ~isBackdropBlurReq: bool=?, ~addAttributeId: string=?, ~customIcon: option<React.element>=?, ~alignModal: string=?, ~modalHeaderIconSize: int=?, ) => React.element
791
9,930
hyperswitch-control-center
src/utils/CurrencyFormatUtils.res
.res
type currencyFormat = | IND | USD | DefaultConvert
17
9,931
hyperswitch-control-center
src/utils/UrlFetchUtils.res
.res
let getFilterValue = value => { 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)) JSON.Encode.array(jsonarr) } else { JSON.Encode.string(value) } }
88
9,932
hyperswitch-control-center
src/utils/ArrayUtils.res
.res
let getUniqueStrArray = (arr: array<string>) => { arr ->Array.map(item => { (item, 0) }) ->Dict.fromArray ->Dict.keysToArray }
46
9,933
hyperswitch-control-center
src/utils/DownloadUtils.res
.res
type blobInstanceType @new external blob: (array<'a>, {"type": string}) => blobInstanceType = "Blob" @val @scope(("window", "URL")) external createObjectURL: blobInstanceType => string = "createObjectURL" @send external clickElement: Dom.element => unit = "click" let download = (~fileName, ~content, ~fileType) => { let blobInstance = blob([content], {"type": fileType}) let url = createObjectURL(blobInstance) let a = Webapi.Dom.document->Webapi.Dom.Document.createElement("a") a->Webapi.Dom.Element.setAttribute("href", url) a->Webapi.Dom.Element.setAttribute("download", fileName) a->clickElement } type imageType = [#svg | #png | #jpeg | #jpg] let downloadOld = (~fileName, ~content) => { download(~fileName, ~content, ~fileType="text/plain") }
203
9,934
hyperswitch-control-center
src/utils/BreadCrumbNavigation.res
.res
type breadcrumb = { title: string, link: string, onClick?: ReactEvent.Mouse.t => unit, warning?: string, mixPanelCustomString?: string, } let arrowDivider = <span className="ml-2 mr-2"> <Icon className="align-middle text-jp-gray-930" size=8 name="chevron-right" /> </span> type dividerVal = | Slash | Arrow @react.component let make = ( ~path: array<breadcrumb>=[], ~currentPageTitle="", ~is_reverse=false, ~cursorStyle="cursor-help", ~commonTextClass="", ~linkTextClass="", ~customTextClass="", ~fontWeight="font-semibold", ~titleTextClass="text-jp-gray-930", ~dividerVal=Arrow, ~childGapClass="", ) => { open LogicUtils let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let prefix = LogicUtils.useUrlPrefix() let showPopUp = PopUpState.useShowPopUp() let pathLength = path->Array.length let divider = { switch dividerVal { | Slash => <p className="text-nd_br_gray-400"> {"/ "->React.string} </p> | _ => arrowDivider } } let textClass = {customTextClass->isEmptyString ? `${textColor.primaryNormal}` : customTextClass} let parentGapClass = "gap-2" let flexDirection = is_reverse ? "flex-wrap flex-row-reverse" : "flex-wrap flex-row" <div className={`flex ${flexDirection} ${fontWeight} ${parentGapClass} items-center w-fit`}> {path ->Array.mapWithIndex((crumb, index) => { let showCrumb = index <= 2 || index === pathLength - 1 let collapse = index === 2 && pathLength > 3 let onClick = switch crumb.onClick { | Some(fn) => fn | None => _ => showPopUp({ popUpType: (Warning, WithIcon), heading: "Heads up!", description: {React.string(crumb.warning->Option.getOr(""))}, handleConfirm: { text: "Yes, go back", onClick: { _ => RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url=crumb.link)) }, }, handleCancel: { text: "No, don't go back", }, }) } <RenderIf key={Int.toString(index)} condition=showCrumb> <div className={`flex ${flexDirection} ${childGapClass} items-center`}> {if collapse { <div className="flex flex-row gap-1 text-jp-2-gray-100 font-medium items-center justify-center"> <span> {React.string("...")} </span> <Icon name="angle-down" size=12 /> </div> } else { <AddDataAttributes attributes=[("data-breadcrumb", crumb.title)]> <div> {switch (crumb.warning, crumb.onClick) { | (None, None) => <Link className={`${textClass} ${linkTextClass} ${commonTextClass}`} to_={GlobalVars.appendDashboardPath(~url=`${prefix}${crumb.link}`)}> {React.string(crumb.title)} </Link> | _ => <a className={`${textClass} ${cursorStyle} ${linkTextClass} ${commonTextClass}`} onClick> {React.string(crumb.title)} </a> }} </div> </AddDataAttributes> }} divider </div> </RenderIf> }) ->React.array} <AddDataAttributes attributes=[("data-breadcrumb", currentPageTitle)]> <div className={`text-fs-14 ${titleTextClass} ${commonTextClass}`}> {React.string(currentPageTitle)} </div> </AddDataAttributes> </div> }
900
9,935
hyperswitch-control-center
src/utils/UserTimeZoneTypes.res
.res
type timezoneData = { offset: string, region: string, title: string, } type timeZoneType = | GMT | EAT | CET | WAT | CAT | EET | CEST | SAST | HDT | AKDT | AST | EST | CDT | CST | MDT | MST | EDT | ADT | PDT | NDT | AEST | NZST | EEST | HKT | WIB | WIT | IDT | PKT | IST | WITA | PST | KST | JST | WEST | ACST | AWST | BST | MSK | ChST | HST | SST | UTC type timeZoneRecordType = { timeZoneAlias: string, timeZoneOffset: string, } type timeRecord = { key: timeZoneType, value: timeZoneRecordType, }
258
9,936
hyperswitch-control-center
src/utils/DateRangeUtils.res
.res
type customDateRange = | Today | Tomorrow | Yesterday | ThisMonth | LastMonth | LastSixMonths | NextMonth | Hour(float) | Day(float) type compareOption = | No_Comparison | Previous_Period | Custom @unboxed type comparison = | EnableComparison | DisableComparison let comparisonMapprer = val => { switch val { | "EnableComparison" => EnableComparison | "DisableComparison" => DisableComparison | _ => DisableComparison } } let getDateString = (value, isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString) => { try { let {year, month, date} = isoStringToCustomTimeZone(value) `${year}-${month}-${date}` } catch { | _error => "" } } let getTimeString = (value, isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString) => { try { let {hour, minute} = isoStringToCustomTimeZone(value) `${hour}:${minute}:00` } catch { | _error => "" } } let getMins = (val: float) => { let mins = val *. 60.0 mins->Float.toString } let getPredefinedStartAndEndDate = ( todayDayJsObj: DayJs.dayJs, isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString, isoStringToCustomTimezoneInFloat: string => TimeZoneHook.dateTimeFloat, customTimezoneToISOString, value: customDateRange, disableFutureDates, disablePastDates, todayDate, todayTime, ) => { let lastMonth = todayDayJsObj.subtract(1, "month").endOf("month").toDate() let lastSixMonths = todayDayJsObj.toDate() let nextMonth = todayDayJsObj.add(1, "month").endOf("month").toDate() let yesterday = todayDayJsObj.subtract(1, "day").toDate() let tomorrow = todayDayJsObj.add(1, "day").toDate() let thisMonth = disableFutureDates ? todayDayJsObj.toDate() : todayDayJsObj.endOf("month").toDate() let customDate = switch value { | LastMonth => lastMonth | LastSixMonths => lastSixMonths | NextMonth => nextMonth | Yesterday => yesterday | Tomorrow => tomorrow | ThisMonth => thisMonth | _ => todayDayJsObj.toDate() } let daysInMonth = (customDate->DayJs.getDayJsForJsDate).endOf("month").toString() ->Date.fromString ->Js.Date.getDate let prevDate = (customDate->DayJs.getDayJsForJsDate).subtract(6, "month").toString() let daysInSixMonth = (customDate->DayJs.getDayJsForJsDate).diff(prevDate, "day")->Int.toFloat let count = switch value { | Today => 1.0 | Yesterday => 1.0 | Tomorrow => 1.0 | LastMonth => daysInMonth | LastSixMonths => daysInSixMonth | ThisMonth => customDate->Js.Date.getDate | NextMonth => daysInMonth | Day(val) => val | Hour(val) => val /. 24.0 +. 1. } let date = customTimezoneToISOString( String.make(customDate->Js.Date.getFullYear), String.make(customDate->Js.Date.getMonth +. 1.0), String.make(customDate->Js.Date.getDate), String.make(customDate->Js.Date.getHours), String.make(customDate->Js.Date.getMinutes), String.make(customDate->Js.Date.getSeconds), )->Date.fromString let todayInitial = date let today = todayInitial ->Date.toISOString ->isoStringToCustomTimezoneInFloat ->TimeZoneHook.dateTimeObjectToDate let msInADay = 24.0 *. 60.0 *. 60.0 *. 1000.0 let durationSecs: float = (count -. 1.0) *. msInADay let dateBeforeDuration = today->Date.getTime->Js.Date.fromFloat let msInterval = disableFutureDates ? dateBeforeDuration->Date.getTime -. durationSecs : dateBeforeDuration->Date.getTime +. durationSecs let dateAfterDuration = msInterval->Js.Date.fromFloat let (finalStartDate, finalEndDate) = disableFutureDates ? (dateAfterDuration, dateBeforeDuration) : (dateBeforeDuration, dateAfterDuration) let startDate = getDateString(finalStartDate->Date.toString, isoStringToCustomTimeZone) let endDate = getDateString(finalEndDate->Date.toString, isoStringToCustomTimeZone) let endTime = { let eTime = switch value { | Hour(_) => getTimeString(finalEndDate->Date.toString, isoStringToCustomTimeZone) | _ => "23:59:59" } disableFutureDates && endDate == todayDate ? todayTime : eTime } let startTime = { let sTime = switch value { | Hour(_) => getTimeString(finalStartDate->Date.toString, isoStringToCustomTimeZone) | _ => "00:00:00" } !disableFutureDates && (value !== Today || disablePastDates) && startDate == todayDate ? todayTime : sTime } let stDate = startDate let enDate = endDate (stDate, enDate, startTime, endTime) } let datetext = (count, disableFutureDates) => { switch count { | Today => "Today" | Tomorrow => "Tomorrow" | Yesterday => "Yesterday" | ThisMonth => "This Month" | LastMonth => "Last Month" | LastSixMonths => "Last 6 Months" | NextMonth => "Next Month" | Hour(val) => if val < 1.0 { disableFutureDates ? `Last ${getMins(val)} Mins` : `Next ${getMins(val)} Mins` } else if val === 1.0 { disableFutureDates ? `Last ${val->Float.toString} Hour` : `Next ${val->Float.toString} Hour` } else if disableFutureDates { `Last ${val->Float.toString} Hours` } else { `Next ${val->Float.toString} Hours` } | Day(val) => disableFutureDates ? `Last ${val->Float.toString} Days` : `Next ${val->Float.toString} Days` } } let convertTimeStamp = (~isoStringToCustomTimeZone, timestamp, format) => { let convertedTimestamp = try { timestamp->isoStringToCustomTimeZone->TimeZoneHook.formattedDateTimeString(format) } catch { | _ => "" } convertedTimestamp } let changeTimeFormat = (~customTimezoneToISOString, ~date, ~time, ~format) => { let dateSplit = String.split(date, "T") let date = dateSplit[0]->Option.getOr("")->String.split("-") let dateDay = date[2]->Option.getOr("") let dateYear = date[0]->Option.getOr("") let dateMonth = date[1]->Option.getOr("") let timeSplit = String.split(time, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let dateTimeCheck = customTimezoneToISOString( dateYear, dateMonth, dateDay, timeHour, timeMinute, timeSecond, ) TimeZoneHook.formattedISOString(dateTimeCheck, format) } let getTimeStringForValue = ( value, isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString, ) => { if value->LogicUtils.isEmptyString { "" } else { try { let check = TimeZoneHook.formattedISOString(value, "YYYY-MM-DDTHH:mm:ss.SSS[Z]") let {hour, minute, second} = isoStringToCustomTimeZone(check) `${hour}:${minute}:${second}` } catch { | _error => "" } } } let formatTimeString = (~timeVal, ~defaultTime, ~showSeconds) => { open LogicUtils if timeVal->isNonEmptyString { let timeArr = timeVal->String.split(":") let timeTxt = `${timeArr->getValueFromArray(0, "00")}:${timeArr->getValueFromArray(1, "00")}` showSeconds ? `${timeTxt}:${timeArr->getValueFromArray(2, "00")}` : timeTxt } else { defaultTime } } let getFormattedDate = (date, format) => { date->Date.fromString->Date.toISOString->TimeZoneHook.formattedISOString(format) } let getDateStringForValue = ( value, isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString, ) => { if value->LogicUtils.isEmptyString { "" } else { try { let check = TimeZoneHook.formattedISOString(value, "YYYY-MM-DDTHH:mm:ss.SSS[Z]") let {year, month, date} = isoStringToCustomTimeZone(check) `${year}-${month}-${date}` } catch { | _error => "" } } } let formatDateString = (~dateVal, ~buttonText, ~defaultLabel, ~isoStringToCustomTimeZone) => { open LogicUtils if dateVal->isNonEmptyString { getFormattedDate(dateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY") } else if buttonText->isNonEmptyString { buttonText } else { defaultLabel } } let getButtonText = ( ~predefinedOptionSelected, ~disableFutureDates, ~startDateVal, ~endDateVal, ~buttonText, ~isoStringToCustomTimeZone, ~comparison, ) => { open LogicUtils let startDateStr = formatDateString( ~dateVal=startDateVal, ~buttonText, ~defaultLabel="[From-Date]", ~isoStringToCustomTimeZone, ) let endDateStr = formatDateString( ~dateVal=endDateVal, ~buttonText, ~defaultLabel="[To-Date]", ~isoStringToCustomTimeZone, ) switch comparison->comparisonMapprer { | DisableComparison => `No Comparison` | EnableComparison => switch predefinedOptionSelected { | Some(value) => datetext(value, disableFutureDates) | None => switch (startDateVal->isEmptyString, endDateVal->isEmptyString) { | (true, true) => `No Comparison` | (true, false) => `${endDateStr}` // When start date is empty, show only end date | (false, true) => `${startDateStr} - Now` // When end date is empty, show start date and "Now" | (false, false) => let separator = startDateStr === buttonText ? "" : "-" `${startDateStr} ${separator} ${endDateStr}` } } } } let getStrokeColor = (disable, isDropdownExpandedActualPrimary) => if disable { "stroke-jp-2-light-gray-600" } else if isDropdownExpandedActualPrimary { "stroke-jp-2-light-gray-1700" } else { "stroke-jp-2-light-gray-1100" } let getComparisionTimePeriod = (~startDate, ~endDate) => { let startingPoint = startDate->DayJs.getDayJsForString let endingPoint = endDate->DayJs.getDayJsForString let gap = endingPoint.diff(startingPoint.toString(), "millisecond") // diff between points let startTimeValue = startingPoint.subtract(gap, "millisecond").toDate()->Date.toISOString let endTimeVal = startingPoint.subtract(1, "millisecond").toDate()->Date.toISOString (startTimeValue, endTimeVal) } let resetStartEndInput = (~setStartDate, ~setEndDate) => { setStartDate(_ => "") setEndDate(_ => "") } let getStartEndDiff = (startDate, endDate) => { let diffTime = Math.abs( endDate->Date.fromString->Date.getTime -. startDate->Date.fromString->Date.getTime, ) diffTime } let getDiffForPredefined = ( predefinedDay, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, disableFutureDates, disablePastDates, ) => { let todayDayJsObj = Date.make()->Date.toString->DayJs.getDayJsForString let todayDate = todayDayJsObj.format("YYYY-MM-DD") let todayTime = todayDayJsObj.format("HH:mm:ss") let format = "YYYY-MM-DDTHH:mm:00[Z]" let (stDate, enDate, stTime, enTime) = getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, predefinedDay, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startTimestamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format, ) let endTimestamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format, ) getStartEndDiff(startTimestamp, endTimestamp) } let getIsPredefinedOptionSelected = ( predefinedDays, startDateVal, endDateVal, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, disableFutureDates, disablePastDates, ) => { let format = "YYYY-MM-DDTHH:mm:00[Z]" predefinedDays->Array.find(item => { let startDate = convertTimeStamp(~isoStringToCustomTimeZone, startDateVal, format) let endDate = convertTimeStamp(~isoStringToCustomTimeZone, endDateVal, format) let difference = getStartEndDiff(startDate, endDate) getDiffForPredefined( item, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, disableFutureDates, disablePastDates, ) === difference }) } let getGapBetweenRange = (~startDate, ~endDate) => { let startingPoint = startDate->DayJs.getDayJsForString let endingPoint = endDate->DayJs.getDayJsForString endingPoint.diff(startingPoint.toString(), "day") // diff between points }
3,280
9,937
hyperswitch-control-center
src/utils/UseEvent.res
.res
let useEvent0 = callback => { let callbackRef = React.useRef(callback) React.useEffect(() => { callbackRef.current = callback None }, [callback]) React.useCallback(() => { callbackRef.current() }, []) }
56
9,938
hyperswitch-control-center
src/utils/LazyUtils.res
.res
type lazyScreen type lazyScreenLoader = unit => promise<lazyScreen> @val external import_: string => promise<lazyScreen> = "import" type reactLazy<'component> = lazyScreenLoader => 'component @module("react") @val external reactLazy: reactLazy<'a> = "lazy"
68
9,939
hyperswitch-control-center
src/utils/DOMUtils.res
.res
type document = {mutable title: string} type window = {mutable _env_: HyperSwitchConfigTypes.urlConfig} @val external document: document = "document" @send external getElementById: (document, string) => Dom.element = "getElementById" @send external createElement: (document, string) => Dom.element = "createElement" @val external window: window = "window" @send external click: (Dom.element, unit) => unit = "click" @send external reset: (Dom.element, unit) => unit = "reset" type event @new external event: string => event = "Event" @send external dispatchEvent: ('a, event) => unit = "dispatchEvent" @send external postMessage: (window, JSON.t, string) => unit = "postMessage" @get external keyCode: 'a => int = "keyCode" @send external querySelectorAll: (document, string) => array<Dom.element> = "querySelectorAll" @send external setAttribute: (Dom.element, string, string) => unit = "setAttribute" @send external remove: (Dom.element, unit) => unit = "remove" @scope(("document", "body")) external appendChild: Dom.element => unit = "appendChild" @scope(("document", "head")) external appendHead: Dom.element => unit = "appendChild" external domProps: {..} => JsxDOM.domProps = "%identity"
299
9,940
hyperswitch-control-center
src/utils/NumericUtils.res
.res
// Copied from https://gist.github.com/Frencil/aab561687cdd2b0de04a let pretty = (range: array<float>, n: int) => { if range->Array.length === 2 { let range = if range[0] === range[1] { [0., range[1]->Option.getOr(0.)] } else { range } let min_n = Int.toFloat(n) /. 3. let shrink_sml = 0.75 let high_u_bias = 1.5 let u5_bias = 0.5 +. 1.5 *. high_u_bias let d = Math.abs(range[0]->Option.getOr(0.) -. range[1]->Option.getOr(0.)) let c = if Math.log(d) /. Math.Constants.ln10 < -2. { Math.abs(d) *. shrink_sml /. min_n } else { d /. Int.toFloat(n) } let base = Math.pow(10., ~exp=Math.floor(Math.log(c) /. Math.Constants.ln10)) let base_toFixed = if base < 1. { Math.abs(Math.round(Math.log(base) /. Math.Constants.ln10))->Float.toInt } else { 0 } let unit = ref(base) if 2. *. base -. c < high_u_bias *. (c -. unit.contents) { unit := 2. *. base if 5. *. base -. c < u5_bias *. (c -. unit.contents) { unit := 5. *. base if 10. *. base -. c < high_u_bias *. (c -. unit.contents) { unit := 10. *. base } } } let ticks = [] let i = if range[0]->Option.getOr(0.) <= unit.contents { 0. } else { let i123 = Math.floor(range[0]->Option.getOr(0.) /. unit.contents) *. unit.contents i123->Float.toFixedWithPrecision(~digits=base_toFixed)->Float.fromString->Option.getOr(0.) } let iRef = ref(i) let break = ref(false) while iRef.contents < range[1]->Option.getOr(0.) && unit.contents > 0. { ticks->Array.push(iRef.contents)->ignore iRef := iRef.contents +. unit.contents if base_toFixed > 0 && unit.contents > 0. { iRef := iRef.contents ->Float.toFixedWithPrecision(~digits=base_toFixed) ->Float.fromString ->Option.getOr(0.) } else { break := true } } ticks->Array.push(iRef.contents)->ignore ticks } else { [0.] } }
639
9,941
hyperswitch-control-center
src/utils/FormDataUtils.res
.res
type formData @new external formData: unit => Fetch.formData = "FormData" @send external append: (Fetch.formData, string, 'a) => unit = "append"
36
9,942
hyperswitch-control-center
src/utils/UrlUtils.res
.res
let useGetFilterDictFromUrl = prefix => { let url = RescriptReactRouter.useUrl() let (searchParamsDict, setSearchParamDict) = React.useState(_ => Dict.make()) React.useEffect(() => { if url.search->LogicUtils.isNonEmptyString { let searcParamsToDict = url.search ->decodeURI ->String.split("&") ->Array.map(str => { let arr = str->String.split("=") let key = arr->Array.get(0)->Option.getOr("-") let val = arr->Array.sliceToEnd(~start=1)->Array.joinWith("=") (key, val->UrlFetchUtils.getFilterValue) // it will return the Json string, Json array }) ->Belt.Array.keepMap(entry => { let (key, val) = entry if prefix->LogicUtils.isEmptyString { Some(entry) } else if key->String.indexOf(`${prefix}.`) === 0 { let transformedKey = key->String.replace(`${prefix}.`, "") Some(transformedKey, val) } else { None } }) ->Dict.fromArray setSearchParamDict(_ => searcParamsToDict) } None }, [url.search]) searchParamsDict }
278
9,943
hyperswitch-control-center
src/utils/JsonFlattenUtils.res
.res
let rec flattenObject = (obj, addIndicatorForObject) => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(obj) => obj ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry if value->Identity.jsonToNullableJson->Js.Nullable.isNullable { Dict.set(newDict, key, value) } else { switch value->JSON.Decode.object { | Some(_valueObj) => { if addIndicatorForObject { Dict.set(newDict, key, JSON.Encode.object(Dict.make())) } let flattenedSubObj = flattenObject(value, addIndicatorForObject) flattenedSubObj ->Dict.toArray ->Array.forEach(subEntry => { let (subKey, subValue) = subEntry Dict.set(newDict, `${key}.${subKey}`, subValue) }) } | None => Dict.set(newDict, key, value) } } }) | _ => () } newDict } let rec setNested = (dict, keys, value) => { if keys->Array.length === 0 { () } else if keys->Array.length === 1 { Dict.set(dict, keys[0]->Option.getOr(""), value) } else { let key = keys[0]->Option.getOr("") let subDict = switch Dict.get(dict, key) { | Some(json) => switch json->JSON.Decode.object { | Some(obj) => obj | None => dict } | None => { let subDict = Dict.make() Dict.set(dict, key, subDict->JSON.Encode.object) subDict } } let remainingKeys = keys->Array.sliceToEnd(~start=1) setNested(subDict, remainingKeys, value) } } let unflattenObject = obj => { let newDict = Dict.make() switch obj->JSON.Decode.object { | Some(dict) => dict ->Dict.toArray ->Array.forEach(entry => { let (key, value) = entry setNested(newDict, key->String.split("."), value) }) | None => () } newDict }
484
9,944
hyperswitch-control-center
src/utils/Modal.res
.res
open ModalUtils type modalData = { heading: string, content: React.element, } module Back = { @react.component let make = (~onClick) => { <Icon size=18 name="chevron-left" className="cursor-pointer opacity-50 dark:opacity-100 " onClick /> } } module ModalHeading = { @react.component let make = ( ~headingClass, ~headerTextClass, ~headerAlignmentClass, ~modalHeading, ~showCloseIcon, ~showCloseOnLeft, ~showBackIcon, ~leftHeadingIcon, ~rightHeading, ~onCloseClick, ~onBackClick, ~modalHeadingDescription, ~modalSubInfo, ~showBorderBottom, ~centerHeading=false, ~headBgClass, ~modalHeadingDescriptionElement, ~showModalHeadingIconName, ~modalHeadingClass, ~modalParentHeadingClass, ~customIcon, ~modalHeaderIconSize, ) => { let borderClass = showBorderBottom ? "border-b border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960 dark:border-opacity-75" : "" let isMobileView = MatchMedia.useMatchMedia("(max-width: 700px)") let justifyClass = centerHeading ? "justify-center" : "justify-between" let headerTextClass = isMobileView ? "text-fs-18 font-semibold" : headerTextClass let descriptionStyle = "text-md font-medium leading-7 opacity-50 mt-1 w-full max-w-sm " let subInfoStyle = "text-md font-medium leading-7 opacity-50 mt-1 w-full max-w-sm empty:hidden" <div className={`!p-4 ${headBgClass->LogicUtils.isNonEmptyString ? headBgClass : "bg-jp-gray-200 dark:bg-jp-gray-darkgray_background"} rounded-t-lg z-10 w-full m-0 md:!pl-6 ${headingClass} ${borderClass} `}> {switch leftHeadingIcon { | Some(icon) => <div className="fill-current flex-col justify-between h-0 bg-jp-gray-100"> <div className="fill-current"> icon </div> </div> | None => React.null }} <div className={`flex items-center ${headerAlignmentClass} ${justifyClass} ${headerTextClass}`}> <div className=modalParentHeadingClass> {if showCloseIcon && showCloseOnLeft && !showBackIcon { onCloseClick->ModalUtils.getCloseIcon } else { React.null }} {if showBackIcon { <div className="mr-4 pt-1.5"> <Back onClick=onBackClick /> </div> } else { React.null }} {if showModalHeadingIconName->LogicUtils.isNonEmptyString { <div className="flex items-center gap-4"> {switch customIcon { | Some(icon) => icon | None => <Icon name=showModalHeadingIconName size=modalHeaderIconSize className="" /> }} <AddDataAttributes attributes=[("data-modal-header-text", modalHeading)]> <div className={`font-inter-style font-semibold text-fs-16 leading-6 text-jp-2-gray-600 ${modalHeadingClass}`}> {React.string(modalHeading)} </div> </AddDataAttributes> </div> } else { <AddDataAttributes attributes=[("data-modal-header-text", modalHeading)]> <div className={`${modalHeadingClass}`}> {React.string(modalHeading)} </div> </AddDataAttributes> }} </div> {switch rightHeading { | Some(rightHeadingElement) => rightHeadingElement | None => React.null }} {if showCloseIcon && !showCloseOnLeft { onCloseClick->ModalUtils.getCloseIcon } else { React.null }} </div> {if modalHeadingDescriptionElement !== React.null { modalHeadingDescriptionElement } else { <AddDataAttributes attributes=[("data-modal-description-text", modalHeading)]> <div className=descriptionStyle> {React.string(modalHeadingDescription)} </div> </AddDataAttributes> }} <div className=subInfoStyle> {React.string(modalSubInfo)} </div> </div> } } module ModalContent = { @react.component let make = (~handleContainerClick, ~bgClass, ~modalClass, ~children, ~customHeight="h-fit") => { <div id="neglectTopbarTheme" onClick=handleContainerClick className={`border border-jp-gray-500 dark:border-jp-gray-900 ${bgClass} shadow rounded-lg dark:text-opacity-75 dark:bg-jp-gray-darkgray_background ${modalClass} ${customHeight}`}> children </div> } } module ModalOverlay = { @react.component let make = ( ~handleOverlayClick, ~showModal, ~children, ~paddingClass, ~modalHeading, ~modalPosition="", ~noBackDrop=false, ~isBackdropBlurReq=true, ~addAttributeId="", ~alignModal, ) => { let isMobileView = MatchMedia.useMatchMedia("(max-width: 700px)") let mobileClass = isMobileView ? "flex flex-col " : "" let displayClass = showModal ? "block" : "hidden" let overlayBgStyle = isBackdropBlurReq ? `bg-grey-700 bg-opacity-50` : "" let backgroundDropStyles = isBackdropBlurReq ? "backdrop-blur-sm" : "" let attributeId = addAttributeId->LogicUtils.isEmptyString ? switch modalHeading { | Some(_heading) => `:${modalHeading->Option.getOr("")}` | None => "" } : `:${addAttributeId}` let zIndexClass = "z-40" <AddDataAttributes attributes=[("data-component", `modal` ++ attributeId)]> {noBackDrop ? <div className={`${displayClass} ${paddingClass} fixed inset-0 ${zIndexClass}`}> children </div> : <div onClick={handleOverlayClick} className={`${mobileClass} ${displayClass} ${overlayBgStyle} fixed h-screen w-screen ${zIndexClass} ${modalPosition} ${paddingClass} flex ${alignModal} inset-0 overflow-auto ${backgroundDropStyles}`}> children </div>} </AddDataAttributes> } } @react.component let make = ( ~showModal, ~setShowModal, ~children, ~modalHeading=?, ~customModalHeading=?, ~bgClass="bg-white dark:bg-jp-gray-lightgray_background", ~modalClass="md:mt-20 overflow-auto", ~childClass="p-2 m-2", ~headingClass="p-2", ~paddingClass="", ~centerHeading=false, ~modalHeadingDescription="", ~modalSubInfo="", ~closeOnOutsideClick=false, ~headerTextClass="font-bold text-fs-24", ~borderBottom=true, ~showCloseIcon=true, ~showCloseOnLeft=false, ~showBackIcon=false, ~leftHeadingIcon=?, ~rightHeading=?, ~onBackClick=_ => (), ~headBgClass="bg-white dark:bg-jp-gray-darkgray_background", ~revealFrom=Reveal.Top, ~modalHeadingDescriptionElement=React.null, ~onCloseClickCustomFun=_ => (), ~modalFooter=React.null, ~overlayBG="bg-jp-gray-950 dark:bg-white-600 dark:bg-opacity-80 bg-opacity-70", ~showModalHeadingIconName="", ~customHeight=?, ~modalHeadingClass="", ~modalPosition="", ~modalParentHeadingClass="flex flex-row flex-1", ~headerAlignmentClass="flex-row", ~noBackDrop=false, ~isBackdropBlurReq=true, ~addAttributeId="", ~customIcon=None, ~alignModal="justify-end", ~modalHeaderIconSize=35, ) => { let showBorderBottom = borderBottom let _ = revealFrom let headerTextClass = headerTextClass->getHeaderTextClass let onCloseClick = _ => { setShowModal(prev => !prev) onCloseClickCustomFun() } let onBackClick = _ => onBackClick() let handleOverlayClick = ev => { if closeOnOutsideClick { open ReactEvent.Mouse ev->stopPropagation onCloseClick(ev) setShowModal(_ => false) } } let handleKeyUp = ev => { if closeOnOutsideClick { open ReactEvent.Keyboard let key = ev->key let keyCode = ev->keyCode if key === "Escape" || keyCode === 27 { setShowModal(_ => false) } } } React.useEffect(() => { if showModal { Window.addEventListener("keyup", handleKeyUp) } else { Window.removeEventListener("keyup", handleKeyUp) } Some( () => { Window.removeEventListener("keyup", handleKeyUp) }, ) }, (showModal, closeOnOutsideClick)) let handleContainerClick = ev => { if closeOnOutsideClick { open ReactEvent.Mouse ev->stopPropagation } } let animationClass = showModal->getAnimationClass <ModalOverlay showModal handleOverlayClick paddingClass modalHeading modalPosition noBackDrop isBackdropBlurReq alignModal addAttributeId> // <Reveal showReveal=showModal revealFrom> <ModalContent handleContainerClick bgClass ?customHeight modalClass={`${animationClass} ${modalClass}`} key={showModal ? "true" : "false"}> {switch modalHeading { | Some(modalHeading) => <ModalHeading headingClass headerTextClass headerAlignmentClass modalHeading showCloseIcon showCloseOnLeft showBackIcon leftHeadingIcon rightHeading onBackClick onCloseClick modalHeadingDescription modalSubInfo showBorderBottom centerHeading headBgClass modalHeadingDescriptionElement showModalHeadingIconName modalHeadingClass modalParentHeadingClass customIcon modalHeaderIconSize /> | None => React.null }} {switch customModalHeading { | Some(element) => element | None => React.null }} <div className=childClass> children </div> {if modalFooter != React.null { <div className="h-[5rem]"> modalFooter </div> } else { React.null }} </ModalContent> // </Reveal> </ModalOverlay> }
2,467
9,945
hyperswitch-control-center
src/utils/Country.res
.res
type timezoneType = { isoAlpha3: string, timeZones: array<string>, countryName: CountryUtils.countries, isoAlpha2: CountryUtils.countiesCode, } let defaultTimeZone = { isoAlpha3: "", timeZones: [], countryName: UnitedStatesOfAmerica, isoAlpha2: US, } let country = [ { isoAlpha3: "AFG", timeZones: ["Asia/Kabul"], countryName: Afghanistan, isoAlpha2: AF, }, { isoAlpha3: "ALB", timeZones: ["Europe/Tirane"], countryName: Albania, isoAlpha2: AL, }, { isoAlpha3: "DZA", timeZones: ["Africa/Algiers"], countryName: Algeria, isoAlpha2: DZ, }, { isoAlpha3: "ARG", timeZones: [ "America/Argentina/Buenos_Aires", "America/Argentina/Cordoba", "America/Argentina/Salta", "America/Argentina/Jujuy", "America/Argentina/Tucuman", "America/Argentina/Catamarca", "America/Argentina/La_Rioja", "America/Argentina/San_Juan", "America/Argentina/Mendoza", "America/Argentina/San_Luis", "America/Argentina/Rio_Gallegos", "America/Argentina/Ushuaia", ], countryName: Argentina, isoAlpha2: AR, }, { isoAlpha3: "ARM", timeZones: ["Asia/Yerevan"], countryName: Armenia, isoAlpha2: AM, }, { isoAlpha3: "AUS", timeZones: [ "Australia/Lord_Howe", "Antarctica/Macquarie", "Australia/Hobart", "Australia/Currie", "Australia/Melbourne", "Australia/Sydney", "Australia/Broken_Hill", "Australia/Brisbane", "Australia/Lindeman", "Australia/Adelaide", "Australia/Darwin", "Australia/Perth", "Australia/Eucla", ], countryName: Australia, isoAlpha2: AU, }, { isoAlpha3: "AUT", timeZones: ["Europe/Vienna"], countryName: Austria, isoAlpha2: AT, }, { isoAlpha3: "AZE", timeZones: ["Asia/Baku"], countryName: Azerbaijan, isoAlpha2: AZ, }, { isoAlpha3: "BHR", timeZones: ["Asia/Bahrain"], countryName: Bahrain, isoAlpha2: BH, }, { isoAlpha3: "BGD", timeZones: ["Asia/Dhaka"], countryName: Bangladesh, isoAlpha2: BD, }, { isoAlpha3: "BLR", timeZones: ["Europe/Minsk"], countryName: Belarus, isoAlpha2: BY, }, { isoAlpha3: "BEL", timeZones: ["Europe/Brussels"], countryName: Belgium, isoAlpha2: BE, }, { isoAlpha3: "BLZ", timeZones: ["America/Belize"], countryName: Belize, isoAlpha2: BZ, }, { isoAlpha3: "BTN", timeZones: ["Asia/Thimphu"], countryName: Bhutan, isoAlpha2: BT, }, { isoAlpha3: "BOL", timeZones: ["America/La_Paz"], countryName: BoliviaPlurinationalState, isoAlpha2: BO, }, { isoAlpha3: "BIH", timeZones: ["Europe/Sarajevo"], countryName: BosniaAndHerzegovina, isoAlpha2: BA, }, { isoAlpha3: "BWA", timeZones: ["Africa/Gaborone"], countryName: Botswana, isoAlpha2: BW, }, { isoAlpha3: "BRA", timeZones: [ "America/Noronha", "America/Belem", "America/Fortaleza", "America/Recife", "America/Araguaina", "America/Maceio", "America/Bahia", "America/Sao_Paulo", "America/Campo_Grande", "America/Cuiaba", "America/Santarem", "America/Porto_Velho", "America/Boa_Vista", "America/Manaus", "America/Eirunepe", "America/Rio_Branco", ], countryName: Brazil, isoAlpha2: BR, }, { isoAlpha3: "BRN", timeZones: ["Asia/Brunei"], countryName: BruneiDarussalam, isoAlpha2: BN, }, { isoAlpha3: "BGR", timeZones: ["Europe/Sofia"], countryName: Bulgaria, isoAlpha2: BG, }, { isoAlpha3: "KHM", timeZones: ["Asia/Phnom_Penh"], countryName: Cambodia, isoAlpha2: KH, }, { isoAlpha3: "CMR", timeZones: ["Africa/Douala"], countryName: Cameroon, isoAlpha2: CM, }, { isoAlpha3: "CAN", timeZones: [ "America/St_Johns", "America/Halifax", "America/Glace_Bay", "America/Moncton", "America/Goose_Bay", "America/Blanc-Sablon", "America/Toronto", "America/Nipigon", "America/Thunder_Bay", "America/Iqaluit", "America/Pangnirtung", "America/Atikokan", "America/Winnipeg", "America/Rainy_River", "America/Resolute", "America/Rankin_Inlet", "America/Regina", "America/Swift_Current", "America/Edmonton", "America/Cambridge_Bay", "America/Yellowknife", "America/Inuvik", "America/Creston", "America/Dawson_Creek", "America/Fort_Nelson", "America/Vancouver", "America/Whitehorse", "America/Dawson", ], countryName: Canada, isoAlpha2: CA, }, { isoAlpha3: "CHL", timeZones: ["America/Santiago", "Pacific/Easter"], countryName: Chile, isoAlpha2: CL, }, { isoAlpha3: "CHN", timeZones: ["Asia/Shanghai", "Asia/Urumqi"], countryName: China, isoAlpha2: CN, }, { isoAlpha3: "COL", timeZones: ["America/Bogota"], countryName: Colombia, isoAlpha2: CO, }, { isoAlpha3: "COD", timeZones: ["Africa/Kinshasa", "Africa/Lubumbashi"], countryName: CongoDemocraticRepublic, isoAlpha2: CD, }, { isoAlpha3: "CRI", timeZones: ["America/Costa_Rica"], countryName: CostaRica, isoAlpha2: CR, }, { isoAlpha3: "CIV", timeZones: ["Africa/Abidjan"], countryName: CotedIvoire, isoAlpha2: CI, }, { isoAlpha3: "HRV", timeZones: ["Europe/Zagreb"], countryName: Croatia, isoAlpha2: HR, }, { isoAlpha3: "CUB", timeZones: ["America/Havana"], countryName: Cuba, isoAlpha2: CU, }, { isoAlpha3: "CZE", timeZones: ["Europe/Prague"], countryName: Czechia, isoAlpha2: CZ, }, { isoAlpha3: "DNK", timeZones: ["Europe/Copenhagen"], countryName: Denmark, isoAlpha2: DK, }, { isoAlpha3: "DJI", timeZones: ["Africa/Djibouti"], countryName: Djibouti, isoAlpha2: DJ, }, { isoAlpha3: "DOM", timeZones: ["America/Santo_Domingo"], countryName: DominicanRepublic, isoAlpha2: DO, }, { isoAlpha3: "ECU", timeZones: ["America/Guayaquil", "Pacific/Galapagos"], countryName: Ecuador, isoAlpha2: EC, }, { isoAlpha3: "EGY", timeZones: ["Africa/Cairo"], countryName: Egypt, isoAlpha2: EG, }, { isoAlpha3: "SLV", timeZones: ["America/El_Salvador"], countryName: ElSalvador, isoAlpha2: SV, }, { isoAlpha3: "ERI", timeZones: ["Africa/Asmara"], countryName: Eritrea, isoAlpha2: ER, }, { isoAlpha3: "EST", timeZones: ["Europe/Tallinn"], countryName: Estonia, isoAlpha2: EE, }, { isoAlpha3: "ETH", timeZones: ["Africa/Addis_Ababa"], countryName: Ethiopia, isoAlpha2: ET, }, { isoAlpha3: "FRO", timeZones: ["Atlantic/Faroe"], countryName: FaroeIslands, isoAlpha2: FO, }, { isoAlpha3: "FIN", timeZones: ["Europe/Helsinki"], countryName: Finland, isoAlpha2: FI, }, { isoAlpha3: "FRA", timeZones: ["Europe/Paris"], countryName: France, isoAlpha2: FR, }, { isoAlpha3: "GEO", timeZones: ["Asia/Tbilisi"], countryName: Georgia, isoAlpha2: GE, }, { isoAlpha3: "DEU", timeZones: ["Europe/Berlin", "Europe/Busingen"], countryName: Germany, isoAlpha2: DE, }, { isoAlpha3: "GRC", timeZones: ["Europe/Athens"], countryName: Greece, isoAlpha2: GR, }, { isoAlpha3: "GRL", timeZones: ["America/Godthab", "America/Danmarkshavn", "America/Scoresbysund", "America/Thule"], countryName: Greenland, isoAlpha2: GL, }, { isoAlpha3: "GTM", timeZones: ["America/Guatemala"], countryName: Guatemala, isoAlpha2: GT, }, { isoAlpha3: "HTI", timeZones: ["America/Port-au-Prince"], countryName: Haiti, isoAlpha2: HT, }, { isoAlpha3: "HND", timeZones: ["America/Tegucigalpa"], countryName: Honduras, isoAlpha2: HN, }, { isoAlpha3: "HKG", timeZones: ["Asia/Hong_Kong"], countryName: HongKong, isoAlpha2: HK, }, { isoAlpha3: "HUN", timeZones: ["Europe/Budapest"], countryName: Hungary, isoAlpha2: HU, }, { isoAlpha3: "ISL", timeZones: ["Atlantic/Reykjavik"], countryName: Iceland, isoAlpha2: IS, }, { isoAlpha3: "IND", timeZones: ["Asia/Kolkata", "Asia/Calcutta"], countryName: India, isoAlpha2: IN, }, { isoAlpha3: "IDN", timeZones: ["Asia/Jakarta", "Asia/Pontianak", "Asia/Makassar", "Asia/Jayapura"], countryName: Indonesia, isoAlpha2: ID, }, { isoAlpha3: "IRN", timeZones: ["Asia/Tehran"], countryName: IranIslamicRepublic, isoAlpha2: IR, }, { isoAlpha3: "IRQ", timeZones: ["Asia/Baghdad"], countryName: Iraq, isoAlpha2: IQ, }, { isoAlpha3: "IRL", timeZones: ["Europe/Dublin"], countryName: Ireland, isoAlpha2: IE, }, { isoAlpha3: "ISR", timeZones: ["Asia/Jerusalem"], countryName: Israel, isoAlpha2: IL, }, { isoAlpha3: "ITA", timeZones: ["Europe/Rome"], countryName: Italy, isoAlpha2: IT, }, { isoAlpha3: "JAM", timeZones: ["America/Jamaica"], countryName: Jamaica, isoAlpha2: JM, }, { isoAlpha3: "JPN", timeZones: ["Asia/Tokyo"], countryName: Japan, isoAlpha2: JP, }, { isoAlpha3: "JOR", timeZones: ["Asia/Amman"], countryName: Jordan, isoAlpha2: JO, }, { isoAlpha3: "KAZ", timeZones: ["Asia/Almaty", "Asia/Qyzylorda", "Asia/Aqtobe", "Asia/Aqtau", "Asia/Oral"], countryName: Kazakhstan, isoAlpha2: KZ, }, { isoAlpha3: "KEN", timeZones: ["Africa/Nairobi"], countryName: Kenya, isoAlpha2: KE, }, { isoAlpha3: "KOR", timeZones: ["Asia/Seoul"], countryName: KoreaRepublic, isoAlpha2: KR, }, { isoAlpha3: "KWT", timeZones: ["Asia/Kuwait"], countryName: Kuwait, isoAlpha2: KW, }, { isoAlpha3: "KGZ", timeZones: ["Asia/Bishkek"], countryName: Kyrgyzstan, isoAlpha2: KG, }, { isoAlpha3: "LAO", timeZones: ["Asia/Vientiane"], countryName: LaoPeoplesDemocraticRepublic, isoAlpha2: LA, }, { isoAlpha3: "LVA", timeZones: ["Europe/Riga"], countryName: Latvia, isoAlpha2: LV, }, { isoAlpha3: "LBN", timeZones: ["Asia/Beirut"], countryName: Lebanon, isoAlpha2: LB, }, { isoAlpha3: "LBY", timeZones: ["Africa/Tripoli"], countryName: Libya, isoAlpha2: LY, }, { isoAlpha3: "LIE", timeZones: ["Europe/Vaduz"], countryName: Liechtenstein, isoAlpha2: LI, }, { isoAlpha3: "LTU", timeZones: ["Europe/Vilnius"], countryName: Lithuania, isoAlpha2: LT, }, { isoAlpha3: "LUX", timeZones: ["Europe/Luxembourg"], countryName: Luxembourg, isoAlpha2: LU, }, { isoAlpha3: "MAC", timeZones: ["Asia/Macau"], countryName: Macao, isoAlpha2: MO, }, { isoAlpha3: "MKD", timeZones: ["Europe/Skopje"], countryName: MacedoniaTheFormerYugoslavRepublic, isoAlpha2: MK, }, { isoAlpha3: "MYS", timeZones: ["Asia/Kuala_Lumpur", "Asia/Kuching"], countryName: Malaysia, isoAlpha2: MY, }, { isoAlpha3: "MDV", timeZones: ["Indian/Maldives"], countryName: Maldives, isoAlpha2: MV, }, { isoAlpha3: "MLI", timeZones: ["Africa/Bamako"], countryName: Mali, isoAlpha2: ML, }, { isoAlpha3: "MLT", timeZones: ["Europe/Malta"], countryName: Malta, isoAlpha2: MT, }, { isoAlpha3: "MEX", timeZones: [ "America/Mexico_City", "America/Cancun", "America/Merida", "America/Monterrey", "America/Matamoros", "America/Mazatlan", "America/Chihuahua", "America/Ojinaga", "America/Hermosillo", "America/Tijuana", "America/Bahia_Banderas", ], countryName: Mexico, isoAlpha2: MX, }, { isoAlpha3: "MDA", timeZones: ["Europe/Chisinau"], countryName: MoldovaRepublic, isoAlpha2: MD, }, { isoAlpha3: "MCO", timeZones: ["Europe/Monaco"], countryName: Monaco, isoAlpha2: MC, }, { isoAlpha3: "MNG", timeZones: ["Asia/Ulaanbaatar", "Asia/Hovd", "Asia/Choibalsan"], countryName: Mongolia, isoAlpha2: MN, }, { isoAlpha3: "MNE", timeZones: ["Europe/Podgorica"], countryName: Montenegro, isoAlpha2: ME, }, { isoAlpha3: "MAR", timeZones: ["Africa/Casablanca"], countryName: Morocco, isoAlpha2: MA, }, { isoAlpha3: "MMR", timeZones: ["Asia/Rangoon"], countryName: Myanmar, isoAlpha2: MM, }, { isoAlpha3: "NPL", timeZones: ["Asia/Kathmandu"], countryName: Nepal, isoAlpha2: NP, }, { isoAlpha3: "NLD", timeZones: ["Europe/Amsterdam"], countryName: Netherlands, isoAlpha2: NL, }, { isoAlpha3: "NZL", timeZones: ["Pacific/Auckland", "Pacific/Chatham"], countryName: NewZealand, isoAlpha2: NZ, }, { isoAlpha3: "NIC", timeZones: ["America/Managua"], countryName: Nicaragua, isoAlpha2: NI, }, { isoAlpha3: "NGA", timeZones: ["Africa/Lagos"], countryName: Nigeria, isoAlpha2: NG, }, { isoAlpha3: "NOR", timeZones: ["Europe/Oslo"], countryName: Norway, isoAlpha2: NO, }, { isoAlpha3: "OMN", timeZones: ["Asia/Muscat"], countryName: Oman, isoAlpha2: OM, }, { isoAlpha3: "PAK", timeZones: ["Asia/Karachi"], countryName: Pakistan, isoAlpha2: PK, }, { isoAlpha3: "PAN", timeZones: ["America/Panama"], countryName: Panama, isoAlpha2: PA, }, { isoAlpha3: "PRY", timeZones: ["America/Asuncion"], countryName: Paraguay, isoAlpha2: PY, }, { isoAlpha3: "PER", timeZones: ["America/Lima"], countryName: Peru, isoAlpha2: PE, }, { isoAlpha3: "PHL", timeZones: ["Asia/Manila"], countryName: Philippines, isoAlpha2: PH, }, { isoAlpha3: "POL", timeZones: ["Europe/Warsaw"], countryName: Poland, isoAlpha2: PL, }, { isoAlpha3: "PRT", timeZones: ["Europe/Lisbon", "Atlantic/Madeira", "Atlantic/Azores"], countryName: Portugal, isoAlpha2: PT, }, { isoAlpha3: "PRI", timeZones: ["America/Puerto_Rico"], countryName: PuertoRico, isoAlpha2: PR, }, { isoAlpha3: "QAT", timeZones: ["Asia/Qatar"], countryName: Qatar, isoAlpha2: QA, }, { isoAlpha3: "REU", timeZones: ["Indian/Reunion"], countryName: Reunion, isoAlpha2: RE, }, { isoAlpha3: "ROU", timeZones: ["Europe/Bucharest"], countryName: Romania, isoAlpha2: RO, }, { isoAlpha3: "RUS", timeZones: [ "Europe/Kaliningrad", "Europe/Moscow", "Europe/Simferopol", "Europe/Volgograd", "Europe/Astrakhan", "Europe/Samara", "Europe/Ulyanovsk", "Asia/Yekaterinburg", "Asia/Omsk", "Asia/Novosibirsk", "Asia/Barnaul", "Asia/Novokuznetsk", "Asia/Krasnoyarsk", "Asia/Irkutsk", "Asia/Chita", "Asia/Yakutsk", "Asia/Khandyga", "Asia/Vladivostok", "Asia/Ust-Nera", "Asia/Magadan", "Asia/Sakhalin", "Asia/Srednekolymsk", "Asia/Kamchatka", "Asia/Anadyr", ], countryName: RussianFederation, isoAlpha2: RU, }, { isoAlpha3: "RWA", timeZones: ["Africa/Kigali"], countryName: Rwanda, isoAlpha2: RW, }, { isoAlpha3: "SAU", timeZones: ["Asia/Riyadh"], countryName: SaudiArabia, isoAlpha2: SA, }, { isoAlpha3: "SEN", timeZones: ["Africa/Dakar"], countryName: Senegal, isoAlpha2: SN, }, { isoAlpha3: "SRB", timeZones: ["Europe/Belgrade"], countryName: Serbia, isoAlpha2: RS, }, { isoAlpha3: "SGP", timeZones: ["Asia/Singapore"], countryName: Singapore, isoAlpha2: SG, }, { isoAlpha3: "SVK", timeZones: ["Europe/Bratislava"], countryName: Slovakia, isoAlpha2: SK, }, { isoAlpha3: "SVN", timeZones: ["Europe/Ljubljana"], countryName: Slovenia, isoAlpha2: SI, }, { isoAlpha3: "SOM", timeZones: ["Africa/Mogadishu"], countryName: Somalia, isoAlpha2: SO, }, { isoAlpha3: "ZAF", timeZones: ["Africa/Johannesburg"], countryName: SouthAfrica, isoAlpha2: ZA, }, { isoAlpha3: "ESP", timeZones: ["Europe/Madrid", "Africa/Ceuta", "Atlantic/Canary"], countryName: Spain, isoAlpha2: ES, }, { isoAlpha3: "LKA", timeZones: ["Asia/Colombo"], countryName: SriLanka, isoAlpha2: LK, }, { isoAlpha3: "SWE", timeZones: ["Europe/Stockholm"], countryName: Sweden, isoAlpha2: SE, }, { isoAlpha3: "CHE", timeZones: ["Europe/Zurich"], countryName: Switzerland, isoAlpha2: CH, }, { isoAlpha3: "SYR", timeZones: ["Asia/Damascus"], countryName: SyrianArabRepublic, isoAlpha2: SY, }, { isoAlpha3: "TWN", timeZones: ["Asia/Taipei"], countryName: TaiwanProvinceOfChina, isoAlpha2: TW, }, { isoAlpha3: "TJK", timeZones: ["Asia/Dushanbe"], countryName: Tajikistan, isoAlpha2: TJ, }, { isoAlpha3: "THA", timeZones: ["Asia/Bangkok"], countryName: Thailand, isoAlpha2: TH, }, { isoAlpha3: "TTO", timeZones: ["America/Port_of_Spain"], countryName: TrinidadAndTobago, isoAlpha2: TT, }, { isoAlpha3: "TUN", timeZones: ["Africa/Tunis"], countryName: Tunisia, isoAlpha2: TN, }, { isoAlpha3: "TUR", timeZones: ["Europe/Istanbul"], countryName: Turkey, isoAlpha2: TR, }, { isoAlpha3: "TKM", timeZones: ["Asia/Ashgabat"], countryName: Turkmenistan, isoAlpha2: TM, }, { isoAlpha3: "UKR", timeZones: ["Europe/Kiev", "Europe/Uzhgorod", "Europe/Zaporozhye"], countryName: Ukraine, isoAlpha2: UA, }, { isoAlpha3: "ARE", timeZones: ["Asia/Dubai"], countryName: UnitedArabEmirates, isoAlpha2: AE, }, { isoAlpha3: "GBR", timeZones: ["Europe/London"], countryName: UnitedKingdomOfGreatBritainAndNorthernIreland, isoAlpha2: GB, }, { isoAlpha3: "USA", timeZones: [ "America/New_York", "America/Detroit", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Indiana/Indianapolis", "America/Indiana/Vincennes", "America/Indiana/Winamac", "America/Indiana/Marengo", "America/Indiana/Petersburg", "America/Indiana/Vevay", "America/Chicago", "America/Indiana/Tell_City", "America/Indiana/Knox", "America/Menominee", "America/North_Dakota/Center", "America/North_Dakota/New_Salem", "America/North_Dakota/Beulah", "America/Denver", "America/Boise", "America/Phoenix", "America/Los_Angeles", "America/Anchorage", "America/Juneau", "America/Sitka", "America/Metlakatla", "America/Yakutat", "America/Nome", "America/Adak", "Pacific/Honolulu", ], countryName: UnitedStatesOfAmerica, isoAlpha2: US, }, { isoAlpha3: "URY", timeZones: ["America/Montevideo"], countryName: Uruguay, isoAlpha2: UY, }, { isoAlpha3: "UZB", timeZones: ["Asia/Samarkand", "Asia/Tashkent"], countryName: Uzbekistan, isoAlpha2: UZ, }, { isoAlpha3: "VEN", timeZones: ["America/Caracas"], countryName: VenezuelaBolivarianRepublic, isoAlpha2: VE, }, { isoAlpha3: "VNM", timeZones: ["Asia/Ho_Chi_Minh"], countryName: Vietnam, isoAlpha2: VN, }, { isoAlpha3: "YEM", timeZones: ["Asia/Aden"], countryName: Yemen, isoAlpha2: YE, }, { isoAlpha3: "ZWE", timeZones: ["Africa/Harare"], countryName: Zimbabwe, isoAlpha2: ZW, }, ]
6,598
9,946
hyperswitch-control-center
src/utils/ResizeObserver.res
.res
type observer type dimensions @new external newResizerObserver: (array<dimensions> => unit) => observer = "ResizeObserver"
29
9,947
hyperswitch-control-center
src/utils/DictionaryUtils.res
.res
let deleteKey = (dictionary: Dict.t<'a>, key: string) => { dictionary ->Dict.toArray ->Belt.Array.keepMap(entry => { let (filterKey, _) = entry key !== filterKey ? Some(entry) : None }) ->Dict.fromArray } let deleteKeys = (dictionary: Dict.t<'a>, keys: array<string>) => { let updatedDict = dictionary ->Dict.toArray ->Belt.Array.keepMap(entry => { let (filterKey, _) = entry keys->Array.includes(filterKey) ? None : Some(entry) }) ->Dict.fromArray updatedDict } let mergeDicts = (arrDict: array<Dict.t<'a>>) => { arrDict ->Array.reduce([], (acc, dict) => { acc->Array.concat(dict->Dict.toArray) }) ->Dict.fromArray } let equalDicts = (dictionary1, dictionary2) => { // if it return nothing means both are same dictionary1 ->Dict.toArray ->Array.find(item => { let (key, value) = item dictionary2->Dict.get(key) !== Some(value) }) ->Option.isNone && dictionary2 ->Dict.toArray ->Array.find(item => { let (key, value) = item dictionary1->Dict.get(key) !== Some(value) }) ->Option.isNone } let checkEqualJsonDicts = (~checkKeys, ~ignoreKeys, dictionary1, dictionary2) => { let dictionary1 = dictionary1->JSON.Encode.object->JsonFlattenUtils.flattenObject(false) let dictionary2 = dictionary2->JSON.Encode.object->JsonFlattenUtils.flattenObject(false) dictionary1 ->Dict.toArray ->Array.find(item => { let (key, value) = item if ( (checkKeys->Array.includes(key) || checkKeys->Array.length === 0) && !(ignoreKeys->Array.includes(key)) ) { switch value->JSON.Classify.classify { | Array(array) => { let arr1 = array->LogicUtils.getStrArrayFromJsonArray let arr2 = dictionary2->LogicUtils.getStrArrayFromDict(key, []) !LogicUtils.isEqualStringArr(arr1, arr2) } | String(string) => string !== dictionary2->LogicUtils.getString(key, "") | _ => dictionary2->LogicUtils.getJsonObjectFromDict(key) !== value } } else { false } }) ->Option.isNone && dictionary2 ->Dict.toArray ->Array.find(item => { let (key, value) = item if checkKeys->Array.includes(key) && !(ignoreKeys->Array.includes(key)) { switch value->JSON.Classify.classify { | Array(array) => { let arr1 = array->LogicUtils.getStrArrayFromJsonArray let arr2 = dictionary1->LogicUtils.getStrArrayFromDict(key, []) !LogicUtils.isEqualStringArr(arr1, arr2) } | String(string) => string !== dictionary1->LogicUtils.getString(key, "") | _ => dictionary1->LogicUtils.getJsonObjectFromDict(key) !== value } } else { false } }) ->Option.isNone } let copyOfDict = dict => { dict->Dict.toArray->Array.copy->Dict.fromArray }
751
9,948
hyperswitch-control-center
src/utils/LogicUtilsTypes.res
.res
type valueType = | Amount | Rate | Volume | Latency | LatencyMs | FormattedAmount | AmountWithSuffix | Default
42
9,949
hyperswitch-control-center
src/utils/Reveal.res
.res
type postion = Top | Right
8
9,950
hyperswitch-control-center
src/utils/LoaderModal.res
.res
@react.component let make = (~showModal, ~setShowModal, ~text) => { <RenderIf condition={showModal}> <Modal showModal setShowModal modalClass="w-80 !h-56 flex items-center justify-center m-auto" paddingClass="" childClass="flex items-center justify-center h-full w-full"> <div className="flex flex-col items-center gap-2"> <Loader /> <div className="text-xl font-semibold mb-4"> {text->React.string} </div> </div> </Modal> </RenderIf> }
134
9,951
hyperswitch-control-center
src/utils/CountryUtils.res
.res
type countries = | AlandIslands | Albania | Afghanistan | Algeria | AmericanSamoa | Andorra | Angola | Anguilla | Antarctica | AntiguaAndBarbuda | Argentina | Armenia | Aruba | Australia | Austria | Azerbaijan | Bahamas | Bahrain | Bangladesh | Barbados | Belarus | Belgium | Belize | Benin | Bermuda | Bhutan | BoliviaPlurinationalState | BonaireSintEustatiusAndSaba | BosniaAndHerzegovina | Botswana | BouvetIsland | Brazil | BritishIndianOceanTerritory | BruneiDarussalam | Bulgaria | BurkinaFaso | Burundi | CaboVerde | Cambodia | Cameroon | Canada | CaymanIslands | CentralAfricanRepublic | Chad | Chile | China | ChristmasIsland | CocosKeelingIslands | Colombia | Comoros | Congo | CongoDemocraticRepublic | CookIslands | CostaRica | CotedIvoire | Croatia | Cuba | Curacao | Cyprus | Czechia | Denmark | Djibouti | Dominica | DominicanRepublic | Ecuador | Egypt | ElSalvador | EquatorialGuinea | Eritrea | Estonia | Ethiopia | FalklandIslandsMalvinas | FaroeIslands | Fiji | Finland | France | FrenchGuiana | FrenchPolynesia | FrenchSouthernTerritories | Gabon | Gambia | Georgia | Germany | Ghana | Gibraltar | Greece | Greenland | Grenada | Guadeloupe | Guam | Guatemala | Guernsey | Guinea | GuineaBissau | Guyana | Haiti | HeardIslandAndMcDonaldIslands | HolySee | Honduras | HongKong | Hungary | Iceland | India | Indonesia | IranIslamicRepublic | Iraq | Ireland | IsleOfMan | Israel | Italy | Jamaica | Japan | Jersey | Jordan | Kazakhstan | Kenya | Kiribati | KoreaDemocraticPeoplesRepublic | KoreaRepublic | Kuwait | Kyrgyzstan | LaoPeoplesDemocraticRepublic | Latvia | Lebanon | Lesotho | Liberia | Libya | Liechtenstein | Lithuania | Luxembourg | Macao | MacedoniaTheFormerYugoslavRepublic | Madagascar | Malawi | Malaysia | Maldives | Mali | Malta | MarshallIslands | Martinique | Mauritania | Mauritius | Mayotte | Mexico | MicronesiaFederatedStates | MoldovaRepublic | Monaco | Mongolia | Montenegro | Montserrat | Morocco | Mozambique | Myanmar | Namibia | Nauru | Nepal | Netherlands | NewCaledonia | NewZealand | Nicaragua | Niger | Nigeria | Niue | NorfolkIsland | NorthernMarianaIslands | Norway | Oman | Pakistan | Palau | PalestineState | Panama | PapuaNewGuinea | Paraguay | Peru | Philippines | Pitcairn | Poland | Portugal | PuertoRico | Qatar | Reunion | Romania | RussianFederation | Rwanda | SaintBarthelemy | SaintHelenaAscensionAndTristandaCunha | SaintKittsAndNevis | SaintLucia | SaintMartinFrenchpart | SaintPierreAndMiquelon | SaintVincentAndTheGrenadines | Samoa | SanMarino | SaoTomeAndPrincipe | SaudiArabia | Senegal | Serbia | Seychelles | SierraLeone | Singapore | SintMaartenDutchpart | Slovakia | Slovenia | SolomonIslands | Somalia | SouthAfrica | SouthGeorgiaAndTheSouthSandwichIslands | SouthSudan | Spain | SriLanka | Sudan | Suriname | SvalbardAndJanMayen | Swaziland | Sweden | Switzerland | SyrianArabRepublic | TaiwanProvinceOfChina | Tajikistan | TanzaniaUnitedRepublic | Thailand | TimorLeste | Togo | Tokelau | Tonga | TrinidadAndTobago | Tunisia | Turkey | Turkmenistan | TurksAndCaicosIslands | Tuvalu | Uganda | Ukraine | UnitedArabEmirates | UnitedKingdomOfGreatBritainAndNorthernIreland | UnitedStatesOfAmerica | UnitedStatesMinorOutlyingIslands | Uruguay | Uzbekistan | Vanuatu | VenezuelaBolivarianRepublic | Vietnam | VirginIslandsBritish | VirginIslandsUS | WallisAndFutuna | WesternSahara | Yemen | Zambia | Zimbabwe let countriesList = [ AlandIslands, Albania, Afghanistan, Algeria, AmericanSamoa, Andorra, Angola, Anguilla, Antarctica, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, BoliviaPlurinationalState, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, BouvetIsland, Brazil, BritishIndianOceanTerritory, BruneiDarussalam, Bulgaria, BurkinaFaso, Burundi, CaboVerde, Cambodia, Cameroon, Canada, CaymanIslands, CentralAfricanRepublic, Chad, Chile, China, ChristmasIsland, CocosKeelingIslands, Colombia, Comoros, Congo, CongoDemocraticRepublic, CookIslands, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, Czechia, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FalklandIslandsMalvinas, FaroeIslands, Fiji, Finland, France, FrenchGuiana, FrenchPolynesia, FrenchSouthernTerritories, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, HeardIslandAndMcDonaldIslands, HolySee, Honduras, HongKong, Hungary, Iceland, India, Indonesia, IranIslamicRepublic, Iraq, Ireland, IsleOfMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kiribati, KoreaDemocraticPeoplesRepublic, KoreaRepublic, Kuwait, Kyrgyzstan, LaoPeoplesDemocraticRepublic, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macao, MacedoniaTheFormerYugoslavRepublic, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, MarshallIslands, Martinique, Mauritania, Mauritius, Mayotte, Mexico, MicronesiaFederatedStates, MoldovaRepublic, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, Niue, NorfolkIsland, NorthernMarianaIslands, Norway, Oman, Pakistan, Palau, PalestineState, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Pitcairn, Poland, Portugal, PuertoRico, Qatar, Reunion, Romania, RussianFederation, Rwanda, SaintBarthelemy, SaintHelenaAscensionAndTristandaCunha, SaintKittsAndNevis, SaintLucia, SaintMartinFrenchpart, SaintPierreAndMiquelon, SaintVincentAndTheGrenadines, Samoa, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaartenDutchpart, Slovakia, Slovenia, SolomonIslands, Somalia, SouthAfrica, SouthGeorgiaAndTheSouthSandwichIslands, SouthSudan, Spain, SriLanka, Sudan, Suriname, SvalbardAndJanMayen, Swaziland, Sweden, Switzerland, SyrianArabRepublic, TaiwanProvinceOfChina, Tajikistan, TanzaniaUnitedRepublic, Thailand, TimorLeste, Togo, Tokelau, Tonga, TrinidadAndTobago, Tunisia, Turkey, Turkmenistan, TurksAndCaicosIslands, Tuvalu, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdomOfGreatBritainAndNorthernIreland, UnitedStatesOfAmerica, UnitedStatesMinorOutlyingIslands, Uruguay, Uzbekistan, Vanuatu, VenezuelaBolivarianRepublic, Vietnam, VirginIslandsBritish, VirginIslandsUS, WallisAndFutuna, WesternSahara, Yemen, Zambia, Zimbabwe, ] type countiesCode = | AF | AX | AL | DZ | AS | AD | AO | AI | AQ | AG | AR | AM | AW | AU | AT | AZ | BS | BH | BD | BB | BY | BE | BZ | BJ | BM | BT | BO | BQ | BA | BW | BV | BR | IO | BN | BG | BF | BI | CV | KH | CM | CA | KY | CF | TD | CL | CN | CX | CC | CO | KM | CG | CD | CK | CR | CI | HR | CU | CW | CY | CZ | DK | DJ | DM | DO | EC | EG | SV | GQ | ER | EE | ET | FK | FO | FJ | FI | FR | GF | PF | TF | GA | GM | GE | DE | GH | GI | GR | GL | GD | GP | GU | GT | GG | GN | GW | GY | HT | HM | VA | HN | HK | HU | IS | IN | ID | IR | IQ | IE | IM | IL | IT | JM | JP | JE | JO | KZ | KE | KI | KP | KR | KW | KG | LA | LV | LB | LS | LR | LY | LI | LT | LU | MO | MK | MG | MW | MY | MV | ML | MT | MH | MQ | MR | MU | YT | MX | FM | MD | MC | MN | ME | MS | MA | MZ | MM | NA | NR | NP | NL | NC | NZ | NI | NE | NG | NU | NF | MP | NO | OM | PK | PW | PS | PA | PG | PY | PE | PH | PN | PL | PT | PR | QA | RE | RO | RU | RW | BL | SH | KN | LC | MF | PM | VC | WS | SM | ST | SA | SN | RS | SC | SL | SG | SX | SK | SI | SB | SO | ZA | GS | SS | ES | LK | SD | SR | SJ | SZ | SE | CH | SY | TW | TJ | TZ | TH | TL | TG | TK | TO | TT | TN | TR | TM | TC | TV | UG | UA | AE | GB | US | UM | UY | UZ | VU | VE | VN | VG | VI | WF | EH | YE | ZM | ZW let getCountryFromCountryCode = code => { switch code { | AF => Afghanistan | AX => AlandIslands | AL => Albania | DZ => Algeria | AS => AmericanSamoa | AD => Andorra | AO => Angola | AI => Anguilla | AQ => Antarctica | AG => AntiguaAndBarbuda | AR => Argentina | AM => Armenia | AW => Aruba | AU => Australia | AT => Austria | AZ => Azerbaijan | BS => Bahamas | BH => Bahrain | BD => Bangladesh | BB => Barbados | BY => Belarus | BE => Belgium | BZ => Belize | BJ => Benin | BM => Bermuda | BT => Bhutan | BO => BoliviaPlurinationalState | BQ => BonaireSintEustatiusAndSaba | BA => BosniaAndHerzegovina | BW => Botswana | BV => BouvetIsland | BR => Brazil | IO => BritishIndianOceanTerritory | BN => BruneiDarussalam | BG => Bulgaria | BF => BurkinaFaso | BI => Burundi | CV => CaboVerde | KH => Cambodia | CM => Cameroon | CA => Canada | KY => CaymanIslands | CF => CentralAfricanRepublic | TD => Chad | CL => Chile | CN => China | CX => ChristmasIsland | CC => CocosKeelingIslands | CO => Colombia | KM => Comoros | CG => Congo | CD => CongoDemocraticRepublic | CK => CookIslands | CR => CostaRica | CI => CotedIvoire | HR => Croatia | CU => Cuba | CW => Curacao | CY => Cyprus | CZ => Czechia | DK => Denmark | DJ => Djibouti | DM => Dominica | DO => DominicanRepublic | EC => Ecuador | EG => Egypt | SV => ElSalvador | GQ => EquatorialGuinea | ER => Eritrea | EE => Estonia | ET => Ethiopia | FK => FalklandIslandsMalvinas | FO => FaroeIslands | FJ => Fiji | FI => Finland | FR => France | GF => FrenchGuiana | PF => FrenchPolynesia | TF => FrenchSouthernTerritories | GA => Gabon | GM => Gambia | GE => Georgia | DE => Germany | GH => Ghana | GI => Gibraltar | GR => Greece | GL => Greenland | GD => Grenada | GP => Guadeloupe | GU => Guam | GT => Guatemala | GG => Guernsey | GN => Guinea | GW => GuineaBissau | GY => Guyana | HT => Haiti | HM => HeardIslandAndMcDonaldIslands | VA => HolySee | HN => Honduras | HK => HongKong | HU => Hungary | IS => Iceland | IN => India | ID => Indonesia | IR => IranIslamicRepublic | IQ => Iraq | IE => Ireland | IM => IsleOfMan | IL => Israel | IT => Italy | JM => Jamaica | JP => Japan | JE => Jersey | JO => Jordan | KZ => Kazakhstan | KE => Kenya | KI => Kiribati | KP => KoreaDemocraticPeoplesRepublic | KR => KoreaRepublic | KW => Kuwait | KG => Kyrgyzstan | LA => LaoPeoplesDemocraticRepublic | LV => Latvia | LB => Lebanon | LS => Lesotho | LR => Liberia | LY => Libya | LI => Liechtenstein | LT => Lithuania | LU => Luxembourg | MO => Macao | MK => MacedoniaTheFormerYugoslavRepublic | MG => Madagascar | MW => Malawi | MY => Malaysia | MV => Maldives | ML => Mali | MT => Malta | MH => MarshallIslands | MQ => Martinique | MR => Mauritania | MU => Mauritius | YT => Mayotte | MX => Mexico | FM => MicronesiaFederatedStates | MD => MoldovaRepublic | MC => Monaco | MN => Mongolia | ME => Montenegro | MS => Montserrat | MA => Morocco | MZ => Mozambique | MM => Myanmar | NA => Namibia | NR => Nauru | NP => Nepal | NL => Netherlands | NC => NewCaledonia | NZ => NewZealand | NI => Nicaragua | NE => Niger | NG => Nigeria | NU => Niue | NF => NorfolkIsland | MP => NorthernMarianaIslands | NO => Norway | OM => Oman | PK => Pakistan | PW => Palau | PS => PalestineState | PA => Panama | PG => PapuaNewGuinea | PY => Paraguay | PE => Peru | PH => Philippines | PN => Pitcairn | PL => Poland | PT => Portugal | PR => PuertoRico | QA => Qatar | RE => Reunion | RO => Romania | RU => RussianFederation | RW => Rwanda | BL => SaintBarthelemy | SH => SaintHelenaAscensionAndTristandaCunha | KN => SaintKittsAndNevis | LC => SaintLucia | MF => SaintMartinFrenchpart | PM => SaintPierreAndMiquelon | VC => SaintVincentAndTheGrenadines | WS => Samoa | SM => SanMarino | ST => SaoTomeAndPrincipe | SA => SaudiArabia | SN => Senegal | RS => Serbia | SC => Seychelles | SL => SierraLeone | SG => Singapore | SX => SintMaartenDutchpart | SK => Slovakia | SI => Slovenia | SB => SolomonIslands | SO => Somalia | ZA => SouthAfrica | GS => SouthGeorgiaAndTheSouthSandwichIslands | SS => SouthSudan | ES => Spain | LK => SriLanka | SD => Sudan | SR => Suriname | SJ => SvalbardAndJanMayen | SZ => Swaziland | SE => Sweden | CH => Switzerland | SY => SyrianArabRepublic | TW => TaiwanProvinceOfChina | TJ => Tajikistan | TZ => TanzaniaUnitedRepublic | TH => Thailand | TL => TimorLeste | TG => Togo | TK => Tokelau | TO => Tonga | TT => TrinidadAndTobago | TN => Tunisia | TR => Turkey | TM => Turkmenistan | TC => TurksAndCaicosIslands | TV => Tuvalu | UG => Uganda | UA => Ukraine | AE => UnitedArabEmirates | GB => UnitedKingdomOfGreatBritainAndNorthernIreland | US => UnitedStatesOfAmerica | UM => UnitedStatesMinorOutlyingIslands | UY => Uruguay | UZ => Uzbekistan | VU => Vanuatu | VE => VenezuelaBolivarianRepublic | VN => Vietnam | VG => VirginIslandsBritish | VI => VirginIslandsUS | WF => WallisAndFutuna | EH => WesternSahara | YE => Yemen | ZM => Zambia | ZW => Zimbabwe } } let getCountryCodeFromCountry = country => { switch country { | Afghanistan => AF | AlandIslands => AX | Albania => AL | Algeria => DZ | AmericanSamoa => AS | Andorra => AD | Angola => AO | Anguilla => AI | Antarctica => AQ | AntiguaAndBarbuda => AG | Argentina => AR | Armenia => AM | Aruba => AW | Australia => AU | Austria => AT | Azerbaijan => AZ | Bahamas => BS | Bahrain => BH | Bangladesh => BD | Barbados => BB | Belarus => BY | Belgium => BE | Belize => BZ | Benin => BJ | Bermuda => BM | Bhutan => BT | BoliviaPlurinationalState => BO | BonaireSintEustatiusAndSaba => BQ | BosniaAndHerzegovina => BA | Botswana => BW | BouvetIsland => BV | Brazil => BR | BritishIndianOceanTerritory => IO | BruneiDarussalam => BN | Bulgaria => BG | BurkinaFaso => BF | Burundi => BI | CaboVerde => CV | Cambodia => KH | Cameroon => CM | Canada => CA | CaymanIslands => KY | CentralAfricanRepublic => CF | Chad => TD | Chile => CL | China => CN | ChristmasIsland => CX | CocosKeelingIslands => CC | Colombia => CO | Comoros => KM | Congo => CG | CongoDemocraticRepublic => CD | CookIslands => CK | CostaRica => CR | CotedIvoire => CI | Croatia => HR | Cuba => CU | Curacao => CW | Cyprus => CY | Czechia => CZ | Denmark => DK | Djibouti => DJ | Dominica => DM | DominicanRepublic => DO | Ecuador => EC | Egypt => EG | ElSalvador => SV | EquatorialGuinea => GQ | Eritrea => ER | Estonia => EE | Ethiopia => ET | FalklandIslandsMalvinas => FK | FaroeIslands => FO | Fiji => FJ | Finland => FI | France => FR | FrenchGuiana => GF | FrenchPolynesia => PF | FrenchSouthernTerritories => TF | Gabon => GA | Gambia => GM | Georgia => GE | Germany => DE | Ghana => GH | Gibraltar => GI | Greece => GR | Greenland => GL | Grenada => GD | Guadeloupe => GP | Guam => GU | Guatemala => GT | Guernsey => GG | Guinea => GN | GuineaBissau => GW | Guyana => GY | Haiti => HT | HeardIslandAndMcDonaldIslands => HM | HolySee => VA | Honduras => HN | HongKong => HK | Hungary => HU | Iceland => IS | India => IN | Indonesia => ID | IranIslamicRepublic => IR | Iraq => IQ | Ireland => IE | IsleOfMan => IM | Israel => IL | Italy => IT | Jamaica => JM | Japan => JP | Jersey => JE | Jordan => JO | Kazakhstan => KZ | Kenya => KE | Kiribati => KI | KoreaDemocraticPeoplesRepublic => KP | KoreaRepublic => KR | Kuwait => KW | Kyrgyzstan => KG | LaoPeoplesDemocraticRepublic => LA | Latvia => LV | Lebanon => LB | Lesotho => LS | Liberia => LR | Libya => LY | Liechtenstein => LI | Lithuania => LT | Luxembourg => LU | Macao => MO | MacedoniaTheFormerYugoslavRepublic => MK | Madagascar => MG | Malawi => MW | Malaysia => MY | Maldives => MV | Mali => ML | Malta => MT | MarshallIslands => MH | Martinique => MQ | Mauritania => MR | Mauritius => MU | Mayotte => YT | Mexico => MX | MicronesiaFederatedStates => FM | MoldovaRepublic => MD | Monaco => MC | Mongolia => MN | Montenegro => ME | Montserrat => MS | Morocco => MA | Mozambique => MZ | Myanmar => MM | Namibia => NA | Nauru => NR | Nepal => NP | Netherlands => NL | NewCaledonia => NC | NewZealand => NZ | Nicaragua => NI | Niger => NE | Nigeria => NG | Niue => NU | NorfolkIsland => NF | NorthernMarianaIslands => MP | Norway => NO | Oman => OM | Pakistan => PK | Palau => PW | PalestineState => PS | Panama => PA | PapuaNewGuinea => PG | Paraguay => PY | Peru => PE | Philippines => PH | Pitcairn => PN | Poland => PL | Portugal => PT | PuertoRico => PR | Qatar => QA | Reunion => RE | Romania => RO | RussianFederation => RU | Rwanda => RW | SaintBarthelemy => BL | SaintHelenaAscensionAndTristandaCunha => SH | SaintKittsAndNevis => KN | SaintLucia => LC | SaintMartinFrenchpart => MF | SaintPierreAndMiquelon => PM | SaintVincentAndTheGrenadines => VC | Samoa => WS | SanMarino => SM | SaoTomeAndPrincipe => ST | SaudiArabia => SA | Senegal => SN | Serbia => RS | Seychelles => SC | SierraLeone => SL | Singapore => SG | SintMaartenDutchpart => SX | Slovakia => SK | Slovenia => SI | SolomonIslands => SB | Somalia => SO | SouthAfrica => ZA | SouthGeorgiaAndTheSouthSandwichIslands => GS | SouthSudan => SS | Spain => ES | SriLanka => LK | Sudan => SD | Suriname => SR | SvalbardAndJanMayen => SJ | Swaziland => SZ | Sweden => SE | Switzerland => CH | SyrianArabRepublic => SY | TaiwanProvinceOfChina => TW | Tajikistan => TJ | TanzaniaUnitedRepublic => TZ | Thailand => TH | TimorLeste => TL | Togo => TG | Tokelau => TK | Tonga => TO | TrinidadAndTobago => TT | Tunisia => TN | Turkey => TR | Turkmenistan => TM | TurksAndCaicosIslands => TC | Tuvalu => TV | Uganda => UG | Ukraine => UA | UnitedArabEmirates => AE | UnitedKingdomOfGreatBritainAndNorthernIreland => GB | UnitedStatesOfAmerica => US | UnitedStatesMinorOutlyingIslands => UM | Uruguay => UY | Uzbekistan => UZ | Vanuatu => VU | VenezuelaBolivarianRepublic => VE | Vietnam => VN | VirginIslandsBritish => VG | VirginIslandsUS => VI | WallisAndFutuna => WF | WesternSahara => EH | Yemen => YE | Zambia => ZM | Zimbabwe => ZW } } let getCountryNameFromVarient = country => { switch country { | Afghanistan => "Afghanistan" | AlandIslands => "AlandIslands" | Albania => "Albania" | Algeria => "Algeria" | AmericanSamoa => "AmericanSamoa" | Andorra => "Andorra" | Angola => "Angola" | Anguilla => "Anguilla" | Antarctica => "Antarctica" | AntiguaAndBarbuda => "AntiguaAndBarbuda" | Argentina => "Argentina" | Armenia => "Armenia" | Aruba => "Aruba" | Australia => "Australia" | Austria => "Austria" | Azerbaijan => "Azerbaijan" | Bahamas => "Bahamas" | Bahrain => "Bahrain" | Bangladesh => "Bangladesh" | Barbados => "Barbados" | Belarus => "Belarus" | Belgium => "Belgium" | Belize => "Belize" | Benin => "Benin" | Bermuda => "Bermuda" | Bhutan => "Bhutan" | BoliviaPlurinationalState => "BoliviaPlurinationalState" | BonaireSintEustatiusAndSaba => "BonaireSintEustatiusAndSaba" | BosniaAndHerzegovina => "BosniaAndHerzegovina" | Botswana => "Botswana" | BouvetIsland => "BouvetIsland" | Brazil => "Brazil" | BritishIndianOceanTerritory => "BritishIndianOceanTerritory" | BruneiDarussalam => "BruneiDarussalam" | Bulgaria => "Bulgaria" | BurkinaFaso => "BurkinaFaso" | Burundi => "Burundi" | CaboVerde => "CaboVerde" | Cambodia => "Cambodia" | Cameroon => "Cameroon" | Canada => "Canada" | CaymanIslands => "CaymanIslands" | CentralAfricanRepublic => "CentralAfricanRepublic" | Chad => "Chad" | Chile => "Chile" | China => "China" | ChristmasIsland => "ChristmasIsland" | CocosKeelingIslands => "CocosKeelingIslands" | Colombia => "Colombia" | Comoros => "Comoros" | Congo => "Congo" | CongoDemocraticRepublic => "CongoDemocraticRepublic" | CookIslands => "CookIslands" | CostaRica => "CostaRica" | CotedIvoire => "CotedIvoire" | Croatia => "Croatia" | Cuba => "Cuba" | Curacao => "Curacao" | Cyprus => "Cyprus" | Czechia => "Czechia" | Denmark => "Denmark" | Djibouti => "Djibouti" | Dominica => "Dominica" | DominicanRepublic => "DominicanRepublic" | Ecuador => "Ecuador" | Egypt => "Egypt" | ElSalvador => "ElSalvador" | EquatorialGuinea => "EquatorialGuinea" | Eritrea => "Eritrea" | Estonia => "Estonia" | Ethiopia => "Ethiopia" | FalklandIslandsMalvinas => "FalklandIslandsMalvinas" | FaroeIslands => "FaroeIslands" | Fiji => "Fiji" | Finland => "Finland" | France => "France" | FrenchGuiana => "FrenchGuiana" | FrenchPolynesia => "FrenchPolynesia" | FrenchSouthernTerritories => "FrenchSouthernTerritories" | Gabon => "Gabon" | Gambia => "Gambia" | Georgia => "Georgia" | Germany => "Germany" | Ghana => "Ghana" | Gibraltar => "Gibraltar" | Greece => "Greece" | Greenland => "Greenland" | Grenada => "Grenada" | Guadeloupe => "Guadeloupe" | Guam => "Guam" | Guatemala => "Guatemala" | Guernsey => "Guernsey" | Guinea => "Guinea" | GuineaBissau => "GuineaBissau" | Guyana => "Guyana" | Haiti => "Haiti" | HeardIslandAndMcDonaldIslands => "HeardIslandAndMcDonaldIslands" | HolySee => "HolySee" | Honduras => "Honduras" | HongKong => "HongKong" | Hungary => "Hungary" | Iceland => "Iceland" | India => "India" | Indonesia => "Indonesia" | IranIslamicRepublic => "IranIslamicRepublic" | Iraq => "Iraq" | Ireland => "Ireland" | IsleOfMan => "IsleOfMan" | Israel => "Israel" | Italy => "Italy" | Jamaica => "Jamaica" | Japan => "Japan" | Jersey => "Jersey" | Jordan => "Jordan" | Kazakhstan => "Kazakhstan" | Kenya => "Kenya" | Kiribati => "Kiribati" | KoreaDemocraticPeoplesRepublic => "KoreaDemocraticPeoplesRepublic" | KoreaRepublic => "KoreaRepublic" | Kuwait => "Kuwait" | Kyrgyzstan => "Kyrgyzstan" | LaoPeoplesDemocraticRepublic => "LaoPeoplesDemocraticRepublic" | Latvia => "Latvia" | Lebanon => "Lebanon" | Lesotho => "Lesotho" | Liberia => "Liberia" | Libya => "Libya" | Liechtenstein => "Liechtenstein" | Lithuania => "Lithuania" | Luxembourg => "Luxembourg" | Macao => "Macao" | MacedoniaTheFormerYugoslavRepublic => "MacedoniaTheFormerYugoslavRepublic" | Madagascar => "Madagascar" | Malawi => "Malawi" | Malaysia => "Malaysia" | Maldives => "Maldives" | Mali => "Mali" | Malta => "Malta" | MarshallIslands => "MarshallIslands" | Martinique => "Martinique" | Mauritania => "Mauritania" | Mauritius => "Mauritius" | Mayotte => "Mayotte" | Mexico => "Mexico" | MicronesiaFederatedStates => "MicronesiaFederatedStates" | MoldovaRepublic => "MoldovaRepublic" | Monaco => "Monaco" | Mongolia => "Mongolia" | Montenegro => "Montenegro" | Montserrat => "Montserrat" | Morocco => "Morocco" | Mozambique => "Mozambique" | Myanmar => "Myanmar" | Namibia => "Namibia" | Nauru => "Nauru" | Nepal => "Nepal" | Netherlands => "Netherlands" | NewCaledonia => "NewCaledonia" | NewZealand => "NewZealand" | Nicaragua => "Nicaragua" | Niger => "Niger" | Nigeria => "Nigeria" | Niue => "Niue" | NorfolkIsland => "NorfolkIsland" | NorthernMarianaIslands => "NorthernMarianaIslands" | Norway => "Norway" | Oman => "Oman" | Pakistan => "Pakistan" | Palau => "Palau" | PalestineState => "PalestineState" | Panama => "Panama" | PapuaNewGuinea => "PapuaNewGuinea" | Paraguay => "Paraguay" | Peru => "Peru" | Philippines => "Philippines" | Pitcairn => "Pitcairn" | Poland => "Poland" | Portugal => "Portugal" | PuertoRico => "PuertoRico" | Qatar => "Qatar" | Reunion => "Reunion" | Romania => "Romania" | RussianFederation => "RussianFederation" | Rwanda => "Rwanda" | SaintBarthelemy => "SaintBarthelemy" | SaintHelenaAscensionAndTristandaCunha => "SaintHelenaAscensionAndTristandaCunha" | SaintKittsAndNevis => "SaintKittsAndNevis" | SaintLucia => "SaintLucia" | SaintMartinFrenchpart => "SaintMartinFrenchpart" | SaintPierreAndMiquelon => "SaintPierreAndMiquelon" | SaintVincentAndTheGrenadines => "SaintVincentAndTheGrenadines" | Samoa => "Samoa" | SanMarino => "SanMarino" | SaoTomeAndPrincipe => "SaoTomeAndPrincipe" | SaudiArabia => "SaudiArabia" | Senegal => "Senegal" | Serbia => "Serbia" | Seychelles => "Seychelles" | SierraLeone => "SierraLeone" | Singapore => "Singapore" | SintMaartenDutchpart => "SintMaartenDutchpart" | Slovakia => "Slovakia" | Slovenia => "Slovenia" | SolomonIslands => "SolomonIslands" | Somalia => "Somalia" | SouthAfrica => "SouthAfrica" | SouthGeorgiaAndTheSouthSandwichIslands => "SouthGeorgiaAndTheSouthSandwichIslands" | SouthSudan => "SouthSudan" | Spain => "Spain" | SriLanka => "SriLanka" | Sudan => "Sudan" | Suriname => "Suriname" | SvalbardAndJanMayen => "SvalbardAndJanMayen" | Swaziland => "Swaziland" | Sweden => "Sweden" | Switzerland => "Switzerland" | SyrianArabRepublic => "SyrianArabRepublic" | TaiwanProvinceOfChina => "TaiwanProvinceOfChina" | Tajikistan => "Tajikistan" | TanzaniaUnitedRepublic => "TanzaniaUnitedRepublic" | Thailand => "Thailand" | TimorLeste => "TimorLeste" | Togo => "Togo" | Tokelau => "Tokelau" | Tonga => "Tonga" | TrinidadAndTobago => "TrinidadAndTobago" | Tunisia => "Tunisia" | Turkey => "Turkey" | Turkmenistan => "Turkmenistan" | TurksAndCaicosIslands => "TurksAndCaicosIslands" | Tuvalu => "Tuvalu" | Uganda => "Uganda" | Ukraine => "Ukraine" | UnitedArabEmirates => "UnitedArabEmirates" | UnitedKingdomOfGreatBritainAndNorthernIreland => "UnitedKingdomOfGreatBritainAndNorthernIreland" | UnitedStatesOfAmerica => "UnitedStatesOfAmerica" | UnitedStatesMinorOutlyingIslands => "UnitedStatesMinorOutlyingIslands" | Uruguay => "Uruguay" | Uzbekistan => "Uzbekistan" | Vanuatu => "Vanuatu" | VenezuelaBolivarianRepublic => "VenezuelaBolivarianRepublic" | Vietnam => "Vietnam" | VirginIslandsBritish => "VirginIslandsBritish" | VirginIslandsUS => "VirginIslandsUS" | WallisAndFutuna => "WallisAndFutuna" | WesternSahara => "WesternSahara" | Yemen => "Yemen" | Zambia => "Zambia" | Zimbabwe => "Zimbabwe" } } let getCountryCodeStringFromVarient = code => { switch code { | AF => "AF" | AX => "AX" | AL => "AL" | DZ => "DZ" | AS => "AS" | AD => "AD" | AO => "AO" | AI => "AI" | AQ => "AQ" | AG => "AG" | AR => "AR" | AM => "AM" | AW => "AW" | AU => "AU" | AT => "AT" | AZ => "AZ" | BS => "BS" | BH => "BH" | BD => "BD" | BB => "BB" | BY => "BY" | BE => "BE" | BZ => "BZ" | BJ => "BJ" | BM => "BM" | BT => "BT" | BO => "BO" | BQ => "BQ" | BA => "BA" | BW => "BW" | BV => "BV" | BR => "BR" | IO => "IO" | BN => "BN" | BG => "BG" | BF => "BF" | BI => "BI" | CV => "CV" | KH => "KH" | CM => "CM" | CA => "CA" | KY => "KY" | CF => "CF" | TD => "TD" | CL => "CL" | CN => "CN" | CX => "CX" | CC => "CC" | CO => "CO" | KM => "KM" | CG => "CG" | CD => "CD" | CK => "CK" | CR => "CR" | CI => "CI" | HR => "HR" | CU => "CU" | CW => "CW" | CY => "CY" | CZ => "CZ" | DK => "DK" | DJ => "DJ" | DM => "DM" | DO => "DO" | EC => "EC" | EG => "EG" | SV => "SV" | GQ => "GQ" | ER => "ER" | EE => "EE" | ET => "ET" | FK => "FK" | FO => "FO" | FJ => "FJ" | FI => "FI" | FR => "FR" | GF => "GF" | PF => "PF" | TF => "TF" | GA => "GA" | GM => "GM" | GE => "GE" | DE => "DE" | GH => "GH" | GI => "GI" | GR => "GR" | GL => "GL" | GD => "GD" | GP => "GP" | GU => "GU" | GT => "GT" | GG => "GG" | GN => "GN" | GW => "GW" | GY => "GY" | HT => "HT" | HM => "HM" | VA => "VA" | HN => "HN" | HK => "HK" | HU => "HU" | IS => "IS" | IN => "IN" | ID => "ID" | IR => "IR" | IQ => "IQ" | IE => "IE" | IM => "IM" | IL => "IL" | IT => "IT" | JM => "JM" | JP => "JP" | JE => "JE" | JO => "JO" | KZ => "KZ" | KE => "KE" | KI => "KI" | KP => "KP" | KR => "KR" | KW => "KW" | KG => "KG" | LA => "LA" | LV => "LV" | LB => "LB" | LS => "LS" | LR => "LR" | LY => "LY" | LI => "LI" | LT => "LT" | LU => "LU" | MO => "MO" | MK => "MK" | MG => "MG" | MW => "MW" | MY => "MY" | MV => "MV" | ML => "ML" | MT => "MT" | MH => "MH" | MQ => "MQ" | MR => "MR" | MU => "MU" | YT => "YT" | MX => "MX" | FM => "FM" | MD => "MD" | MC => "MC" | MN => "MN" | ME => "ME" | MS => "MS" | MA => "MA" | MZ => "MZ" | MM => "MM" | NA => "NA" | NR => "NR" | NP => "NP" | NL => "NL" | NC => "NC" | NZ => "NZ" | NI => "NI" | NE => "NE" | NG => "NG" | NU => "NU" | NF => "NF" | MP => "MP" | NO => "NO" | OM => "OM" | PK => "PK" | PW => "PW" | PS => "PS" | PA => "PA" | PG => "PG" | PY => "PY" | PE => "PE" | PH => "PH" | PN => "PN" | PL => "PL" | PT => "PT" | PR => "PR" | QA => "QA" | RE => "RE" | RO => "RO" | RU => "RU" | RW => "RW" | BL => "BL" | SH => "SH" | KN => "KN" | LC => "LC" | MF => "MF" | PM => "PM" | VC => "VC" | WS => "WS" | SM => "SM" | ST => "ST" | SA => "SA" | SN => "SN" | RS => "RS" | SC => "SC" | SL => "SL" | SG => "SG" | SX => "SX" | SK => "SK" | SI => "SI" | SB => "SB" | SO => "SO" | ZA => "ZA" | GS => "GS" | SS => "SS" | ES => "ES" | LK => "LK" | SD => "SD" | SR => "SR" | SJ => "SJ" | SZ => "SZ" | SE => "SE" | CH => "CH" | SY => "SY" | TW => "TW" | TJ => "TJ" | TZ => "TZ" | TH => "TH" | TL => "TL" | TG => "TG" | TK => "TK" | TO => "TO" | TT => "TT" | TN => "TN" | TR => "TR" | TM => "TM" | TC => "TC" | TV => "TV" | UG => "UG" | UA => "UA" | AE => "AE" | GB => "GB" | US => "US" | UM => "UM" | UY => "UY" | UZ => "UZ" | VU => "VU" | VE => "VE" | VN => "VN" | VG => "VG" | VI => "VI" | WF => "WF" | EH => "EH" | YE => "YE" | ZM => "ZM" | ZW => "ZW" } } let getCountryFromString = country => { switch country { | "Afghanistan" => Afghanistan | "AlandIslands" => AlandIslands | "Albania" => Albania | "AmericanSamoa" => AmericanSamoa | "Andorra" => Andorra | "Angola" => Angola | "Algeria" => Algeria | "Anguilla" => Anguilla | "Antarctica" => Antarctica | "AntiguaAndBarbuda" => AntiguaAndBarbuda | "Argentina" => Argentina | "Armenia" => Armenia | "Aruba" => Aruba | "Australia" => Australia | "Austria" => Austria | "Azerbaijan" => Azerbaijan | "Bahamas" => Bahamas | "Bahrain" => Bahrain | "Bangladesh" => Bangladesh | "Barbados" => Barbados | "Belarus" => Belarus | "Belgium" => Belgium | "Belize" => Belize | "Benin" => Benin | "Bermuda" => Bermuda | "Bhutan" => Bhutan | "BoliviaPlurinationalState" => BoliviaPlurinationalState | "BonaireSintEustatiusAndSaba" => BonaireSintEustatiusAndSaba | "BosniaAndHerzegovina" => BosniaAndHerzegovina | "Botswana" => Botswana | "BouvetIsland" => BouvetIsland | "Brazil" => Brazil | "BritishIndianOceanTerritory" => BritishIndianOceanTerritory | "BruneiDarussalam" => BruneiDarussalam | "Bulgaria" => Bulgaria | "BurkinaFaso" => BurkinaFaso | "Burundi" => Burundi | "CaboVerde" => CaboVerde | "Cambodia" => Cambodia | "Cameroon" => Cameroon | "Canada" => Canada | "CaymanIslands" => CaymanIslands | "CentralAfricanRepublic" => CentralAfricanRepublic | "Chad" => Chad | "Chile" => Chile | "China" => China | "ChristmasIsland" => ChristmasIsland | "CocosKeelingIslands" => CocosKeelingIslands | "Colombia" => Colombia | "Comoros" => Comoros | "Congo" => Congo | "CongoDemocraticRepublic" => CongoDemocraticRepublic | "CookIslands" => CookIslands | "CostaRica" => CostaRica | "CotedIvoire" => CotedIvoire | "Croatia" => Croatia | "Cuba" => Cuba | "Curacao" => Curacao | "Cyprus" => Cyprus | "Czechia" => Czechia | "Denmark" => Denmark | "Djibouti" => Djibouti | "Dominica" => Dominica | "DominicanRepublic" => DominicanRepublic | "Ecuador" => Ecuador | "Egypt" => Egypt | "ElSalvador" => ElSalvador | "EquatorialGuinea" => EquatorialGuinea | "Eritrea" => Eritrea | "Estonia" => Estonia | "Ethiopia" => Ethiopia | "FalklandIslandsMalvinas" => FalklandIslandsMalvinas | "FaroeIslands" => FaroeIslands | "Fiji" => Fiji | "Finland" => Finland | "France" => France | "FrenchGuiana" => FrenchGuiana | "FrenchPolynesia" => FrenchPolynesia | "FrenchSouthernTerritories" => FrenchSouthernTerritories | "Gabon" => Gabon | "Gambia" => Gambia | "Georgia" => Georgia | "Germany" => Germany | "Ghana" => Ghana | "Gibraltar" => Gibraltar | "Greece" => Greece | "Greenland" => Greenland | "Grenada" => Grenada | "Guadeloupe" => Guadeloupe | "Guam" => Guam | "Guatemala" => Guatemala | "Guernsey" => Guernsey | "Guinea" => Guinea | "GuineaBissau" => GuineaBissau | "Guyana" => Guyana | "Haiti" => Haiti | "HeardIslandAndMcDonaldIslands" => HeardIslandAndMcDonaldIslands | "HolySee" => HolySee | "Honduras" => Honduras | "HongKong" => HongKong | "Hungary" => Hungary | "Iceland" => Iceland | "India" => India | "Indonesia" => Indonesia | "IranIslamicRepublic" => IranIslamicRepublic | "Iraq" => Iraq | "Ireland" => Ireland | "IsleOfMan" => IsleOfMan | "Israel" => Israel | "Italy" => Italy | "Jamaica" => Jamaica | "Japan" => Japan | "Jersey" => Jersey | "Jordan" => Jordan | "Kazakhstan" => Kazakhstan | "Kenya" => Kenya | "Kiribati" => Kiribati | "KoreaDemocraticPeoplesRepublic" => KoreaDemocraticPeoplesRepublic | "KoreaRepublic" => KoreaRepublic | "Kuwait" => Kuwait | "Kyrgyzstan" => Kyrgyzstan | "LaoPeoplesDemocraticRepublic" => LaoPeoplesDemocraticRepublic | "Latvia" => Latvia | "Lebanon" => Lebanon | "Lesotho" => Lesotho | "Liberia" => Liberia | "Libya" => Libya | "Liechtenstein" => Liechtenstein | "Lithuania" => Lithuania | "Luxembourg" => Luxembourg | "Macao" => Macao | "MacedoniaTheFormerYugoslavRepublic" => MacedoniaTheFormerYugoslavRepublic | "Madagascar" => Madagascar | "Malawi" => Malawi | "Malaysia" => Malaysia | "Maldives" => Maldives | "Mali" => Mali | "Malta" => Malta | "MarshallIslands" => MarshallIslands | "Martinique" => Martinique | "Mauritania" => Mauritania | "Mauritius" => Mauritius | "Mayotte" => Mayotte | "Mexico" => Mexico | "MicronesiaFederatedStates" => MicronesiaFederatedStates | "MoldovaRepublic" => MoldovaRepublic | "Monaco" => Monaco | "Mongolia" => Mongolia | "Montenegro" => Montenegro | "Montserrat" => Montserrat | "Morocco" => Morocco | "Mozambique" => Mozambique | "Myanmar" => Myanmar | "Namibia" => Namibia | "Nauru" => Nauru | "Nepal" => Nepal | "Netherlands" => Netherlands | "NewCaledonia" => NewCaledonia | "NewZealand" => NewZealand | "Nicaragua" => Nicaragua | "Niger" => Niger | "Nigeria" => Nigeria | "Niue" => Niue | "NorfolkIsland" => NorfolkIsland | "NorthernMarianaIslands" => NorthernMarianaIslands | "Norway" => Norway | "Oman" => Oman | "Pakistan" => Pakistan | "Palau" => Palau | "PalestineState" => PalestineState | "Panama" => Panama | "PapuaNewGuinea" => PapuaNewGuinea | "Paraguay" => Paraguay | "Peru" => Peru | "Philippines" => Philippines | "Pitcairn" => Pitcairn | "Poland" => Poland | "Portugal" => Portugal | "PuertoRico" => PuertoRico | "Qatar" => Qatar | "Reunion" => Reunion | "Romania" => Romania | "RussianFederation" => RussianFederation | "Rwanda" => Rwanda | "SaintBarthelemy" => SaintBarthelemy | "SaintHelenaAscensionAndTristandaCunha" => SaintHelenaAscensionAndTristandaCunha | "SaintKittsAndNevis" => SaintKittsAndNevis | "SaintLucia" => SaintLucia | "SaintMartinFrenchpart" => SaintMartinFrenchpart | "SaintPierreAndMiquelon" => SaintPierreAndMiquelon | "SaintVincentAndTheGrenadines" => SaintVincentAndTheGrenadines | "Samoa" => Samoa | "SanMarino" => SanMarino | "SaoTomeAndPrincipe" => SaoTomeAndPrincipe | "SaudiArabia" => SaudiArabia | "Senegal" => Senegal | "Serbia" => Serbia | "Seychelles" => Seychelles | "SierraLeone" => SierraLeone | "Singapore" => Singapore | "SintMaartenDutchpart" => SintMaartenDutchpart | "Slovakia" => Slovakia | "Slovenia" => Slovenia | "SolomonIslands" => SolomonIslands | "Somalia" => Somalia | "SouthAfrica" => SouthAfrica | "SouthGeorgiaAndTheSouthSandwichIslands" => SouthGeorgiaAndTheSouthSandwichIslands | "SouthSudan" => SouthSudan | "Spain" => Spain | "SriLanka" => SriLanka | "Sudan" => Sudan | "Suriname" => Suriname | "SvalbardAndJanMayen" => SvalbardAndJanMayen | "Swaziland" => Swaziland | "Sweden" => Sweden | "Switzerland" => Switzerland | "SyrianArabRepublic" => SyrianArabRepublic | "TaiwanProvinceOfChina" => TaiwanProvinceOfChina | "Tajikistan" => Tajikistan | "TanzaniaUnitedRepublic" => TanzaniaUnitedRepublic | "Thailand" => Thailand | "TimorLeste" => TimorLeste | "Togo" => Togo | "Tokelau" => Tokelau | "Tonga" => Tonga | "TrinidadAndTobago" => TrinidadAndTobago | "Tunisia" => Tunisia | "Turkey" => Turkey | "Turkmenistan" => Turkmenistan | "TurksAndCaicosIslands" => TurksAndCaicosIslands | "Tuvalu" => Tuvalu | "Uganda" => Uganda | "Ukraine" => Ukraine | "UnitedArabEmirates" => UnitedArabEmirates | "UnitedKingdomOfGreatBritainAndNorthernIreland" => UnitedKingdomOfGreatBritainAndNorthernIreland | "UnitedStatesOfAmerica" => UnitedStatesOfAmerica | "UnitedStatesMinorOutlyingIslands" => UnitedStatesMinorOutlyingIslands | "Uruguay" => Uruguay | "Uzbekistan" => Uzbekistan | "Vanuatu" => Vanuatu | "VenezuelaBolivarianRepublic" => VenezuelaBolivarianRepublic | "Vietnam" => Vietnam | "VirginIslandsBritish" => VirginIslandsBritish | "VirginIslandsUS" => VirginIslandsUS | "WallisAndFutuna" => WallisAndFutuna | "WesternSahara" => WesternSahara | "Yemen" => Yemen | "Zambia" => Zambia | "Zimbabwe" => Zimbabwe | _ => UnitedStatesOfAmerica } } let getCountryCodeFromString = code => { switch code { | "AF" => AF | "AX" => AX | "AL" => AL | "DZ" => DZ | "AS" => AS | "AD" => AD | "AO" => AO | "AI" => AI | "AQ" => AQ | "AG" => AG | "AR" => AR | "AM" => AM | "AW" => AW | "AU" => AU | "AT" => AT | "AZ" => AZ | "BS" => BS | "BH" => BH | "BD" => BD | "BB" => BB | "BY" => BY | "BE" => BE | "BZ" => BZ | "BJ" => BJ | "BM" => BM | "BT" => BT | "BO" => BO | "BQ" => BQ | "BA" => BA | "BW" => BW | "BV" => BV | "BR" => BR | "IO" => IO | "BN" => BN | "BG" => BG | "BF" => BF | "BI" => BI | "CV" => CV | "KH" => KH | "CM" => CM | "CA" => CA | "KY" => KY | "CF" => CF | "TD" => TD | "CL" => CL | "CN" => CN | "CX" => CX | "CC" => CC | "CO" => CO | "KM" => KM | "CG" => CG | "CD" => CD | "CK" => CK | "CR" => CR | "CI" => CI | "HR" => HR | "CU" => CU | "CW" => CW | "CY" => CY | "CZ" => CZ | "DK" => DK | "DJ" => DJ | "DM" => DM | "DO" => DO | "EC" => EC | "EG" => EG | "SV" => SV | "GQ" => GQ | "ER" => ER | "EE" => EE | "ET" => ET | "FK" => FK | "FO" => FO | "FJ" => FJ | "FI" => FI | "FR" => FR | "GF" => GF | "PF" => PF | "TF" => TF | "GA" => GA | "GM" => GM | "GE" => GE | "DE" => DE | "GH" => GH | "GI" => GI | "GR" => GR | "GL" => GL | "GD" => GD | "GP" => GP | "GU" => GU | "GT" => GT | "GG" => GG | "GN" => GN | "GW" => GW | "GY" => GY | "HT" => HT | "HM" => HM | "VA" => VA | "HN" => HN | "HK" => HK | "HU" => HU | "IS" => IS | "IN" => IN | "ID" => ID | "IR" => IR | "IQ" => IQ | "IE" => IE | "IM" => IM | "IL" => IL | "IT" => IT | "JM" => JM | "JP" => JP | "JE" => JE | "JO" => JO | "KZ" => KZ | "KE" => KE | "KI" => KI | "KP" => KP | "KR" => KR | "KW" => KW | "KG" => KG | "LA" => LA | "LV" => LV | "LB" => LB | "LS" => LS | "LR" => LR | "LY" => LY | "LI" => LI | "LT" => LT | "LU" => LU | "MO" => MO | "MK" => MK | "MG" => MG | "MW" => MW | "MY" => MY | "MV" => MV | "ML" => ML | "MT" => MT | "MH" => MH | "MQ" => MQ | "MR" => MR | "MU" => MU | "YT" => YT | "MX" => MX | "FM" => FM | "MD" => MD | "MC" => MC | "MN" => MN | "ME" => ME | "MS" => MS | "MA" => MA | "MZ" => MZ | "MM" => MM | "NA" => NA | "NR" => NR | "NP" => NP | "NL" => NL | "NC" => NC | "NZ" => NZ | "NI" => NI | "NE" => NE | "NG" => NG | "NU" => NU | "NF" => NF | "MP" => MP | "NO" => NO | "OM" => OM | "PK" => PK | "PW" => PW | "PS" => PS | "PA" => PA | "PG" => PG | "PY" => PY | "PE" => PE | "PH" => PH | "PN" => PN | "PL" => PL | "PT" => PT | "PR" => PR | "QA" => QA | "RE" => RE | "RO" => RO | "RU" => RU | "RW" => RW | "BL" => BL | "SH" => SH | "KN" => KN | "LC" => LC | "MF" => MF | "PM" => PM | "VC" => VC | "WS" => WS | "SM" => SM | "ST" => ST | "SA" => SA | "SN" => SN | "RS" => RS | "SC" => SC | "SL" => SL | "SG" => SG | "SX" => SX | "SK" => SK | "SI" => SI | "SB" => SB | "SO" => SO | "ZA" => ZA | "GS" => GS | "SS" => SS | "ES" => ES | "LK" => LK | "SD" => SD | "SR" => SR | "SJ" => SJ | "SZ" => SZ | "SE" => SE | "CH" => CH | "SY" => SY | "TW" => TW | "TJ" => TJ | "TZ" => TZ | "TH" => TH | "TL" => TL | "TG" => TG | "TK" => TK | "TO" => TO | "TT" => TT | "TN" => TN | "TR" => TR | "TM" => TM | "TC" => TC | "TV" => TV | "UG" => UG | "UA" => UA | "AE" => AE | "GB" => GB | "US" => US | "UM" => UM | "UY" => UY | "UZ" => UZ | "VU" => VU | "VE" => VE | "VN" => VN | "VG" => VG | "VI" => VI | "WF" => WF | "EH" => EH | "YE" => YE | "ZM" => ZM | "ZW" => ZW | _ => US } } let splitCountryNameWithSpace = countryName => { countryName->getCountryNameFromVarient->LogicUtils.camelCaseToTitle } let getCountryOption: countries => SelectBox.dropdownOption = countryType => { let countryName = countryType->splitCountryNameWithSpace let countryCode = countryType->getCountryCodeFromCountry->getCountryCodeStringFromVarient {label: countryName, value: countryCode} }
16,889
9,952
hyperswitch-control-center
src/utils/IframeUtils.res
.res
@val external document: 'a = "document" type window type parent @val external window: window = "window" @val @scope("window") external iframeParent: parent = "parent" type event = {data: string} @get external contentWindow: Dom.element => Dom.element = "contentWindow" @send external postMessageToParent: (parent, JSON.t, string) => unit = "postMessage" let handlePostMessage = (~targetOrigin="*", messageArr) => { iframeParent->postMessageToParent(messageArr->Dict.fromArray->JSON.Encode.object, targetOrigin) } @send external postMessageToChildren: (Dom.element, string, string) => unit = "postMessage" let sendPostMessage = (element, message, ~targetOrigin="*") => { element->postMessageToChildren(message->JSON.Encode.object->JSON.stringify, targetOrigin) } let iframePostMessage = (iframeRef: Dom.element, message) => { iframeRef ->contentWindow ->sendPostMessage(message) }
223
9,953
hyperswitch-control-center
src/utils/TimeZoneUtils.res
.res
let getUserTimeZoneString = () => { Date.make()->Js.Date.toTimeString->String.split(" ")->Array.get(1)->Option.getOr("") } let getUserTimeZone = () => { open UserTimeZoneTypes let userTimeZone = getUserTimeZoneString() switch userTimeZone { | "GMT+0000" => GMT | "GMT+0300" => EAT | "GMT+0100" => CET | "GMT+0200" => CAT | "GMT-0900" => HDT | "GMT-0800" => AKDT | "GMT-0400" => AST | "GMT-0500" => EST | "GMT-0600" => CST | "GMT-0700" => MST | "GMT-0300" => ADT | "GMT-0230" => NDT | "GMT+1000" => AEST | "GMT+1200" => NZST | "GMT+0800" => HKT | "GMT+0700" => WIB | "GMT+0900" => WIT | "GMT+0500" => PKT | "GMT+0530" => IST | "GMT+0930" => ACST | "GMT-1000" => HST | "GMT-1100" => SST | _ => UTC } }
367
9,954
hyperswitch-control-center
src/utils/PromiseUtils.res
.res
// Pollyfill for Promise.allSettled() // Promise.allSettled() takes an iterable of promises and returns a single promise that is fulfilled with an array of promise settlement result let allSettledPolyfill = (arr: array<promise<JSON.t>>) => { arr ->Array.map(promise => promise ->Promise.then(val => { Promise.resolve(val) }) ->Promise.catch(err => { switch err { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") err->JSON.Encode.string | _ => JSON.Encode.null }->Promise.resolve }) ) ->Promise.all }
152
9,955
hyperswitch-control-center
src/utils/TimeZoneConversion.res
.res
type timeZoneObject = {timeZone: string} @send external toLocaleString: (Date.t, string, timeZoneObject) => string = "toLocaleString" type dateTime = { year: float, month: float, date: float, hour: float, minute: float, second: float, } let timezoneOffset = Dict.fromArray([("IST", "+05:30"), ("GMT", "+00:00")]) let timezoneLocation = Dict.fromArray([("IST", "Asia/Kolkata"), ("GMT", "UTC")]) let formatter = str => { String.length(str) == 0 ? "00" : String.length(str) == 1 ? `0${str}` : str } let convertTimeZone = (date, timezoneString) => { let localTimeString = Date.fromString(date) toLocaleString(localTimeString, "en-US", {timeZone: timezoneString}) } let isoStringToCustomTimezone = isoString => { let timezone = "IST" let timezoneString = switch Dict.get(timezoneLocation, timezone) { | Some(d) => d | None => "Asia/Kolkata" } let timezoneConvertedString = convertTimeZone(isoString, timezoneString) let timezoneConverted = Date.fromString(timezoneConvertedString) let timeZoneYear = Js.Date.getFullYear(timezoneConverted) let timeZoneMonth = Js.Date.getMonth(timezoneConverted) let timeZoneDate = Js.Date.getDate(timezoneConverted) let timeZoneHour = Js.Date.getHours(timezoneConverted) let timeZoneMinute = Js.Date.getMinutes(timezoneConverted) let timeZoneSecond = Js.Date.getSeconds(timezoneConverted) let customDateTime: dateTime = { year: timeZoneYear, month: timeZoneMonth, date: timeZoneDate, hour: timeZoneHour, minute: timeZoneMinute, second: timeZoneSecond, } customDateTime }
400
9,956
hyperswitch-control-center
src/utils/AnalyticsTypesUtils.res
.res
type dataState<'a> = Loaded('a) | Loading | LoadedError type metricsType = | Latency | Volume | Rate | Amount | NegativeRate type timeObj = { apiStartTime: float, apiEndTime: float, }
61
9,957
hyperswitch-control-center
src/utils/UserPrefUtils.res
.res
open LogicUtils type moduleVisePref = { searchParams?: string, moduleConfig?: Dict.t<JSON.t>, // we store array of string here } type userPref = { lastVisitedTab?: string, moduleVisePref?: Dict.t<moduleVisePref>, } external userPrefToJson: userPref => JSON.t = "%identity" // DO NOT CHANGE THE KEYS let userPreferenceKeyInLocalStorage = "userPreferences" let lastVisitedTabKey = "lastVisitedTab" let moduleWisePrefKey = "moduleVisePref" let moduleConfig = "moduleConfig" let urlKey = "searchParams" let convertToModuleVisePref = json => { let dict = json->LogicUtils.getDictFromJsonObject dict ->Dict.keysToArray ->Array.map(key => { let jsonForTheDict = dict->LogicUtils.getDictfromDict(key) let value = { searchParams: jsonForTheDict->LogicUtils.getString(urlKey, ""), moduleConfig: jsonForTheDict ->LogicUtils.getJsonObjectFromDict(moduleConfig) ->LogicUtils.getDictFromJsonObject, } (key, value) }) ->Dict.fromArray } let converToUserPref = dict => { dict ->Dict.keysToArray ->Array.map(key => { let jsonForTheDict = dict->LogicUtils.getDictfromDict(key) let value = { lastVisitedTab: getString(jsonForTheDict, lastVisitedTabKey, ""), moduleVisePref: getJsonObjectFromDict( jsonForTheDict, moduleWisePrefKey, )->convertToModuleVisePref, } (key, value) }) ->Dict.fromArray } // this will be changed to api call on every change to url this save will happen let saveUserPref = (userPref: Dict.t<userPref>) => { LocalStorage.setItem( userPreferenceKeyInLocalStorage, userPref ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->userPrefToJson) }) ->LogicUtils.getJsonFromArrayOfJson ->JSON.stringify, ) } // this will be changed to api call for updatedUserPref the call will happen only once in initialLoad and we will store it in context let getUserPref = () => { switch LocalStorage.getItem(userPreferenceKeyInLocalStorage)->Nullable.toOption { | Some(str) => str->LogicUtils.safeParse->JSON.Decode.object->Option.getOr(Dict.make())->converToUserPref | None => Dict.make() } } let getSearchParams = (moduleWisePref: Dict.t<moduleVisePref>, ~key: string) => { switch moduleWisePref->Dict.get(key)->Option.getOr({}) { | {searchParams} => searchParams | _ => "" } }
629
9,958
hyperswitch-control-center
src/utils/RenderIf.res
.res
@react.component let make = (~condition, ~children) => { if condition { children } else { React.null } }
33
9,959
hyperswitch-control-center
src/utils/LogicUtils.res
.res
let isEmptyString = str => str->String.length === 0 let isNonEmptyString = str => str->String.length > 0 let methodStr = (method: Fetch.requestMethod) => { switch method { | Get => "GET" | Head => "HEAD" | Post => "POST" | Put => "PUT" | Delete => "DELETE" | Connect => "CONNECT" | Options => "OPTIONS" | Trace => "TRACE" | Patch => "PATCH" | _ => "" } } let useUrlPrefix = () => { "" } let stripV4 = path => { switch path { | list{"v4", ...remaining} => remaining | _ => path } } // parse a string into json and return optional json let safeParseOpt = st => { try { Some(JSON.parseExn(st)) } catch { | _ => None } } // parse a string into json and return json with null default let safeParse = st => { safeParseOpt(st)->Option.getOr(JSON.Encode.null) } let getDictFromJsonObject = json => { switch json->JSON.Decode.object { | Some(dict) => dict | None => Dict.make() } } let convertMapObjectToDict = (genericTypeMapVal: JSON.t) => { try { open MapTypes let map = create(genericTypeMapVal) let mapIterator = map.entries() let dict = object.fromEntries(mapIterator)->getDictFromJsonObject dict } catch { | _ => Dict.make() } } let removeDuplicate = (arr: array<string>) => { arr->Array.filterWithIndex((item, i) => { arr->Array.indexOf(item) === i }) } let sortBasedOnPriority = (sortArr: array<string>, priorityArr: array<string>) => { let finalPriorityArr = priorityArr->Array.filter(val => sortArr->Array.includes(val)) let filteredArr = sortArr->Array.filter(item => !(finalPriorityArr->Array.includes(item))) finalPriorityArr->Array.concat(filteredArr) } let toCamelCase = str => { let strArr = str->String.replaceRegExp(%re("/[-_]+/g"), " ")->String.split(" ") strArr ->Array.mapWithIndex((item, i) => { let matchFn = (match, _, _, _, _, _) => { if i == 0 { match->String.toLocaleLowerCase } else { match->String.toLocaleUpperCase } } item->Js.String2.unsafeReplaceBy3(%re("/(?:^\w|[A-Z]|\b\w)/g"), matchFn) }) ->Array.joinWith("") } let toKebabCase = str => { let strArr = str->String.replaceRegExp(%re("/[-_]+/g"), " ")->String.split(" ") strArr ->Array.map(item => { item->String.toLocaleLowerCase }) ->Array.joinWith("-") } let kebabToSnakeCase = str => { let strArr = str->String.replaceRegExp(%re("/[-_]+/g"), " ")->String.split(" ") strArr ->Array.map(item => { item->String.toLocaleLowerCase }) ->Array.joinWith("_") } let getNameFromEmail = email => { email ->String.split("@") ->Array.get(0) ->Option.getOr("") ->String.split(".") ->Array.map(name => { if name->isEmptyString { name } else { name->String.get(0)->Option.getOr("")->String.toUpperCase ++ name->String.sliceToEnd(~start=1) } }) ->Array.joinWith(" ") } let getOptionString = (dict, key) => { dict->Dict.get(key)->Option.flatMap(obj => obj->JSON.Decode.string) } let getString = (dict, key, default) => { getOptionString(dict, key)->Option.getOr(default) } let getStringFromJson = (json: JSON.t, default) => { json->JSON.Decode.string->Option.getOr(default) } let getBoolFromJson = (json, defaultValue) => { json->JSON.Decode.bool->Option.getOr(defaultValue) } let getArrayFromJson = (json: JSON.t, default) => { json->JSON.Decode.array->Option.getOr(default) } let getOptionalArrayFromDict = (dict, key) => { dict->Dict.get(key)->Option.flatMap(obj => obj->JSON.Decode.array) } let getArrayFromDict = (dict, key, default) => { dict->getOptionalArrayFromDict(key)->Option.getOr(default) } let getArrayDataFromJson = (json, itemToObjMapper) => { json ->JSON.Decode.array ->Option.getOr([]) ->Belt.Array.keepMap(JSON.Decode.object) ->Array.map(itemToObjMapper) } let getStrArray = (dict, key) => { dict ->getOptionalArrayFromDict(key) ->Option.getOr([]) ->Array.map(json => json->JSON.Decode.string->Option.getOr("")) } let getStrArrayFromJsonArray = jsonArr => { jsonArr->Belt.Array.keepMap(JSON.Decode.string) } let getStrArryFromJson = arr => { arr->JSON.Decode.array->Option.map(getStrArrayFromJsonArray)->Option.getOr([]) } let getOptionStrArrayFromJson = json => { json->JSON.Decode.array->Option.map(getStrArrayFromJsonArray) } let getStrArrayFromDict = (dict, key, default) => { dict->Dict.get(key)->Option.flatMap(val => val->getOptionStrArrayFromJson)->Option.getOr(default) } let getOptionStrArrayFromDict = (dict, key) => { dict->Dict.get(key)->Option.flatMap(val => val->getOptionStrArrayFromJson) } let getNonEmptyString = str => { if str->isEmptyString { None } else { Some(str) } } let getNonEmptyArray = arr => { if arr->Array.length === 0 { None } else { Some(arr) } } let getOptionBool = (dict, key) => { dict->Dict.get(key)->Option.flatMap(obj => obj->JSON.Decode.bool) } let getBool = (dict, key, default) => { getOptionBool(dict, key)->Option.getOr(default) } let getJsonObjectFromDict = (dict, key) => { dict->Dict.get(key)->Option.getOr(JSON.Encode.object(Dict.make())) } let getvalFromDict = (dict, key) => { dict->Dict.get(key) } let getBoolFromString = (boolString, default: bool) => { switch boolString->String.toLowerCase { | "true" => true | "false" => false | _ => default } } let getStringFromBool = boolValue => { switch boolValue { | true => "true" | false => "false" } } let getIntFromString = (str, default) => { switch str->Int.fromString { | Some(int) => int | None => default } } let getOptionIntFromString = str => { str->Int.fromString } let getOptionFloatFromString = str => { str->Float.fromString } let getFloatFromString = (str, default) => { switch str->Float.fromString { | Some(floatVal) => floatVal | None => default } } let getIntFromJson = (json, default) => { switch json->JSON.Classify.classify { | String(str) => getIntFromString(str, default) | Number(floatValue) => floatValue->Float.toInt | _ => default } } let getOptionIntFromJson = json => { switch json->JSON.Classify.classify { | String(str) => getOptionIntFromString(str) | Number(floatValue) => Some(floatValue->Float.toInt) | _ => None } } let getOptionFloatFromJson = json => { switch json->JSON.Classify.classify { | String(str) => getOptionFloatFromString(str) | Number(floatValue) => Some(floatValue) | _ => None } } let getFloatFromJson = (json, default) => { switch json->JSON.Classify.classify { | String(str) => getFloatFromString(str, default) | Number(floatValue) => floatValue | _ => default } } let getInt = (dict, key, default) => { switch Dict.get(dict, key) { | Some(value) => getIntFromJson(value, default) | None => default } } let getOptionInt = (dict, key) => { switch Dict.get(dict, key) { | Some(value) => getOptionIntFromJson(value) | None => None } } let getOptionFloat = (dict, key) => { switch Dict.get(dict, key) { | Some(value) => getOptionFloatFromJson(value) | None => None } } let getFloat = (dict, key, default) => { dict->Dict.get(key)->Option.map(json => getFloatFromJson(json, default))->Option.getOr(default) } let getObj = (dict, key, default) => { dict->Dict.get(key)->Option.flatMap(obj => obj->JSON.Decode.object)->Option.getOr(default) } let getDictFromUrlSearchParams = searchParams => { searchParams ->String.split("&") ->Belt.Array.keepMap(getNonEmptyString) ->Belt.Array.keepMap(keyVal => { let splitArray = String.split(keyVal, "=") switch (splitArray->Array.get(0), splitArray->Array.get(1)) { | (Some(key), Some(val)) => Some(key, val) | _ => None } }) ->Dict.fromArray } let setDictNull = (dict, key, optionStr) => { switch optionStr { | Some(str) => dict->Dict.set(key, str->JSON.Encode.string) | None => dict->Dict.set(key, JSON.Encode.null) } } let setOptionString = (dict, key, optionStr) => optionStr->Option.mapOr((), str => dict->Dict.set(key, str->JSON.Encode.string)) let setOptionJson = (dict, key, optionJson) => optionJson->Option.mapOr((), json => dict->Dict.set(key, json)) let setOptionBool = (dict, key, optionInt) => optionInt->Option.mapOr((), bool => dict->Dict.set(key, bool->JSON.Encode.bool)) let setOptionArray = (dict, key, optionArray) => optionArray->Option.mapOr((), array => dict->Dict.set(key, array->JSON.Encode.array)) let setOptionDict = (dict, key, optionDictValue) => optionDictValue->Option.mapOr((), value => dict->Dict.set(key, value->JSON.Encode.object)) let setOptionInt = (dict, key, optionInt) => optionInt->Option.mapOr((), int => dict->Dict.set(key, int->JSON.Encode.int)) let mapOptionOrDefault = (t, defaultVal, func) => t->Option.mapOr(defaultVal, value => value->func) let capitalizeString = str => { String.toUpperCase(String.charAt(str, 0)) ++ Js.String2.substringToEnd(str, ~from=1) } let snakeToCamel = str => { str ->String.split("_") ->Array.mapWithIndex((x, i) => i == 0 ? x : capitalizeString(x)) ->Array.joinWith("") } let camelToSnake = str => { str ->capitalizeString ->String.replaceRegExp(%re("/([a-z0-9A-Z])([A-Z])/g"), "$1_$2") ->String.toLowerCase } let userNameToTitle = str => str->String.split(".")->Array.map(capitalizeString)->Array.joinWith(" ") let camelCaseToTitle = str => { str->capitalizeString->String.replaceRegExp(%re("/([a-z0-9A-Z])([A-Z])/g"), "$1 $2") } let isContainingStringLowercase = (text, searchStr) => { text->String.toLowerCase->String.includes(searchStr->String.toLowerCase) } let snakeToTitle = str => { str ->String.split("_") ->Array.map(x => { let first = x->String.charAt(0)->String.toUpperCase let second = x->Js.String2.substringToEnd(~from=1) first ++ second }) ->Array.joinWith(" ") } let titleToSnake = str => { str->String.split(" ")->Array.map(String.toLowerCase)->Array.joinWith("_") } let getIntFromString = (str, default) => { str->Int.fromString->Option.getOr(default) } let removeTrailingZero = (numeric_str: string) => { numeric_str->Float.fromString->Option.getOr(0.)->Float.toString } let shortNum = ( ~labelValue: float, ~numberFormat: CurrencyFormatUtils.currencyFormat, ~presision: int=2, ) => { open CurrencyFormatUtils let value = Math.abs(labelValue) switch numberFormat { | IND => switch value { | v if v >= 1.0e+7 => `${Float.toFixedWithPrecision(v /. 1.0e+7, ~digits=presision)->removeTrailingZero}Cr` | v if v >= 1.0e+5 => `${Float.toFixedWithPrecision(v /. 1.0e+5, ~digits=presision)->removeTrailingZero}L` | v if v >= 1.0e+3 => `${Float.toFixedWithPrecision(v /. 1.0e+3, ~digits=presision)->removeTrailingZero}K` | _ => Float.toFixedWithPrecision(labelValue, ~digits=presision)->removeTrailingZero } | USD | DefaultConvert => switch value { | v if v >= 1.0e+9 => `${Float.toFixedWithPrecision(v /. 1.0e+9, ~digits=presision)->removeTrailingZero}B` | v if v >= 1.0e+6 => `${Float.toFixedWithPrecision(v /. 1.0e+6, ~digits=presision)->removeTrailingZero}M` | v if v >= 1.0e+3 => `${Float.toFixedWithPrecision(v /. 1.0e+3, ~digits=presision)->removeTrailingZero}K` | _ => Float.toFixedWithPrecision(labelValue, ~digits=presision)->removeTrailingZero } } } let latencyShortNum = (~labelValue: float, ~includeMilliseconds=?) => { if labelValue !== 0.0 { let value = Int.fromFloat(labelValue) let value_days = value / 86400 let years = value_days / 365 let months = mod(value_days, 365) / 30 let days = mod(mod(value_days, 365), 30) let hours = value / 3600 let minutes = mod(value, 3600) / 60 let seconds = mod(mod(value, 3600), 60) let year_disp = if years >= 1 { `${String.make(years)}Y ` } else { "" } let month_disp = if months > 0 { `${String.make(months)}M ` } else { "" } let day_disp = if days > 0 { `${String.make(days)}D ` } else { "" } let hr_disp = if hours > 0 { `${String.make(hours)}H ` } else { "" } let min_disp = if minutes > 0 { `${String.make(minutes)}M ` } else { "" } let millisec_disp = if ( (labelValue < 1.0 || (includeMilliseconds->Option.getOr(false) && labelValue < 60.0)) && labelValue > 0.0 ) { `.${String.make(mod((labelValue *. 1000.0)->Int.fromFloat, 1000))}` } else { "" } let sec_disp = if seconds > 0 || millisec_disp->isNonEmptyString { `${String.make(seconds)}${millisec_disp}S ` } else { "" } if days > 0 { year_disp ++ month_disp ++ day_disp } else { year_disp ++ month_disp ++ day_disp ++ hr_disp ++ min_disp ++ sec_disp } } else { "0" } } let checkEmptyJson = json => { json == JSON.Encode.object(Dict.make()) } let numericArraySortComperator = (a, b) => { if a < b { -1. } else if a > b { 1. } else { 0. } } let isEmptyDict = dict => { dict->Dict.keysToArray->Array.length === 0 } let isNullJson = val => { val == JSON.Encode.null || checkEmptyJson(val) } let stringReplaceAll = (str, old, new) => { str->String.split(old)->Array.joinWith(new) } let getUniqueArray = (arr: array<'t>) => { arr->Array.map(item => (item, ""))->Dict.fromArray->Dict.keysToArray } let getFirstLetterCaps = (str, ~splitBy="-") => { str ->String.toLowerCase ->String.split(splitBy) ->Array.map(capitalizeString) ->Array.joinWith(" ") } let getDictfromDict = (dict, key) => { dict->getJsonObjectFromDict(key)->getDictFromJsonObject } let checkLeapYear = year => (mod(year, 4) === 0 && mod(year, 100) !== 0) || mod(year, 400) === 0 let getValueFromArray = (arr, index, default) => arr->Array.get(index)->Option.getOr(default) let isEqualStringArr = (arr1, arr2) => { let arr1 = arr1->getUniqueArray let arr2 = arr2->getUniqueArray let lengthEqual = arr1->Array.length === arr2->Array.length let isContainsAll = arr1->Array.reduce(true, (acc, str) => { arr2->Array.includes(str) && acc }) lengthEqual && isContainsAll } let getDefaultNumberFormat = _ => { open CurrencyFormatUtils USD } let indianShortNum = labelValue => { shortNum(~labelValue, ~numberFormat=getDefaultNumberFormat()) } let convertNewLineSaperatedDataToArrayOfJson = text => { text ->String.split("\n") ->Array.filter(item => item->isNonEmptyString) ->Array.map(item => { item->safeParse }) } let getTypeValue = value => { switch value { | "all_currencies" => #all_currencies | _ => #none } } let formatCurrency = currency => { switch currency->getTypeValue { | #all_currencies => "USD*" | _ => currency->String.toUpperCase } } let formatAmount = (amount, currency) => { let rec addCommas = str => { let len = String.length(str) if len <= 3 { str } else { let prefix = String.slice(~start=0, ~end=len - 3, str) let suffix = String.slice(~start=len - 3, ~end=len, str) addCommas(prefix) ++ "," ++ suffix } } `${currency} ${addCommas(amount->Int.toString)}` } let valueFormatter = (value, statType: LogicUtilsTypes.valueType, ~currency="", ~suffix="") => { let amountSuffix = currency->formatCurrency let percentFormat = value => { `${Float.toFixedWithPrecision(value, ~digits=2)}%` } switch statType { | Amount => `${value->indianShortNum} ${amountSuffix}` | AmountWithSuffix => `${currency} ${value->Float.toString}${suffix}` | Rate => value->Js.Float.isNaN ? "-" : value->percentFormat | Volume => value->indianShortNum | Latency => latencyShortNum(~labelValue=value) | LatencyMs => latencyShortNum(~labelValue=value, ~includeMilliseconds=true) | FormattedAmount => formatAmount(value->Float.toInt, currency) | Default => value->Float.toString } } let getObjectArrayFromJson = json => { json->getArrayFromJson([])->Array.map(getDictFromJsonObject) } let getListHead = (~default="", list) => { list->List.head->Option.getOr(default) } let dataMerge = (~dataArr: array<array<JSON.t>>, ~dictKey: array<string>) => { let finalData = Dict.make() dataArr->Array.forEach(jsonArr => { jsonArr->Array.forEach(jsonObj => { let dict = jsonObj->getDictFromJsonObject let dictKey = dictKey ->Array.map( ele => { dict->getString(ele, "") }, ) ->Array.joinWith("-") let existingData = finalData->getObj(dictKey, Dict.make())->Dict.toArray let data = dict->Dict.toArray finalData->Dict.set( dictKey, existingData->Array.concat(data)->Dict.fromArray->JSON.Encode.object, ) }) }) finalData->Dict.valuesToArray } let getJsonFromStr = data => { if data->isNonEmptyString { JSON.stringifyWithIndent(safeParse(data), 2) } else { data } } let compareLogic = (firstValue, secondValue) => { let temp1 = firstValue let temp2 = secondValue if temp1 == temp2 { 0. } else if temp1 > temp2 { -1. } else { 1. } } let getJsonFromArrayOfJson = arr => arr->Dict.fromArray->JSON.Encode.object let getTitle = name => { name ->String.toLowerCase ->String.split("_") ->Array.map(capitalizeString) ->Array.joinWith(" ") } // Regex to check if a string contains a substring let regex = (positionToCheckFrom, searchString) => { let searchStringNew = searchString ->String.replaceRegExp(%re("/[<>\[\]';|?*\\]/g"), "") ->String.replaceRegExp(%re("/\(/g"), "\\(") ->String.replaceRegExp(%re("/\+/g"), "\\+") ->String.replaceRegExp(%re("/\)/g"), "\\)") RegExp.fromStringWithFlags( "(.*)(" ++ positionToCheckFrom ++ "" ++ searchStringNew ++ ")(.*)", ~flags="i", ) } let checkStringStartsWithSubstring = (~itemToCheck, ~searchText) => { let isMatch = switch Js.String2.match_(itemToCheck, regex("\\b", searchText)) { | Some(_) => true | None => Js.String2.match_(itemToCheck, regex("_", searchText))->Option.isSome } isMatch && searchText->String.length > 0 } let listOfMatchedText = (text, searchText) => { switch Js.String2.match_(text, regex("\\b", searchText)) { | Some(r) => r->Array.sliceToEnd(~start=1)->Belt.Array.keepMap(x => x) | None => switch Js.String2.match_(text, regex("_", searchText)) { | Some(a) => a->Array.sliceToEnd(~start=1)->Belt.Array.keepMap(x => x) | None => [text] } } } let getJsonFromArrayOfString = arr => { arr->Array.map(ele => ele->JSON.Encode.string)->JSON.Encode.array } let truncateFileNameWithEllipses = (~fileName, ~maxTextLength) => { let lastIndex = fileName->String.lastIndexOf(".") let beforeDotFileName = fileName->String.substring(~start=0, ~end=lastIndex) let afterDotFileType = fileName->String.substringToEnd(~start=lastIndex + 1) if beforeDotFileName->String.length + afterDotFileType->String.length + 1 <= maxTextLength { fileName } else { let truncatedText = beforeDotFileName->String.slice(~start=0, ~end=maxTextLength)->String.concat("...") truncatedText ++ "." ++ afterDotFileType } } let getDaysDiffForDates = (~startDate, ~endDate) => { let startDate = startDate->Date.fromTime let endDate = endDate->Date.fromTime let daysDiff = Math.abs(endDate->Date.getTime -. startDate->Date.getTime) let noOfmiliiseconds = 1000.0 *. 60.0 *. 60.0 *. 24.0 Math.floor(daysDiff /. noOfmiliiseconds) } let getOptionalFromNullable = val => { val->Nullable.toOption } let getValFromNullableValue = (val, default) => { val->getOptionalFromNullable->Option.getOr(default) } let dateFormat = (timestamp, format) => (timestamp->DayJs.getDayJsForString).format(format) let deleteNestedKeys = (dict: Dict.t<'a>, keys: array<string>) => keys->Array.forEach(key => dict->Dict.delete(key)) let removeTrailingSlash = str => { if str->String.endsWith("/") { str->String.slice(~start=0, ~end=-1) } else { str } } let getMappedValueFromArrayOfJson = (array, itemToObjMapper) => array->Belt.Array.keepMap(JSON.Decode.object)->Array.map(itemToObjMapper) let uniqueObjectFromArrayOfObjects = (arr, keyExtractor) => { let uniqueDict = Dict.make() arr->Array.forEach(item => { let key = keyExtractor(item) Dict.set(uniqueDict, key, item) }) Dict.valuesToArray(uniqueDict) }
5,784
9,960
hyperswitch-control-center
src/utils/HyperSwitchUtils.res
.res
let getMixpanelRouteName = (pageTitle, url: RescriptReactRouter.url) => { switch (url.path, url.search) { | (list{"payments", ""}, _) | (list{"refunds", ""}, _) | (list{"disputes", ""}, _) | (list{"connectors", ""}, _) | (list{"routing", ""}, _) | (list{"settings"}, "") => `/${pageTitle}` | (list{"onboarding"}, "") => `/${pageTitle}` | (list{"payments", _}, _) => `/${pageTitle}/paymentid` | (list{"refunds", _}, _) => `/${pageTitle}/refundid` | (list{"disputes", _}, _) => `/${pageTitle}/disputeid` | (list{"connectors", "new"}, _) => `/${pageTitle}/newconnector` | (list{"connectors", _}, _) => `/${pageTitle}/updateconnector` | (list{"routing", routingType}, "") => `/${pageTitle}/${routingType}/newrouting` | (list{"routing", routingType}, _) => `/${pageTitle}/${routingType}/oldrouting` | (list{"settings"}, searchParamValue) => { let type_ = LogicUtils.getDictFromUrlSearchParams(searchParamValue)->Dict.get("type")->Option.getOr("") `/${pageTitle}/${type_}` } | (list{"onboarding"}, searchParamValue) => { let type_ = LogicUtils.getDictFromUrlSearchParams(searchParamValue)->Dict.get("type")->Option.getOr("") `/${pageTitle}/${type_}` } | _ => `/${url.path->List.toArray->Array.joinWith("/")}` } } let delay = ms => Promise.make((resolve, _) => { let _ = setTimeout(() => resolve(), ms) }) let checkIsInternalUser = roleId => { open UserManagementUtils let userType = roleId->stringToVariantMapperInternalUser userType == InternalViewOnly || userType == InternalAdmin } let checkIsTenantAdmin = roleId => { open UserManagementUtils roleId->stringToVariantMapperTenantAdmin == TenantAdmin }
474
9,961
hyperswitch-control-center
src/utils/Form.res
.res
let defaultSubmit = (_, _) => { Nullable.null->Promise.resolve } module FormBody = { @react.component let make = (~children, ~formClass, ~handleSubmit, ~submitOnEnter) => { let form = ReactFinalForm.useForm() let formRef = React.useRef(Nullable.null) React.useEffect(() => { let onKeyDown = (ev: 'a) => { let keyCode = ev->ReactEvent.Keyboard.keyCode let tagName = Document.activeElement->Webapi.Dom.Element.tagName if keyCode === 13 { let enterIsFromWithinForm = switch formRef.current->Nullable.toOption { | Some(element) => element->Webapi.Dom.Element.contains(~child=Document.activeElement) | None => false } if ( tagName !== "INPUT" && tagName !== "TEXTAREA" && ((submitOnEnter && !enterIsFromWithinForm) || enterIsFromWithinForm) ) { let _ = form.submit() } } } Window.addEventListener("keydown", onKeyDown) Some(() => Window.removeEventListener("keydown", onKeyDown)) }, []) <form onSubmit={handleSubmit} className={formClass} ref={formRef->ReactDOM.Ref.domRef}> {children} </form> } } @react.component let make = ( ~children, ~onSubmit=defaultSubmit, ~initialValues=?, ~validate=?, ~formClass="", ~submitOnEnter=false, ) => { <ReactFinalForm.Form subscription=ReactFinalForm.subscribeToValues ?initialValues onSubmit ?validate render={({handleSubmit}) => <FormBody handleSubmit formClass submitOnEnter> {children} </FormBody>} /> }
377
9,962
hyperswitch-control-center
src/utils/Mappers/MerchantAccountDetailsMapper.res
.res
open HSwitchSettingTypes let getMerchantDetails = (values: JSON.t) => { open LogicUtils let valuesDict = values->getDictFromJsonObject let merchantDetails = valuesDict->getObj("merchant_details", Dict.make()) let address = merchantDetails->getObj("address", Dict.make()) let primary_business_details = valuesDict ->getArrayFromDict("primary_business_details", []) ->Array.map(detail => { let detailDict = detail->getDictFromJsonObject let info = { business: detailDict->getString("business", ""), country: detailDict->getString("country", ""), } info }) let reconStatusMapper = reconStatus => { switch reconStatus->String.toLowerCase { | "notrequested" => NotRequested | "requested" => Requested | "active" => Active | "disabled" => Disabled | _ => NotRequested } } let payload: merchantPayload = { merchant_name: valuesDict->getOptionString("merchant_name"), api_key: valuesDict->getString("api_key", ""), publishable_key: valuesDict->getString("publishable_key", ""), merchant_id: valuesDict->getString("merchant_id", valuesDict->getString("id", "")), // this need to be removed, mapper need to be separated for v2 locker_id: valuesDict->getString("locker_id", ""), primary_business_details, merchant_details: { primary_contact_person: merchantDetails->getOptionString("primary_contact_person"), primary_email: merchantDetails->getOptionString("primary_email"), primary_phone: merchantDetails->getOptionString("primary_phone"), secondary_contact_person: merchantDetails->getOptionString("secondary_contact_person"), secondary_email: merchantDetails->getOptionString("secondary_email"), secondary_phone: merchantDetails->getOptionString("secondary_phone"), website: merchantDetails->getOptionString("website"), about_business: merchantDetails->getOptionString("about_business"), address: { line1: address->getOptionString("line1"), line2: address->getOptionString("line2"), line3: address->getOptionString("line3"), city: address->getOptionString("city"), state: address->getOptionString("state"), zip: address->getOptionString("zip"), }, }, enable_payment_response_hash: getBool(valuesDict, "enable_payment_response_hash", false), sub_merchants_enabled: getBool(valuesDict, "sub_merchants_enabled", false), metadata: valuesDict->getString("metadata", ""), parent_merchant_id: valuesDict->getString("parent_merchant_id", ""), payment_response_hash_key: valuesDict->getOptionString("payment_response_hash_key"), redirect_to_merchant_with_http_post: getBool( valuesDict, "redirect_to_merchant_with_http_post", true, ), recon_status: getString(valuesDict, "recon_status", "")->reconStatusMapper, product_type: getString( valuesDict, "product_type", "", )->ProductUtils.getProductVariantFromString, } payload }
663
9,963
hyperswitch-control-center
src/utils/Mappers/GroupACLMapper.res
.res
open CommonAuthTypes open UserManagementTypes let mapGroupAccessTypeToString = groupAccessType => switch groupAccessType { | OperationsView => "operations_view" | OperationsManage => "operations_manage" | ConnectorsView => "connectors_view" | ConnectorsManage => "connectors_manage" | WorkflowsView => "workflows_view" | WorkflowsManage => "workflows_manage" | AnalyticsView => "analytics_view" | UsersView => "users_view" | UsersManage => "users_manage" | MerchantDetailsView => "merchant_details_view" | MerchantDetailsManage => "merchant_details_manage" | OrganizationManage => "organization_manage" | AccountView => "account_view" | AccountManage => "account_manage" | UnknownGroupAccess(val) => val } let mapStringToGroupAccessType = val => switch val { | "operations_view" => OperationsView | "operations_manage" => OperationsManage | "connectors_view" => ConnectorsView | "connectors_manage" => ConnectorsManage | "workflows_view" => WorkflowsView | "workflows_manage" => WorkflowsManage | "analytics_view" => AnalyticsView | "users_view" => UsersView | "users_manage" => UsersManage | "merchant_details_view" => MerchantDetailsView | "merchant_details_manage" => MerchantDetailsManage | "organization_manage" => OrganizationManage | "account_view" => AccountView | "account_manage" => AccountManage | val => UnknownGroupAccess(val) } let mapStringToResourceAccessType = val => switch val { | "payment" => Payment | "refund" => Refund | "api_key" => ApiKey | "account" => Account | "connector" => Connector | "routing" => Routing | "dispute" => Dispute | "mandate" => Mandate | "customer" => Customer | "analytics" => Analytics | "three_ds_decision_manager" => ThreeDsDecisionManager | "surcharge_decision_manager" => SurchargeDecisionManager | "user" => User | "webhook_event" => WebhookEvent | "payout" => Payout | "report" => Report | "recon_token" => ReconToken | "recon_files" => ReconFiles | "recon_and_settlement_analytics" => ReconAndSettlementAnalytics | "recon_upload" => ReconUpload | "recon_reports" => ReconReports | "run_recon" => RunRecon | "recon_config" => ReconConfig | _ => UnknownResourceAccess(val) } let defaultValueForGroupAccessJson = { operationsView: NoAccess, operationsManage: NoAccess, connectorsView: NoAccess, connectorsManage: NoAccess, workflowsView: NoAccess, workflowsManage: NoAccess, analyticsView: NoAccess, usersView: NoAccess, usersManage: NoAccess, merchantDetailsView: NoAccess, merchantDetailsManage: NoAccess, organizationManage: NoAccess, accountView: NoAccess, accountManage: NoAccess, } let getAccessValue = (~groupAccess: groupAccessType, ~groupACL) => groupACL->Array.find(ele => ele == groupAccess)->Option.isSome ? Access : NoAccess // TODO: Refactor to not call function for every group let getGroupAccessJson = groupACL => { operationsView: getAccessValue(~groupAccess=OperationsView, ~groupACL), operationsManage: getAccessValue(~groupAccess=OperationsManage, ~groupACL), connectorsView: getAccessValue(~groupAccess=ConnectorsView, ~groupACL), connectorsManage: getAccessValue(~groupAccess=ConnectorsManage, ~groupACL), workflowsView: getAccessValue(~groupAccess=WorkflowsView, ~groupACL), workflowsManage: getAccessValue(~groupAccess=WorkflowsManage, ~groupACL), analyticsView: getAccessValue(~groupAccess=AnalyticsView, ~groupACL), usersView: getAccessValue(~groupAccess=UsersView, ~groupACL), usersManage: getAccessValue(~groupAccess=UsersManage, ~groupACL), merchantDetailsView: getAccessValue(~groupAccess=MerchantDetailsView, ~groupACL), merchantDetailsManage: getAccessValue(~groupAccess=MerchantDetailsManage, ~groupACL), organizationManage: getAccessValue(~groupAccess=OrganizationManage, ~groupACL), accountView: getAccessValue(~groupAccess=AccountView, ~groupACL), accountManage: getAccessValue(~groupAccess=AccountManage, ~groupACL), } let convertValueToMapGroup = arrayValue => { let userGroupACLMap: Map.t<groupAccessType, authorization> = Map.make() arrayValue->Array.forEach(value => userGroupACLMap->Map.set(value, Access)) userGroupACLMap } let convertValueToMapResources = arrayValue => { let resourceACLMap: Map.t<resourceAccessType, authorization> = Map.make() arrayValue->Array.forEach(value => resourceACLMap->Map.set(value, Access)) resourceACLMap }
1,153
9,964
hyperswitch-control-center
src/utils/Mappers/BusinessProfileMapper.res
.res
open HSwitchSettingTypes let constructWebhookDetailsObject = webhookDetailsDict => { open LogicUtils let webhookDetails = { webhook_version: webhookDetailsDict->getOptionString("webhook_version"), webhook_username: webhookDetailsDict->getOptionString("webhook_username"), webhook_password: webhookDetailsDict->getOptionString("webhook_password"), webhook_url: webhookDetailsDict->getOptionString("webhook_url"), payment_created_enabled: webhookDetailsDict->getOptionBool("payment_created_enabled"), payment_succeeded_enabled: webhookDetailsDict->getOptionBool("payment_succeeded_enabled"), payment_failed_enabled: webhookDetailsDict->getOptionBool("payment_failed_enabled"), } webhookDetails } let constructAuthConnectorObject = authConnectorDict => { open LogicUtils let authConnectorDetails = { authentication_connectors: authConnectorDict->getOptionalArrayFromDict( "authentication_connectors", ), three_ds_requestor_url: authConnectorDict->getOptionString("three_ds_requestor_url"), three_ds_requestor_app_url: authConnectorDict->getOptionString("three_ds_requestor_app_url"), } authConnectorDetails } let businessProfileTypeMapper = values => { open LogicUtils let jsonDict = values->getDictFromJsonObject let webhookDetailsDict = jsonDict->getDictfromDict("webhook_details") let authenticationConnectorDetails = jsonDict->getDictfromDict("authentication_connector_details") let outgoingWebhookHeades = jsonDict->getDictfromDict("outgoing_webhook_custom_http_headers") let metadataKeyValue = jsonDict->getDictfromDict("metadata") { merchant_id: jsonDict->getString("merchant_id", ""), profile_id: jsonDict->getString("profile_id", ""), profile_name: jsonDict->getString("profile_name", ""), return_url: jsonDict->getOptionString("return_url"), payment_response_hash_key: jsonDict->getOptionString("payment_response_hash_key"), webhook_details: webhookDetailsDict->constructWebhookDetailsObject, authentication_connector_details: authenticationConnectorDetails->constructAuthConnectorObject, collect_shipping_details_from_wallet_connector: jsonDict->getOptionBool( "collect_shipping_details_from_wallet_connector", ), always_collect_shipping_details_from_wallet_connector: jsonDict->getOptionBool( "always_collect_shipping_details_from_wallet_connector", ), collect_billing_details_from_wallet_connector: jsonDict->getOptionBool( "collect_billing_details_from_wallet_connector", ), always_collect_billing_details_from_wallet_connector: jsonDict->getOptionBool( "always_collect_billing_details_from_wallet_connector", ), is_connector_agnostic_mit_enabled: jsonDict->getOptionBool("is_connector_agnostic_mit_enabled"), force_3ds_challenge: jsonDict->getOptionBool("force_3ds_challenge"), is_debit_routing_enabled: jsonDict->getOptionBool("is_debit_routing_enabled"), outgoing_webhook_custom_http_headers: !(outgoingWebhookHeades->isEmptyDict) ? Some(outgoingWebhookHeades) : None, metadata: metadataKeyValue->isEmptyDict ? None : Some(metadataKeyValue), is_auto_retries_enabled: jsonDict->getOptionBool("is_auto_retries_enabled"), max_auto_retries_enabled: jsonDict->getOptionInt("max_auto_retries_enabled"), is_click_to_pay_enabled: jsonDict->getOptionBool("is_click_to_pay_enabled"), authentication_product_ids: Some( jsonDict ->getDictfromDict("authentication_product_ids") ->JSON.Encode.object, ), } } let convertObjectToType = value => { value->Array.map(businessProfileTypeMapper) } let getArrayOfBusinessProfile = businessProfileValue => { open LogicUtils businessProfileValue->getArrayFromJson([])->convertObjectToType }
799
9,965
hyperswitch-control-center
src/components/TimeInput.res
.res
let padNum = num => { let str = num->Int.toString if str->String.length === 1 { `0${str}` } else { str } } module OptionVals = { @react.component let make = (~upto=60, ~value, ~onChange, ~isDisabled) => { let cursorClass = isDisabled ? "cursor-not-allowed" : "" <select value={value->Int.toString} onChange disabled=isDisabled className={`dark:bg-jp-gray-lightgray_background font-medium border border-gray-400 rounded-md self-start ${cursorClass} outline-none`}> {Array.make(~length=upto, 0) ->Array.mapWithIndex((_, i) => { <option key={Int.toString(i)} value={Int.toString(i)}> {i->padNum->React.string} </option> }) ->React.array} </select> } } @react.component let make = ( ~label=?, ~input: ReactFinalForm.fieldRenderPropsInput, ~isDisabled=false, ~icon="clock", ~position="1", ~showSeconds=true, ) => { let _ = position let _ = icon let value = switch input.value->JSON.Decode.string { | Some(str) => str | None => "" } let arr = value->String.split(":") let hourVal = arr->Array.get(0)->Option.flatMap(val => val->Belt.Int.fromString)->Option.getOr(0) let minuteVal = arr->Array.get(1)->Option.flatMap(val => val->Belt.Int.fromString)->Option.getOr(0) let secondsVal = arr->Array.get(2)->Option.flatMap(val => val->Belt.Int.fromString)->Option.getOr(0) let changeVal = React.useCallback(index => { (ev: ReactEvent.Form.t) => { let newVal = {ev->ReactEvent.Form.target}["value"]->Int.fromString->Option.getOr(0) let arr = [hourVal, minuteVal, secondsVal] arr[index] = newVal arr ->Array.map(padNum) ->Array.joinWith(":") ->Identity.anyTypeToReactEvent ->input.onChange } }, (hourVal, minuteVal, secondsVal, input.onChange)) let onHourChange = React.useCallback(changeVal(0), [changeVal]) let onMinuteChange = React.useCallback(changeVal(1), [changeVal]) let onSecondsChange = React.useCallback(changeVal(2), [changeVal]) <div className="h-8 max-w-min flex flex-row gap-1 text-sm"> {switch label { | Some(str) => <div className="font-semibold mr-1"> {React.string(str)} </div> | None => React.null }} <OptionVals value=hourVal onChange=onHourChange upto=24 isDisabled /> <div> {React.string(":")} </div> <OptionVals value=minuteVal onChange=onMinuteChange isDisabled /> {if showSeconds { <> <div> {React.string(":")} </div> <OptionVals value=secondsVal onChange=onSecondsChange isDisabled /> </> } else { React.null }} </div> }
727
9,966
hyperswitch-control-center
src/components/DynamicSingleStat.res
.res
type chartType = Default | Table type singleStatData = { title: string, tooltipText: string, deltaTooltipComponent: string => React.element, value: float, delta: float, data: array<(float, float)>, statType: string, showDelta: bool, label?: string, } type columnsType<'colType> = { colType: 'colType, chartType?: chartType, } let generateDefaultStateColumns: array<'colType> => array<columnsType<'colType>> = arr => { arr->Array.map(col => { { colType: col, } }) } type columns<'colType> = { sectionName: string, columns: array<columnsType<'colType>>, sectionInfo?: string, } type singleStatBodyEntity = { filter?: JSON.t, metrics?: array<string>, delta?: bool, startDateTime: string, endDateTime: string, granularity?: string, mode?: string, customFilter?: string, groupByNames?: array<string>, source?: string, prefix?: string, } type urlConfig = { uri: string, metrics: array<string>, prefix?: string, } type deltaRange = {currentSr: AnalyticsUtils.timeRanges} type entityType<'colType, 't, 't2> = { urlConfig: array<urlConfig>, getObjects: JSON.t => array<'t>, getTimeSeriesObject: JSON.t => array<'t2>, defaultColumns: array<columns<'colType>>, // (sectionName, defaultColumns) getData: ('t, array<'t2>, deltaRange, 'colType, string) => singleStatData, totalVolumeCol: option<string>, matrixUriMapper: 'colType => string, // metrix uriMapper will contain the ${prefix}${url} source?: string, customFilterKey?: string, enableLoaders?: bool, statSentiment?: Dict.t<AnalyticsUtils.statSentiment>, statThreshold?: Dict.t<float>, } type timeType = {startTime: string, endTime: string} // this will be removed once filter refactor is merged type singleStatDataObj<'t> = { sectionUrl: string, singleStatData: array<'t>, deltaTime: deltaRange, } let singleStatBodyMake = (singleStatBodyEntity: singleStatBodyEntity) => { [ AnalyticsUtils.getFilterRequestBody( ~filter=singleStatBodyEntity.filter, ~metrics=singleStatBodyEntity.metrics, ~delta=?singleStatBodyEntity.delta, ~startDateTime=singleStatBodyEntity.startDateTime, ~endDateTime=singleStatBodyEntity.endDateTime, ~mode=singleStatBodyEntity.mode, ~customFilter=?singleStatBodyEntity.customFilter, ~source=?singleStatBodyEntity.source, ~granularity=singleStatBodyEntity.granularity, ~prefix=singleStatBodyEntity.prefix, )->JSON.Encode.object, ] ->JSON.Encode.array ->JSON.stringify } type singleStateData<'t, 't2> = { singleStatData: option<array<singleStatDataObj<'t>>>, singleStatTimeData: option<array<(string, array<'t2>)>>, } let deltaTimeRangeMapper: array<JSON.t> => deltaRange = (arrJson: array<JSON.t>) => { open LogicUtils let emptyDict = Dict.make() let _ = arrJson->Array.map(item => { let dict = item->getDictFromJsonObject let deltaTimeRange = dict->getJsonObjectFromDict("deltaTimeRange")->getDictFromJsonObject let fromTime = deltaTimeRange->getString("startTime", "") let toTime = deltaTimeRange->getString("endTime", "") let timeRanges: AnalyticsUtils.timeRanges = {fromTime, toTime} if deltaTimeRange->Dict.toArray->Array.length > 0 { emptyDict->Dict.set("currentSr", timeRanges) } }) { currentSr: emptyDict ->Dict.get("currentSr") ->Option.getOr({ fromTime: "", toTime: "", }), } } // till here @react.component let make = ( ~entity: entityType<'colType, 't, 't2>, ~modeKey=?, ~filterKeys, ~startTimeFilterKey, ~endTimeFilterKey, ~moduleName="", ~showPercentage=true, ~chartAlignment=#column, ~isHomePage=false, ~defaultStartDate="", ~defaultEndDate="", ~filterNullVals=false, ~statSentiment=?, ~statThreshold=?, ~wrapperClass=?, ~formaPayload: option<singleStatBodyEntity => string>=?, ) => { open LogicUtils let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let {filterValueJson} = React.useContext(FilterContext.filterContext) let fetchApi = AuthHooks.useApiFetcher() let getAllFilter = filterValueJson let isMobileView = MatchMedia.useMobileChecker() let (showStats, setShowStats) = React.useState(_ => false) // without prefix only table related Filters 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 === moduleName && prefix->isNonEmptyString { None } else { Some((prefix, value)) } }) ->Dict.fromArray }, [getAllFilter]) let mode = switch modeKey { | Some(modeKey) => Some(getTopLevelFilter->getString(modeKey, "")) | None => Some("ORDER") } let source = switch entity { | {source} => source | _ => "BATCH" } let enableLoaders = entity.enableLoaders->Option.getOr(true) let customFilterKey = switch entity { | {customFilterKey} => customFilterKey | _ => "" } let allFilterKeys = Array.concat( [startTimeFilterKey, endTimeFilterKey, mode->Option.getOr("")], filterKeys, ) let deltaItemToObjMapper = json => { let metaData = json->getDictFromJsonObject->getArrayFromDict("metaData", [])->deltaTimeRangeMapper metaData } 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 filterValueFromUrl = React.useMemo(() => { getTopLevelFilter ->Dict.toArray ->Belt.Array.keepMap(entries => { let (key, value) = entries filterKeys->Array.includes(key) ? Some((key, value)) : None }) ->getJsonFromArrayOfJson ->Some }, [topFiltersToSearchParam]) let startTimeFromUrl = React.useMemo(() => { getTopLevelFilter->getString(startTimeFilterKey, defaultStartDate) }, [topFiltersToSearchParam]) let endTimeFromUrl = React.useMemo(() => { getTopLevelFilter->getString(endTimeFilterKey, defaultEndDate) }, [topFiltersToSearchParam]) let homePageCss = isHomePage || chartAlignment === #row ? "flex-col" : "flex-row" let wrapperClass = wrapperClass->Option.getOr( `flex flex-col md:${homePageCss} flex-wrap justify-start items-stretch relative h-full`, ) let (singleStatData, setSingleStatData) = React.useState(() => None) let (shimmerType, setShimmerType) = React.useState(_ => AnalyticsUtils.Shimmer) let (singleStatTimeData, setSingleStatTimeData) = React.useState(() => None) let (singleStatLoading, setSingleStatLoading) = React.useState(_ => true) let (singleStatLoadingTimeSeries, setSingleStatLoadingTimeSeries) = React.useState(_ => true) let (singlestatDataCombined, setSingleStatCombinedData) = React.useState(_ => { singleStatTimeData, singleStatData, }) React.useEffect(() => { if !(singleStatLoading || singleStatLoadingTimeSeries) { setSingleStatCombinedData(_ => { singleStatTimeData, singleStatData, }) } None }, (singleStatLoadingTimeSeries, singleStatLoading, singleStatTimeData, singleStatData)) let addLogsAroundFetch = AnalyticsLogUtilsHook.useAddLogsAroundFetch() React.useEffect(() => { if singleStatData !== None && singleStatTimeData !== None { setShimmerType(_ => SideLoader) } None }, (singleStatData, singleStatTimeData)) React.useEffect(() => { if startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString { open Promise setSingleStatLoading(_ => enableLoaders) entity.urlConfig ->Array.map(urlConfig => { let {uri, metrics} = urlConfig let domain = String.split("/", uri)->Array.get(4)->Option.getOr("") let startTime = if domain === "mandate" { (endTimeFromUrl->DayJs.getDayJsForString).subtract(1, "hour").toDate()->Date.toISOString } else { startTimeFromUrl } let getDelta = domain !== "mandate" let singleStatBodyEntity = { filter: ?filterValueFromUrl, metrics, delta: getDelta, startDateTime: startTime, endDateTime: endTimeFromUrl, ?mode, customFilter, source, prefix: ?urlConfig.prefix, } let singleStatBodyMakerFn = switch formaPayload { | Some(fun) => fun | _ => singleStatBodyMake } let singleStatBody = singleStatBodyEntity->singleStatBodyMakerFn fetchApi( uri, ~method_=Post, ~bodyStr=singleStatBody, ~headers=[("QueryType", "SingleStat")]->Dict.fromArray, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle="SingleStat Data Api") ->then(json => resolve((`${urlConfig.prefix->Option.getOr("")}${uri}`, json))) ->catch(_err => resolve(("", JSON.Encode.object(Dict.make())))) }) ->Promise.all ->Promise.thenResolve(dataArr => { let data = dataArr->Array.map( item => { let (sectionName, json) = item let data = entity.getObjects(json) let deltaTime = deltaItemToObjMapper(json) let value: singleStatDataObj<'t> = { sectionUrl: sectionName, singleStatData: data, deltaTime, } value }, ) setSingleStatData(_ => Some(data)) setSingleStatLoading(_ => false) }) ->ignore } None }, (endTimeFromUrl, startTimeFromUrl, filterValueFromUrl, customFilter, mode)) React.useEffect(() => { if startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString { setSingleStatLoadingTimeSeries(_ => enableLoaders) open Promise entity.urlConfig ->Array.map(urlConfig => { let {uri, metrics} = urlConfig let domain = String.split("/", uri)->Array.get(4)->Option.getOr("") let startTime = if domain === "mandate" { (endTimeFromUrl->DayJs.getDayJsForString).subtract(1, "hour").toDate()->Date.toISOString } else { startTimeFromUrl } let granularity = DynamicChart.getGranularity(~startTime, ~endTime=endTimeFromUrl)->Array.map( item => item->DynamicChart.getGranularityString, ) let singleStatBodyEntity = { filter: ?filterValueFromUrl, metrics, delta: false, startDateTime: startTime, endDateTime: endTimeFromUrl, granularity: ?granularity->Array.get(0), ?mode, customFilter, source, prefix: ?urlConfig.prefix, } let singleStatBodyMakerFn = switch formaPayload { | Some(fun) => fun | _ => singleStatBodyMake } fetchApi( uri, ~method_=Post, ~bodyStr=singleStatBodyMakerFn(singleStatBodyEntity), ~headers=[("QueryType", "SingleStatTimeseries")]->Dict.fromArray, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle="SingleStatTimeseries Data Api") ->then( json => { resolve((`${urlConfig.prefix->Option.getOr("")}${uri}`, json)) }, ) ->catch( _err => { resolve(("", JSON.Encode.object(Dict.make()))) }, ) }) ->Promise.all ->thenResolve(timeSeriesArr => { let data = timeSeriesArr->Array.map( item => { let (sectionName, json) = item (sectionName, entity.getTimeSeriesObject(json)) }, ) setSingleStatTimeData(_ => Some(data)) setSingleStatLoadingTimeSeries(_ => false) }) ->ignore } None }, (endTimeFromUrl, startTimeFromUrl, filterValueFromUrl, customFilter, mode)) entity.defaultColumns ->Array.mapWithIndex((urlConfig, index) => { let {columns} = urlConfig let fullWidth = {columns->Array.length == 1} let singleStateArr = columns->Array.mapWithIndex((col, singleStatArrIndex) => { let uri = col.colType->entity.matrixUriMapper let timeSeriesData = singlestatDataCombined.singleStatTimeData ->Option.getOr([("--", [])]) ->Belt.Array.keepMap( item => { let (timeSectionName, timeSeriesObj) = item timeSectionName === uri ? Some(timeSeriesObj) : None }, ) let timeSeriesData = []->Array.concatMany(timeSeriesData) switch col.chartType->Option.getOr(Default) { | Table => switch singlestatDataCombined.singleStatData { | Some(sdata) => { let sectiondata = sdata ->Array.filter( item => { item.sectionUrl === uri }, ) ->Array.get(0) let dict = [("queryData", [Dict.make()->JSON.Encode.object]->JSON.Encode.array)]->Dict.fromArray let (title, tooltipText, statType) = switch dict ->JSON.Encode.object ->entity.getObjects ->Array.get(0) { | Some(item) => let date = { currentSr: { fromTime: "", toTime: "", }, } let info = entity.getData( item, timeSeriesData, date, col.colType, mode->Option.getOr("ORDER"), ) (info.title, info.tooltipText, info.statType) | None => ("", "", "") } switch sectiondata { | Some(data) => let info = data.singleStatData->Array.map( infoData => { entity.getData( infoData, timeSeriesData, data.deltaTime, col.colType, mode->Option.getOr("ORDER"), ) }, ) let modifiedData = info->Array.map( item => { let val: HSwitchSingleStatTableWidget.tableRowType = { rowLabel: item.label->Option.getOr("NA"), rowValue: item.value, } val }, ) modifiedData->Array.sort( (a, b) => { let rowValue_a = a.rowValue let rowValue_b = b.rowValue rowValue_a <= rowValue_b ? 1. : -1. }, ) <HSwitchSingleStatTableWidget key={singleStatArrIndex->Int.toString} singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} title tooltipText loaderType=shimmerType value=modifiedData statType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment ?statThreshold fullWidth /> | None => <HSwitchSingleStatTableWidget key={singleStatArrIndex->Int.toString} deltaTooltipComponent=React.null value=[] statType="" singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment ?statThreshold fullWidth /> } } | None => <HSwitchSingleStatTableWidget key={singleStatArrIndex->Int.toString} deltaTooltipComponent=React.null value=[] statType="" singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment fullWidth /> } | _ => switch singlestatDataCombined.singleStatData { | Some(sdata) => { let sectiondata = sdata ->Array.filter( item => { item.sectionUrl === uri }, ) ->Array.get(0) switch sectiondata { | Some(data) => { let info = data.singleStatData->Array.map( infoData => { entity.getData( infoData, timeSeriesData, data.deltaTime, col.colType, mode->Option.getOr("ORDER"), ) }, ) switch info->Array.get(0) { | Some(stateData) => <HSwitchSingleStatWidget key={singleStatArrIndex->Int.toString} title=stateData.title tooltipText=stateData.tooltipText deltaTooltipComponent={stateData.deltaTooltipComponent(stateData.statType)} value=stateData.value data=stateData.data statType=stateData.statType singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} showPercentage=stateData.showDelta loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment fullWidth ?statThreshold /> | _ => <HSwitchSingleStatWidget key={singleStatArrIndex->Int.toString} title="" tooltipText="" deltaTooltipComponent=React.null value=0. data=[] statType="" singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment ?statThreshold fullWidth /> } } | None => <HSwitchSingleStatWidget key={singleStatArrIndex->Int.toString} title="" tooltipText="" deltaTooltipComponent=React.null value=0. data=[] statType="" singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment ?statThreshold fullWidth /> } } | None => <HSwitchSingleStatWidget key={singleStatArrIndex->Int.toString} title="" tooltipText="" deltaTooltipComponent=React.null value=0. data=[] statType="" singleStatLoading={singleStatLoading || singleStatLoadingTimeSeries} loaderType=shimmerType statChartColor={mod(singleStatArrIndex, 2) === 0 ? #blue : #grey} filterNullVals ?statSentiment fullWidth /> } } }) <AddDataAttributes attributes=[("data-dynamic-single-stats", "dynamic stats")] key={index->Int.toString}> <div className=wrapperClass> {if isMobileView { <div className="flex flex-col gap-2 items-center h-full"> <div className="flex flex-wrap w-full h-full"> {singleStateArr ->Array.mapWithIndex((element, index) => { <RenderIf condition={index < 4 || showStats} key={index->Int.toString}> <div className="w-full md:w-1/2"> element </div> </RenderIf> }) ->React.array} </div> <div className="w-full px-2"> <Button text={showStats ? "Hide All Stats" : "View All Stats"} onClick={_ => setShowStats(prev => !prev)} buttonType={Pagination} customButtonStyle="w-full" /> </div> </div> } else { singleStateArr->React.array }} </div> </AddDataAttributes> }) ->React.array }
4,947
9,967
hyperswitch-control-center
src/components/CustomExpandableTable.res
.res
open Table @react.component let make = ( ~title, ~heading=[], ~rows, ~offset=0, ~fullWidth=true, ~showScrollBar=false, ~setFilterObj=?, ~filterObj=?, ~onExpandIconClick, ~expandedRowIndexArray, ~getRowDetails, ~showSerial=false, ) => { if showSerial { heading->Array.unshift(makeHeaderInfo(~key="serial_number", ~title="S.No"))->ignore } let isMobileView = MatchMedia.useMobileChecker() let filterPresent = heading->Array.find(head => head.showFilter)->Option.isSome let highlightEnabledFieldsArray = heading->Array.reduceWithIndex([], (acc, item, index) => { if item.highlightCellOnHover { let _ = Array.push(acc, index) } acc }) let scrollBarClass = if showScrollBar { "show-scrollbar" } else { "" } let rowInfo: array<array<cell>> = { let a = rows->Array.mapWithIndex((data, i) => { if showSerial { data->Array.unshift(Text((i + 1)->Int.toString))->ignore } data }) a } let headingsLen = heading->Array.length let widthClass = if fullWidth { "min-w-full" } else { "" } let handleUpdateFilterObj = (ev, i) => { switch setFilterObj { | Some(fn) => fn((prevFilterObj: option<array<filterObject>>) => { prevFilterObj->Option.map(prevObj => { prevObj->Array.map( obj => { if obj.key === Int.toString(i) { { key: Int.toString(i), options: obj.options, selected: ev->Identity.formReactEventToArrayOfString, } } else { obj } }, ) }) }) | None => () } } let tableClass = "" let borderClass = "border border-jp-gray-500 dark:border-jp-gray-960 rounded" <div className={`overflow ${scrollBarClass} ${tableClass}`} //replaced "overflow-auto" -> to be tested with master style={minHeight: {filterPresent ? "30rem" : ""}}> <AddDataAttributes attributes=[("data-expandable-table", title)]> <table className={`table-auto ${widthClass} h-full ${borderClass}`} colSpan=0> <RenderIf condition={heading->Array.length !== 0 && !isMobileView}> <thead> <tr> {heading ->Array.mapWithIndex((item, i) => { let isFirstCol = i === 0 let isLastCol = i === headingsLen - 1 let oldThemeRoundedClass = if isFirstCol { "rounded-tl" } else if isLastCol { "rounded-tr" } else { "" } let roundedClass = oldThemeRoundedClass let borderClass = isLastCol ? "" : "border-jp-gray-500 dark:border-jp-gray-960" let borderClass = borderClass let bgColor = "bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950" let headerTextClass = "text-jp-gray-800 dark:text-jp-gray-text_darktheme dark:text-opacity-75" let fontWeight = "font-bold" let fontSize = "text-sm" let paddingClass = "px-4 py-3" <AddDataAttributes attributes=[("data-table-heading", item.title)] key={i->Int.toString}> <th className="p-0"> <div className={`flex flex-row ${borderClass} justify-between items-center ${paddingClass} ${bgColor} ${headerTextClass} whitespace-pre ${roundedClass}`}> <div className={`${fontWeight} ${fontSize}`}> {React.string(item.title)} </div> <RenderIf condition={item.showFilter || item.showSort}> <div className="flex flex-row items-center select-none"> {if item.showFilter { let (options, selected) = filterObj ->Option.flatMap(obj => switch obj[i] { | Some(ele) => (ele.options, ele.selected) | None => ([], []) }->Some ) ->Option.getOr(([], [])) if options->Array.length > 1 { let filterInput: ReactFinalForm.fieldRenderPropsInput = { name: "filterInput", onBlur: _ => (), onChange: ev => handleUpdateFilterObj(ev, i), onFocus: _ => (), value: selected->Array.map(JSON.Encode.string)->JSON.Encode.array, checked: true, } <SelectBox.BaseDropdown allowMultiSelect=true hideMultiSelectButtons=true buttonText="" input={filterInput} options={options->SelectBox.makeOptions} deselectDisable=false baseComponent={<Icon className="align-middle text-gray-400" name="filter" size=12 />} autoApply=false /> } else { React.null } } else { React.null }} </div> </RenderIf> </div> </th> </AddDataAttributes> }) ->React.array} </tr> </thead> </RenderIf> <tbody> {rowInfo ->Array.mapWithIndex((item: array<cell>, rowIndex) => { <CollapsableTableRow key={Int.toString(rowIndex)} item rowIndex offset highlightEnabledFieldsArray expandedRowIndexArray onExpandIconClick getRowDetails heading title /> }) ->React.array} </tbody> </table> </AddDataAttributes> </div> }
1,330
9,968
hyperswitch-control-center
src/components/DesktopView.res
.res
@react.component let make = (~children) => { let isMobileView = MatchMedia.useMobileChecker() <RenderIf condition={!isMobileView}> children </RenderIf> }
40
9,969
hyperswitch-control-center
src/components/InfraCalendar.res
.res
type month = Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec type highlighter = { highlightSelf: bool, highlightLeft: bool, highlightRight: bool, } 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 = ( ~item, ~month, ~year, ~rowIndex as _rowIndex, ~onDateClick, ~cellHighlighter=defaultCellHighlighter, ~cellRenderer=defaultCellRenderer, ~startDate="", ~endDate="", ~disablePastDates=true, ~disableFutureDates=false, ) => { open LogicUtils let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let highlight = cellHighlighter { if item == Array.make(~length=7, "") { React.null } 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 isFutureDate = todayInitial -. date->Date.getTime < 0.0 let onClick = _ => { let isClickDisabled = isFutureDate ? disableFutureDates : disablePastDates switch !isClickDisabled { | true => switch onDateClick { | Some(fn) => if obj->isNonEmptyString { 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) || (!isFutureDate && disablePastDates) ) { "cursor-not-allowed" } else { "cursor-default" } let classN = obj->isEmptyString || hSelf.highlightSelf ? `h-12 w-12 font-fira-code text-center dark:text-jp-gray-text_darktheme text-opacity-75 ${dayClass} p-0 pb-1` : `cursor-pointer h-12 w-12 text-center font-fira-code font-medium dark:text-jp-gray-text_darktheme text-opacity-75 dark:hover:bg-opacity-100 ${dayClass} p-0 pb-1` let c2 = obj->isNonEmptyString && hSelf.highlightSelf ? "h-full w-full cursor-pointer flex border flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-opacity-100 rounded-full" : "h-full w-full" let shouldHighlight = (startDate, endDate, obj, month, year) => { if startDate->isNonEmptyString && obj->isNonEmptyString { 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 parsedStartDate = getDate(String.split(startDate, "-")) let z = getDate([year, month, obj]) if endDate->isNonEmptyString { let parsedEndDate = getDate(String.split(endDate, "-")) z == parsedStartDate && 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 dark:hover:text-jp-gray-text_darktheme rounded-full" : 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 dark:hover:text-jp-gray-text_darktheme rounded-l-full " : 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 dark:hover:text-jp-gray-text_darktheme rounded-r-full " : z > parsedStartDate && z < parsedEndDate ? "h-full w-full flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary text-white dark:hover:text-jp-gray-text_darktheme dark:bg-opacity-100" : "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 text-white dark:hover:text-jp-gray-text_darktheme dark:bg-opacity-100 rounded-full" } else { "h-full w-full" } } else { "h-full w-full" } } let c3 = { shouldHighlight( startDate, endDate, obj, Float.toString(month +. 1.0), Float.toString(year), ) } <td key={Int.toString(cellIndex)} className=classN onClick> <span className={`${startDate->isEmptyString ? c2 : c3} ${obj->isNonEmptyString ? "dark:hover:border-jp-gray-400 dark:text-jp-gray-text_darktheme dark:hover:text-white" : ""}`}> <span className={obj->isEmptyString ? "" : "border border-transparent hover:text-jp-gray-950 hover:border-jp-gray-950 p-3 hover:bg-white dark:hover:bg-jp-gray-950 dark:hover:text-white rounded-full"}> {cellRenderer( obj->isEmptyString ? None : Some((Date.toString(date)->DayJs.getDayJsForString).format("YYYY-MM-DD")), )} </span> </span> </td> }) ->React.array} </tr> } } } } @react.component let make = ( ~month, ~year, ~onDateClick=?, ~showTitle=true, ~cellHighlighter=?, ~cellRenderer=?, ~highLightList=?, ~startDate="", ~endDate="", ~disablePastDates=true, ~disableFutureDates=false, ) => { // ~cellHighlighter: option<(~date: Date.t) => highlighter>=None, let _ = highLightList let months = [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] let heading = ["S", "M", "T", "W", "T", "F", "S"] 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-4 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> : React.null} <table className="table-auto min-w-full"> <thead> <tr> {heading ->Array.mapWithIndex((item, i) => { <th key={Int.toString(i)} className="p-0"> <div className="flex flex-1 justify-center py-2 font-medium text-jp-gray-700 dark:text-jp-gray-text_darktheme dark:text-opacity-50"> {React.string(item)} </div> </th> }) ->React.array} </tr> </thead> <tbody> {rowInfo ->Array.mapWithIndex((item, rowIndex) => { <TableRow key={Int.toString(rowIndex)} item rowIndex onDateClick ?cellHighlighter ?cellRenderer month={getMonthInFloat(month)} year={Int.toFloat(year)} startDate endDate disablePastDates disableFutureDates /> }) ->React.array} </tbody> </table> </div> }
2,470
9,970
hyperswitch-control-center
src/components/ACLDiv.res
.res
@react.component let make = ( ~authorization, ~onClick, ~children, ~className="", ~noAccessDescription=?, ~description=?, ~tooltipWidthClass=?, ~isRelative=?, ~showTooltip=true, ~contentAlign=?, ~justifyClass=?, ~tooltipForWidthClass=?, ~dataAttrStr=?, ~height=?, ) => { switch showTooltip { | true => <ACLToolTip authorization ?noAccessDescription ?tooltipForWidthClass ?description ?isRelative ?contentAlign ?tooltipWidthClass ?justifyClass ?height toolTipFor={<AddDataAttributes attributes=[("data-testid", dataAttrStr->Option.getOr("")->String.toLowerCase)]> <div className onClick={authorization === CommonAuthTypes.Access ? onClick : {_ => ()}}> {children} </div> </AddDataAttributes>} toolTipPosition={Top} /> | false => React.null } }
231
9,971
hyperswitch-control-center
src/components/DateRangeCompareFields.res
.res
let defaultCellHighlighter = (_): Calendar.highlighter => { { highlightSelf: false, highlightLeft: false, highlightRight: false, } } let useErrorValueResetter = (value: string, setValue: (string => string) => unit) => { React.useEffect(() => { let isErroryTimeValue = _ => { try { false } catch { | _error => true } } if value->isErroryTimeValue { setValue(_ => "") } None }, []) } 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 isStartBeforeEndDate = (start, end) => { let startDate = getDate(String.split(start, "-")) let endDate = getDate(String.split(end, "-")) startDate < endDate } module PredefinedOption = { @react.component let make = ( ~predefinedOptionSelected, ~value, ~onClick, ~disableFutureDates, ~disablePastDates, ~todayDayJsObj, ~isoStringToCustomTimeZone, ~isoStringToCustomTimezoneInFloat, ~customTimezoneToISOString, ~todayDate, ~todayTime, ~formatDateTime, ~isTooltipVisible=true, ) => { open DateRangeUtils let optionBG = if predefinedOptionSelected === Some(value) { "bg-blue-100 dark:bg-jp-gray-850 py-2" } else { "bg-transparent md:bg-white md:dark:bg-jp-gray-lightgray_background py-2" } let (stDate, enDate, stTime, enTime) = getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, value, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startDate = getFormattedDate(`${stDate}T${stTime}Z`, formatDateTime) let endDate = getFormattedDate(`${enDate}T${enTime}Z`, formatDateTime) let handleClick = () => { onClick(value, disableFutureDates) } let dateRangeDropdownVal = datetext(value, disableFutureDates) <ToolTip tooltipWidthClass="w-fit" tooltipForWidthClass="!block w-full" description={isTooltipVisible ? `${startDate} - ${endDate}` : ""} toolTipFor={<AddDataAttributes attributes=[("data-daterange-dropdown-value", dateRangeDropdownVal)]> <div> <div className={`${optionBG} mx-2 rounded-md p-2 hover:bg-jp-gray-100 hover:bg-opacity-75 dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 cursor-pointer text-sm font-medium text-grey-900`} onClick={_ev => handleClick()}> {React.string(dateRangeDropdownVal)} </div> </div> </AddDataAttributes>} toolTipPosition=Right contentAlign=Left /> } } module Base = { @react.component let make = ( ~startDateVal: string, ~setStartDateVal: (string => string) => unit, ~comparison: string, ~setComparison: (string => string) => unit, ~endDateVal: string, ~setEndDateVal: (string => string) => unit, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~dateRangeLimit=?, ~optFieldKey as _=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~selectStandardTime=false, ~buttonType=?, ~buttonText="", ~allowedDateRange=?, ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~customborderCSS="", ~isTooltipVisible=true, ~compareWithStartTime: string, ~compareWithEndTime: string, ) => { open DateRangeHelper open DateRangeUtils open LogicUtils let (isCustomSelected, setIsCustomSelected) = React.useState(_ => predefinedDays->Array.length === 0 ) let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let isoStringToCustomTimezoneInFloat = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat() let (clickedDates, setClickedDates) = React.useState(_ => []) let (localStartDate, setLocalStartDate) = React.useState(_ => startDateVal) let (localEndDate, setLocalEndDate) = React.useState(_ => endDateVal) let (isDropdownExpanded, setIsDropdownExpanded) = React.useState(_ => false) let (calendarVisibility, setCalendarVisibility) = React.useState(_ => false) let isMobileView = MatchMedia.useMobileChecker() let isFilterSection = React.useContext(TableFilterSectionContext.filterSectionContext) let dropdownPosition = isFilterSection && !isMobileView && isCustomSelected ? "right-0" : "" let todayDayJsObj = React.useMemo(() => { Date.make()->Date.toString->DayJs.getDayJsForString }, [isDropdownExpanded]) let currentTime = todayDayJsObj.format("HH:mm") let todayDate = todayDayJsObj.format("YYYY-MM-DD") let todayTime = React.useMemo(() => { todayDayJsObj.format("HH:mm:ss") }, [currentTime]) let initialStartTime = disableFutureDates || selectStandardTime ? "00:00:00" : "23:59:59" let initialEndTime = disableFutureDates || selectStandardTime ? "23:59:59" : "00:00:00" React.useEffect(() => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) None }, (startDateVal, endDateVal)) let resetStartEndInput = () => { setLocalStartDate(_ => "") setLocalEndDate(_ => "") } React.useEffect(() => { switch dateRangeLimit { | Some(maxLen) => { let diff = getStartEndDiff(localStartDate, localEndDate) if diff > (maxLen->Int.toFloat *. 24. *. 60. *. 60. -. 1.) *. 1000. { resetStartEndInput() } } | None => () } None }, (localStartDate, localEndDate)) let dateRangeRef = React.useRef(Nullable.null) let dropdownRef = React.useRef(Nullable.null) useErrorValueResetter(startDateVal, setStartDateVal) useErrorValueResetter(endDateVal, setEndDateVal) let startDate = localStartDate->getDateStringForValue(isoStringToCustomTimeZone) let endDate = localEndDate->getDateStringForValue(isoStringToCustomTimeZone) let isDropdownExpandedActual = isDropdownExpanded && calendarVisibility let saveDates = () => { if localStartDate->isNonEmptyString && localEndDate->isNonEmptyString { setStartDateVal(_ => localStartDate) setEndDateVal(_ => localEndDate) } } let resetToInitalValues = () => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) } OutsideClick.useOutsideClick( ~refs=ArrayOfRef([dateRangeRef, dropdownRef]), ~isActive=isDropdownExpanded || calendarVisibility, ~callback=() => { setIsDropdownExpanded(_ => false) setCalendarVisibility(p => !p) if isDropdownExpandedActual && isCustomSelected { resetToInitalValues() } }, ) let changeEndDate = (ele, isFromCustomInput, time) => { if disableApply { setIsDropdownExpanded(_ => false) } if localEndDate == ele && isFromCustomInput { setEndDateVal(_ => "") } else { let endDateSplit = String.split(ele, "-") let endDateDate = endDateSplit[2]->Option.getOr("") let endDateYear = endDateSplit[0]->Option.getOr("") let endDateMonth = endDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if disableFutureDates && ele == todayDate { todayTime } else { initialEndTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let endDateTimeCheck = customTimezoneToISOString( endDateYear, endDateMonth, endDateDate, timeHour, timeMinute, timeSecond, ) setLocalEndDate(_ => TimeZoneHook.formattedISOString(endDateTimeCheck, format)) } } let changeStartDate = (ele, isFromCustomInput, time) => { let setDate = str => { let startDateSplit = String.split(str, "-") let startDateDay = startDateSplit[2]->Option.getOr("") let startDateYear = startDateSplit[0]->Option.getOr("") let startDateMonth = startDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if !disableFutureDates && ele == todayDate && !standardTimeToday { todayTime } else { initialStartTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let startDateTimeCheck = customTimezoneToISOString( startDateYear, startDateMonth, startDateDay, timeHour, timeMinute, timeSecond, ) setLocalStartDate(_ => TimeZoneHook.formattedISOString(startDateTimeCheck, format)) } let resetStartDate = () => { resetStartEndInput() setDate(ele) } if startDate->isNonEmptyString && startDate == ele && isFromCustomInput { changeEndDate(ele, isFromCustomInput, None) } else if startDate->isNonEmptyString && startDate > ele && isFromCustomInput { resetStartDate() } else if endDate->isNonEmptyString && startDate == ele && isFromCustomInput { resetStartDate() } else if ( ele > startDate && ele < endDate && startDate->isNonEmptyString && endDate->isNonEmptyString && isFromCustomInput ) { resetStartDate() } else if ( startDate->isNonEmptyString && endDate->isNonEmptyString && ele > endDate && isFromCustomInput ) { resetStartDate() } else { () } if !isFromCustomInput || startDate->isEmptyString { setDate(ele) } if ( (startDate->isNonEmptyString && endDate->isEmptyString && !isFromCustomInput) || (startDate->isNonEmptyString && endDate->isEmptyString && isStartBeforeEndDate(startDate, ele) && isFromCustomInput) ) { changeEndDate(ele, isFromCustomInput, None) } } let onDateClick = str => { let data = switch Array.find(clickedDates, x => x == str) { | Some(_d) => Belt.Array.keep(clickedDates, x => x != str) | None => Array.concat(clickedDates, [str]) } let dat = data->Array.map(x => x) setClickedDates(_ => dat) changeStartDate(str, true, None) } let handleApply = _ => { setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) saveDates() } let cancelButton = _ => { resetToInitalValues() setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) } let selectedStartDate = if localStartDate->isNonEmptyString { getFormattedDate( localStartDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD", ) } else { "" } let selectedEndDate = if localEndDate->isNonEmptyString { getFormattedDate(localEndDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD") } else { "" } let setStartDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalStartDate(_ => timestamp) } } let setEndDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalEndDate(_ => timestamp) } } let startTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let startTimeVal = timeValEv->Identity.formReactEventToString let endTime = localEndDate->getTimeStringForValue(isoStringToCustomTimeZone) if localStartDate->isNonEmptyString { if disableFutureDates && selectedStartDate == todayDate && startTimeVal > todayTime { setStartDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && startTimeVal > endTime ) { () } else { setStartDate(~date=startDate, ~time=startTimeVal) } } }, onFocus: _ => (), value: localStartDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let endTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let endTimeVal = timeValEv->Identity.formReactEventToString let startTime = localStartDate->getTimeStringForValue(isoStringToCustomTimeZone) if localEndDate->isNonEmptyString { if disableFutureDates && selectedEndDate == todayDate && endTimeVal > todayTime { setEndDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && endTimeVal < startTime ) { () } else { setEndDate(~date=endDate, ~time=endTimeVal) } } }, onFocus: _ => (), value: localEndDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let startDateStr = startDateVal->isNonEmptyString ? getFormattedDate( startDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? buttonText : "[From-Date]" let endDateStr = endDateVal->isNonEmptyString ? getFormattedDate( endDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? "" : "[To-Date]" let handleDropdownClick = () => { if predefinedDays->Array.length > 0 { if calendarVisibility { setCalendarVisibility(_ => false) setIsDropdownExpanded(_ => !isDropdownExpanded) } else { setIsDropdownExpanded(_ => true) setCalendarVisibility(_ => true) } } else { setIsDropdownExpanded(_p => !isDropdownExpanded) setCalendarVisibility(_ => !isDropdownExpanded) } } React.useEffect(() => { if startDate->isNonEmptyString && endDate->isNonEmptyString { if ( localStartDate->isNonEmptyString && localEndDate->isNonEmptyString && (disableApply || !isCustomSelected) ) { saveDates() } } None }, (startDate, endDate, localStartDate, localEndDate)) let customStyleForBtn = "rounded-lg bg-white" let timeVisibilityClass = showTime ? "block" : "hidden" let getPredefinedValues = predefinedDay => { let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, predefinedDay, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startTimestamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) let endTimestamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) (startTimestamp, endTimestamp) } let predefinedOptionSelected = predefinedDays->Array.find(item => { let startDate = convertTimeStamp( ~isoStringToCustomTimeZone, startDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let endDate = convertTimeStamp( ~isoStringToCustomTimeZone, endDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let (startTimestamp, endTimestamp) = getPredefinedValues(item) let prestartDate = convertTimeStamp( ~isoStringToCustomTimeZone, startTimestamp, "YYYY-MM-DDTHH:mm:00[Z]", ) let preendDate = convertTimeStamp( ~isoStringToCustomTimeZone, endTimestamp, "YYYY-MM-DDTHH:mm:00[Z]", ) startDate == prestartDate && endDate == preendDate }) let buttonText = switch predefinedOptionSelected { | Some(value) => DateRangeUtils.datetext(value, disableFutureDates) | None => startDateVal->isEmptyString && endDateVal->isEmptyString ? `Select Date` : endDateVal->isEmptyString ? `${startDateStr} - Now` : `${startDateStr} ${startDateStr === buttonText ? "" : "-"} ${endDateStr}` } let buttonType: option<Button.buttonType> = buttonType let setDateTime = (~date, setLocalDate) => { if date->isNonEmptyString { setLocalDate(_ => date) } } let handleCompareOptionClick = value => { switch value { | Custom => setCalendarVisibility(_ => true) setIsCustomSelected(_ => true) setComparison(_ => (EnableComparison :> string)) | No_Comparison => { setCalendarVisibility(_ => false) setIsDropdownExpanded(_ => false) setIsCustomSelected(_ => false) setComparison(_ => (DisableComparison :> string)) setLocalStartDate(_ => compareWithStartTime) setLocalEndDate(_ => compareWithEndTime) setStartDateVal(_ => compareWithStartTime) setEndDateVal(_ => compareWithEndTime) } | Previous_Period => { setCalendarVisibility(_ => false) setIsDropdownExpanded(_ => false) setIsCustomSelected(_ => false) setDateTime(~date=startDateVal, setLocalStartDate) setDateTime(~date=endDateVal, setLocalEndDate) let _ = setTimeout(() => { setComparison(_ => (EnableComparison :> string)) }, 0) } } } let dropDownElement = () => { <div className={"flex md:flex-row flex-col w-full py-2"}> <AddDataAttributes attributes=[("data-date-picker-predifined", "predefined-options")]> <div className="flex flex-wrap gap-1 md:flex-col"> {[No_Comparison, Previous_Period, Custom] ->Array.mapWithIndex((value, i) => { <div key={i->Int.toString} className="w-full md:min-w-max text-center md:text-start"> <CompareOption value comparison startDateVal endDateVal onClick=handleCompareOptionClick /> </div> }) ->React.array} </div> </AddDataAttributes> <AddDataAttributes attributes=[("data-date-picker-section", "date-picker-calendar")]> <div className={calendarVisibility && isCustomSelected ? "w-auto md:w-max h-auto" : "hidden"}> <CalendarList count=numMonths cellHighlighter=defaultCellHighlighter startDate endDate onDateClick disablePastDates disableFutureDates dateRangeLimit={DateRangeUtils.getGapBetweenRange( ~startDate=compareWithStartTime, ~endDate=compareWithEndTime, ) + 1} calendarContaierStyle="md:mx-3 md:my-1 border-0 md:border" ?allowedDateRange /> <div className={`${timeVisibilityClass} w-full flex flex-row md:gap-4 p-3 justify-around md:justify-start dark:text-gray-400 text-gray-700 `}> <TimeInput input=startTimeInput showSeconds label="From" /> <TimeInput input=endTimeInput showSeconds label="To" /> </div> {if disableApply { React.null } else { <div id="neglectTopbarTheme" className="flex flex-row flex-wrap gap-3 bg-white dark:bg-jp-gray-lightgray_background px-3 mt-3 mb-1 align-center justify-end "> <Button text="Cancel" buttonType=Secondary buttonState=Normal buttonSize=Small onClick={cancelButton} /> <Button text="Apply" buttonType=Primary buttonState={endDate->LogicUtils.isEmptyString ? Disabled : Normal} buttonSize=Small onClick={handleApply} /> </div> }} </div> </AddDataAttributes> </div> } let dropDownClass = `absolute ${dropdownPosition} z-20 max-h-min max-w-min overflow-auto bg-white dark:bg-jp-gray-950 rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none mt-2 right-0` <div ref={dateRangeRef->ReactDOM.Ref.domRef} className="daterangSelection relative"> <DateSelectorButton startDateVal endDateVal setStartDateVal setEndDateVal disable isDropdownOpen=isDropdownExpanded removeFilterOption resetToInitalValues showTime buttonText showSeconds predefinedOptionSelected disableFutureDates onClick={_ => handleDropdownClick()} buttonType textStyle iconBorderColor=customborderCSS customButtonStyle=customStyleForBtn showLeftIcon=false isCompare=true comparison /> <RenderIf condition={isDropdownExpanded}> <div ref={dropdownRef->ReactDOM.Ref.domRef} className=dropDownClass> {dropDownElement()} </div> </RenderIf> </div> } } let useStateForInput = (input: ReactFinalForm.fieldRenderPropsInput) => { React.useMemo(() => { let val = input.value->JSON.Decode.string->Option.getOr("") let onChange = fn => { let newVal = fn(val) input.onChange(newVal->Identity.stringToFormReactEvent) } (val, onChange) }, [input]) } @react.component let make = ( ~startKey: string, ~endKey: string, ~comparisonKey: string, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~optFieldKey=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~allowedDateRange=?, ~selectStandardTime=false, ~buttonText="", ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~isTooltipVisible=true, ~compareWithStartTime, ~compareWithEndTime, ~dateRangeLimit=?, ) => { let startInput = ReactFinalForm.useField(startKey).input let endInput = ReactFinalForm.useField(endKey).input let comparisonInput = ReactFinalForm.useField(comparisonKey).input let (startDateVal, setStartDateVal) = useStateForInput(startInput) let (endDateVal, setEndDateVal) = useStateForInput(endInput) let (comparison, setComparison) = useStateForInput(comparisonInput) React.useEffect(() => { if ( compareWithStartTime->LogicUtils.isNonEmptyString && compareWithEndTime->LogicUtils.isNonEmptyString ) { let (startTime, endTime) = DateRangeUtils.getComparisionTimePeriod( ~startDate=compareWithStartTime, ~endDate=compareWithEndTime, ) setStartDateVal(_ => startTime) setEndDateVal(_ => endTime) } None }, [compareWithStartTime, compareWithEndTime]) <Base comparison setComparison startDateVal setStartDateVal endDateVal setEndDateVal showTime disable disablePastDates disableFutureDates predefinedDays format numMonths disableApply removeFilterOption ?dateRangeLimit ?optFieldKey textHideInMobileView showSeconds hideDate selectStandardTime buttonText ?allowedDateRange ?textStyle standardTimeToday removeConversion isTooltipVisible compareWithStartTime compareWithEndTime /> }
5,891
9,972
hyperswitch-control-center
src/components/DynamicFilter.res
.res
module CustomFilters = { @react.component let make = ( ~setShowModal, ~tabNames, ~moduleName as _, ~setCustomFilter, ~currentFilterValue, ) => { open LogicUtils let (errMessage, setErrMessage) = React.useState(_ => "") let (completionDisposable, setCompletionDisposable) = Recoil.useRecoilState( AnalyticsAtoms.completionProvider, ) let theme = switch ThemeProvider.useTheme() { | Dark => "vs-dark" | Light => "light" } let (localData, setLocalData) = React.useState(_ => currentFilterValue) let placeholderText = "ex: payment_method_type = 'UPI' and payment_method_type in ('WALLET', 'UPI') or currency not in ('GBP', 'AED') and auth_type != 'OTP'" let (placeholderTextSt, setPlaceHolder) = React.useState(_ => placeholderText) let onSubmit = _ => { setCustomFilter(localData) setShowModal(_ => false) } let onChange = str => { if str->isEmptyString { setPlaceHolder(_ => placeholderText) } setLocalData(_ => str) } React.useEffect(() => { setErrMessage(_ => "") if String.includes(localData, `"`) { setErrMessage(str => `${str} Please use ' instead of ".`) } let validatorArr = String.replaceRegExp(localData, %re("/ AND /gi"), "@@") ->String.replaceRegExp(%re("/ OR /gi"), "@@") ->String.split("@@") validatorArr->Array.forEach(ele => { let mArr = String.replaceRegExp(ele, %re("/ != /gi"), "@@") ->String.replaceRegExp(%re("/ > /gi"), "@@") ->String.replaceRegExp(%re("/ < /gi"), "@@") ->String.replaceRegExp(%re("/ >= /gi"), "@@") ->String.replaceRegExp(%re("/ <= /gi"), "@@") ->String.replaceRegExp(%re("/ = /gi"), "@@") ->String.replaceRegExp(%re("/ IN /gi"), "@@") ->String.replaceRegExp(%re("/ NOT IN /gi"), "@@") ->String.replaceRegExp(%re("/ LIKE /gi"), "@@") ->String.split("@@") let firstEle = mArr[0]->Option.getOr("") if ( firstEle->isNonEmptyString && tabNames->Array.indexOf(firstEle->String.trim->String.toLowerCase) < 0 ) { setErrMessage(str => `${str} ${firstEle} is not a valid dimension.`) } }) None }, [localData]) let beforeMount = (monaco: Monaco.monaco) => { let provideCompletionItems = (model, position: Monaco.Language.position) => { let word = Monaco.Language.getWordUntilPosition(model, position) let range: Monaco.Language.range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn, } let createSuggest = range => { Array.map(tabNames, val => { let value: Monaco.Language.labels = { label: val, insertText: val, range, } value }) } { Monaco.Language.suggestions: createSuggest(range), } } switch completionDisposable { | Some(_val) => () | None => setCompletionDisposable(_ => Monaco.Language.registerCompletionItemProvider( monaco.languages, "sql", {provideCompletionItems: provideCompletionItems}, )->Some ) } } let (mounseEnter, setMouseEnter) = React.useState(_ => false) <div className="border-t border-gray-200 p-5" onClick={_ => {setPlaceHolder(_ => "")}} onKeyPress={_ => {setMouseEnter(_ => true)}} onMouseLeave={_ => {setMouseEnter(_ => false)}}> {if placeholderTextSt->isNonEmptyString && localData->isEmptyString && !mounseEnter { <div className="monaco-placeholder text-black opacity-50 ml-6 "> {placeholderTextSt->React.string} </div> } else { React.null }} <Monaco.Editor language=#sql height="40vh" value={localData} theme onChange beforeMount options={ emptySelectionClipboard: true, wordWrap: #on, lineNumbers: #off, minimap: {enabled: false}, roundedSelection: false, } /> <div> <span className="flex break-words text-red-800"> {errMessage->isEmptyString ? React.null : React.string(errMessage)} </span> <div className="mt-6"> <Button text="Apply Filter" buttonType=Primary buttonSize=Small onClick=onSubmit buttonState={errMessage->isEmptyString ? Normal : Disabled} /> </div> </div> </div> } } @react.component let make = ( ~title="", ~initialFilters: array<EntityType.initialFilters<'t>>, ~options: array<EntityType.optionType<'t>>, ~popupFilterFields, ~initialFixedFilters: array<EntityType.initialFilters<'t>>, ~defaultFilterKeys: array<string>, ~tabNames: array<string>, ~updateUrlWith=?, ~showCustomFilter=true, ~customLeftView=React.null, ~filterButtonStyle="", ~moduleName="", ~customFilterKey="", ~filterFieldsPortalName="navbarSecondRow", ~filtersDisplayOption=true, ~showSelectFiltersSearch=false, ~refreshFilters=true, ) => { open LogicUtils let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let localFilters = initialFilters->Array.filter(item => item.localFilter->Option.isSome) let remoteOptions = options->Array.filter(item => item.localFilter->Option.isNone) let defaultFilters = ""->JSON.Encode.string let (showModal, setShowModal) = React.useState(_ => false) let {updateExistingKeys, filterValue, removeKeys} = React.useContext(FilterContext.filterContext) let currentCustomFilterValue = filterValue->Dict.get(customFilterKey)->Option.getOr("") let setCustomFilter = customFilter => { updateExistingKeys(Dict.fromArray([(customFilterKey, customFilter)])) } let customFilters = if customFilterKey->isNonEmptyString { <> <div className="mx-2"> <Button text="Add Custom Filters" buttonType=Button.FilterAdd showBorder=false buttonSize=Small leftIcon={CustomIcon(<Icon name="add_custom_img" size=14 />)} textStyle={`${textColor.primaryNormal}`} onClick={_ => setShowModal(_ => true)} /> </div> <Modal modalHeading="Add Custom Filter" showModal setShowModal modalClass="w-full md:w-2/3 mx-auto"> <CustomFilters setShowModal tabNames moduleName setCustomFilter currentFilterValue=currentCustomFilterValue /> </Modal> </> } else { React.null } let clearFilters = () => { let clearFilterKeys = [customFilterKey]->Array.concat(tabNames) removeKeys(clearFilterKeys) } <div className="flex-1 ml-1"> <Filter title defaultFilters fixedFilters=initialFixedFilters requiredSearchFieldsList=[] localFilters localOptions=[] remoteOptions remoteFilters=initialFilters popupFilterFields autoApply=false addFilterStyle="pt-4" filterButtonStyle defaultFilterKeys customRightView=customFilters customLeftView ?updateUrlWith clearFilters initalCount={currentCustomFilterValue->isNonEmptyString ? 1 : 0} showSelectFiltersSearch tableName=moduleName /> </div> }
1,820
9,973
hyperswitch-control-center
src/components/DatePicker.res
.res
@react.component let make = ( ~input: ReactFinalForm.fieldRenderPropsInput, ~isDisabled=false, ~disablePastDates=true, ~disableFutureDates=false, ~format="YYYY-MM-DDTHH:mm:ss", ~customButtonStyle="", ~newThemeCustomButtonStyle="", ~leftIcon=?, ~rightIcon=?, ~buttonType=?, ~buttonSize=?, ~customDisabledFutureDays=0.0, ~currentDateHourFormat="00", ~currentDateMinuteFormat="00", ~currentDateSecondsFormat="00", ~calendarContaierStyle=?, ~showTime=false, ~showSeconds=true, ~fullLength=?, ) => { open LogicUtils let dropdownRef = React.useRef(Nullable.null) let (isExpanded, setIsExpanded) = React.useState(_ => false) let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let (selectedDate, setSelectedDate) = React.useState(_ => input.value ->getStringFromJson("") ->DateRangeUtils.getDateStringForValue(isoStringToCustomTimeZone) ) let (date, setDate) = React.useState(_ => { if selectedDate->isNonEmptyString { let date = String.split(selectedDate, "-") let dateDay = date->Array.get(2)->Option.getOr("1") let dateMonth = date->Array.get(1)->Option.getOr("1") let dateYear = date->Array.get(0)->Option.getOr("1970") let timeSplit = switch input.value->JSON.Decode.string { | Some(str) => str | None => "" } ->DateRangeUtils.getTimeStringForValue(isoStringToCustomTimeZone) ->String.split(":") let timeHour = timeSplit->Array.get(0)->Option.getOr(currentDateHourFormat) let timeMinute = timeSplit->Array.get(1)->Option.getOr(currentDateMinuteFormat) let timeSecond = timeSplit->Array.get(2)->Option.getOr(currentDateSecondsFormat) let dateTimeCheck = customTimezoneToISOString( dateYear, dateMonth, dateDay, timeHour, timeMinute, timeSecond, ) let timestamp = TimeZoneHook.formattedISOString(dateTimeCheck, format) timestamp } else { "" } }) let dropdownVisibilityClass = if isExpanded { "inline-block z-100" } else { "hidden" } let onDateClick = str => { showTime ? () : setIsExpanded(p => !p) setSelectedDate(_ => str) let currentDateSplit = String.split(str, "-") let currentDateDay = currentDateSplit->Array.get(2)->Option.getOr("1") let currentDateYear = currentDateSplit->Array.get(0)->Option.getOr("1970") let currentDateMonth = currentDateSplit->Array.get(1)->Option.getOr("1") let currentDateTimeCheck = customTimezoneToISOString( currentDateYear, currentDateMonth, currentDateDay, currentDateHourFormat, currentDateMinuteFormat, currentDateSecondsFormat, ) setDate(_ => currentDateTimeCheck) input.onChange(currentDateTimeCheck->Identity.stringToFormReactEvent) } React.useEffect(() => { if input.value == ""->JSON.Encode.string { setSelectedDate(_ => "") } None }, [input.value]) let defaultCellHighlighter = currDate => { let highlighter: Calendar.highlighter = { highlightSelf: currDate === selectedDate, highlightLeft: false, highlightRight: false, } highlighter } OutsideClick.useOutsideClick( ~refs=ArrayOfRef([dropdownRef]), ~isActive=isExpanded, ~callback=() => { setIsExpanded(p => !p) }, ) let changeVisibility = _ => { if !isDisabled { setIsExpanded(p => !p) } } let buttonText = { let startDateStr = if selectedDate->isEmptyString { "Select Date" } else if !showTime { selectedDate } else { let time = date->DateRangeUtils.getTimeStringForValue(isoStringToCustomTimeZone) let splitTime = time->String.split(":") `${selectedDate} ${time->isEmptyString ? `${currentDateHourFormat}:${currentDateMinuteFormat}${showSeconds ? ":" ++ currentDateSecondsFormat : ""}` : splitTime->Array.get(0)->Option.getOr("NA") ++ ":" ++ splitTime->Array.get(1)->Option.getOr("NA") ++ ( showSeconds ? ":" ++ splitTime->Array.get(2)->Option.getOr("NA") : "" )}` } startDateStr } let buttonIcon = if isExpanded { "angle-up" } else { "angle-down" } let rightIcon: Button.iconType = switch rightIcon { | Some(icon) => icon | None => FontAwesome(buttonIcon) } let leftIcon: Button.iconType = switch leftIcon { | Some(icon) => icon | None => FontAwesome("calendar") } let fullLengthWidthClass = fullLength->Option.getOr(false) ? "2xl:w-full" : "" let startTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let timeVal = timeValEv->Identity.formReactEventToString if selectedDate->isNonEmptyString { let todayDayJsObj = Date.make()->Date.toString->DayJs.getDayJsForString let todayTime = todayDayJsObj.format("HH:mm:ss") let todayDate = todayDayJsObj.format("YYYY-MM-DD") let timeVal = if disableFutureDates && selectedDate == todayDate && timeVal > todayTime { todayTime } else { timeVal } let date = String.split(selectedDate, "-") let dateDay = date->Array.get(2)->Option.getOr("1") let dateMonth = date->Array.get(1)->Option.getOr("1") let dateYear = date->Array.get(0)->Option.getOr("1970") let timeSplit = String.split(timeVal, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr(currentDateHourFormat) let timeMinute = timeSplit->Array.get(1)->Option.getOr(currentDateMinuteFormat) let timeSecond = timeSplit->Array.get(2)->Option.getOr(currentDateSecondsFormat) let dateTimeCheck = customTimezoneToISOString( dateYear, dateMonth, dateDay, timeHour, timeMinute, timeSecond, ) let timestamp = TimeZoneHook.formattedISOString(dateTimeCheck, format) setDate(_ => timestamp) input.onChange(timestamp->dateFormat(format)->Identity.stringToFormReactEvent) } }, onFocus: _ => (), value: { let time = date->DateRangeUtils.getTimeStringForValue(isoStringToCustomTimeZone) let time = time->isEmptyString ? `${currentDateHourFormat}:${currentDateMinuteFormat}:${currentDateSecondsFormat}` : time time->JSON.Encode.string }, checked: false, } let styleClass = showTime ? " flex-col bg-white dark:bg-jp-gray-lightgray_background border-jp-gray-500 dark:border-jp-gray-960 p-4 rounded border" : "flex-row" let isMobileView = MatchMedia.useMobileChecker() let calendarElement = <> <CalendarList count=1 cellHighlighter=defaultCellHighlighter onDateClick disablePastDates disableFutureDates customDisabledFutureDays ?calendarContaierStyle /> {if showTime { <div className={`w-fit dark:text-gray-400 text-gray-700 `}> <TimeInput input=startTimeInput isDisabled={selectedDate->isEmptyString} showSeconds /> </div> } else { React.null }} </> <div ref={dropdownRef->ReactDOM.Ref.domRef} className="md:relative"> <Button text=buttonText customButtonStyle ?buttonType ?buttonSize buttonState={isDisabled ? Disabled : Normal} leftIcon rightIcon onClick={changeVisibility} ?fullLength /> <div className=dropdownVisibilityClass> {if isMobileView { <BottomModal headerText={buttonText} onCloseClick={changeVisibility}> calendarElement </BottomModal> } else { <div className={`absolute flex w-max z-10 bg-white ${fullLengthWidthClass} ${styleClass}`}> calendarElement </div> }} </div> </div> }
1,970
9,974
hyperswitch-control-center
src/components/Button.res
.res
type buttonState = Normal | Loading | Disabled | NoHover | Focused type buttonVariant = Fit | Long | Full | Rounded type buttonType = | Primary | Secondary | PrimaryOutline | SecondaryFilled | NonFilled | Pagination | Pill | FilterAdd | Delete | Transparent | SelectTransparent | DarkPurple | Dropdown type buttonSize = Large | Medium | Small | XSmall type iconType = | FontAwesome(string) | CustomIcon(React.element) | CustomRightIcon(React.element) | Euler(string) | NoIcon type badgeColor = | BadgeGreen | BadgeRed | BadgeBlue | BadgeGray | BadgeOrange | BadgeYellow | BadgeDarkGreen | BadgeDarkRed | NoBadge type badge = { value: string, color: badgeColor, } let useGetBgColor = ( ~buttonType, ~buttonState, ~showBorder, ~isDropdownOpen=false, ~isPhoneDropdown=false, ) => { let config = React.useContext(ThemeProvider.themeContext) let buttonConfig = config.globalUIConfig.button.backgroundColor switch buttonType { | Primary => switch buttonState { | Focused | Normal => buttonConfig.primaryNormal | Loading => buttonConfig.primaryLoading | Disabled => buttonConfig.primaryDisabled | NoHover => buttonConfig.primaryNoHover } | PrimaryOutline => buttonConfig.primaryOutline | SecondaryFilled => switch buttonState { | Focused | Normal => "bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 hover:shadow dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none" | Loading => "bg-jp-gray-200 dark:bg-jp-gray-800 dark:bg-opacity-10" | Disabled => "bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | NoHover => "bg-gradient-to-b overflow-x-scroll from-jp-gray-200 to-jp-gray-300 dark:from-jp-gray-950 dark:to-jp-gray-950 dark:gray-text_darktheme focus:outline-none dark:text-opacity-50 text-opacity-50" } | NonFilled => switch buttonState { | Focused | Normal => "hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-40 dark:hover:bg-jp-gray-950 dark:hover:bg-opacity-100 dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none" | Loading => "bg-jp-gray-200 dark:bg-jp-gray-800 dark:bg-opacity-10" | Disabled => "bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | NoHover => "hover:bg-jp-gray-600 hover:bg-opacity-40 dark:hover:bg-jp-gray-950 dark:hover:bg-opacity-100 dark:text-jp-gray-text_darktheme focus:outline-none dark:text-opacity-50 text-opacity-50" } | FilterAdd => switch buttonState { | Focused | Normal => "hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-40 dark:hover:bg-jp-gray-950 dark:hover:bg-opacity-100 text-primary dark:text-primary dark:text-opacity-100 focus:outline-none" | Loading => "bg-jp-gray-200 dark:bg-jp-gray-800 dark:bg-opacity-10" | Disabled => "bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | NoHover => "hover:bg-jp-gray-600 hover:bg-opacity-40 dark:hover:bg-jp-gray-950 dark:hover:bg-opacity-100 dark:text-primary focus:outline-none dark:text-opacity-100 text-opacity-50" } | Pagination => switch buttonState { | Focused | Normal => "font-medium border-transparent text-nd_gray-500 focus:outline-none" | Loading => "border-left-1 border-right-1 font-normal border-left-1 bg-jp-gray-200 dark:bg-jp-gray-800 dark:bg-opacity-10" | Disabled => "border-left-1 border-right-1 font-normal border-left-1 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | NoHover => "bg-primary bg-opacity-10 border-transparent font-medium dark:text-jp-gray-text_darktheme dark:text-opacity-75" } | Dropdown => { let hoverCss = isPhoneDropdown ? "" : "hover:bg-jp-2-light-gray-100" let color = if isDropdownOpen { showBorder ? "bg-jp-2-light-gray-100 shadow-jp-2-sm-gray-focus" : isPhoneDropdown ? "bg-transparent" : "bg-jp-2-light-gray-100" } else if isPhoneDropdown { "" } else { "bg-white" } switch buttonState { | Disabled => "bg-gray-200 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | _ => `${color} ${hoverCss} focus:outline-none dark:active:shadow-none` } } | Secondary => switch buttonState { | Focused | Normal => showBorder ? buttonConfig.secondaryNormal : buttonConfig.secondaryNoBorder | Loading => showBorder ? buttonConfig.secondaryLoading : buttonConfig.secondaryNoBorder | Disabled => showBorder ? buttonConfig.secondaryDisabled : buttonConfig.secondaryNoBorder | NoHover => buttonConfig.secondaryNoHover } | Pill => switch buttonState { | Focused | Normal => "bg-white text-jp-gray-900 text-opacity-50 hover:shadow hover:text-opacity-75 dark:bg-jp-gray-darkgray_background dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none" | Loading => showBorder ? "bg-white dark:bg-jp-gray-darkgray_background" : "bg-jp-gray-600 bg-opacity-40 dark:bg-jp-gray-950 dark:bg-opacity-100" | Disabled => showBorder ? "bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" : "px-4" | NoHover => "bg-white text-jp-gray-900 text-opacity-50 dark:bg-jp-gray-darkgray_background dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none" } | Delete => switch buttonState { | Focused | Normal => "bg-red-960 hover:from-red-960 hover:to-red-950 focus:outline-none" | Loading => "bg-red-960" | Disabled => "bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50" | NoHover => "bg-gradient-to-t from-red-960 to-red-800 hover:from-red-960 hover:to-red-960 focus:outline-none dark:text-opacity-50 text-opacity-50" } | Transparent => switch buttonState { | Focused | Normal => "bg-gray-50 hover:bg-gray-200 dark:bg-jp-gray-darkgray_background focus:outline-none" | Loading => "bg-gray-50 hover:bg-gray-200 focus:outline-none" | Disabled => "bg-gray-50 hover:bg-gray-200 dark:bg-jp-gray-darkgray_background focus:outline-none" | NoHover => "bg-gray-50 hover:bg-gray-200 focus:outline-none" } | SelectTransparent => switch buttonState { | Focused | Normal => "bg-blue-100 hover:bg-blue-200 dark:bg-black focus:outline-none" | Loading => "bg-gray-100 hover:bg-blue-200 focus:outline-none" | Disabled => "bg-gray-100 hover:bg-blue-200 focus:outline-none" | NoHover => "bg-gray-100 hover:bg-blue-200 focus:outline-none" } | DarkPurple => switch buttonState { | Focused | Normal => "bg-[#4F54EF] dark:bg-black focus:outline-none" | Loading => "bg-[#4F54EF] dark:bg-black focus:outline-none" | Disabled => "bg-[#4F54EF] dark:bg-black focus:outline-none" | NoHover => "bg-[#4F54EF] dark:bg-black focus:outline-none" } } } let useGetTextColor = ( ~buttonType, ~buttonState, ~showBorder, ~isDropdownOpen=false, ~isPhoneDropdown=false, ) => { let config = React.useContext(ThemeProvider.themeContext) let textConfig = config.globalUIConfig.button.textColor switch buttonType { | Primary => switch buttonState { | Disabled => textConfig.primaryDisabled | _ => textConfig.primaryNormal } | PrimaryOutline => textConfig.primaryOutline | FilterAdd => "text-primary" | Delete => "text-white" | Transparent => "text-gray-400" | SelectTransparent => "text-primary" | Dropdown => switch buttonState { | Disabled => "text-jp-2-light-gray-600" | Loading => "text-jp-2-light-gray-600" | _ => if isDropdownOpen { showBorder || isPhoneDropdown ? "text-jp-2-light-gray-2000" : "text-jp-2-light-gray-1700" } else { "text-jp-2-light-gray-1200 hover:text-jp-2-light-gray-2000" } } | Secondary => switch buttonState { | Disabled => textConfig.secondaryDisabled | Loading => textConfig.secondaryLoading | _ => textConfig.secondaryNormal } | SecondaryFilled => switch buttonState { | Disabled => "text-jp-gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-25" | Loading => "text-jp-gray-800 hover:text-black dark:text-jp-gray-text_darktheme dark:text-opacity-75" | _ => "text-jp-gray-800 hover:text-black dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75" } | DarkPurple => "text-white" | Pagination => switch buttonState { | Disabled => "font-medium text-nd_gray-300" | NoHover => "font-medium text-primary text-opacity-1 hover:text-opacity-70" | _ => "text-nd_gray-500 hover:bg-nd_gray-150" } | _ => switch buttonState { | Disabled => "text-jp-gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-25" | Loading => showBorder ? "text-jp-gray-900 text-opacity-50 hover:text-opacity-100 dark:text-jp-gray-text_darktheme dark:text-opacity-75" : "text-jp-gray-900 text-opacity-50 hover:text-opacity-100 dark:text-jp-gray-text_darktheme dark:text-opacity-75" | _ => "text-jp-gray-900 text-opacity-50 hover:text-opacity-100 dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75" } } } @react.component let make = ( ~buttonFor="", ~loadingText="Loading..", ~buttonState: buttonState=Normal, ~text=?, ~isSelectBoxButton=false, ~buttonType: buttonType=SecondaryFilled, ~isDropdownOpen=false, ~buttonVariant: buttonVariant=Fit, ~buttonSize: option<buttonSize>=?, ~leftIcon: iconType=NoIcon, ~rightIcon: iconType=NoIcon, ~showBorder=true, ~type_="button", ~flattenBottom=false, ~flattenTop=false, ~onEnterPress=true, ~onClick=?, ~textStyle="", ~iconColor="", ~iconBorderColor="", ~customIconMargin=?, ~customTextSize=?, ~customIconSize=?, ~textWeight=?, ~fullLength=false, ~disableRipple=false, ~customButtonStyle="", ~textStyleClass=?, ~customTextPaddingClass=?, ~allowButtonTextMinWidth=true, ~badge: badge={ value: 1->Int.toString, color: NoBadge, }, ~buttonRightText=?, ~ellipsisOnly=false, ~isRelative=true, ~customPaddingClass=?, ~customRoundedClass=?, ~customHeightClass=?, ~customBackColor=?, ~isPhoneDropdown=false, ~showBtnTextToolTip=false, ~showTooltip=false, ~tooltipText=?, ~toolTipPosition=ToolTip.Top, ~dataTestId="", ) => { let parentRef = React.useRef(Nullable.null) let dummyRef = React.useRef(Nullable.null) let buttonRef = disableRipple ? dummyRef : parentRef let rippleEffect = RippleEffectBackground.useHorizontalRippleHook(buttonRef) if !isPhoneDropdown { rippleEffect } let customTextOverFlowClass = switch textStyleClass { | Some(val) => val | None => "overflow-hidden" } // Hyperswitch doesn't have use case of some btn type variant // overridding the variant with a used type let buttonType = switch buttonType { | SecondaryFilled => Secondary | _ => buttonType } let buttonSize: buttonSize = buttonSize->Option.getOr(MatchMedia.useMatchMedia("(max-width: 800px)") ? Small : Medium) let lengthStyle = if fullLength { "w-full justify-between" } else { "" } let badgeColor = switch buttonState { | Disabled => "bg-slate-300" | _ => switch badge.color { | BadgeGreen => "bg-green-950 dark:bg-opacity-50" | BadgeRed => "bg-red-960 dark:bg-opacity-50" | BadgeBlue => "bg-primary dark:bg-opacity-50" | BadgeGray => "bg-blue-table_gray" | BadgeOrange => "bg-orange-950 dark:bg-opacity-50" | BadgeYellow => "bg-blue-table_yellow" | BadgeDarkGreen => "bg-green-700" | BadgeDarkRed => "bg-red-400" | NoBadge => "hidden" } } let badgeTextColor = switch buttonState { | Disabled => "text-white" | _ => switch badge.color { | BadgeGray => "text-jp-gray-900" | BadgeYellow => "text-jp-gray-900" | _ => "text-white" } } let heightClass = customHeightClass->Option.getOr("") let cursorType = switch buttonState { | Loading => "cursor-wait" | Disabled => "cursor-not-allowed" | _ => "cursor-pointer" } let paddingClass = customPaddingClass->Option.getOr("") let customWidthClass = switch buttonSize { | Large => "w-147-px" | Medium => "w-145-px" | Small => "w-137-px" | _ => "" } let customHeightClass = switch buttonSize { | Large => "h-40-px" | Medium => "h-36-px" | Small => "h-32-px" | _ => "" } let textPaddingClass = customTextPaddingClass->Option.getOr( switch buttonSize { | XSmall => "px-1" | Small => "px-1" | Medium => "px-1" | Large => "py-3" }, ) let textSize = customTextSize->Option.getOr( switch buttonSize { | XSmall => "text-fs-11" | Small => "text-fs-13" | Medium => "text-body" | Large => "text-fs-16" }, ) let ellipsisClass = ellipsisOnly ? "truncate" : "" let ellipsisParentClass = ellipsisOnly ? "max-w-[250px] md:max-w-xs" : "" let iconSize = customIconSize->Option.getOr( switch buttonSize { | XSmall => 12 | Small => 14 | Medium => 16 | Large => 18 }, ) let strokeColor = "" let iconPadding = switch buttonSize { | XSmall => "px-1" | Small => "px-2" | Medium => "pr-3" | Large => "px-3" } let iconMargin = customIconMargin->Option.getOr( switch buttonSize { | XSmall | Small => "ml-1" | Medium | Large => "ml-3" }, ) let rightIconSpacing = switch buttonSize { | XSmall | Small => "mt-0.5 px-1" | Medium | Large => "mx-3 mt-0.5" } let badgeSpacing = switch buttonSize { | XSmall | Small => "px-2 mb-0.5 mr-0.5" | Medium | Large => "px-2 mb-1 mr-0.5" } let badgeTextSize = switch buttonSize { | XSmall | Small => "text-sm" | Medium | Large => "text-base" } let backColor = useGetBgColor( ~buttonType, ~buttonState, ~showBorder, ~isDropdownOpen, ~isPhoneDropdown, ) let textColor = useGetTextColor( ~buttonType, ~buttonState, ~showBorder, ~isDropdownOpen, ~isPhoneDropdown, ) let defaultRoundedClass = switch buttonSize { | Large => "rounded-xl" | Small => "rounded-lg" | Medium => "rounded-10-px" | XSmall => "rounded-md" } let {isFirst, isLast} = React.useContext(ButtonGroupContext.buttonGroupContext) let roundedClass = { let roundedBottom = flattenBottom ? "rounded-b-none" : "" let roundedTop = flattenTop ? "rounded-t-none" : "" let roundedDirection = if isFirst && isLast { defaultRoundedClass } else if isFirst { "rounded-l-md" } else if isLast { "rounded-r-md" } else if buttonType == Pagination { "rounded-lg" } else { "" } `${roundedDirection} ${roundedBottom} ${roundedTop}` } let borderStyle = { let borderWidth = if showBorder || (buttonType === Dropdown && !(isFirst && isLast)) { if isFirst && isLast { "border" } else if isFirst { "border focus:border-r" } else if isLast { "border focus:border-l" } else { "border border-x-1 focus:border-x" } } else { "border-0" } switch buttonType { | Primary => switch buttonState { | Disabled => "" | _ => if showBorder { `${borderWidth} border-1.5 ` } else { "" } } | PrimaryOutline => `border-2` | Dropdown | Secondary => showBorder ? switch buttonState { | Disabled => "" | Loading => `${borderWidth} border-border_gray` | _ => `${borderWidth} border-border_gray dark:border-jp-gray-960 dark:border-opacity-100` } : switch buttonState { | Disabled => "" | Loading => borderWidth | _ => borderWidth } | SecondaryFilled => switch buttonState { | Disabled => "" | Loading => `${borderWidth} border-jp-gray-600 border-opacity-75 dark:border-jp-gray-960 dark:border-opacity-100 ` | _ => `${borderWidth} border-jp-gray-500 dark:border-jp-gray-960` } | Pill => showBorder ? { switch buttonState { | Disabled => "" | Loading => `${borderWidth} border-jp-gray-600 border-opacity-75 dark:border-jp-gray-960 dark:border-opacity-100` | _ => `${borderWidth} border-jp-gray-500 dark:border-jp-gray-960` } } : { switch buttonState { | Disabled => "" | Loading => borderWidth | _ => borderWidth } } | FilterAdd => "border-0" | SelectTransparent => "border border-1 border-primary" | Transparent => "border border-jp-2-light-gray-400" | Delete => switch buttonState { | Disabled => "" | Loading => `${borderWidth} border-jp-gray-600 border-opacity-75 dark:border-jp-gray-960 dark:border-opacity-100 ` | _ => `${borderWidth} border-jp-gray-500 dark:border-jp-gray-960` } | _ => switch buttonState { | Disabled => "" | Loading => `${borderWidth} border-jp-gray-600 border-opacity-75 dark:border-jp-gray-960 dark:border-opacity-100 ` | _ => `${borderWidth} border-jp-gray-500 dark:border-jp-gray-960` } } } let dis = switch buttonState { | Focused | Normal => false | NoHover => false | _ => true } let loaderIconColor = switch buttonType { | Primary => Some("text-white") | _ => None } let handleClick = ev => { switch onClick { | Some(fn) => fn(ev) | None => () } } let textWeight = switch textWeight { | Some(weight) => weight | _ => "text-sm font-medium leading-5" } let textId = text->Option.getOr("") let iconId = switch leftIcon { | FontAwesome(iconName) | Euler(iconName) => iconName | CustomIcon(_) => "CustomIcon" | CustomRightIcon(_) => "CustomRightIcon" | NoIcon => switch rightIcon { | FontAwesome(iconName) | Euler(iconName) => iconName | CustomIcon(_) => "CustomIcon" | NoIcon => "" | CustomRightIcon(_) => "CustomRightIcon" } } let dataAttrKey = isSelectBoxButton ? "data-value" : "data-button-for" let dataAttrStr = textId->LogicUtils.isEmptyString ? iconId : textId->String.concat(buttonFor)->LogicUtils.toCamelCase let relativeClass = isRelative ? "relative" : "" let conditionalButtonStyles = `${allowButtonTextMinWidth ? "min-w-min" : ""} ${customBackColor->Option.getOr(backColor)} ${customRoundedClass->Option.getOr( roundedClass, )}` let customJustifyStyle = customButtonStyle->String.includes("justify") ? "" : "justify-center" <AddDataAttributes attributes=[(dataAttrKey, dataAttrStr), ("data-testid", dataTestId)]> <button type_ disabled=dis ref={parentRef->ReactDOM.Ref.domRef} onKeyUp={e => e->ReactEvent.Keyboard.preventDefault} onKeyPress={e => { if !onEnterPress { e->ReactEvent.Keyboard.preventDefault } }} className={`flex group ${customButtonStyle} ${customJustifyStyle} ${relativeClass} ${heightClass} ${conditionalButtonStyles} items-center ${borderStyle} ${cursorType} ${paddingClass} ${lengthStyle} ${customTextOverFlowClass} ${textColor} ${customWidthClass} ${customHeightClass}`} onClick=handleClick> {if buttonState == Loading { <span className={iconPadding}> <span className={`flex items-center mx-2 animate-spin`}> <Loadericon size=iconSize iconColor=?loaderIconColor /> </span> </span> } else { switch leftIcon { | FontAwesome(iconName) => <span className={`flex items-center ${iconColor} ${iconMargin} ${iconPadding}`}> <Icon className={`align-middle ${strokeColor} ${iconBorderColor}`} size=iconSize name=iconName /> </span> | Euler(iconName) => <span className={`flex items-center ${iconColor} ${iconMargin}`}> <Icon className={`align-middle ${strokeColor}`} size=iconSize name=iconName /> </span> | CustomIcon(element) => <span className={`flex items-center ${iconMargin}`}> {element} </span> | _ => React.null } }} {switch text { | Some(textStr) => if !(textStr->LogicUtils.isEmptyString) { let btnContent = <AddDataAttributes attributes=[("data-button-text", textStr)]> <div className={`${textPaddingClass} px-3 ${textSize} ${textWeight} ${ellipsisClass} whitespace-pre ${textStyle}`}> {buttonState == Loading ? React.string(loadingText) : React.string(textStr)} </div> </AddDataAttributes> if showBtnTextToolTip { <div className=ellipsisParentClass> <ToolTip description={tooltipText->Option.getOr("")} toolTipFor=btnContent contentAlign=Default justifyClass="justify-start" toolTipPosition /> </div> } else { <div className=ellipsisParentClass> btnContent </div> } } else { React.null } | None => React.null }} {switch badge.color { | NoBadge => React.null | _ => <AddDataAttributes attributes=[("data-badge-value", badge.value)]> <span className={`flex items-center ${rightIconSpacing} ${badgeColor} ${badgeTextColor} ${badgeSpacing} ${badgeTextSize} rounded-full`}> {React.string(badge.value)} </span> </AddDataAttributes> }} {switch buttonRightText { | Some(text) => <RenderIf condition={!(text->LogicUtils.isEmptyString)}> <span className="text-jp-2-light-primary-600 font-semibold text-fs-14"> {React.string(text)} </span> </RenderIf> | None => React.null }} {switch rightIcon { | FontAwesome(iconName) => <span className={`flex items-center ${rightIconSpacing}`}> <Icon className={`align-middle ${strokeColor}`} size=iconSize name=iconName /> </span> | Euler(iconName) => <span className={`flex items-center ${iconMargin}`}> <Icon className={`align-middle ${strokeColor}`} size=iconSize name=iconName /> </span> | CustomIcon(element) => <span className={`flex items-center ${iconPadding} `}> {element} </span> | _ => React.null }} </button> </AddDataAttributes> }
6,444
9,975
hyperswitch-control-center
src/components/Table.res
.res
include TableUtils module TableFilterRow = { @react.component let make = ( ~item: array<filterRow>, ~removeVerticalLines, ~removeHorizontalLines, ~evenVertivalLines, ~tableDataBorderClass, ~customFilterRowStyle, ~showCheckbox, ) => { let colsLen = item->Array.length let borderColor = "border-jp-gray-light_table_border_color dark:border-jp-gray-960" let paddingClass = "px-8 py-3" let hoverClass = "hover:bg-jp-gray-table_hover dark:hover:bg-jp-gray-table_hover_dark" <tr className={`filterColumns group rounded-md h-10 bg-white dark:bg-jp-gray-lightgray_background ${hoverClass} transition duration-300 ease-in-out text-fs-13 text-jp-gray-900 text-opacity-75 dark:text-jp-gray-text_darktheme dark:text-opacity-75 ${customFilterRowStyle}`}> {if showCheckbox { <td /> } else { React.null }} {item ->Array.mapWithIndex((obj: filterRow, cellIndex) => { let isLast = cellIndex === colsLen - 1 let showBorderTop = true let borderTop = showBorderTop ? "border-t" : "border-t-0" let borderClass = if removeHorizontalLines && removeVerticalLines { "" } else if isLast { `${borderTop} ${borderColor}` } else if removeVerticalLines || (evenVertivalLines && mod(cellIndex, 2) === 0) { `${borderTop} ${borderColor}` } else { `${borderTop} border-r ${borderColor}` } <td key={Int.toString(cellIndex)} className={`align-top ${borderClass} ${tableDataBorderClass}`}> <div className={`box-border ${paddingClass}`}> <TableFilterCell cell=obj /> </div> </td> }) ->React.array} </tr> } } module TableRow = { @react.component let make = ( ~title, ~item: array<cell>, ~rowIndex, ~onRowClick, ~onRowDoubleClick, ~onRowClickPresent, ~offset, ~removeVerticalLines, ~removeHorizontalLines, ~evenVertivalLines, ~highlightEnabledFieldsArray, ~tableDataBorderClass="", ~collapseTableRow=false, ~expandedRow: _ => React.element, ~onMouseEnter, ~onMouseLeave, ~highlightText, ~clearFormatting=false, ~rowHeightClass="", ~rowCustomClass="", ~fixedWidthClass, ~isHighchartLegend=false, ~labelMargin="", ~isEllipsisTextRelative=true, ~customMoneyStyle="", ~ellipseClass="", ~selectedRowColor="bg-white dark:bg-jp-gray-lightgray_background", ~lastColClass="", ~fixLastCol=false, ~alignCellContent="", ~customCellColor="", ~highlightSelectedRow=false, ~selectedIndex, ~setSelectedIndex, ) => { open Window let (isCurrentRowExpanded, setIsCurrentRowExpanded) = React.useState(_ => false) let (expandedData, setExpandedData) = React.useState(_ => React.null) let actualIndex = offset + rowIndex let onClick = React.useCallback(_ => { let isRangeSelected = getSelection().\"type" == "Range" switch (onRowClick, isRangeSelected) { | (Some(fn), false) => { setSelectedIndex(_ => actualIndex) fn(actualIndex) } | _ => () } }, (onRowClick, actualIndex)) let onDoubleClick = React.useCallback(_ => { switch onRowDoubleClick { | Some(fn) => fn(actualIndex) | _ => () } }, (onRowDoubleClick, actualIndex)) let onMouseEnter = React.useCallback(_ => { switch onMouseEnter { | Some(fn) => fn(actualIndex) | _ => () } }, (onMouseEnter, actualIndex)) let onMouseLeave = React.useCallback(_ => { switch onMouseLeave { | Some(fn) => fn(actualIndex) | _ => () } }, (onMouseLeave, actualIndex)) let colsLen = item->Array.length let cursorClass = onRowClickPresent ? "cursor-pointer" : "" let rowRef = React.useRef(Nullable.null) let coloredRow = // colour based on custom cell's value item ->Array.find(obj => { switch obj { | CustomCell(_, x) => x === "true" | _ => false } }) ->Option.isSome let bgColor = coloredRow ? selectedRowColor : highlightSelectedRow && selectedIndex == actualIndex ? "bg-nd_gray-150" : "bg-white dark:bg-jp-gray-lightgray_background" let fontSize = "text-fs-14" let fontWeight = "font-medium" let textColor = "text-nd_gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-75" let hoverClass = onRowClickPresent ? "hover:bg-nd_gray-50 dark:hover:bg-jp-gray-table_hover_dark" : "" let tableBodyText = if isHighchartLegend { `group rounded-md ${cursorClass} text-fs-10 font-medium dark:text-jp-gray-dark_chart_legend_text jp-gray-light_chart_legend_text pb-4 whitespace-nowrap text-ellipsis overflow-x-hidden` } else { `group rounded-md ${cursorClass} ${bgColor} ${fontSize} ${fontWeight} ${rowCustomClass} ${textColor} ${hoverClass} transition duration-300 ease-in-out` } <> <tr ref={rowRef->ReactDOM.Ref.domRef} className=tableBodyText onClick onMouseEnter onMouseLeave onDoubleClick> {item ->Array.mapWithIndex((obj: cell, cellIndex) => { let isLast = cellIndex === colsLen - 1 let showBorderTop = switch obj { | Text(x) => x !== "-" | _ => true } let paddingClass = switch obj { | Link(_) => "pt-2" | _ => "py-3" } let coloredRow = switch obj { | CustomCell(_, x) => x === "true" | _ => false } let customColorCell = coloredRow ? customCellColor : "" let highlightCell = highlightEnabledFieldsArray->Array.includes(cellIndex) let highlightClass = highlightCell ? "hover:font-bold" : "" let borderColor = "border-nd_br_gray-150 dark:border-jp-gray-960" let borderTop = showBorderTop ? "border-t" : "border-t-0" let borderClass = if removeHorizontalLines && removeVerticalLines { "" } else if isLast { `${borderTop} ${borderColor}` } else if removeVerticalLines || (evenVertivalLines && mod(cellIndex, 2) === 0) { `${borderTop} ${borderColor}` } else { `${borderTop} border-r ${borderColor}` } let cursorI = cellIndex == 0 && collapseTableRow ? "cursor-pointer" : "" let isLast = cellIndex === colsLen - 1 let lastColProp = isLast && fixLastCol ? "border-l h-full !py-0 flex flex-col justify-center" : "" let tableRowBorderClass = if isHighchartLegend { `align-center ${highlightClass} ${tableDataBorderClass} ${cursorI} ${rowHeightClass}` } else if isLast { `align-center ${lastColClass} ${borderClass} ${highlightClass} ${tableDataBorderClass} ${cursorI} ${rowHeightClass}` } else { `align-center ${borderClass} ${highlightClass} ${tableDataBorderClass} ${cursorI} ${rowHeightClass}` } let paddingClass = `px-8 ${paddingClass}` let tableRowPaddingClass = if isHighchartLegend { `box-border py-1 ${lastColProp} ${alignCellContent}` } else { `box-border ${paddingClass} ${lastColProp} ${alignCellContent}` } let location = `${title}_tr${(rowIndex + 1)->Int.toString}_td${(cellIndex + 1) ->Int.toString}` <AddDataAttributes key={cellIndex->Int.toString} attributes=[("data-table-location", location)]> <td key={Int.toString(cellIndex)} className={`${tableRowBorderClass} ${customColorCell}`} style={width: fixedWidthClass} onClick={_ => { if collapseTableRow && cellIndex == 0 { setIsCurrentRowExpanded(prev => !prev) setExpandedData(_ => expandedRow()) } }}> <div className=tableRowPaddingClass> {if collapseTableRow { <div className="flex flex-row gap-4 items-center"> {if cellIndex === 0 { <Icon name={isCurrentRowExpanded ? "caret-down" : "caret-right"} size=14 /> } else { React.null }} <TableCell cell=obj highlightText clearFormatting labelMargin isEllipsisTextRelative customMoneyStyle ellipseClass /> </div> } else { <TableCell cell=obj highlightText clearFormatting labelMargin isEllipsisTextRelative customMoneyStyle ellipseClass /> }} </div> </td> </AddDataAttributes> }) ->React.array} </tr> {if isCurrentRowExpanded { <tr className="dark:border-jp-gray-dark_disable_border_color"> <td colSpan=12 className=""> {expandedData} </td> </tr> } else { React.null }} </> } } module SortAction = { @react.component let make = ( ~item: TableUtils.header, ~sortedObj: option<TableUtils.sortedObject>, ~setSortedObj, ~sortIconSize, ~isLastCol=false, ~filterRow: option<filterRow>, ) => { if item.showSort || filterRow->Option.isSome { let order: sortOrder = switch sortedObj { | Some(obj: sortedObject) => obj.key === item.key ? obj.order : NONE | None => NONE } let handleSortClick = _ => { switch setSortedObj { | Some(fn) => fn(_ => Some({ key: item.key, order: order === DEC ? INC : DEC, })) | None => () } } <AddDataAttributes attributes=[("data-table", "tableSort")]> <div className="cursor-pointer text-gray-300 pl-4" onClick=handleSortClick> <SortIcons order size=sortIconSize /> </div> </AddDataAttributes> } else { React.null } } } module TableHeadingCell = { @react.component let make = ( ~item, ~index, ~headingArray, ~isHighchartLegend, ~frozenUpto, ~heightHeadingClass, ~tableheadingClass, ~sortedObj, ~setSortedObj, ~filterObj, ~fixedWidthClass, ~setFilterObj, ~headingCenter, ~filterIcon=?, ~filterDropdownClass=?, ~filterDropdownMaxHeight=?, ~selectAllCheckBox: option<multipleSelectRows>, ~setSelectAllCheckBox, ~isFrozen=false, ~lastHeadingClass="", ~fixLastCol=false, ~headerCustomBgColor=?, ~filterRow, ~customizeColumnNewTheme=?, ~tableHeadingTextClass="", ) => { let i = index let isFirstCol = i === 0 let isLastCol = i === headingArray->Array.length - 1 let handleUpdateFilterObj = (ev, i) => { switch setFilterObj { | Some(fn) => fn((prevFilterObj: array<filterObject>) => { prevFilterObj->Array.map(obj => { obj.key === Int.toString(i) ? { key: Int.toString(i), options: obj.options, selected: ev->Identity.formReactEventToArrayOfString, } : obj }) }) | None => () } } let setIsSelected = isAllSelected => { switch setSelectAllCheckBox { | Some(fn) => fn(_ => { if isAllSelected { Some(ALL) } else { None } }) | None => () } } let headerBgColor = headerCustomBgColor->Option.isSome ? headerCustomBgColor->Option.getOr("") : " bg-nd_gray-50 dark:bg-jp-gray-darkgray_background" let paddingClass = "px-8 py-3" let roundedClass = if isFirstCol { "rounded-tl" } else if isLastCol { "rounded-tr" } else { "" } let headerTextClass = "text-nd_gray-400 leading-18 dark:text-jp-gray-text_darktheme dark:text-opacity-75" let fontWeight = "font-medium" let fontSize = "text-fs-13 " let lastColProp = isLastCol && fixLastCol ? "sticky right-0 !px-0 !py-0 z-20" : "" let borderlastCol = isLastCol && fixLastCol ? "border-l px-4 py-3 h-full justify-center !flex-col" : "" let tableHeaderClass = if isHighchartLegend { `tableHeader ${lastColProp} p-3 justify-between items-center dark:text-jp-gray-dark_chart_legend_text jp-gray-light_chart_legend_text text-opacity-75 dark:text-opacity-75 whitespace-pre select-none ${isLastCol ? lastHeadingClass : ""}` } else { let heightHeadingClass2 = frozenUpto == 0 ? "" : heightHeadingClass `tableHeader ${lastColProp} ${item.customWidth->Option.getOr( "", )} justify-between items-center ${headerTextClass} whitespace-pre select-none ${headerBgColor} ${paddingClass} ${roundedClass} ${heightHeadingClass2} ${tableheadingClass} ${isLastCol ? lastHeadingClass : ""}` } let tableHeadingTextClass = if isHighchartLegend { "text-fs-11 dark:text-blue-300 text-jp-gray-900 text-opacity-80 dark:text-opacity-100 font-medium not-italic whitespace-nowrap text-ellipsis overflow-x-hidden " } else { `${fontWeight} ${fontSize} ${tableHeadingTextClass}` } let (isAllSelected, isSelectedStateMinus, checkboxDimension) = ( selectAllCheckBox->Option.isSome, selectAllCheckBox === Some(PARTIAL), "h-4 w-4", ) let sortIconSize = isHighchartLegend ? 11 : 15 let justifyClass = "" <AddDataAttributes attributes=[("data-table-heading", item.title)]> <th key={Int.toString(i)} className=tableHeaderClass style={width: fixedWidthClass}> {switch customizeColumnNewTheme { | Some(value) => <div className="flex flex-row justify-center items-center"> value.customizeColumnUi </div> | None => <div className={`flex flex-row ${borderlastCol} ${headingCenter ? "justify-center" : justifyClass}`}> <div className=""> <div className={"flex flex-row"}> <RenderIf condition={item.showMultiSelectCheckBox->Option.getOr(false)}> <div className=" mt-1 mr-2"> <CheckBoxIcon isSelected={isAllSelected} setIsSelected isSelectedStateMinus checkboxDimension /> </div> </RenderIf> <div className="flex justify-between items-center"> {switch item.headerElement { | Some(headerElement) => headerElement | _ => <div className=tableHeadingTextClass> {React.string(item.title)} </div> }} <RenderIf condition={item.data->Option.isSome}> <AddDataAttributes attributes=[("data-heading-value", item.data->Option.getOr(""))]> <div className="flex justify-start text-fs-10 font-medium text-gray-400 whitespace-pre text-ellipsis overflow-x-hidden"> {React.string(` (${item.data->Option.getOr("")})`)} </div> </AddDataAttributes> </RenderIf> {if item.showFilter || item.showSort || filterRow->Option.isSome { let selfClass = "self-end" <div className={`flex flex-row ${selfClass} items-center`}> <SortAction item sortedObj setSortedObj sortIconSize filterRow isLastCol={false} /> {if item.showFilter { let (options, selected) = switch filterObj { | Some(obj) => switch obj[i] { | Some(ele) => (ele.options, ele.selected) | None => ([], []) } | None => ([], []) } if options->Array.length > 1 { let filterInput: ReactFinalForm.fieldRenderPropsInput = { name: "filterInput", onBlur: _ => (), onChange: ev => handleUpdateFilterObj(ev, i), onFocus: _ => (), value: selected->Array.map(JSON.Encode.string)->JSON.Encode.array, checked: true, } let icon = switch filterIcon { | Some(icon) => icon | None => <Icon className="align-middle text-gray-400" name="filter" size=12 /> } let dropdownClass = switch filterDropdownClass { | Some(className) => className | None => "" } let maxHeight = filterDropdownMaxHeight <div className={`${dropdownClass}`}> <SelectBox.BaseDropdown allowMultiSelect=true hideMultiSelectButtons=true buttonText="" input={filterInput} options={options->SelectBox.makeOptions} deselectDisable=false baseComponent=icon autoApply=false ?maxHeight /> </div> } else { React.null } } else { React.null }} </div> } else { React.null }} </div> <RenderIf condition={item.isMandatory->Option.getOr(false)}> <div className="text-red-400 text-sm ml-1"> {React.string("*")} </div> </RenderIf> <RenderIf condition={item.description->Option.getOr("")->LogicUtils.isNonEmptyString}> <div className="text-sm text-gray-500 mx-2"> <ToolTip description={item.description->Option.getOr("")} toolTipPosition={ToolTip.Bottom} /> </div> </RenderIf> </div> </div> </div> }} </th> </AddDataAttributes> } } module TableHeadingRow = { @react.component let make = ( ~headingArray, ~isHighchartLegend, ~frozenUpto, ~heightHeadingClass, ~tableheadingClass, ~sortedObj, ~setSortedObj, ~filterObj, ~fixedWidthClass, ~setFilterObj, ~headingCenter, ~filterIcon=?, ~filterDropdownClass=?, ~selectAllCheckBox, ~setSelectAllCheckBox, ~isFrozen=false, ~lastHeadingClass="", ~fixLastCol=false, ~headerCustomBgColor=?, ~filterDropdownMaxHeight=?, ~columnFilterRow, ~customizeColumnNewTheme=?, ~tableHeadingTextClass="", ) => { if headingArray->Array.length !== 0 { <thead> <tr> {headingArray ->Array.mapWithIndex((item, i) => { let columnFilterRow: array<filterRow> = columnFilterRow->Option.getOr([]) let filterRow = columnFilterRow->Array.get(i) <TableHeadingCell key={Int.toString(i)} item index=i headingArray isHighchartLegend frozenUpto heightHeadingClass tableheadingClass sortedObj setSortedObj filterObj fixedWidthClass setFilterObj headingCenter ?filterIcon ?filterDropdownClass selectAllCheckBox setSelectAllCheckBox isFrozen lastHeadingClass fixLastCol ?headerCustomBgColor ?filterDropdownMaxHeight filterRow ?customizeColumnNewTheme tableHeadingTextClass /> }) ->React.array} </tr> </thead> } else { React.null } } } @react.component let make = ( ~title="Title", ~heading=[], ~rows, ~offset=0, ~onRowClick=?, ~onRowDoubleClick=?, ~onRowClickPresent=false, ~fullWidth=true, ~removeVerticalLines=true, ~removeHorizontalLines=false, ~evenVertivalLines=false, ~showScrollBar=false, ~setSortedObj=?, ~sortedObj=?, ~setFilterObj=?, ~filterObj=?, ~columnFilterRow=?, ~tableheadingClass="", ~tableBorderClass="", ~tableDataBorderClass="", ~collapseTableRow=false, ~getRowDetails=?, ~actualData=?, ~onExpandClickData as _=?, ~onMouseEnter=?, ~onMouseLeave=?, ~highlightText="", ~heightHeadingClass="h-16", ~frozenUpto=0, ~clearFormatting=false, ~rowHeightClass="", ~isMinHeightRequired=false, ~rowCustomClass="", ~enableEqualWidthCol=false, ~isHighchartLegend=false, ~headingCenter=false, ~filterIcon=?, ~filterDropdownClass=?, ~showHeading=true, ~maxTableHeight="", ~labelMargin="", ~customFilterRowStyle="", ~selectAllCheckBox=?, ~setSelectAllCheckBox=?, ~isEllipsisTextRelative=true, ~customMoneyStyle="", ~ellipseClass="", ~selectedRowColor=?, ~lastHeadingClass="", ~showCheckbox=false, ~lastColClass="", ~fixLastCol=false, ~headerCustomBgColor=?, ~alignCellContent=?, ~minTableHeightClass="", ~filterDropdownMaxHeight=?, ~customizeColumnNewTheme=?, ~customCellColor=?, ~customBorderClass=?, ~showborderColor=true, ~tableHeadingTextClass="", ~nonFrozenTableParentClass="", ~showAutoScroll=false, ~showVerticalScroll=false, ~showPagination=true, ~highlightSelectedRow=false, ) => { let isMobileView = MatchMedia.useMobileChecker() let rowInfo: array<array<cell>> = rows let actualData: option<array<Nullable.t<'t>>> = actualData let numberOfCols = heading->Array.length let (selectedIndex, setSelectedIndex) = React.useState(_ => -1) open Webapi let totalTableWidth = Dom.document ->Dom.Document.getElementById(`table`) ->Option.mapOr(0, ele => ele->Document.offsetWidth) let equalColWidth = (totalTableWidth / numberOfCols)->Int.toString let fixedWidthClass = enableEqualWidthCol ? `${equalColWidth}px` : "" let widthClass = if fullWidth { "min-w-full" } else { "" } let stickCol = {"sticky left-0 z-10"} let scrollBarClass = if showScrollBar { "show-scrollbar" } else { "" } let filterPresent = heading->Array.find(head => head.showFilter)->Option.isSome let highlightEnabledFieldsArray = heading->Array.reduceWithIndex([], (acc, item, index) => { if item.highlightCellOnHover { let _ = Array.push(acc, index) } acc }) let getRowDetails = (rowIndex: int) => { switch actualData { | Some(actualData) => switch getRowDetails { | Some(fn) => fn(actualData->Array.get(rowIndex)->Option.getOr(Nullable.null)) | None => React.null } | None => React.null } } let tableRows = (rowArr, isCustomiseColumn) => { rowArr ->Array.mapWithIndex((item: array<cell>, rowIndex) => { <TableRow title key={Int.toString(offset + rowIndex)} item rowIndex offset onRowClick onRowDoubleClick onRowClickPresent removeVerticalLines removeHorizontalLines evenVertivalLines highlightEnabledFieldsArray tableDataBorderClass collapseTableRow expandedRow={_ => getRowDetails(offset + rowIndex)} onMouseEnter onMouseLeave highlightText clearFormatting rowHeightClass rowCustomClass={`${rowCustomClass} ${isCustomiseColumn ? "opacity-0" : ""}`} fixedWidthClass isHighchartLegend labelMargin isEllipsisTextRelative customMoneyStyle ellipseClass ?selectedRowColor lastColClass fixLastCol ?alignCellContent ?customCellColor selectedIndex setSelectedIndex highlightSelectedRow /> }) ->React.array } let renderTableHeadingRow = (headingArray, isFrozen, isCustomiseColumn, lastHeadingClass) => { let columnFilterRow = switch columnFilterRow { | Some(fitlerRows) => switch isFrozen { | true => Some(fitlerRows->Array.slice(~start=0, ~end=frozenUpto)) | false => Some(fitlerRows->Array.sliceToEnd(~start=frozenUpto)) } | None => None } let tableheadingClass = customizeColumnNewTheme->Option.isSome ? `${tableheadingClass} ${heightHeadingClass}` : tableheadingClass let customizeColumnNewTheme = isCustomiseColumn ? customizeColumnNewTheme : None <TableHeadingRow headingArray isHighchartLegend frozenUpto heightHeadingClass tableheadingClass sortedObj setSortedObj filterObj fixedWidthClass setFilterObj headingCenter ?filterIcon ?filterDropdownClass selectAllCheckBox setSelectAllCheckBox isFrozen lastHeadingClass fixLastCol ?headerCustomBgColor ?filterDropdownMaxHeight columnFilterRow ?customizeColumnNewTheme tableHeadingTextClass /> } let tableFilterRow = (~isFrozen) => { switch columnFilterRow { | Some(fitlerRows) => { let filterRows = switch isFrozen { | true => fitlerRows->Array.slice(~start=0, ~end=frozenUpto) | false => fitlerRows->Array.sliceToEnd(~start=frozenUpto) } <TableFilterRow item=filterRows removeVerticalLines removeHorizontalLines tableDataBorderClass evenVertivalLines customFilterRowStyle showCheckbox /> } | None => React.null } } let frozenHeading = heading->Array.slice(~start=0, ~end=frozenUpto) let frozenCustomiseColumnHeading = [ makeHeaderInfo(~key="", ~title="Customize Column", ~showMultiSelectCheckBox=true), ] let frozenRow = rowInfo->Array.map(row => { row->Array.slice(~start=0, ~end=frozenUpto) }) let remainingHeading = heading->Array.sliceToEnd(~start=frozenUpto) let remaingRow = rowInfo->Array.map(row => { row->Array.sliceToEnd(~start=frozenUpto) }) let frozenTableWidthClass = isMobileView ? "w-48" : "w-auto" let parentBoderColor = "border rounded-lg dark:border-jp-gray-960" let boderColor = !showborderColor ? "" : " dark:border-jp-gray-960" let frozenTable = { <table className={`table-auto ${frozenTableWidthClass} ${parentBoderColor} ${tableBorderClass} ${stickCol}`}> <RenderIf condition=showHeading> {renderTableHeadingRow(frozenHeading, true, false, lastHeadingClass)} </RenderIf> <tbody> {tableFilterRow(~isFrozen=true)} {tableRows(frozenRow, false)} </tbody> </table> } let totalLength = rowInfo->Array.length let customizeColumn = { <table className={`table-auto rounded-lg sticky right-0 !px-0 !py-0 z-10`}> <RenderIf condition=showHeading> {renderTableHeadingRow( frozenCustomiseColumnHeading, true, true, `${lastHeadingClass} rounded-tl-none rounded-tr-lg`, )} </RenderIf> <tbody> {tableRows( Array.fromInitializer(~length=totalLength, i => i + 1)->Array.map(_ => [Text("")]), true, )} </tbody> </table> } let tableBorderClass = if isHighchartLegend { `table-auto ${widthClass}` } else { `table-auto ${widthClass} ${tableBorderClass} ${boderColor} rounded-lg` } let (lclFilterOpen, _) = React.useContext(DataTableFilterOpenContext.filterOpenContext) let nonFrozenTable = { <table id="table" className=tableBorderClass> <RenderIf condition=showHeading> {renderTableHeadingRow(remainingHeading, false, false, `${lastHeadingClass}`)} </RenderIf> <tbody> {tableFilterRow(~isFrozen=false)} {tableRows(remaingRow, false)} </tbody> </table> } let parentMinWidthClass = frozenUpto > 0 ? "min-w-max" : "" let childMinWidthClass = frozenUpto > 0 ? "" : "min-w-full" let overflowClass = lclFilterOpen->Dict.valuesToArray->Array.reduce(false, (acc, item) => item || acc) ? "" : isMinHeightRequired ? "" : "overflow-scroll" let roundedBorders = showPagination ? "rounded-t-lg" : "rounded-lg" let parentBorderRadius = !isHighchartLegend ? `border border-nd_br_gray-150 ${roundedBorders}` : "" let tableScrollbarCss = ` @supports (-webkit-appearance: none) { .table-scrollbar { scrollbar-width: auto; scrollbar-color: #99a0ae; } .table-scrollbar::-webkit-scrollbar { display: block; height: 4px; width: 5px; } .table-scrollbar::-webkit-scrollbar-thumb { background-color: #99a0ae; border-radius: 3px; } .table-scrollbar::-webkit-scrollbar-track { display:none; } } ` let autoscrollcss = showAutoScroll ? "table-scrollbar" : "" let verticalScroll = !showVerticalScroll ? "overflow-y-hidden" : "" <div className={`flex flex-row items-stretch ${scrollBarClass} loadedTable ${parentMinWidthClass} ${customBorderClass->Option.getOr( parentBorderRadius, )}`} style={ minHeight: { minTableHeightClass->LogicUtils.isNonEmptyString ? minTableHeightClass : filterPresent || isMinHeightRequired ? "25rem" : "" }, maxHeight: maxTableHeight, } //replaced "overflow-auto" -> to be tested with master > <RenderIf condition={frozenUpto > 0}> {frozenTable} </RenderIf> <style> {React.string(tableScrollbarCss)} </style> <div className={`flex-1 ${overflowClass} no-scrollbar rounded-lg ${childMinWidthClass} ${nonFrozenTableParentClass} ${autoscrollcss} ${verticalScroll} `}> nonFrozenTable </div> {switch customizeColumnNewTheme { | Some(customizeColumnObj) => <RenderIf condition={customizeColumnObj.customizeColumnUi !== React.null}> {customizeColumn} </RenderIf> | None => React.null }} </div> }
7,352
9,976
hyperswitch-control-center
src/components/NoDataFound.res
.res
type renderType = InfoBox | Painting | NotFound | Locked | LoadError | ExtendDateUI @react.component let make = ( ~title=?, ~message, ~renderType: renderType=InfoBox, ~children=?, ~customCssClass="my-6", ~customBorderClass="", ~customMessageCss="", ~handleClick=?, ) => { let prefix = LogicUtils.useUrlPrefix() let isMobileView = MatchMedia.useMobileChecker() let marginPaddingClass = { let marginPaddingClass = switch renderType { | Painting => "mt-16 p-16" | NotFound => "mt-16 p-5 mb-12" | Locked => "mt-32 p-16" | LoadError => "mt-32 p-16" | InfoBox => "" | ExtendDateUI => "mt-16 p-16" } isMobileView ? "" : marginPaddingClass } let containerClass = `flex flex-col ${marginPaddingClass} container mx-auto items-center` let msgCss = isMobileView ? `text-l text-center mt-4 ${customMessageCss}` : `px-3 text-2xl mt-32 ${customMessageCss}` <AddDataAttributes attributes=[ ("data-component", message->LogicUtils.stringReplaceAll(" ", "-")->String.toLowerCase), ]> {<div className={`${customCssClass} rounded-md`}> {switch title { | Some(val) => <DesktopView> <div className="font-bold text-fs-16 text-jp-gray-900 text-opacity-75 mb-4 mt-4 dark:text-white dark:text-opacity-75"> {React.string(val)} </div> </DesktopView> | None => React.null }} <div className={`border ${customBorderClass} bg-white p-3 pl-5 rounded font-semibold text-jp-gray-900 text-opacity-50 dark:bg-jp-gray-lightgray_background dark:text-jp-gray-text_darktheme dark:text-opacity-50 dark:border-jp-gray-no_data_border`}> {switch renderType { | InfoBox => <div className="flex flex-row items-center"> <Icon name="no_data" size=18 className="opacity-50 hover:opacity-100 dark:brightness-50 dark:opacity-75 dark:invert" /> <div className="px-3 text-fs-16"> {React.string(message)} </div> </div> | Painting => <div className=containerClass> <div className=" mb-8 mt-8 max-w-full h-auto"> <img alt="illustration" src={`/icons/Illustration.svg`} /> </div> <div className={`${msgCss}`}> {React.string(message)} </div> <div> {switch children { | Some(child) => child | None => React.null }} </div> </div> | NotFound => <div className=containerClass> <div className="mb-8 mt-4 max-w-full h-auto"> <img alt="not-found" src={`${prefix}/notfound.svg`} /> </div> <div className="px-3 text-base mt-2"> {React.string(message)} </div> </div> | Locked => <div className=containerClass> <div className="mb-8 mt-8 max-w-full h-auto"> <img alt="locked" src={`/icons/Locked.svg`} /> </div> <div className="px-3 text-base"> {React.string(message)} </div> <div> {switch children { | Some(child) => child | None => React.null }} </div> </div> | LoadError => <div className=containerClass> <div className="mb-8 mt-8 max-w-full h-auto"> <img alt="load-error" src={`/icons/LoadError.svg`} /> </div> <div className="px-3 text-base"> {React.string(message)} </div> <div> {switch children { | Some(child) => child | None => React.null }} </div> </div> | ExtendDateUI => <div className=containerClass> <div className="items-center text-2xl text-black font-bold mb-4"> {message->React.string} </div> {switch handleClick { | Some(fn) => <div> <ACLButton buttonType=Primary onClick=fn text="Expand the search to the previous 90 days" /> <div className="flex justify-center"> <p className="mt-6"> {"Or try the following:"->React.string} <ul className="list-disc"> <li> {"Try a different search parameter"->React.string} </li> <li> {"Adjust or remove filters and search once more"->React.string} </li> </ul> </p> </div> </div> | None => React.null }} </div> }} </div> </div>} </AddDataAttributes> }
1,173
9,977
hyperswitch-control-center
src/components/ACLButton.resi
.resi
@react.component let make: ( ~text: string=?, ~buttonState: Button.buttonState=?, ~buttonType: Button.buttonType=?, ~buttonVariant: Button.buttonVariant=?, ~buttonSize: Button.buttonSize=?, ~leftIcon: Button.iconType=?, ~rightIcon: Button.iconType=?, ~showBorder: bool=?, ~type_: string=?, ~onClick: JsxEvent.Mouse.t => unit=?, ~textStyle: string=?, ~customIconMargin: string=?, ~customTextSize: string=?, ~customIconSize: int=?, ~textWeight: string=?, ~fullLength: bool=?, ~disableRipple: bool=?, ~customButtonStyle: string=?, ~textStyleClass: string=?, ~customTextPaddingClass: string=?, ~allowButtonTextMinWidth: bool=?, ~customPaddingClass: string=?, ~customRoundedClass: string=?, ~customHeightClass: string=?, ~customBackColor: string=?, ~showBtnTextToolTip: bool=?, ~authorization: CommonAuthTypes.authorization=?, ~tooltipText: string=?, ~toolTipPosition: ToolTip.toolTipPosition=?, ) => React.element
283
9,978
hyperswitch-control-center
src/components/DateRangeField.res
.res
let defaultCellHighlighter = (_): Calendar.highlighter => { { highlightSelf: false, highlightLeft: false, highlightRight: false, } } let useErroryValueResetter = (value: string, setValue: (string => string) => unit) => { React.useEffect(() => { let isErroryTimeValue = _ => { try { false } catch { | _error => true } } if value->isErroryTimeValue { setValue(_ => "") } None }, []) } let isStartBeforeEndDate = (start, end) => { 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 startDate = getDate(String.split(start, "-")) let endDate = getDate(String.split(end, "-")) startDate < endDate } module PredefinedOption = { @react.component let make = ( ~predefinedOptionSelected, ~value, ~onClick, ~disableFutureDates, ~disablePastDates, ~todayDayJsObj, ~isoStringToCustomTimeZone, ~isoStringToCustomTimezoneInFloat, ~customTimezoneToISOString, ~todayDate, ~todayTime, ~formatDateTime, ~isTooltipVisible=true, ) => { open DateRangeUtils let optionBG = if predefinedOptionSelected === Some(value) { "bg-blue-100 dark:bg-jp-gray-850 py-2" } else { "bg-transparent md:bg-white md:dark:bg-jp-gray-lightgray_background py-2" } let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, value, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startDate = getFormattedDate(`${stDate}T${stTime}Z`, formatDateTime) let endDate = getFormattedDate(`${enDate}T${enTime}Z`, formatDateTime) let handleClick = _value => { onClick(value, disableFutureDates) } let dateRangeDropdownVal = datetext(value, disableFutureDates) <ToolTip tooltipWidthClass="w-fit" tooltipForWidthClass="!block w-full" description={isTooltipVisible ? `${startDate} - ${endDate}` : ""} toolTipFor={<AddDataAttributes attributes=[("data-daterange-dropdown-value", dateRangeDropdownVal)]> <div> <div className={`${optionBG} mx-2 rounded-md p-2 hover:bg-jp-gray-100 hover:bg-opacity-75 dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 cursor-pointer text-sm font-medium text-grey-900`} onClick=handleClick> {React.string(dateRangeDropdownVal)} </div> </div> </AddDataAttributes>} toolTipPosition=Right contentAlign=Left /> } } module Base = { @react.component let make = ( ~startDateVal: string, ~setStartDateVal: (string => string) => unit, ~endDateVal: string, ~setEndDateVal: (string => string) => unit, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~dateRangeLimit=?, ~optFieldKey as _=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~selectStandardTime=false, ~buttonType=?, ~buttonText="", ~allowedDateRange=?, ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~customborderCSS="", ~isTooltipVisible=true, ~events=?, ) => { open DateRangeUtils open LogicUtils let (isCustomSelected, setIsCustomSelected) = React.useState(_ => predefinedDays->Array.length === 0 ) let formatDateTime = showSeconds ? "MMM DD, YYYY HH:mm:ss" : "MMM DD, YYYY HH:mm" let (showOption, setShowOption) = React.useState(_ => false) let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let isoStringToCustomTimezoneInFloat = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat() let (clickedDates, setClickedDates) = React.useState(_ => []) let (localStartDate, setLocalStartDate) = React.useState(_ => startDateVal) let (localEndDate, setLocalEndDate) = React.useState(_ => endDateVal) let (_localOpt, setLocalOpt) = React.useState(_ => "") let (isDropdownExpanded, setIsDropdownExpanded) = React.useState(_ => false) let (calendarVisibility, setCalendarVisibility) = React.useState(_ => false) let isMobileView = MatchMedia.useMobileChecker() let isFilterSection = React.useContext(TableFilterSectionContext.filterSectionContext) let dropdownPosition = isFilterSection && !isMobileView && isCustomSelected ? "right-0" : "" let todayDayJsObj = React.useMemo(() => { Date.make()->Date.toString->DayJs.getDayJsForString }, [isDropdownExpanded]) let currentTime = todayDayJsObj.format("HH:mm") let todayDate = todayDayJsObj.format("YYYY-MM-DD") let todayTime = React.useMemo(() => { todayDayJsObj.format("HH:mm:ss") }, [currentTime]) let initialStartTime = disableFutureDates || selectStandardTime ? "00:00:00" : "23:59:59" let initialEndTime = disableFutureDates || selectStandardTime ? "23:59:59" : "00:00:00" React.useEffect(() => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) setLocalOpt(_ => "") None }, (startDateVal, endDateVal)) let resetStartEndInput = () => { setLocalStartDate(_ => "") setLocalEndDate(_ => "") setLocalOpt(_ => "") } let handleEvent = React.useCallback(() => { switch events { | Some(fn) => fn() | _ => () } }, [events]) React.useEffect(() => { switch dateRangeLimit { | Some(maxLen) => { let diff = getStartEndDiff(localStartDate, localEndDate) if diff > (maxLen->Int.toFloat *. 24. *. 60. *. 60. -. 1.) *. 1000. { resetStartEndInput() } } | None => () } None }, (localStartDate, localEndDate)) React.useEffect(() => { if isDropdownExpanded == true { handleEvent() } None }, [isDropdownExpanded]) let dateRangeRef = React.useRef(Nullable.null) let dropdownRef = React.useRef(Nullable.null) useErroryValueResetter(startDateVal, setStartDateVal) useErroryValueResetter(endDateVal, setEndDateVal) let startDate = localStartDate->getDateStringForValue(isoStringToCustomTimeZone) let endDate = localEndDate->getDateStringForValue(isoStringToCustomTimeZone) let isDropdownExpandedActual = isDropdownExpanded && calendarVisibility let dropdownVisibilityClass = if isDropdownExpandedActual { "inline-block" } else { "hidden" } let saveDates = () => { if localStartDate->isNonEmptyString && localEndDate->isNonEmptyString { setStartDateVal(_ => localStartDate) setEndDateVal(_ => localEndDate) } } let resetToInitalValues = () => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) setLocalOpt(_ => "") } OutsideClick.useOutsideClick( ~refs=ArrayOfRef([dateRangeRef, dropdownRef]), ~isActive=isDropdownExpanded || calendarVisibility, ~callback=() => { setIsDropdownExpanded(_ => false) setCalendarVisibility(p => !p) if isDropdownExpandedActual && isCustomSelected { resetToInitalValues() } }, ) let changeEndDate = (ele, isFromCustomInput, time) => { if disableApply { setIsDropdownExpanded(_ => false) } if localEndDate == ele && isFromCustomInput { setEndDateVal(_ => "") } else { let endDateSplit = String.split(ele, "-") let endDateDate = endDateSplit[2]->Option.getOr("") let endDateYear = endDateSplit[0]->Option.getOr("") let endDateMonth = endDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if disableFutureDates && ele == todayDate { todayTime } else { initialEndTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let endDateTimeCheck = customTimezoneToISOString( endDateYear, endDateMonth, endDateDate, timeHour, timeMinute, timeSecond, ) setLocalEndDate(_ => TimeZoneHook.formattedISOString(endDateTimeCheck, format)) } } let changeStartDate = (ele, isFromCustomInput, time) => { let setDate = str => { let startDateSplit = String.split(str, "-") let startDateDay = startDateSplit[2]->Option.getOr("") let startDateYear = startDateSplit[0]->Option.getOr("") let startDateMonth = startDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if !disableFutureDates && ele == todayDate && !standardTimeToday { todayTime } else { initialStartTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let startDateTimeCheck = customTimezoneToISOString( startDateYear, startDateMonth, startDateDay, timeHour, timeMinute, timeSecond, ) setLocalStartDate(_ => TimeZoneHook.formattedISOString(startDateTimeCheck, format)) } let resetStartDate = () => { resetStartEndInput() setDate(ele) } if startDate->isNonEmptyString && startDate == ele && isFromCustomInput { changeEndDate(ele, isFromCustomInput, None) } else if startDate->isNonEmptyString && startDate > ele && isFromCustomInput { resetStartDate() } else if endDate->isNonEmptyString && startDate == ele && isFromCustomInput { resetStartDate() } else if ( ele > startDate && ele < endDate && startDate->isNonEmptyString && endDate->isNonEmptyString && isFromCustomInput ) { resetStartDate() } else if ( startDate->isNonEmptyString && endDate->isNonEmptyString && ele > endDate && isFromCustomInput ) { resetStartDate() } else { () } if !isFromCustomInput || startDate->isEmptyString { setDate(ele) } if ( (startDate->isNonEmptyString && endDate->isEmptyString && !isFromCustomInput) || (startDate->isNonEmptyString && endDate->isEmptyString && isStartBeforeEndDate(startDate, ele) && isFromCustomInput) ) { changeEndDate(ele, isFromCustomInput, None) } } let onDateClick = str => { let data = switch Array.find(clickedDates, x => x == str) { | Some(_d) => Belt.Array.keep(clickedDates, x => x != str) | None => Array.concat(clickedDates, [str]) } let dat = data->Array.map(x => x) setClickedDates(_ => dat) changeStartDate(str, true, None) } let handleApply = _ => { setShowOption(_ => false) setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) saveDates() } let cancelButton = _ => { resetToInitalValues() setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) } let selectedStartDate = if localStartDate->isNonEmptyString { getFormattedDate( localStartDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD", ) } else { "" } let selectedEndDate = if localEndDate->isNonEmptyString { getFormattedDate(localEndDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD") } else { "" } let setStartDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalStartDate(_ => timestamp) } } let setEndDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalEndDate(_ => timestamp) } } let startTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let startTimeVal = timeValEv->Identity.formReactEventToString let endTime = localEndDate->getTimeStringForValue(isoStringToCustomTimeZone) if localStartDate->isNonEmptyString { if disableFutureDates && selectedStartDate == todayDate && startTimeVal > todayTime { setStartDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && startTimeVal > endTime ) { () } else { setStartDate(~date=startDate, ~time=startTimeVal) } } }, onFocus: _ => (), value: localStartDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let endTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let endTimeVal = timeValEv->Identity.formReactEventToString let startTime = localStartDate->getTimeStringForValue(isoStringToCustomTimeZone) if localEndDate->isNonEmptyString { if disableFutureDates && selectedEndDate == todayDate && endTimeVal > todayTime { setEndDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && endTimeVal < startTime ) { () } else { setEndDate(~date=endDate, ~time=endTimeVal) } } }, onFocus: _ => (), value: localEndDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let startDateStr = startDateVal->isNonEmptyString ? getFormattedDate( startDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? buttonText : "[From-Date]" let endDateStr = endDateVal->isNonEmptyString ? getFormattedDate( endDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? "" : "[To-Date]" let startTimeStr = startDateVal->isNonEmptyString ? startDateVal->getTimeStringForValue(isoStringToCustomTimeZone) : "00:00:00" let endTimeStr = startDateVal->isNonEmptyString ? endDateVal->getTimeStringForValue(isoStringToCustomTimeZone) : "23:59:59" let endTimeStr = { let timeArr = endTimeStr->String.split(":") let endTimeTxt = `${timeArr[0]->Option.getOr("00")}:${timeArr[1]->Option.getOr("00")}` showSeconds ? `${endTimeTxt}:${timeArr[2]->Option.getOr("00")}` : endTimeTxt } let startTimeStr = { let timeArr = startTimeStr->String.split(":") let startTimeTxt = `${timeArr[0]->Option.getOr("00")}:${timeArr[1]->Option.getOr("00")}` showSeconds ? `${startTimeTxt}:${timeArr[2]->Option.getOr("00")}` : startTimeTxt } let tooltipText = { startDateVal->isEmptyString && endDateVal->isEmptyString ? `Select Date ${showTime ? "and Time" : ""}` : showTime ? `${startDateStr} ${startTimeStr} - ${endDateStr} ${endTimeStr}` : endDateVal->isEmptyString ? `${startDateStr} - Now` : `${startDateStr} ${startDateStr === buttonText ? "" : "-"} ${endDateStr}` } let buttonIcon = isDropdownExpanded ? "angle-up" : "angle-down" let handlePredefinedOptionClick = (value, disableFutureDates) => { setIsCustomSelected(_ => false) setCalendarVisibility(_ => false) setIsDropdownExpanded(_ => false) setShowOption(_ => false) let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, value, disableFutureDates, disablePastDates, todayDate, todayTime, ) resetStartEndInput() setStartDate(~date=startDate, ~time=stTime) setEndDate(~date=endDate, ~time=enTime) setLocalOpt(_ => DateRangeUtils.datetext(value, disableFutureDates) ->String.toLowerCase ->String.split(" ") ->Array.joinWith("_") ) changeStartDate(stDate, false, Some(stTime)) changeEndDate(enDate, false, Some(enTime)) } let handleDropdownClick = () => { if predefinedDays->Array.length > 0 { if calendarVisibility { setCalendarVisibility(_ => false) setShowOption(_ => !isDropdownExpanded) setIsDropdownExpanded(_ => !isDropdownExpanded) setShowOption(_ => !isCustomSelected) } else { setIsDropdownExpanded(_ => true) setShowOption(_ => true) setCalendarVisibility(_ => true) } } else { setIsDropdownExpanded(_p => !isDropdownExpanded) setCalendarVisibility(_ => !isDropdownExpanded) } } React.useEffect(() => { if startDate->isNonEmptyString && endDate->isNonEmptyString { if ( localStartDate->isNonEmptyString && localEndDate->isNonEmptyString && (disableApply || !isCustomSelected) ) { saveDates() } if disableApply { setShowOption(_ => false) } } None }, (startDate, endDate, localStartDate, localEndDate)) let customStyleForBtn = "rounded-lg bg-white w-fit" let timeVisibilityClass = showTime ? "block" : "hidden" let getDiffForPredefined = predefinedDay => { let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, predefinedDay, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startTimestamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) let endTimestamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) getStartEndDiff(startTimestamp, endTimestamp) } let getPredefinedValues = predefinedDay => { let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, predefinedDay, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startTimestamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) let endTimestamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) (startTimestamp, endTimestamp) } let predefinedOptionSelected = predefinedDays->Array.find(item => { let startDate = convertTimeStamp( ~isoStringToCustomTimeZone, startDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let endDate = convertTimeStamp( ~isoStringToCustomTimeZone, endDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let (startTimestamp, endTimestamp) = getPredefinedValues(item) let prestartDate = convertTimeStamp( ~isoStringToCustomTimeZone, startTimestamp, "YYYY-MM-DDTHH:mm:00[Z]", ) let preendDate = convertTimeStamp( ~isoStringToCustomTimeZone, endTimestamp, "YYYY-MM-DDTHH:mm:00[Z]", ) startDate == prestartDate && endDate == preendDate }) let buttonText = switch predefinedOptionSelected { | Some(value) => DateRangeUtils.datetext(value, disableFutureDates) | None => startDateVal->isEmptyString && endDateVal->isEmptyString ? `Select Date` : endDateVal->isEmptyString ? `${startDateStr} - Now` : `${startDateStr} ${startDateStr === buttonText ? "" : "-"} ${endDateStr}` } let filteredPredefinedDays = { switch dateRangeLimit { | Some(limit) => predefinedDays->Array.filter(item => { getDiffForPredefined(item) <= (limit->Float.fromInt *. 24. *. 60. *. 60. -. 1.) *. 1000. }) | None => predefinedDays } } let customeRangeBg = switch predefinedOptionSelected { | Some(_) => "bg-white dark:bg-jp-gray-lightgray_background" | None => "bg-jp-gray-100 dark:bg-jp-gray-850" } let removeApplyFilter = ev => { ev->ReactEvent.Mouse.stopPropagation resetToInitalValues() setStartDateVal(_ => "") setEndDateVal(_ => "") } let buttonType: option<Button.buttonType> = buttonType let arrowIconSize = 14 let strokeColor = if disable { "stroke-jp-2-light-gray-600" } else if isDropdownExpandedActual { "stroke-jp-2-light-gray-1700" } else { "stroke-jp-2-light-gray-1100" } let iconElement = { <div className="flex flex-row gap-2"> <Icon className=strokeColor name=buttonIcon size=arrowIconSize /> {if removeFilterOption && startDateVal->isNonEmptyString && endDateVal->isNonEmptyString { <Icon name="crossicon" size=16 onClick=removeApplyFilter /> } else { React.null }} </div> } let calendarElement = <div className={`flex md:flex-row flex-col w-full py-2`}> {if predefinedDays->Array.length > 0 && showOption { <AddDataAttributes attributes=[("data-date-picker-predifined", "predefined-options")]> <div className="flex flex-wrap gap-1 md:flex-col"> {filteredPredefinedDays ->Array.mapWithIndex((value, i) => { <div key={i->Int.toString} className="w-1/3 md:w-full md:min-w-max text-center md:text-start"> <PredefinedOption predefinedOptionSelected value onClick=handlePredefinedOptionClick disableFutureDates disablePastDates todayDayJsObj isoStringToCustomTimeZone isoStringToCustomTimezoneInFloat customTimezoneToISOString todayDate todayTime formatDateTime isTooltipVisible /> </div> }) ->React.array} <AddDataAttributes attributes=[("data-daterange-dropdown-value", "Custom Range")]> <div className={`text-center md:text-start min-w-max bg-white dark:bg-jp-gray-lightgray_background w-1/3 hover:bg-jp-gray-100 hover:bg-opacity-75 dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 cursor-pointer mx-2 rounded-md p-2 text-sm font-medium text-grey-900 ${customeRangeBg}}`} onClick={_ => { setCalendarVisibility(_ => true) setIsCustomSelected(_ => true) }}> {React.string("Custom Range")} </div> </AddDataAttributes> </div> </AddDataAttributes> } else { React.null }} <AddDataAttributes attributes=[("data-date-picker-section", "date-picker-calendar")]> <div className={calendarVisibility && isCustomSelected ? "w-auto md:w-max h-auto" : "hidden"}> <CalendarList count=numMonths cellHighlighter=defaultCellHighlighter startDate endDate onDateClick disablePastDates disableFutureDates ?dateRangeLimit calendarContaierStyle="md:mx-3 md:my-1 border-0 md:border" ?allowedDateRange /> <div className={`${timeVisibilityClass} w-full flex flex-row md:gap-4 p-3 justify-around md:justify-start dark:text-gray-400 text-gray-700 `}> <TimeInput input=startTimeInput showSeconds label="From" /> <TimeInput input=endTimeInput showSeconds label="To" /> </div> {if disableApply { React.null } else { <div id="neglectTopbarTheme" className="flex flex-row flex-wrap gap-3 bg-white dark:bg-jp-gray-lightgray_background px-3 mt-3 mb-1 align-center justify-end "> <Button text="Cancel" buttonType=Secondary buttonState=Normal buttonSize=Small onClick={cancelButton} /> <Button text="Apply" buttonType=Primary buttonState={endDate->LogicUtils.isEmptyString ? Disabled : Normal} buttonSize=Small onClick={handleApply} /> </div> }} </div> </AddDataAttributes> </div> open HeadlessUI <> <div className={"md:relative daterangSelection"}> <AddDataAttributes attributes=[ ("data-date-picker", `dateRangePicker${isFilterSection ? "-Filter" : ""}`), ("data-date-picker-start-date", `${startDateStr} ${startTimeStr}`), ("data-date-picker-end-date", `${endDateStr} ${endTimeStr}`), ]> <div ref={dateRangeRef->ReactDOM.Ref.domRef}> <ToolTip description={tooltipText} toolTipFor={<Button dataTestId="date-range-selector" text={isMobileView && textHideInMobileView ? "" : buttonText} leftIcon={CustomIcon(<Icon name="calendar-filter" size=22 />)} rightIcon={CustomIcon(iconElement)} buttonSize=Large isDropdownOpen=isDropdownExpandedActual onClick={_ => handleDropdownClick()} iconBorderColor={customborderCSS} customButtonStyle={customStyleForBtn} buttonState={disable ? Disabled : Normal} ?buttonType ?textStyle />} justifyClass="justify-end" toolTipPosition={Top} /> </div> </AddDataAttributes> {if isDropdownExpandedActual { if isMobileView { <BottomModal headerText={buttonText} onCloseClick={cancelButton}> calendarElement </BottomModal> } else { <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" show={isDropdownExpandedActual} leaveTo="transform opacity-0 scale-95"> <div ref={dropdownRef->ReactDOM.Ref.domRef} className={`${dropdownVisibilityClass} absolute ${dropdownPosition} z-20 max-h-min max-w-min overflow-auto bg-white dark:bg-jp-gray-950 rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none mt-2 right-0`}> calendarElement </div> </Transition> } } else { React.null }} </div> </> } } let useStateForInput = (input: ReactFinalForm.fieldRenderPropsInput) => { React.useMemo(() => { let val = input.value->JSON.Decode.string->Option.getOr("") let onChange = fn => { let newVal = fn(val) input.onChange(newVal->Identity.stringToFormReactEvent) } (val, onChange) }, [input]) } @react.component let make = ( ~startKey: string, ~endKey: string, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~dateRangeLimit=?, ~optFieldKey=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~allowedDateRange=?, ~selectStandardTime=false, ~buttonText="", ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~isTooltipVisible=true, ~events=?, ) => { let startInput = ReactFinalForm.useField(startKey).input let endInput = ReactFinalForm.useField(endKey).input let (startDateVal, setStartDateVal) = useStateForInput(startInput) let (endDateVal, setEndDateVal) = useStateForInput(endInput) <Base startDateVal setStartDateVal endDateVal setEndDateVal showTime disable disablePastDates disableFutureDates predefinedDays format numMonths disableApply removeFilterOption ?dateRangeLimit ?optFieldKey textHideInMobileView showSeconds hideDate selectStandardTime buttonText ?allowedDateRange ?textStyle standardTimeToday removeConversion isTooltipVisible ?events /> }
7,267
9,979
hyperswitch-control-center
src/components/DynamicTabs.res
.res
type tab = { title: string, value: string, isRemovable: bool, description?: string, } let getValueFromArrayTab = (tabsVal: array<tab>, index: int) => { switch tabsVal->Array.get(index) { | Some(val) => val.value | None => "" } } 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" let setTabScroll = ( firstTabRef, lastTabRef, scrollRef, setIsLeftArrowVisible, setIsRightArrowVisible, getBoundingRectInfo, ) => { 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 >= 1 setIsLeftArrowVisible(_ => newIsLeftArrowVisible) setIsRightArrowVisible(_ => newIsRightArrowVisible) } module TabInfo = { @react.component let make = ( ~title, ~isSelected, ~index, ~isRemovable, ~setCollapsibleTabs, ~selectedIndex, ~tabNames, ~handleSelectedTab: (~tabValue: string, ~collapsibleTabs: array<tab>, ~removed: bool) => unit, ~tabStacksnames, ~setTabStacksnames, ~description="", ) => { let fontClass = "font-inter-style" let defaultThemeBasedClass = `${fontClass} px-6` let defaultClasses = `font-semibold ${defaultThemeBasedClass} w-max flex flex-auto flex-row items-center justify-center text-body mb-1` let selectionClasses = if isSelected { "font-semibold text-black" } else { "text-jp-gray-700 dark:text-jp-gray-tabset_gray dark:text-opacity-75 hover:text-jp-gray-800 dark:hover:text-opacity-100 font-medium" } let handleClick = React.useCallback(_ => { handleSelectedTab( ~tabValue={ switch tabNames->Array.get(index) { | Some(tab) => tab.value | None => getValueFromArrayTab(tabNames, 0) } }, ~collapsibleTabs=tabNames, ~removed=false, ) }, (index, handleSelectedTab)) let bottomBorderColor = "" let borderClass = "" let lineStyle = "bg-black w-full h-0.5 rounded-full" let crossIcon = switch isRemovable { | true => <svg onClick={ev => { ReactEvent.Mouse.stopPropagation(ev) ReactEvent.Mouse.preventDefault(ev) setTabStacksnames(prev => { let updatedStackAfterRemovingTab = prev->Array.copy->Array.filter(item => item !== getValueFromArrayTab(tabNames, index)) updatedStackAfterRemovingTab->Array.filterWithIndex((item, index) => index === 0 ? true : item !== updatedStackAfterRemovingTab->Array.get(index - 1)->Option.getOr("") ) }) let updatedTabNames = tabNames->Array.copy->Array.filterWithIndex((_, i) => i !== index) setCollapsibleTabs(_ => updatedTabNames) if selectedIndex === index { // if selected index is removed then url will be updated and to the previous tab in the tabstack or else just the removal of the current tab would do if Array.length(tabStacksnames) >= 1 { handleSelectedTab( ~tabValue={ switch tabStacksnames->Array.pop { | Some(tabName) => tabName | None => getValueFromArrayTab(updatedTabNames, 0) } }, ~collapsibleTabs=updatedTabNames, ~removed=true, ) } else { handleSelectedTab( ~tabValue=getValueFromArrayTab(updatedTabNames, 0), ~collapsibleTabs=updatedTabNames, ~removed=true, ) } } else { handleSelectedTab( ~tabValue=getValueFromArrayTab(updatedTabNames, 0), ~collapsibleTabs=updatedTabNames, ~removed=true, ) } }} style={marginLeft: "15px"} height="10" width="10" fill="none" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"> <path d="M11.8339 1.34102L10.6589 0.166016L6.00057 4.82435L1.34224 0.166016L0.167236 1.34102L4.82557 5.99935L0.167236 10.6577L1.34224 11.8327L6.00057 7.17435L10.6589 11.8327L11.8339 10.6577L7.17557 5.99935L11.8339 1.34102Z" fill="#7c7d82" /> </svg> | _ => React.null } let tab = <div className="flex flex-col"> <div className={`${defaultClasses} ${selectionClasses}`} onClick={handleClick}> {React.string( title ->String.split("+") ->Array.map(String.trim) ->Array.map(LogicUtils.snakeToTitle) ->Array.joinWith(" + "), )} crossIcon </div> <div /> <RenderIf condition={isSelected}> <FramerMotion.Motion.Div className=lineStyle layoutId="underline" /> </RenderIf> <RenderIf condition={!isSelected}> <div className="w-full h-0.5 rounded-full" /> </RenderIf> </div> <div className={`flex flex-row cursor-pointer pt-0.5 pb-0 ${borderClass} ${bottomBorderColor} items-center h-14`}> {tab} </div> } } module IndicationArrow = { @react.component let make = (~iconName, ~side, ~refElement: React.ref<Js.nullable<Dom.element>>, ~isVisible) => { let isMobileView = MatchMedia.useMobileChecker() let onClick = { _ => refElement.current ->Nullable.toOption ->Option.forEach(input => input->(scrollIntoView(_, {behavior: "smooth", block: "nearest", inline: "nearest"})) ) } let roundness = side == "left" ? "rounded-tr-md ml-2" : "rounded-tl-md" let className = { if isVisible { `mt-auto mb-1.5 ${roundness} drop-shadow-md` } else { "hidden" } } <RenderIf condition={isMobileView}> <div className> <Button buttonType=Secondary buttonState={isVisible ? Normal : Disabled} leftIcon={FontAwesome(iconName)} onClick flattenBottom=true /> </div> </RenderIf> } } 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>, ~disableIndicationArrow=false, ~tabContainerClass="", ~showBorder=true, ~maxSelection=1, ~tabId="", ~setActiveTab: string => unit, ~updateUrlDict=?, ~initalTab: option<array<string>>=?, ~defaultTabs: option<array<tab>>=?, ~enableDescriptionHeader: bool=false, ~toolTipDescription="Add more tabs", ~updateCollapsableTabs=false, ~showAddMoreTabs=true, ) => { open LogicUtils let eulerBgClass = "bg-jp-gray-100 dark:bg-jp-gray-darkgray_background" let bgClass = eulerBgClass // this tabs will always loaded independent of user preference let isMobileView = MatchMedia.useMobileChecker() let defaultTabs = defaultTabs->Option.getOr(tabs->Array.copy->Array.filter(item => !item.isRemovable)) let tabOuterClass = `gap-1.5` let bottomBorderClass = "" let outerAllignmentClass = "" let availableTabUserPrefKey = `dynamicTab_available_tab_${tabId}` let updateTabNameWith = switch updateUrlDict { | Some(fn) => fn | None => _ => () } let {addConfig, getConfig} = React.useContext(UserPrefContext.userPrefContext) let {filterValueJson} = React.useContext(FilterContext.filterContext) let getTabNames = filterValueJson let getTitle = key => { ( tabs ->Array.filter(item => { item.value == key }) ->Array.get(0) ->Option.getOr({title: "", value: "", isRemovable: false}) ).title } let (tabsDetails, setTabDetails) = React.useState(_ => tabs->Array.copy) let (selectedIndex, setSelectedIndex) = React.useState(_ => 0) let (initialIndex, updatedCollapsableTabs) = React.useMemo(() => { let defautTabValues = defaultTabs->Array.map(item => item.value) let collapsibleTabs = switch getConfig(availableTabUserPrefKey) { | Some(jsonVal) => { let tabsFromPreference = jsonVal ->getStrArryFromJson ->Array.filter(item => !(defautTabValues->Array.includes(item))) let tabsFromPreference = Array.concat(defautTabValues, tabsFromPreference)->Array.map(item => item->String.split(",") ) tabsFromPreference->Belt.Array.keepMap(tabName => { let tabName = tabName->getUniqueArray let validated = tabName ->Array.filter(item => !(tabs->Array.map(item => item.value)->Array.includes(item))) ->Array.length === 0 let concatinatedTabNames = tabName->Array.map(getTitle)->Array.joinWith(" + ") if validated && tabName->Array.length <= maxSelection && tabName->Array.length > 0 { let newTab = { title: concatinatedTabNames, value: tabName->Array.joinWith(","), description: switch tabs->Array.find( item => { item.value === tabName->Array.joinWith(",") }, ) { | Some(tabValue) => enableDescriptionHeader ? tabValue.description->Option.getOr("") : "" | None => "" }, isRemovable: switch tabs->Array.find( item => { item.value === tabName->Array.joinWith(",") }, ) { | Some(tabValue) => tabValue.isRemovable | None => true }, } Some(newTab) } else { None } }) } | None => defaultTabs } let tabName = switch initalTab { | Some(value) => value | None => getTabNames->getStrArrayFromDict("tabName", [])->Array.filter(item => item->isNonEmptyString) } let tabName = tabName->LogicUtils.getUniqueArray let validated = tabName ->Array.filter(item => !(tabs->Array.map(item => item.value)->Array.includes(item))) ->Array.length === 0 let concatinatedTabNames = tabName->Array.map(getTitle)->Array.joinWith(" + ") if validated && tabName->Array.length <= maxSelection && tabName->Array.length > 0 { let concatinatedTabIndex = collapsibleTabs->Array.map(item => item.title)->Array.indexOf(concatinatedTabNames) if concatinatedTabIndex === -1 { let newTab = [ { title: concatinatedTabNames, value: tabName->Array.joinWith(","), isRemovable: true, }, ] let updatedColllapsableTab = Array.concat(collapsibleTabs, newTab) setTabDetails(_ => Array.concat(tabsDetails, newTab)) (Array.length(collapsibleTabs), updatedColllapsableTab) } else { (concatinatedTabIndex, collapsibleTabs) } } else { setSelectedIndex(_ => 0) (0, collapsibleTabs) } }, [updateCollapsableTabs]) let (collapsibleTabs, setCollapsibleTabs) = React.useState(_ => updatedCollapsableTabs) let (formattedOptions, setFormattedOptions) = React.useState(_ => []) React.useEffect(_ => { setSelectedIndex(_ => initialIndex) None }, [initialIndex]) React.useEffect(_ => { setCollapsibleTabs(_ => updatedCollapsableTabs) None }, [updatedCollapsableTabs]) // this will update the current available tabs to the userpreference React.useEffect(() => { let collapsibleTabsValues = collapsibleTabs ->Array.map(item => { item.value->JSON.Encode.string }) ->JSON.Encode.array addConfig(availableTabUserPrefKey, collapsibleTabsValues) None }, [collapsibleTabs]) let (tabStacksnames, setTabStacksnames) = React.useState(_ => [ getValueFromArrayTab(updatedCollapsableTabs, 0), getValueFromArrayTab(updatedCollapsableTabs, 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 onScroll = _ => { setTabScroll( firstTabRef, lastTabRef, scrollRef, setIsLeftArrowVisible, setIsRightArrowVisible, getBoundingRectInfo, ) } let (showModal, setShowModal) = React.useState(() => false) let handleSelectedTab: ( ~tabValue: string, ~collapsibleTabs: array<tab>, ~removed: bool, ) => unit = (~tabValue: string, ~collapsibleTabs: array<tab>, ~removed: bool) => { if !removed { if ( tabValue !== tabStacksnames->Array.get(tabStacksnames->Array.length - 1)->Option.getOr("") ) { setTabStacksnames(prev => { Array.concat(prev, [tabValue]) }) } updateTabNameWith(Dict.fromArray([("tabName", `[${tabValue}]`)])) setActiveTab(tabValue) setSelectedIndex(_ => Math.Int.max(0, collapsibleTabs->Array.map(item => item.value)->Array.indexOf(tabValue)) ) } else { updateTabNameWith( Dict.fromArray([ ( "tabName", `[${tabStacksnames->Array.get(tabStacksnames->Array.length - 1)->Option.getOr("")}]`, ), ]), ) setActiveTab(tabStacksnames->Array.get(tabStacksnames->Array.length - 1)->Option.getOr("")) setSelectedIndex(_ => Math.Int.max( 0, collapsibleTabs ->Array.map(item => item.value) ->Array.indexOf( tabStacksnames->Array.get(tabStacksnames->Array.length - 1)->Option.getOr(""), ), ) ) } } let onSubmit = values => { let tabName = values->Array.map(getTitle)->Array.joinWith(" + ") let tabValue = values->Array.joinWith(",") if !Array.includes(collapsibleTabs->Array.map(item => item.title), tabName) { let newTab = [ { title: tabName, value: tabValue, isRemovable: true, }, ] let updatedCollapsableTabs = Array.concat(collapsibleTabs, newTab) setCollapsibleTabs(_ => updatedCollapsableTabs) setTabDetails(_ => Array.concat(tabsDetails, newTab)) setSelectedIndex(_ => Array.length(updatedCollapsableTabs) - 1) setTabStacksnames(prev => Array.concat(prev, [getValueFromArrayTab(newTab, 0)])) updateTabNameWith(Dict.fromArray([("tabName", `[${getValueFromArrayTab(newTab, 0)}]`)])) setActiveTab(getValueFromArrayTab(newTab, 0)) setTimeout(_ => { lastTabRef.current ->Nullable.toOption ->Option.forEach(input => input->(scrollIntoView(_, {behavior: "smooth", block: "nearest", inline: "start"})) ) }, 200)->ignore } else { setSelectedIndex(_ => Array.indexOf(collapsibleTabs->Array.map(item => item.value), tabValue)) updateTabNameWith(Dict.fromArray([("tabName", `[${values->Array.joinWith(",")}]`)])) setActiveTab(values->Array.joinWith(",")) } setShowModal(_ => false) } React.useEffect(() => { let options = tabs ->Array.filter(tab => !(tab.value->String.split(",")->Array.length > 1)) ->Array.map((x): SelectBox.dropdownOption => { switch x.description { | Some(description) => { label: x.title, value: x.value, icon: CustomRightIcon( description->LogicUtils.isNonEmptyString ? <ToolTip customStyle="-mr-1.5" arrowCustomStyle={isMobileView ? "" : "ml-1.5"} description toolTipPosition={ToolTip.BottomLeft} justifyClass="ml-2 h-auto mb-0.5" /> : React.null, ), } | _ => {label: x.title, value: x.value} } }) setFormattedOptions(_ => options) None }, [collapsibleTabs]) let addBtnTextStyle = "text-md text-black !px-0 mx-0" let headerTextClass = None <div className={isMobileView ? `sticky top-0 z-15 ${bgClass}` : ""}> <ErrorBoundary> <div className="py-0 flex flex-row"> <RenderIf condition={!isMobileView}> <IndicationArrow iconName="caret-left" side="left" refElement=firstTabRef isVisible=isLeftArrowVisible /> </RenderIf> <div className={`overflow-x-auto no-scrollbar overflow-y-hidden ${outerAllignmentClass}`} ref={scrollRef->ReactDOM.Ref.domRef} onScroll> <div className="flex flex-row"> <div className={`flex flex-row mt-5 ${tabOuterClass} ${tabContainerClass}`}> {collapsibleTabs ->Array.mapWithIndex((tab, i) => { let ref = if i == 0 { firstTabRef->ReactDOM.Ref.domRef->Some } else { setTimeout(_ => { setTabScroll( firstTabRef, lastTabRef, scrollRef, setIsLeftArrowVisible, setIsRightArrowVisible, getBoundingRectInfo, ) }, 200)->ignore lastTabRef->ReactDOM.Ref.domRef->Some } <div ?ref key={Int.toString(i)}> <TabInfo title={tab.title} isSelected={selectedIndex === i} index={i} isRemovable={tab.isRemovable} setCollapsibleTabs selectedIndex tabNames=collapsibleTabs handleSelectedTab tabStacksnames setTabStacksnames description=?{tab.description} /> </div> }) ->React.array} </div> <div className={disableIndicationArrow ? "hidden" : "block"} /> </div> </div> <div className="flex flex-row"> <RenderIf condition={!isMobileView}> <IndicationArrow iconName="caret-right" side="right" refElement=lastTabRef isVisible=isRightArrowVisible /> </RenderIf> <RenderIf condition={showAddMoreTabs && formattedOptions->Array.length > 0}> <div className="flex flex-row" style={marginTop: "20px", marginLeft: "7px"}> <ToolTip description=toolTipDescription toolTipFor={<Button text="+" buttonType={Secondary} buttonSize=Small customButtonStyle="!w-10" textStyle=addBtnTextStyle onClick={_ => setShowModal(_ => true)} />} toolTipPosition=Top tooltipWidthClass="w-fit" /> </div> </RenderIf> </div> </div> <SelectModal modalHeading="Add Segment" modalHeadingDescription={`You can select up to ${maxSelection->Int.toString} options`} ?headerTextClass showModal setShowModal onSubmit initialValues=[] options=formattedOptions submitButtonText="Add Segment" showSelectAll=false showDeSelectAll=true maxSelection headerClass="h-fit" /> <div className=bottomBorderClass /> </ErrorBoundary> </div> }
4,911
9,980
hyperswitch-control-center
src/components/InputFields.resi
.resi
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: string, ~deselectDisable: bool=?, ~isHorizontal: bool=?, ~disableSelect: bool=?, ~fullLength: bool=?, ~customButtonStyle: string=?, ~textStyle: string=?, ~marginTop: string=?, ~customStyle: string=?, ~searchable: bool=?, ~showBorder: bool=?, ~showToolTipOptions: bool=?, ~textEllipsisForDropDownOptions: bool=?, ~showCustomBtnAtEnd: bool=?, ~dropDownCustomBtnClick: bool=?, ~addDynamicValue: bool=?, ~showMatchingRecordsText: bool=?, ~fixedDropDownDirection: SelectBox.direction=?, ~customButton: React.element=?, ~buttonType: Button.buttonType=?, ~dropdownCustomWidth: string=?, ~allowButtonTextMinWidth: bool=?, ~setExtSearchString: ('a => string) => unit=?, ~textStyleClass: string=?, ~ellipsisOnly: bool=?, ~showBtnTextToolTip: bool=?, ~dropdownClassName: string=?, ~descriptionOnHover: bool=?, ~buttonSize: Button.buttonSize=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'b) => React.element let infraSelectInput: ( ~options: array<SelectBox.dropdownOption>, ~deselectDisable: bool=?, ~borderRadius: string=?, ~selectedClass: string=?, ~nonSelectedClass: string=?, ~showTickMark: bool=?, ~allowMultiSelect: bool=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let filterMultiSelectInput: ( ~options: array<FilterSelectBox.dropdownOption>, ~optionSize: CheckBoxIcon.size=?, ~buttonText: string, ~buttonSize: Button.buttonSize=?, ~hideMultiSelectButtons: bool=?, ~allowMultiSelect: bool=?, ~showSelectionAsChips: bool=?, ~showToggle: bool=?, ~isDropDown: bool=?, ~searchable: bool=?, ~showBorder: bool=?, ~optionRigthElement: React.element=?, ~customStyle: string=?, ~customMargin: string=?, ~customButtonStyle: string=?, ~hideBorder: bool=?, ~allSelectType: FilterSelectBox.allSelectType=?, ~showToolTip: bool=?, ~showNameAsToolTip: bool=?, ~buttonType: Button.buttonType=?, ~showSelectAll: bool=?, ~isHorizontal: bool=?, ~fullLength: bool=?, ~fixedDropDownDirection: FilterSelectBox.direction=?, ~dropdownCustomWidth: string=?, ~customMarginStyle: string=?, ~buttonTextWeight: string=?, ~marginTop: string=?, ~customButtonLeftIcon: Button.iconType=?, ~customButtonPaddingClass: string=?, ~customButtonIconMargin: string=?, ~customTextPaddingClass: string=?, ~listFlexDirection: string=?, ~buttonClickFn: string => unit=?, ~showDescriptionAsTool: bool=?, ~optionClass: string=?, ~selectClass: string=?, ~toggleProps: string=?, ~showSelectCountButton: bool=?, ~showAllSelectedOptions: bool=?, ~leftIcon: Button.iconType=?, ~customBackColor: string=?, ~customSelectAllStyle: string=?, ~onItemSelect: (JsxEventU.Mouse.t, string) => unit=?, ~wrapBasis: string=?, ~dropdownClassName: string=?, ~baseComponentMethod: bool => React.element=?, ~disableSelect: bool=?, unit, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let multiSelectInput: ( ~options: array<SelectBox.dropdownOption>, ~optionSize: CheckBoxIcon.size=?, ~buttonText: string, ~buttonSize: Button.buttonSize=?, ~hideMultiSelectButtons: bool=?, ~showSelectionAsChips: bool=?, ~showToggle: bool=?, ~isDropDown: bool=?, ~searchable: bool=?, ~showBorder: bool=?, ~optionRigthElement: React.element=?, ~customStyle: string=?, ~customMargin: string=?, ~customButtonStyle: string=?, ~hideBorder: bool=?, ~allSelectType: SelectBox.allSelectType=?, ~showToolTip: bool=?, ~showNameAsToolTip: bool=?, ~buttonType: Button.buttonType=?, ~showSelectAll: bool=?, ~isHorizontal: bool=?, ~fullLength: bool=?, ~fixedDropDownDirection: SelectBox.direction=?, ~dropdownCustomWidth: string=?, ~customMarginStyle: string=?, ~buttonTextWeight: string=?, ~marginTop: string=?, ~customButtonLeftIcon: Button.iconType=?, ~customButtonPaddingClass: string=?, ~customButtonIconMargin: string=?, ~customTextPaddingClass: string=?, ~listFlexDirection: string=?, ~buttonClickFn: string => unit=?, ~showDescriptionAsTool: bool=?, ~optionClass: string=?, ~selectClass: string=?, ~toggleProps: string=?, ~showSelectCountButton: bool=?, ~showAllSelectedOptions: bool=?, ~leftIcon: Button.iconType=?, ~customBackColor: string=?, ~customSelectAllStyle: string=?, ~onItemSelect: (JsxEventU.Mouse.t, string) => unit=?, ~wrapBasis: string=?, ~dropdownClassName: string=?, ~baseComponentMethod: bool => React.element=?, ~disableSelect: bool=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let radioInput: ( ~options: array<SelectBox.dropdownOption>, ~buttonText: string, ~disableSelect: bool=?, ~optionSize: CheckBoxIcon.size=?, ~isHorizontal: bool=?, ~deselectDisable: bool=?, ~customStyle: string=?, ~baseComponentCustomStyle: string=?, ~customSelectStyle: string=?, ~fill: string=?, ~maxHeight: string=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let textInput: ( ~description: string=?, ~isDisabled: bool=?, ~autoFocus: bool=?, ~type_: string=?, ~inputMode: string=?, ~pattern: string=?, ~autoComplete: string=?, ~maxLength: int=?, ~leftIcon: React.element=?, ~rightIcon: React.element=?, ~rightIconOnClick: JsxEventU.Mouse.t => unit=?, ~inputStyle: string=?, ~customStyle: string=?, ~customWidth: string=?, ~customPaddingClass: string=?, ~iconOpacity: string=?, ~rightIconCustomStyle: string=?, ~leftIconCustomStyle: string=?, ~customDashboardClass: string=?, ~onHoverCss: string=?, ~onDisabledStyle: string=?, ~onActiveStyle: string=?, ~customDarkBackground: string=?, ~phoneInput: bool=?, ~widthMatchwithPlaceholderLength: option<int>=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: string) => React.element let textTagInput: ( ~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: string, ~name: string=?, ~customStyle: string=?, ~disabled: bool=?, ~seperateByComma: bool=?, ~seperateBySpace: bool=?, ~customButtonStyle: string=?, ) => React.element let fileInput: unit => (~input: ReactFinalForm.fieldRenderPropsInput) => React.element let numericTextInput: ( ~isDisabled: bool=?, ~customStyle: string=?, ~inputMode: string=?, ~precision: int=?, ~maxLength: int=?, ~removeLeadingZeroes: bool=?, ~leftIcon: React.element=?, ~rightIcon: React.element=?, ~customPaddingClass: string=?, ~rightIconCustomStyle: string=?, ~leftIconCustomStyle: string=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: string) => React.element let singleDatePickerInput: ( ~disablePastDates: bool=?, ~disableFutureDates: bool=?, ~customDisabledFutureDays: float=?, ~format: string=?, ~currentDateHourFormat: string=?, ~currentDateMinuteFormat: string=?, ~currentDateSecondsFormat: string=?, ~customButtonStyle: string=?, ~newThemeCustomButtonStyle: string=?, ~calendarContaierStyle: string=?, ~buttonSize: Button.buttonSize=?, ~showTime: bool=?, ~fullLength: bool=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let filterDateRangeField: ( ~startKey: string, ~endKey: string, ~format: string, ~disablePastDates: bool=?, ~disableFutureDates: bool=?, ~showTime: bool=?, ~predefinedDays: array<DateRangeUtils.customDateRange>=?, ~disableApply: bool=?, ~numMonths: int=?, ~dateRangeLimit: int=?, ~removeFilterOption: bool=?, ~optFieldKey: 'a=?, ~showSeconds: bool=?, ~hideDate: bool=?, ~selectStandardTime: bool=?, ~isTooltipVisible: bool=?, ~allowedDateRange: Calendar.dateObj=?, ~events: unit => unit=?, ) => comboCustomInputRecord let filterCompareDateRangeField: ( ~startKey: string, ~endKey: string, ~comparisonKey: string, ~format: string, ~disablePastDates: bool=?, ~disableFutureDates: bool=?, ~showTime: bool=?, ~predefinedDays: array<DateRangeUtils.customDateRange>=?, ~disableApply: bool=?, ~numMonths: int=?, ~dateRangeLimit: int=?, ~removeFilterOption: bool=?, ~optFieldKey: 'a=?, ~showSeconds: bool=?, ~hideDate: bool=?, ~selectStandardTime: bool=?, ~isTooltipVisible: bool=?, ~compareWithStartTime: string, ~compareWithEndTime: string, ) => comboCustomInputRecord let dateRangeField: ( ~startKey: string, ~endKey: string, ~format: string, ~disablePastDates: bool=?, ~disableFutureDates: bool=?, ~showTime: bool=?, ~predefinedDays: array<DateRangeUtils.customDateRange>=?, ~disableApply: bool=?, ~numMonths: int=?, ~dateRangeLimit: int=?, ~removeFilterOption: bool=?, ~optFieldKey: 'a=?, ~showSeconds: bool=?, ~hideDate: bool=?, ~selectStandardTime: bool=?, ~customButtonStyle: string=?, ~isTooltipVisible: bool=?, ) => comboCustomInputRecord let multiLineTextInput: ( ~isDisabled: bool, ~rows: option<int>, ~cols: option<int>, ~customClass: string=?, ~leftIcon: React.element=?, ~maxLength: int=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: string) => React.element let iconFieldWithMessageDes: ( (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element, ~description: string=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let passwordMatchField: ( ~leftIcon: React.element=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: string) => React.element let checkboxInput: ( ~isHorizontal: bool=?, ~options: array<SelectBox.dropdownOption>, ~optionSize: CheckBoxIcon.size=?, ~isSelectedStateMinus: bool=?, ~disableSelect: bool=?, ~buttonText: string=?, ~maxHeight: string=?, ~searchable: bool=?, ~searchInputPlaceHolder: string=?, ~dropdownCustomWidth: string=?, ~customSearchStyle: string=?, ~customLabelStyle: string=?, ~customMarginStyle: string=?, ~customStyle: string=?, ~checkboxDimension: string=?, ~wrapBasis: string=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element let boolInput: ( ~isDisabled: bool, ~isCheckBox: bool=?, ~boolCustomClass: string=?, ) => (~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder: 'a) => React.element
3,076
9,981
hyperswitch-control-center
src/components/CalendarList.res
.res
external ffInputToSelectInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput< array<string>, > = "%identity" open Calendar @react.component let make = ( ~changeHighlightCellStyle="", ~calendarContaierStyle="", ~month: option<month>=?, ~year: option<int>=?, ~onDateClick=?, ~count=1, ~cellHighlighter=?, ~cellRenderer=?, ~startDate="", ~endDate="", ~disablePastDates=true, ~disableFutureDates=false, ~dateRangeLimit=?, ~setShowMsg=?, ~secondCalendar=false, ~firstCalendar=false, ~customDisabledFutureDays=0.0, ~allowedDateRange=?, ) => { let (hoverdDate, setHoverdDate) = React.useState(_ => "") let months = [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] let _ = onDateClick // check whether month and date has value let getMonthFromFloat = value => { let valueInt = value->Float.toInt months[valueInt]->Option.getOr(Jan) } 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, " } } let startMonth = switch month { | Some(m) => Int.toFloat(Float.toInt(getMonthInFloat(m))) | None => { let tMonth = Int.toFloat(Float.toInt(Js.Date.getMonth(Date.make()))) disableFutureDates && count > 1 ? tMonth -. 1.0 : tMonth } } let startYear = switch year { | Some(y) => Int.toFloat(y) | None => Js.Date.getFullYear(Date.make()) } let (currDateIm, setCurrDate) = React.useState(() => Js.Date.makeWithYM(~year=startYear, ~month=startMonth, ()) ) let handleChangeMonthBy = month => { let currDateTemp = Js.Date.fromFloat(Js.Date.valueOf(currDateIm)) let newDate = Js.Date.fromFloat( Js.Date.setMonth( currDateTemp, Int.toFloat(Float.toInt(Js.Date.getMonth(currDateTemp)) + month), ), ) setCurrDate(_ => newDate) } let dummyRow = Array.make(~length=count, 1) <div className={`flex flex-1 flex-row justify-center overflow-auto bg-jp-gray-100 bg-opacity-20 rounded-md border select-none ${calendarContaierStyle}`}> {dummyRow ->Array.mapWithIndex((_item, i) => { let currDateTemp = Js.Date.fromFloat(Js.Date.valueOf(currDateIm)) let tempDate = Js.Date.setMonth( currDateTemp, Int.toFloat(Float.toInt(Js.Date.getMonth(currDateTemp)) + i), ) let tempMonth = if disableFutureDates { (Js.Date.fromFloat(tempDate)->DayJs.getDayJsForJsDate).toString() ->Date.fromString ->Js.Date.getMonth } else { Js.Date.getMonth(Js.Date.fromFloat(tempDate)) } let tempYear = Js.Date.getFullYear(Js.Date.fromFloat(tempDate)) let showLeft = i == 0 && !secondCalendar let showRight = i + 1 == Array.length(dummyRow) && !firstCalendar let monthAndYear = String.concat( getMonthInStr(getMonthFromFloat(tempMonth)), Float.toString(tempYear), ) let iconClass = "inline-block text-jp-gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-25 cursor-pointer" <div key={Int.toString(i)}> <div className="flex flex-row justify-between items-center p-3"> {showLeft ? <> <Icon name="angle-double-left" className=iconClass size=24 onClick={_ => handleChangeMonthBy(-12)} /> <Icon name="chevron-left" className=iconClass onClick={_ => handleChangeMonthBy(-1)} /> </> : React.null} <AddDataAttributes attributes=[("data-calendar-date", monthAndYear)]> <div className="font-medium text-sm md:text-base text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-75"> {React.string(monthAndYear)} </div> </AddDataAttributes> {showRight ? <> <Icon name="chevron-right" className=iconClass onClick={_ => handleChangeMonthBy(1)} /> <Icon name="angle-double-right" className=iconClass size=24 onClick={_ => handleChangeMonthBy(12)} /> </> : React.null} </div> <Calendar key={Int.toString(i)} month={getMonthFromFloat(tempMonth)} year={Float.toInt(tempYear)} showTitle=false hoverdDate setHoverdDate ?cellHighlighter ?cellRenderer ?onDateClick startDate endDate disablePastDates disableFutureDates changeHighlightCellStyle ?dateRangeLimit ?setShowMsg customDisabledFutureDays ?allowedDateRange /> </div> }) ->React.array} </div> }
1,301
9,982
hyperswitch-control-center
src/components/HSwitchFeedBackModal.res
.res
@react.component let make = ( ~modalHeading, ~setShowModal, ~showModal, ~feedbackVia="user", ~modalType: HSwitchFeedBackModalUtils.modalType=FeedBackModal, ) => { open HSwitchFeedBackModalUtils open APIUtils let {email} = CommonAuthHooks.useCommonAuthInfo()->Option.getOr(CommonAuthHooks.defaultAuthInfo) let showToast = ToastState.useShowToast() let updateDetails = useUpdateMethod() let getURL = useGetURL() let onSubmit = async (values, _) => { try { let url = getURL(~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post) let body = [ ( "Feedback", HSwitchUtils.getBodyForFeedBack(~email, ~values, ~modalType)->JSON.Encode.object, ), ]->LogicUtils.getJsonFromArrayOfJson let _ = await updateDetails(url, body, Post) let successMessage = switch modalType { | FeedBackModal => "Thanks for feedback" | RequestConnectorModal => "Request submitted succesfully" } showToast(~toastType=ToastSuccess, ~message=successMessage, ~autoClose=false) } catch { | _ => () } setShowModal(_ => false) Nullable.null } let showLabel = switch modalType { | FeedBackModal => false | RequestConnectorModal => true } let modalFormFields = switch modalType { | FeedBackModal => <> <RatingOptions icons=["angry", "frown", "smile", "smile-beam", "grin-hearts"] size=30 /> <div className="text-md w-full font-medium mt-7 -mb-1 text-dark_black opacity-80 my-5"> {"Type of feedback"->React.string} </div> <div className="mb-5 mt-1"> <FormRenderer.FieldRenderer field=selectFeedbackType /> </div> <div className="text-md w-full font-medium mt-3 ml-2 -mb-1 text-dark_black opacity-80 my-5"> {"How can we improve your hyperswitch experience?"->React.string} </div> <div className="mt-2"> <FormRenderer.FieldRenderer field={feedbackTextBox} /> </div> </> | RequestConnectorModal => <div className="flex flex-col gap-1"> <FormRenderer.FieldRenderer field=connectorNameField /> <FormRenderer.FieldRenderer field=connectorDescription /> </div> } let submitBtnText = switch modalType { | FeedBackModal => "Send" | RequestConnectorModal => "Submit Request" } <Modal modalHeading headingClass="!bg-transparent dark:!bg-jp-gray-lightgray_background" showModal setShowModal borderBottom=true closeOnOutsideClick=true modalClass="w-full max-w-xl m-auto dark:!bg-jp-gray-lightgray_background pb-3"> <Form onSubmit validate={values => values->validateFields(~modalType)}> <LabelVisibilityContext showLabel> <div className="flex flex-col justify-center"> {modalFormFields} <div className="flex justify-end gap-3 p-1 mt-4"> <Button buttonType=Button.Secondary onClick={_ => setShowModal(_ => false)} text="Cancel" /> <FormRenderer.SubmitButton text=submitBtnText /> </div> </div> </LabelVisibilityContext> </Form> </Modal> }
792
9,983
hyperswitch-control-center
src/components/MonacoEditorLazy.res
.res
@react.component let make = ( ~defaultLanguage: string, ~defaultValue=?, ~value=?, ~height=?, ~theme=?, ~readOnly=false, ~width=?, ~onChange=?, ~onValidate=?, ~showCopy=true, ~fontSize=?, ~fontFamily=?, ~fontWeight=?, ~minimap=true, ~outerWidth="w-full", ~onMount: option<Monaco.Editor.IStandaloneCodeEditor.t => unit>=?, ~headerComponent=?, ) => { let copyValue = value->Option.isNone ? defaultValue : value <AddDataAttributes attributes=[("data-editor", "Monaco Editor"), ("text", value->Option.getOr(""))]> <div className={`flex flex-col ${outerWidth}`}> {headerComponent->Option.getOr(React.null)} {showCopy ? <Clipboard.Copy data=copyValue /> : React.null} <MonacoEditor defaultLanguage ?defaultValue ?value ?height ?theme ?width options={{readOnly, fontSize, fontFamily, fontWeight, minimap: {enabled: minimap}}} ?onChange ?onValidate ?onMount /> </div> </AddDataAttributes> }
283
9,984
hyperswitch-control-center
src/components/DateRangePicker.res
.res
let defaultCellHighlighter = (_): Calendar.highlighter => { { highlightSelf: false, highlightLeft: false, highlightRight: false, } } let useErroryValueResetter = (value: string, setValue: (string => string) => unit) => { React.useEffect(() => { let isErroryTimeValue = _ => { try { false } catch { | _error => true } } if value->isErroryTimeValue { setValue(_ => "") } None }, []) } let isStartBeforeEndDate = (start, end) => { 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 startDate = getDate(String.split(start, "-")) let endDate = getDate(String.split(end, "-")) startDate < endDate } module PredefinedOption = { @react.component let make = ( ~predefinedOptionSelected, ~value, ~onClick, ~disableFutureDates, ~disablePastDates, ~todayDayJsObj, ~isoStringToCustomTimeZone, ~isoStringToCustomTimezoneInFloat, ~customTimezoneToISOString, ~todayDate, ~todayTime, ~formatDateTime, ~isTooltipVisible=true, ) => { open DateRangeUtils let optionBG = if predefinedOptionSelected === Some(value) { "bg-blue-100 dark:bg-jp-gray-850 py-2" } else { "bg-transparent md:bg-white md:dark:bg-jp-gray-lightgray_background py-2" } let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, value, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startDate = getFormattedDate(`${stDate}T${stTime}Z`, formatDateTime) let endDate = getFormattedDate(`${enDate}T${enTime}Z`, formatDateTime) let handleClick = _value => { onClick(value, disableFutureDates) } let dateRangeDropdownVal = DateRangeUtils.datetext(value, disableFutureDates) <ToolTip tooltipWidthClass="w-fit" tooltipForWidthClass="!block w-full" description={isTooltipVisible ? `${startDate} - ${endDate}` : ""} toolTipFor={<AddDataAttributes attributes=[("data-daterange-dropdown-value", dateRangeDropdownVal)]> <div> <div className={`${optionBG} px-4 py-2 hover:bg-jp-gray-100 hover:bg-opacity-75 dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 cursor-pointer text-sm text-gray-500 dark:text-gray-400`} onClick=handleClick> {React.string(dateRangeDropdownVal)} </div> </div> </AddDataAttributes>} toolTipPosition=Right contentAlign=Left /> } } module Base = { @react.component let make = ( ~startDateVal: string, ~setStartDateVal: (string => string) => unit, ~endDateVal: string, ~setEndDateVal: (string => string) => unit, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~dateRangeLimit=?, ~optFieldKey as _=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~selectStandardTime=false, ~buttonType=?, ~customButtonStyle=?, ~buttonText="", ~allowedDateRange=?, ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~customborderCSS="", ~isTooltipVisible=true, ) => { open DateRangeUtils open LogicUtils let (isCustomSelected, setIsCustomSelected) = React.useState(_ => predefinedDays->Array.length === 0 ) let formatDateTime = showSeconds ? "MMM DD, YYYY HH:mm:ss" : "MMM DD, YYYY HH:mm" let (showOption, setShowOption) = React.useState(_ => false) let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let isoStringToCustomTimezoneInFloat = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat() let (clickedDates, setClickedDates) = React.useState(_ => []) let (localStartDate, setLocalStartDate) = React.useState(_ => startDateVal) let (localEndDate, setLocalEndDate) = React.useState(_ => endDateVal) let (_localOpt, setLocalOpt) = React.useState(_ => "") let (showMsg, setShowMsg) = React.useState(_ => false) let (isDropdownExpanded, setIsDropdownExpanded) = React.useState(_ => false) let (calendarVisibility, setCalendarVisibility) = React.useState(_ => false) let isMobileView = MatchMedia.useMobileChecker() let isFilterSection = React.useContext(TableFilterSectionContext.filterSectionContext) let dropdownPosition = isFilterSection && !isMobileView && isCustomSelected ? "right-0" : "" let todayDayJsObj = React.useMemo(() => { Date.make()->Date.toString->DayJs.getDayJsForString }, [isDropdownExpanded]) let currentTime = todayDayJsObj.format("HH:mm") let todayDate = todayDayJsObj.format("YYYY-MM-DD") let todayTime = React.useMemo(() => { todayDayJsObj.format("HH:mm:ss") }, [currentTime]) let initialStartTime = disableFutureDates || selectStandardTime ? "00:00:00" : "23:59:59" let initialEndTime = disableFutureDates || selectStandardTime ? "23:59:59" : "00:00:00" React.useEffect(() => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) setLocalOpt(_ => "") None }, (startDateVal, endDateVal)) let resetStartEndInput = () => { setLocalStartDate(_ => "") setLocalEndDate(_ => "") setLocalOpt(_ => "") } React.useEffect(() => { switch dateRangeLimit { | Some(maxLen) => { let diff = getStartEndDiff(localStartDate, localEndDate) if diff > (maxLen->Int.toFloat *. 24. *. 60. *. 60. -. 1.) *. 1000. { setShowMsg(_ => true) resetStartEndInput() } } | None => () } None }, (localStartDate, localEndDate)) let dateRangeRef = React.useRef(Nullable.null) let dropdownRef = React.useRef(Nullable.null) useErroryValueResetter(startDateVal, setStartDateVal) useErroryValueResetter(endDateVal, setEndDateVal) let startDate = localStartDate->getDateStringForValue(isoStringToCustomTimeZone) let endDate = localEndDate->getDateStringForValue(isoStringToCustomTimeZone) let isDropdownExpandedActual = isDropdownExpanded && calendarVisibility let dropdownVisibilityClass = if isDropdownExpandedActual { "inline-block" } else { "hidden" } let saveDates = () => { if localStartDate->isNonEmptyString && localEndDate->isNonEmptyString { setStartDateVal(_ => localStartDate) setEndDateVal(_ => localEndDate) } } let resetToInitalValues = () => { setLocalStartDate(_ => startDateVal) setLocalEndDate(_ => endDateVal) setLocalOpt(_ => "") } OutsideClick.useOutsideClick( ~refs=ArrayOfRef([dateRangeRef, dropdownRef]), ~isActive=isDropdownExpanded || calendarVisibility, ~callback=() => { setIsDropdownExpanded(_ => false) setCalendarVisibility(p => !p) if isDropdownExpandedActual && isCustomSelected { resetToInitalValues() } }, ) let changeEndDate = (ele, isFromCustomInput, time) => { if disableApply { setIsDropdownExpanded(_ => false) } if localEndDate == ele && isFromCustomInput { setEndDateVal(_ => "") } else { let endDateSplit = String.split(ele, "-") let endDateDate = endDateSplit[2]->Option.getOr("") let endDateYear = endDateSplit[0]->Option.getOr("") let endDateMonth = endDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if disableFutureDates && ele == todayDate { todayTime } else { initialEndTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let endDateTimeCheck = customTimezoneToISOString( endDateYear, endDateMonth, endDateDate, timeHour, timeMinute, timeSecond, ) setLocalEndDate(_ => TimeZoneHook.formattedISOString(endDateTimeCheck, format)) } } let changeStartDate = (ele, isFromCustomInput, time) => { let setDate = str => { let startDateSplit = String.split(str, "-") let startDateDay = startDateSplit[2]->Option.getOr("") let startDateYear = startDateSplit[0]->Option.getOr("") let startDateMonth = startDateSplit[1]->Option.getOr("") let splitTime = switch time { | Some(val) => val | None => if !disableFutureDates && ele == todayDate && !standardTimeToday { todayTime } else { initialStartTime } } let timeSplit = String.split(splitTime, ":") let timeHour = timeSplit->Array.get(0)->Option.getOr("00") let timeMinute = timeSplit->Array.get(1)->Option.getOr("00") let timeSecond = timeSplit->Array.get(2)->Option.getOr("00") let startDateTimeCheck = customTimezoneToISOString( startDateYear, startDateMonth, startDateDay, timeHour, timeMinute, timeSecond, ) setLocalStartDate(_ => TimeZoneHook.formattedISOString(startDateTimeCheck, format)) } let resetStartDate = () => { resetStartEndInput() setDate(ele) } if startDate->isNonEmptyString && startDate == ele && isFromCustomInput { changeEndDate(ele, isFromCustomInput, None) } else if startDate->isNonEmptyString && startDate > ele && isFromCustomInput { resetStartDate() } else if endDate->isNonEmptyString && startDate == ele && isFromCustomInput { resetStartDate() } else if ( ele > startDate && ele < endDate && startDate->isNonEmptyString && endDate->isNonEmptyString && isFromCustomInput ) { resetStartDate() } else if ( startDate->isNonEmptyString && endDate->isNonEmptyString && ele > endDate && isFromCustomInput ) { resetStartDate() } else { () } if !isFromCustomInput || startDate->isEmptyString { setDate(ele) } if ( (startDate->isNonEmptyString && endDate->isEmptyString && !isFromCustomInput) || (startDate->isNonEmptyString && endDate->isEmptyString && isStartBeforeEndDate(startDate, ele) && isFromCustomInput) ) { changeEndDate(ele, isFromCustomInput, None) } } let onDateClick = str => { let data = switch Array.find(clickedDates, x => x == str) { | Some(_d) => Belt.Array.keep(clickedDates, x => x != str) | None => Array.concat(clickedDates, [str]) } let dat = data->Array.map(x => x) setClickedDates(_ => dat) changeStartDate(str, true, None) } let handleApply = _ => { setShowOption(_ => false) setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) saveDates() } let cancelButton = _ => { resetToInitalValues() setCalendarVisibility(p => !p) setIsDropdownExpanded(_ => false) } let selectedStartDate = if localStartDate->isNonEmptyString { getFormattedDate( localStartDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD", ) } else { "" } let selectedEndDate = if localEndDate->isNonEmptyString { getFormattedDate(localEndDate->getDateStringForValue(isoStringToCustomTimeZone), "YYYY-MM-DD") } else { "" } let setStartDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalStartDate(_ => timestamp) } } let setEndDate = (~date, ~time) => { if date->isNonEmptyString { let timestamp = changeTimeFormat(~date, ~time, ~customTimezoneToISOString, ~format) setLocalEndDate(_ => timestamp) } } let startTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let startTimeVal = timeValEv->Identity.formReactEventToString let endTime = localEndDate->getTimeStringForValue(isoStringToCustomTimeZone) if localStartDate->isNonEmptyString { if disableFutureDates && selectedStartDate == todayDate && startTimeVal > todayTime { setStartDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && startTimeVal > endTime ) { () } else { setStartDate(~date=startDate, ~time=startTimeVal) } } }, onFocus: _ => (), value: localStartDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let endTimeInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: timeValEv => { let endTimeVal = timeValEv->Identity.formReactEventToString let startTime = localStartDate->getTimeStringForValue(isoStringToCustomTimeZone) if localEndDate->isNonEmptyString { if disableFutureDates && selectedEndDate == todayDate && endTimeVal > todayTime { setEndDate(~date=startDate, ~time=todayTime) } else if ( disableFutureDates && selectedStartDate == selectedEndDate && endTimeVal < startTime ) { () } else { setEndDate(~date=endDate, ~time=endTimeVal) } } }, onFocus: _ => (), value: localEndDate->getTimeStringForValue(isoStringToCustomTimeZone)->JSON.Encode.string, checked: false, } let startDateStr = startDateVal->isNonEmptyString ? getFormattedDate( startDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? buttonText : "[From-Date]" let endDateStr = endDateVal->isNonEmptyString ? getFormattedDate( endDateVal->getDateStringForValue(isoStringToCustomTimeZone), "MMM DD, YYYY", ) : buttonText->isNonEmptyString ? "" : "[To-Date]" let startTimeStr = startDateVal->isNonEmptyString ? startDateVal->getTimeStringForValue(isoStringToCustomTimeZone) : "00:00:00" let endTimeStr = startDateVal->isNonEmptyString ? endDateVal->getTimeStringForValue(isoStringToCustomTimeZone) : "23:59:59" let endTimeStr = { let timeArr = endTimeStr->String.split(":") let endTimeTxt = `${timeArr[0]->Option.getOr("00")}:${timeArr[1]->Option.getOr("00")}` showSeconds ? `${endTimeTxt}:${timeArr[2]->Option.getOr("00")}` : endTimeTxt } let startTimeStr = { let timeArr = startTimeStr->String.split(":") let startTimeTxt = `${timeArr[0]->Option.getOr("00")}:${timeArr[1]->Option.getOr("00")}` showSeconds ? `${startTimeTxt}:${timeArr[2]->Option.getOr("00")}` : startTimeTxt } let buttonText = { startDateVal->isEmptyString && endDateVal->isEmptyString ? `Select Date ${showTime ? "and Time" : ""}` : showTime ? `${startDateStr} ${startTimeStr} - ${endDateStr} ${endTimeStr}` : `${startDateStr} ${startDateStr === buttonText ? "" : "-"} ${endDateStr}` } let buttonIcon = isDropdownExpanded ? "angle-up" : "angle-down" let handlePredefinedOptionClick = (value, disableFutureDates) => { setIsCustomSelected(_ => false) setCalendarVisibility(_ => false) setIsDropdownExpanded(_ => false) setShowOption(_ => false) let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, value, disableFutureDates, disablePastDates, todayDate, todayTime, ) resetStartEndInput() setStartDate(~date=startDate, ~time=stTime) setEndDate(~date=endDate, ~time=enTime) setLocalOpt(_ => DateRangeUtils.datetext(value, disableFutureDates) ->String.toLowerCase ->String.split(" ") ->Array.joinWith("_") ) changeStartDate(stDate, false, Some(stTime)) changeEndDate(enDate, false, Some(enTime)) } let handleDropdownClick = () => { if predefinedDays->Array.length > 0 { if calendarVisibility { setCalendarVisibility(_ => false) setShowOption(_ => !isDropdownExpanded) setIsDropdownExpanded(_ => !isDropdownExpanded) setShowOption(_ => !isCustomSelected) } else { setIsDropdownExpanded(_ => true) setShowOption(_ => true) setCalendarVisibility(_ => true) } } else { setIsDropdownExpanded(_p => !isDropdownExpanded) setCalendarVisibility(_ => !isDropdownExpanded) } } let displayStartDate = convertTimeStamp( ~isoStringToCustomTimeZone, localStartDate, formatDateTime, ) let modifiedStartDate = if removeConversion { (displayStartDate->DayJs.getDayJsForString).subtract(330, "minute").format( "YYYY-MM-DDTHH:mm:ss[Z]", ) } else { displayStartDate } let displayEndDate = convertTimeStamp(~isoStringToCustomTimeZone, localEndDate, formatDateTime) let modifiedEndDate = if removeConversion { (displayEndDate->DayJs.getDayJsForString).subtract(330, "minute").format( "YYYY-MM-DDTHH:mm:ss[Z]", ) } else { displayEndDate } React.useEffect(() => { if startDate->isNonEmptyString && endDate->isNonEmptyString { if ( localStartDate->isNonEmptyString && localEndDate->isNonEmptyString && (disableApply || !isCustomSelected) ) { saveDates() } if disableApply { setShowOption(_ => false) } } None }, (startDate, endDate, localStartDate, localEndDate)) let btnStyle = customButtonStyle->Option.getOr("") let customStyleForBtn = btnStyle->isNonEmptyString ? btnStyle : "" let timeVisibilityClass = showTime ? "block" : "hidden" let getDiffForPredefined = predefinedDay => { let (stDate, enDate, stTime, enTime) = DateRangeUtils.getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, predefinedDay, disableFutureDates, disablePastDates, todayDate, todayTime, ) let startTimestamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) let endTimestamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:00[Z]", ) getStartEndDiff(startTimestamp, endTimestamp) } let predefinedOptionSelected = predefinedDays->Array.find(item => { let startDate = convertTimeStamp( ~isoStringToCustomTimeZone, startDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let endDate = convertTimeStamp( ~isoStringToCustomTimeZone, endDateVal, "YYYY-MM-DDTHH:mm:00[Z]", ) let difference = getStartEndDiff(startDate, endDate) getDiffForPredefined(item) === difference }) let filteredPredefinedDays = { switch dateRangeLimit { | Some(limit) => predefinedDays->Array.filter(item => { getDiffForPredefined(item) <= (limit->Float.fromInt *. 24. *. 60. *. 60. -. 1.) *. 1000. }) | None => predefinedDays } } let customeRangeBg = switch predefinedOptionSelected { | Some(_) => "bg-white dark:bg-jp-gray-lightgray_background" | None => "bg-jp-gray-100 dark:bg-jp-gray-850" } let removeApplyFilter = ev => { ev->ReactEvent.Mouse.stopPropagation resetToInitalValues() setStartDateVal(_ => "") setEndDateVal(_ => "") } let buttonType: option<Button.buttonType> = buttonType let calendarIcon = "calendar" let arrowIconSize = 14 let strokeColor = if disable { "stroke-jp-2-light-gray-600" } else if isDropdownExpandedActual { "stroke-jp-2-light-gray-1700" } else { "stroke-jp-2-light-gray-1100" } let iconElement = { <div className="flex flex-row gap-2"> <Icon className=strokeColor name=buttonIcon size=arrowIconSize /> {if removeFilterOption && startDateVal->isNonEmptyString && endDateVal->isNonEmptyString { <Icon name="crossicon" size=16 onClick=removeApplyFilter /> } else { React.null }} </div> } let calendarElement = <div className={`flex md:flex-row flex-col w-full`}> {if predefinedDays->Array.length > 0 && showOption { <AddDataAttributes attributes=[("data-date-picker-predifined", "predefined-options")]> <div className="flex flex-wrap md:flex-col"> {filteredPredefinedDays ->Array.mapWithIndex((value, i) => { <div key={i->Int.toString} className="w-1/3 md:w-full md:min-w-max text-center md:text-start"> <PredefinedOption predefinedOptionSelected value onClick=handlePredefinedOptionClick disableFutureDates disablePastDates todayDayJsObj isoStringToCustomTimeZone isoStringToCustomTimezoneInFloat customTimezoneToISOString todayDate todayTime formatDateTime isTooltipVisible /> </div> }) ->React.array} <div className={`text-center md:text-start min-w-max bg-white dark:bg-jp-gray-lightgray_background w-1/3 px-4 py-2 hover:bg-jp-gray-100 hover:bg-opacity-75 dark:hover:bg-jp-gray-850 dark:hover:bg-opacity-100 cursor-pointer text-sm text-gray-500 dark:text-gray-400 ${customeRangeBg}}`} onClick={_ => { setCalendarVisibility(_ => true) setIsCustomSelected(_ => true) }}> {React.string("Custom Range")} </div> </div> </AddDataAttributes> } else { React.null }} <AddDataAttributes attributes=[("data-date-picker-section", "date-picker-calendar")]> <div className={calendarVisibility && isCustomSelected ? "w-auto md:w-max h-auto" : "hidden"}> <CalendarList count=numMonths cellHighlighter=defaultCellHighlighter startDate endDate onDateClick disablePastDates disableFutureDates ?dateRangeLimit setShowMsg calendarContaierStyle="md:m-3 border-0 md:border" ?allowedDateRange /> <div className={`${timeVisibilityClass} w-full flex flex-row md:gap-4 p-3 justify-around md:justify-start dark:text-gray-400 text-gray-700 `}> <TimeInput input=startTimeInput showSeconds label="From" /> <TimeInput input=endTimeInput showSeconds label="To" /> </div> {if disableApply { React.null } else { <div id="neglectTopbarTheme" className="flex flex-row flex-wrap gap-4 bg-white dark:bg-jp-gray-lightgray_background p-3 align-center justify-end "> <div className="text-gray-700 font-fira-code dark:text-gray-400 flex-wrap font-medium self-center text-sm"> {if ( displayStartDate->isNonEmptyString && displayEndDate->isNonEmptyString && !disableApply && !hideDate ) { <div className="flex flex-col"> <AddDataAttributes attributes=[("data-date-range-start", displayStartDate)]> <div> {React.string(modifiedStartDate)} </div> </AddDataAttributes> <AddDataAttributes attributes=[("data-date-range-end", displayEndDate)]> <div> {React.string(modifiedEndDate)} </div> </AddDataAttributes> </div> } else if showMsg { let msg = `Date Range should not exceed ${dateRangeLimit ->Option.getOr(0) ->Int.toString} days` <span className="w-full flex flex-row items-center mr-0 text-red-500"> <FormErrorIcon /> {React.string(msg)} </span> } else { React.null }} </div> <Button text="Cancel" buttonType=Secondary buttonState=Normal buttonSize=Small onClick={cancelButton} /> <Button text="Apply" buttonType=Primary buttonState={endDate->LogicUtils.isEmptyString ? Disabled : Normal} buttonSize=Small onClick={handleApply} /> </div> }} </div> </AddDataAttributes> </div> <> <div className={"md:relative daterangSelection"}> <AddDataAttributes attributes=[ ("data-date-picker", `dateRangePicker${isFilterSection ? "-Filter" : ""}`), ("data-date-picker-start-date", `${startDateStr} ${startTimeStr}`), ("data-date-picker-end-date", `${endDateStr} ${endTimeStr}`), ]> <div ref={dateRangeRef->ReactDOM.Ref.domRef}> <Button text={isMobileView && textHideInMobileView ? "" : buttonText} leftIcon={FontAwesome(calendarIcon)} rightIcon={CustomIcon(iconElement)} buttonSize=Small isDropdownOpen=isDropdownExpandedActual onClick={_ => handleDropdownClick()} iconBorderColor={customborderCSS} customButtonStyle={customStyleForBtn} buttonState={disable ? Disabled : Normal} ?buttonType ?textStyle /> </div> </AddDataAttributes> {if isDropdownExpandedActual { if isMobileView { <BottomModal headerText={buttonText} onCloseClick={cancelButton}> calendarElement </BottomModal> } else { <div ref={dropdownRef->ReactDOM.Ref.domRef} className={`${dropdownVisibilityClass} absolute ${dropdownPosition} z-20 bg-white dark:bg-jp-gray-lightgray_background rounded border-jp-gray-500 dark:border-jp-gray-960 shadow-md dark:shadow-sm dark:shadow-gray-700 max-h-min max-w-min overflow-auto`}> calendarElement </div> } } else { React.null }} </div> </> } } let useStateForInput = (input: ReactFinalForm.fieldRenderPropsInput) => { React.useMemo(() => { let val = input.value->JSON.Decode.string->Option.getOr("") let onChange = fn => { let newVal = fn(val) input.onChange(newVal->Identity.stringToFormReactEvent) } (val, onChange) }, [input]) } @react.component let make = ( ~startKey: string, ~endKey: string, ~showTime=false, ~disable=false, ~disablePastDates=true, ~disableFutureDates=false, ~predefinedDays=[], ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ~numMonths=1, ~disableApply=true, ~removeFilterOption=false, ~dateRangeLimit=?, ~optFieldKey=?, ~textHideInMobileView=true, ~showSeconds=true, ~hideDate=false, ~allowedDateRange=?, ~selectStandardTime=false, ~customButtonStyle=?, ~buttonText="", ~textStyle=?, ~standardTimeToday=false, ~removeConversion=false, ~isTooltipVisible=true, ) => { let startInput = ReactFinalForm.useField(startKey).input let endInput = ReactFinalForm.useField(endKey).input let (startDateVal, setStartDateVal) = useStateForInput(startInput) let (endDateVal, setEndDateVal) = useStateForInput(endInput) <Base startDateVal setStartDateVal endDateVal setEndDateVal showTime disable disablePastDates disableFutureDates predefinedDays format numMonths disableApply removeFilterOption ?dateRangeLimit ?optFieldKey textHideInMobileView showSeconds hideDate selectStandardTime ?customButtonStyle buttonText ?allowedDateRange ?textStyle standardTimeToday removeConversion isTooltipVisible /> }
7,099
9,985
hyperswitch-control-center
src/components/MakeRuleFieldComponent.res
.res
let validateConditionJson = json => { open LogicUtils let checkValue = dict => { dict ->getArrayFromDict("value", []) ->Array.filter(ele => { ele != ""->JSON.Encode.string }) ->Array.length > 0 || dict->getString("value", "")->LogicUtils.isNonEmptyString || dict->getFloat("value", -1.0) !== -1.0 || dict->getString("operator", "") == "IS NULL" || dict->getString("operator", "") == "IS NOT NULL" } switch json->JSON.Decode.object { | Some(dict) => ["operator", "real_field"]->Array.every(key => dict->Dict.get(key)->Option.isSome) && dict->checkValue | None => false } } module TextView = { @react.component let make = ( ~str, ~fontColor="text-jp-gray-800 dark:text-jp-gray-600", ~fontWeight="font-medium", ) => { str->LogicUtils.isNonEmptyString ? <AddDataAttributes attributes=[("data-plc-text", str)]> <div className={`text-opacity-75 dark:text-opacity-75 hover:text-opacity-100 dark:hover:text-opacity-100 mx-1 ${fontColor} ${fontWeight} `}> {React.string(str)} </div> </AddDataAttributes> : React.null } } module CompressedView = { @react.component let make = (~id, ~isFirst, ~keyType) => { open LogicUtils let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let conditionInput = ReactFinalForm.useField(id).input let displayForValue = value => switch value->JSON.Classify.classify { | Array(arr) => arr->Array.joinWithUnsafe(", ") | String(str) => str | Number(num) => num->Float.toString | Object(obj) => obj->getString("value", "") | _ => "" } let condition = conditionInput.value ->JSON.Decode.object ->Option.flatMap(dict => { Some( dict->getString("logical", ""), dict->getString("lhs", ""), dict->getString("comparison", ""), dict->getDictfromDict("value")->getJsonObjectFromDict("value")->displayForValue, dict->getDictfromDict("metadata")->getOptionString("key"), dict->getDictfromDict("value")->getDictfromDict("value")->getOptionString("key"), ) }) switch condition { | Some((logical, field, operator, value, key, metadataKeyType)) => <div className="flex flex-wrap items-center gap-4"> {if !isFirst { <TextView str=logical fontColor={`${textColor.primaryNormal}`} fontWeight="font-semibold" /> } else { React.null }} <TextView str=field /> {switch key { | Some(val) => <TextView str=val /> | None => React.null }} <RenderIf condition={keyType->AdvancedRoutingUtils.variantTypeMapper == Metadata_value}> {switch metadataKeyType { | Some(val) => <TextView str=val /> | None => React.null }} </RenderIf> <TextView str=operator fontColor="text-red-500" fontWeight="font-semibold" /> <TextView str={value} /> </div> | None => React.null } } }
781
9,986
hyperswitch-control-center
src/components/TableUtils.resi
.resi
let regex: string => RescriptCore.RegExp.t let highlightedText: (Js.String.t, string) => React.element 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<RescriptCore.JSON.t> => unit, disableParam: disableField, } type hideItem = {key: string, value: string} external jsonToStr: RescriptCore.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: sortOrder => string type label = {title: string, color: labelColor, showIcon?: bool} type currency = string type filterRow = | DropDownFilter(string, array<RescriptCore.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) | 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: 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: { @react.component let make: (~progressPercentage: int) => React.element } let getTextAlignmentClass: textAlign => string module BaseComponentMethod: { @react.component let make: (~showDropDown: bool, ~filterKey: string) => React.element } module LabelCell: { @react.component let make: ( ~labelColor: labelColor, ~text: Js.String.t, ~labelMargin: string=?, ~highlightText: string=?, ~fontStyle: string=?, ~showIcon: bool=?, ) => React.element } module NewLabelCell: { @react.component let make: ( ~labelColor: labelColor, ~text: string, ~labelMargin: string=?, ~highlightText: string=?, ~fontStyle: string=?, ) => React.element } module ColoredTextCell: { @react.component let make: (~labelColor: labelColor, ~text: string, ~customPadding: string=?) => React.element } module Numeric: { @react.component let make: (~num: float, ~mapper: float => string, ~clearFormatting: bool) => React.element } module MoneyCell: { let getAmountValue: (float, string) => string @react.component let make: ( ~amount: float, ~currency: string, ~isCard: bool=?, ~textAlign: textAlign=?, ~fontBold: bool=?, ~customMoneyStyle: string=?, ) => React.element } module LinkCell: { @react.component let make: (~data: Js.String.t, ~trimLength: int=?) => React.element } module DateCell: { @react.component let make: ( ~timestamp: string, ~isCard: bool=?, ~textStyle: string=?, ~textAlign: textAlign=?, ~customDateStyle: string=?, ~hideTime: bool=?, ~hideTimeZone: bool=?, ) => React.element } module StartEndDateCell: { @react.component let make: (~startDate: string, ~endDate: string, ~isCard: bool=?) => React.element } module EllipsisText: { @react.component let make: ( ~text: Js.String.t, ~width: string, ~highlightText: string=?, ~isEllipsisTextRelative: bool=?, ~ellipseClass: string=?, ~ellipsisIdentifier: string=?, ~ellipsisThreshold: int=?, ~toolTipPosition: ToolTip.toolTipPosition=?, ) => React.element } module TrimmedText: { @react.component let make: ( ~text: Js.String.t, ~width: string, ~highlightText: string=?, ~hideShowMore: bool=?, ) => React.element } module TableFilterCell: { @react.component let make: (~cell: filterRow) => React.element } module DeltaColumn: { @react.component let make: (~value: float, ~delta: float) => React.element } module TableCell: { @react.component let make: ( ~cell: cell, ~textAlign: textAlign=?, ~fontBold: bool=?, ~labelMargin: labelMargin=?, ~customMoneyStyle: string=?, ~customDateStyle: string=?, ~highlightText: string=?, ~hideShowMore: bool=?, ~clearFormatting: bool=?, ~fontStyle: string=?, ~isEllipsisTextRelative: bool=?, ~ellipseClass: string=?, ) => React.element } module NewTableCell: { @react.component let make: ( ~cell: cell, ~textAlign: textAlign=?, ~fontBold: bool=?, ~labelMargin: labelMargin=?, ~customMoneyStyle: string=?, ~customDateStyle: string=?, ~highlightText: string=?, ~hideShowMore: bool=?, ~clearFormatting: bool=?, ~fontStyle: string=?, ) => React.element } type rowType = Filter | Row let getTableCellValue: cell => string module SortIcons: { @react.component let make: (~order: sortOrder, ~size: int) => React.element } module HeaderActions: { @react.component let make: ( ~order: sortOrder, ~actionOptions: array<SelectBox.dropdownOption>=?, ~onChange: ReactEvent.Form.t => unit, ~filterRow: option<filterRow>, ~isLastCol: bool=?, ~filterKey: string, ) => React.element }
1,745
9,987
hyperswitch-control-center
src/components/InfraCalendarList.res
.res
external ffInputToSelectInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput< array<string>, > = "%identity" let startYear = ref(2016) let years = [] while Date.make()->Js.Date.getFullYear->Float.toInt >= startYear.contents { years->Array.push(startYear.contents)->ignore startYear := startYear.contents + 1 } years->Array.reverse let months: array<InfraCalendar.month> = [ Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, ] let getMonthInStr = (mon: InfraCalendar.month) => { 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, " } } let getMonthFromFloat = value => { let valueInt = value->Float.toInt months[valueInt]->Option.getOr(Jan) } module YearItem = { @send external scrollIntoView: Dom.element => unit = "scrollIntoView" @react.component let make = (~tempYear, ~year, ~handleChangeMonthBy, ~setCurrDate, ~tempMonth) => { let isSelected = year->Int.toFloat === tempYear let yearRef = React.useRef(Nullable.null) React.useEffect(() => { if isSelected { switch yearRef.current->Nullable.toOption { | Some(element) => element->scrollIntoView | None => () } } None }, [isSelected]) <li className={`p-2 ${year === tempYear->Float.toInt ? "bg-blue-600 text-white" : "dark:hover:bg-jp-gray-900 hover:bg-jp-gray-100"} cursor-pointer bg-opacity-100`} value={year->Int.toString} ref={yearRef->ReactDOM.Ref.domRef} onClick={e => { let tar: float = ReactEvent.Mouse.currentTarget(e)["value"] let yearDiff = (tar -. tempYear)->Float.toInt if yearDiff !== 0 { handleChangeMonthBy(yearDiff * 12) setCurrDate(_ => Js.Date.makeWithYM(~year=tar, ~month=tempMonth, ())) } }}> {year->Int.toString->React.string} </li> } } module MonthItem = { @send external scrollIntoView: Dom.element => unit = "scrollIntoView" @react.component let make = ( ~index, ~tempMonth: float, ~tempYear, ~handleChangeMonthBy, ~setCurrDate, ~mon: InfraCalendar.month, ) => { let isSelected = index->Int.toFloat === tempMonth let monthRef = React.useRef(Nullable.null) React.useEffect(() => { if isSelected { switch monthRef.current->Nullable.toOption { | Some(element) => element->scrollIntoView | None => () } } None }, [isSelected]) <li value={index->Int.toString} onClick={e => { let tar: float = ReactEvent.Mouse.currentTarget(e)["value"] let monthDiff = (tar -. tempMonth)->Float.toInt if monthDiff !== 0 { handleChangeMonthBy(monthDiff) setCurrDate(_ => Js.Date.makeWithYM(~year=tempYear, ~month=tar, ())) } }} ref={monthRef->ReactDOM.Ref.domRef} className={`p-2 px-4 ${index === tempMonth->Float.toInt ? "bg-blue-600 text-white" : "dark:hover:bg-jp-gray-900 hover:bg-jp-gray-100"} cursor-pointer`}> {mon->getMonthInStr->String.replaceRegExp(%re("/,/g"), "")->React.string} </li> } } open InfraCalendar @react.component let make = ( ~month as _, ~year as _, ~onDateClick=?, ~cellHighlighter=?, ~cellRenderer=?, ~startDate="", ~endDate="", ~disablePastDates=true, ~disableFutureDates=false, ~monthYearListVisibility, ~handleChangeMonthBy, ~currDateIm, ~setCurrDate, ) => { <span className="flex flex-1 flex-row overflow-auto border-t border-b dark:border-jp-gray-900 select-none"> { let currDateTemp = Js.Date.fromFloat(Js.Date.valueOf(currDateIm)) let tempDate = Js.Date.setMonth( currDateTemp, Int.toFloat(Float.toInt(Js.Date.getMonth(currDateTemp))), ) let tempMonth = Js.Date.getMonth(Js.Date.fromFloat(tempDate)) let tempYear = Js.Date.getFullYear(Js.Date.fromFloat(tempDate)) <span> {monthYearListVisibility ? <div className="flex text-jp-gray-600 justify-between w-80"> <ul className="w-1/2 h-80 overflow-scroll"> {months ->Array.mapWithIndex((mon, i) => <MonthItem key={i->Int.toString} index=i tempMonth tempYear handleChangeMonthBy setCurrDate mon /> ) ->React.array} </ul> <ul className="w-1/2"> {years ->Array.mapWithIndex((year, i) => <YearItem key={i->Int.toString} tempMonth tempYear handleChangeMonthBy year setCurrDate /> ) ->React.array} </ul> </div> : <InfraCalendar month={getMonthFromFloat(tempMonth)} year={Float.toInt(tempYear)} showTitle=false ?cellHighlighter ?cellRenderer ?onDateClick startDate endDate disablePastDates disableFutureDates />} </span> } </span> }
1,405
9,988
hyperswitch-control-center
src/components/DateRangeHelper.res
.res
open DateRangeUtils module CompareOption = { @react.component let make = (~value: compareOption, ~comparison, ~startDateVal, ~endDateVal, ~onClick) => { let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let previousPeriod = React.useMemo(() => { let startDateStr = formatDateString( ~dateVal=startDateVal, ~buttonText="", ~defaultLabel=startDateVal, ~isoStringToCustomTimeZone, ) let endDateStr = formatDateString( ~dateVal=endDateVal, ~buttonText="", ~defaultLabel=endDateVal, ~isoStringToCustomTimeZone, ) `${startDateStr} - ${endDateStr}` }, [comparison]) <div onClick={_ => onClick(value)} className={`text-center md:text-start min-w-max bg-white w-full hover:bg-jp-gray-100 hover:bg-opacity-75 cursor-pointer mx-2 rounded-md p-2 text-sm font-medium text-grey-900 `}> {switch value { | No_Comparison => "No Comparison"->React.string | Previous_Period => <div> {"Previous Period : "->React.string} <span className="opacity-70"> {{previousPeriod}->React.string} </span> </div> | Custom => "Custom Range"->React.string }} </div> } } module ButtonRightIcon = { open LogicUtils @react.component let make = ( ~startDateVal, ~endDateVal, ~setStartDateVal, ~setEndDateVal, ~disable, ~isDropdownOpen, ~removeFilterOption, ~resetToInitalValues, ) => { let buttonIcon = isDropdownOpen ? "angle-up" : "angle-down" let removeApplyFilter = ev => { ev->ReactEvent.Mouse.stopPropagation resetToInitalValues() setStartDateVal(_ => "") setEndDateVal(_ => "") } <div className="flex flex-row gap-2"> <Icon className={getStrokeColor(disable, isDropdownOpen)} name=buttonIcon size=14 /> <RenderIf condition={removeFilterOption && startDateVal->isNonEmptyString && endDateVal->isNonEmptyString}> <Icon name="crossicon" size=16 onClick=removeApplyFilter /> </RenderIf> </div> } } module DateSelectorButton = { open LogicUtils @react.component let make = ( ~startDateVal, ~endDateVal, ~setStartDateVal, ~setEndDateVal, ~disable, ~isDropdownOpen, ~removeFilterOption, ~resetToInitalValues, ~showTime, ~buttonText, ~showSeconds, ~predefinedOptionSelected, ~disableFutureDates, ~onClick, ~buttonType, ~textStyle, ~iconBorderColor, ~customButtonStyle, ~enableToolTip=true, ~showLeftIcon=true, ~isCompare=false, ~comparison, ) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let isMobileView = MatchMedia.useMobileChecker() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let startDateStr = formatDateString( ~dateVal=startDateVal, ~buttonText, ~defaultLabel="[From-Date]", ~isoStringToCustomTimeZone, ) let endDateStr = formatDateString( ~dateVal=endDateVal, ~buttonText, ~defaultLabel="[To-Date]", ~isoStringToCustomTimeZone, ) let startTimeStr = formatTimeString( ~timeVal=startDateVal->getTimeStringForValue(isoStringToCustomTimeZone), ~defaultTime="00:00:00", ~showSeconds, ) let endTimeStr = formatTimeString( ~timeVal=endDateVal->getTimeStringForValue(isoStringToCustomTimeZone), ~defaultTime="23:59:59", ~showSeconds, ) let tooltipText = { switch (startDateVal->isEmptyString, endDateVal->isEmptyString, showTime) { | (true, true, _) => `Select Date ${showTime ? "and Time" : ""}` | (false, true, true) => `${startDateStr} ${startTimeStr} - Now` | (false, false, true) => `${startDateStr} ${startTimeStr} - ${endDateStr} ${endTimeStr}` | (false, false, false) => `${startDateStr} ${startDateStr === buttonText ? "" : "-"} ${endDateStr}` | _ => "" } } let formatText = text => isMobileView ? "" : text let buttonText = getButtonText( ~predefinedOptionSelected, ~disableFutureDates, ~startDateVal, ~endDateVal, ~buttonText, ~isoStringToCustomTimeZone, ~comparison, )->formatText let leftIcon = if isCompare { let text = buttonText === "No Comparison" ? "" : "Compare: " Button.CustomIcon(<span className="font-medium text-sm"> {text->React.string} </span>) } else if showLeftIcon { Button.CustomIcon(<Icon name="calendar-filter" size=22 />) } else { Button.NoIcon } let rightIcon = { Button.CustomIcon( <ButtonRightIcon startDateVal endDateVal setStartDateVal setEndDateVal disable isDropdownOpen removeFilterOption resetToInitalValues />, ) } let textStyle = switch textStyle { | Some(value) => value | None => isCompare ? textColor.primaryNormal : "" } let button = <Button text={buttonText} leftIcon rightIcon buttonSize={Large} isDropdownOpen onClick iconBorderColor customButtonStyle buttonState={disable ? Disabled : Normal} ?buttonType textStyle /> if enableToolTip { <ToolTip description={tooltipText} toolTipFor={button} justifyClass="justify-end" toolTipPosition={Top} /> } else { button } } }
1,402
9,989
hyperswitch-control-center
src/components/ReactWindowTable.res
.res
open TableUtils type checkBoxProps = { showCheckBox: bool, selectedData: array<JSON.t>, setSelectedData: (array<JSON.t> => array<JSON.t>) => unit, } let checkBoxPropDefaultVal: checkBoxProps = { showCheckBox: false, selectedData: [], setSelectedData: _ => (), } module FilterRow = { @react.component let make = ( ~item: filterRow, ~hideFilter, ~removeVerticalLines, ~tableDataBorderClass, ~isLast, ~cellIndex, ~cellWidth, ) => { <div className={`flex flex-row group h-full border-t dark:border-jp-gray-960 ${cellWidth} bg-white dark:bg-jp-gray-lightgray_background hover:bg-jp-gray-table_hover dark:hover:bg-jp-gray-100 dark:hover:bg-opacity-10 transition duration-300 ease-in-out text-fs-13 text-jp-gray-900 text-opacity-75 dark:text-jp-gray-text_darktheme dark:text-opacity-75`}> { let paddingClass = "py-3 px-3" let borderClass = if isLast { ` border-jp-gray-light_table_border_color dark:border-jp-gray-960` } else if removeVerticalLines { ` border-jp-gray-light_table_border_color dark:border-jp-gray-960` } else { ` border-r border-jp-gray-light_table_border_color dark:border-jp-gray-960` } { if hideFilter { React.null } else { <div key={Int.toString(cellIndex)} className={`h-full p-0 align-top ${borderClass} ${tableDataBorderClass} ${cellWidth}`}> <div className={`h-full box-border ${paddingClass}`}> <TableFilterCell cell=item /> </div> </div> } } } </div> } } module NewCell = { @react.component let make = ( ~item: array<cell>, ~rowIndex, ~onRowClick, ~onRowClickPresent, ~removeVerticalLines, ~highlightEnabledFieldsArray, ~tableDataBorderClass="", ~collapseTableRow=false, ~expandedRow: _ => React.element, ~onMouseEnter, ~onMouseLeave, ~style, ~setExpandedIndexArr, ~expandedIndexArr, ~handleExpand, ~highlightText="", ~columnWidthArr, ~showSerialNumber=false, ~customSerialNoColumn=false, ~customCellColor="", ~showCheckBox=false, ) => { open Window let onClick = React.useCallback(_ => { let isRangeSelected = getSelection().\"type" == "Range" switch (onRowClick, isRangeSelected) { | (Some(fn), false) => fn(rowIndex) | _ => () } }, (onRowClick, rowIndex)) let isCurrentRowExpanded = React.useMemo(() => { expandedIndexArr->Array.includes(rowIndex) }, [expandedIndexArr]) let onMouseEnter = React.useCallback(_ => { switch onMouseEnter { | Some(fn) => fn(rowIndex) | _ => () } }, (onMouseEnter, rowIndex)) let onMouseLeave = React.useCallback(_ => { switch onMouseLeave { | Some(fn) => fn(rowIndex) | _ => () } }, (onMouseLeave, rowIndex)) let colsLen = item->Array.length let cursorClass = onRowClickPresent ? "cursor-pointer" : "" let customcellColouredCellCheck = item ->Array.map((obj: cell) => { switch obj { | CustomCell(_, x) => x->String.split(",")->Array.includes("true") | _ => false } }) ->Array.includes(true) let customcellColouredCell = customcellColouredCellCheck && customCellColor->LogicUtils.isNonEmptyString ? customCellColor : "bg-white hover:bg-jp-gray-table_hover dark:hover:bg-jp-gray-850" <div className={`h-full ${customcellColouredCell} border-t border-jp-gray-light_table_border_color dark:border-jp-gray-960 dark:bg-jp-gray-lightgray_background transition duration-300 ease-in-out `} style> <div className={`flex flex-row group rounded-md ${cursorClass} text-fs-13 text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-75 overflow-hidden break-words`} onClick onMouseEnter onMouseLeave> {item ->Array.mapWithIndex((obj: cell, cellIndex) => { let cellWidth = if cellIndex === colsLen - 1 { "w-full" } else if ( (showCheckBox && cellIndex === 0) || showSerialNumber && cellIndex === 0 || (showSerialNumber && showCheckBox && cellIndex === 1) ) { "w-24" } else { columnWidthArr ->Array.get(cellIndex) ->Option.getOr(`${cellIndex === 0 && customSerialNoColumn ? "w-24" : "w-64"}`) } let overflowStyle = cellIndex === colsLen ? "overflow-hidden" : "" let isLast = cellIndex === colsLen - 1 let paddingClass = switch obj { | Link(_) => "pt-2" | _ => "py-3" } let highlightCell = highlightEnabledFieldsArray->Array.includes(cellIndex) let borderClass = if isLast || removeVerticalLines { `border-jp-gray-light_table_border_color dark:border-jp-gray-960` } else { `border-r border-jp-gray-light_table_border_color dark:border-jp-gray-960` } let cursorI = cellIndex == 0 ? "cursor-pointer" : "" <div key={Int.toString(cellIndex)} className={`${cellWidth} ${overflowStyle} h-auto align-top ${borderClass} ${highlightCell ? "hover:font-bold" : ""} ${tableDataBorderClass} ${collapseTableRow ? cursorI : ""}`} onClick={_ => { if collapseTableRow && cellIndex == 0 { handleExpand(rowIndex, true) if !isCurrentRowExpanded { setExpandedIndexArr(prev => { prev->Array.concat([rowIndex]) }) } else { setExpandedIndexArr(prev => { prev->Array.filter(item => item != rowIndex) }) } } }}> <div className={`${cellWidth} h-full box-border pl-4 ${paddingClass}`}> {if collapseTableRow { <div className="flex flex-row gap-4 items-center"> {if cellIndex === 0 { <Icon name={isCurrentRowExpanded ? "caret-down" : "caret-right"} size=14 /> } else { React.null }} <TableCell cell=obj highlightText hideShowMore=true /> </div> } else { <TableCell cell=obj highlightText /> }} </div> </div> }) ->React.array} </div> {if isCurrentRowExpanded { <div className="dark:border-jp-gray-dark_disable_border_color ml-10"> {expandedRow()} </div> } else { React.null }} </div> } } module ReactWindowTableComponent = { @react.component let make = ( ~heading=[], ~rows, ~onRowClick=?, ~onRowClickPresent=false, ~fullWidth, ~removeVerticalLines=true, ~showScrollBar=false, ~columnFilterRow=?, ~tableheadingClass="", ~tableBorderClass="", ~tableDataBorderClass="", ~collapseTableRow=false, ~getRowDetails=?, ~getIndex=?, ~rowItemHeight=100, ~selectAllCheckBox=?, ~setSelectAllCheckBox=?, ~actualData=?, ~onMouseEnter=?, ~onMouseLeave=?, ~highlightText="", ~tableHeight, ~columnWidth, ~showSerialNumber=false, ~customSerialNoColumn=false, ~customCellColor="", ~showCheckBox=false, ) => { let actualData: option<array<Nullable.t<'t>>> = actualData let getRowDetails = (rowIndex: int) => { switch actualData { | Some(actualData) => switch getRowDetails { | Some(fn) => fn(actualData->Array.get(rowIndex)->Option.getOr(Nullable.null)) | None => React.null } | None => React.null } } let getIndex = (rowIndex: int) => { switch getIndex { | Some(fn) => fn(rowIndex) | None => () } } let fn = React.useRef((_, _) => ()) let rowInfo: array<array<cell>> = rows let (expandedIndexArr, setExpandedIndexArr) = React.useState(_ => []) let handleExpand = (index, bool) => fn.current(index, bool) React.useEffect(() => { setExpandedIndexArr(_ => []) handleExpand(0, true) None }, [rowInfo->Array.length]) let headingsLen = heading->Array.length let widthClass = if fullWidth { "min-w-full" } else { "" } let scrollBarClass = if showScrollBar { "show-scrollbar" } else { "no-scrollbar" } let filterPresent = heading->Array.find(head => head.showFilter)->Option.isSome let highlightEnabledFieldsArray = heading->Array.reduceWithIndex([], (acc, item, index) => { if item.highlightCellOnHover { let _ = Array.push(acc, index) } acc }) let colFilt = columnFilterRow->Option.getOr([]) let colFilter = showCheckBox ? [TextFilter("")]->Array.concat(colFilt) : colFilt let arr = switch columnWidth { | Some(arr) => arr | _ => heading->Array.mapWithIndex((_, i) => { i === 0 && customSerialNoColumn ? "w-24" : "w-64" }) } let headingReact = if heading->Array.length !== 0 { <div className="sticky z-10 top-0 "> <div className="flex flex-row"> {heading ->Array.mapWithIndex((item, i) => { let isFirstCol = i === 0 let isLastCol = i === headingsLen - 1 let cellWidth = if i === heading->Array.length - 1 { "w-full" } else if ( (showCheckBox && i === 0) || showSerialNumber && i === 0 || (showSerialNumber && showCheckBox && i === 1) ) { "w-24" } else { arr ->Array.get(i) ->Option.getOr(`${isFirstCol && customSerialNoColumn ? "w-24" : "w-64"}`) } let roundedClass = if isFirstCol { "rounded-tl" } else if isLastCol { "rounded-tr" } else { "" } let borderClass = if isLastCol { "" } else if removeVerticalLines { "border-jp-gray-500 dark:border-jp-gray-960" } else { "border-r border-jp-gray-500 dark:border-jp-gray-960" } let (isAllSelected, isSelectedStateMinus, checkboxDimension) = ( selectAllCheckBox->Option.isSome, selectAllCheckBox === Some(PARTIAL), "h-4 w-4", ) let setIsSelected = isAllSelected => { switch setSelectAllCheckBox { | Some(fn) => fn(_ => { if isAllSelected { Some(ALL) } else { None } }) | None => () } } <div key={Int.toString(i)} className={` ${cellWidth} ${borderClass} justify-between items-center bg-white dark:bg-jp-gray-darkgray_background text-opacity-75 dark:text-jp-gray-text_darktheme dark:text-opacity-75 whitespace-pre select-none ${roundedClass} ${tableheadingClass}`}> <div className={`flex flex-row ${cellWidth} pl-2 py-4 bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 text-jp-gray-900`}> <div className=""> <div className="flex flex-row"> <div className="font-bold text-fs-13"> {React.string(item.title)} </div> <RenderIf condition={item.description->Option.isSome}> <div className="text-sm text-gray-500 mx-2"> <ToolTip description={item.description->Option.getOr("")} toolTipPosition={ToolTip.Bottom} /> </div> </RenderIf> </div> <RenderIf condition={item.showMultiSelectCheckBox->Option.getOr(false)}> <div className=" mt-1 mr-2"> <CheckBoxIcon isSelected={isAllSelected} setIsSelected isSelectedStateMinus checkboxDimension /> </div> </RenderIf> <RenderIf condition={item.data->Option.isSome}> <div className="flex justify-start font-bold text-fs-10 whitespace-pre text-ellipsis overflow-x-hidden"> {React.string(item.data->Option.getOr(""))} </div> </RenderIf> </div> </div> <div> { let len = colFilter->Array.length switch colFilter->Array.get(i) { | Some(fitlerRows) => <FilterRow item=fitlerRows hideFilter={showCheckBox && isFirstCol} removeVerticalLines tableDataBorderClass isLast={i === len - 1} cellIndex=i cellWidth /> | None => React.null } } </div> </div> }) ->React.array} </div> </div> } else { React.null } let rows = index => { rowInfo->Array.length == 0 ? React.null : { let rowIndex = index->LogicUtils.getInt("index", 0) getIndex(rowIndex) let item = rowInfo->Array.get(rowIndex)->Option.getOr([]) let style = index->LogicUtils.getJsonObjectFromDict("style")->Identity.jsonToReactDOMStyle <> <NewCell key={Int.toString(rowIndex)} item rowIndex onRowClick onRowClickPresent removeVerticalLines highlightEnabledFieldsArray tableDataBorderClass collapseTableRow expandedRow={_ => getRowDetails(rowIndex)} onMouseEnter onMouseLeave style setExpandedIndexArr expandedIndexArr handleExpand highlightText columnWidthArr=arr showSerialNumber customSerialNoColumn customCellColor showCheckBox /> </> } } let getHeight = index => { if expandedIndexArr->Array.includes(index) { 500 } else { rowItemHeight } } <div className={` overflow-x-scroll ${scrollBarClass}`} style={minHeight: {filterPresent ? "30rem" : ""}}> <div className={`w-max ${widthClass} h-full border border-jp-gray-940 border-opacity-50 dark:border-jp-gray-960 rounded-lg ${tableBorderClass}`} colSpan=0> <div className="bg-white dark:bg-jp-gray-lightgray_background"> {headingReact} <ReactWindow.VariableSizeList ref={el => { open ReactWindow.ListComponent fn.current = (index, val) => el->resetAfterIndex(index, val) }} itemSize={index => getHeight(index)} height=tableHeight overscanCount=6 itemCount={rowInfo->Array.length}> {rows} </ReactWindow.VariableSizeList> </div> </div> </div> } } open DynamicTableUtils type sortTyp = ASC | DSC type sortOb = { sortKey: string, sortType: sortTyp, } let sortAtom: Recoil.recoilAtom<Dict.t<sortOb>> = Recoil.atom("sortAtom", Dict.make()) 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) => x | Number(_num) => x | Bool(val) => val ? "true"->JSON.Encode.string : "false"->JSON.Encode.string | _ => ""->JSON.Encode.string } | None => ""->JSON.Encode.string } } let sortedArrayByOrder = { let _ = 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 = item1->JSON.Decode.object->Option.flatMap(dict => dict->Dict.get(key)) let val2 = item2->JSON.Decode.object->Option.flatMap(dict => dict->Dict.get(key)) let value1 = getValue(val1) let value2 = getValue(val2) if value1 === value2 { 0. } else if value1 > value2 { sortOrder === DEC ? 1. : -1. } else if sortOrder === DEC { -1. } else { 1. } }) originalData } sortedArrayByOrder } @react.component let make = ( ~actualData: array<Nullable.t<'t>>, ~title, ~visibleColumns=?, ~description=?, ~tableActions=?, ~rightTitleElement=React.null, ~bottomActions=?, ~showSerialNumber=false, ~totalResults, ~entity: EntityType.entityType<'colType, 't>, ~onEntityClick=?, ~removeVerticalLines=true, ~downloadCsv=?, ~hideTitle=false, ~tableDataLoading=false, ~dataNotFoundComponent=?, ~tableLocalFilter=false, ~tableheadingClass="", ~tableBorderClass="", ~tableDataBorderClass="", ~collapseTableRow=false, ~getRowDetails=?, ~getIndex=?, ~rowItemHeight=100, ~checkBoxProps: checkBoxProps=checkBoxPropDefaultVal, ~showScrollBar=false, ~onMouseEnter=?, ~onMouseLeave=?, ~activeColumnsAtom=?, ~highlightText="", ~tableHeight=500, ~columnWidth=?, ~customSerialNoColumn=false, ~customCellColor=?, ~filterWithIdOnly=false, ~fullWidth=true, ) => { let (columnFilter, setColumnFilterOrig) = React.useState(_ => Dict.make()) let url = RescriptReactRouter.useUrl() let dateFormatConvertor = useDateFormatConvertor() let (showColumnSelector, setShowColumnSelector) = React.useState(() => false) let chooseCols = <ChooseColumnsWrapper entity totalResults defaultColumns=entity.defaultColumns activeColumnsAtom setShowColumnSelector showColumnSelector /> let filterSection = <div className="flex flex-row gap-4"> {chooseCols} </div> let customizeColumnButtonType: Button.buttonType = SecondaryFilled let customizeButtonTextStyle = "" let customizeColumn = if ( Some(activeColumnsAtom)->Option.isSome && entity.allColumns->Option.isSome && actualData->Array.length > 0 ) { <Button text="Customize Columns" leftIcon={CustomIcon(<Icon name="vertical_slider" size=15 className="mr-1" />)} textStyle=customizeButtonTextStyle buttonType=customizeColumnButtonType buttonSize=Small onClick={_ => { setShowColumnSelector(_ => true) }} customButtonStyle="" showBorder={false} /> } else { React.null } 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->LogicUtils.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]) 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) 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 {getShowLink} = entity let columToConsider = React.useMemo(() => { switch (entity.allColumns, visibleColumns) { | (Some(allCol), _) => Some(allCol) | (_, Some(visibleColumns)) => Some(visibleColumns) | _ => Some(entity.defaultColumns) } }, (entity.allColumns, visibleColumns, entity.defaultColumns)) 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 dictArrObj = Dict.make() let columnFilterCopy = columnFilter->DictionaryUtils.deleteKey(key) let newValues = actualData ->filteredData(columnFilterCopy, visibleColumns, entity, dateFormatConvertor) ->Belt.Array.keepMap( item => { item->Nullable.toOption }, ) switch columToConsider { | Some(allCol) => newValues->Array.forEach( rows => { allCol->Array.forEach( item => { let heading = {item->entity.getHeading} let key = heading.key let dataType = heading.dataType 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, "") } switch dictArrObj->Dict.get(key) { | Some(arr) => Dict.set(dictArrObj, key, Array.concat(arr, [value])) | None => Dict.set(dictArrObj, key, [value]) } }, ) }, ) | None => () } let filterValueArray = dictArrObj->Dict.get(key)->Option.getOr([]) 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.)) ->Array.toSorted(LogicUtils.numericArraySortComperator) let lengthOfArr = newArr->Array.length if lengthOfArr >= 2 { Table.Range( key, newArr[0]->Option.getOr(0.), newArr[lengthOfArr - 1]->Option.getOr(0.), ) } else if lengthOfArr >= 1 { Table.Range(key, newArr[0]->Option.getOr(0.), newArr[0]->Option.getOr(0.)) } 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, columToConsider, totalResults, visibleColumns, columnFilter)) let actualData = if tableLocalFilter { filteredData(actualData, columnFilter, visibleColumns, entity, dateFormatConvertor) } else { actualData } let selectAllCheckBox = React.useMemo(() => { let selectedRowDataLength = checkBoxProps.selectedData->Array.length let isCompleteDataSelected = selectedRowDataLength === actualData->Array.length if isCompleteDataSelected { Some(ALL) } else if checkBoxProps.selectedData->Array.length === 0 { None } else { Some(PARTIAL) } }, (checkBoxProps.selectedData, actualData)) let setSelectAllCheckBox = React.useCallback( (v: option<TableUtils.multipleSelectRows> => option<TableUtils.multipleSelectRows>) => { switch v(selectAllCheckBox) { | Some(ALL) => checkBoxProps.setSelectedData(_ => { actualData->Array.map(Identity.nullableOfAnyTypeToJsonType) }) | Some(PARTIAL) | None => checkBoxProps.setSelectedData(_ => []) } }, [selectAllCheckBox], ) React.useEffect(() => { if selectAllCheckBox === Some(ALL) { checkBoxProps.setSelectedData(_ => { actualData->Array.map(Identity.nullableOfAnyTypeToJsonType) }) } else if selectAllCheckBox === None { checkBoxProps.setSelectedData(_ => []) } None }, [selectAllCheckBox]) let sNoArr = Dict.get(columnFilter, "s_no")->Option.getOr([]) // filtering for SNO let rows = actualData ->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 getIdFromJson = json => { let selectedPlanDict = json->JSON.Decode.object->Option.getOr(Dict.make()) selectedPlanDict->LogicUtils.getString("id", "") } let setIsSelected = isSelected => { if isSelected { checkBoxProps.setSelectedData(prev => prev->Array.concat([nullableItem->Identity.nullableOfAnyTypeToJsonType]) ) } else { checkBoxProps.setSelectedData(prev => if filterWithIdOnly { prev->Array.filter( item => getIdFromJson(item) !== getIdFromJson(nullableItem->Identity.nullableOfAnyTypeToJsonType), ) } else { prev->Array.filter( item => item !== nullableItem->Identity.nullableOfAnyTypeToJsonType, ) } ) } } if showSerialNumber && actualRows->Array.length > 0 { actualRows ->Array.unshift( Numeric( (1 + index)->Int.toFloat, (val: float) => { val->Float.toString }, ), ) ->ignore } if checkBoxProps.showCheckBox { let selectedRowIndex = checkBoxProps.selectedData->Array.findIndex(item => if filterWithIdOnly { getIdFromJson(item) == getIdFromJson(nullableItem->Identity.nullableOfAnyTypeToJsonType) } else { 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)->LogicUtils.getStringFromBool, ), ) ->ignore } actualRows }) ->Belt.Array.keepMap(item => { item->Array.length == 0 ? None : Some(item) }) let dataExists = rows->Array.length > 0 let heading = heading->Array.mapWithIndex((head, index) => { let getValue = row => row->Array.get(index)->Option.mapOr("", Table.getTableCellValue) let default = switch rows[0] { | Some(ele) => getValue(ele) | None => "" } let head: Table.header = { ...head, showSort: head.showSort && dataExists && ( totalResults == Array.length(rows) ? rows->Array.some(row => getValue(row) !== default) : true ), } head }) let handleRowClick = React.useCallback(index => { let actualVal = switch actualData[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->LogicUtils.isNonEmptyString ? `${link}?${url.search}` : link RescriptReactRouter.push(finalUrl) } | None => () } } | None => () } }, (actualData, getShowLink, onEntityClick, url.search)) let handleMouseEnter = React.useCallback(index => { let actualVal = switch actualData[index] { | Some(ele) => ele->Nullable.toOption | None => None } switch actualVal { | Some(value) => switch onMouseEnter { | Some(fn) => fn(value) | None => () } | None => () } }, (actualData, getShowLink, onMouseEnter, url.search)) let handleMouseLeave = React.useCallback(index => { let actualVal = switch actualData[index] { | Some(ele) => ele->Nullable.toOption | None => None } switch actualVal { | Some(value) => switch onMouseLeave { | Some(fn) => fn(value) | None => () } | None => () } }, (actualData, getShowLink, onMouseLeave, url.search)) <AddDataAttributes attributes=[("data-loaded-table", title)]> <div> <div className={` bg-gray-50 dark:bg-jp-gray-darkgray_background empty:hidden`} style={zIndex: "2"}> <div className="flex flex-row justify-between items-center mt-4 mb-2"> {if hideTitle { React.null } else { <TableHeading title noVerticalMargin=true ?description /> }} customizeColumn </div> rightTitleElement <div className="flex flex-row my-2"> <TableFilterSectionContext isFilterSection=true> <div className="flex-1"> {filterSection->React.Children.map(element => { if element === React.null { React.null } else { <div className="pb-3"> element </div> } })} </div> </TableFilterSectionContext> <div className="flex flex-row"> {switch tableActions { | Some(actions) => <LoadedTableContext value={actualData->LoadedTableContext.toInfoData}> actions </LoadedTableContext> | None => React.null }} </div> </div> </div> {if totalResults > 0 { <div> { let children = <ReactWindowTableComponent actualData heading rows onRowClick=handleRowClick onRowClickPresent={onEntityClick->Option.isSome || getShowLink->Option.isSome} fullWidth removeVerticalLines showScrollBar=false ?columnFilterRow tableheadingClass tableBorderClass tableDataBorderClass collapseTableRow ?getRowDetails ?getIndex rowItemHeight ?selectAllCheckBox setSelectAllCheckBox onMouseEnter=handleMouseEnter onMouseLeave=handleMouseLeave highlightText tableHeight columnWidth showSerialNumber customSerialNoColumn ?customCellColor showCheckBox=checkBoxProps.showCheckBox /> switch tableLocalFilter { | true => <DatatableContext value={filterValue}> <DataTableFilterOpenContext value={filterOpenValue}> children </DataTableFilterOpenContext> </DatatableContext> | false => children } } </div> } else if totalResults === 0 && !tableDataLoading { switch dataNotFoundComponent { | Some(comp) => comp | None => <NoDataFound message="No Data Available" renderType=Painting /> } } else { React.null }} {if tableDataLoading { <TableDataLoadingIndicator showWithData={rows->Array.length !== 0} /> } else { React.null }} {switch bottomActions { | Some(actions) => <LoadedTableContext value={actualData->LoadedTableContext.toInfoData}> actions </LoadedTableContext> | None => React.null }} {switch downloadCsv { | Some(actionData) => <div className="flex justify-end mt-4 mb-2 "> <LoadedTableContext value={actualData->LoadedTableContext.toInfoData}> actionData </LoadedTableContext> </div> | None => React.null }} </div> </AddDataAttributes> }
8,342
9,990
hyperswitch-control-center
src/components/NotFoundPage.res
.res
@react.component let make = (~message="Error 404!") => { let {setDashboardPageState} = React.useContext(GlobalProvider.defaultContext) <NoDataFound message renderType={NotFound}> <Button text={"Go to Home"} buttonType=Primary buttonSize=Small onClick={_ => { setDashboardPageState(_ => #HOME) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/home")) }} customButtonStyle="mt-4" /> </NoDataFound> }
121
9,991
hyperswitch-control-center
src/components/Button.resi
.resi
type buttonState = Normal | Loading | Disabled | NoHover | Focused type buttonVariant = Fit | Long | Full | Rounded type buttonType = | Primary | Secondary | PrimaryOutline | SecondaryFilled | NonFilled | Pagination | Pill | FilterAdd | Delete | Transparent | SelectTransparent | DarkPurple | Dropdown type buttonSize = Large | Medium | Small | XSmall type iconType = | FontAwesome(string) | CustomIcon(React.element) | CustomRightIcon(React.element) | Euler(string) | NoIcon type badgeColor = | BadgeGreen | BadgeRed | BadgeBlue | BadgeGray | BadgeOrange | BadgeYellow | BadgeDarkGreen | BadgeDarkRed | NoBadge type badge = {value: string, color: badgeColor} let useGetBgColor: ( ~buttonType: buttonType, ~buttonState: buttonState, ~showBorder: bool, ~isDropdownOpen: bool=?, ~isPhoneDropdown: bool=?, ) => string let useGetTextColor: ( ~buttonType: buttonType, ~buttonState: buttonState, ~showBorder: bool, ~isDropdownOpen: bool=?, ~isPhoneDropdown: bool=?, ) => string @react.component let make: ( ~buttonFor: string=?, ~loadingText: string=?, ~buttonState: buttonState=?, ~text: string=?, ~isSelectBoxButton: bool=?, ~buttonType: buttonType=?, ~isDropdownOpen: bool=?, ~buttonVariant: buttonVariant=?, ~buttonSize: buttonSize=?, ~leftIcon: iconType=?, ~rightIcon: iconType=?, ~showBorder: bool=?, ~type_: string=?, ~flattenBottom: bool=?, ~flattenTop: bool=?, ~onEnterPress: bool=?, ~onClick: JsxEvent.Mouse.t => unit=?, ~textStyle: string=?, ~iconColor: string=?, ~iconBorderColor: string=?, ~customIconMargin: string=?, ~customTextSize: string=?, ~customIconSize: int=?, ~textWeight: string=?, ~fullLength: bool=?, ~disableRipple: bool=?, ~customButtonStyle: string=?, ~textStyleClass: string=?, ~customTextPaddingClass: string=?, ~allowButtonTextMinWidth: bool=?, ~badge: badge=?, ~buttonRightText: string=?, ~ellipsisOnly: bool=?, ~isRelative: bool=?, ~customPaddingClass: string=?, ~customRoundedClass: string=?, ~customHeightClass: string=?, ~customBackColor: string=?, ~isPhoneDropdown: bool=?, ~showBtnTextToolTip: bool=?, ~showTooltip: bool=?, ~tooltipText: string=?, ~toolTipPosition: ToolTip.toolTipPosition=?, ~dataTestId: string=?, ) => React.element
706
9,992
hyperswitch-control-center
src/components/BottomModal.res
.res
@react.component let make = (~onCloseClick, ~children, ~headerText) => { let onClick = e => { e->ReactEvent.Mouse.stopPropagation } <div onClick className={`flex flex-col border border-jp-gray-500 dark:border-jp-gray-960 bg-jp-gray-950 dark:bg-white-600 dark:bg-opacity-80 fixed bg-opacity-70 h-screen w-screen z-40 pt-12 flex justify-end inset-0 backdrop-blur-sm overscroll-contain`}> <div className={`!pl-4 desktop:bg-gray-200 z-10 sticky top-0 w-full top-0 m-0 md:!pl-6 dark:bg-jp-gray-850 p-4 border border-jp-gray-500 dark:border-jp-gray-900 bg-jp-gray-100 dark:bg-jp-gray-lightgray_background shadow dark:text-opacity-75 dark:bg-jp-gray-darkgray_background h-fit`}> <div className={`text-lg font-bold flex flex-row justify-between -mr-2`}> {React.string(headerText)} <ModalCloseIcon onClick={onCloseClick} /> </div> </div> <div className={`border border-jp-gray-500 dark:border-jp-gray-900 shadow dark:text-opacity-75 dark:bg-jp-gray-darkgray_background overflow-scroll`}> {children} </div> </div> }
339
9,993
hyperswitch-control-center
src/components/HSwitchSingleStatTableWidget.res
.res
type statChartColor = [#blue | #grey] type tableRowType = { rowLabel: string, rowValue: float, } type cols = | Label | Value let visibleColumns = [Label, Value] let colMapper = (col: cols) => { switch col { | Label => "rowLabel" | Value => "rowValue" } } let tableItemToObjMapper: 'a => tableRowType = dict => { open LogicUtils { { rowLabel: dict->getString(Label->colMapper, "NA"), rowValue: dict->getFloat(Value->colMapper, 0.0), } } } let getObjects: JSON.t => array<tableRowType> = json => { open LogicUtils json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { let key = colType->colMapper switch colType { | Label => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=TextType) | Value => Table.makeHeaderInfo(~key, ~title="Amount", ~dataType=TextType) } } let percentFormat = value => { `${Float.toFixedWithPrecision(value, ~digits=2)}%` } type statType = Amount | Rate | NegativeRate | Volume | Latency | LatencyMs | Default let stringToVarient = statType => { switch statType { | "Amount" => Amount | "Rate" => Rate | "NegativeRate" => NegativeRate | "Volume" => Volume | "Latency" => Latency | "LatencyMs" => LatencyMs | _ => Default } } // if day > then only date else time let statValue = (val, statType) => { let statType = statType->stringToVarient open LogicUtils switch statType { | Amount => val->indianShortNum | Rate | NegativeRate => val->Js.Float.isNaN ? "-" : val->percentFormat | Volume => val->indianShortNum | Latency => latencyShortNum(~labelValue=val) | LatencyMs => latencyShortNum(~labelValue=val, ~includeMilliseconds=true) | Default => val->Float.toString } } let getCell = (obj, colType, stateType): Table.cell => { switch colType { | Label => Text(obj.rowLabel) | Value => Text(obj.rowValue->statValue(stateType)) } } module ShowMore = { @react.component let make = (~value: array<tableRowType>, ~title, ~tableEntity) => { let (showModal, setShowModal) = React.useState(_ => false) let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let tableData = if value->Array.length > 0 { value->Array.map(item => { item->Nullable.make }) } else { [] } let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30" <> <div className="flex text-blue-900 text-sm font-bold cursor-pointer justify-end w-full" onClick={_ => setShowModal(_ => !showModal)}> {"more.."->React.string} </div> <Modal closeOnOutsideClick=true modalHeading=title showModal setShowModal modalClass="w-full max-w-lg mx-auto md:mt-44 "> <LoadedTable visibleColumns title="HSwitch Single Stat Table" hideTitle=true actualData={tableData} entity=tableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass showResultsPerPageSelector=false tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </Modal> </> } } @react.component let make = ( ~deltaTooltipComponent=React.null, ~value: array<tableRowType>, ~title="", ~tooltipText="", ~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 isMobileWidth = MatchMedia.useMatchMedia("(max-width: 700px)") let tableEntity = EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="", ~defaultColumns=visibleColumns, ~requiredSearchFieldsList=[], ~allColumns=visibleColumns, ~getCell=(tableRowType, cols) => getCell(tableRowType, cols, statType), ~getHeading, ) let modifiedData = value->Array.filter(val => val.rowValue > 0.0) 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={`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-start h-full gap-2"> <RenderIf condition={singleStatLoading && loaderType === SideLoader}> <div className="animate-spin self-end absolute"> <Icon name="spinner" size=16 /> </div> </RenderIf> <div className={"flex gap-2 items-center text-jp-gray-700 font-bold self-start"}> <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 className="flex gap-1 flex-col w-full mt-1"> {if modifiedData->Array.length > 0 { <> {modifiedData ->Array.filterWithIndex((_val, index) => index < 3) ->Array.mapWithIndex((item, index) => { <div key={index->Int.toString} className="flex justify-between w-full text-sm opacity-70"> <div> {item.rowLabel->React.string} </div> <div> {item.rowValue->statValue(statType)->React.string} </div> </div> }) ->React.array} <RenderIf condition={modifiedData->Array.length > 5}> <ShowMore value=modifiedData title tableEntity /> </RenderIf> </> } else { <div className="w-full border flex justify-center border-dashed text-sm opacity-70 rounded-lg px-5 py-2"> {"No Data"->React.string} </div> }} </div> </div> </div> </div> } }
1,815
9,994
hyperswitch-control-center
src/components/AdvancedSearchComponent.res
.res
let getSummary: JSON.t => EntityType.summary = json => { switch json->JSON.Decode.object { | Some(dict) => { let rowsCount = LogicUtils.getArrayFromDict(dict, "rows", [])->Array.length let totalCount = LogicUtils.getInt(dict, "entries", 0) {totalCount, count: rowsCount} } | None => {totalCount: 0, count: 0} } } @react.component let make = (~children, ~setData=?, ~entity: EntityType.entityType<'colType, 't>, ~setSummary=?) => { let {getObjects, searchUrl: url} = entity let fetchApi = AuthHooks.useApiFetcher() let initialValueJson = JSON.Encode.object(Dict.make()) let showToast = ToastState.useShowToast() let (showModal, setShowModal) = React.useState(_ => false) let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let onSubmit = (values, form: ReactFinalForm.formApi) => { open Promise fetchApi( url, ~bodyStr=JSON.stringify(values), ~method_=Post, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->then(res => res->Fetch.Response.json) ->then(json => { let jsonData = json->JSON.Decode.object->Option.flatMap(dict => dict->Dict.get("rows")) let newData = switch jsonData { | Some(actualJson) => actualJson->getObjects->Array.map(obj => obj->Nullable.make) | None => [] } let summaryData = json->JSON.Decode.object->Option.flatMap(dict => dict->Dict.get("summary")) let summary = switch summaryData { | Some(x) => x->getSummary | None => {totalCount: 0, count: 0} } switch setSummary { | Some(fn) => fn(_ => summary) | None => () } switch setData { | Some(fn) => fn(_ => Some(newData)) | None => () } setShowModal(_ => false) form.reset(JSON.Encode.object(Dict.make())->Nullable.make) 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 finalValuesDict = switch values->JSON.Decode.object { | Some(dict) => dict | None => Dict.make() } let keys = Dict.keysToArray(finalValuesDict) let errors = Dict.make() if keys->Array.length === 0 { Dict.set(errors, "Please Choose One of the fields", ""->JSON.Encode.string) } errors->JSON.Encode.object } <div className="mr-2"> <Button leftIcon={FontAwesome("search")} text={"Search"} buttonType=Primary onClick={_ => setShowModal(_ => true)} /> <Modal modalHeading="Search" showModal setShowModal modalClass="w-full md:w-5/12 mx-auto"> <Form onSubmit validate=validateForm initialValues=initialValueJson> {children} <div className="flex justify-center mb-2"> <div className="flex justify-between p-1"> <FormRenderer.SubmitButton text="Submit" /> </div> </div> </Form> </Modal> </div> }
797
9,995
hyperswitch-control-center
src/components/SearchInput.res
.res
open LottieFiles @react.component let make = ( ~onChange, ~inputText, ~autoFocus=true, ~placeholder="", ~searchIconCss="ml-2", ~roundedBorder=true, ~widthClass="w-full", ~heightClass="h-8", ~searchRef=?, ~shouldSubmitForm=true, ~placeholderCss="bg-transparent text-fs-14", ~bgColor="border-jp-gray-600 border-opacity-75 focus-within:border-primary", ~iconName="new_search_icon", ~onKeyDown=_ => {()}, ~showSearchIcon=false, ) => { let (prevVal, setPrevVal) = React.useState(_ => "") let showPopUp = PopUpState.useShowPopUp() let defaultRef = React.useRef(Nullable.null) let searchRef = searchRef->Option.getOr(defaultRef) let handleSearch = e => { setPrevVal(_ => inputText) let value = {e->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 searchStr = value->String.replace("<script>", "")->String.replace("</script>", "") // let searchStr = (e->ReactEvent.Form.target)["value"] onChange(searchStr) } let clearSearch = e => { e->ReactEvent.Mouse.stopPropagation onChange("") } let form = shouldSubmitForm ? None : Some("fakeForm") let borderClass = roundedBorder ? "border rounded-md pl-1 pr-2" : "border-b-2 focus-within:border-b" let exitCross = useLottieJson(exitSearchCross) let enterCross = useLottieJson(enterSearchCross) <div className={`${widthClass} ${borderClass} ${heightClass} flex flex-row items-center justify-between dark:bg-jp-gray-lightgray_background dark:focus-within:border-primary hover:border-opacity-100 dark:border-jp-gray-850 dark:border-opacity-50 dark:hover:border-opacity-100 ${bgColor} `}> <RenderIf condition={showSearchIcon}> <Icon name="nd-search" className="w-4 h-4" /> </RenderIf> <input ref={searchRef->ReactDOM.Ref.domRef} type_="text" value=inputText onChange=handleSearch placeholder className={`rounded-md w-full pl-2 focus:outline-none ${placeholderCss}`} autoFocus ?form onKeyDown /> <AddDataAttributes attributes=[("data-icon", "searchExit")]> <div className="h-6 flex w-6" onClick=clearSearch> <ReactSuspenseWrapper loadingText=""> <Lottie animationData={(prevVal->LogicUtils.isNonEmptyString && inputText->LogicUtils.isEmptyString) || (prevVal->LogicUtils.isEmptyString && inputText->LogicUtils.isEmptyString) ? exitCross : enterCross} autoplay=true loop=false /> </ReactSuspenseWrapper> </div> </AddDataAttributes> </div> }
758
9,996
hyperswitch-control-center
src/components/FilterUtils.res
.res
let parseFilterString = queryString => { queryString ->decodeURI ->String.split("&") ->Belt.Array.keepMap(str => { let arr = str->String.split("=") let key = arr->Array.get(0)->Option.getOr("-") let val = arr->Array.sliceToEnd(~start=1)->Array.joinWith("=") key->LogicUtils.isEmptyString || val->LogicUtils.isEmptyString ? None : Some((key, val)) }) ->Dict.fromArray } let parseFilterDict = dict => { dict ->Dict.toArray ->Array.map(item => { let (key, value) = item `${key}=${value}` }) ->Array.joinWith("&") }
159
9,997
hyperswitch-control-center
src/components/DynamicTableUtils.res
.res
let tableHeadingClass = "font-bold text-xl text-black text-opacity-75 dark:text-white dark:text-opacity-75" type view = Table | Card let visibilityColFunc = ( ~dateFormatConvertor: string => option<JSON.t>, ~jsonVal: option<JSON.t>, ~tableCell: Table.cell, ) => { switch tableCell { | Label(x) | ColoredText(x) => (x.title->JSON.Encode.string->Some, jsonVal) // wherever we are doing transformation only that transformed value for serch | Text(x) | EllipsisText(x, _) | CustomCell(_, x) => (x->JSON.Encode.string->Some, jsonVal) | Date(x) => (dateFormatConvertor(x), dateFormatConvertor(x)) | StartEndDate(start, end) => ( `${dateFormatConvertor(start) ->Option.getOr(""->JSON.Encode.string) ->String.make} ${dateFormatConvertor(end) ->Option.getOr(""->JSON.Encode.string) ->String.make}` ->JSON.Encode.string ->Some, dateFormatConvertor(end), ) | _ => (jsonVal, jsonVal) // or else taking the value from the actual json } } let useDateFormatConvertor = () => { let dateFormat = React.useContext(DateFormatProvider.dateFormatContext) let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat() let dateFormatConvertor = dateStr => { try { let customTimeZone = isoStringToCustomTimeZone(dateStr) TimeZoneHook.formattedDateTimeFloat(customTimeZone, dateFormat)->JSON.Encode.string->Some } catch { | _ => None } } dateFormatConvertor } let filteredData = ( actualData: array<Nullable.t<'t>>, columnFilter: Dict.t<array<JSON.t>>, visibleColumns: option<array<'colType>>, entity: EntityType.entityType<'colType, 't>, dateFormatConvertor: string => option<JSON.t>, ) => { let selectedFiltersKeys = columnFilter->Dict.keysToArray if selectedFiltersKeys->Array.length > 0 { actualData->Array.filter(item => { switch item->Nullable.toOption { | Some(row) => // either to take this row or not if any filter is present then take row or else drop let rowDict = row->Identity.genericTypeToDictOfJson let anyMatch = selectedFiltersKeys->Array.find(keys => { // Selected fitler switch Dict.get(columnFilter, keys) { | Some(selectedArr) => { // selected value of the fitler let jsonVal = Dict.get( rowDict->JSON.Encode.object->JsonFlattenUtils.flattenObject(false), keys, ) let visibleColumns = visibleColumns ->Option.getOr(entity.defaultColumns) ->Belt.Array.keepMap( item => { let columnEntity = entity.getHeading(item) let entityKey = entity.getHeading(item).key let dataType = columnEntity.dataType entityKey === keys ? Some((dataType, item)) : None }, ) switch visibleColumns[0] { | Some(ele) => { let (visibleColumns, item) = ele let jsonVal = visibilityColFunc( ~dateFormatConvertor, ~jsonVal, ~tableCell=entity.getCell(row, item), ) switch visibleColumns { | DropDown => { let selectedArr = selectedArr ->Belt.Array.keepMap(item => item->JSON.Decode.string) ->Array.map(String.toLowerCase) let currVal = switch jsonVal { | (Some(transformed), _) => transformed->String.make->String.toLowerCase | (None, _) => "" } !(selectedArr->Array.includes(currVal)) } | LabelType | TextType => { let selectedArr1 = selectedArr->Belt.Array.keepMap(item => item->JSON.Decode.string) let currVal = switch jsonVal { | (Some(transformed), _) => transformed->String.make | (None, _) => "" } let searchedText = selectedArr1->Array.get(0)->Option.getOr("") !String.includes( searchedText->String.toUpperCase, currVal->String.toUpperCase, ) } | MoneyType | NumericType | ProgressType => { let selectedArr = selectedArr->Belt.Array.keepMap(item => item->JSON.Decode.float) let currVal = switch jsonVal { | (_, Some(actualVal)) => actualVal->String.make->Js.Float.fromString | _ => 0. } !( currVal >= selectedArr[0]->Option.getOr(0.) && currVal <= selectedArr[1]->Option.getOr(0.) ) } } } | None => false } } | None => false } }) anyMatch->Option.isNone | None => false } }) } else { actualData } } let convertStrCellToFloat = (dataType: Table.cellType, str: string) => { switch dataType { | DropDown | LabelType | TextType => str->JSON.Encode.string | MoneyType | NumericType | ProgressType => str->Float.fromString->Option.getOr(0.)->JSON.Encode.float } } let convertFloatCellToStr = (dataType: Table.cellType, num: float) => { switch dataType { | DropDown | LabelType | TextType => num->Float.toString->JSON.Encode.string | MoneyType | NumericType | ProgressType => num->JSON.Encode.float } } let defaultRefetchFn = () => {Js.log("This is default refetch")} let refetchContext = React.createContext(defaultRefetchFn) module RefetchContextProvider = { let make = React.Context.provider(refetchContext) } module TableHeading = { @react.component let make = (~title, ~noVerticalMargin=false, ~description=?, ~titleTooltip=false) => { let tooltipFlexDir = titleTooltip ? `flex-row` : `flex-col` let marginClass = if noVerticalMargin { "" } else { "lg:mb-4 lg:mt-8" } if title->LogicUtils.isNonEmptyString || description->Option.isSome { <div className={`flex ${tooltipFlexDir} ${marginClass}`}> {if title->LogicUtils.isNonEmptyString { <AddDataAttributes attributes=[("data-table-heading-title", title)]> <div className=tableHeadingClass> {React.string(title)} </div> </AddDataAttributes> } else { React.null }} {switch description { | Some(desc) => switch titleTooltip { | true => <div className="text-sm text-gray-500 mx-2"> <ToolTip description={desc} toolTipPosition={ToolTip.Bottom} /> </div> | _ => <AddDataAttributes attributes=[("data-table-heading-desc", desc)]> <div className="text-base text-jp-gray-700 dark:text-jp-gray-800"> {React.string(desc)} </div> </AddDataAttributes> } | None => React.null }} </div> } else { React.null } } } module TableLoadingErrorIndicator = { @react.component let make = ( ~title, ~titleSize: NewThemeUtils.headingSize=Large, ~showFilterBorder=false, ~fetchSuccess, ~filters, ~buttonType: Button.buttonType=Primary, ~hideTitle=false, ) => { let isMobileView = MatchMedia.useMobileChecker() let filtersBorder = if !isMobileView && showFilterBorder { "p-2 bg-white dark:bg-black border border-jp-2-light-gray-400 rounded-lg" } else { "" } <div className={`flex flex-col w-full`}> <RenderIf condition={!hideTitle}> <TableHeading title /> </RenderIf> <TableFilterSectionContext isFilterSection=true> <div className=filtersBorder> {filters} </div> </TableFilterSectionContext> <div className={`flex flex-col py-16 text-center items-center`}> {fetchSuccess ? <> <div className="animate-spin mb-10"> <Icon name="spinner" /> </div> {React.string("Loading...")} </> : <> <div className="mb-4 text-xl"> {React.string("Oops, Something Went Wrong! Try again Later.")} </div> <Button text="Refresh" leftIcon={FontAwesome("sync-alt")} onClick={_ => Window.Location.reload()} buttonType /> </>} </div> </div> } } module TableDataLoadingIndicator = { @react.component let make = (~showWithData=true) => { let padding = showWithData ? "py-8 rounded-b" : "py-56 rounded" <div className={`flex flex-col ${padding} justify-center space-x-2 items-center bg-white shadow-md dark:bg-jp-gray-lightgray_background dark:shadow-md`}> <div className="animate-spin mb-4"> <Icon name="spinner" /> </div> <div className="text-gray-500"> {React.string("Loading...")} </div> </div> } } module ChooseColumns = { @react.component let make = ( ~entity: EntityType.entityType<'colType, 't>, ~totalResults, ~defaultColumns, ~activeColumnsAtom: Recoil.recoilAtom<array<'colType>>, ~setShowColumnSelector, ~showColumnSelector, ~isModalView=true, ~sortingBasedOnDisabled=true, ~orderdColumnBasedOnDefaultCol: bool=false, ~showSerialNumber=true, ~mandatoryOptions=[], ) => { let (visibleColumns, setVisibleColumns) = Recoil.useRecoilState(activeColumnsAtom) let {getHeading} = entity let setColumns = React.useCallback(fn => { setVisibleColumns(fn) setShowColumnSelector(_ => false) }, [setVisibleColumns]) if entity.allColumns->Option.isSome && totalResults > 0 { <CustomizeTableColumns showModal=showColumnSelector setShowModal=setShowColumnSelector allHeadersArray=?entity.allColumns visibleColumns setColumns getHeading defaultColumns isModalView sortingBasedOnDisabled orderdColumnBasedOnDefaultCol showSerialNumber /> } else { React.null } } } module ChooseColumnsWrapper = { @react.component let make = ( ~entity: EntityType.entityType<'colType, 't>, ~totalResults, ~defaultColumns, ~activeColumnsAtom as optionalActiveColumnsAtom, ~setShowColumnSelector, ~showColumnSelector, ~isModalView=true, ~sortingBasedOnDisabled=true, ~showSerialNumber=true, ~setShowDropDown=_ => (), ) => { switch optionalActiveColumnsAtom { | Some(activeColumnsAtom) => <AddDataAttributes attributes=[("data-table", "dynamicTableChooseColumn")]> <ChooseColumns entity activeColumnsAtom isModalView totalResults defaultColumns setShowColumnSelector showColumnSelector sortingBasedOnDisabled showSerialNumber /> </AddDataAttributes> | None => React.null } } }
2,543
9,998
hyperswitch-control-center
src/components/Icon.resi
.resi
@react.component let make: ( ~name: string, ~size: int=?, ~className: string=?, ~themeBased: bool=?, ~onClick: ReactEvent.Mouse.t => unit=?, ~parentClass: string=?, ~customIconColor: string=?, ~customWidth: string=?, ~customHeight: string=?, ) => React.element
86
9,999
hyperswitch-control-center
src/components/NewCalendar.res
.res
open DateTimeUtils type highlighter = { highlightSelf: bool, highlightLeft: bool, highlightRight: bool, } 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->Array.get(2)->Option.getOr("")) } | None => React.string("") } } @react.component let make = ( ~changeHighlightCellStyle="", ~item, ~month, ~year, ~rowIndex, ~onDateClick, ~cellHighlighter=defaultCellHighlighter, ~cellRenderer=defaultCellRenderer, ~startDate="", ~endDate="", ~hoverdDate, ~setHoverdDate, ~disablePastDates=true, ~disableFutureDates=false, ~customDisabledFutureDays=0.0, ~dateRangeLimit=?, ~setShowMsg=?, ~windowIndex, ~setIsDateClicked=?, ) => { open LogicUtils 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 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 = _ => { switch setIsDateClicked { | Some(setIsDateClicked) => setIsDateClicked(_ => true) | _ => () } let isClickDisabled = (endDate->isEmptyString && !isInLimit) || (isFutureDate ? disableFutureDates : disablePastDates) || (customDisabledFutureDays > 0.0 && isInCustomDisable) 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) ) { "cursor-not-allowed" } else { "cursor-default" } let getDate = date => { let datevalue = Js.Date.makeWithYMD( ~year=Js.Float.fromString(date->Array.get(0)->Option.getOr("0")), ~month=Js.Float.fromString( String.make(Js.Float.fromString(date->Array.get(1)->Option.getOr("0")) -. 1.0), ), ~date=Js.Float.fromString(date->Array.get(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 isTodayHighlight = today == renderingDate && startDate != today && endDate != today let textColor = isTodayHighlight ? "bg-jp-2-light-primary-100 rounded-full" : "text-jp-gray-900 text-opacity-75 dark:text-opacity-75" let classN = `h-10 w-10 p-0 text-center ${textColor} dark:text-jp-gray-text_darktheme ${dayClass}` let selectedcellClass = `h-10 w-10 flex flex-1 justify-center items-center bg-primary bg-opacity-100 dark:bg-primary dark:bg-opacity-100 text-white rounded-full ` let c2 = obj->isNonEmptyString && hSelf.highlightSelf ? selectedcellClass : "h-10 w-10" let shouldHighlight = (startDate, endDate, obj, month, year) => { let cellSelectedHiglight = "h-full w-full flex flex-1 justify-center items-center dark:bg-opacity-100 text-gray-600 dark:text-gray-400" let cellHoverHighlight = `h-full w-full flex flex-1 justify-center items-center dark:bg-opacity-100` if startDate->isNonEmptyString { let parsedStartDate = getDate(String.split(startDate, "-")) let zObj = getDate([year, month, obj]) if obj->isNonEmptyString { let z = getDate([year, month, obj]) if endDate->isNonEmptyString { let parsedEndDate = getDate(String.split(endDate, "-")) z == parsedStartDate ? selectedcellClass : z == parsedEndDate ? selectedcellClass : z > parsedStartDate && z < parsedEndDate ? `${cellSelectedHiglight} bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 ${cellIndex == 0 ? "rounded-l-full" : ""} ${cellIndex == 6 ? "rounded-r-full" : ""}` : "h-full w-full" } else if z == parsedStartDate { `${selectedcellClass} ${changeHighlightCellStyle}` } else if ( hoverdDate->isNonEmptyString && endDate->isEmptyString && z > parsedStartDate && z <= hoverdDate->Date.fromString && !( (isFutureDate && disableFutureDates) || !isFutureDate && disablePastDates || (endDate->isEmptyString && !isInLimit) ) ) { `${cellHoverHighlight} bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 ${cellIndex == 0 ? "rounded-l-full" : ""} ${cellIndex == 6 ? "rounded-r-full" : ""}` } else { "h-full w-full" } } else if endDate->isNonEmptyString { let parsedEndDate = getDate(String.split(endDate, "-")) zObj > parsedStartDate && zObj < parsedEndDate ? `${cellSelectedHiglight} ${cellIndex == 0 ? "bg-gradient-to-r from-jp-2-light-primary-100/0 to-jp-2-light-primary-100/100" : cellIndex == 6 ? "bg-gradient-to-r from-jp-2-light-primary-100/100 to-jp-2-light-primary-100/0" : "bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 "} ` : "h-full w-full " } else if ( hoverdDate->isNonEmptyString && endDate->isEmptyString && zObj > parsedStartDate && zObj <= hoverdDate->Date.fromString && !( (isFutureDate && disableFutureDates) || !isFutureDate && disablePastDates || (endDate->isEmptyString && !isInLimit) ) ) { `${cellHoverHighlight} ${cellIndex == 0 ? "bg-gradient-to-r from-jp-2-light-primary-100/0 to-jp-2-light-primary-100/100" : cellIndex == 6 ? "bg-gradient-to-r from-jp-2-light-primary-100/100 to-jp-2-light-primary-100/0" : "bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 "} ` } else { "h-full w-full" } } else { "h-full w-full" } } let shouldHighlightBackground = (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 && parsedStartDate != parsedEndDate ? "bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 rounded-l-full hover:rounded-l-full" : z == parsedEndDate && parsedStartDate != parsedEndDate ? "bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 rounded-r-full hover:rounded-r-full flex justify-between" : "" } else if hoverdDate->isNonEmptyString && z == parsedStartDate { "bg-jp-2-light-primary-100 dark:bg-jp-2-dark-primary-100 rounded-l-full hover:rounded-l-full" } else { "" } } else { "" } } let highlightBgClass = { shouldHighlightBackground( startDate, endDate, obj, Float.toString(month +. 1.0), Float.toString(year), ) } 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={`${windowIndex->Int.toString}X${cellIndex->Int.toString}`} className={`${classN} ${highlightBgClass} text-sm font-normal`} 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) ? "disabled" : "enabled", ), ]> <span className={`${startDate->isEmptyString ? c2 : c3} ${isTodayHighlight ? "flex flex-col justify-center items-center pl-0.5" : ""}`}> {cellRenderer( obj->isEmptyString ? None : Some((Date.toString(date)->DayJs.getDayJsForString).format("YYYY-MM-D")), )} {isTodayHighlight ? <div className="bg-primary h-1.5 w-1.5 rounded-full" /> : React.null} </span> </AddDataAttributes> </td> }) ->React.array} </tr> {rowIndex < 5 ? <tr className="h-1" /> : React.null} </> } } } } @react.component let make = ( ~changeHighlightCellStyle="", ~month, ~year, ~onDateClick=?, ~hoverdDate, ~setHoverdDate, ~showTitle=true, ~cellHighlighter=?, ~cellRenderer=?, ~highLightList as _=?, ~startDate="", ~endDate="", ~disablePastDates=true, ~disableFutureDates=false, ~dateRangeLimit=?, ~setShowMsg=?, ~showHead=true, ~customDisabledFutureDays=0.0, ~isFutureDate=true, ~setIsDateClicked=?, ) => { open LogicUtils let heading = ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"] let isMobileView = MatchMedia.useMobileChecker() let getMonthInFloat = mon => Array.indexOf(months, mon)->Float.fromInt let totalMonths = disablePastDates ? 1 : (year - 1970) * 12 + getMonthInFloat(month)->Float.toInt + 1 let futureMonths = isFutureDate && !disableFutureDates ? 120 : 0 let (lastStartDate, setLastStartDate) = React.useState(_ => "") let fn = React.useRef((_, _) => ()) 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 " } } let handleExpand = (index, string) => fn.current(index, string) React.useEffect(() => { handleExpand(totalMonths - 1, "center") None }, []) React.useEffect(() => { let currentMonth = getMonthInFloat(month)->Float.toInt + 1 if startDate != lastStartDate { let startYear = startDate->isNonEmptyString ? (startDate->DayJs.getDayJsForString).format("YYYY") : "" let startMonth = (startDate->isNonEmptyString ? (startDate->DayJs.getDayJsForString).format("MM") : "") ->Int.fromString ->Option.getOr(currentMonth) let startYearDiff = year - startYear->Int.fromString->Option.getOr(2022) let startIndex = 12 * startYearDiff + (currentMonth - startMonth) if startDate->isNonEmptyString { handleExpand(totalMonths - startIndex - 1, "center") } setLastStartDate(_ => startDate) } else { let endYear = endDate->isNonEmptyString ? (endDate->DayJs.getDayJsForString).format("YYYY") : "" let endMonth = (endDate->isNonEmptyString ? (endDate->DayJs.getDayJsForString).format("MM") : "") ->Int.fromString ->Option.getOr(currentMonth) let endYearDiff = year - endYear->Int.fromString->Option.getOr(2022) let endIndex = 12 * endYearDiff + (currentMonth - endMonth) if endDate->isNonEmptyString { handleExpand(totalMonths - endIndex - 1, "center") } } None }, (startDate, endDate)) let rows = index => { let windowIndex = totalMonths - index->getInt("index", 0) - 1 let newMonth = DayJs.getDayJs().subtract(windowIndex, "month").month() let newYear = DayJs.getDayJs().subtract(windowIndex, "month").year() let updatedMonth = months->Array.get(newMonth)->Option.getOr(Jan) // get first day let firstDay = Js.Date.getDay( Js.Date.makeWithYM(~year=Int.toFloat(newYear), ~month=getMonthInFloat(updatedMonth), ()), ) // get Days in month let daysInMonth = switch updatedMonth { | Jan => 31 | Feb => checkLeapYear(newYear) ? 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 style={index->getJsonObjectFromDict("style")->Identity.jsonToReactDOMStyle}> <div className={`font-normal text-fs-16 text-[#344054] leading-6 mt-5`}> {React.string(`${updatedMonth->getMonthInStr} ${newYear->Int.toString}`)} </div> <table className="table-auto min-w-full"> <tbody> {rowInfo ->Array.mapWithIndex((item, rowIndex) => { <TableRow key={rowIndex->Int.toString} item rowIndex onDateClick hoverdDate setHoverdDate ?cellHighlighter ?cellRenderer month={getMonthInFloat(updatedMonth)} year={Int.toFloat(newYear)} startDate endDate disablePastDates disableFutureDates changeHighlightCellStyle ?dateRangeLimit ?setShowMsg customDisabledFutureDays windowIndex ?setIsDateClicked /> }) ->React.array} </tbody> </table> </div> } <div className="text-sm px-2 pb-2 font-inter-style flex flex-col items-center"> <div className="border-b-2"> {if showHead { <div className="flex flex-row justify-between"> {heading ->Array.mapWithIndex((item, i) => { <div className="w-10" key={Int.toString(i)}> <div className="flex flex-1 justify-center pb-2.5 pt-0.5 text-jp-gray-700 dark:text-jp-gray-text_darktheme dark:text-opacity-50"> {React.string(isMobileView ? item->String.charAt(0) : item)} </div> </div> }) ->React.array} </div> } else { React.null }} </div> <ReactWindow.VariableSizeList ref={el => { open ReactWindow.ListComponent fn.current = (index, string) => el->scrollToItem(index, string) }} width=300 itemSize={_ => 290} height=290 itemCount={totalMonths + futureMonths}> {rows} </ReactWindow.VariableSizeList> </div> }
4,696
10,000
hyperswitch-control-center
src/components/NewThemeUtils.resi
.resi
type headingSize = XSmall | Small | Medium | Large module NewThemeHeading: { @react.component let make: ( ~heading: string, ~description: string=?, ~headingColor: string=?, ~descriptionColor: string=?, ~headingSize: headingSize=?, ~rightActions: React.element=?, ~headingRightElemnt: React.element=?, ~alignItems: string=?, ~outerMargin: string=?, ) => React.element } module Badge: { type color = Blue | Gray @react.component let make: (~number: int, ~color: color=?) => React.element }
147
10,001
hyperswitch-control-center
src/components/AddDataAttributes.res
.res
let spreadProps = React.cloneElement @react.component let make = (~attributes: array<(string, string)>, ~children) => { let attributesDict = attributes->Dict.fromArray let ignoreAttributes = React.useContext(AddAttributesContext.ignoreAttributesContext) if !ignoreAttributes { children->spreadProps(attributesDict) } else { children } }
81
10,002
hyperswitch-control-center
src/components/Loader.res
.res
@react.component let make = ( ~loadingText="Loading...", ~children=React.null, ~slow=false, ~customSpinnerIconColor: string="", ~loadingTextColor="", ) => { let animationType = if slow { "animate-spin-slow" } else { "animate-spin" } let size = if slow { 60 } else { 20 } let loader = <div className={`flex flex-col py-16 text-center items-center ${loadingTextColor}`}> <div className={`${animationType} mb-10`}> <Icon name="spinner" size customIconColor=customSpinnerIconColor /> </div> {children} </div> <div className="flex flex-col"> <div className="w-full flex justify-center py-10"> <div className="w-20 h-16"> <React.Suspense fallback={loader}> <ErrorBoundary> {loader} </ErrorBoundary> </React.Suspense> </div> </div> </div> }
242
10,003
hyperswitch-control-center
src/components/CollapsableTableRow.res
.res
@react.component let make = ( ~item: array<Table.cell>, ~rowIndex, ~offset as _, ~highlightEnabledFieldsArray, ~expandedRowIndexArray, ~onExpandIconClick, ~getRowDetails, ~heading, ~title, ) => { let isCurrentRowExpanded = expandedRowIndexArray->Array.includes(rowIndex) let headingArray = [] heading->Array.forEach((item: TableUtils.header) => { headingArray->Array.push(item.title)->ignore }) let textColor = "text-jp-gray-900 dark:text-jp-gray-text_darktheme text-opacity-75 dark:text-opacity-75" let fontStyle = "font-fira-code" let fontSize = "text-sm" let borderRadius = "rounded-md" <> <DesktopView> <tr className={`group h-full ${borderRadius} bg-white dark:bg-jp-gray-lightgray_background hover:bg-jp-gray-table_hover dark:hover:bg-jp-gray-100 dark:hover:bg-opacity-10 ${textColor} ${fontStyle} transition duration-300 ease-in-out ${fontSize}`}> {item ->Array.mapWithIndex((obj: Table.cell, cellIndex) => { let showBorderTop = switch obj { | Text(x) => x !== "-" | _ => true } let paddingClass = switch obj { | Link(_) => "pt-2" | _ => "py-3" } let highlightCell = highlightEnabledFieldsArray->Array.includes(cellIndex) let borderTop = showBorderTop ? "border-t" : "border-t-0" let borderClass = `${borderTop} border-jp-gray-500 dark:border-jp-gray-960` let hCell = highlightCell ? "hover:font-bold" : "" let cursorI = cellIndex == 0 ? "cursor-pointer" : "" let location = `${title}_tr${(rowIndex + 1)->Int.toString}_td${(cellIndex + 1) ->Int.toString}` <AddDataAttributes key={cellIndex->Int.toString} attributes=[("data-table-location", location)]> <td key={Int.toString(cellIndex)} className={`h-full p-0 align-top ${borderClass} ${hCell} ${cursorI}`} onClick={_ => { if cellIndex == 0 { onExpandIconClick(isCurrentRowExpanded, rowIndex) } }}> <div className={`h-full box-border px-4 ${paddingClass}`}> <div className="flex flex-row gap-4 items-center"> <RenderIf condition={cellIndex === 0}> <Icon name={isCurrentRowExpanded ? "caret-down" : "caret-right"} size=14 /> </RenderIf> <Table.TableCell cell=obj /> </div> </div> </td> </AddDataAttributes> }) ->React.array} </tr> <RenderIf condition=isCurrentRowExpanded> <AddDataAttributes attributes=[("data-table-row-expanded", (rowIndex + 1)->Int.toString)]> <tr className="dark:border-jp-gray-dark_disable_border_color"> <td colSpan=12 className=""> {getRowDetails(rowIndex)} </td> </tr> </AddDataAttributes> </RenderIf> </DesktopView> <MobileView> <div className="px-3 py-4 bg-white dark:bg-jp-gray-lightgray_background"> {item ->Array.mapWithIndex((obj, index) => { let heading = headingArray->Array.get(index)->Option.getOr("") <RenderIf condition={index !== 0} key={index->Int.toString}> <div className="flex mb-5 justify-between"> <div className="text-jp-gray-900 opacity-50 font-medium"> {React.string(heading)} </div> <div className="font-semibold"> <Table.TableCell cell=obj /> </div> </div> </RenderIf> }) ->React.array} {getRowDetails(rowIndex)} </div> </MobileView> </> }
907
10,004
hyperswitch-control-center
src/components/DragDrop.res
.res
type draggableDefaultDestination = {index: int, droppableId: string} type draggableItem = React.element let defaultDraggableDest = { index: 0, droppableId: "", } @react.component let make = ( ~isHorizontal=true, ~listItems: array<JSON.t>, ~setListItems: (array<JSON.t> => array<JSON.t>) => unit, ~keyExtractor: JSON.t => option<string>, ) => { let (list, setList) = React.useState(_ => listItems) 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) } } let onDragEnd = result => { // dropped outside the list let dest = Nullable.toOption(result["destination"]) let hasCorrectDestination = switch dest { | None => false | Some(_a) => true } if hasCorrectDestination { let res = switch dest { | Some(a) => { let retValue: draggableDefaultDestination = { index: a.index, droppableId: a.droppableId, } retValue } | _ => defaultDraggableDest } let (updatedList, hasChanged) = reorder(list, result["source"]["index"], res.index) if hasChanged { setList(_ => updatedList) } } } let onSubmit = () => { let updatedDict = Dict.make() Dict.set(updatedDict, "items", list) //TODO conversion // let transformedList = arrOfObjToArrOfObjValue(value=list, ) setListItems(_ => list) } let directionClass = isHorizontal ? "flex-row" : "flex-col" let droppableDirection = isHorizontal ? "horizontal" : "vertical" <div> <div className={`w-min p-3 bg-jp-gray-50 dark:bg-jp-gray-950 rounded border border-jp-gray-500 dark:border-jp-gray-960 align-center justify-center rounded-t-none flex ${directionClass}`}> <span> <ReactBeautifulDND.DragDropContext onDragEnd={onDragEnd}> <ReactBeautifulDND.Droppable droppableId="droppable" direction={droppableDirection}> {(provided, _snapshot) => { React.cloneElement( <div className={`flex ${directionClass}`} ref={provided["innerRef"]}> {list ->Array.mapWithIndex((item, index) => { let val = keyExtractor(item) switch val { | Some(str) => <ReactBeautifulDND.Draggable key={`item-${Int.toString(index)}`} index={index} draggableId={`item-${Int.toString(index)}`}> {(provided, _snapshot) => { React.cloneElement( React.cloneElement( <span onDragStart={provided["onDragStart"]} ref={provided["innerRef"]} className={`flex ${directionClass} p-3 m-1 bg-jp-gray-50 dark:bg-jp-gray-950 rounded border border-jp-gray-500 dark:border-jp-gray-960 align-center justify-center rounded-t-none`}> {React.string(str)} </span>, provided["draggableProps"], ), provided["dragHandleProps"], ) }} </ReactBeautifulDND.Draggable> | None => React.null } }) ->React.array} {provided["placeholder"]} </div>, provided["droppableProps"], ) }} </ReactBeautifulDND.Droppable> </ReactBeautifulDND.DragDropContext> </span> </div> <div className="pt-5 inline-block "> <Button text="Update" buttonType=Primary onClick={_ => onSubmit()} /> </div> </div> }
930
10,005
hyperswitch-control-center
src/components/SelectBox.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="", ~customRowClass="", ~labelDescription=Some(""), ~labelDescriptionClass="", ~customSelectionIcon=Button.NoIcon, ) => { 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 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-gray-900 dark:text-jp-gray-text_darktheme" 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 = !isDropDown && optionSize === Large ? "text-fs-16" : "text-base" 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 let searchStyle = searchString->String.length > 0 ? "flex" : "" 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} ${customRowClass}`}> {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} ${customSelectStyle}`}> <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 ${searchStyle}`}> {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}> {<div className="flex gap-1 items-center"> <span key={i->Int.toString} className=textClass value=labelText> {item->React.string} </span> <p className={`${labelDescriptionClass}`}> {`${labelDescription->Option.getOr("")}`->React.string} </p> </div>} </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"> {switch (customSelectionIcon, isSelected) { | (Button.CustomIcon(ele), true) => ele | (_, _) => <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>, 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: 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(""), labelDescription: dropdownOption.labelDescription, customComponent: dropdownOption.customComponent, } } 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, ~insertselectBtnRef=?, ~insertclearBtnRef=?, ~customLabelStyle=?, ~showToggle=false, ~showSerialNumber=false, ~heading="Some heading", ~showSelectionAsChips=true, ~maxHeight="md:max-h-72", ~searchable=?, ~optionRigthElement=?, ~searchInputPlaceHolder="", ~showSearchIcon=false, ~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=[], ~customComponent=None, ) => { 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 shadow-generic_shadow dark:shadow-generic_shadow_dark animate-textTransition transition duration-400" } else if showToggle { "bg-white border rounded dark:bg-jp-gray-darkgray_background border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 rounded " } 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 selectBtnRef = insertselectBtnRef->Option.map(ReactDOM.Ref.callbackDomRef) let clearBtnRef = insertclearBtnRef->Option.map(ReactDOM.Ref.callbackDomRef) let (isChooseAllToggleSelected, setChooseAllToggleSelected) = React.useState(() => false) let gapClass = switch optionRigthElement { | Some(_) => "flex gap-4" | None => "" } let onClick = ev => { 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 id="neglectTopbarTheme" className={`${widthClass} ${outerClass} ${borderClass} ${animationClass} ${dropdownClassName}`}> {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 { <div className={`${customSearchStyle} border-b border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 z-index: 50`}> <div className="flex flex-row justify-between"> <div ref=?selectBtnRef onClick={selectAll(true)}> <Button text="SELECT ALL" buttonType=NonFilled buttonSize=Small customButtonStyle="w-32 text-fs-11 mx-1" buttonState={noOfSelected !== options->Array.length ? Normal : Disabled} /> </div> <div ref=?clearBtnRef onClick={selectAll(false)}> <Button text="CLEAR ALL" buttonType=NonFilled buttonSize=Small customButtonStyle="w-32 text-fs-11 mx-1" buttonState={noOfSelected !== 0 && showClearAll ? Normal : Disabled} /> </div> </div> {if ( noOfSelected !== options->Array.length && noOfSelected !== 0 && showSelectionAsChips ) { <div className="text-sm text-gray-500 text-start mt-1 ml-1.5 font-bold"> {React.string( `${noOfSelected->Int.toString} items selected out of ${options ->Array.length ->Int.toString} options`, )} </div> } else { React.null }} </div> } else 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 pt-2 pb-1 mx-1 rounded-lg 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 ${customSearchStyle}`}> {React.string("No matching records found")} </div> } else if filteredOptions->Array.find(item => item.value === "Loading...")->Option.isSome { <Loader /> } else { switch customComponent { | Some(elem) => elem | _ => 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> {if hasApplyButton { <Button buttonType=Primary text="Apply" flattenTop=false customButtonStyle="w-full items-center" buttonState={!applyBtnDisabled ? Normal : Disabled} onClick /> } else { <RenderIf condition={isDropDown && noOfSelected > 0 && showSelectCountButton}> <Button buttonType=Primary text={`Select ${noOfSelected->Int.toString}`} flattenTop=true customButtonStyle="w-full items-center" onClick /> </RenderIf> }} </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=false, ~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={`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 customRowClass={option.customRowClass} /> } 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", ~bottomComponent=?, ~optionClass="", ~selectClass="", ~customScrollStyle=?, ~shouldDisplaySelectedOnTop, ~labelDescriptionClass="", ~customSelectionIcon=Button.NoIcon, ) => { let decodedValue = value->JSON.Decode.string switch (decodedValue, shouldDisplaySelectedOnTop) { | (Some(str), true) => newOptions->Array.sort((item1, item2) => { if item1.value == str { -1. } else if item2.value == str { 1. } else { 0. } }) | (_, _) => () } let dropdownList = 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 = switch option.customComponent { | Some(elem) => elem | _ => <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 customRowClass={option.customRowClass} optionClass selectClass labelDescription=option.labelDescription labelDescriptionClass customSelectionIcon /> } 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 sidebarScrollbarCss = ` @supports (-webkit-appearance: none) { .sidebar-scrollbar { scrollbar-color: #8a8c8f; } .sidebar-scrollbar::-webkit-scrollbar-thumb { background-color: #8a8c8f; border-radius: 3px; } .sidebar-scrollbar::-webkit-scrollbar-track { display: none; } } ` let (className, styleElement) = switch (customScrollStyle, isHorizontal) { | (None, false) => ("", React.null) | (Some(style), false) => ( `${style} sidebar-scrollbar`, <style> {React.string(sidebarScrollbarCss)} </style>, ) | (None, true) => ("flex flex-row", React.null) | (Some(style), true) => ( `${style} sidebar-scrollbar flex flex-row`, <style> {React.string(sidebarScrollbarCss)} </style>, ) } <> <div className={className}> {styleElement} {dropdownList} </div> <div className="sticky bottom-0"> {switch bottomComponent { | Some(comp) => <span> {comp} </span> | None => React.null }} </div> </> } } 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="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=false, ~showToolTipOptions=false, ~textEllipsisForDropDownOptions=false, ~bottomComponent=React.null, ~optionClass="", ~selectClass="", ~customScrollStyle=?, ~dropdownContainerStyle="", ~shouldDisplaySelectedOnTop=false, ~labelDescriptionClass="", ~customSelectionIcon=Button.NoIcon, ~placeholderCss="", ) => { 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 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 => () } } } 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.value, 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 heightScroll = switch customScrollStyle { | Some(_) => "max-h-full" | None => maxHeight } let searchInputUI = <div className={`border-b p-2 border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 ${customSearchStyle}`}> <div> <SearchInput inputText=searchString onChange=handleSearch searchRef placeholder={searchInputPlaceHolder->LogicUtils.isEmptyString ? "Search name or ID..." : searchInputPlaceHolder} showSearchIcon placeholderCss /> </div> </div> <div className={`${dropDownbgClass} ${roundedClass} dark:bg-jp-gray-lightgray_background ${dropdownContainerStyle} ${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={`${heightScroll} ${listPadding} ${overflowClass} text-fs-13 font-semibold text-jp-gray-900 text-opacity-75 dark:text-jp-gray-text_darktheme dark:text-opacity-75 ${inlineClass} ${baseComponentCustomStyle}`}> {if newOptions->Array.length === 0 && showMatchingRecordsText { <div className={`flex justify-center items-center m-4 ${customSearchStyle}`}> {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 bottomComponent optionClass selectClass ?customScrollStyle shouldDisplaySelectedOnTop labelDescriptionClass customSelectionIcon /> } 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" ?customScrollStyle shouldDisplaySelectedOnTop /> </React.Fragment> }) ->React.array } }} </div> </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-10", //to position dropdown below the button, ~customStyle="", ~customSearchStyle="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=?, ~allowButtonTextMinWidth=?, ~customMarginStyle=?, ~customButtonLeftIcon: option<Button.iconType>=?, ~customTextPaddingClass=?, ~customButtonPaddingClass=?, ~customButtonIconMargin=?, ~textStyleClass=?, ~buttonStyleOnDropDownOpened="", ~selectedString="", ~setSelectedString=_ => (), ~setExtSearchString=_ => (), ~listFlexDirection="", ~ellipsisOnly=false, ~isPhoneDropdown=false, ~onApply=?, ~showAllSelectedOptions=true, ~buttonClickFn=?, ~toggleChevronState: option<unit => unit>=?, ~showSelectCountButton=false, ~maxHeight=?, ~customBackColor=?, ~showToolTipOptions=false, ~textEllipsisForDropDownOptions=false, ~showBtnTextToolTip=false, ~dropdownClassName="", ~searchInputPlaceHolder="", ~showSearchIcon=false, ~sortingBasedOnDisabled=?, ~customSelectStyle="", ~baseComponentCustomStyle="", ~bottomComponent=React.null, ~optionClass="", ~selectClass="", ~customDropdownOuterClass="", ~customScrollStyle=?, ~dropdownContainerStyle="", ~shouldDisplaySelectedOnTop=false, ~labelDescriptionClass="", ~customSelectionIcon=Button.NoIcon, ~placeholderCss="", ) => { let transformedOptions = useTransformed(options) let isMobileView = MatchMedia.useMobileChecker() let isSelectTextDark = React.useContext( DropdownTextWeighContextWrapper.selectedTextWeightContext, ) let isFilterSection = React.useContext(TableFilterSectionContext.filterSectionContext) let showBorder = isFilterSection && !isMobileView ? Some(false) : showBorder let dropdownOuterClass = "border border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 rounded shadow-generic_shadow dark:shadow-generic_shadow_dark z-40" 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 ) let onApply = ev => { switch onApply { | Some(fn) => fn(ev) | None => () } setPreservedAppliedOptions(_ => newInputSelect.value->LogicUtils.getStrArryFromJson) } let clearBtnRef = React.useRef(Nullable.null) let insertselectBtnRef = element => { if !Js.Nullable.isNullable(element) { selectBtnRef.current = element } } React.useEffect(() => { setShowDropDown(_ => false) None }, [dropDownCustomBtnClick]) let insertclearBtnRef = element => { if !Js.Nullable.isNullable(element) { clearBtnRef.current = element } } let refs = autoApply ? [selectBoxRef, dropdownRef] : [selectBoxRef, dropdownRef, selectBtnRef, clearBtnRef] OutsideClick.useOutsideClick(~refs=ArrayOfRef(refs), ~isActive=showDropDown, ~callback=() => { setShowDropDown(_ => false) hasApplyButton ? newInputSelect.onChange(preservedAppliedOptions) : () }) React.useEffect(() => { switch toggleChevronState { | Some(fn) => fn() | None => () } None }, [showDropDown]) 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" let arrowIconSize = 14 let (dropDowntext, leftIcon: Button.iconType, iconStroke) = allowMultiSelect ? (buttonText, defaultLeftIcon, "") : switch newInputRadio.value->JSON.Decode.string { | Some(str) => switch transformedOptions->Array.find(x => x.value === str) { | Some(x) => (x.label, x.icon, x.iconStroke) | None => (buttonText, defaultLeftIcon, "") } | None => (buttonText, defaultLeftIcon, "") } 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 : buttonText 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 insertselectBtnRef insertclearBtnRef showSelectionAsChips ?searchable disableSelect ?dropdownCustomWidth ?deselectDisable isMobileView hasApplyButton setShowDropDown ?customMarginStyle listFlexDirection onApply showSelectCountButton ?maxHeight dropdownClassName customStyle searchInputPlaceHolder showSearchIcon ?sortingBasedOnDisabled preservedAppliedOptions customSearchStyle /> } 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 customSelectStyle baseComponentCustomStyle bottomComponent optionClass selectClass ?customScrollStyle dropdownContainerStyle shouldDisplaySelectedOnTop labelDescriptionClass customSelectionIcon customSearchStyle placeholderCss /> } 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 } <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 = <AddDataAttributes attributes=[("data-dropdown-for", buttonText)]> <div> {<Button text=selectButtonText leftIcon onClick ?textStyle buttonSize ellipsisOnly={ellipsisOnly || !showSelectionAsChips} badge={!showSelectionAsChips ? badgeForSelect : {value: 0->Int.toString, color: NoBadge}} rightIcon={CustomIcon(buttonIcon)} buttonState={disableSelect ? Disabled : Normal} fullLength buttonType={Dropdown} isPhoneDropdown isDropdownOpen=showDropDown iconBorderColor={iconStroke} isSelectBoxButton=true customButtonStyle={`${customButtonStyle} ${showDropDown ? buttonStyleOnDropDownOpened : ""} transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)]`} ?showBorder ?allowButtonTextMinWidth ?textStyleClass showBtnTextToolTip />} </div> </AddDataAttributes> 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> {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} ${customDropdownOuterClass} z-20 ${marginBottom} rounded-lg 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} ${customDropdownOuterClass} z-20 ${marginBottom} rounded-lg 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 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> } } 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=false, ~customLabelStyle=?, ~customMargin="", ~showToolTip=false, ~showNameAsToolTip=false, ~showBorder=?, ~showCustomBtnAtEnd=false, ~dropDownCustomBtnClick=false, ~addDynamicValue=false, ~showMatchingRecordsText=true, ~customButton=React.null, ~descriptionOnHover=false, ~fixedDropDownDirection=?, ~dropdownCustomWidth=?, ~allowButtonTextMinWidth=?, ~baseComponent=?, ~baseComponentMethod=?, ~customMarginStyle=?, ~buttonTextWeight=?, ~customButtonLeftIcon=?, ~customTextPaddingClass=?, ~customButtonPaddingClass=?, ~customButtonIconMargin=?, ~textStyleClass=?, ~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="", ~customScrollStyle=?, ~shouldDisplaySelectedOnTop=false, ~placeholderCss="", (), ) => { let isMobileView = MatchMedia.useMobileChecker() let (selectedString, setSelectedString) = React.useState(_ => "") let newInputSelect = input->ffInputToSelectInput let newInputRadio = input->ffInputToRadioInput 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 ?allowButtonTextMinWidth ?baseComponent ?baseComponentMethod ?customMarginStyle ?buttonTextWeight ?customButtonLeftIcon ?customTextPaddingClass ?customButtonPaddingClass ?customButtonIconMargin ?textStyleClass buttonStyleOnDropDownOpened selectedString setSelectedString setExtSearchString listFlexDirection ellipsisOnly isPhoneDropdown ?hasApplyButton ?onApply ?showAllSelectedOptions ?buttonClickFn showSelectCountButton defaultLeftIcon=?leftIcon ?maxHeight ?customBackColor showToolTipOptions textEllipsisForDropDownOptions showBtnTextToolTip dropdownClassName ?searchInputPlaceHolder showSearchIcon ?customScrollStyle shouldDisplaySelectedOnTop placeholderCss /> } 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 ?customScrollStyle shouldDisplaySelectedOnTop placeholderCss /> } }
18,139
10,006
hyperswitch-control-center
src/components/ButtonGroupIp.res
.res
open SelectBox @react.component let make = ( ~input: ReactFinalForm.fieldRenderPropsInput, ~options: array<dropdownOption>, ~buttonClass="", ~isDisabled=false, ~isSeparate=false, ~buttonSize=?, ) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let onChange = str => input.onChange(str->Identity.stringToFormReactEvent) let buttonState = {isDisabled ? Button.Disabled : Button.Normal} let buttons = options ->Array.mapWithIndex((op, i) => { let active = input.value->LogicUtils.getStringFromJson("") === op.value if isSeparate { <Button key={i->Int.toString} text={op.label} onClick={_ => onChange(op.value)} buttonType={active ? Primary : SecondaryFilled} leftIcon=?op.icon buttonState ?buttonSize /> } else { <Button key={i->Int.toString} text={op.label} onClick={_ => onChange(op.value)} textStyle={active ? `${textColor.primaryNormal}` : ""} textWeight={active ? "font-semibold" : "font-medium"} customButtonStyle={active ? "shadow-inner" : ""} buttonType={active ? SecondaryFilled : Secondary} leftIcon=?op.icon buttonState ?buttonSize /> } }) ->React.array if isSeparate { <div className={`flex flex-row gap-4 items-center my-2 ${buttonClass}`}> {buttons} </div> } else { <ButtonGroup wrapperClass="flex flex-row mr-2 ml-1"> {buttons} </ButtonGroup> } }
389
10,007
hyperswitch-control-center
src/components/NewCalendarTimeInput.res
.res
open DateTimeUtils let textBoxClass = " font-inter-style text-fs-14 leading-5 font-normal text-jp-2-light-gray-2000" module CustomInputBox = { @react.component let make = ( ~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder, ~isDisabled=false, ~type_="text", ~inputMode="text", ~autoFocus=false, ~widthClass="w-full", ~fontClassName="text-jp-gray-900 text-body text-opacity-75", ~borderClass="h-10 pl-4 border-2 border-jp-gray-700 dark:border-jp-gray-800 border-opacity-25 focus:border-opacity-100 focus:border-primary dark:focus:border-primary rounded-md", ~maxLength=100, ~setVal, ) => { let cursorClass = if isDisabled { "cursor-not-allowed bg-jp-gray-400 dark:bg-jp-gray-950" } else { "bg-transparent" } let placeholder = if isDisabled { "To be filled by customer" } else { placeholder } let className = `${widthClass} ${cursorClass} placeholder-jp-gray-900 placeholder-opacity-50 dark:placeholder-jp-gray-700 dark:placeholder-opacity-50 ${borderClass} focus:text-opacity-100 focus:outline-none dark:text-jp-gray-text_darktheme dark:text-opacity-75 dark:focus:text-opacity-100 ${fontClassName}` let value = switch input.value->JSON.Decode.string { | Some(str) => str | _ => "" } <HeadlessUISelectBox value={String("")} setValue=setVal dropDownClass={`w-[216px] h-[296px] overflow-scroll !rounded-lg !shadow-jp-2-xs`} textClass=textBoxClass dropdownPosition=Right closeListOnClick=true options={timeOptions->Array.map(str => { let item: HeadlessUISelectBox.updatedOptionWithIcons = { label: str, value: str, isDisabled: false, leftIcon: NoIcon, rightIcon: NoIcon, customIconStyle: None, customTextStyle: None, description: None, } item })} className=""> <input className name={input.name} onBlur={input.onBlur} onChange={input.onChange} onFocus={input.onFocus} value disabled={isDisabled} placeholder={placeholder} type_ inputMode autoFocus maxLength /> </HeadlessUISelectBox> } } @react.component let make = ( ~startDate, ~endDate, ~localStartDate, ~disableFutureDates, ~todayDate, ~todayTime, ~localEndDate, ~getTimeStringForValue, ~isoStringToCustomTimeZone, ~setStartDate, ~setEndDate, ~startTimeStr, ~endTimeStr, ) => { let {globalUIConfig: {border: {borderColor}}} = React.useContext(ThemeProvider.themeContext) let todayDateTime = DayJs.getDayJs() let time = todayDateTime.format("hh:mm:ss a") let defaultStartTime = endDate == todayDateTime.format("YYYY-MM-DD") ? time->String.toUpperCase : (`${endDate} ${endTimeStr}`->DayJs.getDayJsForString).format( "hh:mm:ss a", )->String.toUpperCase let (fromTime, setFromTime) = React.useState(_ => (`${startDate} ${startTimeStr}`->DayJs.getDayJsForString).format( "hh:mm:ss a", )->String.toUpperCase ) let (toTime, settoTime) = React.useState(_ => defaultStartTime) let fromDateJs = startDate->DayJs.getDayJsForString let toDateJs = endDate->DayJs.getDayJsForString let inputFromDate: ReactFinalForm.fieldRenderPropsInput = { name: "fromDate", onBlur: _ => (), onChange: ev => { let value = ReactEvent.Form.target(ev)["value"] setFromTime(_ => value) }, onFocus: _ => (), value: fromTime->JSON.Encode.string, checked: true, } let inputtoDate: ReactFinalForm.fieldRenderPropsInput = { name: "toDate", onBlur: _ => (), onChange: ev => { let value = ReactEvent.Form.target(ev)["value"] settoTime(_ => value) }, onFocus: _ => (), value: toTime->JSON.Encode.string, checked: true, } let setFromTimeDropdown = val => { let fromTimeArr = val->String.split(" ") let fromTime = `${fromTimeArr->Array.get(0)->Option.getOr("12:00")}:00 ${fromTimeArr ->Array.get(1) ->Option.getOr("AM")}` setFromTime(_ => fromTime->String.toUpperCase) } let setToTimeDropdown = val => { let toTimeArr = val->String.split(" ") let toTime = `${toTimeArr->Array.get(0)->Option.getOr("11:59")}:00 ${toTimeArr ->Array.get(1) ->Option.getOr("PM")}` settoTime(_ => toTime->String.toUpperCase) } React.useEffect(() => { let endTime = localEndDate->getTimeStringForValue(isoStringToCustomTimeZone) let startDateTime = `${startDate} ${fromTime}`->DayJs.getDayJsForString if startDateTime.isValid() { let startTimeVal = startDateTime.format("HH:mm:ss") if localStartDate->LogicUtils.isNonEmptyString { if disableFutureDates && startDate == todayDate && startTimeVal > todayTime { setStartDate(~date=startDate, ~time=todayTime) } else if disableFutureDates && startDate == endDate && startTimeVal > endTime { () } else { setStartDate(~date=startDate, ~time=startTimeVal) } } } None }, [fromTime]) React.useEffect(() => { let startTime = localStartDate->getTimeStringForValue(isoStringToCustomTimeZone) let endDateTime = `${endDate} ${toTime}`->DayJs.getDayJsForString if endDateTime.isValid() { let endTimeVal = endDateTime.format("HH:mm:ss") if localEndDate->LogicUtils.isNonEmptyString { if disableFutureDates && endDate == todayDate && endTimeVal > todayTime { setEndDate(~date=startDate, ~time=todayTime) } else if disableFutureDates && startDate == endDate && endTimeVal < startTime { () } else { setEndDate(~date=endDate, ~time=endTimeVal) } } } None }, [toTime]) let updatedFromDate = fromDateJs.isValid() ? try { fromDateJs.format("dddd, MMMM DD, YYYY") } catch { | _error => "" } : "" let updatedToDate = toDateJs.isValid() ? try { toDateJs.format("dddd, MMMM DD, YYYY") } catch { | _error => "" } : "" let dateClass = "text-jp-2-light-gray-1200 text-fs-16 font-normal leading-6 mb-4" <div className="w-[328px] px-6 font-inter-style mb-12 pt-4 "> <div className="mb-10"> <div className={dateClass}> {React.string(updatedFromDate)} </div> <div className="w-4/12"> <CustomInputBox input=inputFromDate fontClassName=textBoxClass placeholder="09:00 AM" borderClass={`h-10 pl-1 border-b border-jp-gray-lightmode_steelgray dark:border-jp-gray-700 border-opacity-75 focus:border-opacity-100 ${borderColor.primaryFocused} dark:${borderColor.primaryFocused}`} setVal=setFromTimeDropdown /> </div> </div> <div> <div className=dateClass> {React.string(updatedToDate)} </div> <div className="w-4/12"> <CustomInputBox input=inputtoDate fontClassName=textBoxClass placeholder="11:00 PM" borderClass={`h-10 pl-1 border-b border-jp-gray-lightmode_steelgray dark:border-jp-gray-700 border-opacity-75 focus:border-opacity-100 ${borderColor.primaryFocused} dark:${borderColor.primaryFocused}`} setVal=setToTimeDropdown /> </div> </div> </div> }
1,947
10,008
hyperswitch-control-center
src/components/TabularInput.res
.res
external ffInputToTableInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput< array<array<string>>, > = "%identity" module FieldInputRenderer = { @react.component let make = (~item, ~input: ReactFinalForm.fieldRenderPropsInput) => { <td> {item(input)} </td> } } module TableCell = { @react.component let make = (~onClick, ~elemIndex, ~isLast, ~fields, ~onChange, ~keyValue) => { <tr key={Int.toString(elemIndex)} className=" h-full rounded-md bg-white dark:bg-jp-gray-lightgray_background transition duration-300 ease-in-out text-sm text-jp-gray-800 dark:text-jp-gray-text_darktheme dark:text-opacity-75"> {fields ->Array.mapWithIndex((itm, i) => { let input: ReactFinalForm.fieldRenderPropsInput = { name: `input`, onBlur: _ => (), onChange: ev => { let event = ev->ReactEvent.Form.target onChange(elemIndex, i, event["value"]) }, onFocus: _ => (), value: (keyValue[elemIndex]->Option.getOr([]))[i]->Option.getOr("")->JSON.Encode.string, checked: true, } <FieldInputRenderer item=itm input key={Int.toString(i)} /> }) ->React.array} <td className="mt-2 ml-5"> <Button text={isLast ? "Add Row" : "Remove"} buttonState=Normal buttonSize=Small leftIcon={isLast ? FontAwesome("plus-circle") : FontAwesome("minus-circle")} onClick={onClick(elemIndex, isLast)} /> </td> </tr> } } module TableHeading = { @react.component let make = (~heading) => { <th> <div className={`flex flex-row justify-between px-4 py-3 bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 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="font-bold text-sm"> {heading->React.string} </div> </div> </th> } } module TableStructure = { @react.component let make = (~children, ~headings) => { <div> <table className="table-auto w-full h-full" colSpan=0> <thead> <tr className="h-full rounded-md bg-white dark:bg-jp-gray-lightgray_background hover:bg-jp-gray-table_hover dark:hover:bg-jp-gray-100 dark:hover:bg-opacity-10 transition duration-300 ease-in-out text-sm text-jp-gray-800 dark:text-jp-gray-text_darktheme dark:text-opacity-75"> {headings ->Array.mapWithIndex((heading, i) => { <TableHeading heading key={Int.toString(i)} /> }) ->React.array} </tr> {children->React.Children.map(element => { element })} </thead> </table> </div> } } @react.component let make = (~input: ReactFinalForm.fieldRenderPropsInput, ~headings, ~fields) => { let tableInput = input->ffInputToTableInput let currentValue = React.useMemo(() => { switch tableInput.value->JSON.Decode.array { | Some(str) => str->Array.map(item => { switch item->JSON.Decode.array { | Some(a) => a->Array.map( itm => { LogicUtils.getStringFromJson(itm, "") }, ) | None => [] } }) | None => [] } }, [tableInput.value]) let dummyInitialState = [{fields->Array.map(_ => {""})}] let initialState = Array.length(currentValue) > 0 ? currentValue : dummyInitialState let (keyValue, setKeyValue) = React.useState(() => initialState) let onKeyUp = tableInput.onChange let onChange = (elemIndex, coloumnIndex, value) => { let a = keyValue->Array.mapWithIndex((itm, index) => { if index == elemIndex { itm->Array.mapWithIndex((val, k) => { if k == coloumnIndex { value } else { val } }) } else { itm } }) onKeyUp(a) setKeyValue(_ => a) } let onClick = (elemIndex, isLast) => _ => { let value = if isLast { Array.concat(initialState, dummyInitialState) } else { Array.filterWithIndex(initialState, (_, index) => index !== elemIndex) } setKeyValue(_ => value) onKeyUp(value) } <TableStructure headings> {initialState ->Array.mapWithIndex((_, i) => { let isLast = {i == Array.length(initialState) - 1} <TableCell onClick elemIndex=i isLast fields onChange keyValue /> }) ->React.array} </TableStructure> }
1,164
10,009
hyperswitch-control-center
src/components/DragNDropDemoLazy.res
.res
open LazyUtils type props = { isHorizontal: option<bool>, keyExtractor: JSON.t => option<string>, listItems: array<JSON.t>, setListItems: (array<JSON.t> => array<JSON.t>) => unit, } let make: props => React.element = reactLazy(() => import_("./DragNDropDemo.res.js"))
77
10,010
hyperswitch-control-center
src/components/LoadedTableWithCustomColumns.res
.res
@react.component let make = ( ~defaultSort=?, ~title, ~description=?, ~tableActions=?, ~rightTitleElement=React.null, ~bottomActions=?, ~showSerialNumber=false, ~actualData, ~totalResults, ~resultsPerPage, ~offset, ~setOffset, ~handleRefetch=() => (), ~entity: EntityType.entityType<'colType, 't>, ~onEntityClick=?, ~currrentFetchCount, ~filters=React.null, ~tableDataBackgroundClass="", ~hideRightTitleElement=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=_ => React.null, ~onMouseEnter=?, ~onMouseLeave=?, ~frozenUpto=?, ~heightHeadingClass=?, ~highlightText="", ~enableEqualWidthCol=false, ~clearFormatting=false, ~rowHeightClass="", ~allowNullableRows=false, ~titleTooltip=false, ~isAnalyticsModule=false, ~rowCustomClass="", ~isHighchartLegend=false, ~filterObj=?, ~setFilterObj=?, ~headingCenter=false, ~filterIcon=?, ~customColumnMapper, ~defaultColumns, ~sortingBasedOnDisabled=true, ~showSerialNumberInCustomizeColumns=true, ~showResultsPerPageSelector=true, ~setExtFilteredDataLength=?, ~noScrollbar=false, ~previewOnly=false, ~remoteSortEnabled=false, ~showAutoScroll=false, ~hideCustomisableColumnButton=false, ~customizeColumnButtonIcon="customise-columns", ) => { let (showColumnSelector, setShowColumnSelector) = React.useState(() => false) let activeColumnsAtom = customColumnMapper->Some let visibleColumns = customColumnMapper->Recoil.useRecoilValueFromAtom let chooseCols = <DynamicTableUtils.ChooseColumnsWrapper entity totalResults={actualData->Array.length} activeColumnsAtom defaultColumns setShowColumnSelector showColumnSelector sortingBasedOnDisabled showSerialNumber={showSerialNumberInCustomizeColumns} /> let filt = <div className="flex flex-row gap-4"> {filters} {chooseCols} </div> let customizeColumn = <RenderIf condition={!hideRightTitleElement}> <Portal to={`${title}CustomizeColumn`}> <Button leftIcon=Button.CustomIcon(<Icon name=customizeColumnButtonIcon size=16 />) buttonType=SecondaryFilled buttonSize=Small onClick={_ => setShowColumnSelector(_ => true)} customButtonStyle="!rounded !bg-white !h-10 !text-black !w-10" /> </Portal> </RenderIf> let rightTitleElement = !previewOnly ? customizeColumn : React.null <LoadedTable visibleColumns entity actualData title hideTitle ?description rightTitleElement ?tableActions showSerialNumber totalResults currrentFetchCount offset resultsPerPage setOffset handleRefetch ?onEntityClick ?downloadCsv filters=filt tableDataLoading dataLoading ignoreUrlUpdate ?advancedSearchComponent setData setSummary ?dataNotFoundComponent ?bottomActions ?renderCard ?defaultSort tableLocalFilter collapseTableRow ?frozenUpto ?heightHeadingClass getRowDetails ?onMouseEnter ?onMouseLeave rowHeightClass titleTooltip rowCustomClass ?filterObj ?setFilterObj ?filterIcon tableheadingClass tableDataBackgroundClass showResultsPerPageSelector ?setExtFilteredDataLength noScrollbar remoteSortEnabled showAutoScroll hideCustomisableColumnButton /> }
1,000
10,011
hyperswitch-control-center
src/components/NewCalendarList.res
.res
open DateTimeUtils external ffInputToSelectInput: ReactFinalForm.fieldRenderPropsInput => ReactFinalForm.fieldRenderPropsCustomInput< array<string>, > = "%identity" open NewCalendar @react.component let make = ( ~forwardRef as _=?, ~changeHighlightCellStyle="", ~calendarContaierStyle="", ~month: option<month>=?, ~year: option<int>=?, ~onDateClick=?, ~changeEndDate=?, ~changeStartDate=?, ~count=1, ~cellHighlighter=?, ~cellRenderer=?, ~startDate="", ~endDate="", ~showTime=false, ~disablePastDates=true, ~disableFutureDates=false, ~dateRangeLimit=?, ~setShowMsg=?, ~secondCalendar=false, ~firstCalendar=false, ~customDisabledFutureDays=0.0, ) => { open LogicUtils let (fromDate, setFromDate) = React.useState(_ => "") let (toDate, setToDate) = React.useState(_ => "") let (fromDateOnFocus, setFromDateOnFocus) = React.useState(_ => false) let (toDateOnFocus, setToDateOnFocus) = React.useState(_ => false) let (isDateClicked, setIsDateClicked) = React.useState(_ => false) let startYear = switch year { | Some(y) => Int.toFloat(y) | None => Js.Date.getFullYear(Date.make()) } React.useEffect(() => { let fromDateJs = fromDate->DayJs.getDayJsForString let toDateJs = toDate->DayJs.getDayJsForString let permittedMaxYears = startYear->Float.toInt + 10 let updatedFromDate = fromDate->isNonEmptyString && fromDate->String.length >= 5 && fromDateJs.isValid() && fromDateJs.year() <= permittedMaxYears ? try { fromDateJs.format("YYYY-MM-DD") } catch { | _error => "" } : "" let updatedToDate = toDate->isNonEmptyString && toDate->String.length >= 5 && toDateJs.isValid() && toDateJs.year() <= permittedMaxYears ? try { toDateJs.format("YYYY-MM-DD") } catch { | _error => "" } : "" if updatedFromDate->isNonEmptyString && updatedFromDate != startDate { switch changeStartDate { | Some(changeStartDate) => changeStartDate(updatedFromDate, false, false, None) | None => () } } if ( updatedFromDate->isNonEmptyString && updatedToDate->isNonEmptyString && updatedToDate != endDate && toDateJs >= fromDateJs ) { switch changeEndDate { | Some(changeEndDate) => changeEndDate(updatedToDate, false, None) | None => () } } None }, (fromDate, toDate)) React.useEffect(() => { if startDate->isNonEmptyString && !fromDateOnFocus { setFromDate(_ => (startDate->DayJs.getDayJsForString).format("MMM DD, YYYY")) } if endDate->isNonEmptyString && !toDateOnFocus { setToDate(_ => (endDate->DayJs.getDayJsForString).format("MMM DD, YYYY")) } else { setToDate(_ => "") } None }, (fromDateOnFocus, toDateOnFocus)) React.useEffect(() => { if isDateClicked { if startDate->isNonEmptyString && !fromDateOnFocus { setFromDate(_ => (startDate->DayJs.getDayJsForString).format("MMM DD, YYYY")) } if endDate->isNonEmptyString && !toDateOnFocus { setToDate(_ => (endDate->DayJs.getDayJsForString).format("MMM DD, YYYY")) } else { setToDate(_ => "") } setIsDateClicked(_ => false) } None }, [isDateClicked]) let (hoverdDate, setHoverdDate) = React.useState(_ => "") let _ = onDateClick // check whether month and date has value let getMonthFromFloat = value => { let valueInt = value->Float.toInt months->Array.get(valueInt)->Option.getOr(Jan) } let getMonthInFloat = mon => { Array.indexOf(months, mon)->Float.fromInt } let startMonth = switch month { | Some(m) => Int.toFloat(Float.toInt(getMonthInFloat(m))) | None => { let tMonth = Int.toFloat(Float.toInt(Js.Date.getMonth(Date.make()))) disableFutureDates && count > 1 ? tMonth -. 1.0 : tMonth } } let (currDateIm, _setCurrDate) = React.useState(() => Js.Date.makeWithYM(~year=startYear, ~month=startMonth, ()) ) let dummyRow = Array.make(~length=count, 1) <div className={`flex flex-1 flex-row justify-center overflow-auto select-none ${calendarContaierStyle}`}> {dummyRow ->Array.mapWithIndex((_item, i) => { let currDateTemp = Js.Date.fromFloat(Js.Date.valueOf(currDateIm)) let tempDate = Js.Date.setMonth( currDateTemp, Int.toFloat(Float.toInt(Js.Date.getMonth(currDateTemp)) + i), ) let tempMonth = if disableFutureDates { (Js.Date.fromFloat(tempDate)->DayJs.getDayJsForJsDate).toString() ->Date.fromString ->Js.Date.getMonth } else { Js.Date.getMonth(Js.Date.fromFloat(tempDate)) } let tempYear = Js.Date.getFullYear(Js.Date.fromFloat(tempDate)) let inputFromDate: ReactFinalForm.fieldRenderPropsInput = { name: "fromDate", onBlur: _ => setFromDateOnFocus(_ => false), onChange: ev => { let value = ReactEvent.Form.target(ev)["value"] setFromDate(_ => value) }, onFocus: _ => setFromDateOnFocus(_ => true), value: fromDate->JSON.Encode.string, checked: true, } let inputtoDate: ReactFinalForm.fieldRenderPropsInput = { name: "toDate", onBlur: _ => setToDateOnFocus(_ => false), onChange: ev => { let value = ReactEvent.Form.target(ev)["value"] setToDate(_ => value) }, onFocus: _ => setToDateOnFocus(_ => true), value: toDate->JSON.Encode.string, checked: true, } let topPadding = !showTime ? "pt-6" : "" <div key={Int.toString(i)}> <div className={`flex flex-row justify-between items-center px-6 pb-5 ${topPadding}`}> <TextInput customDashboardClass="h-11 text-base font-normal shadow-jp-2-xs" customStyle="!text-[#344054] font-inter-style" input=inputFromDate placeholder="From" /> <div className="font-normal text-base text-jp-gray-800 dark:text-jp-gray-text_darktheme dark:text-opacity-75 px-4"> {React.string("-")} </div> <TextInput customDashboardClass="h-11 text-base font-normal shadow-jp-2-xs" customStyle="!text-[#344054] font-inter-style" input=inputtoDate placeholder="To" /> </div> <NewCalendar key={Int.toString(i)} month={getMonthFromFloat(tempMonth)} year={Float.toInt(tempYear)} showTitle=false hoverdDate setHoverdDate ?cellHighlighter ?cellRenderer ?onDateClick startDate endDate disablePastDates disableFutureDates changeHighlightCellStyle ?dateRangeLimit ?setShowMsg customDisabledFutureDays setIsDateClicked /> </div> }) ->React.array} </div> }
1,751
10,012
hyperswitch-control-center
src/components/ACLDiv.resi
.resi
@react.component let make: ( ~authorization: CommonAuthTypes.authorization, ~onClick: JsxEvent.Mouse.t => unit, ~children: React.element, ~className: string=?, ~noAccessDescription: string=?, ~description: string=?, ~tooltipWidthClass: string=?, ~isRelative: bool=?, ~showTooltip: bool=?, ~contentAlign: ToolTip.contentPosition=?, ~justifyClass: string=?, ~tooltipForWidthClass: string=?, ~dataAttrStr: string=?, ~height: string=?, ) => React.element
134
10,013
hyperswitch-control-center
src/components/TableLocalFilters.res
.res
external formEventToJsonArr: ReactEvent.Form.t => array<JSON.t> = "%identity" module RangeSliderLocalFilter = { @react.component let make = ( ~filterKey, ~minVal: float, ~maxVal: float, ~maxSlide: ReactFinalForm.fieldRenderPropsInput, ~minSlide: ReactFinalForm.fieldRenderPropsInput, ) => { let (lclFiltrState, setLclFltrState) = React.useContext(DatatableContext.datatableContext) let dropdownRef = React.useRef(Nullable.null) let (showDropDown, setShowDropDown) = React.useState(() => false) let selectedFilterVal = Dict.get(lclFiltrState, filterKey) let filterIconName = "bars-filter" let strokeColor = "" let rightIcon = switch selectedFilterVal { | Some(val) => <div className="flex flex-row justify-between w-full"> <div className="px-2 text-fs-13 font-medium truncate whitespace-pre "> {val ->Array.mapWithIndex((item, index) => index > 0 ? `...${item->String.make}` : item->String.make ) ->Array.reduce("", (acc, item) => acc ++ item) ->React.string} </div> <span className={`flex items-center `}> <Icon className="align-middle" name="cross" onClick={_ => { setLclFltrState(filterKey, []) }} /> </span> </div> | None => <div className="flex flex-row justify-between w-full"> <div className="px-2 text-fs-13 font-medium truncate whitespace-pre "> {"All"->React.string} </div> <span className={`flex items-center `}> <Icon className={`align-middle ${strokeColor}`} size=12 name=filterIconName /> </span> </div> } OutsideClick.useOutsideClick( ~refs=ArrayOfRef([dropdownRef]), ~isActive=showDropDown, ~callback=() => { setShowDropDown(_ => false) }, ) let min = minVal->Float.toString let max = maxVal->Float.toString <div className="flex relative flex-row flex-wrap"> <div className="flex relative flex-row flex-wrap w-full"> <div className="flex justify-center relative h-10 flex flex-row min-w-min items-center bg-white text-jp-gray-900 text-opacity-75 hover:shadow hover:text-jp-gray-900 hover:text-opacity-75 dark:bg-jp-gray-darkgray_background dark:hover:bg-jp-gray-950 dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none rounded-md border border-jp-gray-950 border-opacity-20 dark:border-jp-gray-960 dark:border-opacity-100 text-jp-gray-950 hover:text-black dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75 cursor-pointer px-2 w-full justify-between overflow-hidden w-full" type_="button" onClick={_ => setShowDropDown(prev => !prev)}> {rightIcon} </div> <RenderIf condition={min !== max && showDropDown}> <div ref={dropdownRef->ReactDOM.Ref.domRef} className=" top-3.5 px-4 pt-4 pb-2 bg-white border dark:bg-jp-gray-lightgray_background border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 rounded shadow-generic_shadow dark:shadow-generic_shadow_dark mt-8 absolute border border-jp-gray-lightmode_steelgray border-opacity-75 dark:border-jp-gray-960 rounded shadow-generic_shadow dark:shadow-generic_shadow_dark z-20 "> <div className="flex"> <RangeSlider min max maxSlide minSlide /> </div> </div> </RenderIf> </div> </div> } } module FilterDropDown = { @react.component let make = (~val, ~arr: array<JSON.t>=[]) => { let (lclFiltrState, setLclFltrState) = React.useContext(DatatableContext.datatableContext) let filterIconName = "bars-filter" let strokeColor = "" // Making the options Unique let dummyDict = Dict.make() arr->LogicUtils.getStrArrayFromJsonArray->Array.forEach(item => Dict.set(dummyDict, item, "")) let options = dummyDict ->Dict.keysToArray ->Array.filter(item => item->LogicUtils.isNonEmptyString) ->SelectBox.makeOptions let selectedValue = Dict.get(lclFiltrState, val)->Option.getOr([]) let filterInput: ReactFinalForm.fieldRenderPropsInput = { name: val, onBlur: _ => (), onChange: ev => setLclFltrState(val, ev->formEventToJsonArr), onFocus: _ => (), value: selectedValue->JSON.Encode.array, checked: true, } let (buttonText, icon) = switch selectedValue->Array.length > 0 { | true => ( selectedValue->JSON.Encode.array->JSON.stringify, Button.CustomIcon( <div onClick={e => e->ReactEvent.Mouse.stopPropagation}> <span className={`flex items-center `} onClick={_ => { setLclFltrState(val, []) }}> <Icon className="align-middle" name="cross" /> </span> </div>, ), ) | false => ("All", Button.Euler(filterIconName)) } if options->Array.length > 1 { <SelectBox.BaseDropdown allowMultiSelect=true hideMultiSelectButtons=true buttonText input={filterInput} options baseComponent={<Button text=buttonText rightIcon=icon ellipsisOnly=true customButtonStyle="w-full justify-between" disableRipple=true buttonSize=Small buttonType=Secondary />} autoApply=true addButton=true searchable=true fullLength=false fixedDropDownDirection=SelectBox.BottomRight showClearAll=false showSelectAll=false /> } else { <div className="flex justify-center relative h-10 flex flex-row min-w-min items-center bg-white text-jp-gray-900 text-opacity-75 hover:shadow hover:text-jp-gray-900 hover:text-opacity-75 dark:bg-jp-gray-darkgray_background dark:hover:bg-jp-gray-950 dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none rounded-md border border-jp-gray-950 border-opacity-20 dark:border-jp-gray-960 dark:border-opacity-100 text-jp-gray-950 hover:text-black dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75 cursor-pointer px-2 w-full justify-between overflow-hidden w-full" type_="button"> <div className="max-w-[250px] md:max-w-xs"> <div className="px-2 text-fs-13 font-medium truncate whitespace-pre "> {"All"->React.string} </div> </div> <span className={`flex items-center `}> <Icon className={`align-middle ${strokeColor}`} size=12 name=filterIconName /> </span> </div> } } } module TextFilterCell = { @react.component let make = (~val) => { let (lclFiltrState, setLclFltrState) = React.useContext(DatatableContext.datatableContext) let filterIconName = "bars-filter" let strokeColor = "" let showPopUp = PopUpState.useShowPopUp() let selectedValue = Dict.get(lclFiltrState, val) ->Option.getOr([]) ->Array.get(0) ->Option.getOr(""->JSON.Encode.string) let localInput = React.useMemo((): 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 value = value->String.replace("<script>", "")->String.replace("</script>", "") setLclFltrState(val, [value->JSON.Encode.string]) }, onFocus: _ => (), value: selectedValue, checked: false, } }, [selectedValue]) let rightIcon = selectedValue === ""->JSON.Encode.string ? <span className={`flex items-center `}> <Icon className={`align-middle ${strokeColor}`} size=12 name=filterIconName /> </span> : <span className={`flex items-center `} onClick={_ => setLclFltrState(val, [""->JSON.Encode.string])}> <Icon className="align-middle" name="cross" /> </span> <div className="flex"> <TextInput input=localInput customStyle="flex justify-center h-10 flex flex-row items-center text-opacity-50 hover:text-opacity-100 dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75 rounded-md border-jp-gray-500 dark:border-jp-gray-960 to-jp-gray-200 dark:from-jp-gray-lightgray_background dark:to-jp-gray-lightgray_background hover:shadow dark:text-jp-gray-text_darktheme dark:text-opacity-50 px-2 w-full justify-between " placeholder="All" isDisabled=false inputMode="text" rightIcon /> </div> } } module RangeFilterCell = { @react.component let make = (~minVal, ~maxVal, ~val) => { let (lclFiltrState, setLclFltrState) = React.useContext(DatatableContext.datatableContext) let minVal = Math.floor(minVal) let maxVal = Math.ceil(maxVal) let selectedValueStr = Dict.get(lclFiltrState, val)->Option.getOr([ minVal->JSON.Encode.float, maxVal->JSON.Encode.float, ]) let minSlide = React.useMemo((): ReactFinalForm.fieldRenderPropsInput => { { name: "--", onBlur: _ => (), onChange: ev => { let value = {ev->ReactEvent.Form.target}["value"] let leftVal = value->Js.Float.fromString->JSON.Encode.float let rightvalue = selectedValueStr[1]->Option.getOr(JSON.Encode.null) switch selectedValueStr[1] { | Some(ele) => setLclFltrState(val, [leftVal > rightvalue ? rightvalue : leftVal, ele]) | None => () } }, onFocus: _ => (), value: selectedValueStr[0]->Option.getOr(JSON.Encode.float(0.0)), checked: false, } }, [selectedValueStr]) let maxSlide = React.useMemo((): ReactFinalForm.fieldRenderPropsInput => { { name: "--", onBlur: _ => (), onChange: ev => { let value = {ev->ReactEvent.Form.target}["value"] let rightvalue = value->Js.Float.fromString->JSON.Encode.float switch selectedValueStr[0] { | Some(ele) => setLclFltrState(val, [ele, ele > rightvalue ? ele : rightvalue]) | None => () } }, onFocus: _ => (), value: selectedValueStr[1]->Option.getOr(JSON.Encode.float(0.0)), checked: false, } }, [selectedValueStr]) <RangeSliderLocalFilter filterKey=val minVal maxVal maxSlide minSlide /> } }
2,700
10,014
hyperswitch-control-center
src/components/MultipleFileUpload.res
.res
type dataTransfer @get external dataTransfer: ReactEvent.Mouse.t => 'a = "dataTransfer" @get external files: dataTransfer => 'a = "files" open LogicUtils @val external atob: string => string = "atob" @send external focus: Dom.element => unit = "focus" @react.component let make = ( ~input: ReactFinalForm.fieldRenderPropsInput, ~fileType=".pdf", ~fileNamesInput: option<ReactFinalForm.fieldRenderPropsInput>=?, ~isDisabled=false, ~shouldParse=true, ~showUploadtoast=true, ~parseFile=str => str, ~shouldEncodeBase64=false, ~decodeParsedfile=false, ~widthClass="w-[253px]", ~heightClass="h-[74px]", ~buttonHeightClass="", ~parentDisplayClass="flex gap-5", ~displayClass="flex flex-col flex-wrap overflow-auto", ~buttonElement=?, ~rowsLimit=?, ~validateUploadedFile=?, ~allowMultiFileSelect=false, ~fileOnClick=(_, _) => (), ~customDownload=false, ~sizeLimit=?, ~pointerDisable=false, ) => { let (key, setKey) = React.useState(_ => 1) let formValues = ReactFinalForm.useField(input.name ++ "_filenames").input let fileNamesInput = switch fileNamesInput { | Some(filenamesInput) => filenamesInput | None => formValues } let fileTypeInput = ReactFinalForm.useField(input.name ++ "_filemimes").input let defaultFileNames = fileNamesInput.value->getStrArryFromJson // let defaultFileMimes = input.value->getArrayFromJson([]) let (fileNames, setFilenames) = React.useState(_ => defaultFileNames) let (fileTypes, setFileTypes) = React.useState(_ => defaultFileNames) let showToast = ToastState.useShowToast() React.useEffect(() => { fileNamesInput.onChange(fileNames->Identity.anyTypeToReactEvent) fileTypeInput.onChange(fileTypes->Identity.anyTypeToReactEvent) None }, (fileNames, fileTypes)) let clearData = indx => { setFilenames(prev => prev->Array.filterWithIndex((_, i) => indx !== i)) setFileTypes(prev => prev->Array.filterWithIndex((_, i) => indx !== i)) input.onChange( input.value ->getArrayFromJson([]) ->Array.filterWithIndex((_, i) => indx != i) ->JSON.Encode.array ->Identity.anyTypeToReactEvent, ) setKey(prev => prev + 1) } let toast = (message, toastType) => { showToast(~message, ~toastType) } let fileEmptyCheckUpload = (~value, ~files, ~filename, ~mimeType) => { if value->LogicUtils.isNonEmptyString { setFilenames(prev => { let fileArr = prev->Array.copy->Array.concat(filename) fileArr }) setFileTypes(prev => { let mimeArr = prev->Array.copy->Array.concat(mimeType) mimeArr }) files->Array.push(value->JSON.Encode.string)->ignore if showUploadtoast { toast("File Uploaded Successfully", ToastSuccess) } } else { toast("Error uploading file", ToastError) } } let onChange = evt => { let target = ReactEvent.Form.target(evt) let arr = [0] let break = ref(false) let files = input.value->LogicUtils.getArrayFromJson([]) while !break.contents { if target["files"]->Array.length > arr[0]->Option.getOr(0) { let index = arr->Array.get(0)->Option.getOr(0) switch target["files"][index] { | Some(value) => { let filename = value["name"] let size = value["size"] let mimeType = value["type"] let fileFormat = String.concat( ".", Array.pop(filename->String.split("."))->Option.getOr(""), ) let fileTypeArr = fileType->String.split(",") let isCorrectFileFormat = fileTypeArr->Array.includes(fileFormat) || fileTypeArr->Array.includes("*") let fileReader = FileReader.reader let _file = if filename->String.includes("p12") { fileReader.readAsBinaryString(value) } else if shouldEncodeBase64 { fileReader.readAsDataURL(value) } else { fileReader.readAsText(value) } fileReader.onload = e => { let target = ReactEvent.Form.target(e) let file = target["result"] let value = shouldParse ? file->parseFile : value let isValid = switch validateUploadedFile { | Some(fn) => fn(file) | _ => true } if !isCorrectFileFormat { input.onChange(Identity.stringToFormReactEvent("")) toast("Invalid file format", ToastError) } else if isValid { switch sizeLimit { | Some(sizeLimit) => if size > sizeLimit { showToast( ~message=`File size too large, upload below ${(sizeLimit / 1000) ->Int.toString}kb`, ~toastType=ToastError, ) } else { switch rowsLimit { | Some(val) => let rows = String.split(file, "\n")->Array.length if value->LogicUtils.isNonEmptyString && rows - 1 < val { setFilenames(prev => { let fileArr = prev->Array.copy->Array.concat(filename) fileArr }) setFileTypes(prev => { let mimeArr = prev->Array.copy->Array.concat(mimeType) mimeArr }) files->Array.push(value->JSON.Encode.string)->ignore if showUploadtoast { toast("File Uploaded Successfully", ToastSuccess) } } else if showUploadtoast { toast("File Size Exceeded", ToastError) } | None => fileEmptyCheckUpload(~value, ~files, ~filename, ~mimeType) } } | None => fileEmptyCheckUpload(~value, ~files, ~filename, ~mimeType) } } else { toast("Invalid file", ToastError) } } arr->Array.set(0, arr[0]->Option.getOr(0) + 1)->ignore } | None => () } } else { break := true } input.onChange(Identity.anyTypeToReactEvent(files)) } } let val = getArrayFromJson(input.value, []) let onClick = (fileName, indx) => { DownloadUtils.downloadOld( ~fileName, ~content=decodeParsedfile ? try { val->Array.get(indx)->Option.getOr(JSON.Encode.null)->getStringFromJson("")->atob } catch { | _ => toast("Error : Unable to parse file", ToastError) "" } : val->Array.get(indx)->Option.getOr(JSON.Encode.null)->getStringFromJson(""), ) } let cursor = isDisabled ? "cursor-not-allowed" : "cursor-pointer" <div className={`${parentDisplayClass}`}> <label> <div onDragOver={ev => { ev->ReactEvent.Mouse.preventDefault }} onDrop={ev => { ReactEvent.Mouse.preventDefault(ev) let files = ev->dataTransfer->files if files->Array.length > 0 { let file = files["0"] let filename = file["name"] let mimeType = file["type"] setFilenames(prev => prev->Array.concat(filename)) setFileTypes(prev => prev->Array.concat(mimeType)) input.onChange( Identity.anyTypeToReactEvent( input.value->getArrayFromJson([])->Array.concat([file->JSON.Encode.string]), ), ) } }}> {if !isDisabled { <input key={Int.toString(key)} type_="file" accept={fileType} hidden=true onChange multiple=allowMultiFileSelect /> } else { React.null }} {switch buttonElement { | Some(element) => element | None => <div className={`flex items-center justify-center gap-2 ${cursor} ${widthClass} ${heightClass} ${buttonHeightClass} rounded-md border border-[#8C8E9D4D] text-[#0E111E] `}> <Icon name="cloud-upload-alt" /> <span> {"Upload files"->React.string} </span> </div> }} </div> </label> <div className={`${heightClass} ${displayClass} justify-between gap-x-5`}> {fileNames ->Array.mapWithIndex((fileName, indx) => { <div key={indx->Int.toString} className="flex items-center border p-2 gap-4 rounded-lg"> <div className={pointerDisable ? "flex items-center gap-4 flex-1 pointer-events-none" : "flex items-center gap-4 flex-1"}> {switch fileName->String.split(".")->Array.pop->Option.getOr("") { | "pdf" => <img alt="pdf" src={`/icons/paIcons/pdfIcon.svg`} /> | "csv" => <img alt="csv" src={`/icons/paIcons/csvIcon.svg`} /> | _ => React.null }} <div className="flex flex-row text-sm text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-40 text-opacity-50 font-medium" onClick={_ => if customDownload { fileOnClick(indx, fileName) } else { onClick(fileName, indx) }}> {React.string(fileName)} </div> </div> {if !isDisabled { <Icon onClick={_ => clearData(indx)} className="cursor-pointer text-jp-gray-900 text-opacity-50" size=14 name="times" /> } else { React.null }} </div> }) ->React.array} </div> </div> }
2,252
10,015
hyperswitch-control-center
src/components/Filter.res
.res
module ClearFilters = { @react.component let make = ( ~defaultFilterKeys=[], ~clearFilters=?, ~isCountRequired=true, ~outsidefilter=false, ) => { let {updateExistingKeys} = React.useContext(FilterContext.filterContext) let textStyle = "text-red-900" let leftIcon: Button.iconType = CustomIcon(<Icon name="trash-outline" size=24 />) let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values", "initialValues"])->Nullable.make, ) let handleClearFilter = switch clearFilters { | Some(fn) => _ => { fn() // fn() } | None => _ => { let searchStr = formState.values ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.toArray ->Belt.Array.keepMap(entry => { let (key, value) = entry switch defaultFilterKeys->Array.includes(key) { | true => 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 } | false => None } }) ->Array.joinWith("&") searchStr->FilterUtils.parseFilterString->updateExistingKeys } } let hasExtraFilters = React.useMemo(() => { formState.initialValues ->JSON.Decode.object ->Option.getOr(Dict.make()) ->Dict.toArray ->Array.filter(entry => { let (_, value) = entry let isEmptyValue = switch value->JSON.Classify.classify { | String(str) => str->LogicUtils.isEmptyString | Array(arr) => arr->Array.length === 0 | Null => true | _ => false } !isEmptyValue }) ->Array.length > 0 }, (formState.initialValues, defaultFilterKeys)) let text = "Clear All" <RenderIf condition={hasExtraFilters || outsidefilter}> <Button text customButtonStyle="!h-10" showBorder=true textStyle leftIcon onClick=handleClearFilter buttonType={Secondary} customIconMargin="-mr-1" /> </RenderIf> } } module AutoSubmitter = { @react.component let make = (~autoApply, ~submit, ~defaultFilterKeys, ~submitInputOnEnter) => { let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values", "dirtyFields"])->Nullable.make, ) let form = ReactFinalForm.useForm() let values = formState.values React.useEffect(() => { let onKeyDown = ev => { let keyCode = ev->ReactEvent.Keyboard.keyCode if keyCode === 13 && submitInputOnEnter { form.submit()->ignore } } Window.addEventListener("keydown", onKeyDown) Some(() => Window.removeEventListener("keydown", onKeyDown)) }, []) React.useEffect(() => { if formState.dirty { let defaultFieldsHaveChanged = defaultFilterKeys->Array.some(key => { formState.dirtyFields->Dict.get(key)->Option.getOr(false) }) // if autoApply is false then still autoApply can work for the default filters if autoApply || defaultFieldsHaveChanged { submit(formState.values, 0)->ignore } } None }, [values]) React.null } } 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.toInt->Int.toString | _ => "" } } @react.component let make = ( ~defaultFilters, ~fixedFilters: array<EntityType.initialFilters<'t>>=[], ~requiredSearchFieldsList as _, ~setOffset=?, ~title="", ~path="", ~remoteFilters: array<EntityType.initialFilters<'t>>, ~remoteOptions: array<EntityType.optionType<'t>>, ~localOptions as _, ~localFilters: array<EntityType.initialFilters<'t>>, ~mandatoryRemoteKeys=[], ~popupFilterFields: array<EntityType.optionType<'t>>=[], ~tableName=?, ~autoApply=false, ~submitInputOnEnter=false, ~addFilterStyle="", ~filterButtonStyle="", ~defaultFilterKeys=[], ~customRightView=React.null, ~customLeftView=React.null, ~updateUrlWith=?, ~clearFilters=?, ~showClearFilter=true, ~initalCount=0, ~showSelectFiltersSearch=false, ) => { open HeadlessUI open LogicUtils let isMobileView = MatchMedia.useMobileChecker() let {query, filterKeys, setfilterKeys} = React.useContext(FilterContext.filterContext) let (allFilters, setAllFilters) = React.useState(_ => remoteFilters->Array.map(item => item.field) ) let (initialValueJson, setInitialValueJson) = React.useState(_ => JSON.Encode.object(Dict.make())) let (filterList, setFilterList) = React.useState(_ => []) let (count, setCount) = React.useState(_ => initalCount) let searchParams = query->decodeURI let verticalGap = !isMobileView ? "gap-y-3" : "" React.useEffect(_ => { let updatedAllFilters = remoteFilters->Array.map(item => item.field) setAllFilters(_ => updatedAllFilters) None }, [remoteFilters]) let localFilterJson = RemoteFiltersUtils.getInitialValuesFromUrl( ~searchParams, ~initialFilters={Array.concat(localFilters, fixedFilters)}, (), ) let clearFilterJson = RemoteFiltersUtils.getInitialValuesFromUrl( ~searchParams, ~initialFilters={localFilters}, ~options=remoteOptions, (), ) ->getDictFromJsonObject ->Dict.keysToArray ->Array.length React.useEffect(() => { let initialValues = RemoteFiltersUtils.getInitialValuesFromUrl( ~searchParams, ~initialFilters={Array.concat(remoteFilters, fixedFilters)}, ~mandatoryRemoteKeys, ~options=remoteOptions, (), ) switch updateUrlWith { | Some(fn) => fn( initialValues ->getDictFromJsonObject ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, getStrFromJson(key, value)) }) ->Dict.fromArray, ) | None => () } switch initialValues->JSON.Decode.object { | Some(_) => { let selectedFilters = [] let filtersUnseletced = [] filterKeys->Array.forEach(key => { let item = remoteFilters->Array.find( item => { item.field.inputNames->Array.get(0)->Option.getOr("") === key }, ) switch item { | Some(val) => selectedFilters->Array.push(val.field)->ignore | _ => () } }) remoteFilters->Array.forEach(item => { if !(selectedFilters->Array.includes(item.field)) { filtersUnseletced->Array.push(item.field)->ignore } }) setFilterList(_ => selectedFilters) setCount(_prev => clearFilterJson + initalCount) setAllFilters(_prev => filtersUnseletced) let finalInitialValueJson = initialValues->JsonFlattenUtils.unflattenObject->JSON.Encode.object setInitialValueJson(_ => finalInitialValueJson) } | None => () } None }, (searchParams, filterKeys)) let onSubmit = (values, _) => { let obj = values->JSON.Decode.object->Option.getOr(Dict.make())->Dict.toArray->Dict.fromArray let flattendDict = obj->JSON.Encode.object->JsonFlattenUtils.flattenObject(false) let localFilterDict = localFilterJson->JsonFlattenUtils.flattenObject(false) switch updateUrlWith { | Some(updateUrlWith) => RemoteFiltersUtils.applyFilters( ~currentFilterDict=flattendDict, ~options=remoteOptions, ~defaultFilters, ~setOffset, ~path, ~existingFilterDict=localFilterDict, ~tableName, ~updateUrlWith, (), ) | None => RemoteFiltersUtils.applyFilters( ~currentFilterDict=flattendDict, ~options=remoteOptions, ~defaultFilters, ~setOffset, ~path, ~existingFilterDict=localFilterDict, ~tableName, (), ) } open Promise Nullable.null->resolve } let addFilter = option => { let updatedFilters = filterList->Array.concat([option]) let keys = [] updatedFilters->Array.forEach(item => switch item.inputNames->Array.get(0) { | Some(val) => keys->Array.push(val)->ignore | _ => () } ) setfilterKeys(_ => keys) } let allFiltersUI = <Menu \"as"="div" className="relative inline-block text-left"> {_ => <div> <Menu.Button className="flex items-center whitespace-pre leading-5 justify-center text-sm px-4 py-2 font-medium rounded-lg h-10 hover:bg-opacity-80 bg-white border"> {_ => { <> <Icon className={"mr-2"} name="plus" size=15 /> {"Add Filters"->React.string} </> }} </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 left-0 w-fit z-50 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"> {allFilters ->Array.mapWithIndex((option, i) => <Menu.Item key={i->Int.toString}> {props => <div className="relative w-max"> <button onClick={_ => addFilter(option)} className={ let activeClasses = props["active"] ? "bg-gray-100 dark:bg-black" : "" `group flex rounded-md items-center w-48 px-2 py-2 text-sm font-medium ${activeClasses}` }> <RenderIf condition={option.label->isNonEmptyString}> <div className="mr-5 text-left"> {option.label->snakeToTitle->React.string} </div> </RenderIf> <RenderIf condition={option.label->isEmptyString}> <div className="mr-5 text-left"> {option.inputNames ->getValueFromArray(0, "") ->snakeToTitle ->React.string} </div> </RenderIf> </button> </div>} </Menu.Item> ) ->React.array} </div> </> }} </Menu.Items> </Transition> </div>} </Menu> <Form onSubmit initialValues=initialValueJson> <AutoSubmitter autoApply submit=onSubmit defaultFilterKeys submitInputOnEnter /> {<AddDataAttributes attributes=[("data-filter", "remoteFilters")]> {<> <div className="flex gap-2 justify-between my-2"> <div className={`flex gap-2 flex-wrap ${verticalGap}`}> {customLeftView} <RenderIf condition={allFilters->Array.length > 0}> {allFiltersUI} </RenderIf> </div> <div className="flex gap-2"> <RenderIf condition={fixedFilters->Array.length > 0}> <FormRenderer.FieldsRenderer fields={fixedFilters->Array.map(item => item.field)} labelClass="hidden" fieldWrapperClass="p-0" /> </RenderIf> <PortalCapture key={`${title}OMPView`} name={`${title}OMPView`} /> <PortalCapture key={`${title}CustomizeColumn`} name={`${title}CustomizeColumn`} /> </div> </div> <div className={`flex gap-2 flex-wrap ${verticalGap}`}> <FormRenderer.FieldsRenderer fields={filterList} labelClass="hidden" fieldWrapperClass="p-0" /> <RenderIf condition={count > 0}> <ClearFilters defaultFilterKeys ?clearFilters outsidefilter={initalCount > 0} /> </RenderIf> </div> </>} </AddDataAttributes>} <FormValuesSpy /> </Form> }
2,973
10,016
hyperswitch-control-center
src/components/ButtonGroup.res
.res
module ButtonWrapper = { let makeInfoRecord = (~isFirst, ~isLast): ButtonGroupContext.buttonInfo => { {isFirst, isLast} } @react.component let make = (~element, ~count, ~index) => { let isFirst = index === 0 let isLast = index === count - 1 let value = React.useMemo(() => makeInfoRecord(~isFirst, ~isLast), (isFirst, isLast)) <ButtonGroupContext.Parent value> element </ButtonGroupContext.Parent> } } @react.component let make = (~children, ~wrapperClass="flex flex-row") => { let count = children->React.Children.count <div className=wrapperClass> {children->React.Children.mapWithIndex((element, index) => { <ButtonWrapper element count index /> })} </div> }
191
10,017
hyperswitch-control-center
src/components/PopUpContainer.res
.res
open PopUpState @react.component let make = (~children) => { let (openPopUps, setOpenPopUp) = Recoil.useRecoilState(PopUpState.openPopUp) let activePopUp = openPopUps->Array.get(0) let popUp = switch activePopUp { | Some(popUp) => { let handleConfirm = ev => { setOpenPopUp(prevArr => prevArr->Array.sliceToEnd(~start=1)) switch popUp.handleConfirm.onClick { | Some(onClick) => onClick(ev) | None => () } } let handlePopUp = ev => { setOpenPopUp(prevArr => prevArr->Array.sliceToEnd(~start=1)) switch popUp.handleCancel { | Some(fn) => switch fn.onClick { | Some(onClick) => onClick(ev) | None => ev->ReactEvent.Mouse.stopPropagation } | None => () } } let handleCancel = ev => { setOpenPopUp(prevArr => prevArr->Array.sliceToEnd(~start=1)) switch popUp.handleCancel { | Some(fn) => switch fn.onClick { | Some(onClick) => onClick(ev) | None => ev->ReactEvent.Mouse.stopPropagation } | None => () } } let {heading, description, popUpType} = popUp let popUpSize = switch popUp.popUpSize { | Some(size) => size | None => Large } let (buttonText, confirmButtonIcon) = (popUp.handleConfirm.text, popUp.handleConfirm.icon) let (cancelButtonText, showCloseIcon, cancelButtonIcon) = switch popUp.handleCancel { | Some(obj) => switch popUp.showCloseIcon { | Some(false) => (Some(obj.text), Some(false), obj.icon) | _ => (Some(obj.text), Some(true), obj.icon) } | None => switch popUp.showCloseIcon { | Some(false) => (None, Some(false), None) | _ => (None, None, None) } } let (popUpTypeActual, showIcon) = popUpType let showIcon = switch showIcon { | WithIcon => true | WithoutIcon => false } <PopUpConfirm handlePopUp handleConfirm handleCancel confirmType=heading confirmText=description buttonText ?confirmButtonIcon ?cancelButtonIcon popUpType=popUpTypeActual ?cancelButtonText showIcon showPopUp=true ?showCloseIcon popUpSize /> } | None => React.null } <div className="relative"> children {popUp} </div> }
615
10,018
hyperswitch-control-center
src/components/RatingOptions.res
.res
@react.component let make = (~icons, ~size) => { let (isActive, setIsActive) = React.useState(_ => false) let ratingInput = ReactFinalForm.useField("rating").input let rating = ratingInput.value->LogicUtils.getIntFromJson(1) let handleClick = ratingNumber => { ratingInput.onChange(ratingNumber->Identity.anyTypeToReactEvent) setIsActive(_ => true) } <div className="flex flex-row justify-evenly py-5"> {icons ->Array.mapWithIndex((icon, index) => { let iconRating = index + 1 <Icon key={Int.toString(index)} className={isActive && rating === iconRating ? "rounded-full text-yellow-500" : "rounded-full text-gray-400 hover:text-yellow-500"} name=icon size onClick={_ => handleClick(iconRating)} /> }) ->React.array} </div> }
218
10,019
hyperswitch-control-center
src/components/DynamicTable.res
.res
let useRemoteFilter = (~searchParams, ~remoteFilters, ~remoteOptions, ~mandatoryRemoteKeys) => { let (remoteFiltersFromUrl, setRemoteFiltersFromUrl) = React.useState(() => JSON.Encode.object(Dict.make()) ) let remoteFiltersFromUrlTemp = React.useMemo(() => { RemoteFiltersUtils.getInitialValuesFromUrl( ~searchParams, ~initialFilters=remoteFilters, ~options=remoteOptions, ~mandatoryRemoteKeys, (), ) }, [searchParams]) if remoteFiltersFromUrlTemp->JSON.stringify !== remoteFiltersFromUrl->JSON.stringify { setRemoteFiltersFromUrl(_prev => remoteFiltersFromUrlTemp) } remoteFiltersFromUrl } @react.component let make = ( ~entity: EntityType.entityType<'colType, 't>, ~title, ~titleSize: NewThemeUtils.headingSize=Large, ~hideTitle=false, ~description=?, ~hideFiltersOnNoData=false, ~showSerialNumber=false, ~tableActions=?, ~isTableActionBesideFilters=false, ~hideFilterTopPortals=true, ~bottomActions=?, ~resultsPerPage=15, ~onEntityClick=?, ~method: Fetch.requestMethod=Post, ~path=?, ~downloadCsv=?, ~prefixAddition=?, ~ignoreUrlUpdate=false, ~advancedSearchComponent=?, ~body=?, ~isFiltersInPortal=true, ~defaultSort=?, ~dataNotFoundComponent=?, ~visibleColumns as visibleColumnsProp=?, ~activeColumnsAtom=?, ~customizedColumnsStyle="", ~renderCard=?, ~getCustomUriForOrder=?, ~portalKey="desktopNavbarLeft", ~isEulerOrderEntity=false, ~tableLocalFilter=false, ~dropdownSearchKeyValueNames=[], ~searchkeysDict=Dict.make(), ~mandatoryRemoteKeys=[], ~isSearchKeyArray=false, ~forcePreventConcatData=false, ~collapseTableRow=false, ~showRefreshFilter=true, ~filterButtonStyle="", ~getRowDetails=_ => React.null, ~onMouseEnter=?, ~onMouseLeave=?, ~customFilterStyle="", ~reactWindow=false, ~frozenUpto=?, ~heightHeadingClass=?, ~rowHeightClass="", ~titleTooltip=false, ~rowCustomClass="", ~requireDateFormatting=false, ~autoApply=?, ~showClearFilter=true, ~addDataLoading=false, ~filterObj=?, ~setFilterObj=?, ~filterCols=?, ~filterIcon=?, ~applyFilters=false, ~errorButtonType: Button.buttonType=Primary, ~maxTableHeight="", ~tableheadingClass="", ~ignoreHeaderBg=false, ~customLocalFilterStyle="", ~showFiltersSearch=false, ~showFilterBorder=false, ~headBottomMargin="mb-6 mobile:mb-4", ~noDataMsg="No Data Available", ~checkBoxProps=?, ~tableBorderClass=?, ~paginationClass=?, ~tableDataBorderClass=?, ~tableActionBorder=?, ~disableURIdecode=false, ~mergeBodytoRemoteFilterDict=false, ~defaultKeysAllowed=?, ~urlKeyTypeDict: Dict.t<RemoteFiltersUtils.urlKEyType>=Dict.make(), ) => { open LogicUtils let { getObjects, dataKey, summaryKey, initialFilters, options, headers, uri, getSummary, searchValueDict, getNewUrl, defaultColumns, popupFilterFields, dateRangeFilterDict, filterCheck, filterForRow, } = entity let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let tableName = prefixAddition->Option.getOr(false) ? title->(String.replaceRegExp(_, %re("/ /g"), "-"))->String.toLowerCase->Some : None let (defaultFilters, setDefaultFilters) = React.useState(() => entity.defaultFilters) let defaultSummary: EntityType.summary = {totalCount: 0, count: 0} let (summary, setSummary) = React.useState(() => defaultSummary) let (data, setData) = React.useState(() => None) let (tableDataLoading, setTableDataLoading) = React.useState(() => false) let fetchApi = AuthHooks.useApiFetcher() let url = RescriptReactRouter.useUrl() let searchParams = disableURIdecode ? url.search : url.search->decodeURI let (refreshData, _setRefreshData) = React.useContext(RefreshStateContext.refreshStateContext) let (offset, setOffset) = React.useState(() => 0) let remoteFilters = initialFilters->Array.filter(item => item.localFilter->Option.isNone) let filtersFromUrl = getDictFromUrlSearchParams(searchParams) let localFilters = initialFilters->Array.filter(item => item.localFilter->Option.isSome) let showToast = ToastState.useShowToast() let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let localOptions = Array.concat(options, popupFilterFields)->Array.filter(item => item.localFilter->Option.isSome) let remoteOptions = Array.concat(options, popupFilterFields)->Array.filter(item => item.localFilter->Option.isNone) let remoteFiltersFromUrl = useRemoteFilter( ~searchParams, ~remoteFilters, ~remoteOptions, ~mandatoryRemoteKeys, ) let isMobileView = MatchMedia.useMobileChecker() let resultsPerPage = isMobileView ? 10 : resultsPerPage let (fetchSuccess, setFetchSuccess) = React.useState(() => true) let (refetchCounter, setRefetchCounter) = React.useState(() => 0) let (showColumnSelector, setShowColumnSelector) = React.useState(() => false) let (finalData, setFinalData) = React.useState(_ => None) React.useEffect(() => { setDefaultFilters(_ => entity.defaultFilters) None }, [entity.defaultFilters]) React.useEffect(() => { let remoteFilterDict = RemoteFiltersUtils.getFinalDict( ~filterJson=defaultFilters, ~filtersFromUrl=remoteFiltersFromUrl, ~options=remoteOptions->Array.concat(popupFilterFields), ~isEulerOrderEntity, ~dropdownSearchKeyValueNames, ~searchkeysDict, ~isSearchKeyArray, ~defaultKeysAllowed?, ~urlKeyTypeDict, (), ) open Promise let finalJson = switch body { | Some(b) => let remoteFilterDict = remoteFilterDict->getDictFromJsonObject if mergeBodytoRemoteFilterDict { DictionaryUtils.mergeDicts([b->getDictFromJsonObject, remoteFilterDict])->JSON.Encode.object } else { b } | None => remoteFilterDict } let clearData = () => { setData(_ => Some([])) } let setNewData = sampleRes => { if ( (remoteFiltersFromUrl->getDictFromJsonObject != Dict.make() && offset == 0) || forcePreventConcatData ) { clearData() } setData(prevData => { let newData = prevData->Option.getOr([])->Array.concat(sampleRes) Some(newData) }) } let getCustomUri = (uri, searchValueDict) => { let uriList = Dict.keysToArray(searchValueDict)->Array.map(val => { let defaultFilterOffset = defaultFilters->getDictFromJsonObject->getInt("offset", 0) let dictValue = if val === "offset" { defaultFilterOffset->Int.toString } else { let x = filtersFromUrl ->Dict.get(val) ->Option.getOr(searchValueDict->Dict.get(val)->Option.getOr("")) if requireDateFormatting && (val == "startTime" || val == "endTime") { (x->DayJs.getDayJsForString).format("YYYY-MM-DD+HH:mm:ss") } else if requireDateFormatting && (val == "start_date" || val == "end_date") { (x->DayJs.getDayJsForString).format("YYYY-MM-DD HH:mm:ss") } else { x } } let urii = dictValue->isEmptyString || dictValue == "NA" ? "" : `${val}=${dictValue}` urii }) let uri = uri ++ "?" ++ uriList->Array.filter(val => val->isNonEmptyString)->Array.joinWith("&") uri } let uri = switch searchValueDict { | Some(searchValueDict) => getCustomUri(uri, searchValueDict) | None => uri } let uri = switch getCustomUriForOrder { | Some(getCustomUri) => getCustomUri(uri, ~filtersJson=remoteFiltersFromUrl, ~finalJson) | None => uri } let uri = uri ++ getNewUrl(defaultFilters) setTableDataLoading(_ => true) fetchApi( uri, ~bodyStr=JSON.stringify(finalJson), ~headers, ~method_=method, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->then(resp => { let status = resp->Fetch.Response.status if status >= 300 { setFetchSuccess(_ => false) setTableDataLoading(_ => false) } Fetch.Response.json(resp) }) ->then(json => { switch json->JSON.Classify.classify { | Array(_arr) => json->getObjects->Array.map(obj => obj->Nullable.make)->setNewData | Object(dict) => { let flattenedObject = JsonFlattenUtils.flattenObject(json, false) switch Dict.get(flattenedObject, dataKey) { | Some(x) => x->getObjects->Array.map(obj => obj->Nullable.make)->setNewData | None => () } let summary = switch Dict.get(dict, summaryKey) { | Some(x) => x->getSummary | None => dict->JSON.Encode.object->getSummary } setSummary(_ => summary) } | _ => showToast(~message="Response was not a JSON object", ~toastType=ToastError, ~autoClose=true) } setTableDataLoading(_ => false) resolve() }) ->catch(_ => { resolve() }) ->ignore None }, (remoteFiltersFromUrl, defaultFilters, fetchApi, refreshData, uri)) React.useEffect(() => { if refetchCounter > 0 { Window.Location.reload() } None }, [refetchCounter]) let refetch = React.useCallback(() => { setRefetchCounter(p => p + 1) }, [setRefetchCounter]) let visibleColumns = visibleColumnsProp->Option.getOr(defaultColumns) let handleRefetch = () => { let rowFetched = data->Option.getOr([])->Array.length if rowFetched !== summary.totalCount { setTableDataLoading(_ => true) let newDefaultFilter = defaultFilters->JSON.Decode.object->Option.getOr(Dict.make())->Dict.toArray->Dict.fromArray Dict.set(newDefaultFilter, "offset", rowFetched->Int.toFloat->JSON.Encode.float) setDefaultFilters(_ => newDefaultFilter->JSON.Encode.object) } } let showLocalFilter = (localFilters->Array.length > 0 || localOptions->Array.length > 0) && (applyFilters ? finalData : data)->Option.getOr([])->Array.length > 0 let showRemoteFilter = remoteFilters->Array.length > 0 || remoteOptions->Array.length > 0 let filters = { if ( (Array.length(initialFilters) > 0 || Array.length(options) > 0) && (showLocalFilter || showRemoteFilter) && (!hideFiltersOnNoData || data->Option.getOr([])->Array.length > 0) ) { let children = <div className={`flex-1 ${customFilterStyle}`}> {if showLocalFilter { <LabelVisibilityContext showLabel=false> <LocalFilters entity setOffset ?path remoteFilters localFilters mandatoryRemoteKeys remoteOptions localOptions ?tableName customLocalFilterStyle showSelectFiltersSearch=showFiltersSearch disableURIdecode /> </LabelVisibilityContext> } else { React.null }} <RenderIf condition=showRemoteFilter> <LabelVisibilityContext showLabel=false> <Filter defaultFilters=entity.defaultFilters requiredSearchFieldsList=entity.requiredSearchFieldsList setOffset filterButtonStyle ?path title remoteFilters localFilters mandatoryRemoteKeys remoteOptions localOptions popupFilterFields ?tableName ?autoApply showClearFilter showSelectFiltersSearch=showFiltersSearch /> </LabelVisibilityContext> </RenderIf> </div> if isFiltersInPortal { <Portal to=portalKey> {children} </Portal> } else { children } } else { React.null } } React.useEffect(() => { let temp = switch filterObj { | Some(obj) => switch filterCols { | Some(cols) => let _ = cols->Array.map(key => { obj[key] = filterForRow(data, key) }) obj | _ => [] } | _ => [] } switch setFilterObj { | Some(fn) => fn(_ => temp) | _ => () } None }, [data]) let checkLength = ref(true) React.useEffect(() => { let findVal = (accumulator, item: TableUtils.filterObject) => Array.concat(accumulator, item.selected) let keys = switch filterObj { | Some(obj) => obj->Array.reduce([], findVal) | None => [] } switch filterObj { | Some(obj) => switch filterCols { | Some(cols) => for i in 0 to cols->Array.length - 1 { checkLength := checkLength.contents && switch obj[cols[i]->Option.getOr(0)] { | Some(ele) => Array.length(ele.selected) > 0 | None => false } } | _ => () } if checkLength.contents { let newData = switch data { | Some(data) => data->Array.filter(item => { switch item->Nullable.toOption { | Some(val) => filterCheck(val, keys) | _ => false } }) | None => [] } setFinalData(_ => Some(newData)) } else { setFinalData(_ => data) } | _ => () } None }, (filterObj, data)) let dataLoading = addDataLoading ? tableDataLoading : false let customizeColumnButtonType: Button.buttonType = SecondaryFilled switch applyFilters ? finalData : data { | Some(actualData) => { let localFilteredData = localFilters->Array.length > 0 || localOptions->Array.length > 0 ? RemoteFiltersUtils.getLocalFiltersData( ~resArr=actualData, ~dateRangeFilterDict, ~searchParams, ~initialFilters=localFilters, ~options=localOptions, (), ) : actualData let currrentFetchCount = localFilteredData->Array.length open DynamicTableUtils let totalResults = if actualData->Array.length < summary.totalCount { summary.totalCount } else { currrentFetchCount } let customizeColumn = if ( activeColumnsAtom->Option.isSome && entity.allColumns->Option.isSome && totalResults > 0 ) { <Button text="Customize Columns" leftIcon=Button.CustomIcon(<Icon name="vertical_slider" size=15 className="mr-1" />) buttonType=customizeColumnButtonType buttonSize=Small onClick={_ => setShowColumnSelector(_ => true)} customButtonStyle=customizedColumnsStyle showBorder={true} /> } else { React.null } let chooseCols = if customizeColumn === React.null { React.null } else { <ChooseColumnsWrapper entity totalResults defaultColumns activeColumnsAtom setShowColumnSelector showColumnSelector /> } let filt = <div className={`flex flex-row gap-4`}> {filters} {chooseCols} </div> <RefetchContextProvider value=refetch> {if reactWindow { <ReactWindowTable visibleColumns entity actualData=localFilteredData title hideTitle ?description rightTitleElement=customizeColumn ?tableActions showSerialNumber totalResults ?onEntityClick ?downloadCsv tableDataLoading ?dataNotFoundComponent ?bottomActions tableLocalFilter collapseTableRow getRowDetails ?onMouseEnter ?onMouseLeave /> } else { <LoadedTable visibleColumns entity actualData=localFilteredData title titleSize hideTitle ?description rightTitleElement={customizeColumn} ?tableActions isTableActionBesideFilters hideFilterTopPortals showSerialNumber totalResults currrentFetchCount offset resultsPerPage setOffset ignoreHeaderBg handleRefetch ?onEntityClick ?downloadCsv filters=filt showFilterBorder headBottomMargin tableDataLoading dataLoading ignoreUrlUpdate ?advancedSearchComponent setData setSummary ?dataNotFoundComponent ?bottomActions ?renderCard ?defaultSort tableLocalFilter collapseTableRow ?frozenUpto ?heightHeadingClass getRowDetails ?onMouseEnter ?onMouseLeave rowHeightClass titleTooltip rowCustomClass ?filterObj ?setFilterObj ?filterIcon maxTableHeight tableheadingClass noDataMsg ?checkBoxProps ?tableBorderClass ?paginationClass ?tableDataBorderClass ?tableActionBorder /> }} </RefetchContextProvider> } | None => <DynamicTableUtils.TableLoadingErrorIndicator title titleSize showFilterBorder fetchSuccess filters buttonType=errorButtonType hideTitle /> } }
4,177
10,020