Skip to content

Your lightweight open-source personal agent.

10.2 KB
Raw Blame
import { type KeyboardEvent, useDeferredValue, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { Search } from "lucide-react";
import { useTranslation } from "react-i18next";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogTitle,
} from "@/components/ui/dialog";
import { deriveTitle, visibleSessionPreview } from "@/lib/format";
import { findLoadedMessagePreview } from "@/lib/loaded-message-search";
import type { ThreadMessageCache } from "@/lib/thread-message-cache";
import { cn } from "@/lib/utils";
import type { ChatSummary } from "@/lib/types";

interface SessionSearchDialogProps {
  open: boolean;
  sessions: ChatSummary[];
  activeKey: string | null;
  loading: boolean;
  titleOverrides?: Record<string, string>;
  messageCache?: ThreadMessageCache;
  onOpenChange: (open: boolean) => void;
  onSelect: (key: string) => void;
}

interface SessionSearchResult {
  session: ChatSummary;
  preview?: string;
}

const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};
const noSubscription = () => () => {};
const noRevision = () => 0;

export function SessionSearchDialog({
  open,
  sessions,
  activeKey,
  loading,
  titleOverrides = EMPTY_TITLE_OVERRIDES,
  messageCache,
  onOpenChange,
  onSelect,
}: SessionSearchDialogProps) {
  const { t } = useTranslation();
  const inputRef = useRef<HTMLInputElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [scrollTop, setScrollTop] = useState(0);
  const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
  const [query, setQuery] = useState("");
  const [highlightedIndex, setHighlightedIndex] = useState(0);

  const messageRevision = useSyncExternalStore(
    open && messageCache ? messageCache.subscribe : noSubscription,
    messageCache?.getRevision ?? noRevision,
  );
  const normalizedQuery = query.trim().toLowerCase();
  const searchQuery = useDeferredValue(normalizedQuery);
  const searchRevision = useDeferredValue(messageRevision);
  const searchPending = searchQuery !== normalizedQuery || searchRevision !== messageRevision;
  const searchableSessions = useMemo(() => sessions.map((session) => ({
    session,
    text: [titleOverrides[session.key], session.title, visibleSessionPreview(session.preview),
      session.handle ? `@${session.handle.name}` : undefined]
      .filter(Boolean).join(" ").toLowerCase(),
  })), [sessions, titleOverrides]);
  const sessionResults = useMemo<SessionSearchResult[]>(() => {
    if (!open) return [];
    if (!searchQuery) return sessions.map((session) => ({ session }));
    const terms = searchQuery.split(/\s+/).filter(Boolean);
    return searchableSessions.flatMap(({ session, text }) => {
      if (terms.every((term) => text.includes(term))) return [{ session }];
      const preview = messageCache && findLoadedMessagePreview(
        messageCache.readLoadedMessages(session.chatId), searchQuery,
      );
      return preview === undefined ? [] : [{ session, preview }];
    });
  }, [searchQuery, open, sessions, searchableSessions, messageCache, searchRevision]);
  const itemCount = sessionResults.length;
  const rowHeight = 64;
  const windowStart = Math.max(0, Math.min(itemCount - 1, Math.floor(scrollTop / rowHeight) - 4));
  const windowEnd = Math.min(itemCount, windowStart + 24);

  useEffect(() => {
    if (!open) return;
    setQuery("");
    setHighlightedIndex(0);
    window.setTimeout(() => inputRef.current?.focus(), 0);
  }, [open]);

  useEffect(() => {
    setHighlightedIndex(0);
    setScrollTop(0);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [normalizedQuery]);

  useEffect(() => {
    setHighlightedIndex((index) =>
      itemCount === 0 ? 0 : Math.min(index, itemCount - 1),
    );
  }, [itemCount]);

  useEffect(() => {
    itemRefs.current = itemRefs.current.slice(0, itemCount);
  }, [itemCount]);

  useEffect(() => {
    if (!open) return;
    const scroller = scrollRef.current;
    if (scroller) {
      const top = highlightedIndex * rowHeight;
      if (top < scroller.scrollTop || top + rowHeight > scroller.scrollTop + scroller.clientHeight) {
        scroller.scrollTop = top;
        setScrollTop(top);
      }
    }
    itemRefs.current[highlightedIndex]?.scrollIntoView({
      block: "nearest",
      inline: "nearest",
    });
  }, [highlightedIndex, open]);

  const handleSelect = (key: string) => {
    if (searchPending) return;
    onOpenChange(false);
    onSelect(key);
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "ArrowDown") {
      event.preventDefault();
      setHighlightedIndex((index) =>
        itemCount === 0 ? 0 : (index + 1) % itemCount,
      );
      return;
    }
    if (event.key === "ArrowUp") {
      event.preventDefault();
      setHighlightedIndex((index) =>
        itemCount === 0 ? 0 : (index - 1 + itemCount) % itemCount,
      );
      return;
    }
    if (event.key === "Enter") {
      event.preventDefault();
      if (searchPending) return;
      const highlighted = sessionResults[highlightedIndex];
      if (!highlighted) return;
      handleSelect(highlighted.session.key);
    }
  };

  const emptyLabel = normalizedQuery
    ? t("sidebar.noSearchResults")
    : t("chat.noSessions");
  const sectionLabel = normalizedQuery
    ? t("sidebar.searchResults")
    : t("sidebar.recent");

  if (!open) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        showCloseButton={false}
        className={cn(
          "session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0",
        )}
      >
        <DialogTitle className="sr-only">{t("sidebar.searchAria")}</DialogTitle>
        <DialogDescription className="sr-only">
          {t("sidebar.searchPlaceholder")}
        </DialogDescription>
        <div className="session-search-input flex h-[62px] shrink-0 items-center gap-3 border-b border-border px-[18px]">
          <Search
            className="h-[18px] w-[18px] shrink-0 text-muted-foreground"
            aria-hidden
          />
          <input
            ref={inputRef}
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={t("sidebar.searchPlaceholder")}
            aria-label={t("sidebar.searchAria")}
            className="h-full min-w-0 flex-1 bg-transparent text-[19px] font-normal leading-none text-foreground outline-none placeholder:text-muted-foreground"
          />
        </div>

        <div
          ref={scrollRef}
          onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
          data-testid="session-search-scroll"
          aria-busy={searchPending}
          className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
        >
          <section>
            <div className="session-search-label px-2.5 pb-1.5 pt-1 text-[12px] font-medium text-muted-foreground">
              {sectionLabel}
            </div>

            {loading && sessions.length === 0 ? (
              <div className="px-3 py-7 text-[13px] text-muted-foreground">
                {t("chat.loading")}
              </div>
            ) : sessionResults.length === 0 ? (
              <div className="px-3 py-7 text-[13px] text-muted-foreground">
                {emptyLabel}
              </div>
            ) : (
              <ul>
                <li aria-hidden style={{ height: windowStart * rowHeight }} />
                {sessionResults.slice(windowStart, windowEnd).map(({ session, preview: matchPreview }, offset) => {
                  const index = windowStart + offset;
                  const title = titleOverrides[session.key]?.trim() ||
                    session.title?.trim() ||
                    deriveTitle(session.preview, t("chat.newChat"));
                  const preview = matchPreview ?? visibleSessionPreview(session.preview);
                  const showPreview =
                    preview.length > 0 &&
                    preview.toLowerCase() !== title.trim().toLowerCase();
                  const highlighted = index === highlightedIndex;
                  const active = session.key === activeKey;
                  return (
                    <li key={session.key} style={{ height: rowHeight }}>
                      <button
                        ref={(node) => {
                          itemRefs.current[index] = node;
                        }}
                        type="button"
                        disabled={searchPending}
                        onClick={() => handleSelect(session.key)}
                        onMouseEnter={() => setHighlightedIndex(index)}
                        aria-current={active ? "page" : undefined}
                        className={cn(
                          "grid h-full w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-control px-3 py-2 text-left transition-colors",
                          highlighted
                            ? "bg-muted text-foreground"
                            : "text-foreground hover:bg-muted",
                        )}
                      >
                        <span className="min-w-0 flex-1">
                          <span className="block truncate text-[14px] font-medium leading-5">
                            {title}
                          </span>
                          {showPreview ? (
                            <span
                              className="block truncate text-[12px] leading-4 text-muted-foreground"
                            >
                              {preview}
                            </span>
                          ) : null}
                        </span>
                        {active ? (
                          <span className="shrink-0 rounded-full bg-muted-foreground/10 px-2 py-0.5 text-[11px] font-medium text-muted-foreground">
                            {t("common.current", { defaultValue: "Current" })}
                          </span>
                        ) : null}
                      </button>
                    </li>
                  );
                })}
                <li aria-hidden style={{ height: (itemCount - windowEnd) * rowHeight }} />
              </ul>
            )}
          </section>
        </div>
      </DialogContent>
    </Dialog>
  );
}