mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-07-24 17:36:47 +08:00
## Summary
Aligns the **Go agent runtime/canvas/components/tools** behavior with
the **Python `agent/` implementation** so the same stored canvas DSL
produces the same execution result on either side. Every component,
tool, and runtime primitive in `internal/agent/` is now driven by the
same semantics as its Python counterpart — variable resolution, template
substitution, control flow, error reporting, retry/cancel, and stream
event shapes.
The **retrieval component is the one explicit exception** in this PR. It
is being reworked in a separate change and is excluded from this
alignment pass; the wrapper slot (`universe_a_wrappers.go →
newRetrievalComponent`) is preserved.
## Scope of alignment
### Components (all aligned with `agent/component/`)
`Begin` · `Message` · `LLM` (incl. ChatTemplateKwargs,
MessageHistoryWindowSize, VisualFiles, Cite, OutputStructure,
JSONOutput, TopP, MaxRetries, DelayAfterError, credentials) · `Agent`
(react + tool artifact capture + `Reset()` interface-assert) · `Switch`
(12/12 operators, Python-equivalent semantics) · `Categorize` · `Invoke`
· `Iteration` · `Loop` (macro-expansion through `workflowx.AddLoopNode`)
· `UserFillUp` (Python-equivalent interrupt/resume via eino
`compose.Interrupt`/`ResumeWithData`) · `FillUp` · `DataOperations` ·
`ListOperations` · `StringTransform` · `VariableAggregator` ·
`VariableAssigner` · `Browser` (full stagehand runtime parity) ·
`DocsGenerator` · `ExcelProcessor`.
### Tools (all aligned with `agent/tools/`)
`Retrieval` (wrapper slot only — logic out of scope) · `MCPToolAdapter`
(streamable-HTTP) · `CodeExec` (sandbox bridge with
`code_exec_contract.go` matching Python contract) · `AkShare` · `ArXiv`
· `Crawler` · `DeepL` · `DuckDuckGo` · `Email` · `ExeSQL` · `GitHub` ·
`Google` · `GoogleScholar` · `Jin10` · `PubMed` · `QWeather` · `SearXNG`
· `Tavily` · `Tushare` · `Wencai` · `Wikipedia` · `YahooFinance` —
uniform `eino tool.InvokableTool` interface, SSRF protection, shared
HTTP client.
### Canvas execution engine (`internal/agent/canvas/`)
Aligned with Python's `agent/canvas.py`:
- **Scheduler** (`scheduler.go`): state pre/post handlers, node lambdas,
per-component timeout resolver (4-level: per-class env → per-class table
→ uniform env → 600s fallback), `legacyNoOpNames`.
- **Loop subgraph** (`loop_subgraph.go`): Python-equivalent
`AddLoopNode` macro expansion + condition translation.
- **Multibranch** (`multibranch.go`): `Switch` / `Categorize` routing
via `compose.NewGraphMultiBranch` — same branch selection semantics as
Python.
- **Parallel subgraph** (`parallel_subgraph.go`): matches Python's
parallel fan-out contract.
- **Interrupt/Resume** (`interrupt_resume.go`): `UserFillUpNodeBody` /
`IsInterruptError` / `ExtractInterruptContexts` — replaces the
deprecated Python sentinel chain with eino's native interrupt API,
preserving the same external behavior.
- **Checkpoint** (`checkpoint_store.go`): `RedisCheckPointStore`
Get/Set/Delete, with business metadata (status / canvas_id /
parent_run_id) on a parallel Redis Hash.
- **RunTracker** (`run_tracker.go`): Start / MarkSucceeded / MarkFailed
/ MarkCancelled / AttachCheckpoint — same lifecycle as the Python run
record.
- **Cancel** (`cancel.go`): Redis pub/sub watch.
- **Stream** (`stream.go`): SSE channel with `messages` / `waiting` /
`errors` / `done` events, same shape as Python's `agent.canvas.RunEvent`
payload.
### DSL bridge (`internal/agent/dsl/`)
- `normalize.go`: v1↔v2 collapsed into a single wire format — Python and
Go consume the same stored JSON.
- `reset.go`: per-run state reset matches Python's `Canvas.reset()`
semantics.
- Testdata mirrors Python's `agent_msg.json` / `all.json` / etc.
### Runtime (`internal/agent/runtime/`)
- `CanvasState` / `NewCanvasState` / `GetVar` / `SetVar` / `ReadVars`:
same `{{cpn_id@param}}` resolution model.
- `ResolveTemplate` (regex fast path + gonja fallback) — Python
Jinja-style semantics.
- `selector.go`, `metrics.go`, `component.go`: shared runtime contracts.
## Out of scope (intentionally)
- **`Retrieval` component logic** — wrapped only; full parity lands in a
follow-up PR.
- **Frontend** — only minor dsl-bridge / canvas UX fixes ride along.
- **CLI / admin / model registry** — orthogonal to agent behavior.
## How alignment is verified
`internal/service/agent_run_e2e_test.go` exercises the **full production
chain** against real Python-shaped DSL fixtures:
```
loadCanvasForUser → versionDAO.GetLatest → decodeCanvasFromDSL →
canvas.Compile → cc.Workflow.Invoke → answer extraction
```
using in-memory SQLite + miniredis (no Docker). Covers:
- `TestRunAgent_RealCanvas_BeginMessage` — happy path, `{{sys.query}}`
resolution
- `TestRunAgent_RealCanvas_WaitForUserResume` — two-run resume cycle
(Python-equivalent)
- `TestRunAgent_RealCanvas_CompileFails` — unknown component name →
sanitized error (Python-equivalent)
- `TestRunAgent_RealCanvas_InvokeFails` — unresolvable template ref
(Python-equivalent)
- `TestRunAgent_RunTracker_AttachCheckpoint_CallSequence` —
Start→AttachCheckpoint→MarkSucceeded lifecycle
`internal/handler/agent_test.go` — SSE streaming parity (`Content-Type:
text/event-stream`, `data: {…}\n\n`, trailing `data: [DONE]\n\n`,
OpenAI-compatible non-stream `choices`).
`internal/agent/canvas/fixture_compile_test.go` + per-component tests
pin the Python-equivalent outputs.
```
go test -count=1 -v -run 'TestRunAgent_RealCanvas|TestRunAgent_RunTracker' ./internal/service/
```
## Design reference
`docs/develop/agent-go-port-design.md` (1329 lines, last cross-checked
2026-06-17) — module layout, per-component / per-tool inventory,
corner-case catalogue, and the actionable backlog (Section 14, including
the retrieval alignment follow-up).
---------
Co-authored-by: Claude <noreply@anthropic.com>
597 lines
20 KiB
TypeScript
597 lines
20 KiB
TypeScript
import { Input } from '@/components/ui/input';
|
|
import { cn } from '@/lib/utils';
|
|
import { isEmpty } from 'lodash';
|
|
import { ChevronDown, X } from 'lucide-react';
|
|
import * as React from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { Popover, PopoverContent, PopoverTrigger } from './popover';
|
|
|
|
/**
|
|
* Extracts text content from a ReactNode for filtering purposes.
|
|
* Handles strings, numbers, JSX elements with nested text, and arrays.
|
|
*/
|
|
const getNodeText = (node: React.ReactNode): string => {
|
|
if (typeof node === 'string' || typeof node === 'number') {
|
|
return String(node);
|
|
}
|
|
if (React.isValidElement(node)) {
|
|
const children = (node.props as { children?: React.ReactNode }).children;
|
|
if (children) {
|
|
return getNodeText(children);
|
|
}
|
|
return '';
|
|
}
|
|
if (Array.isArray(node)) {
|
|
return node.map(getNodeText).join('');
|
|
}
|
|
return '';
|
|
};
|
|
|
|
/** Interface for tag select options */
|
|
export interface InputSelectOption {
|
|
/** Value of the option */
|
|
value: string;
|
|
/** Display label of the option */
|
|
label: string | React.ReactNode;
|
|
}
|
|
|
|
/** Properties for the InputSelect component */
|
|
export interface InputSelectProps {
|
|
/** Options for the select component */
|
|
options?: InputSelectOption[];
|
|
/** Selected values - type depends on the input type */
|
|
value?: string | string[] | number | number[] | Date | Date[];
|
|
/** Callback when value changes */
|
|
onChange?: (
|
|
value: string | string[] | number | number[] | Date | Date[],
|
|
) => void;
|
|
/** Placeholder text */
|
|
placeholder?: string;
|
|
/** Additional class names */
|
|
className?: string;
|
|
/** Style object */
|
|
style?: React.CSSProperties;
|
|
/** Whether to allow multiple selections */
|
|
multi?: boolean;
|
|
/** Type of input: text, number, date, or datetime */
|
|
type?: 'text' | 'number' | 'date' | 'datetime';
|
|
}
|
|
|
|
/** Internal display for single-select selected value. Click label to re-edit (string labels only). */
|
|
const SingleSelectDisplay: React.FC<{
|
|
value: string | number | Date;
|
|
options: InputSelectOption[];
|
|
type: 'text' | 'number' | 'date' | 'datetime';
|
|
onEdit: (editText: string) => void;
|
|
onRemove: () => void;
|
|
}> = ({ value, options, type, onEdit, onRemove }) => {
|
|
const selectedOption = options.find((opt) =>
|
|
type === 'number'
|
|
? Number(opt.value) === Number(value)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(opt.value).getTime() === new Date(value as any).getTime()
|
|
: String(opt.value) === String(value),
|
|
);
|
|
|
|
const label =
|
|
selectedOption?.label ??
|
|
(type === 'number'
|
|
? String(value)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(value as any).toLocaleString()
|
|
: String(value));
|
|
|
|
const canEdit = typeof label === 'string';
|
|
|
|
return (
|
|
<div className={cn('flex items-center max-w-full')}>
|
|
<div
|
|
className={cn(
|
|
'flex-1 truncate',
|
|
canEdit ? 'cursor-text' : 'cursor-default',
|
|
)}
|
|
onClick={(e) => {
|
|
if (!canEdit) return;
|
|
e.stopPropagation();
|
|
onEdit(getNodeText(label));
|
|
}}
|
|
>
|
|
{label}
|
|
</div>
|
|
<button
|
|
type="button"
|
|
className="ml-2 flex-[0_0_24px] text-text-secondary hover:text-text-primary focus:outline-none"
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
onRemove();
|
|
}}
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</button>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const InputSelect = React.forwardRef<HTMLInputElement, InputSelectProps>(
|
|
(
|
|
{
|
|
options = [],
|
|
value = [],
|
|
onChange,
|
|
placeholder = 'Select tags...',
|
|
className,
|
|
style,
|
|
multi = false,
|
|
type = 'text',
|
|
},
|
|
ref,
|
|
) => {
|
|
const [inputValue, setInputValue] = React.useState('');
|
|
const [open, setOpen] = React.useState(false);
|
|
const [isFocused, setIsFocused] = React.useState(false);
|
|
const inputRef = React.useRef<HTMLInputElement>(null);
|
|
const { t } = useTranslation();
|
|
|
|
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement, [
|
|
inputRef,
|
|
]);
|
|
|
|
// Normalize value to array for consistent handling based on type
|
|
const normalizedValue = React.useMemo(() => {
|
|
if (Array.isArray(value)) {
|
|
return value;
|
|
} else if (value !== undefined && value !== null) {
|
|
if (type === 'number') {
|
|
return typeof value === 'number' ? [value] : [Number(value)];
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
return value instanceof Date ? [value] : [new Date(value as any)];
|
|
} else {
|
|
return typeof value === 'string' ? [value] : [String(value)];
|
|
}
|
|
} else {
|
|
return [];
|
|
}
|
|
}, [value, type]);
|
|
|
|
/**
|
|
* Removes a tag from the selected values
|
|
* @param tagValue - The value of the tag to remove
|
|
*/
|
|
const handleRemoveTag = (tagValue: any) => {
|
|
let newValue: any[];
|
|
|
|
if (type === 'number') {
|
|
newValue = (normalizedValue as number[]).filter((v) => v !== tagValue);
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
newValue = (normalizedValue as Date[]).filter(
|
|
(v) => v.getTime() !== tagValue.getTime(),
|
|
);
|
|
} else {
|
|
newValue = (normalizedValue as string[]).filter((v) => v !== tagValue);
|
|
}
|
|
|
|
// Return single value if not multi-select, otherwise return array
|
|
let result: string | number | Date | string[] | number[] | Date[];
|
|
if (multi) {
|
|
result = newValue;
|
|
} else {
|
|
if (type === 'number') {
|
|
result = newValue[0] || 0;
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
result = newValue[0] || new Date();
|
|
} else {
|
|
result = newValue[0] || '';
|
|
}
|
|
}
|
|
|
|
onChange?.(result);
|
|
};
|
|
|
|
/**
|
|
* Adds a tag to the selected values
|
|
* @param optionValue - The value of the tag to add
|
|
*/
|
|
const handleAddTag = (optionValue: any) => {
|
|
let newValue: any[];
|
|
|
|
if (multi) {
|
|
// For multi-select, add to array if not already included
|
|
if (type === 'number') {
|
|
const numValue =
|
|
typeof optionValue === 'number' ? optionValue : Number(optionValue);
|
|
if (
|
|
!(normalizedValue as number[]).includes(numValue) &&
|
|
!isNaN(numValue)
|
|
) {
|
|
newValue = [...(normalizedValue as number[]), numValue];
|
|
onChange?.(newValue as number[]);
|
|
}
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
const dateValue =
|
|
optionValue instanceof Date ? optionValue : new Date(optionValue);
|
|
if (
|
|
!(normalizedValue as Date[]).some(
|
|
(d) => d.getTime() === dateValue.getTime(),
|
|
)
|
|
) {
|
|
newValue = [...(normalizedValue as Date[]), dateValue];
|
|
onChange?.(newValue as Date[]);
|
|
}
|
|
} else {
|
|
if (!(normalizedValue as string[]).includes(optionValue)) {
|
|
newValue = [...(normalizedValue as string[]), optionValue];
|
|
onChange?.(newValue as string[]);
|
|
}
|
|
}
|
|
} else {
|
|
// For single-select, replace the value
|
|
if (type === 'number') {
|
|
const numValue =
|
|
typeof optionValue === 'number' ? optionValue : Number(optionValue);
|
|
if (!isNaN(numValue)) {
|
|
onChange?.(numValue);
|
|
}
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
const dateValue =
|
|
optionValue instanceof Date ? optionValue : new Date(optionValue);
|
|
onChange?.(dateValue);
|
|
} else {
|
|
onChange?.(optionValue);
|
|
}
|
|
}
|
|
|
|
setInputValue('');
|
|
setOpen(false); // Close the popover after adding a tag
|
|
};
|
|
|
|
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const newValue = e.target.value;
|
|
setInputValue(newValue);
|
|
setOpen(!!newValue); // Open popover when there's input
|
|
};
|
|
|
|
/**
|
|
* Commits the current inputValue to the selected values, matching by label first,
|
|
* then falling back to the typed value. No-op when inputValue is empty/whitespace.
|
|
* Used by Enter key handler and blur handler.
|
|
*/
|
|
const commitInputValue = () => {
|
|
if (inputValue.trim() === '') return;
|
|
|
|
// Match by label text first
|
|
const matchedOption = options.find(
|
|
(opt) =>
|
|
getNodeText(opt.label).toLowerCase() === inputValue.toLowerCase(),
|
|
);
|
|
if (matchedOption) {
|
|
handleAddTag(matchedOption.value);
|
|
return;
|
|
}
|
|
|
|
// Otherwise, validate by type and add as a new value
|
|
let valueToAdd: any;
|
|
if (type === 'number') {
|
|
const numValue = Number(inputValue);
|
|
if (isNaN(numValue)) return;
|
|
valueToAdd = numValue;
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
const dateValue = new Date(inputValue);
|
|
if (isNaN(dateValue.getTime())) return;
|
|
valueToAdd = dateValue;
|
|
} else {
|
|
valueToAdd = inputValue;
|
|
}
|
|
|
|
// Skip if value is already selected
|
|
const isAlreadySelected = normalizedValue.some((v) =>
|
|
type === 'number'
|
|
? Number(v) === Number(valueToAdd)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(v as any).getTime() === valueToAdd.getTime()
|
|
: String(v) === valueToAdd,
|
|
);
|
|
if (!isAlreadySelected) {
|
|
handleAddTag(valueToAdd);
|
|
}
|
|
};
|
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
|
if (
|
|
e.key === 'Backspace' &&
|
|
inputValue === '' &&
|
|
normalizedValue.length > 0
|
|
) {
|
|
// Remove last tag when pressing backspace on empty input
|
|
const newValue = [...normalizedValue];
|
|
newValue.pop();
|
|
// Return single value if not multi-select, otherwise return array
|
|
let result: string | number | Date | string[] | number[] | Date[];
|
|
if (multi) {
|
|
if (type === 'number') {
|
|
result = newValue as number[];
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
result = newValue as Date[];
|
|
} else {
|
|
result = newValue as string[];
|
|
}
|
|
} else {
|
|
if (type === 'number') {
|
|
result = newValue[0] || 0;
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
result = newValue[0] || new Date();
|
|
} else {
|
|
result = newValue[0] || '';
|
|
}
|
|
}
|
|
|
|
onChange?.(result);
|
|
} else if (e.key === 'Enter' && inputValue.trim() !== '') {
|
|
e.preventDefault();
|
|
commitInputValue();
|
|
} else if (e.key === 'Escape') {
|
|
inputRef.current?.blur();
|
|
setOpen(false);
|
|
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
|
// Allow navigation in the dropdown
|
|
return;
|
|
}
|
|
};
|
|
|
|
const handleContainerClick = () => {
|
|
inputRef.current?.focus();
|
|
setOpen(true);
|
|
setIsFocused(true);
|
|
};
|
|
|
|
const handleInputFocus = () => {
|
|
setOpen(true);
|
|
setIsFocused(true);
|
|
};
|
|
|
|
const handleInputBlur = () => {
|
|
// Delay closing to allow click on options to register
|
|
setTimeout(() => {
|
|
commitInputValue();
|
|
setOpen(false);
|
|
setIsFocused(false);
|
|
}, 150);
|
|
};
|
|
|
|
// Filter options to exclude already selected ones (only for multi-select)
|
|
const availableOptions = multi
|
|
? options.filter(
|
|
(option) =>
|
|
!normalizedValue.some((v) =>
|
|
type === 'number'
|
|
? Number(v) === Number(option.value)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(v as any).getTime() ===
|
|
new Date(option.value).getTime()
|
|
: String(v) === option.value,
|
|
),
|
|
)
|
|
: options;
|
|
|
|
const filteredOptions = availableOptions.filter(
|
|
(option) =>
|
|
!inputValue ||
|
|
getNodeText(option.label)
|
|
.toLowerCase()
|
|
.includes(inputValue.toString().toLowerCase()),
|
|
);
|
|
|
|
// If there are no matching options but there is an input value, create a new option with the input value
|
|
const showInputAsOption = React.useMemo(() => {
|
|
if (!inputValue) return false;
|
|
|
|
const hasLabelMatch = options.some(
|
|
(option) =>
|
|
getNodeText(option.label).toLowerCase() ===
|
|
inputValue.toString().toLowerCase(),
|
|
);
|
|
|
|
let isAlreadySelected = false;
|
|
if (type === 'number') {
|
|
const numValue = Number(inputValue);
|
|
isAlreadySelected =
|
|
!isNaN(numValue) && (normalizedValue as number[]).includes(numValue);
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
const dateValue = new Date(inputValue);
|
|
isAlreadySelected =
|
|
!isNaN(dateValue.getTime()) &&
|
|
(normalizedValue as Date[]).some(
|
|
(d) => d.getTime() === dateValue.getTime(),
|
|
);
|
|
} else {
|
|
isAlreadySelected = (normalizedValue as string[]).includes(inputValue);
|
|
}
|
|
return (
|
|
!hasLabelMatch &&
|
|
!isAlreadySelected &&
|
|
inputValue.toString().trim() !== ''
|
|
);
|
|
}, [inputValue, options, normalizedValue, type]);
|
|
|
|
const triggerElement = (
|
|
<div
|
|
className={cn(
|
|
'flex items-center gap-1 w-full rounded-md border-0.5 border-border-button bg-bg-input px-3 py-1 min-h-8 cursor-text',
|
|
'outline-none transition-colors',
|
|
'focus-within:outline-none focus-within:ring-1 focus-within:ring-accent-primary',
|
|
className,
|
|
)}
|
|
style={style}
|
|
onClick={handleContainerClick}
|
|
>
|
|
{/* Wrapper for tags and input - this part wraps */}
|
|
<div className="flex flex-wrap items-center gap-1 flex-1 min-w-0">
|
|
{/* Render selected tags - only show tags if multi is true or if single select has a value */}
|
|
{multi &&
|
|
normalizedValue.map((tagValue, index) => {
|
|
const option = options.find((opt) =>
|
|
type === 'number'
|
|
? Number(opt.value) === Number(tagValue)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(opt.value).getTime() ===
|
|
new Date(tagValue).getTime()
|
|
: String(opt.value) === String(tagValue),
|
|
) || {
|
|
value: String(tagValue),
|
|
label: String(tagValue),
|
|
};
|
|
|
|
return (
|
|
<div
|
|
key={`${tagValue}-${index}`}
|
|
className="flex items-center bg-bg-card text-text-primary rounded px-2 py-1 text-xs mr-1 mb-1 border border-border-card truncate"
|
|
>
|
|
<div className="flex-1 truncate">{option.label}</div>
|
|
<button
|
|
type="button"
|
|
className="ml-1 text-text-secondary hover:text-text-primary focus:outline-none"
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
handleRemoveTag(tagValue);
|
|
}}
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</button>
|
|
</div>
|
|
);
|
|
})}
|
|
|
|
{/* For single select, show the selected value as text instead of a tag */}
|
|
{!multi && !isEmpty(normalizedValue[0]) && (
|
|
<SingleSelectDisplay
|
|
value={normalizedValue[0]}
|
|
options={options}
|
|
type={type}
|
|
onEdit={(editText) => {
|
|
handleRemoveTag(normalizedValue[0]);
|
|
setInputValue(editText);
|
|
setIsFocused(true);
|
|
setOpen(true);
|
|
requestAnimationFrame(() => {
|
|
const input = inputRef.current;
|
|
if (input) {
|
|
input.focus();
|
|
input.setSelectionRange(editText.length, editText.length);
|
|
}
|
|
});
|
|
}}
|
|
onRemove={() => handleRemoveTag(normalizedValue[0])}
|
|
/>
|
|
)}
|
|
|
|
{/* Input field for adding new tags - hide if single select and value is already selected, or in multi select when not focused */}
|
|
{(multi ? isFocused : multi || isEmpty(normalizedValue[0])) && (
|
|
<Input
|
|
ref={inputRef}
|
|
type={
|
|
type === 'date'
|
|
? 'date'
|
|
: type === 'datetime'
|
|
? 'datetime-local'
|
|
: type === 'number'
|
|
? 'number'
|
|
: 'text'
|
|
}
|
|
value={
|
|
type === 'number' && inputValue
|
|
? String(inputValue)
|
|
: type === 'date' || type === 'datetime'
|
|
? inputValue
|
|
: inputValue
|
|
}
|
|
onChange={handleInputChange}
|
|
onKeyDown={handleKeyDown}
|
|
placeholder={
|
|
(
|
|
multi
|
|
? normalizedValue.length === 0
|
|
: isEmpty(normalizedValue[0])
|
|
)
|
|
? placeholder
|
|
: ''
|
|
}
|
|
className="flex-grow min-w-[50px] border-none px-1 py-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 h-auto "
|
|
onClick={(e) => e.stopPropagation()}
|
|
onFocus={handleInputFocus}
|
|
onBlur={handleInputBlur}
|
|
/>
|
|
)}
|
|
</div>
|
|
<ChevronDown
|
|
className={cn(
|
|
'h-4 w-4 text-text-secondary shrink-0 transition-transform',
|
|
open && 'rotate-180',
|
|
)}
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<Popover open={open} onOpenChange={setOpen}>
|
|
<PopoverTrigger asChild>{triggerElement}</PopoverTrigger>
|
|
<PopoverContent
|
|
className="p-0 min-w-[var(--radix-popover-trigger-width)] max-w-[var(--radix-popover-trigger-width)] data-[state=open]:data-[side=top]:animate-slideDownAndFade data-[state=open]:data-[side=right]:animate-slideLeftAndFade data-[state=open]:data-[side=bottom]:animate-slideUpAndFade data-[state=open]:data-[side=left]:animate-slideRightAndFade"
|
|
align="start"
|
|
sideOffset={4}
|
|
collisionPadding={4}
|
|
onOpenAutoFocus={(e) => e.preventDefault()} // Prevent auto focus on content
|
|
>
|
|
<div className="max-h-60 overflow-auto">
|
|
{filteredOptions.length > 0 &&
|
|
filteredOptions.map((option) => (
|
|
<div
|
|
key={option.value}
|
|
className="px-4 py-2 hover:bg-border-button cursor-pointer text-text-secondary w-full truncate"
|
|
onClick={() => {
|
|
let optionValue: any;
|
|
if (type === 'number') {
|
|
optionValue = Number(option.value);
|
|
if (isNaN(optionValue)) return; // Skip invalid numbers
|
|
} else if (type === 'date' || type === 'datetime') {
|
|
optionValue = new Date(option.value);
|
|
if (isNaN(optionValue.getTime())) return; // Skip invalid dates
|
|
} else {
|
|
optionValue = option.value;
|
|
}
|
|
handleAddTag(optionValue);
|
|
}}
|
|
>
|
|
{option.label}
|
|
</div>
|
|
))}
|
|
{showInputAsOption && (
|
|
<div
|
|
key={inputValue}
|
|
className="px-4 py-2 hover:bg-border-button cursor-pointer text-text-secondary w-full truncate"
|
|
onClick={() =>
|
|
handleAddTag(
|
|
type === 'number'
|
|
? Number(inputValue)
|
|
: type === 'date' || type === 'datetime'
|
|
? new Date(inputValue)
|
|
: inputValue,
|
|
)
|
|
}
|
|
>
|
|
{t('common.add')} "{inputValue}"
|
|
</div>
|
|
)}
|
|
{filteredOptions.length === 0 && !showInputAsOption && (
|
|
<div className="px-4 py-2 text-text-secondary w-full truncate">
|
|
{t('common.noResults')}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</PopoverContent>
|
|
</Popover>
|
|
);
|
|
},
|
|
);
|
|
|
|
InputSelect.displayName = 'InputSelect';
|
|
|
|
export { InputSelect };
|