All files / src/components MessageSearch.tsx

0% Statements 0/341
0% Branches 0/1
0% Functions 0/1
0% Lines 0/341

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Search, X, ChevronUp, ChevronDown, Clock, User, Filter } from 'lucide-react';
import { Button } from './ui';
import { useChatStore, Message } from '../store/chatStore';
 
export interface SearchFilters {
  sender: 'all' | 'user' | 'assistant';
  timeRange: 'all' | 'today' | 'week' | 'month';
}
 
export interface SearchResult {
  message: Message;
  matchIndices: Array<{ start: number; end: number }>;
}
 
interface MessageSearchProps {
  onNavigateToMessage: (messageId: string) => void;
}
 
const SEARCH_HISTORY_KEY = 'zclaw-search-history';
const MAX_HISTORY_ITEMS = 10;
 
export function MessageSearch({ onNavigateToMessage }: MessageSearchProps) {
  const { messages } = useChatStore();
 
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [filters, setFilters] = useState<SearchFilters>({
    sender: 'all',
    timeRange: 'all',
  });
  const [currentMatchIndex, setCurrentMatchIndex] = useState(0);
  const [showFilters, setShowFilters] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
 
  // Load search history from localStorage
  useEffect(() => {
    try {
      const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
      if (saved) {
        setSearchHistory(JSON.parse(saved));
      }
    } catch {
      // Ignore parse errors
    }
  }, []);
 
  // Save search query to history
  const saveToHistory = useCallback((searchQuery: string) => {
    if (!searchQuery.trim()) return;
 
    setSearchHistory((prev) => {
      const filtered = prev.filter((item) => item !== searchQuery);
      const updated = [searchQuery, ...filtered].slice(0, MAX_HISTORY_ITEMS);
      try {
        localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
      } catch {
        // Ignore storage errors
      }
      return updated;
    });
  }, []);
 
  // Filter messages by time range
  const filterByTimeRange = useCallback((message: Message, timeRange: SearchFilters['timeRange']): boolean => {
    if (timeRange === 'all') return true;
 
    const messageTime = new Date(message.timestamp).getTime();
    const now = Date.now();
    const day = 24 * 60 * 60 * 1000;
 
    switch (timeRange) {
      case 'today':
        return messageTime >= now - day;
      case 'week':
        return messageTime >= now - 7 * day;
      case 'month':
        return messageTime >= now - 30 * day;
      default:
        return true;
    }
  }, []);
 
  // Filter messages by sender
  const filterBySender = useCallback((message: Message, sender: SearchFilters['sender']): boolean => {
    if (sender === 'all') return true;
    if (sender === 'user') return message.role === 'user';
    if (sender === 'assistant') return message.role === 'assistant' || message.role === 'tool';
    return true;
  }, []);
 
  // Search messages and find matches
  const searchResults = useMemo((): SearchResult[] => {
    if (!query.trim()) return [];
 
    const searchTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
    if (searchTerms.length === 0) return [];
 
    const results: SearchResult[] = [];
 
    for (const message of messages) {
      // Apply filters
      if (!filterBySender(message, filters.sender)) continue;
      if (!filterByTimeRange(message, filters.timeRange)) continue;
 
      const content = message.content.toLowerCase();
      const matchIndices: Array<{ start: number; end: number }> = [];
 
      // Find all matches
      for (const term of searchTerms) {
        let startIndex = 0;
        while (true) {
          const index = content.indexOf(term, startIndex);
          if (index === -1) break;
          matchIndices.push({ start: index, end: index + term.length });
          startIndex = index + 1;
        }
      }
 
      if (matchIndices.length > 0) {
        // Sort and merge overlapping matches
        matchIndices.sort((a, b) => a.start - b.start);
        const merged: Array<{ start: number; end: number }> = [];
        for (const match of matchIndices) {
          if (merged.length === 0 || merged[merged.length - 1].end < match.start) {
            merged.push(match);
          } else {
            merged[merged.length - 1].end = Math.max(merged[merged.length - 1].end, match.end);
          }
        }
        results.push({ message, matchIndices: merged });
      }
    }
 
    return results;
  }, [query, messages, filters, filterBySender, filterByTimeRange]);
 
  // Navigate to previous match
  const handlePrevious = useCallback(() => {
    if (searchResults.length === 0) return;
    setCurrentMatchIndex((prev) =>
      prev > 0 ? prev - 1 : searchResults.length - 1
    );
    const result = searchResults[currentMatchIndex > 0 ? currentMatchIndex - 1 : searchResults.length - 1];
    onNavigateToMessage(result.message.id);
  }, [searchResults, currentMatchIndex, onNavigateToMessage]);
 
  // Navigate to next match
  const handleNext = useCallback(() => {
    if (searchResults.length === 0) return;
    setCurrentMatchIndex((prev) =>
      prev < searchResults.length - 1 ? prev + 1 : 0
    );
    const result = searchResults[currentMatchIndex < searchResults.length - 1 ? currentMatchIndex + 1 : 0];
    onNavigateToMessage(result.message.id);
  }, [searchResults, currentMatchIndex, onNavigateToMessage]);
 
  // Handle keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+F or Cmd+F to open search
      if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        setIsOpen((prev) => !prev);
        setTimeout(() => inputRef.current?.focus(), 100);
      }
 
      // Escape to close search
      if (e.key === 'Escape' && isOpen) {
        setIsOpen(false);
        setQuery('');
      }
 
      // Enter to navigate to next match
      if (e.key === 'Enter' && isOpen && searchResults.length > 0) {
        if (e.shiftKey) {
          handlePrevious();
        } else {
          handleNext();
        }
      }
    };
 
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, searchResults.length, handlePrevious, handleNext]);
 
  // Reset current match index when results change
  useEffect(() => {
    setCurrentMatchIndex(0);
  }, [searchResults.length]);
 
  // Handle search submit
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (query.trim()) {
      saveToHistory(query.trim());
      if (searchResults.length > 0) {
        onNavigateToMessage(searchResults[0].message.id);
      }
    }
  };
 
  // Clear search
  const handleClear = () => {
    setQuery('');
    inputRef.current?.focus();
  };
 
  // Toggle search panel
  const toggleSearch = () => {
    setIsOpen((prev) => !prev);
    if (!isOpen) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  };
 
  return (
    <>
      {/* Search toggle button */}
      <Button
        variant="ghost"
        size="sm"
        onClick={toggleSearch}
        className={`flex items-center gap-1.5 ${isOpen ? 'text-orange-600 dark:text-orange-400 bg-orange-50 dark:bg-orange-900/20' : 'text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}`}
        title="Search messages (Ctrl+F)"
        aria-label="Search messages"
        aria-expanded={isOpen}
      >
        <Search className="w-3.5 h-3.5" />
        <span className="hidden sm:inline">Search</span>
      </Button>
 
      {/* Search panel */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.2 }}
            className="border-b border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 overflow-hidden"
          >
            <div className="px-4 py-3">
              <form onSubmit={handleSubmit} className="flex items-center gap-2">
                {/* Search input */}
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    ref={inputRef}
                    type="text"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    placeholder="Search messages..."
                    className="w-full pl-9 pr-8 py-2 text-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 dark:focus:ring-orange-400 focus:border-transparent"
                    aria-label="Search query"
                  />
                  {query && (
                    <button
                      type="button"
                      onClick={handleClear}
                      className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                      aria-label="Clear search"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  )}
                </div>
 
                {/* Filter toggle */}
                <Button
                  type="button"
                  variant={showFilters ? 'secondary' : 'ghost'}
                  size="sm"
                  onClick={() => setShowFilters((prev) => !prev)}
                  className="flex items-center gap-1"
                  aria-label="Toggle filters"
                  aria-expanded={showFilters}
                >
                  <Filter className="w-4 h-4" />
                  <span className="hidden sm:inline">Filters</span>
                </Button>
 
                {/* Navigation buttons */}
                {searchResults.length > 0 && (
                  <div className="flex items-center gap-1">
                    <span className="text-xs text-gray-500 dark:text-gray-400 px-2">
                      {currentMatchIndex + 1} / {searchResults.length}
                    </span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={handlePrevious}
                      className="p-1.5"
                      aria-label="Previous match"
                    >
                      <ChevronUp className="w-4 h-4" />
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={handleNext}
                      className="p-1.5"
                      aria-label="Next match"
                    >
                      <ChevronDown className="w-4 h-4" />
                    </Button>
                  </div>
                )}
              </form>
 
              {/* Filters panel */}
              <AnimatePresence>
                {showFilters && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700"
                  >
                    <div className="flex flex-wrap gap-4">
                      {/* Sender filter */}
                      <div className="flex items-center gap-2">
                        <label className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                          <User className="w-3.5 h-3.5" />
                          Sender:
                        </label>
                        <select
                          value={filters.sender}
                          onChange={(e) => setFilters((prev) => ({ ...prev, sender: e.target.value as SearchFilters['sender'] }))}
                          className="text-xs bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-orange-500"
                        >
                          <option value="all">All</option>
                          <option value="user">User</option>
                          <option value="assistant">Assistant</option>
                        </select>
                      </div>
 
                      {/* Time range filter */}
                      <div className="flex items-center gap-2">
                        <label className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                          <Clock className="w-3.5 h-3.5" />
                          Time:
                        </label>
                        <select
                          value={filters.timeRange}
                          onChange={(e) => setFilters((prev) => ({ ...prev, timeRange: e.target.value as SearchFilters['timeRange'] }))}
                          className="text-xs bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-orange-500"
                        >
                          <option value="all">All time</option>
                          <option value="today">Today</option>
                          <option value="week">This week</option>
                          <option value="month">This month</option>
                        </select>
                      </div>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
 
              {/* Search history */}
              {!query && searchHistory.length > 0 && (
                <div className="mt-2">
                  <div className="text-xs text-gray-400 dark:text-gray-500 mb-1">Recent searches:</div>
                  <div className="flex flex-wrap gap-1">
                    {searchHistory.slice(0, 5).map((item, index) => (
                      <button
                        key={index}
                        type="button"
                        onClick={() => setQuery(item)}
                        className="text-xs px-2 py-1 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors"
                      >
                        {item}
                      </button>
                    ))}
                  </div>
                </div>
              )}
 
              {/* No results message */}
              {query && searchResults.length === 0 && (
                <div className="mt-2 text-xs text-gray-500 dark:text-gray-400 text-center py-2">
                  No messages found matching "{query}"
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
 
// Utility function to highlight search matches in text
export function highlightSearchMatches(
  text: string,
  query: string,
  highlightClassName: string = 'bg-yellow-200 dark:bg-yellow-700/50 rounded px-0.5'
): React.ReactNode[] {
  if (!query.trim()) return [text];
 
  const searchTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
  if (searchTerms.length === 0) return [text];
 
  const lowerText = text.toLowerCase();
  const matches: Array<{ start: number; end: number }> = [];
 
  // Find all matches
  for (const term of searchTerms) {
    let startIndex = 0;
    while (true) {
      const index = lowerText.indexOf(term, startIndex);
      if (index === -1) break;
      matches.push({ start: index, end: index + term.length });
      startIndex = index + 1;
    }
  }
 
  if (matches.length === 0) return [text];
 
  // Sort and merge overlapping matches
  matches.sort((a, b) => a.start - b.start);
  const merged: Array<{ start: number; end: number }> = [];
  for (const match of matches) {
    if (merged.length === 0 || merged[merged.length - 1].end < match.start) {
      merged.push({ ...match });
    } else {
      merged[merged.length - 1].end = Math.max(merged[merged.length - 1].end, match.end);
    }
  }
 
  // Build highlighted result
  const result: React.ReactNode[] = [];
  let lastIndex = 0;
 
  for (let i = 0; i < merged.length; i++) {
    const match = merged[i];
 
    // Text before match
    if (match.start > lastIndex) {
      result.push(text.slice(lastIndex, match.start));
    }
 
    // Highlighted match
    result.push(
      <mark key={i} className={highlightClassName}>
        {text.slice(match.start, match.end)}
      </mark>
    );
 
    lastIndex = match.end;
  }
 
  // Remaining text
  if (lastIndex < text.length) {
    result.push(text.slice(lastIndex));
  }
 
  return result;
}