Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/checkableselect custom search #545

Merged
merged 2 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions packages/ui/__stories__/CheckableSelectField.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,18 @@ WithoutOptions.args = {
options: [],
defaultOpen: true,
}

export const CustomSearch = Template.bind({})
CustomSearch.args = {
value: [],
options,
filterOptionsLabel: 'Custom negative search',
defaultOpen: true,
filterOptions: (candidate, input) => {
if (!input) {
return true
}

return !candidate.label.toLowerCase().includes(input)
},
}
47 changes: 46 additions & 1 deletion packages/ui/__tests__/Select/CheckableSelectField.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react'
import { useUID } from 'react-uid'
import { mountAndCheckA11Y } from '@hazelcast/test-helpers'
import { mountAndCheckA11Y, simulateChange } from '@hazelcast/test-helpers'
import { act } from 'react-dom/test-utils'

import { CheckableSelectField } from '../../src/Select/CheckableSelectField'
Expand Down Expand Up @@ -306,4 +306,49 @@ describe('CheckableSelectField', () => {
expect(wrapper.findDataTest('test-no-options-message').exists()).toBeTruthy()
expect(wrapper.findDataTest('test-no-options-message').text()).toBe('There are no options')
})

it('Custom search', async () => {
let id = 0
const onChange = jest.fn()
const filterOptions = jest.fn()
useUIDMock.mockImplementation(() => {
id += 1
return id.toString()
})
const wrapper = await mountAndCheckA11Y(
<CheckableSelectField
defaultOpen
name={selectName}
label={selectLabel}
options={options}
value={[]}
id={'21313123'}
onChange={onChange}
data-test="test"
filterOptions={filterOptions}
noOptionsMessage="There are no options"
/>,
)

const searchInput = wrapper.findDataTestFirst('test-search').find('input')

expect(searchInput).toBeTruthy()
act(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
simulateChange(searchInput, 'Luke')
})

expect(filterOptions).toHaveBeenCalledTimes(0)

act(() => {
wrapper.findDataTestFirst('test-toggle-custom-search').find('input').simulate('change')
})

act(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
simulateChange(searchInput, 'Luke2')
})

expect(filterOptions).toHaveBeenCalled()
})
})
15 changes: 10 additions & 5 deletions packages/ui/src/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { ChangeEvent, FC, FocusEvent, ReactElement, ReactText, useRef, MouseEvent } from 'react'
import React, { ChangeEvent, FocusEvent, ReactElement, ReactText, useRef, MouseEvent, forwardRef } from 'react'
import { Check, Minus } from 'react-feather'
import { DataTestProp } from '@hazelcast/helpers'
import { useUID } from 'react-uid'
Expand Down Expand Up @@ -28,6 +28,7 @@ export type CheckboxExtraProps = {
required?: boolean
className?: string
classNameLabel?: string
'aria-label'?: string
classNameCheckmark?: string
}

Expand All @@ -43,7 +44,7 @@ type CheckboxProps = CheckboxCoreProps & CheckboxExtraProps & DataTestProp
* - It's important to realise that we don't set checkbox value, but state (on/off). That is the main difference from other input types.
* - They can have a special indeterminate state, that represents a '3rd' value, usually used in tree structures, etc.
*/
export const Checkbox: FC<CheckboxProps> = (props) => {
export const Checkbox = forwardRef<HTMLDivElement, CheckboxProps>((props, ref) => {
const {
checked,
name,
Expand All @@ -60,14 +61,15 @@ export const Checkbox: FC<CheckboxProps> = (props) => {
disabled = false,
required,
'data-test': dataTest,
'aria-label': ariaLabel,
onClick,
} = props
const inputRef = useRef<HTMLInputElement>(null)
const id = useUID()

return (
<div className={classNames(className, { [styles.withError]: 'error' in props })} data-test={dataTest}>
{/*
<div ref={ref} className={classNames(className, { [styles.withError]: 'error' in props })} data-test={dataTest}>
{/*
We can only style forward elements based on input state (with ~ or +), has() is not supported yet.
That's why we need to explicitly pass error/checked/disabled classes to the wrapper element.
*/}
Expand All @@ -94,6 +96,7 @@ export const Checkbox: FC<CheckboxProps> = (props) => {
ref={inputRef}
id={id}
name={name}
aria-label={ariaLabel}
checked={!!checked}
onChange={onChange}
onBlur={onBlur}
Expand All @@ -115,4 +118,6 @@ export const Checkbox: FC<CheckboxProps> = (props) => {
<Error truncated error={error} className={styles.errorContainer} inputId={id} />
</div>
)
}
})

Checkbox.displayName = 'Checkbox'
7 changes: 7 additions & 0 deletions packages/ui/src/Select/CheckableSelectField.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,14 @@
}

.search {
display: flex;
align-items: center;
gap: c.$grid * 2;
margin-bottom: c.$grid * 2;

&Field {
flex-grow: 1;
}
}

.option {
Expand Down
59 changes: 44 additions & 15 deletions packages/ui/src/Select/CheckableSelectField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import { Link } from '../Link'
import { SelectFieldOption } from './helpers'
import { TextField } from '../TextField'
import { HelpProps } from '../Help'
import { Tooltip } from '../Tooltip'
import { Checkbox } from '../Checkbox'
import { useOpenCloseState } from '../hooks'
import { TruncatedText } from '../TruncatedText'

import styles from './CheckableSelectField.module.scss'
import { TruncatedText } from '../TruncatedText'

export type CheckableSelectFieldCoreStaticProps<V> = {
name: string
Expand Down Expand Up @@ -40,6 +42,8 @@ export type CheckableSelectFieldExtraProps<V> = {
noOptionsMessage?: string
defaultOpen?: boolean
id?: string
filterOptionsLabel?: string
filterOptions?: (candidate: SelectFieldOption<V>, input: string) => boolean
}

export type CheckableSelectProps<V> = CheckableSelectFieldCoreStaticProps<V> & CheckableSelectFieldExtraProps<V>
Expand Down Expand Up @@ -77,9 +81,12 @@ export const CheckableSelectField = <V extends string | number = number>(props:
noneSelectedLabel = 'None selected',
noOptionsMessage = 'No options',
id: rootId,
filterOptions,
filterOptionsLabel,
} = props
const id = useUID()
const { isOpen, toggle, close } = useOpenCloseState(defaultOpen)
const { isOpen: isCustomSearchEnabled, toggle: toggleCustomSearch } = useOpenCloseState(false)
const [searchValue, setSearchValue] = useState('')
const [forceUpdateToken, setForceUpdateToken] = useState(1)
const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null)
Expand All @@ -97,8 +104,14 @@ export const CheckableSelectField = <V extends string | number = number>(props:
const filteredOptions = useMemo(() => {
const value = searchValue.toLowerCase()

return options.filter(({ label }) => label.toLowerCase().includes(value))
}, [options, searchValue])
return options.filter((option) => {
if (isCustomSearchEnabled && filterOptions) {
return filterOptions(option, value)
}

return option.label.toLowerCase().includes(value)
})
}, [options, searchValue, isCustomSearchEnabled, filterOptions])

const getValueLabel = () => {
if (placeholderMode === 'permanent') {
Expand Down Expand Up @@ -150,18 +163,34 @@ export const CheckableSelectField = <V extends string | number = number>(props:
onUpdateLayout={() => setForceUpdateToken((token) => token + 1)}
>
<div className={styles.dropdown} data-test={`${dataTest}-dropdown`}>
<TextField
size={size}
iconSize="medium"
className={styles.search}
name="checkable-select-search"
data-test={`${dataTest}-search`}
onChange={(e) => setSearchValue(e.target.value)}
value={searchValue}
label=""
disabled={disabled}
placeholder={placeholder}
/>
<div className={styles.search}>
<TextField
size={size}
iconSize="medium"
className={styles.searchField}
name="checkable-select-search"
data-test={`${dataTest}-search`}
onChange={(e) => setSearchValue(e.target.value)}
value={searchValue}
label=""
disabled={disabled}
placeholder={placeholder}
/>
{filterOptions && (
<Tooltip content={filterOptionsLabel} zIndex={21}>
{(tooltipRef) => (
<Checkbox
ref={tooltipRef}
aria-label="Custom search checkbox"
checked={isCustomSearchEnabled}
name="toggle custom search"
onChange={toggleCustomSearch}
data-test={`${dataTest}-toggle-custom-search`}
/>
)}
</Tooltip>
)}
</div>
<div className={styles.options}>
{filteredOptions.length > 0 ? (
filteredOptions.map((option) => {
Expand Down
10 changes: 5 additions & 5 deletions packages/ui/src/Tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import { getPortalContainer, PortalContainer } from './utils/portal'

import styles from './Tooltip.module.scss'

const tooltipZIndex = 20

const TooltipContext = createContext<{
hide: () => void
clearHideTimeout: () => void
Expand All @@ -47,14 +45,15 @@ export type TooltipProps = {
hoverAbleTooltip?: boolean
children: (
ref: React.Dispatch<React.SetStateAction<HTMLElement | null>>,
onMouseEnter?: MouseEventHandler<Element>,
onMouseLeave?: MouseEventHandler<Element>,
onMouseEnter?: MouseEventHandler,
onMouseLeave?: MouseEventHandler,
) => ReactNode
popperRef?: MutableRefObject<PopperRef | undefined>
updateToken?: ReactText | boolean
tooltipContainer?: PortalContainer
wordBreak?: CSSProperties['wordBreak']
disabled?: boolean
zIndex?: number
}

/**
Expand Down Expand Up @@ -88,6 +87,7 @@ export const Tooltip: FC<TooltipProps> = ({
tooltipContainer = 'body',
hoverAbleTooltip = true,
disabled = false,
zIndex = 20,
}) => {
const [isShown, setShown] = useState<boolean>(false)
const timeoutRef = useRef<NodeJS.Timeout | null>(null)
Expand Down Expand Up @@ -225,7 +225,7 @@ export const Tooltip: FC<TooltipProps> = ({
className={cn(styles.overlay, {
[styles.hidden]: !isTooltipVisible,
})}
style={{ ...popper.styles.popper, ...{ zIndex: context ? tooltipZIndex + 1 : tooltipZIndex }, wordBreak }}
style={{ ...popper.styles.popper, ...{ zIndex: context ? zIndex + 1 : zIndex }, wordBreak }}
data-test="tooltip-overlay"
aria-hidden
{...popper.attributes.popper}
Expand Down
Loading