All files / modules/10-common/components/Filter Filter.tsx

86.36% Statements 38/44
83.02% Branches 44/53
72.73% Functions 8/11
86.05% Lines 37/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228              25x 25x 25x 25x 25x 25x 25x 25x     25x   25x 25x                                                                   25x                                 64x 58x 58x   58x 58x   57x       57x             58x   58x                   58x 24x           58x 24x     58x       58x 28x                         58x 58x   58x             3x         28x                                                                           1x 1x 1x                                                                           25x        
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { ReactElement, useEffect } from 'react'
import * as Yup from 'yup'
import { Drawer, IDrawerProps } from '@blueprintjs/core'
import { Formik, FormikProps, FormikErrors } from 'formik'
import { truncate } from 'lodash-es'
import { FormikForm, Button, Layout, OverlaySpinner, ButtonVariation } from '@wings-software/uicore'
import { useStrings } from 'framework/strings'
import { CrudOperation, FilterCRUD, FilterCRUDRef } from './FilterCRUD/FilterCRUD'
import type { FilterInterface, FilterDataInterface } from './Constants'
 
import css from './Filter.module.scss'
 
const MAX_FILTER_NAME_LENGTH = 30
const KEY_CODE_FOR_ENTER_KEY = 13
 
export interface FilterProps<T, U> extends Partial<Omit<FormikProps<T>, 'onSubmit' | 'initialValues'>> {
  formFields: React.ReactElement
  initialFilter: FilterDataInterface<T, U>
  filters?: U[]
  isRefreshingFilters: boolean
  /*TODO @vardan fix the type later on*/
  // onApply: FormikProps<T>['onSubmit']
  onApply: (formData: T) => void
  onClose: () => void
  onSaveOrUpdate: (isUpdate: boolean, data: FilterDataInterface<T, U>) => Promise<void>
  onDelete: (identifier: string) => Promise<void>
  onFilterSelect: (identifier: string) => void
  onValidate?: (values: Partial<T>) => FormikErrors<Partial<T>>
  onClear?: () => void
  dataSvcConfig?: Map<CrudOperation, (...rest: any[]) => Promise<any>>
  ref?: FilterFowardRef<U>
  onSuccessfulCrudOperation?: () => Promise<void>
  validationSchema?: Yup.ObjectSchema
  isOpen?: boolean
}
 
export interface FilterRef<U> {
  saveOrUpdateFilterHandler: ((isUpdate: boolean, payload: U) => Promise<U | undefined>) | undefined
  deleteFilterHandler: ((identifier: string) => Promise<void>) | undefined
  duplicateFilterHandler: ((identifier: string) => Promise<void>) | undefined
}
 
export type FilterFowardRef<U> =
  | ((instance: FilterRef<U> | null) => void)
  | React.MutableRefObject<FilterRef<U> | null>
  | null
 
const FilterRef = <T, U extends FilterInterface>(props: FilterProps<T, U>, filterRef: FilterFowardRef<U>) => {
  const {
    formFields,
    onApply,
    onClose,
    initialFilter,
    filters,
    onSaveOrUpdate,
    onDelete,
    onFilterSelect,
    onValidate,
    isRefreshingFilters,
    onClear,
    dataSvcConfig,
    onSuccessfulCrudOperation,
    validationSchema,
    isOpen
  } = props
  const { getString } = useStrings()
  const filterCRUDRef = React.useRef<FilterCRUDRef<U> | null>(null)
 
  useEffect(() => {
    if (!filterRef) return
 
    Iif (typeof filterRef === 'function') {
      return
    }
 
    filterRef.current = {
      deleteFilterHandler: filterCRUDRef.current?.deleteFilterHandler,
      saveOrUpdateFilterHandler: filterCRUDRef.current?.saveOrUpdateFilterHandler,
      duplicateFilterHandler: filterCRUDRef.current?.duplicateFilterHandler
    }
  })
 
  const [drawerOpen, setDrawerOpen] = React.useState(typeof isOpen === 'undefined' ? true : isOpen)
 
  const defaultPageDrawerProps: IDrawerProps = {
    autoFocus: true,
    canEscapeKeyClose: true,
    canOutsideClickClose: true,
    enforceFocus: true,
    isOpen: drawerOpen,
    size: 700,
    position: 'right'
  }
 
  React.useEffect(() => {
    Iif (defaultPageDrawerProps.isOpen !== drawerOpen) {
      defaultPageDrawerProps.isOpen = drawerOpen
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [drawerOpen])
 
  React.useEffect(() => {
    setDrawerOpen(typeof isOpen === 'undefined' ? true : isOpen)
  }, [isOpen])
 
  const closeDrawer = (): void => {
    setDrawerOpen(false)
  }
 
  const getDrawerTitle = (isUpdate: boolean, filterName?: string): JSX.Element => {
    return (
      <Layout.Horizontal spacing="small" className={css.titleLayout}>
        <div className={css.title} title={filterName}>
          {isUpdate
            ? truncate(filterName, {
                length: MAX_FILTER_NAME_LENGTH
              })
            : getString('filters.newFilter')}
        </div>
      </Layout.Horizontal>
    )
  }
 
  const { name, filterVisibility, identifier } = initialFilter?.metadata
  const isUpdate = (name !== '' && filterVisibility !== undefined) as boolean
 
  return (
    <Drawer {...defaultPageDrawerProps} onClosed={onClose}>
      <Formik<T>
        onSubmit={onApply}
        initialValues={initialFilter.formValues}
        enableReinitialize={true}
        validate={values => {
          return onValidate?.(values)
        }}
        validationSchema={validationSchema ?? Yup.object()}
      >
        {formik => {
          return (
            <FormikForm
              onKeyDown={(keyEvent: KeyboardEvent) => {
                /* istanbul ignore else */ Iif ((keyEvent.charCode || keyEvent.keyCode) === KEY_CODE_FOR_ENTER_KEY) {
                  keyEvent.preventDefault()
                }
              }}
            >
              <div className={css.main}>
                <section className={css.formSection}>
                  <Layout.Vertical
                    spacing="large"
                    padding={{ top: 'xlarge', left: 'xlarge', right: 'xlarge' }}
                    height="100%"
                  >
                    {getDrawerTitle(isUpdate, name)}
                    <Layout.Vertical className={css.layout} padding={{ top: 'medium' }}>
                      {isRefreshingFilters ? (
                        <OverlaySpinner show={true} className={css.loading}>
                          <></>
                        </OverlaySpinner>
                      ) : (
                        <>
                          <div>
                            {formFields && React.cloneElement(formFields, { ...formFields.props, formikProps: formik })}
                          </div>
                          <Layout.Horizontal spacing={'medium'} padding={{ bottom: 'xsmall' }}>
                            <Button
                              variation={ButtonVariation.PRIMARY}
                              type="submit"
                              text={getString('filters.apply')}
                            />
                            <Button
                              variation={ButtonVariation.TERTIARY}
                              type={'reset'}
                              intent={'none'}
                              text={getString('filters.clearAll')}
                              onClick={(event: React.MouseEvent<Element, MouseEvent>) => {
                                event.preventDefault()
                                onClear?.()
                                formik?.setValues({} as T)
                              }}
                            />
                          </Layout.Horizontal>
                        </>
                      )}
                    </Layout.Vertical>
                  </Layout.Vertical>
                </section>
                <section className={css.filterSection}>
                  <FilterCRUD<U>
                    isRefreshingFilters={isRefreshingFilters}
                    filters={filters}
                    onSaveOrUpdate={async (_isUpdate: boolean, formdata: U): Promise<void> => {
                      await onSaveOrUpdate(_isUpdate, {
                        metadata: formdata,
                        formValues: formik.values
                      } as FilterDataInterface<T, U>)
                    }}
                    isLeftFilterDirty={formik.dirty}
                    initialValues={{ name, filterVisibility, identifier } as U}
                    onClose={closeDrawer}
                    onDelete={onDelete}
                    onFilterSelect={onFilterSelect}
                    ref={filterCRUDRef}
                    dataSvcConfig={dataSvcConfig}
                    onSuccessfulCrudOperation={onSuccessfulCrudOperation}
                  />
                </section>
              </div>
            </FormikForm>
          )
        }}
      </Formik>
    </Drawer>
  )
}
 
export const Filter = React.forwardRef(FilterRef) as <T, U extends FilterInterface>(
  props: FilterProps<T, U>,
  filterRef: FilterFowardRef<U>
) => ReactElement