Skip to content
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
6 changes: 6 additions & 0 deletions .changeset/ten-snails-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@example/ui-playground": patch
"@genseki/react": patch
---

fix: combobox state management
142 changes: 111 additions & 31 deletions examples/ui-playground/src/app/playground/shadcn/combobox-section.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react'
import React, { useState } from 'react'

import { CheckIcon, UserIcon } from '@phosphor-icons/react'

Expand Down Expand Up @@ -57,27 +57,67 @@ const languages = [
]

function BasicComboboxMultiple() {
const [items, setItems] = useState(frameworks)

return (
<ComboboxProvider items={frameworks} multipleItems={true}>
<ComboboxTriggerMultiValue className="w-[200px]" />
<ComboboxContent>
<ComboboxCommandInput />
<ComboboxCommandEmpty>No framework found.</ComboboxCommandEmpty>
<ComboboxCommandList>
<ComboboxCommandGroup>
{({ items }) => {
return items.map((framework) => (
<ComboboxCommandItem
key={framework.value}
value={framework.value}
label={framework.label}
/>
))
}}
</ComboboxCommandGroup>
</ComboboxCommandList>
</ComboboxContent>
</ComboboxProvider>
<div>
<button
className="px-8 py-4 bg-blue-500 text-white rounded-md mb-4 cursor-pointer"
onClick={() => {
setItems((prev) => {
// Generate a random alphabet letter for value and label
const alphabet = 'abcdefghijklmnopqrstuvwxyz'
const randomChar = alphabet[Math.floor(Math.random() * alphabet.length)]
return [
...prev,
{
value: randomChar + Math.floor(Math.random() * 100),
label: randomChar.toUpperCase(),
},
]
})
}}
>
append item
</button>
<button
className="px-8 py-4 bg-red-500 text-white rounded-md mb-4 cursor-pointer ml-4"
onClick={() => {
setItems([
{
value: 'next.js',
label: 'Next.js',
},
{
value: 'sveltekit',
label: 'SvelteKit',
},
])
}}
>
Reset items
</button>
<ComboboxProvider items={items} multipleItems={true}>
<ComboboxTriggerMultiValue className="w-[200px]" />
<ComboboxContent>
<ComboboxCommandInput />
<ComboboxCommandEmpty>No framework found.</ComboboxCommandEmpty>
<ComboboxCommandList>
<ComboboxCommandGroup>
{({ items }) => {
return items.map((framework) => (
<ComboboxCommandItem
key={framework.value}
value={framework.value}
label={framework.label}
/>
))
}}
</ComboboxCommandGroup>
</ComboboxCommandList>
</ComboboxContent>
</ComboboxProvider>
</div>
)
}

Expand Down Expand Up @@ -108,16 +148,56 @@ function BasicComboboxSingle() {

// Controlled Combobox Example
function ControlledComboboxMultiple() {
const [items, setItems] = useState(frameworks)
const [value, setValue] = React.useState<string[]>([])
const [open, setOpen] = React.useState(false)

console.log('value:', value)
console.log('items:', items)

return (
<div className="space-y-4">
<button
className="px-8 py-4 bg-blue-500 text-white rounded-md mb-4 cursor-pointer"
onClick={() => {
setItems((prev) => {
// Generate a random alphabet letter for value and label
const alphabet = 'abcdefghijklmnopqrstuvwxyz'
const randomChar = alphabet[Math.floor(Math.random() * alphabet.length)]
return [
...prev,
{
value: randomChar + Math.floor(Math.random() * 100),
label: randomChar.toUpperCase(),
},
]
})
}}
>
append item
</button>
<button
className="px-8 py-4 bg-red-500 text-white rounded-md mb-4 cursor-pointer ml-4"
onClick={() => {
setItems([
{
value: 'next.js',
label: 'Next.js',
},
{
value: 'sveltekit',
label: 'SvelteKit',
},
])
}}
>
Reset items
</button>
<ComboboxProvider
items={languages}
items={items}
open={open}
onOpenChange={setOpen}
value={value ?? undefined}
value={value}
onValueChange={setValue}
multipleItems
>
Expand All @@ -143,14 +223,14 @@ function ControlledComboboxMultiple() {

<div className="flex gap-2 items-center">
<Typography type="caption" className="text-muted-foreground">
Selected: {value.join(', ') || 'None'}
Selected: {JSON.stringify(value)}
</Typography>
<div className="inline-flex gap-x-4">
<Button size="sm" variant="outline" onClick={() => setValue([''])}>
<Button size="sm" variant="outline" onClick={() => setValue([])}>
Clear
</Button>
<Button size="sm" variant="outline" onClick={() => setValue(['typescript'])}>
TypeScript
<Button size="sm" variant="outline" onClick={() => setValue(['sveltekit'])}>
Svelete Kit
</Button>
</div>
</div>
Expand Down Expand Up @@ -194,10 +274,10 @@ function ControlledComboboxSingle() {

<div className="flex gap-2 items-center">
<Typography type="caption" className="text-muted-foreground">
Selected: {value.join(', ') || 'None'}
{JSON.stringify(value)}
</Typography>
<div className="inline-flex gap-x-4">
<Button size="sm" variant="outline" onClick={() => setValue([''])}>
<Button size="sm" variant="outline" onClick={() => setValue([])}>
Clear
</Button>
<Button size="sm" variant="outline" onClick={() => setValue(['typescript'])}>
Expand Down Expand Up @@ -258,10 +338,10 @@ function ControlledInputGroupComboboxSingle() {
</div>
<div className="flex gap-2 items-center">
<Typography type="caption" className="text-muted-foreground">
Selected: {value.join(', ') || 'None'}
{JSON.stringify(value)}
</Typography>
<div className="inline-flex gap-x-4">
<Button size="sm" variant="outline" onClick={() => setValue([''])}>
<Button size="sm" variant="outline" onClick={() => setValue([])}>
Clear
</Button>
<Button size="sm" variant="outline" onClick={() => setValue(['typescript'])}>
Expand Down
25 changes: 16 additions & 9 deletions packages/react/v2/components/primitives/combobox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use client'
import React from 'react'
import React, { useEffect } from 'react'

import { CaretUpDownIcon, CheckIcon, XIcon } from '@phosphor-icons/react'
import { useControllableState } from '@radix-ui/react-use-controllable-state'
Expand Down Expand Up @@ -35,7 +35,6 @@ interface ComboboxContextValue {
value: string[]
onValueChange: React.Dispatch<React.SetStateAction<string[]>>
items: Item[]
setItems: React.Dispatch<React.SetStateAction<Item[]>>
multipleItems?: boolean
}

Expand All @@ -52,16 +51,25 @@ interface ComboboxProviderProps {
multipleItems?: boolean
}

function ComboboxProvider(props: ComboboxProviderProps) {
const [items, setItems] = React.useState<Item[]>(props.items ?? [])
const ComboboxProvider = React.memo((props: ComboboxProviderProps) => {
const filterValueAppearInItems = (value: string[]) => {
return value?.filter((v) => props.items.some((item) => item.value === v)) || []
}

// typing value
const [value, setValue] = useControllableState<string[]>({
defaultProp: [''],
onChange: props.onValueChange,
defaultProp: [],
onChange: (value) => {
props.onValueChange?.(filterValueAppearInItems(value))
},
prop: props.value,
})

useEffect(() => {
// Sync if value is not under items
setValue(filterValueAppearInItems(value))
}, [props.items])

// popover state
const [open, setOpen] = useControllableState({
defaultProp: false,
Expand All @@ -75,14 +83,13 @@ function ComboboxProvider(props: ComboboxProviderProps) {
onValueChange={setValue}
open={open}
onOpenChange={setOpen}
items={items}
setItems={setItems}
items={props.items}
multipleItems={props.multipleItems ?? false}
>
<_ComboboxPopoverProvider>{props.children}</_ComboboxPopoverProvider>
</_ComboboxProvider>
)
}
})

function _ComboboxPopoverProvider(props: { children?: React.ReactNode }) {
const ctx = useCombobox()
Expand Down
Loading