Files
Netcatty/components/terminal/autocomplete/AutocompletePopup.tsx
T
rnarany 51d9f715da feat(autocomplete): localize common commands and polish terminal hints (#4172)
* feat(autocomplete): add zh-CN descriptions for zip, unzip, make, nano

Cover 32 missing Fig descriptions, generate zh-TW, add batch coverage tests, and record source and semantic checks.

* fix(autocomplete): correct zip, unzip, and make semantics

Limit zip -9 to the compression level, warn that unzip -0 is a suspect upstream option, and describe make -N as the Apple/NeXT compatibility extension.

* fix(autocomplete): simplify unzip -0 warning and correct NeXT note

Keep the -O gbk version caveat in the research record and describe Next/NeXT as a capitalization difference.

* feat(autocomplete): complete remaining common command descriptions

Add 177 zh-CN descriptions for python, python3, node, vim, sort, awk, and sed; generate zh-TW, cover the batch with real Fig specs, and record one deferred shared node key.

* fix(autocomplete): correct sed n and sort parallel semantics

Add the automatic-print condition to sed n, remove the universal CPU default from sort --parallel, and remove duplicated adopted-entry sections from the source record.

* fix: repair macOS terminal setup and align autocomplete details

- Read OSC 7 setup payloads through base64 stdin so BSD/macOS works
- Keep the FIDO askpass socket path within the Unix sun_path limit
- Align autocomplete descriptions in a shared fixed column
- Fix an invalid optional-parameter declaration and lint warnings
- Harden macOS-sensitive OSC 7, SFTP, temp-dir and privacy tests

* feat(autocomplete): add zh-CN descriptions for file and text utilities

Cover ln, stat, wc, cut, uniq, tee and xargs with 70 localized
descriptions. Add coverage and localization tests, preload the new common
specs, and record the upstream wc/xargs wording corrections.

* fix(autocomplete): keep popup scrollbars draggable

Panel mousedown handlers no longer preventDefault across the whole box, so the right-side detail scrollbar and the suggestion list scrollbar can be dragged while padding clicks still preserve terminal focus.

* fix(autocomplete): keep detail panel open while selecting text

Delay row hover clearing so the pointer can move into the right-side detail panel, and allow native text selection there without stealing terminal focus on ordinary padding clicks.
2026-11-07 20:00:43 +08:00

744 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Popup autocomplete menu for terminal.
* Renders a floating list of completion suggestions near the terminal cursor.
* Shows a detail tooltip for the selected/hovered item with full description.
* Colors are derived from the active terminal theme for visual consistency.
*/
import React, { useEffect, useLayoutEffect, useRef, useState, memo } from "react";
import { Folder, File, Link } from "lucide-react";
import type { CompletionSuggestion, SuggestionSource } from "./completionEngine";
import {
clampAutocompletePopupGeometry,
computeAutocompletePopupPlacement,
resolveAutocompleteClampViewport,
} from "./terminalAutocompleteLayout";
export interface AutocompleteThemeColors {
background: string;
foreground: string;
selection: string;
cursor: string;
}
export interface SubDirEntry {
name: string;
type: "file" | "directory" | "symlink";
}
export interface SubDirPanel {
entries: SubDirEntry[];
selectedIndex: number;
dirPath: string;
}
interface AutocompletePopupProps {
suggestions: CompletionSuggestion[];
selectedIndex: number;
/** Cursor anchor in viewport coordinates */
anchorViewport: { left: number; top: number; bottom: number };
visible: boolean;
expandUpward?: boolean;
themeColors?: AutocompleteThemeColors;
onSelect: (suggestion: CompletionSuggestion) => void;
maxHeight?: number;
subDirPanels?: SubDirPanel[];
subDirFocusLevel?: number;
/** Reference to the terminal container for calculating fixed position */
containerRef?: React.RefObject<HTMLDivElement | null>;
/** Ask the autocomplete controller to recompute cursor-relative popup position */
onRequestReposition?: () => void;
/** Offset from top of container to terminal content area (toolbar + search bar) */
searchBarOffset?: number;
/** Called when user clicks outside the popup to dismiss it */
onDismiss?: () => void;
}
const SOURCE_LABELS: Record<SuggestionSource, { label: string; fullLabel: string; fallbackColor: string }> = {
history: { label: "h", fullLabel: "History", fallbackColor: "#FBBF24" },
command: { label: "c", fullLabel: "Command", fallbackColor: "#34D399" },
subcommand: { label: "s", fullLabel: "Subcommand", fallbackColor: "#60A5FA" },
option: { label: "o", fullLabel: "Option", fallbackColor: "#A78BFA" },
arg: { label: "a", fullLabel: "Argument", fallbackColor: "#F87171" },
path: { label: "p", fullLabel: "Path", fallbackColor: "#38BDF8" },
snippet: { label: "{}", fullLabel: "Snippet", fallbackColor: "#C084FC" },
plugin: { label: "P", fullLabel: "Plugin", fallbackColor: "#F472B6" },
};
/** Lucide icon components for file types in path suggestions */
const FILE_TYPE_CONFIG: Record<string, { Icon: React.FC<{ size?: number; color?: string }>; color: string }> = {
directory: { Icon: Folder, color: "#38BDF8" },
file: { Icon: File, color: "#94A3B8" },
symlink: { Icon: Link, color: "#A78BFA" },
};
const FileTypeIcon: React.FC<{ fileType: string }> = ({ fileType }) => {
const cfg = FILE_TYPE_CONFIG[fileType] ?? FILE_TYPE_CONFIG.file;
return (
<span
style={{
width: "18px",
height: "18px",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
}}
>
<cfg.Icon size={14} color={cfg.color} />
</span>
);
};
/** Chevron indicator for expandable directory items */
const DirExpandIndicator: React.FC<{ visible: boolean; color: string }> = ({ visible, color }) => (
<span style={{ fontSize: "10px", color, opacity: visible ? 0.6 : 0, flexShrink: 0, marginLeft: "2px" }}>›</span>
);
/** Small key-cap badge shown on the selected row to hint the actionable key. */
const KeyCap: React.FC<{ label: string; color: string; bg: string }> = ({ label, color, bg }) => (
<span
style={{
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
boxSizing: "border-box",
height: "16px",
minWidth: "16px",
padding: "0 4px",
fontSize: "11px",
lineHeight: 1,
borderRadius: "4px",
border: `1px solid color-mix(in srgb, ${color} 35%, transparent)`,
color: `color-mix(in srgb, ${color} 80%, ${bg})`,
backgroundColor: `color-mix(in srgb, ${color} 12%, ${bg})`,
flexShrink: 0,
fontFamily:
'ui-sans-serif, -apple-system, "Segoe UI", system-ui, sans-serif',
}}
>
{label}
</span>
);
const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
suggestions,
selectedIndex,
anchorViewport,
visible,
expandUpward = false,
themeColors,
onSelect,
maxHeight = 240,
subDirPanels = [],
subDirFocusLevel = -1,
containerRef,
onRequestReposition,
searchBarOffset: _searchBarOffset = 30,
onDismiss,
}) => {
const wrapperRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const selectedRef = useRef<HTMLDivElement>(null);
const [hoveredIndex, setHoveredIndex] = useState(-1);
const [measuredSize, setMeasuredSize] = useState<{ width: number; height: number } | null>(null);
const hoverClearTimerRef = useRef<number | null>(null);
const cancelHoverClear = () => {
if (hoverClearTimerRef.current === null) return;
window.clearTimeout(hoverClearTimerRef.current);
hoverClearTimerRef.current = null;
};
// Rows and the detail panel are separate boxes with a small gap. Keep the
// hovered row alive briefly so moving the pointer into the detail panel does
// not unmount the panel before it can be read, selected, or scrolled.
const scheduleHoverClear = () => {
cancelHoverClear();
hoverClearTimerRef.current = window.setTimeout(() => {
hoverClearTimerRef.current = null;
setHoveredIndex(-1);
}, 400);
};
useEffect(() => () => {
if (hoverClearTimerRef.current !== null) {
window.clearTimeout(hoverClearTimerRef.current);
hoverClearTimerRef.current = null;
}
}, []);
useEffect(() => {
if (selectedRef.current && listRef.current) {
selectedRef.current.scrollIntoView({
block: "nearest",
behavior: "instant" as ScrollBehavior,
});
}
}, [selectedIndex]);
// Reset hover when suggestions change
useEffect(() => {
if (hoverClearTimerRef.current !== null) {
window.clearTimeout(hoverClearTimerRef.current);
hoverClearTimerRef.current = null;
}
setHoveredIndex(-1);
}, [suggestions]);
useEffect(() => {
if (!visible || !onRequestReposition) return;
let frameId = 0;
const requestReposition = () => {
if (frameId) cancelAnimationFrame(frameId);
frameId = requestAnimationFrame(() => {
frameId = 0;
onRequestReposition();
});
};
const container = containerRef?.current;
const observer = container ? new ResizeObserver(requestReposition) : null;
observer?.observe(container);
window.addEventListener("resize", requestReposition);
return () => {
if (frameId) cancelAnimationFrame(frameId);
observer?.disconnect();
window.removeEventListener("resize", requestReposition);
};
}, [containerRef, onRequestReposition, visible]);
useEffect(() => {
if (!visible || !onRequestReposition || suggestions.length === 0) return;
let firstFrame = 0;
let secondFrame = 0;
firstFrame = requestAnimationFrame(() => {
onRequestReposition();
secondFrame = requestAnimationFrame(onRequestReposition);
});
return () => {
if (firstFrame) cancelAnimationFrame(firstFrame);
if (secondFrame) cancelAnimationFrame(secondFrame);
};
}, [onRequestReposition, subDirPanels.length, suggestions, visible]);
useLayoutEffect(() => {
if (!visible || suggestions.length === 0) {
setMeasuredSize((current) => (current === null ? current : null));
return;
}
let frameId = 0;
const measure = () => {
const rect = wrapperRef.current?.getBoundingClientRect();
if (!rect || rect.width <= 0 || rect.height <= 0) return;
setMeasuredSize((current) => {
if (
current &&
Math.abs(current.width - rect.width) < 0.5 &&
Math.abs(current.height - rect.height) < 0.5
) {
return current;
}
return { width: rect.width, height: rect.height };
});
};
measure();
const wrapper = wrapperRef.current;
const observer = wrapper ? new ResizeObserver(measure) : null;
observer?.observe(wrapper);
frameId = requestAnimationFrame(measure);
return () => {
if (frameId) cancelAnimationFrame(frameId);
observer?.disconnect();
};
// hoveredIndex intentionally not a dependency: the detail panel below has
// a fixed box (width/height), so hovering cannot change the wrapper's
// size — re-measuring per hover would only feed the resize back into the
// position clamp and jitter the popup under the pointer (#3426).
}, [selectedIndex, subDirPanels, suggestions, visible]);
// Dismiss popup when clicking outside
useEffect(() => {
if (!visible || !onDismiss) return;
const handlePointerDown = (e: PointerEvent) => {
if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
onDismiss();
}
};
document.addEventListener("pointerdown", handlePointerDown);
return () => document.removeEventListener("pointerdown", handlePointerDown);
}, [visible, onDismiss]);
if (!visible || suggestions.length === 0) return null;
const bg = themeColors?.background ?? "#1e1e2e";
const fg = themeColors?.foreground ?? "#cdd6f4";
// Accent comes from the active terminal theme's cursor/selection colors,
// which already track the user's accent setting (custom accent rewrites them
// in applyCustomAccentToTerminalTheme). Falling back to selection, then a
// neutral fg-mix, keeps older/partial theme payloads working. This is what
// makes the popup's highlight follow the accent instead of a hardcoded blue.
const accent = themeColors?.cursor || themeColors?.selection || fg;
const popupBg = `color-mix(in srgb, ${bg} 92%, ${fg} 8%)`;
const popupBorder = `color-mix(in srgb, ${bg} 75%, ${fg} 25%)`;
const selectedBg = `color-mix(in srgb, ${accent} 26%, ${bg} 74%)`;
const selectedBorderAccent = `color-mix(in srgb, ${accent} 60%, ${bg} 40%)`;
const hoverBg = `color-mix(in srgb, ${accent} 12%, ${bg} 88%)`;
const textColor = fg;
const dimTextColor = `color-mix(in srgb, ${fg} 50%, ${bg} 50%)`;
// Determine which item to show the detail tooltip for
const detailIndex = hoveredIndex >= 0 ? hoveredIndex : selectedIndex;
const detailItem = detailIndex >= 0 ? suggestions[detailIndex] : null;
const showDetail = detailItem?.description && detailItem.description.length > 0;
// Whether ANY item in the current set can open the detail tooltip (non-path
// row with a description). Placement reserves space from this set-level flag
// rather than the hovered item, so moving the mouse between rows can't change
// totalWidth/height and shift the popup out from under the pointer.
const setMayShowDetailPanel = suggestions.some(
(s) => s.source !== "path" && Boolean(s.description && s.description.length > 0),
);
// The tooltip is only visible for the hovered/selected non-path row, but it
// is MOUNTED for the whole set with a fixed box (width = the reserved
// DETAIL_PANEL_MAX_WIDTH, height = the reserved estimatedDetailHeight) and
// toggled with visibility instead of mounting/unmounting. A hover-driven
// size change would flow through the measured-size clamp below and move the
// popup under a stationary pointer, which flips the hovered row and
// self-oscillates — the violent mousemove jitter from #3426.
const detailVisible = Boolean(
showDetail && detailItem && detailItem.source !== "path",
);
const fixedLeft = anchorViewport.left;
const fixedLineTop = anchorViewport.top;
const fixedLineBottom = anchorViewport.bottom;
const viewportPadding = 8;
const anchorGap = 8;
const clampViewport = resolveAutocompleteClampViewport(containerRef?.current ?? null);
const availableWidth = Math.max(0, clampViewport.width - viewportPadding * 2);
const estimatedPopupHeight = Math.min(maxHeight, suggestions.length * 28 + 8);
// Reserve the detail height for the whole set (not the hovered row) so the
// chosen direction/height stays stable while hovering.
const estimatedDetailHeight = setMayShowDetailPanel ? 96 : 0;
const desiredContentHeight = Math.max(estimatedPopupHeight, estimatedDetailHeight);
// Total horizontal extent so the WHOLE assembly is clamped inside the
// viewport — not just the main list. Mirrors the rendered maxWidths:
// main list (400) + each cascading sub-dir panel (240) + the detail
// tooltip (280), separated by the flex gap (4). Without this, expanding a
// directory near the right edge pushed the sub-panels off-screen (#1202).
const FLEX_GAP = 4;
const MAIN_LIST_MAX_WIDTH = 400;
const SUBDIR_PANEL_MAX_WIDTH = 240;
const DETAIL_PANEL_MAX_WIDTH = 280;
const totalWidth =
MAIN_LIST_MAX_WIDTH +
subDirPanels.length * (FLEX_GAP + SUBDIR_PANEL_MAX_WIDTH) +
(setMayShowDetailPanel ? FLEX_GAP + DETAIL_PANEL_MAX_WIDTH : 0);
const clampWidth =
MAIN_LIST_MAX_WIDTH +
subDirPanels.length * (FLEX_GAP + SUBDIR_PANEL_MAX_WIDTH);
const placement = computeAutocompletePopupPlacement({
anchorTop: fixedLineTop,
anchorBottom: fixedLineBottom,
anchorLeft: fixedLeft,
viewportWidth: clampViewport.width,
viewportHeight: clampViewport.height,
clampViewport,
desiredHeight: desiredContentHeight,
totalWidth,
clampWidth,
maxHeight,
anchorGap,
viewportPadding,
expandUpwardHint: expandUpward,
forceExpandUpward: expandUpward,
});
const renderUpward = placement.renderUpward;
const effectiveMaxHeight = placement.maxHeight;
// Fixed tooltip height: matches the 96px the placement pass reserved
// (estimatedDetailHeight), capped by the space actually available so the
// mounted-but-hidden panel can never push the wrapper past the clamp.
const detailPanelHeight = Math.max(0, Math.min(96, effectiveMaxHeight));
const anchoredTop = placement.top;
const clampedLeft = placement.left;
const finalGeometry = measuredSize
? clampAutocompletePopupGeometry({
left: clampedLeft,
top: anchoredTop,
width: measuredSize.width,
height: measuredSize.height,
clampViewport,
viewportPadding,
})
: { left: clampedLeft, top: anchoredTop };
const sharedBoxStyle = {
// border-box so each panel's maxWidth is its true outer width (padding +
// border included). The horizontal clamp's totalWidth sums these maxWidths,
// so this keeps the off-screen math exact even for the padded detail panel.
boxSizing: "border-box" as const,
backgroundColor: popupBg,
border: `1px solid ${popupBorder}`,
borderRadius: "6px",
boxShadow: renderUpward
? "0 -2px 6px rgba(0, 0, 0, 0.15)"
: "0 2px 6px rgba(0, 0, 0, 0.15)",
fontFamily: "inherit",
fontSize: "13px",
color: textColor,
overscrollBehavior: "contain" as const,
};
// Keep terminal focus when clicking a panel's padding, but leave the native
// scrollbar alone so its thumb can still be dragged. `preventDefault()` on
// the scrollbar mousedown made the right-side detail panel impossible to
// scroll by dragging.
const handlePanelMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
event.stopPropagation();
const element = event.currentTarget;
const rect = element.getBoundingClientRect();
const scrollbarWidth = Math.max(16, element.offsetWidth - element.clientWidth);
const overVerticalScrollbar = event.clientX >= rect.right - scrollbarWidth;
if (!overVerticalScrollbar) event.preventDefault();
};
const handlePanelWheel = (event: React.WheelEvent<HTMLDivElement>) => {
// Keep wheel scrolling inside the popup instead of letting it reach the
// terminal's history/font-size handlers.
event.stopPropagation();
};
// Keep every inline description starting at the same x. The option column is
// sized from the longest suggestion in this popup, capped so descriptions
// still get useful width in a narrow terminal pane.
const longestCommandLength = suggestions.reduce(
(max, suggestion) => Math.max(max, suggestion.displayText.length),
0,
);
const commandColumnWidth = Math.max(
52,
Math.min(150, longestCommandLength * 7 + 12, availableWidth * 0.42),
);
return (
<div
ref={wrapperRef}
style={{
position: "fixed",
left: `${finalGeometry.left}px`,
top: `${finalGeometry.top}px`,
zIndex: 10000,
display: "flex",
maxWidth: `${availableWidth}px`,
alignItems: renderUpward ? "flex-end" : "flex-start",
gap: "4px",
// Hit-test transparent: the wrapper's box spans the whole assembly,
// including the mounted-but-hidden detail reserve, so leaving it
// auto would make the transparent area around a short list a dead
// zone (clicks there preventDefault + stopPropagation and never
// reach the terminal or the outside-dismiss handler). Children
// re-enable pointer events individually. (#3427 review)
pointerEvents: "none",
}}
>
{/* Main suggestion list */}
<div
ref={listRef}
className="xterm-autocomplete-popup"
style={{
...sharedBoxStyle,
maxHeight: `${effectiveMaxHeight}px`,
minWidth: `${Math.min(180, setMayShowDetailPanel ? availableWidth / 2 : availableWidth)}px`,
maxWidth: "400px",
overflowY: "auto",
overflowX: "hidden",
padding: "4px 0",
userSelect: "none",
pointerEvents: "auto",
}}
// Keep the terminal focused when clicking the list's padding or
// scrollbar; scrollbar dragging is left to the browser.
onMouseDown={handlePanelMouseDown}
onWheel={handlePanelWheel}
>
{suggestions.map((suggestion, index) => {
const isSelected = index === selectedIndex;
const isHovered = index === hoveredIndex;
const sourceInfo = SOURCE_LABELS[suggestion.source];
const hasInlineDescription = suggestion.source !== "snippet"
&& Boolean(suggestion.description);
return (
<div
key={`${suggestion.text}-${index}`}
ref={isSelected ? selectedRef : undefined}
style={{
display: "flex",
alignItems: "center",
padding: "5px 10px",
cursor: "pointer",
backgroundColor: isSelected ? selectedBg : isHovered ? hoverBg : "transparent",
// Accent rail on the active row so the highlight reads as the
// theme accent. Inset shadow avoids shifting row layout.
boxShadow: isSelected ? `inset 2px 0 0 0 ${selectedBorderAccent}` : undefined,
gap: "8px",
lineHeight: "1.4",
}}
onMouseEnter={() => {
cancelHoverClear();
setHoveredIndex(index);
}}
onMouseLeave={scheduleHoverClear}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
onSelect(suggestion);
}}
>
{/* Source / file type indicator */}
{suggestion.source === "path" && suggestion.fileType ? (
<FileTypeIcon fileType={suggestion.fileType} />
) : (
<span
role="img"
aria-label={sourceInfo.fullLabel}
title={sourceInfo.fullLabel}
style={{
width: "18px",
height: "18px",
borderRadius: "3px",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "10px",
fontWeight: 600,
color: sourceInfo.fallbackColor,
backgroundColor: `${sourceInfo.fallbackColor}15`,
flexShrink: 0,
}}
>
{sourceInfo.label}
</span>
)}
{/* Command text. A shared fixed column keeps every description
aligned on the same left edge instead of following each
variable-width option label. */}
<span
title={hasInlineDescription ? suggestion.displayText : undefined}
style={{
flex: hasInlineDescription ? "0 0 auto" : "1 1 auto",
width: hasInlineDescription ? `${commandColumnWidth}px` : undefined,
minWidth: 0,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
color: textColor,
fontWeight: isSelected ? 500 : 400,
}}
>
{suggestion.displayText}
</span>
{/* Inline description (truncated). Snippets show only their label
in the row — the full command lives in the detail preview. */}
{hasInlineDescription && (
<span
style={{
flex: "1 1 auto",
minWidth: 0,
fontSize: "11px",
color: dimTextColor,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{suggestion.description}
</span>
)}
{/* Frequency badge for history */}
{suggestion.frequency && suggestion.frequency > 1 && (
<span
style={{
fontSize: "10px",
color: dimTextColor,
flexShrink: 0,
}}
>
×{suggestion.frequency}
</span>
)}
{/* Expand indicator for directories */}
{suggestion.source === "path" && suggestion.fileType === "directory" && (
<DirExpandIndicator visible={isSelected || isHovered} color={dimTextColor} />
)}
{/* Key hint on the selected row: → expands directories, ↵ runs. */}
{isSelected && (
<span style={{ display: "flex", gap: "3px", marginLeft: "4px", flexShrink: 0 }}>
{suggestion.source === "path" && suggestion.fileType === "directory" && (
<KeyCap label="→" color={dimTextColor} bg={popupBg} />
)}
<KeyCap label="⏎" color={dimTextColor} bg={popupBg} />
</span>
)}
</div>
);
})}
</div>
{/* Cascading sub-directory panels */}
{subDirPanels.map((panel, level) => (
<div
key={panel.dirPath}
style={{
...sharedBoxStyle,
maxHeight: `${effectiveMaxHeight}px`,
minWidth: "150px",
maxWidth: "240px",
overflowY: "auto",
overflowX: "hidden",
padding: "4px 0",
userSelect: "none",
alignSelf: "flex-start",
pointerEvents: "auto",
}}
// Keep the terminal focused when clicking the panel's padding or
// scrollbar; scrollbar dragging is left to the browser.
onMouseDown={handlePanelMouseDown}
onWheel={handlePanelWheel}
>
{panel.entries.map((entry, idx) => {
const isFocused = level === subDirFocusLevel;
const isSubSelected = isFocused && idx === panel.selectedIndex;
return (
<div
key={entry.name}
ref={isSubSelected ? (el) => { el?.scrollIntoView({ block: "nearest" }); } : undefined}
style={{
display: "flex",
alignItems: "center",
padding: "4px 10px",
cursor: "pointer",
backgroundColor: isSubSelected ? selectedBg
: (idx === panel.selectedIndex && level < subDirFocusLevel) ? hoverBg
: "transparent",
boxShadow: isSubSelected ? `inset 2px 0 0 0 ${selectedBorderAccent}` : undefined,
gap: "8px",
lineHeight: "1.4",
}}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
<FileTypeIcon fileType={entry.type} />
<span style={{
flex: 1, overflow: "hidden", textOverflow: "ellipsis",
whiteSpace: "nowrap", color: textColor,
}}>
{entry.name}{entry.type === "directory" ? "/" : ""}
</span>
{entry.type === "directory" && (
<DirExpandIndicator visible={isSubSelected || (idx === panel.selectedIndex && level < subDirFocusLevel)} color={dimTextColor} />
)}
</div>
);
})}
</div>
))}
{/* Detail tooltip panel — shows full description for non-path items.
Mounted for the whole set with a fixed, hover-independent box and
toggled via visibility so hovering rows can never resize (and thus
re-clamp the position of) the popup (#3426). */}
{setMayShowDetailPanel && (
<div
style={{
...sharedBoxStyle,
padding: "10px 12px",
width: "280px",
minWidth: 0,
height: `${detailPanelHeight}px`,
// The width remains independent of content/hover, but can shrink
// with the assembly inside a narrow terminal pane.
flexShrink: 1,
// Bound the tooltip too: a long multi-line snippet description must
// scroll, not push the panel past the viewport edge (#1202).
overflowY: "auto",
alignSelf: renderUpward ? "flex-end" : "flex-start",
visibility: detailVisible ? "visible" : "hidden",
// The detail text can be selected and copied; use text cursor and
// native selection instead of forcing terminal focus.
userSelect: "text",
cursor: "text",
// visibility:hidden already skips hit testing, but keep the
// hidden reserve explicitly non-interactive so the mounted
// panel can never swallow clicks meant for the terminal.
pointerEvents: detailVisible ? "auto" : "none",
}}
onMouseDown={(event) => {
// Do not preventDefault: that would block selecting the long
// description or dragging the panel's scrollbar.
event.stopPropagation();
}}
onMouseEnter={cancelHoverClear}
onMouseLeave={scheduleHoverClear}
onWheel={handlePanelWheel}
>
{detailVisible && detailItem && (
<>
<div style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "6px" }}>
<span style={{ fontWeight: 600, fontSize: "13px" }}>{detailItem.displayText}</span>
<span style={{
fontSize: "10px",
color: SOURCE_LABELS[detailItem.source].fallbackColor,
padding: "1px 5px",
borderRadius: "3px",
backgroundColor: `${SOURCE_LABELS[detailItem.source].fallbackColor}15`,
}}>
{SOURCE_LABELS[detailItem.source].fullLabel}
</span>
</div>
<div style={{ fontSize: "12px", color: dimTextColor, lineHeight: "1.5", wordBreak: "break-word" }}>
{detailItem.source === "snippet" ? (
<pre
style={{
margin: 0,
whiteSpace: "pre-wrap",
wordBreak: "break-word",
fontFamily: "var(--terminal-font, monospace)",
fontSize: "11px",
lineHeight: 1.4,
}}
>
{detailItem.description}
</pre>
) : (
detailItem.description
)}
</div>
</>
)}
</div>
)}
</div>
);
};
export default memo(AutocompletePopup);