Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(web): keep the search input as the only tab stop and own Escape (#43861)

yyhd2842b020ef3
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index da81f8dc8a8..80eab1a9606 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -1360,19 +1360,6 @@
"count": 1
}
},
- "web/app/components/base/search-input/__tests__/index.spec.tsx": {
- "dify/require-disable-directive-description": {
- "count": 1
- }
- },
- "web/app/components/base/search-input/index.stories.tsx": {
- "jsx-a11y/label-has-associated-control": {
- "count": 3
- },
- "no-console": {
- "count": 3
- }
- },
"web/app/components/base/tag-input/index.stories.tsx": {
"jsx-a11y/label-has-associated-control": {
"count": 12
diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsx
index bfe69d670ec..d0f281bbe21 100644
--- a/web/app/components/apps/__tests__/list.spec.tsx
+++ b/web/app/components/apps/__tests__/list.spec.tsx
@@ -1071,11 +1071,10 @@ describe('List', () => {
describe('Search Functionality', () => {
it('should clear the keywords URL state', async () => {
+ const user = userEvent.setup()
const { onUrlUpdate } = renderList('?keywords=existing+search')
- const clearButton = document.querySelector('.i-ri-close-circle-fill')?.closest('button')
- expect(clearButton)!.toBeInTheDocument()
- if (clearButton) fireEvent.click(clearButton)
+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))
expect(screen.getByRole('searchbox')).toHaveValue('')
await waitFor(() => {
diff --git a/web/app/components/base/search-input/__tests__/index.spec.tsx b/web/app/components/base/search-input/__tests__/index.spec.tsx
index 1564f67d621..2032857227b 100644
--- a/web/app/components/base/search-input/__tests__/index.spec.tsx
+++ b/web/app/components/base/search-input/__tests__/index.spec.tsx
@@ -11,6 +11,7 @@ describe('SearchInput', () => {
expect(input).toBeInTheDocument()
expect(input).toHaveValue('')
expect(input).toHaveAttribute('name', 'query')
+ expect(input).toHaveAttribute('type', 'text')
expect(input).toHaveAttribute('autocomplete', 'off')
})
@@ -58,7 +59,7 @@ describe('SearchInput', () => {
})
it('focuses the searchbox when autoFocus is enabled', () => {
- // oxlint-disable-next-line jsx-a11y/no-autofocus
+ // oxlint-disable-next-line jsx-a11y/no-autofocus -- The case exercises the autoFocus prop itself.
render(<SearchInput value="" onValueChange={() => {}} autoFocus />)
expect(screen.getByRole('searchbox', { name: 'common.operation.search' })).toHaveFocus()
})
@@ -69,6 +70,7 @@ describe('SearchInput', () => {
const clearButton = screen.getByLabelText('common.operation.clear')
expect(clearButton).toBeInTheDocument()
+ expect(clearButton).toHaveAttribute('tabindex', '-1')
})
it('keeps a disabled searchbox inert and exposes its description', () => {
@@ -199,5 +201,89 @@ describe('SearchInput', () => {
expect(searchbox).toHaveValue('')
expect(searchbox).toHaveFocus()
})
+
+ it('keeps focus in the searchbox while the clear button is pressed', async () => {
+ const user = userEvent.setup()
+
+ function ControlledSearchInput() {
+ const [value, setValue] = useState('has value')
+
+ return <SearchInput value={value} onValueChange={setValue} />
+ }
+
+ render(<ControlledSearchInput />)
+ const searchbox = screen.getByRole('searchbox', { name: 'common.operation.search' })
+ const onBlur = vi.fn()
+ searchbox.addEventListener('blur', onBlur)
+ searchbox.focus()
+
+ await user.pointer({
+ keys: '[MouseLeft>]',
+ target: screen.getByLabelText('common.operation.clear'),
+ })
+ expect(searchbox).toHaveFocus()
+
+ await user.pointer({ keys: '[/MouseLeft]' })
+ expect(searchbox).toHaveValue('')
+ expect(searchbox).toHaveFocus()
+ expect(onBlur).not.toHaveBeenCalled()
+ })
+
+ it('clears on Escape and keeps the key from the owning dialog while it has a value', async () => {
+ const user = userEvent.setup()
+ // Base UI dismissal listens for Escape on the document, so a swallowed key never reaches it.
+ const onDocumentKeyDown = vi.fn()
+ document.addEventListener('keydown', onDocumentKeyDown)
+
+ function ControlledSearchInput() {
+ const [value, setValue] = useState('has value')
+
+ return <SearchInput value={value} onValueChange={setValue} />
+ }
+
+ try {
+ render(<ControlledSearchInput />)
+ const searchbox = screen.getByRole('searchbox', { name: 'common.operation.search' })
+ searchbox.focus()
+
+ await user.keyboard('{Escape}')
+
+ expect(searchbox).toHaveValue('')
+ expect(searchbox).toHaveFocus()
+ expect(onDocumentKeyDown).not.toHaveBeenCalled()
+ } finally {
+ document.removeEventListener('keydown', onDocumentKeyDown)
+ }
+ })
+
+ it('lets Escape reach the owning dialog when the searchbox is empty', async () => {
+ const user = userEvent.setup()
+ const onDocumentKeyDown = vi.fn()
+ document.addEventListener('keydown', onDocumentKeyDown)
+
+ try {
+ render(<SearchInput value="" onValueChange={() => {}} />)
+ screen.getByRole('searchbox', { name: 'common.operation.search' }).focus()
+
+ await user.keyboard('{Escape}')
+
+ expect(onDocumentKeyDown).toHaveBeenCalledOnce()
+ } finally {
+ document.removeEventListener('keydown', onDocumentKeyDown)
+ }
+ })
+
+ it('leaves Escape to the IME during composition', () => {
+ const onValueChange = vi.fn()
+ render(<SearchInput value="initial" onValueChange={onValueChange} />)
+ const input = screen.getByRole('searchbox', { name: 'common.operation.search' })
+
+ fireEvent.compositionStart(input)
+ fireEvent.change(input, { target: { value: 'final' } })
+ fireEvent.keyDown(input, { key: 'Escape' })
+
+ expect(input).toHaveValue('final')
+ expect(onValueChange).not.toHaveBeenCalled()
+ })
})
})
diff --git a/web/app/components/base/search-input/index.stories.tsx b/web/app/components/base/search-input/index.stories.tsx
deleted file mode 100644
index b07e37bcffc..00000000000
--- a/web/app/components/base/search-input/index.stories.tsx
+++ /dev/null
@@ -1,448 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import type { ComponentProps } from 'react'
-import { Kbd } from '@langgenius/dify-ui/kbd'
-import { useState } from 'react'
-import { SearchInput } from '.'
-
-const meta = {
- title: 'Base/Data Entry/SearchInput',
- component: SearchInput,
- parameters: {
- layout: 'centered',
- docs: {
- description: {
- component:
- 'Search input component with search icon, clear button, and IME composition support for Asian languages.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- value: {
- control: 'text',
- description: 'Search input value',
- },
- onValueChange: {
- action: 'value changed',
- description: 'Value change handler',
- },
- placeholder: {
- control: 'text',
- description: 'Placeholder text',
- },
- className: {
- control: 'text',
- description: 'Additional CSS classes',
- },
- },
- args: {
- onValueChange: (v: string) => {
- console.log('Search value changed:', v)
- },
- },
-} satisfies Meta<typeof SearchInput>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const SearchInputDemo = (args: ComponentProps<typeof SearchInput>) => {
- const [value, setValue] = useState(args.value || '')
-
- return (
- <div style={{ width: '400px' }}>
- <SearchInput
- {...args}
- value={value}
- onValueChange={(v: string) => {
- setValue(v)
- console.log('Search value changed:', v)
- }}
- />
- {value && (
- <div className="mt-3 text-sm text-gray-600">
- Searching for: <span className="font-semibold">{value}</span>
- </div>
- )}
- </div>
- )
-}
-
-// Default state
-export const Default: Story = {
- render: (args) => <SearchInputDemo {...args} />,
- args: {
- placeholder: 'Search...',
- value: '',
- onValueChange: (v: string) => {
- console.log('Search value changed:', v)
- },
- },
-}
-
-// With initial value
-export const WithInitialValue: Story = {
- render: (args) => <SearchInputDemo {...args} />,
- args: {
- value: 'Initial search query',
- placeholder: 'Search...',
- },
-}
-
-// Custom placeholder
-export const CustomPlaceholder: Story = {
- render: (args) => <SearchInputDemo {...args} />,
- args: {
- placeholder: 'Search documents, files, and more...',
- value: '',
- },
-}
-
-// Real-world example - User list search
-const UserListSearchDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
-
- const users = [
- { id: 1, name: 'Alice Johnson', email: '[email protected]', role: 'Admin' },
- { id: 2, name: 'Bob Smith', email: '[email protected]', role: 'User' },
- { id: 3, name: 'Charlie Brown', email: '[email protected]', role: 'User' },
- { id: 4, name: 'Diana Prince', email: '[email protected]', role: 'Editor' },
- { id: 5, name: 'Eve Davis', email: '[email protected]', role: 'User' },
- ]
-
- const filteredUsers = users.filter(
- (user) =>
- user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
- user.role.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
- <h3 className="mb-4 text-lg font-semibold">Team Members</h3>
- <SearchInput
- value={searchQuery}
- onValueChange={setSearchQuery}
- placeholder="Search by name, email, or role..."
- />
- <div className="mt-4 space-y-2">
- {filteredUsers.length > 0 ? (
- filteredUsers.map((user) => (
- <div key={user.id} className="rounded-lg border border-gray-200 p-3 hover:bg-gray-50">
- <div className="flex items-center justify-between">
- <div>
- <div className="text-sm font-medium">{user.name}</div>
- <div className="text-xs text-gray-500">{user.email}</div>
- </div>
- <span className="rounded-sm bg-blue-100 px-2 py-1 text-xs text-blue-700">
- {user.role}
- </span>
- </div>
- </div>
- ))
- ) : (
- <div className="py-8 text-center text-sm text-gray-500">
- No users found matching "{searchQuery}"
- </div>
- )}
- </div>
- <div className="mt-4 text-xs text-gray-500">
- Showing {filteredUsers.length} of {users.length} members
- </div>
- </div>
- )
-}
-
-export const UserListSearch: Story = {
- render: () => <UserListSearchDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Real-world example - Product search
-const ProductSearchDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
-
- const products = [
- { id: 1, name: 'Laptop Pro 15"', category: 'Electronics', price: 1299 },
- { id: 2, name: 'Wireless Mouse', category: 'Accessories', price: 29 },
- { id: 3, name: 'Mechanical Keyboard', category: 'Accessories', price: 89 },
- { id: 4, name: 'Monitor 27" 4K', category: 'Electronics', price: 499 },
- { id: 5, name: 'USB-C Hub', category: 'Accessories', price: 49 },
- { id: 6, name: 'Laptop Stand', category: 'Accessories', price: 39 },
- ]
-
- const filteredProducts = products.filter(
- (product) =>
- product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- product.category.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div style={{ width: '600px' }} className="rounded-lg border border-gray-200 bg-white p-6">
- <h3 className="mb-4 text-lg font-semibold">Product Catalog</h3>
- <SearchInput
- value={searchQuery}
- onValueChange={setSearchQuery}
- placeholder="Search products..."
- />
- <div className="mt-4 grid grid-cols-2 gap-3">
- {filteredProducts.length > 0 ? (
- filteredProducts.map((product) => (
- <div
- key={product.id}
- className="rounded-lg border border-gray-200 p-4 transition-shadow hover:shadow-md"
- >
- <div className="mb-1 text-sm font-medium">{product.name}</div>
- <div className="mb-2 text-xs text-gray-500">{product.category}</div>
- <div className="text-lg font-semibold text-blue-600">${product.price}</div>
- </div>
- ))
- ) : (
- <div className="col-span-2 py-8 text-center text-sm text-gray-500">No products found</div>
- )}
- </div>
- </div>
- )
-}
-
-export const ProductSearch: Story = {
- render: () => <ProductSearchDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Real-world example - Documentation search
-const DocumentationSearchDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
-
- const docs = [
- {
- id: 1,
- title: 'Getting Started',
- category: 'Introduction',
- excerpt: 'Learn the basics of our platform',
- },
- {
- id: 2,
- title: 'API Reference',
- category: 'Developers',
- excerpt: 'Complete API documentation and examples',
- },
- {
- id: 3,
- title: 'Authentication Guide',
- category: 'Security',
- excerpt: 'Set up OAuth and API key authentication',
- },
- {
- id: 4,
- title: 'Best Practices',
- category: 'Guides',
- excerpt: 'Tips for optimal performance and security',
- },
- {
- id: 5,
- title: 'Troubleshooting',
- category: 'Support',
- excerpt: 'Common issues and their solutions',
- },
- ]
-
- const filteredDocs = docs.filter(
- (doc) =>
- doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
- doc.category.toLowerCase().includes(searchQuery.toLowerCase()) ||
- doc.excerpt.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div style={{ width: '700px' }} className="rounded-lg bg-gray-50 p-6">
- <h3 className="mb-2 text-xl font-bold">Documentation</h3>
- <p className="mb-4 text-sm text-gray-600">
- Search our comprehensive guides and API references
- </p>
- <SearchInput
- value={searchQuery}
- onValueChange={setSearchQuery}
- placeholder="Search documentation..."
- />
- <div className="mt-4 space-y-3">
- {filteredDocs.length > 0 ? (
- filteredDocs.map((doc) => (
- <div
- key={doc.id}
- className="cursor-pointer rounded-lg border border-gray-200 bg-white p-4 transition-colors hover:border-blue-300"
- >
- <div className="mb-2 flex items-start justify-between">
- <h4 className="text-base font-semibold">{doc.title}</h4>
- <span className="rounded-sm bg-gray-100 px-2 py-1 text-xs text-gray-600">
- {doc.category}
- </span>
- </div>
- <p className="text-sm text-gray-600">{doc.excerpt}</p>
- </div>
- ))
- ) : (
- <div className="py-12 text-center">
- <div className="mb-2 text-4xl">🔍</div>
- <div className="text-sm text-gray-500">No documentation found for "{searchQuery}"</div>
- </div>
- )}
- </div>
- </div>
- )
-}
-
-export const DocumentationSearch: Story = {
- render: () => <DocumentationSearchDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Real-world example - Command palette
-const CommandPaletteDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
-
- const commands = [
- { id: 1, name: 'Create new document', icon: '📄', shortcut: '⌘N' },
- { id: 2, name: 'Open settings', icon: '⚙️', shortcut: '⌘,' },
- { id: 3, name: 'Search everywhere', icon: '🔍', shortcut: '⌘K' },
- { id: 4, name: 'Toggle sidebar', icon: '📁', shortcut: '⌘B' },
- { id: 5, name: 'Save changes', icon: '💾', shortcut: '⌘S' },
- { id: 6, name: 'Undo last action', icon: '↩️', shortcut: '⌘Z' },
- { id: 7, name: 'Redo last action', icon: '↪️', shortcut: '⌘⇧Z' },
- ]
-
- const filteredCommands = commands.filter((cmd) =>
- cmd.name.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div
- style={{ width: '600px' }}
- className="overflow-hidden rounded-lg border border-gray-300 bg-white shadow-lg"
- >
- <div className="border-b border-gray-200 p-4">
- <SearchInput
- value={searchQuery}
- onValueChange={setSearchQuery}
- placeholder="Type a command or search..."
- />
- </div>
- <div className="max-h-100 overflow-y-auto">
- {filteredCommands.length > 0 ? (
- filteredCommands.map((cmd) => (
- <div
- key={cmd.id}
- className="flex cursor-pointer items-center justify-between border-b border-gray-100 px-4 py-3 last:border-b-0 hover:bg-gray-100"
- >
- <div className="flex items-center gap-3">
- <span className="text-xl">{cmd.icon}</span>
- <span className="text-sm">{cmd.name}</span>
- </div>
- <Kbd>{cmd.shortcut}</Kbd>
- </div>
- ))
- ) : (
- <div className="py-8 text-center text-sm text-gray-500">No commands found</div>
- )}
- </div>
- </div>
- )
-}
-
-export const CommandPalette: Story = {
- render: () => <CommandPaletteDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Real-world example - Live search with results count
-const LiveSearchWithCountDemo = () => {
- const [searchQuery, setSearchQuery] = useState('')
-
- const items = [
- 'React Documentation',
- 'React Hooks',
- 'React Router',
- 'Redux Toolkit',
- 'TypeScript Guide',
- 'JavaScript Basics',
- 'CSS Grid Layout',
- 'Flexbox Tutorial',
- 'Node.js Express',
- 'MongoDB Guide',
- ]
-
- const filteredItems = items.filter((item) =>
- item.toLowerCase().includes(searchQuery.toLowerCase()),
- )
-
- return (
- <div style={{ width: '500px' }} className="rounded-lg border border-gray-200 bg-white p-6">
- <div className="mb-4 flex items-center justify-between">
- <h3 className="text-lg font-semibold">Learning Resources</h3>
- {searchQuery && (
- <span className="text-sm text-gray-500">
- {filteredItems.length} result
- {filteredItems.length !== 1 ? 's' : ''}
- </span>
- )}
- </div>
- <SearchInput
- value={searchQuery}
- onValueChange={setSearchQuery}
- placeholder="Search resources..."
- />
- <div className="mt-4 space-y-2">
- {filteredItems.map((item) => (
- <div
- key={item}
- className="cursor-pointer rounded-lg border border-gray-200 p-3 transition-colors hover:border-blue-300 hover:bg-blue-50"
- >
- <div className="text-sm font-medium">{item}</div>
- </div>
- ))}
- </div>
- </div>
- )
-}
-
-export const LiveSearchWithCount: Story = {
- render: () => <LiveSearchWithCountDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Size variations
-const SizeVariationsDemo = () => {
- const [value1, setValue1] = useState('')
- const [value2, setValue2] = useState('')
- const [value3, setValue3] = useState('')
-
- return (
- <div style={{ width: '500px' }} className="space-y-4">
- <div>
- <label className="mb-2 block text-xs font-medium text-gray-600">Default Size</label>
- <SearchInput value={value1} onValueChange={setValue1} placeholder="Search..." />
- </div>
- <div>
- <label className="mb-2 block text-xs font-medium text-gray-600">Medium Size</label>
- <SearchInput value={value2} onValueChange={setValue2} placeholder="Search..." />
- </div>
- <div>
- <label className="mb-2 block text-xs font-medium text-gray-600">Large Size</label>
- <SearchInput value={value3} onValueChange={setValue3} placeholder="Search..." />
- </div>
- </div>
- )
-}
-
-export const SizeVariations: Story = {
- render: () => <SizeVariationsDemo />,
- parameters: { controls: { disable: true } },
-} as unknown as Story
-
-// Interactive playground
-export const Playground: Story = {
- render: (args) => <SearchInputDemo {...args} />,
- args: {
- value: '',
- placeholder: 'Search...',
- },
-}
diff --git a/web/app/components/base/search-input/index.tsx b/web/app/components/base/search-input/index.tsx
index dc3e4e52c5e..73681a53b3f 100644
--- a/web/app/components/base/search-input/index.tsx
+++ b/web/app/components/base/search-input/index.tsx
@@ -1,10 +1,33 @@
import type { InputGroupInputProps } from '@langgenius/dify-ui/input-group'
-import type { Ref } from 'react'
+import type { ComponentProps, Ref } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { useTranslation } from 'react-i18next'
import { useSearchInput } from './use-search-input'
+type SearchInputClearProps = Pick<
+ ComponentProps<'button'>,
+ 'className' | 'onClick' | 'onMouseDown' | 'tabIndex'
+> & {
+ 'aria-label': string
+}
+
+// Same look as dify-ui `ComboboxClear` and `DropdownMenuClear`; change all three together.
+// Spread `clearProps` from `useSearchInput` so the button stays out of the tab order and never
+// takes focus from the input.
+export function SearchInputClear({ className, ...props }: SearchInputClearProps) {
+ return (
+ <IconButton
+ size="sm"
+ className={cn('hover:bg-components-input-bg-hover', className)}
+ {...props}
+ >
+ <span className="i-ri-close-line size-4" aria-hidden="true" />
+ </IconButton>
+ )
+}
+
type SearchInputProps = {
ref?: Ref<HTMLInputElement>
value: string
@@ -29,17 +52,15 @@ export function SearchInput({
'aria-label': ariaLabel,
}: SearchInputProps) {
const { t } = useTranslation(['common'])
- const { inputProps, clear } = useSearchInput({ value, onValueChange, ref })
+ const { inputProps, canClear, clearProps } = useSearchInput({ value, onValueChange, ref })
return (
<InputGroup className={className}>
<InputGroupInput
{...inputProps}
- type="search"
name={name}
aria-describedby={ariaDescribedBy}
aria-label={ariaLabel ?? t(($) => $['operation.search'], { ns: 'common' })}
- className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
placeholder={placeholder ?? t(($) => $['operation.search'], { ns: 'common' })}
disabled={disabled}
autoComplete="off"
@@ -53,16 +74,12 @@ export function SearchInput({
aria-hidden="true"
/>
</InputGroupAddon>
- {!!inputProps.value && !disabled && (
+ {canClear && !disabled && (
<InputGroupAddon align="inline-end" className="ps-0.75 pe-1.25">
- <IconButton
- size="sm"
+ <SearchInputClear
+ {...clearProps}
aria-label={t(($) => $['operation.clear'], { ns: 'common' })}
- className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"
- onClick={clear}
- >
- <span className="i-ri-close-circle-fill size-4" aria-hidden="true" />
- </IconButton>
+ />
</InputGroupAddon>
)}
</InputGroup>
diff --git a/web/app/components/base/search-input/use-search-input.ts b/web/app/components/base/search-input/use-search-input.ts
index 7732ddc537d..a7c89bc70c0 100644
--- a/web/app/components/base/search-input/use-search-input.ts
+++ b/web/app/components/base/search-input/use-search-input.ts
@@ -1,4 +1,4 @@
-import type { CompositionEvent, Ref } from 'react'
+import type { CompositionEvent, KeyboardEvent, MouseEvent, Ref } from 'react'
import { useMergedRefs } from '@langgenius/dify-ui/use-merged-refs'
import { useRef, useState } from 'react'
@@ -14,6 +14,7 @@ export function useSearchInput({ value, onValueChange, ref }: SearchInputOptions
const isComposingRef = useRef(false)
const compositionCommitRef = useRef<string | null>(null)
const [compositionValue, setCompositionValue] = useState<string | null>(null)
+ const displayValue = compositionValue ?? value
const clear = () => {
isComposingRef.current = false
@@ -25,9 +26,23 @@ export function useSearchInput({ value, onValueChange, ref }: SearchInputOptions
return {
clear,
+ canClear: displayValue !== '',
+ // The input is the only tab stop; the clear button is a pointer shortcut that never takes
+ // focus, matching Base UI's `Combobox.Clear`. Keyboard users clear with Escape.
+ clearProps: {
+ tabIndex: -1,
+ onMouseDown: (event: MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault()
+ },
+ onClick: clear,
+ },
inputProps: {
ref: mergedRef,
- value: compositionValue ?? value,
+ // A plain text input with the searchbox role: browsers attach private Escape and
+ // cancel-button behavior to `type="search"`, and this hook owns both instead.
+ type: 'text' as const,
+ role: 'searchbox',
+ value: displayValue,
onValueChange: (nextValue: string) => {
if (isComposingRef.current) {
setCompositionValue(nextValue)
@@ -40,6 +55,16 @@ export function useSearchInput({ value, onValueChange, ref }: SearchInputOptions
}
onValueChange(nextValue)
},
+ onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key !== 'Escape') return
+ // Escape ends the composition first; the IME owns that press.
+ if (isComposingRef.current || event.nativeEvent.isComposing) return
+ // An empty searchbox lets Escape reach the owning popover or dialog.
+ if (displayValue === '') return
+ event.preventDefault()
+ event.stopPropagation()
+ clear()
+ },
onCompositionStart: () => {
isComposingRef.current = true
compositionCommitRef.current = null
diff --git a/web/app/components/plugins/marketplace/search-input.tsx b/web/app/components/plugins/marketplace/search-input.tsx
index 6966fa30435..7ec40963317 100644
--- a/web/app/components/plugins/marketplace/search-input.tsx
+++ b/web/app/components/plugins/marketplace/search-input.tsx
@@ -1,11 +1,10 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { Separator } from '@langgenius/dify-ui/separator'
import { useTranslation } from '#i18n'
-import { SearchInput } from '@/app/components/base/search-input'
+import { SearchInput, SearchInputClear } from '@/app/components/base/search-input'
import { useSearchInput } from '@/app/components/base/search-input/use-search-input'
import { PluginTagsFilter } from '../plugin-tags-filter'
import { useSearchPluginText } from './atoms'
@@ -31,35 +30,29 @@ export function MarketplacePluginSearch() {
const { t } = useTranslation(['plugin'])
const [value, onValueChange] = useSearchPluginText()
const { tags, onTagsChange } = useMarketplaceTagsFilter()
- const { inputProps, clear } = useSearchInput({ value, onValueChange })
+ const { inputProps, canClear, clearProps } = useSearchInput({ value, onValueChange })
const label = t(($) => $.searchPlugins, { ns: 'plugin' })
return (
<InputGroup className="rounded-xl p-1.5 shadow-md [&>input]:py-1.5 [&>input]:body-md-medium">
<InputGroupInput
{...inputProps}
- type="search"
name="query"
autoComplete="off"
enterKeyHint="search"
aria-label={label}
placeholder={label}
- className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
/>
<InputGroupAddon className="ps-0 pe-2">
<PluginTagsFilter value={tags} onValueChange={onTagsChange} variant="labeled" />
<Separator decorative orientation="vertical" className="mx-1 h-3.5" />
</InputGroupAddon>
- {!!inputProps.value && (
+ {canClear && (
<InputGroupAddon align="inline-end" className="ps-2 pe-1">
- <IconButton
- size="sm"
+ <SearchInputClear
+ {...clearProps}
aria-label={t(($) => $.clearSearch, { ns: 'plugin', label })}
- className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"
- onClick={clear}
- >
- <span aria-hidden className="i-ri-close-circle-fill size-4" />
- </IconButton>
+ />
</InputGroupAddon>
)}
</InputGroup>
diff --git a/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx
index 3b2e0946d9e..44bde5394c0 100644
--- a/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx
@@ -19,16 +19,18 @@ function SearchHarness() {
}
describe('PluginSearchInput', () => {
- it('clears search from the keyboard without clearing tags, and restores input focus', async () => {
+ it('clears search with Escape without clearing tags, and keeps the clear button out of the tab order', async () => {
const user = userEvent.setup()
render(<SearchHarness />)
const input = screen.getByRole('searchbox', { name: 'Search plugins' })
await user.click(input)
await user.tab()
- expect(screen.getByRole('button', { name: /^plugin\.clearSearch/ })).toHaveFocus()
- await user.keyboard('{Enter}')
+ expect(screen.getByRole('button', { name: 'pluginTags.tags.rag' })).toHaveFocus()
+ await user.click(input)
+ await user.keyboard('{Escape}')
expect(input).toHaveValue('')
expect(input).toHaveFocus()
+ expect(screen.queryByRole('button', { name: /^plugin\.clearSearch/ })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'pluginTags.tags.rag' })).toBeInTheDocument()
})
diff --git a/web/app/components/plugins/plugin-search-input/index.tsx b/web/app/components/plugins/plugin-search-input/index.tsx
index ebe9cd6c0ab..a9589924c31 100644
--- a/web/app/components/plugins/plugin-search-input/index.tsx
+++ b/web/app/components/plugins/plugin-search-input/index.tsx
@@ -1,10 +1,10 @@
'use client'
import type { Ref } from 'react'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { Separator } from '@langgenius/dify-ui/separator'
import { useTranslation } from 'react-i18next'
+import { SearchInputClear } from '@/app/components/base/search-input'
import { useSearchInput } from '@/app/components/base/search-input/use-search-input'
import { PluginTagsFilter } from '../plugin-tags-filter'
@@ -30,13 +30,12 @@ export function PluginSearchInput({
autoFocus,
}: PluginSearchInputProps) {
const { t } = useTranslation(['plugin'])
- const { inputProps, clear } = useSearchInput({ value, onValueChange, ref })
+ const { inputProps, canClear, clearProps } = useSearchInput({ value, onValueChange, ref })
return (
<InputGroup className={className}>
<InputGroupInput
{...inputProps}
- type="search"
name="query"
autoComplete="off"
enterKeyHint="search"
@@ -44,7 +43,6 @@ export function PluginSearchInput({
placeholder={placeholder}
// oxlint-disable-next-line jsx-a11y/no-autofocus -- Picker owners request focus when replacing an already-focused menu.
autoFocus={autoFocus}
- className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"
/>
<InputGroupAddon className="ps-1.75 pe-1.25">
<span
@@ -53,15 +51,11 @@ export function PluginSearchInput({
/>
</InputGroupAddon>
<InputGroupAddon align="inline-end" className="gap-1 ps-0.75 pe-0.5">
- {!!inputProps.value && (
- <IconButton
- size="sm"
+ {canClear && (
+ <SearchInputClear
+ {...clearProps}
aria-label={t(($) => $.clearSearch, { ns: 'plugin', label: placeholder })}
- className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"
- onClick={clear}
- >
- <span aria-hidden className="i-ri-close-circle-fill size-4" />
- </IconButton>
+ />
)}
<Separator decorative orientation="vertical" className="mx-0 h-3.5" />
<PluginTagsFilter value={tags} onValueChange={onTagsChange} />