All files / src/components SearchPanel.tsx

94.64% Statements 159/168
91.34% Branches 95/104
96.61% Functions 57/59
96.55% Lines 140/145

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 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511                                                          365x 365x   365x 365x     591x                 4x   4x                                           45x       28x 28x 8x 8x   28x                     288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x 288x     288x 288x 49x     288x 288x   288x   28x             28x 28x 28x 28x           27x 27x 27x 27x     1x 1x 1x 1x   28x         288x   28x 28x           288x 49x 1x 1x       288x 2x 2x 2x             1x 1x     1x   2x       288x 49x 49x       288x   124x 124x 124x         288x   9x 9x 9x 9x 1x     9x 9x 9x           288x   1x 1x 1x 1x 1x           288x 3x 3x 3x   3x 1x   3x 3x 3x 3x       288x 78x     288x 76x       288x 73x 24x       288x   170x 1x 1x 1x   169x 3x 3x 3x   166x 1x 1x 1x   165x 1x 1x           288x 864x   288x                 124x                                       864x     9x                         4x   29x                                   3x                 1x                                   31x             1x                     1x 1x 1x 1x 1x                                                             8x                                               327x     646x       7x   8x                                                                                            
import DOMPurify from "dompurify";
import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
import { api, type SearchResult } from "../api";
import { extractSearchTerms } from "../utils";
import {
	CalendarIcon,
	FilterIcon,
	MailOpenIcon,
	PaperclipIcon,
	SearchIcon,
	StarIcon,
	XIcon,
} from "./Icons";
import { toast } from "./Toast";
 
interface SearchPanelProps {
	onClose: () => void;
	onSelectMessage: (id: number) => void;
	inboundConnectorId: number | null;
	onResultsChange?: (results: SearchResult[]) => void;
	onQueryChange?: (query: string) => void;
	initialQuery?: string;
}
 
/**
 * Highlight search terms in a plain text string, returning a React node.
 * Strips search operators (from:, to:, etc.) before matching.
 */
export function highlightText(text: string, query: string): ReactNode {
	const terms = extractSearchTerms(query);
	Iif (terms.length === 0) return text;
 
	const regex = new RegExp(`(${terms.join("|")})`, "gi");
	const parts = text.split(regex);
 
	// biome-ignore lint/suspicious/noArrayIndexKey: index is stable; parts are positional split segments
	return <>{parts.map((part, i) => (i % 2 === 1 ? <mark key={`h-${i}`}>{part}</mark> : part))}</>;
}
 
interface ActiveFilter {
	type: string;
	value: string;
	label: string;
}
 
const SEARCH_PAGE_SIZE = 30;
 
const QUICK_FILTERS: { type: string; value: string; label: string; icon: React.ReactNode }[] = [
	{
		type: "is",
		value: "unread",
		label: "Unread",
		icon: <MailOpenIcon className="w-3.5 h-3.5" />,
	},
	{
		type: "is",
		value: "starred",
		label: "Starred",
		icon: <StarIcon className="w-3.5 h-3.5" />,
	},
	{
		type: "has",
		value: "attachment",
		label: "Has attachment",
		icon: <PaperclipIcon className="w-3.5 h-3.5" />,
	},
];
 
function filterKey(f: ActiveFilter): string {
	return `${f.type}:${f.value}`;
}
 
function buildQueryWithFilters(text: string, filters: ActiveFilter[]): string {
	const parts = [text.trim()];
	for (const f of filters) {
		const val = f.value.includes(" ") ? `"${f.value}"` : f.value;
		parts.push(`${f.type}:${val}`);
	}
	return parts.filter(Boolean).join(" ");
}
 
export function SearchPanel({
	onClose,
	onSelectMessage,
	inboundConnectorId,
	onResultsChange,
	onQueryChange,
	initialQuery = "",
}: SearchPanelProps) {
	const [query, setQuery] = useState(initialQuery);
	const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([]);
	const [results, setResults] = useState<SearchResult[]>([]);
	const [activeQuery, setActiveQuery] = useState(initialQuery);
	const [loading, setLoading] = useState(false);
	const [loadingMore, setLoadingMore] = useState(false);
	const [searched, setSearched] = useState(false);
	const [hasMore, setHasMore] = useState(false);
	const [focusedIndex, setFocusedIndex] = useState(-1);
	const [showDateFilter, setShowDateFilter] = useState(false);
	const [dateAfter, setDateAfter] = useState("");
	const [dateBefore, setDateBefore] = useState("");
	const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);
	const resultRefs = useRef<(HTMLButtonElement | null)[]>([]);
	const lastQueryRef = useRef("");
 
	// Focus the search input when panel mounts
	const inputRef = useRef<HTMLInputElement>(null);
	useEffect(() => {
		requestAnimationFrame(() => inputRef.current?.focus());
	}, []);
 
	const initialQueryRef = useRef(initialQuery);
	const initialQueryFiredRef = useRef(false);
 
	const doSearch = useCallback(
		(fullQuery: string) => {
			Iif (!fullQuery.trim()) {
				setResults([]);
				setSearched(false);
				setHasMore(false);
				setActiveQuery("");
				return;
			}
			lastQueryRef.current = fullQuery;
			setActiveQuery(fullQuery);
			setLoading(true);
			api
				.search(fullQuery, {
					inboundConnectorId: inboundConnectorId ?? undefined,
					limit: SEARCH_PAGE_SIZE,
				})
				.then((r) => {
					setResults(r);
					setSearched(true);
					setHasMore(r.length >= SEARCH_PAGE_SIZE);
					setFocusedIndex(r.length > 0 ? 0 : -1);
				})
				.catch(() => {
					setResults([]);
					setFocusedIndex(-1);
					setHasMore(false);
					toast("Search failed", "error");
				})
				.finally(() => setLoading(false));
		},
		[inboundConnectorId],
	);
 
	const triggerSearch = useCallback(
		(text: string, filters: ActiveFilter[]) => {
			const fullQuery = buildQueryWithFilters(text, filters);
			doSearch(fullQuery);
		},
		[doSearch],
	);
 
	// Trigger search on mount if an initial query was provided
	useEffect(() => {
		if (initialQueryRef.current && !initialQueryFiredRef.current) {
			initialQueryFiredRef.current = true;
			triggerSearch(initialQueryRef.current, []);
		}
	}, [triggerSearch]);
 
	const handleLoadMore = useCallback(() => {
		Iif (loadingMore || !lastQueryRef.current) return;
		setLoadingMore(true);
		api
			.search(lastQueryRef.current, {
				inboundConnectorId: inboundConnectorId ?? undefined,
				limit: SEARCH_PAGE_SIZE,
				offset: results.length,
			})
			.then((more) => {
				setResults((prev) => [...prev, ...more]);
				setHasMore(more.length >= SEARCH_PAGE_SIZE);
			})
			.catch(() => {
				toast("Failed to load more results", "error");
			})
			.finally(() => setLoadingMore(false));
	}, [inboundConnectorId, results.length, loadingMore]);
 
	// Cleanup debounce timeout on unmount
	useEffect(() => {
		return () => {
			if (debounceRef.current) clearTimeout(debounceRef.current);
		};
	}, []);
 
	const handleChange = useCallback(
		(value: string) => {
			setQuery(value);
			if (debounceRef.current) clearTimeout(debounceRef.current);
			debounceRef.current = setTimeout(() => triggerSearch(value, activeFilters), 300);
		},
		[triggerSearch, activeFilters],
	);
 
	const toggleFilter = useCallback(
		(type: string, value: string, label: string) => {
			setActiveFilters((prev) => {
				const key = filterKey({ type, value, label });
				const exists = prev.some((f) => filterKey(f) === key);
				const next = exists
					? prev.filter((f) => filterKey(f) !== key)
					: [...prev, { type, value, label }];
				// Trigger search with updated filters
				if (debounceRef.current) clearTimeout(debounceRef.current);
				debounceRef.current = setTimeout(() => triggerSearch(query, next), 150);
				return next;
			});
		},
		[query, triggerSearch],
	);
 
	const removeFilter = useCallback(
		(filter: ActiveFilter) => {
			setActiveFilters((prev) => {
				const next = prev.filter((f) => filterKey(f) !== filterKey(filter));
				Eif (debounceRef.current) clearTimeout(debounceRef.current);
				debounceRef.current = setTimeout(() => triggerSearch(query, next), 150);
				return next;
			});
		},
		[query, triggerSearch],
	);
 
	const applyDateFilter = useCallback(() => {
		const newFilters = activeFilters.filter((f) => f.type !== "after" && f.type !== "before");
		Eif (dateAfter) {
			newFilters.push({ type: "after", value: dateAfter, label: `After ${dateAfter}` });
		}
		if (dateBefore) {
			newFilters.push({ type: "before", value: dateBefore, label: `Before ${dateBefore}` });
		}
		setActiveFilters(newFilters);
		setShowDateFilter(false);
		if (debounceRef.current) clearTimeout(debounceRef.current);
		debounceRef.current = setTimeout(() => triggerSearch(query, newFilters), 150);
	}, [dateAfter, dateBefore, activeFilters, query, triggerSearch]);
 
	// Notify parent of results and query changes
	useEffect(() => {
		onResultsChange?.(results);
	}, [results, onResultsChange]);
 
	useEffect(() => {
		onQueryChange?.(activeQuery);
	}, [activeQuery, onQueryChange]);
 
	// Scroll focused result into view
	useEffect(() => {
		if (focusedIndex >= 0) {
			resultRefs.current[focusedIndex]?.scrollIntoView({ block: "nearest" });
		}
	}, [focusedIndex]);
 
	const handleKeyDown = useCallback(
		(e: React.KeyboardEvent) => {
			if (e.key === "Escape") {
				e.stopPropagation();
				onClose();
				return;
			}
			if (e.key === "ArrowDown") {
				e.preventDefault();
				setFocusedIndex((prev) => (prev < results.length - 1 ? prev + 1 : prev));
				return;
			}
			if (e.key === "ArrowUp") {
				e.preventDefault();
				setFocusedIndex((prev) => (prev > 0 ? prev - 1 : prev));
				return;
			}
			if (e.key === "Enter" && focusedIndex >= 0 && results[focusedIndex]) {
				e.preventDefault();
				onSelectMessage(results[focusedIndex].id);
			}
		},
		[results, focusedIndex, onSelectMessage, onClose],
	);
 
	const isFilterActive = (type: string, value: string) =>
		activeFilters.some((f) => f.type === type && f.value === value);
 
	return (
		<div className="flex flex-col h-full" onKeyDown={handleKeyDown}>
			{/* Search input */}
			<div className="flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-gray-800">
				<SearchIcon className="w-4 h-4 text-gray-400 flex-shrink-0" />
				<input
					ref={inputRef}
					type="text"
					value={query}
					onChange={(e) => handleChange(e.target.value)}
					className="flex-1 bg-transparent text-sm outline-none"
					placeholder="Search messages…"
					autoFocus
				/>
				{loading && <span className="text-xs text-gray-400 animate-pulse">Searching…</span>}
				<button
					type="button"
					onClick={onClose}
					className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 p-0.5"
					aria-label="Close"
				>
					<XIcon className="w-4 h-4" />
				</button>
			</div>
 
			{/* Quick filters */}
			<div className="flex items-center gap-2 px-4 py-2 border-b border-gray-100 dark:border-gray-800 flex-wrap">
				<FilterIcon className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
				{QUICK_FILTERS.map((qf) => (
					<button
						key={`${qf.type}:${qf.value}`}
						type="button"
						onClick={() => toggleFilter(qf.type, qf.value, qf.label)}
						className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
							isFilterActive(qf.type, qf.value)
								? "bg-stork-100 text-stork-700 dark:bg-stork-900 dark:text-stork-300"
								: "bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700"
						}`}
					>
						{qf.icon}
						{qf.label}
					</button>
				))}
				<button
					type="button"
					onClick={() => setShowDateFilter((v) => !v)}
					className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
						activeFilters.some((f) => f.type === "after" || f.type === "before")
							? "bg-stork-100 text-stork-700 dark:bg-stork-900 dark:text-stork-300"
							: "bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700"
					}`}
				>
					<CalendarIcon className="w-3.5 h-3.5" />
					Date range
				</button>
			</div>
 
			{/* Date range picker */}
			{showDateFilter && (
				<div className="flex items-center gap-2 px-4 py-2 border-b border-gray-100 dark:border-gray-800">
					<label className="text-xs text-gray-500">
						After:
						<input
							type="date"
							value={dateAfter}
							onChange={(e) => setDateAfter(e.target.value)}
							className="ml-1 bg-transparent text-xs border border-gray-300 dark:border-gray-600 rounded px-1.5 py-0.5"
						/>
					</label>
					<label className="text-xs text-gray-500">
						Before:
						<input
							type="date"
							value={dateBefore}
							onChange={(e) => setDateBefore(e.target.value)}
							className="ml-1 bg-transparent text-xs border border-gray-300 dark:border-gray-600 rounded px-1.5 py-0.5"
						/>
					</label>
					<button
						type="button"
						onClick={applyDateFilter}
						className="text-xs px-2 py-0.5 bg-stork-600 text-white rounded hover:bg-stork-700 transition-colors"
					>
						Apply
					</button>
				</div>
			)}
 
			{/* Active filter chips */}
			{activeFilters.length > 0 && (
				<div className="flex items-center gap-1.5 px-4 py-1.5 border-b border-gray-100 dark:border-gray-800 flex-wrap">
					{activeFilters.map((f) => (
						<span
							key={filterKey(f)}
							className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-stork-100 text-stork-700 dark:bg-stork-900 dark:text-stork-300"
						>
							{f.label}
							<button
								type="button"
								onClick={() => removeFilter(f)}
								className="hover:text-stork-900 dark:hover:text-stork-100"
								aria-label={`Remove ${f.label} filter`}
							>
								<XIcon className="w-3 h-3" />
							</button>
						</span>
					))}
					<button
						type="button"
						onClick={() => {
							setActiveFilters([]);
							setDateAfter("");
							setDateBefore("");
							Eif (debounceRef.current) clearTimeout(debounceRef.current);
							debounceRef.current = setTimeout(() => triggerSearch(query, []), 150);
						}}
						className="text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
					>
						Clear all
					</button>
				</div>
			)}
 
			{/* Search tips — shown near the input before any search has been run */}
			{!searched && !loading && (
				<div className="px-4 py-2 border-b border-gray-100 dark:border-gray-800 text-xs text-gray-400">
					Tip: <kbd className="bg-gray-200 dark:bg-gray-700 px-1 rounded">↑</kbd>/
					<kbd className="bg-gray-200 dark:bg-gray-700 px-1 rounded">↓</kbd> to navigate,{" "}
					<kbd className="bg-gray-200 dark:bg-gray-700 px-1 rounded">Enter</kbd> to select,{" "}
					<kbd className="bg-gray-200 dark:bg-gray-700 px-1 rounded">Esc</kbd> to exit.{" "}
					<span className="text-gray-300 dark:text-gray-600">|</span>{" "}
					<code className="text-gray-500">from:</code> <code className="text-gray-500">to:</code>{" "}
					<code className="text-gray-500">subject:</code>{" "}
					<code className="text-gray-500">has:attachment</code>{" "}
					<code className="text-gray-500">is:unread</code>{" "}
					<code className="text-gray-500">before:</code>{" "}
					<code className="text-gray-500">after:</code>
				</div>
			)}
 
			{/* Results */}
			<div className="flex-1 overflow-y-auto">
				{loading && results.length === 0 && (
					<div className="animate-pulse" data-testid="search-skeleton">
						{[1, 2, 3, 4].map((i) => (
							<div
								key={i}
								className="px-4 py-3 border-b border-gray-100 dark:border-gray-800 space-y-1.5"
							>
								<div className="flex items-baseline gap-2">
									<div className="h-3.5 bg-gray-200 dark:bg-gray-700 rounded w-28" />
									<div className="h-3 bg-gray-100 dark:bg-gray-800 rounded w-16 ml-auto" />
								</div>
								<div className="h-3.5 bg-gray-200 dark:bg-gray-700 rounded w-48" />
								<div className="h-3 bg-gray-100 dark:bg-gray-800 rounded w-64" />
							</div>
						))}
					</div>
				)}
				{searched && results.length === 0 && !loading && (
					<div className="p-6 text-center text-gray-400 text-sm">
						{query.trim()
							? `No results for \u201c${query}\u201d`
							: activeFilters.length > 0
								? "No messages match the selected filters"
								: "No results"}
					</div>
				)}
				{results.map((r, idx) => (
					<button
						key={r.id}
						ref={(el) => {
							resultRefs.current[idx] = el;
						}}
						type="button"
						onClick={() => {
							onSelectMessage(r.id);
						}}
						onMouseEnter={() => setFocusedIndex(idx)}
						aria-label={`${r.subject || "No subject"} from ${r.from_name || r.from_address}`}
						aria-selected={idx === focusedIndex}
						className={`w-full text-left px-4 py-3 border-b border-gray-100 dark:border-gray-800 transition-colors ${
							idx === focusedIndex
								? "bg-stork-50 dark:bg-stork-950"
								: "hover:bg-gray-50 dark:hover:bg-gray-800"
						}`}
					>
						<div className="flex items-baseline gap-2">
							<span className="text-sm font-medium truncate">{r.from_name || r.from_address}</span>
							<span className="text-xs text-gray-400 flex-shrink-0">
								{new Date(r.date).toLocaleDateString()}
							</span>
						</div>
						<div className="text-sm text-gray-700 dark:text-gray-300 truncate">
							{highlightText(r.subject || "(no subject)", query)}
						</div>
						{r.snippet && (
							<div
								className="text-xs text-gray-500 mt-0.5 line-clamp-1"
								dangerouslySetInnerHTML={{
									__html: DOMPurify.sanitize(r.snippet, {
										ALLOWED_TAGS: ["b", "mark"],
									}),
								}}
							/>
						)}
					</button>
				))}
				{hasMore && (
					<div className="px-4 py-3 text-center">
						<button
							type="button"
							onClick={handleLoadMore}
							disabled={loadingMore}
							className="text-sm text-stork-600 dark:text-stork-400 hover:text-stork-700 dark:hover:text-stork-300 disabled:opacity-50 transition-colors"
						>
							{loadingMore ? "Loading…" : `Load more results (${results.length} shown)`}
						</button>
					</div>
				)}
			</div>
		</div>
	);
}