Skip to content

Commit

Permalink
feat: add conditional onClick action to chip list (#579)
Browse files Browse the repository at this point in the history
  • Loading branch information
floreks authored Mar 29, 2024
1 parent f9d498d commit 4c1cf7f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 9 deletions.
33 changes: 24 additions & 9 deletions src/components/ChipList.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { Flex, Span } from 'honorable'
import isEmpty from 'lodash-es/isEmpty'
import { type ComponentProps, type ReactElement, useState } from 'react'
import {
type ComponentProps,
type Dispatch,
type ReactElement,
useState,
} from 'react'

import { HamburgerMenuCollapseIcon } from '../icons'

Expand All @@ -15,13 +20,17 @@ export type ChipListProps<TValue> = {
transformValue?: TransformFn<TValue>
limit: number
emptyState?: JSX.Element | null
onClickCondition?: (value: TValue) => boolean
onClick?: Dispatch<TValue>
} & ChipProps

function ChipList<TValue = string>({
values = [],
transformValue,
limit = 4,
emptyState,
onClickCondition,
onClick,
...props
}: ChipListProps<TValue>): ReactElement {
const [collapsed, setCollapsed] = useState(true)
Expand All @@ -37,14 +46,20 @@ function ChipList<TValue = string>({
) : (
<Span body2>There is nothing to display here.</Span>
))}
{values.slice(0, collapsed ? limit : undefined).map((v, i) => (
<Chip
key={(v as any).key || i}
{...props}
>
{transformValue ? transformValue(v) : `${v}`}
</Chip>
))}
{values.slice(0, collapsed ? limit : undefined).map((v, i) => {
const clickable = onClickCondition?.(v) ?? false

return (
<Chip
key={(v as any).key || i}
clickable={clickable}
onClick={() => clickable && onClick(v)}
{...props}
>
{transformValue ? transformValue(v) : `${v}`}
</Chip>
)
})}
{values.length > limit && (
<>
{collapsed && (
Expand Down
38 changes: 38 additions & 0 deletions src/stories/ChipList.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,35 @@ function TextTemplate({ onFillLevel, ...args }: any) {
)
}

function CustomClickTemplate({ onFillLevel, ...args }: any) {
const VALUES = [
'avengers',
'iron man',
'doctor strange',
'thor',
'black panther',
'guardians of the galaxy',
]

return (
<WrapWithIf
condition={onFillLevel > 0}
wrapper={
<Card
width="600px"
padding="medium"
fillLevel={onFillLevel}
/>
}
>
<ChipList
values={VALUES}
{...args}
/>
</WrapWithIf>
)
}

interface Label {
key?: string
value: string
Expand Down Expand Up @@ -142,3 +171,12 @@ Empty.args = {
size: 'small',
onFillLevel: 0,
}

export const CustomClick = CustomClickTemplate.bind({})
CustomClick.args = {
severity: 'info',
size: 'small',
onFillLevel: 0,
onClickCondition: (value: string) => value === 'avengers',
onClick: (value: string) => alert(value),
}

0 comments on commit 4c1cf7f

Please sign in to comment.