Files
kandev/apps/web/components/task/chat/message-history-search.tsx
T
João Salavisa f3aeab020a feat(web): chat history nav with ArrowUp/Down and Ctrl+R fuzzy search (#1246)
* feat(web): chat history nav with ArrowUp/Down and Ctrl+R fuzzy search

ArrowUp/ArrowDown cycle the user's previous messages in the chat composer
(bash-style), Ctrl+R opens a fuzzy reverse-search overlay anchored to the
input. Opening the overlay drains the paginated message history in the
background so search covers the whole session, not only the pages already
loaded in the chat list.

* fix(web): address PR review on chat history nav (#1246)

- Always clear isDraining on cancel, error, and normal completion (cleanup
  setter + try/catch/finally in the drain loop).
- Ctrl+R no longer dead-keys when the loaded history is empty: the overlay
  opens unconditionally and renders "No matches" until drained pages arrive.
- Dedupe adjacent user prompts in the original message stream, not in the
  extracted output, so repeated prompts separated by agent/tool turns stay
  reachable from ArrowUp and Ctrl+R.
- Stabilize handleReverseSearchSelect by depending on the destructured
  closeReverseSearch instead of the spread overlay object.
- HitRow key={hit.index} so React reuses rows across re-rankings.
- Reorder SSR/isOpen guards before computeStyle so window.* isn't touched
  during a server render.
- Add use-drain-older-messages.test.ts covering normal drain, batch cap,
  cancellation on active->false, and rejection clearing isDraining.

* fix(web): address PR feedback on chat history nav (#1246)

- writeHistoryContent wraps editor mutations in try/finally so
  state.isApplying clears even if a chain or onChange handler throws.
- Dismiss the Ctrl+R overlay on window resize and capture-phase scroll so
  the fixed-position portal can't drift away from the editor anchor.
- Drop the unused historyRef from useChatHistory's return value.
- Extract HitRow into message-history-search-row.tsx so the search file
  stays under the 200-line cap.

* fix(web): keep Ctrl+R overlay open during keyboard navigation (#1246)

- Drop capture:true on the window scroll listener so scrollIntoView inside
  the overlay's own result list (triggered by keyboard navigation past the
  visible window) no longer dismisses the overlay.
- Remove the always-true isOpen prop and the unreachable guard from
  MessageHistorySearch; visibility is controlled solely by the parent's
  conditional render.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-06-02 17:00:38 +01:00

201 lines
6.5 KiB
TypeScript

"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { searchHistory, type SearchHit } from "./message-history";
import { HitRow } from "./message-history-search-row";
type MessageHistorySearchProps = {
/** Newest-first list of the user's previous messages for this session. */
history: readonly string[];
/** True while older messages are still being paginated in from the backend
* (overlay-driven drain). The list updates live as more arrive. */
isLoadingOlder?: boolean;
/** Bottom-anchor rect (typically the chat input's bounding rect). The
* overlay positions itself directly above this rect. */
anchorRect: DOMRect | null;
onClose: () => void;
/** Invoked when the user picks a result. `index` is the position in
* `history` so the editor's history navigation can resume from there. */
onSelect: (index: number) => void;
};
const OVERLAY_HEIGHT = 280;
const OVERLAY_MAX_WIDTH = 700;
function clampSelectedIndex(prev: number, hitCount: number): number {
if (hitCount === 0) return 0;
if (prev >= hitCount) return hitCount - 1;
if (prev < 0) return 0;
return prev;
}
function useHits(history: readonly string[], query: string): SearchHit[] {
return useMemo(() => searchHistory(history, query), [history, query]);
}
/** Track the selected index without an effect: reset to 0 when the query
* changes (state-during-render pattern), then clamp against the live hit
* count when reading. The setter remains stable so handlers can move it. */
function useSelectedIndex(hitCount: number, query: string) {
const [rawSelectedIndex, setSelectedIndex] = useState(0);
const [trackedQuery, setTrackedQuery] = useState(query);
if (trackedQuery !== query) {
setTrackedQuery(query);
setSelectedIndex(0);
}
const selectedIndex = clampSelectedIndex(rawSelectedIndex, hitCount);
return [selectedIndex, setSelectedIndex] as const;
}
type OverlayKeyArgs = {
hits: SearchHit[];
selectedIndex: number;
setSelectedIndex: React.Dispatch<React.SetStateAction<number>>;
onSelect: (index: number) => void;
onClose: () => void;
};
function handleOverlayKeyDown(event: React.KeyboardEvent, args: OverlayKeyArgs) {
const { hits, selectedIndex, setSelectedIndex, onSelect, onClose } = args;
if (event.key === "ArrowDown") {
event.preventDefault();
setSelectedIndex((i) => Math.min(i + 1, hits.length - 1));
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
return;
}
if (event.key === "Enter") {
event.preventDefault();
const hit = hits[selectedIndex];
if (hit) onSelect(hit.index);
return;
}
if (event.key === "Escape") {
event.preventDefault();
onClose();
}
}
function useScrollSelectedIntoView(
selectedIndex: number,
listRef: React.RefObject<HTMLDivElement | null>,
) {
useEffect(() => {
const list = listRef.current;
if (!list) return;
const item = list.querySelector<HTMLElement>(`[data-hit-index="${selectedIndex}"]`);
if (item) item.scrollIntoView({ block: "nearest" });
}, [selectedIndex, listRef]);
}
function computeStyle(anchorRect: DOMRect | null): React.CSSProperties | null {
if (!anchorRect) return null;
const left = Math.max(8, anchorRect.left);
const maxWidth = Math.min(OVERLAY_MAX_WIDTH, Math.max(200, window.innerWidth - left - 8));
return {
position: "fixed",
left,
width: Math.min(maxWidth, anchorRect.width || maxWidth),
bottom: window.innerHeight - anchorRect.top + 8,
maxHeight: OVERLAY_HEIGHT,
zIndex: 60,
pointerEvents: "auto",
};
}
export function MessageHistorySearch({
history,
isLoadingOlder = false,
anchorRect,
onClose,
onSelect,
}: MessageHistorySearchProps) {
const [query, setQuery] = useState("");
const hits = useHits(history, query);
const [selectedIndex, setSelectedIndex] = useSelectedIndex(hits.length, query);
const inputRef = useRef<HTMLInputElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
useEffect(() => {
requestAnimationFrame(() => inputRef.current?.focus());
}, []);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
onClose();
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [onClose]);
useScrollSelectedIntoView(selectedIndex, listRef);
if (typeof document === "undefined") return null;
const style = computeStyle(anchorRect);
if (!style) return null;
const overlay = (
<div
ref={containerRef}
style={style}
className="overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10"
data-testid="history-search-overlay"
>
<div className="flex items-center gap-2 px-2 py-1.5 border-b border-border/50">
<span className="text-xs font-medium text-muted-foreground shrink-0">
(reverse-i-search)
</span>
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) =>
handleOverlayKeyDown(e, { hits, selectedIndex, setSelectedIndex, onSelect, onClose })
}
placeholder="Type to search previous messages..."
className="flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
data-testid="history-search-input"
/>
{isLoadingOlder && (
<span
className="text-[10px] text-muted-foreground shrink-0"
data-testid="history-search-loading-older"
>
loading older…
</span>
)}
</div>
<div
ref={listRef}
className="overflow-y-auto py-1 scrollbar-thin"
style={{ maxHeight: OVERLAY_HEIGHT - 36 }}
>
{hits.length === 0 ? (
<div className="px-3 py-2 text-xs text-muted-foreground">No matches</div>
) : (
hits.map((hit, rowIndex) => (
<HitRow
key={hit.index}
hit={hit}
isSelected={rowIndex === selectedIndex}
rowIndex={rowIndex}
onMouseEnter={setSelectedIndex}
onClick={onSelect}
/>
))
)}
</div>
</div>
);
return createPortal(overlay, document.body);
}