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

feat(item): Added ability to disable Command.Item from filtering #257

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
29 changes: 19 additions & 10 deletions cmdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ type ItemProps = Children &
keywords?: string[]
/** Whether this item is forcibly rendered regardless of filtering. */
forceMount?: boolean
/**
* Optionally set to `false` to turn off the automatic filtering and sorting for this item.
*/
shouldFilter?: boolean
}
type GroupProps = Children &
Omit<DivProps, 'heading' | 'value'> & {
Expand Down Expand Up @@ -117,7 +121,7 @@ type CommandProps = Children &
}

type Context = {
value: (id: string, value: string, keywords?: string[]) => void
value: (id: string, value: string, shouldFilter: boolean, keywords?: string[]) => void
item: (id: string, groupId: string) => () => void
group: (id: string) => () => void
filter: () => boolean
Expand Down Expand Up @@ -191,7 +195,7 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
}))
const allItems = useLazyRef<Set<string>>(() => new Set()) // [...itemIds]
const allGroups = useLazyRef<Map<string, Set<string>>>(() => new Map()) // groupId → [...itemIds]
const ids = useLazyRef<Map<string, { value: string; keywords?: string[] }>>(() => new Map()) // id → { value, keywords }
const ids = useLazyRef<Map<string, { value: string; shouldFilter: boolean; keywords?: string[] }>>(() => new Map()) // id → { value, shouldFilter, keywords }
const listeners = useLazyRef<Set<() => void>>(() => new Set()) // [...rerenders]
const propsRef = useAsRef(props)
const {
Expand Down Expand Up @@ -272,10 +276,10 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
const context: Context = React.useMemo(
() => ({
// Keep id → {value, keywords} mapping up-to-date
value: (id, value, keywords) => {
value: (id, value, shouldFilter, keywords) => {
if (value !== ids.current.get(id)?.value) {
ids.current.set(id, { value, keywords })
state.current.filtered.items.set(id, score(value, keywords))
ids.current.set(id, { value, shouldFilter, keywords })
state.current.filtered.items.set(id, score(value, shouldFilter, keywords))
schedule(2, () => {
sort()
store.emit()
Expand Down Expand Up @@ -351,7 +355,9 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
[],
)

function score(value: string, keywords?: string[]) {
function score(value: string, shouldFilter: boolean, keywords?: string[]): number {
if (!shouldFilter) return 1

const filter = propsRef.current?.filter ?? defaultFilter
return value ? filter(value, state.current.search, keywords) : 0
}
Expand Down Expand Up @@ -443,7 +449,9 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
for (const id of allItems.current) {
const value = ids.current.get(id)?.value ?? ''
const keywords = ids.current.get(id)?.keywords ?? []
const rank = score(value, keywords)
const shouldFilter = ids.current.get(id)?.shouldFilter ?? true

const rank = score(value, shouldFilter, keywords)
state.current.filtered.items.set(id, rank)
if (rank > 0) itemCount++
}
Expand Down Expand Up @@ -665,7 +673,7 @@ const Item = React.forwardRef<HTMLDivElement, ItemProps>((props, forwardedRef) =
}
}, [forceMount])

const value = useValue(id, ref, [props.value, props.children, ref], props.keywords)
const value = useValue(id, ref, [props.value, props.children, ref], props.keywords, props.shouldFilter ?? true)

const store = useStore()
const selected = useCmdk((state) => state.value && state.value === value.current)
Expand All @@ -691,7 +699,7 @@ const Item = React.forwardRef<HTMLDivElement, ItemProps>((props, forwardedRef) =

if (!render) return null

const { disabled, value: _, onSelect: __, forceMount: ___, keywords: ____, ...etc } = props
const { disabled, value: _, onSelect: __, forceMount: ___, keywords: ____, shouldFilter: _____, ...etc } = props

return (
<Primitive.div
Expand Down Expand Up @@ -1021,6 +1029,7 @@ function useValue(
ref: React.RefObject<HTMLElement>,
deps: (string | React.ReactNode | React.RefObject<HTMLElement>)[],
aliases: string[] = [],
shouldFilter: boolean = true,
) {
const valueRef = React.useRef<string>()
const context = useCommand()
Expand All @@ -1043,7 +1052,7 @@ function useValue(

const keywords = aliases.map((alias) => alias.trim())

context.value(id, value, keywords)
context.value(id, value, shouldFilter, keywords)
ref.current?.setAttribute(VALUE_ATTR, value)
valueRef.current = value
})
Expand Down
12 changes: 12 additions & 0 deletions test/item.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,15 @@ test.describe('item advanced', async () => {
await expect(page.locator(`[cmdk-item]`)).toHaveCount(2)
})
})

test.describe('item shouldFilter false', async () => {
test.beforeEach(async ({ page }) => {
await page.goto('/item-no-filter')
})

test('items with shouldFilter set to false still show when filtering', async ({ page }) => {
await expect(page.locator(`[cmdk-item]`)).toHaveCount(3)
await page.locator(`[cmdk-input]`).type('A')
await expect(page.locator(`[cmdk-item]`)).toHaveCount(2)
})
})
20 changes: 20 additions & 0 deletions test/pages/item-no-filter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Command } from 'cmdk'
import * as React from 'react'

const Page = () => {
return (
<div>
<Command>
<Command.Input placeholder="Search…" />
<Command.List>
<Command.Empty>No results.</Command.Empty>
<Command.Item>Item A</Command.Item>
<Command.Item>Item B</Command.Item>
<Command.Item shouldFilter={false}>Item C</Command.Item>
</Command.List>
</Command>
</div>
)
}

export default Page