-
Notifications
You must be signed in to change notification settings - Fork 500
Expand file tree
/
Copy pathFilterConditionNode.tsx
More file actions
464 lines (421 loc) · 14.3 KB
/
FilterConditionNode.tsx
File metadata and controls
464 lines (421 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import React from "react";
import { ConditionExpression, FilterOperator } from "@helicone-package/filters/types";
import { useFilterAST } from "../context/filterContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ChevronDown, Trash2, Loader2 } from "lucide-react";
import SearchableSelect, {
SearchableSelectOption,
} from "./ui/SearchableSelect";
import SearchableInput, { SearchableInputOption } from "./ui/SearchableInput";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useFilterUIDefinitions } from "../filterUIDefinitions/useFilterUIDefinitions";
import clsx from "clsx";
import { Small } from "@/components/ui/typography";
import DateTimeInput from "./ui/DateTimeInput";
import { logger } from "@/lib/telemetry/logger";
// Define the FILTER_OPERATOR_LABELS mapping
const FILTER_OPERATOR_LABELS: Record<FilterOperator, string> = {
eq: "=",
neq: "≠",
is: "is",
gt: ">",
gte: "≥",
lt: "<",
lte: "≤",
like: "~",
ilike: "≈",
contains: "⊃",
"not-contains": "⊅",
in: "∈",
};
// Define descriptive operator labels for dropdown menu
const FILTER_OPERATOR_DESCRIPTIVE_LABELS: Record<FilterOperator, string> = {
eq: "Equals (=)",
neq: "Not Equals (≠)",
is: "Is",
gt: "Greater Than (>)",
gte: "Greater Than or Equal (≥)",
lt: "Less Than (<)",
lte: "Less Than or Equal (≤)",
like: "Like (~)",
ilike: "Case Insensitive Like (≈)",
contains: "Contains (⊃)",
"not-contains": "Not Contains (⊅)",
in: "In (∈)",
};
// Component for number input with suggestions
const NumberInput: React.FC<{
value: string | number;
onValueChange: (value: number) => void;
suggestions?: { label: string; value: number }[];
disabled?: boolean;
className?: string;
}> = ({
value,
onValueChange,
suggestions = [],
disabled = false,
className = "",
}) => {
const [open, setOpen] = React.useState(false);
const [inputValue, setInputValue] = React.useState(value.toString());
const containerRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
setInputValue(value.toString());
}, [value]);
// Handle direct input changes
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInputValue(newValue);
// For empty input, use 0
if (newValue === "") {
onValueChange(0);
return;
}
const numericValue = Number(newValue);
if (!isNaN(numericValue) && newValue !== "" && !newValue.endsWith('.')) {
onValueChange(numericValue);
}
};
// Handle clicking outside to close dropdown
React.useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
// Convert suggestions to SearchableSelectOption format
const selectOptions: SearchableSelectOption[] = suggestions.map((opt) => ({
label: opt.label,
value: String(opt.value),
}));
const toggleDropdown = () => {
if (!disabled && selectOptions.length > 0) {
setOpen(!open);
}
};
return (
<div className="relative w-full" ref={containerRef}>
<div className="flex">
<Input
type="text"
value={inputValue}
onChange={handleInputChange}
disabled={disabled}
className={`h-7 w-full text-[10px] ${className}`}
/>
{selectOptions.length > 0 && (
<ChevronDown
className={clsx(
"absolute right-2 top-1/2 -translate-y-1/2 cursor-pointer transition-transform",
open && "rotate-180",
)}
size={10}
onClick={toggleDropdown}
/>
)}
</div>
{open && selectOptions.length > 0 && (
<div className="absolute left-0 top-8 z-10 max-h-[200px] w-full overflow-y-auto border border-border bg-white shadow-md dark:bg-slate-950">
{selectOptions.map((option) => (
<div
key={option.value}
className="cursor-pointer px-2 py-1.5 text-[10px] hover:bg-slate-100 dark:hover:bg-slate-800"
onClick={() => {
onValueChange(Number(option.value));
setOpen(false);
}}
>
{option.label}
</div>
))}
</div>
)}
</div>
);
};
interface FilterConditionNodeProps {
condition: ConditionExpression;
path: number[];
isFirst?: boolean;
isLast?: boolean;
}
export const FilterConditionNode: React.FC<FilterConditionNodeProps> = ({
condition,
path,
isFirst = false,
isLast = false,
}) => {
const { store: filterStore } = useFilterAST();
const { filterDefinitions: filterDefs, isLoading } = useFilterUIDefinitions();
// Handle changing a field in a condition
const handleFieldChange = (fieldId: string) => {
// Find the filter definition for this field
const filterDef = filterDefs.find((def) => def.id === fieldId);
if (!filterDef) return;
// Create updated field with default operator
const defaultOperator = filterDef.operators[0] || "eq";
const defaultValue = (() => {
switch (filterDef.type) {
case "number":
return 0;
case "boolean":
return true;
default:
return "";
}
})();
// Create updated condition with new field and default operator
const needsKey = filterDef.subType === "property" || filterDef.subType === "score";
const updated: ConditionExpression = {
...condition,
field: {
column: (filterDef.column ?? fieldId) as any,
subtype: filterDef.subType,
table: filterDef.table,
...(needsKey && { key: fieldId, valueMode: "value" as const }),
},
operator: defaultOperator,
value: defaultValue,
};
filterStore.updateFilterExpression(path, updated);
};
// Handle changing the operator in a condition
const handleOperatorChange = (operator: string) => {
const updated = { ...condition, operator: operator as FilterOperator };
filterStore.updateFilterExpression(path, updated);
};
// Handle changing the value in a condition
const handleValueChange = (value: string | number | boolean) => {
const updated = { ...condition, value };
filterStore.updateFilterExpression(path, updated);
};
// Handle removing the condition
const handleRemove = () => {
const parentPath = filterStore.getParentPath(path);
const parentExpression = filterStore.getFilterExpression(parentPath);
if (parentExpression?.type == "and" || parentExpression?.type == "or") {
if (parentExpression.expressions.length === 1) {
return filterStore.removeFilterExpression(parentPath);
}
}
filterStore.removeFilterExpression(path);
};
// Find the filter definition - use key for properties/scores, column otherwise
const filterDefId = condition.field.key || condition.field.column;
const filterDef = filterDefs.find((def) => def.id === filterDefId);
// Get available operators
const operators = filterDef?.operators || [];
// ValueOptions for select-type fields
const valueOptions = filterDef?.valueOptions || [];
// Convert filterDefs to SearchableSelectOption format
const fieldOptions: SearchableSelectOption[] = filterDefs.map((def) => ({
label: def.label,
value: def.id,
subType: def.subType,
}));
// Convert operators to SearchableSelectOption format
const operatorOptions: SearchableSelectOption[] = operators.map((op) => ({
label: FILTER_OPERATOR_DESCRIPTIVE_LABELS[op],
value: op,
}));
// Convert valueOptions to SearchableSelectOption format if needed
const selectValueOptions: SearchableSelectOption[] = valueOptions.map(
(opt) => ({
label: opt.label,
value: String(opt.value),
}),
);
// Handle search function for searchable fields
const handleSearch = async (
searchTerm: string,
): Promise<SearchableInputOption[]> => {
if (!filterDef?.onSearch) return [];
try {
const results = await filterDef.onSearch(searchTerm);
return results.map((result) => ({
label: result.label,
value: String(result.value),
}));
} catch (error) {
logger.error({ error }, "Error searching");
return [];
}
};
if (isLoading) {
return (
<div className="flex items-center gap-2 rounded-md border border-border bg-accent p-2">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
<Small className="text-muted-foreground">
Loading filter options...
</Small>
</div>
);
}
if (!filterDef) {
return (
<div className="flex items-center justify-between border border-amber-300 bg-amber-50 p-2 dark:border-amber-800 dark:bg-amber-950">
<div className="flex flex-col">
<span className="text-xs font-medium text-amber-800 dark:text-amber-300">
Invalid field: "{condition.field.column || "empty"}"
</span>
<span className="text-[10px] text-amber-600 dark:text-amber-400">
Please select a valid field or remove
</span>
</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={handleRemove}
className="h-6 w-6 border text-amber-700 hover:bg-amber-100 dark:text-amber-300 dark:hover:bg-amber-900"
>
<Trash2 size={12} />
</Button>
</div>
);
}
// Render value input based on field type
const renderValueInput = () => {
// For number fields with valueOptions
if (filterDef?.type === "number") {
// Convert value to number for NumberInput
let numValue: number = 0;
if (typeof condition.value === "boolean") {
numValue = condition.value ? 1 : 0;
} else if (typeof condition.value === "string") {
// For strings, parse as float (handles both integers and decimals)
numValue = parseFloat(condition.value) || 0;
} else if (typeof condition.value === "number") {
numValue = condition.value;
}
return (
<NumberInput
value={numValue}
onValueChange={(val) => handleValueChange(val)}
suggestions={valueOptions as { label: string; value: number }[]}
disabled={!condition.field.column || !condition.operator}
className="w-full rounded-none border-none focus:outline-none focus-visible:ring-0 focus-visible:ring-offset-0"
/>
);
}
if (filterDef?.type === "datetime") {
return (
<DateTimeInput
value={String(condition.value)}
onValueChange={handleValueChange}
/>
);
}
// For searchable fields with onSearch function
if (filterDef?.type === "searchable" && filterDef.onSearch) {
return (
<SearchableInput
value={String(condition.value)}
onValueChange={handleValueChange}
onSearch={handleSearch}
placeholder="Type to search..."
emptyMessage="No results found"
disabled={!condition.field.column || !condition.operator}
className="h-7 w-full rounded-none border-none focus:outline-none focus-visible:ring-0 focus-visible:ring-offset-0"
/>
);
}
// For select-type fields with valueOptions
if (filterDef?.type === "select" || valueOptions.length > 0) {
return (
<SearchableSelect
options={selectValueOptions}
value={String(condition.value)}
onValueChange={handleValueChange}
placeholder="Select value"
searchPlaceholder="Search value..."
emptyMessage="No value found."
disabled={!condition.field.column || !condition.operator}
className="h-7 w-full rounded-none text-[10px] focus-visible:ring-0 focus-visible:ring-offset-0"
/>
);
}
// Default: regular input
return (
<Input
value={String(condition.value)}
onChange={(e) => handleValueChange(e.target.value)}
disabled={!condition.field.column || !condition.operator}
placeholder="Enter value"
className="h-7 w-full rounded-none text-[10px] focus-visible:ring-0 focus-visible:ring-offset-0"
/>
);
};
return (
<div
className={clsx(
"flex flex-row items-center border bg-slate-100 dark:bg-slate-950",
isFirst && "rounded-t-md",
isLast && "rounded-b-md",
)}
>
<SearchableSelect
options={fieldOptions}
value={filterDefId}
onValueChange={handleFieldChange}
placeholder="Select field"
searchPlaceholder="Search field..."
emptyMessage="No field found."
width="200px"
className={clsx(
"h-7 flex-shrink-0 rounded-none border-none bg-transparent text-[10px] focus-visible:ring-0 focus-visible:ring-offset-0",
)}
/>
<Select
value={condition.operator}
onValueChange={handleOperatorChange}
disabled={!condition.field.column}
>
<SelectTrigger className="h-7 w-[40px] flex-shrink-0 rounded-none rounded-l-none border-none bg-transparent px-1 text-center text-[10px] font-normal focus-visible:ring-0 focus-visible:ring-offset-0">
<SelectValue placeholder="Op">
{condition.operator &&
FILTER_OPERATOR_LABELS[condition.operator as FilterOperator]}
</SelectValue>
</SelectTrigger>
<SelectContent className="focus-visible:ring-0 focus-visible:ring-offset-0">
{operatorOptions.map((op) => (
<SelectItem
key={op.value}
value={op.value}
className="text-[10px] font-normal focus-visible:ring-0 focus-visible:ring-offset-0"
>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="flex-grow">{renderValueInput()}</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={handleRemove}
className="h-6 flex-shrink-0 border-none px-1"
>
<Trash2 size={12} className="" />
</Button>
</div>
);
};
export default FilterConditionNode;