Files
paperclip/ui/src/components/InlineEntitySelector.tsx
T
Dotta d0bdbe11a9 Stabilize inline selector keyboard handling (#4617)
## Thinking Path

> - Paperclip's board UI relies on compact selectors for frequent issue
and agent edits.
> - Inline selectors often live inside larger keyboard-aware surfaces
such as composers and popovers.
> - Arrow, enter, tab, and escape keys handled by the selector should
not leak to parent document shortcuts.
> - Stale company selection should also stay hidden until the company
list confirms it is valid.
> - This pull request tightens inline selector keyboard handling and
adds regression coverage for stale company bootstrap behavior.
> - The benefit is fewer accidental parent interactions and safer
company-scoped UI initialization.

## What Changed

- Added a stable empty `recentOptionIds` default so selector filtering
does not get a new array every render.
- Mirrored highlighted option state into a ref so Enter/Tab commits the
current highlighted option reliably after keyboard navigation.
- Stopped propagation for selector-owned navigation/commit/escape keys.
- Added jsdom regressions for inline selector keyboard handling and
CompanyProvider stale selection behavior.

## Verification

- `pnpm exec vitest run ui/src/components/InlineEntitySelector.test.tsx
ui/src/context/CompanyContext.test.tsx`
- Targeted selector and CompanyProvider tests pass cleanly without React
`act(...)` warnings.
- Screenshots not attached: this is keyboard/state behavior covered by
component tests.

## Risks

- Low risk: changes are scoped to inline selector key handling and
tests. The main behavior shift is intentionally preventing handled
selector keys from reaching parent listeners.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex coding agent based on GPT-5, tool-enabled local
repository and shell access, Paperclip heartbeat context.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-04-27 20:04:35 -05:00

229 lines
8.6 KiB
TypeScript

import { forwardRef, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Check } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { orderItemsBySelectedAndRecent } from "../lib/recent-selections";
import { cn } from "../lib/utils";
export interface InlineEntityOption {
id: string;
label: string;
searchText?: string;
}
interface InlineEntitySelectorProps {
value: string;
options: InlineEntityOption[];
placeholder: string;
noneLabel: string;
searchPlaceholder: string;
emptyMessage: string;
onChange: (id: string) => void;
onConfirm?: () => void;
className?: string;
renderTriggerValue?: (option: InlineEntityOption | null) => ReactNode;
renderOption?: (option: InlineEntityOption, isSelected: boolean) => ReactNode;
recentOptionIds?: string[];
/** Skip the Portal so the popover stays in the DOM tree (fixes scroll inside Dialogs). */
disablePortal?: boolean;
/** Open the popover when the trigger receives keyboard/programmatic focus. */
openOnFocus?: boolean;
}
const EMPTY_RECENT_OPTION_IDS: string[] = [];
export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySelectorProps>(
function InlineEntitySelector(
{
value,
options,
placeholder,
noneLabel,
searchPlaceholder,
emptyMessage,
onChange,
onConfirm,
className,
renderTriggerValue,
renderOption,
recentOptionIds = EMPTY_RECENT_OPTION_IDS,
disablePortal,
openOnFocus = true,
},
ref,
) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [highlightedIndex, setHighlightedIndex] = useState(0);
const highlightedIndexRef = useRef(0);
const inputRef = useRef<HTMLInputElement>(null);
const shouldPreventCloseAutoFocusRef = useRef(false);
const isPointerDownRef = useRef(false);
const allOptions = useMemo<InlineEntityOption[]>(() => {
const baseOptions = [{ id: "", label: noneLabel, searchText: noneLabel }, ...options];
return orderItemsBySelectedAndRecent(baseOptions, value, recentOptionIds);
}, [noneLabel, options, recentOptionIds, value]);
const filteredOptions = useMemo(() => {
const term = query.trim().toLowerCase();
if (!term) return allOptions;
return allOptions.filter((option) => {
const haystack = `${option.label} ${option.searchText ?? ""}`.toLowerCase();
return haystack.includes(term);
});
}, [allOptions, query]);
const currentOption = options.find((option) => option.id === value) ?? null;
const setHighlightedIndexValue = useCallback((next: number | ((current: number) => number)) => {
const resolved = typeof next === "function" ? next(highlightedIndexRef.current) : next;
highlightedIndexRef.current = resolved;
setHighlightedIndex(resolved);
}, []);
useEffect(() => {
if (!open) return;
const selectedIndex = filteredOptions.findIndex((option) => option.id === value);
setHighlightedIndexValue(selectedIndex >= 0 ? selectedIndex : 0);
}, [filteredOptions, open, setHighlightedIndexValue, value]);
const commitSelection = (index: number, moveNext: boolean) => {
const option = filteredOptions[index] ?? filteredOptions[0];
if (option) onChange(option.id);
shouldPreventCloseAutoFocusRef.current = moveNext;
setOpen(false);
setQuery("");
if (moveNext && onConfirm) {
requestAnimationFrame(() => {
onConfirm();
});
}
};
return (
<Popover
open={open}
onOpenChange={(next) => {
setOpen(next);
if (!next) setQuery("");
}}
>
<PopoverTrigger asChild>
<button
ref={ref}
type="button"
className={cn(
"inline-flex min-w-0 items-center gap-1 rounded-md border border-border bg-muted/40 px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
onPointerDown={() => { isPointerDownRef.current = true; }}
onFocus={() => {
if (openOnFocus && !isPointerDownRef.current) setOpen(true);
isPointerDownRef.current = false;
}}
>
{renderTriggerValue
? renderTriggerValue(currentOption)
: (currentOption?.label ?? <span className="text-muted-foreground">{placeholder}</span>)}
</button>
</PopoverTrigger>
<PopoverContent
align="start"
side="bottom"
collisionPadding={16}
className="w-[min(20rem,calc(100vw-2rem))] p-1"
disablePortal={disablePortal}
onOpenAutoFocus={(event) => {
event.preventDefault();
// On touch devices, don't auto-focus the search input to avoid
// opening the virtual keyboard which reshapes the viewport and
// pushes the popover off-screen.
const isTouch = typeof window.matchMedia === "function"
? window.matchMedia("(pointer: coarse)").matches
: false;
if (!isTouch) {
inputRef.current?.focus();
}
}}
onCloseAutoFocus={(event) => {
if (!shouldPreventCloseAutoFocusRef.current) return;
event.preventDefault();
shouldPreventCloseAutoFocusRef.current = false;
}}
>
<input
ref={inputRef}
className="w-full border-b border-border bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground/60"
placeholder={searchPlaceholder}
value={query}
onChange={(event) => {
setQuery(event.target.value);
}}
onKeyDown={(event) => {
if (event.key === "ArrowDown") {
event.preventDefault();
event.stopPropagation();
setHighlightedIndexValue((current) =>
filteredOptions.length === 0 ? 0 : (current + 1) % filteredOptions.length,
);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
event.stopPropagation();
setHighlightedIndexValue((current) => {
if (filteredOptions.length === 0) return 0;
return current <= 0 ? filteredOptions.length - 1 : current - 1;
});
return;
}
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitSelection(highlightedIndexRef.current, true);
return;
}
if (event.key === "Tab" && !event.shiftKey) {
event.preventDefault();
event.stopPropagation();
commitSelection(highlightedIndexRef.current, true);
return;
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setOpen(false);
}
}}
/>
<div className="max-h-56 overflow-y-auto overscroll-contain py-1 touch-pan-y">
{filteredOptions.length === 0 ? (
<p className="px-2 py-2 text-xs text-muted-foreground">{emptyMessage}</p>
) : (
filteredOptions.map((option, index) => {
const isSelected = option.id === value;
const isHighlighted = index === highlightedIndex;
return (
<button
key={option.id || "__none__"}
type="button"
className={cn(
"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm touch-manipulation",
isHighlighted && "bg-accent",
)}
onMouseEnter={() => setHighlightedIndexValue(index)}
onClick={() => commitSelection(index, true)}
>
{renderOption ? renderOption(option, isSelected) : <span className="truncate">{option.label}</span>}
<Check className={cn("ml-auto h-3.5 w-3.5 text-muted-foreground", isSelected ? "opacity-100" : "opacity-0")} />
</button>
);
})
)}
</div>
</PopoverContent>
</Popover>
);
},
);