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

select-item-form-field-v2 #312

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import IconClose from '@aboutbits/react-material-icons/dist/IconClose'
import IconKeyboardArrowDown from '@aboutbits/react-material-icons/dist/IconKeyboardArrowDown'
import classNames from 'classnames'
import { ReactNode, useMemo, useRef } from 'react'
import { useInternationalization, useTheme } from '../../../framework'
import { FormTone, FormVariant, InputLabel, InputMessage } from '../../form'
import { useInputCss } from '../../form/primitive/useThemedCss'
import { Mode, RequiredProps, HideRequiredProps } from '../../types'
import { useId } from '../../util'
import { useFieldError } from '../util/useFieldError'
import { replacePlaceholderColorWithTextColor } from './replacePlaceholderColorWithTextColor'

export type SelectItemFormFieldInputV2Props<Item> = {
name: string
label: string
placeholder: string
selectedItem: Item | null | undefined
renderItem: (item: Item) => ReactNode
onOpenSelect: () => void
onClear: () => void
disabled?: boolean
hasError?: boolean
mode?: Mode
variant?: FormVariant
className?: string
} & RequiredProps &
HideRequiredProps

export function SelectItemFormFieldInputV2<Item>({
name,
label,
placeholder,
selectedItem,
renderItem,
onOpenSelect,
onClear,
disabled = false,
hasError,
mode = Mode.Light,
variant = FormVariant.Ghost,
className,
required,
hideRequired,
}: SelectItemFormFieldInputV2Props<Item>) {
const id = useId()
const componentRef = useRef<HTMLDivElement | null>(null)

const error = useFieldError(name)

const inputCss = useInputCss({
mode,
variant,
tone: error ? FormTone.Critical : FormTone.Neutral,
disabled,
withIconStart: false,
withIconEnd: false,
})

const customCssEmptyInput = useMemo(
() => replacePlaceholderColorWithTextColor(inputCss),
[inputCss],
)
const { messages } = useInternationalization()
const { form } = useTheme()

return (
<div ref={componentRef} className={className}>
<InputLabel
htmlFor={id}
showRequired={required && !hideRequired}
disabled={disabled}
>
{label}
</InputLabel>
{selectedItem === null || selectedItem === undefined ? (
<button
disabled={disabled}
type="button"
id={id}
onClick={() => {
onOpenSelect()
}}
className={classNames(
customCssEmptyInput,
form.selectItem.input.container.base,
hasError
? form.selectItem.input.container.error
: form.selectItem.input.container.normal,
)}
>
<span className={form.selectItem.input.placeholder.base}>
{placeholder}
</span>
<span className={form.selectItem.input.iconContainer.base}>
<IconKeyboardArrowDown
className={classNames(
form.selectItem.input.icon.base,
disabled && form.selectItem.input.icon.disabled,
)}
/>
</span>
</button>
) : (
<div
className={classNames(
inputCss,
form.selectItem.input.container.base,
hasError
? form.selectItem.input.container.error
: form.selectItem.input.container.normal,
)}
>
<button
disabled={disabled}
type="button"
id={id}
onClick={() => {
onOpenSelect()
}}
className={form.selectItem.input.selectButton.base}
>
<span>{renderItem(selectedItem)}</span>
</button>
<button
disabled={disabled}
type="button"
onClick={() => {
onClear()
}}
className={classNames(
form.selectItem.input.iconContainer.base,
hasError
? form.selectItem.input.iconContainer.error
: form.selectItem.input.iconContainer.normal,
)}
>
<IconClose
className={classNames(
form.selectItem.input.icon.base,
disabled && form.selectItem.input.icon.disabled,
)}
title={messages['select.clear']}
/>
</button>
</div>
)}
{Boolean(error) && (
<InputMessage
mode={mode}
tone={FormTone.Critical}
disabled={disabled}
message={error?.message}
/>
)}
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import { IndexType } from '@aboutbits/pagination'
import { zodResolver } from '@hookform/resolvers/zod'
import { action } from '@storybook/addon-actions'
import {
Controls,
Primary,
Stories,
Subheading,
Title,
} from '@storybook/addon-docs'
import { Description } from '@storybook/blocks'
import { Meta, StoryObj } from '@storybook/react'
import { useState, useEffect, ComponentProps } from 'react'
import { DefaultValues, useForm } from 'react-hook-form'
import { z } from 'zod'
import {
InternationalizationMessages,
Theme,
} from '../../../../.storybook/components'
import { ErrorBody } from '../../util'
import { Form } from '../Form'
import {
SearchQueryParameters,
PaginatedResponse,
SelectItemFormFieldV2,
} from '.'

const userSchema = z.object({
id: z.number(),
name: z.string(),
})

type User = z.infer<typeof userSchema>

type StoryProps = ComponentProps<
typeof SelectItemFormFieldV2<User, ErrorBody>
> & {
initialItem?: User
}

const meta = {
title: 'components/react-hook-form/SelectItemFormFieldV2',
component: SelectItemFormFieldV2,
args: {
name: 'user',
label: 'Select user',
placeholder: 'User',
dialogTitle: 'Users',
dialogLabel: 'Users',
noSearchResults: 'No users available.',
renderListItem: (item) => item.name,
renderErrorMessage: (error) => error.message,
paginationConfig: { indexType: IndexType.ZERO_BASED },
dialogProps: { overlayClassName: 'z-10' },
},
argTypes: {
disabled: { type: 'boolean' },
},
decorators: [
(Story, context) => {
const personSchema = z.object({
user: userSchema,
})
type Person = z.infer<typeof personSchema>
const defaultPerson: DefaultValues<Person> = {
user: context.args.initialItem,
}
const form = useForm({
resolver: zodResolver(personSchema),
defaultValues: defaultPerson,
})
return (
<Form form={form} onSubmit={action('onSubmit')}>
<Story />
</Form>
)
},
],
parameters: {
docs: {
page: () => (
<>
<Title />
<Description />
<Primary />
<Subheading>Props</Subheading>
<Controls />
<Theme component="form" items={['selectItem']} />
<InternationalizationMessages
items={[
'select.clear',
'select.search.empty',
'search.placeholder',
]}
/>
<Stories />
</>
),
},
},
} satisfies Meta<StoryProps>

export default meta
type Story = StoryObj<StoryProps>

const useGetDataSuccess = ({
search,
page,
size,
}: SearchQueryParameters): {
data?: PaginatedResponse<User>
error?: Error
} => {
const [data, setData] = useState<User[] | undefined>()

useEffect(() => {
setData(undefined)
const id = setTimeout(() => {
setData(
Array.from(Array(200).keys())
.map((index): User => {
return {
id: index,
name: `User ${index.toString()}`,
}
})
.filter((user) => {
if (search !== undefined) {
return user.name.includes(search)
} else {
return true
}
}),
)
}, 1000)
return () => {
clearTimeout(id)
}
}, [search, page, size])

if (data === undefined) {
return {}
} else {
return {
data: {
items: data.slice(page * size, page * size + size),
currentPage: page,
perPage: size,
total: data.length,
},
}
}
}

const useGetDataError = (): {
data?: PaginatedResponse<User>
error?: Error
} => {
return {
error: new Error('Something went wrong'),
}
}

const useGetDataEmpty = ({
size,
}: SearchQueryParameters): {
data?: PaginatedResponse<User>
error?: Error
} => {
return {
data: {
items: [],
currentPage: 0,
perPage: size,
total: 0,
},
}
}

export const Default: Story = {
args: { useGetData: useGetDataSuccess },
}

export const WithInitialItem: Story = {
args: {
useGetData: useGetDataSuccess,
initialItem: { id: 3, name: 'User 3' },
},
}

export const WithError: Story = {
args: { useGetData: useGetDataError },
}

export const WithEmptyList: Story = {
args: { useGetData: useGetDataEmpty },
}
Loading