All files / components/records FilterBuilderPanel.tsx

64.28% Statements 72/112
61.9% Branches 52/84
61.53% Functions 24/39
70.96% Lines 66/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492                                                                                          4x                 4x                     4x         4x             4x           2x       2x                                       4x                     1x       1x 1x   1x 1x   1x 1x   1x   1x                           1x 1x 1x           1x 1x           14x 14x 14x 14x 14x                         2x       2x                           2x                       2x                     2x                     2x                         4x   1x                   186x 186x   186x   186x   186x     186x           186x 1x 1x   1x 1x 1x     186x 1x 1x 1x     186x 8x   7x   8x     186x   186x                                                                                             8x 2x 2x   2x                                                 4x                   10x                                       12x                                                                                                                                     7x                 1x                        
/**
 * Filter Builder Panel
 * Collapsible panel for building advanced filter expressions on collection records
 */
 
import { useState, useCallback } from 'react';
import { Filter, Plus, X, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import type { FieldDefinition } from '@/services/collections.service';
 
// ── Types ────────────────────────────────────────────────────────────────────
 
type Operator = '=' | '!=' | '>' | '>=' | '<' | '<=' | '~' | '!~' | 'null' | '!null';
 
export interface FilterRow {
    id: string;
    field: string;
    operator: Operator;
    value: string;
}
 
export interface FilterBuilderPanelProps {
    schema: FieldDefinition[];
    appliedRows: FilterRow[];
    onApply: (filterExpression: string, rows: FilterRow[]) => void;
    onClear: () => void;
    onRemovePill: (id: string) => void;
}
 
// ── Operator definitions ──────────────────────────────────────────────────────
 
interface OperatorDef {
    value: Operator;
    label: string;
}
 
const TEXT_OPERATORS: OperatorDef[] = [
    { value: '=', label: 'equals' },
    { value: '!=', label: 'not equals' },
    { value: '~', label: 'contains' },
    { value: '!~', label: 'not contains' },
    { value: 'null', label: 'is empty' },
    { value: '!null', label: 'is not empty' },
];
 
const NUMBER_OPERATORS: OperatorDef[] = [
    { value: '=', label: 'equals' },
    { value: '!=', label: 'not equals' },
    { value: '>', label: 'greater than' },
    { value: '>=', label: 'greater than or equal' },
    { value: '<', label: 'less than' },
    { value: '<=', label: 'less than or equal' },
    { value: 'null', label: 'is empty' },
    { value: '!null', label: 'is not empty' },
];
 
const BOOLEAN_OPERATORS: OperatorDef[] = [
    { value: '=', label: 'equals' },
    { value: '!=', label: 'not equals' },
];
 
const REFERENCE_OPERATORS: OperatorDef[] = [
    { value: '=', label: 'equals' },
    { value: '!=', label: 'not equals' },
    { value: 'null', label: 'is empty' },
    { value: '!null', label: 'is not empty' },
];
 
const NULL_ONLY_OPERATORS: OperatorDef[] = [
    { value: 'null', label: 'is empty' },
    { value: '!null', label: 'is not empty' },
];
 
function getOperatorsForType(fieldType: string): OperatorDef[] {
    switch (fieldType) {
        case 'text':
        case 'email':
        case 'url':
            return TEXT_OPERATORS;
        case 'number':
            return NUMBER_OPERATORS;
        case 'boolean':
            return BOOLEAN_OPERATORS;
        case 'date':
        case 'datetime':
            return NUMBER_OPERATORS; // same comparisons as number
        case 'reference':
            return REFERENCE_OPERATORS;
        case 'file':
        case 'json':
            return NULL_ONLY_OPERATORS;
        default:
            return TEXT_OPERATORS;
    }
}
 
// ── System fields always available for filtering ──────────────────────────────
 
const SYSTEM_FIELDS: FieldDefinition[] = [
    { name: 'id', type: 'text' },
    { name: 'created_at', type: 'datetime' },
    { name: 'updated_at', type: 'datetime' },
    { name: 'created_by', type: 'text' },
    { name: 'updated_by', type: 'text' },
];
 
// ── Filter expression compiler ────────────────────────────────────────────────
 
function escapeValue(value: string): string {
    return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
 
function compileRow(row: FilterRow, allFields: FieldDefinition[]): string | null {
    const { field, operator, value } = row;
    Iif (!field || !operator) return null;
 
    const fieldDef = allFields.find((f) => f.name === field);
    const fieldType = fieldDef?.type ?? 'text';
 
    Iif (operator === 'null') return `${field} IS NULL`;
    Iif (operator === '!null') return `${field} IS NOT NULL`;
 
    Iif (!value.trim()) return null;
 
    switch (fieldType) {
        case 'number':
            return `${field} ${operator} ${value}`;
        case 'boolean':
            return `${field} ${operator} ${value.toLowerCase()}`;
        case 'date':
        case 'datetime': {
            const escaped = escapeValue(value);
            return `${field} ${operator} "${escaped}"`;
        }
        case 'text':
        case 'email':
        case 'url':
        default: {
            Iif (operator === '~') return `${field} ~ "%${escapeValue(value)}%"`;
            Iif (operator === '!~') return `${field} !~ "%${escapeValue(value)}%"`;
            return `${field} ${operator} "${escapeValue(value)}"`;
        }
    }
}
 
export function compileFilterExpression(rows: FilterRow[], allFields: FieldDefinition[]): string {
    const parts = rows.map((r) => compileRow(r, allFields)).filter(Boolean) as string[];
    return parts.join(' && ');
}
 
// ── Pill label builder ────────────────────────────────────────────────────────
 
function pillLabel(row: FilterRow): string {
    Iif (row.operator === 'null') return `${row.field} is empty`;
    Iif (row.operator === '!null') return `${row.field} is not empty`;
    Iif (row.operator === '~') return `${row.field} contains "${row.value}"`;
    Iif (row.operator === '!~') return `${row.field} not contains "${row.value}"`;
    return `${row.field} ${row.operator} "${row.value}"`;
}
 
// ── Value input by field type ─────────────────────────────────────────────────
 
interface ValueInputProps {
    fieldType: string;
    operator: Operator;
    value: string;
    onChange: (v: string) => void;
}
 
function ValueInput({ fieldType, operator, value, onChange }: ValueInputProps) {
    Iif (operator === 'null' || operator === '!null') {
        return <div className="flex-1 h-9" />; // spacer
    }
 
    Iif (fieldType === 'boolean') {
        return (
            <Select value={value} onValueChange={onChange}>
                <SelectTrigger className="flex-1 h-9">
                    <SelectValue placeholder="Select value" />
                </SelectTrigger>
                <SelectContent>
                    <SelectItem value="true">true</SelectItem>
                    <SelectItem value="false">false</SelectItem>
                </SelectContent>
            </Select>
        );
    }
 
    Iif (fieldType === 'number') {
        return (
            <Input
                type="number"
                className="flex-1 h-9"
                placeholder="Value"
                value={value}
                onChange={(e) => onChange(e.target.value)}
            />
        );
    }
 
    Iif (fieldType === 'date') {
        return (
            <Input
                type="date"
                className="flex-1 h-9"
                value={value}
                onChange={(e) => onChange(e.target.value)}
            />
        );
    }
 
    Iif (fieldType === 'datetime') {
        return (
            <Input
                type="datetime-local"
                className="flex-1 h-9"
                value={value}
                onChange={(e) => onChange(e.target.value)}
            />
        );
    }
 
    return (
        <Input
            type="text"
            className="flex-1 h-9"
            placeholder="Value"
            value={value}
            onChange={(e) => onChange(e.target.value)}
        />
    );
}
 
// ── Main component ────────────────────────────────────────────────────────────
 
let rowCounter = 0;
function newRow(): FilterRow {
    return { id: `row-${++rowCounter}`, field: '', operator: '=', value: '' };
}
 
export default function FilterBuilderPanel({
    schema,
    appliedRows,
    onApply,
    onClear,
    onRemovePill,
}: FilterBuilderPanelProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [draftRows, setDraftRows] = useState<FilterRow[]>([]);
 
    const allFields = [...schema, ...SYSTEM_FIELDS];
 
    const addRow = () => setDraftRows((prev) => [...prev, newRow()]);
 
    const removeRow = (id: string) =>
        setDraftRows((prev) => prev.filter((r) => r.id !== id));
 
    const updateRow = useCallback((id: string, patch: Partial<FilterRow>) => {
        setDraftRows((prev) =>
            prev.map((r) => (r.id === id ? { ...r, ...patch } : r)),
        );
    }, []);
 
    const handleApply = () => {
        const validRows = draftRows.filter(
            (r) => r.field && (r.operator === 'null' || r.operator === '!null' || r.value.trim()),
        );
        const expression = compileFilterExpression(validRows, allFields);
        onApply(expression, validRows);
        setIsOpen(false);
    };
 
    const handleClear = () => {
        setDraftRows([]);
        onClear();
        setIsOpen(false);
    };
 
    const handleToggle = () => {
        if (!isOpen) {
            // Pre-populate draft with applied rows on open
            setDraftRows(appliedRows.length ? [...appliedRows] : []);
        }
        setIsOpen((v) => !v);
    };
 
    const activeCount = appliedRows.length;
 
    return (
        <div className="space-y-2">
            {/* Toggle Button */}
            <div className="flex items-center gap-2">
                <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleToggle}
                    className="gap-2"
                >
                    <Filter className="h-4 w-4" />
                    Filters
                    {activeCount > 0 && (
                        <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-xs">
                            {activeCount}
                        </Badge>
                    )}
                    {isOpen ? (
                        <ChevronUp className="h-3 w-3 ml-1" />
                    ) : (
                        <ChevronDown className="h-3 w-3 ml-1" />
                    )}
                </Button>
                {activeCount > 0 && !isOpen && (
                    <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="text-muted-foreground h-8 px-2 text-xs"
                        onClick={handleClear}
                    >
                        Clear all
                    </Button>
                )}
            </div>
 
            {/* Collapsible Panel */}
            {isOpen && (
                <div className="border rounded-lg p-4 space-y-3 bg-muted/20">
                    {draftRows.length === 0 && (
                        <p className="text-sm text-muted-foreground">
                            No filters added. Click "Add Filter" to start filtering records.
                        </p>
                    )}
 
                    {draftRows.map((row) => {
                        const fieldDef = allFields.find((f) => f.name === row.field);
                        const fieldType = fieldDef?.type ?? 'text';
                        const operators = getOperatorsForType(fieldType);
 
                        return (
                            <div key={row.id} className="flex items-center gap-2">
                                {/* Field selector */}
                                <Select
                                    value={row.field}
                                    onValueChange={(v) =>
                                        updateRow(row.id, {
                                            field: v,
                                            operator: getOperatorsForType(
                                                allFields.find((f) => f.name === v)?.type ?? 'text',
                                            )[0].value,
                                            value: '',
                                        })
                                    }
                                >
                                    <SelectTrigger className="w-40 h-9">
                                        <SelectValue placeholder="Field" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {schema.length > 0 && (
                                            <>
                                                <div className="px-2 py-1 text-xs font-medium text-muted-foreground uppercase tracking-wide">
                                                    Fields
                                                </div>
                                                {schema.map((f) => (
                                                    <SelectItem key={f.name} value={f.name}>
                                                        {f.name}
                                                    </SelectItem>
                                                ))}
                                                <div className="px-2 py-1 text-xs font-medium text-muted-foreground uppercase tracking-wide mt-1">
                                                    System
                                                </div>
                                            </>
                                        )}
                                        {SYSTEM_FIELDS.map((f) => (
                                            <SelectItem key={f.name} value={f.name}>
                                                {f.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
 
                                {/* Operator selector */}
                                <Select
                                    value={row.operator}
                                    onValueChange={(v) =>
                                        updateRow(row.id, { operator: v as Operator, value: '' })
                                    }
                                    disabled={!row.field}
                                >
                                    <SelectTrigger className="w-44 h-9">
                                        <SelectValue placeholder="Operator" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {operators.map((op) => (
                                            <SelectItem key={op.value} value={op.value}>
                                                {op.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
 
                                {/* Value input */}
                                <ValueInput
                                    fieldType={fieldType}
                                    operator={row.operator}
                                    value={row.value}
                                    onChange={(v) => updateRow(row.id, { value: v })}
                                />
 
                                {/* Remove button */}
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-9 w-9 shrink-0 text-muted-foreground hover:text-destructive"
                                    onClick={() => removeRow(row.id)}
                                >
                                    <X className="h-4 w-4" />
                                </Button>
                            </div>
                        );
                    })}
 
                    {/* Actions */}
                    <div className="flex items-center gap-2 pt-1">
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={addRow}
                            className="gap-1"
                        >
                            <Plus className="h-3 w-3" />
                            Add Filter
                        </Button>
                        <div className="flex-1" />
                        <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={handleClear}
                            className="text-muted-foreground"
                        >
                            Clear All
                        </Button>
                        <Button
                            type="button"
                            size="sm"
                            onClick={handleApply}
                            disabled={draftRows.length === 0}
                        >
                            Apply Filters
                        </Button>
                    </div>
                </div>
            )}
 
            {/* Filter Pills */}
            {appliedRows.length > 0 && (
                <div className="flex flex-wrap gap-1.5">
                    {appliedRows.map((row) => (
                        <Badge
                            key={row.id}
                            variant="secondary"
                            className="gap-1 pr-1 font-normal text-xs"
                        >
                            <span>{pillLabel(row)}</span>
                            <button
                                type="button"
                                className="ml-0.5 rounded-sm hover:bg-muted-foreground/20 p-0.5"
                                onClick={() => onRemovePill(row.id)}
                                aria-label={`Remove filter: ${pillLabel(row)}`}
                            >
                                <X className="h-3 w-3" />
                            </button>
                        </Badge>
                    ))}
                </div>
            )}
        </div>
    );
}