mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-17 05:20:55 +00:00
📜 refactor: Move the Prompts Popover Into the Chat Package (#17670)
* refactor: Move the Prompts Popover Into the Chat Package * test: Check Dialog Focus Without Querying the Hidden Composer * fix: Keep the Search Typed After the Slash When the Prompts Popover Opens
This commit is contained in:
parent
222a369c60
commit
9c83beea0e
7 changed files with 405 additions and 210 deletions
|
|
@ -1,17 +1,10 @@
|
|||
import { useState, useRef, useEffect, useMemo, memo, useCallback } from 'react';
|
||||
import { AutoSizer, List } from 'react-virtualized';
|
||||
import { MentionItem } from '@librechat/chat/components';
|
||||
import { useState, useEffect, useMemo, memo, useCallback } from 'react';
|
||||
import { useToastContext } from '@librechat/client';
|
||||
import { useSetRecoilState, useRecoilValue } from 'recoil';
|
||||
import { useInitPopoverInput } from '@librechat/chat/react';
|
||||
import { Input, Spinner, useCombobox, useRemScale, useToastContext } from '@librechat/client';
|
||||
import { PromptsPopover } from '@librechat/chat/components';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import type { PromptOption } from '~/common';
|
||||
import {
|
||||
removeCharIfLast,
|
||||
detectVariables,
|
||||
isExternalPromptGroup,
|
||||
getPromptResolveErrorMessage,
|
||||
} from '~/utils';
|
||||
import { detectVariables, isExternalPromptGroup, getPromptResolveErrorMessage } from '~/utils';
|
||||
import { activateCatalog, useLocalize, usePromptContentResolver } from '~/hooks';
|
||||
import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest';
|
||||
import { useRecordPromptUsage } from '~/data-provider';
|
||||
|
|
@ -19,8 +12,6 @@ import { VariableDialog } from '~/components/Prompts';
|
|||
import { usePromptGroupsContext } from '~/Providers';
|
||||
import store from '~/store';
|
||||
|
||||
const commandChar = '/';
|
||||
|
||||
const PopoverContainer = memo(
|
||||
({
|
||||
index,
|
||||
|
|
@ -59,8 +50,6 @@ const PopoverContainer = memo(
|
|||
},
|
||||
);
|
||||
|
||||
const ROW_HEIGHT = 44;
|
||||
|
||||
function PromptsCommand({
|
||||
index,
|
||||
textAreaRef,
|
||||
|
|
@ -71,7 +60,6 @@ function PromptsCommand({
|
|||
submitPrompt: (textPrompt: string) => void;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const remScale = useRemScale();
|
||||
const { showToast } = useToastContext();
|
||||
const { mutate: recordUsage } = useRecordPromptUsage();
|
||||
const resolvePromptContent = usePromptContentResolver();
|
||||
|
|
@ -80,9 +68,6 @@ function PromptsCommand({
|
|||
const { data, isLoading } = allPromptGroups ?? {};
|
||||
const showPromptsPopover = useRecoilValue(store.showPromptsPopoverFamily(index));
|
||||
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [isVariableDialogOpen, setVariableDialogOpen] = useState(false);
|
||||
const [variableGroup, setVariableGroup] = useState<TPromptGroup | null>(null);
|
||||
const [variableText, setVariableText] = useState<string | undefined>(undefined);
|
||||
|
|
@ -99,33 +84,8 @@ function PromptsCommand({
|
|||
const prompts = useMemo(() => data?.promptGroups, [data]);
|
||||
const promptsMap = useMemo(() => data?.promptsMap, [data]);
|
||||
|
||||
const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
|
||||
value: '',
|
||||
options: prompts ?? [],
|
||||
});
|
||||
|
||||
const initInputRef = useInitPopoverInput({
|
||||
inputRef,
|
||||
textAreaRef,
|
||||
commandChar,
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
});
|
||||
|
||||
const handleSelect = useCallback(
|
||||
async (mention?: PromptOption, e?: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (!mention) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSearchValue('');
|
||||
setOpen(false);
|
||||
setShowPromptsPopover(false);
|
||||
|
||||
if (textAreaRef.current) {
|
||||
removeCharIfLast(textAreaRef.current, commandChar);
|
||||
}
|
||||
|
||||
async (mention: PromptOption, e?: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
const group = promptsMap?.[mention.id];
|
||||
if (!group) {
|
||||
return;
|
||||
|
|
@ -180,9 +140,6 @@ function PromptsCommand({
|
|||
}
|
||||
},
|
||||
[
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
setShowPromptsPopover,
|
||||
textAreaRef,
|
||||
promptsMap,
|
||||
submitPrompt,
|
||||
|
|
@ -196,17 +153,15 @@ function PromptsCommand({
|
|||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleOpenChange = useCallback((open: boolean) => {
|
||||
if (!open) {
|
||||
setActiveIndex(0);
|
||||
setSearchValue('');
|
||||
} else {
|
||||
/** Opening the picker before background warmup starts the fetch now */
|
||||
activateCatalog('prompts');
|
||||
setVariableGroup(null);
|
||||
setVariableText(undefined);
|
||||
return;
|
||||
}
|
||||
}, [open, setSearchValue]);
|
||||
/** Opening the picker before background warmup starts the fetch now */
|
||||
activateCatalog('prompts');
|
||||
setVariableGroup(null);
|
||||
setVariableText(undefined);
|
||||
}, []);
|
||||
|
||||
/** The full prompt list is fetched on first popover open, not at app startup */
|
||||
useEffect(() => {
|
||||
|
|
@ -215,58 +170,10 @@ function PromptsCommand({
|
|||
}
|
||||
}, [showPromptsPopover, requestAllPromptGroups]);
|
||||
|
||||
useEffect(() => {
|
||||
setActiveIndex((prev) => Math.min(prev, Math.max(matches.length - 1, 0)));
|
||||
}, [matches.length]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const currentActiveItem = document.getElementById(`prompt-item-${activeIndex}`);
|
||||
currentActiveItem?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
|
||||
}, [activeIndex]);
|
||||
|
||||
if (!hasAccess) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rowRenderer = ({
|
||||
index,
|
||||
key,
|
||||
style,
|
||||
}: {
|
||||
index: number;
|
||||
key: string;
|
||||
style: React.CSSProperties;
|
||||
}) => {
|
||||
const mention = matches[index] as PromptOption;
|
||||
return (
|
||||
<MentionItem
|
||||
index={index}
|
||||
type="prompt"
|
||||
key={key}
|
||||
style={style}
|
||||
onClick={() => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
timeoutRef.current = null;
|
||||
handleSelect(mention);
|
||||
}}
|
||||
name={mention.label ?? ''}
|
||||
icon={mention.icon}
|
||||
description={mention.description}
|
||||
isActive={index === activeIndex}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<PopoverContainer
|
||||
index={index}
|
||||
|
|
@ -276,82 +183,15 @@ function PromptsCommand({
|
|||
setVariableDialogOpen={setVariableDialogOpen}
|
||||
textAreaRef={textAreaRef}
|
||||
>
|
||||
<div className="absolute bottom-28 z-10 w-full space-y-2">
|
||||
<div className="popover border-border-light bg-surface-tertiary-alt rounded-theme-popover border p-2 shadow-lg">
|
||||
<Input
|
||||
ref={initInputRef}
|
||||
placeholder={localize('com_ui_command_usage_placeholder')}
|
||||
variant="embedded"
|
||||
className="mb-1"
|
||||
autoComplete="off"
|
||||
value={searchValue}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
setOpen(false);
|
||||
setShowPromptsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
}
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (matches.length === 0) {
|
||||
return;
|
||||
}
|
||||
setActiveIndex((prevIndex) => (prevIndex + 1) % matches.length);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
if (matches.length === 0) {
|
||||
return;
|
||||
}
|
||||
setActiveIndex((prevIndex) => (prevIndex - 1 + matches.length) % matches.length);
|
||||
} else if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
if (matches.length === 0) {
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
setShowPromptsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
handleSelect(matches[activeIndex] as PromptOption | undefined, e);
|
||||
} else if (e.key === 'Backspace' && searchValue === '') {
|
||||
setOpen(false);
|
||||
setShowPromptsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onFocus={() => setOpen(true)}
|
||||
onBlur={() => {
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setOpen(false);
|
||||
setShowPromptsPopover(false);
|
||||
}, 150);
|
||||
}}
|
||||
/>
|
||||
{open && isLoading && matches.length === 0 && (
|
||||
<div className="text-text-primary flex h-32 items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{open && matches.length > 0 && (
|
||||
<div className="max-h-40">
|
||||
<AutoSizer disableHeight>
|
||||
{({ width }) => (
|
||||
<List
|
||||
width={width}
|
||||
overscanRowCount={5}
|
||||
rowHeight={ROW_HEIGHT * remScale}
|
||||
rowCount={matches.length}
|
||||
rowRenderer={rowRenderer}
|
||||
scrollToIndex={activeIndex}
|
||||
height={Math.min(matches.length * ROW_HEIGHT, 160) * remScale}
|
||||
/>
|
||||
)}
|
||||
</AutoSizer>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<PromptsPopover
|
||||
textAreaRef={textAreaRef}
|
||||
placeholder={localize('com_ui_command_usage_placeholder')}
|
||||
prompts={prompts ?? []}
|
||||
isLoading={isLoading === true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSelectPrompt={handleSelect}
|
||||
onClose={() => setShowPromptsPopover(false)}
|
||||
/>
|
||||
</PopoverContainer>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -92,31 +92,6 @@ jest.mock('~/hooks', () => ({
|
|||
usePromptContentResolver: () => mockResolve,
|
||||
}));
|
||||
|
||||
/* react-virtualized renders nothing in jsdom without a measured size; replace
|
||||
AutoSizer + List with a flat ul so every row's MentionItem button renders. */
|
||||
jest.mock('react-virtualized', () => ({
|
||||
...jest.requireActual('react-virtualized'),
|
||||
AutoSizer: ({ children }: { children: (size: { width: number }) => React.ReactNode }) =>
|
||||
children({ width: 320 }),
|
||||
List: ({
|
||||
rowCount,
|
||||
rowRenderer,
|
||||
}: {
|
||||
rowCount: number;
|
||||
rowRenderer: (args: {
|
||||
index: number;
|
||||
key: string;
|
||||
style: React.CSSProperties;
|
||||
}) => React.ReactNode;
|
||||
}) => {
|
||||
const rows: React.ReactNode[] = [];
|
||||
for (let i = 0; i < rowCount; i++) {
|
||||
rows.push(rowRenderer({ index: i, key: `row-${i}`, style: {} }));
|
||||
}
|
||||
return <ul data-testid="prompts-list">{rows}</ul>;
|
||||
},
|
||||
}));
|
||||
|
||||
import PromptsCommand from '../PromptsCommand';
|
||||
|
||||
const makeTextarea = (initial = '/') => {
|
||||
|
|
@ -236,14 +211,14 @@ describe('PromptsCommand keyboard navigation', () => {
|
|||
const input = getInput();
|
||||
|
||||
fireEvent.change(input, { target: { value: 'zzz' } });
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(screen.queryByRole('option')).toBeNull();
|
||||
|
||||
/* Arrow keys on an empty list must be no-ops, not `% 0` -> NaN. */
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
fireEvent.keyDown(input, { key: 'ArrowUp' });
|
||||
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
expect(screen.getAllByRole('button')).toHaveLength(2);
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2);
|
||||
|
||||
/* Without the guard the active index would still be NaN here and no
|
||||
item would highlight; with it, navigation resumes from a valid index. */
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
export { removeCharIfLast } from '@librechat/chat';
|
||||
|
||||
/**
|
||||
* Insert text at the cursor position in a textarea.
|
||||
*/
|
||||
|
|
|
|||
141
e2e/specs/mock/scenarios/composer-prompts.spec.ts
Normal file
141
e2e/specs/mock/scenarios/composer-prompts.spec.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import {
|
||||
MOCK_ENDPOINTS,
|
||||
NEW_CHAT_PATH,
|
||||
messagesView,
|
||||
requestJson,
|
||||
getAccessToken,
|
||||
selectMockEndpoint,
|
||||
} from '../helpers';
|
||||
|
||||
/**
|
||||
* The `/` prompts popover, drawn by the chat package's command popover: a combobox over the
|
||||
* user's prompts that sends a plain prompt on pick and asks for the variables of one that has
|
||||
* them, keeping focus in that dialog when the pick was made with Tab.
|
||||
*/
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
type CreatedGroup = { group?: { _id?: string } };
|
||||
|
||||
async function createPrompt(page: Page, name: string, prompt: string): Promise<string> {
|
||||
const token = await getAccessToken(page);
|
||||
const body = await requestJson<CreatedGroup>(page, {
|
||||
path: '/api/prompts',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: { prompt: { prompt, type: 'text' }, group: { name, category: 'e2e' } },
|
||||
});
|
||||
const id = body.group?._id ?? '';
|
||||
expect(id).not.toBe('');
|
||||
return id;
|
||||
}
|
||||
|
||||
async function deletePrompt(page: Page, id: string) {
|
||||
const token = await getAccessToken(page);
|
||||
await requestJson<{ message?: string }>(page, {
|
||||
path: `/api/prompts/groups/${encodeURIComponent(id)}`,
|
||||
token,
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
async function openPrompts(page: Page) {
|
||||
const textarea = page.getByRole('textbox', { name: 'Message input' });
|
||||
await textarea.click();
|
||||
await textarea.press('/');
|
||||
const combobox = page.getByRole('combobox', { name: /Select a Prompt/ });
|
||||
await expect(combobox).toBeFocused();
|
||||
return { textarea, combobox };
|
||||
}
|
||||
|
||||
async function withPrompts(
|
||||
page: Page,
|
||||
prompts: Array<{ name: string; text: string }>,
|
||||
run: () => Promise<void>,
|
||||
) {
|
||||
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
|
||||
const ids: string[] = [];
|
||||
try {
|
||||
for (const { name, text } of prompts) {
|
||||
ids.push(await createPrompt(page, name, text));
|
||||
}
|
||||
await page.reload();
|
||||
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
|
||||
await run();
|
||||
} finally {
|
||||
for (const id of ids) {
|
||||
await deletePrompt(page, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('prompts popover', () => {
|
||||
test('keyboard moves and announces the active prompt @scenario:prompts-popover-keyboard-combobox', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const tag = `${testInfo.project.name}-${Date.now()}`;
|
||||
await withPrompts(
|
||||
page,
|
||||
[
|
||||
{ name: `e2e-alpha-${tag}`, text: 'Alpha prompt text' },
|
||||
{ name: `e2e-beta-${tag}`, text: 'Beta prompt text' },
|
||||
],
|
||||
async () => {
|
||||
const { textarea, combobox } = await openPrompts(page);
|
||||
await combobox.fill(`e2e-`);
|
||||
await expect(combobox).toHaveAttribute('aria-expanded', 'true');
|
||||
const listbox = page.locator(`[id="${await combobox.getAttribute('aria-controls')}"]`);
|
||||
await expect(listbox.getByRole('option')).not.toHaveCount(0);
|
||||
await expect(combobox).toHaveAttribute('aria-activedescendant', 'prompt-item-0');
|
||||
|
||||
await combobox.press('ArrowDown');
|
||||
await expect(combobox).toHaveAttribute('aria-activedescendant', 'prompt-item-1');
|
||||
await expect(page.locator('[id="prompt-item-1"]')).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
await combobox.press('Escape');
|
||||
await expect(page.getByRole('combobox', { name: /Select a Prompt/ })).toHaveCount(0);
|
||||
await expect(textarea).toBeFocused();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('a plain prompt picked with Enter is sent @scenario:prompts-popover-sends-plain-prompt', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const name = `e2e-send-${testInfo.project.name}-${Date.now()}`;
|
||||
const text = `Summarize the e2e note ${Date.now()}`;
|
||||
await withPrompts(page, [{ name, text }], async () => {
|
||||
const { combobox } = await openPrompts(page);
|
||||
await combobox.fill(name);
|
||||
await expect(page.getByRole('option', { name })).toBeVisible();
|
||||
await combobox.press('Enter');
|
||||
|
||||
await expect(page.getByRole('combobox', { name: /Select a Prompt/ })).toHaveCount(0);
|
||||
await expect(messagesView(page)).toContainText(text, { timeout: 30000 });
|
||||
});
|
||||
});
|
||||
|
||||
test('a prompt with variables picked with Tab opens its dialog and keeps focus there @scenario:prompts-popover-variables-dialog', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const name = `e2e-vars-${testInfo.project.name}-${Date.now()}`;
|
||||
await withPrompts(
|
||||
page,
|
||||
[{ name, text: 'Write to {{recipient}} about the e2e run' }],
|
||||
async () => {
|
||||
const { combobox } = await openPrompts(page);
|
||||
await combobox.fill(name);
|
||||
await expect(page.getByRole('option', { name })).toBeVisible();
|
||||
await combobox.press('Tab');
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog).toContainText(name);
|
||||
await expect
|
||||
.poll(() => dialog.evaluate((node) => node.contains(document.activeElement)))
|
||||
.toBe(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -20,6 +20,7 @@ export type {
|
|||
export { default as StopButton } from './components/composer/StopButton';
|
||||
export { default as MentionItem } from './components/composer/MentionItem';
|
||||
export { default as MentionPopover } from './components/composer/popover/Mention';
|
||||
export { default as PromptsPopover } from './components/composer/popover/Prompts';
|
||||
export { default as CommandPopover } from './components/composer/popover/Command';
|
||||
export { default as CollapseChat } from './components/composer/CollapseChat';
|
||||
export { default as ComposerChip } from './components/composer/bar/Chip';
|
||||
|
|
@ -34,6 +35,7 @@ export {
|
|||
export type { ComposerSubmitRoute } from './components/composer/submit';
|
||||
export type { MentionItemProps } from './components/composer/MentionItem';
|
||||
export type { MentionPopoverProps } from './components/composer/popover/Mention';
|
||||
export type { PromptsPopoverProps } from './components/composer/popover/Prompts';
|
||||
export type {
|
||||
CommandOption,
|
||||
CommandPopoverProps,
|
||||
|
|
|
|||
111
packages/chat/src/components/composer/popover/Prompts.tsx
Normal file
111
packages/chat/src/components/composer/popover/Prompts.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useCombobox } from '@librechat/client';
|
||||
import type { KeyboardEvent, MutableRefObject } from 'react';
|
||||
import type { CommandOption, CommandDismissReason } from './Command';
|
||||
import { removeCharIfLast } from '../../../core/textarea';
|
||||
import useInitPopoverInput from '../../../react/popover';
|
||||
import CommandPopover from './Command';
|
||||
|
||||
const COMMAND_CHAR = '/';
|
||||
|
||||
export interface PromptsPopoverProps<T extends CommandOption> {
|
||||
textAreaRef: MutableRefObject<HTMLTextAreaElement | null>;
|
||||
/** Localized placeholder for the search field. */
|
||||
placeholder: string;
|
||||
prompts: T[];
|
||||
isLoading: boolean;
|
||||
/** The search field opened or closed; the host loads its catalog on open. */
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
/** A prompt was picked; the popover has already closed and dropped the `/`. A Tab pick passes
|
||||
* its event so the host can keep focus for a dialog that follows. */
|
||||
onSelectPrompt: (prompt: T, event?: KeyboardEvent<HTMLInputElement>) => void;
|
||||
/** Hides the popover. */
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** The `/` popover: filters the user's prompts and hands the pick to the host, which resolves
|
||||
* its text and either submits it or asks for its variables. */
|
||||
export default function PromptsPopover<T extends CommandOption>({
|
||||
textAreaRef,
|
||||
placeholder,
|
||||
prompts,
|
||||
isLoading,
|
||||
onOpenChange,
|
||||
onSelectPrompt,
|
||||
onClose,
|
||||
}: PromptsPopoverProps<T>): React.JSX.Element {
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
|
||||
value: '',
|
||||
options: prompts,
|
||||
});
|
||||
|
||||
const initInputRef = useInitPopoverInput({
|
||||
inputRef,
|
||||
textAreaRef,
|
||||
commandChar: COMMAND_CHAR,
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
});
|
||||
|
||||
const openChangeRef = useRef(onOpenChange);
|
||||
openChangeRef.current = onOpenChange;
|
||||
|
||||
/** The popover mounts closed and opens from its input's ref, which may already have moved the
|
||||
* text typed after the `/` into the search; only a real close clears it. */
|
||||
const wasOpen = useRef(false);
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
wasOpen.current = true;
|
||||
} else if (wasOpen.current) {
|
||||
wasOpen.current = false;
|
||||
setActiveIndex(0);
|
||||
setSearchValue('');
|
||||
}
|
||||
openChangeRef.current?.(open);
|
||||
}, [open, setSearchValue]);
|
||||
|
||||
const handleSelect = (prompt: CommandOption, e?: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e?.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
setSearchValue('');
|
||||
setOpen(false);
|
||||
onClose();
|
||||
if (textAreaRef.current) {
|
||||
removeCharIfLast(textAreaRef.current, COMMAND_CHAR);
|
||||
}
|
||||
onSelectPrompt(prompt as T, e);
|
||||
};
|
||||
|
||||
const handleDismiss = (reason: CommandDismissReason, e?: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (reason === 'commit') {
|
||||
e?.preventDefault();
|
||||
}
|
||||
setOpen(false);
|
||||
onClose();
|
||||
if (reason !== 'blur') {
|
||||
textAreaRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<CommandPopover
|
||||
type="prompt"
|
||||
placeholder={placeholder}
|
||||
inputRef={initInputRef}
|
||||
searchValue={searchValue}
|
||||
onSearchChange={setSearchValue}
|
||||
open={open}
|
||||
onOpen={() => setOpen(true)}
|
||||
matches={matches as CommandOption[]}
|
||||
activeIndex={activeIndex}
|
||||
onActiveIndexChange={setActiveIndex}
|
||||
isLoading={isLoading}
|
||||
onSelect={handleSelect}
|
||||
onDismiss={handleDismiss}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { PromptsPopoverProps } from '../Prompts';
|
||||
import type { CommandOption } from '../Command';
|
||||
import PromptsPopover from '../Prompts';
|
||||
|
||||
/**
|
||||
* The `/` popover's contract with its host: a pick closes the popover, drops the `/` from the
|
||||
* draft and hands the prompt over; Enter never submits the form behind it, while Tab's default is
|
||||
* left to the host, which keeps focus only when a dialog follows.
|
||||
*/
|
||||
|
||||
type Prompt = CommandOption & { id: string };
|
||||
|
||||
const prompts: Prompt[] = [
|
||||
{ id: 'g1', type: 'prompt', value: 'summarize', label: 'summarize' },
|
||||
{ id: 'g2', type: 'prompt', value: 'translate', label: 'translate' },
|
||||
];
|
||||
|
||||
beforeAll(() => {
|
||||
Element.prototype.scrollIntoView = jest.fn();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
const renderPrompts = (props: Partial<PromptsPopoverProps<Prompt>> = {}) => {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = '/';
|
||||
document.body.appendChild(textarea);
|
||||
const textAreaRef = { current: textarea };
|
||||
const onClose = jest.fn();
|
||||
const onSelectPrompt = jest.fn();
|
||||
const onOpenChange = jest.fn();
|
||||
render(
|
||||
<PromptsPopover
|
||||
textAreaRef={textAreaRef}
|
||||
placeholder="Prompts"
|
||||
prompts={prompts}
|
||||
isLoading={false}
|
||||
onClose={onClose}
|
||||
onSelectPrompt={onSelectPrompt}
|
||||
onOpenChange={onOpenChange}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
return { textarea, onClose, onSelectPrompt, onOpenChange };
|
||||
};
|
||||
|
||||
const input = () => screen.getByRole('combobox');
|
||||
|
||||
describe('PromptsPopover', () => {
|
||||
it('reports opening to the host and lists the prompts as options', () => {
|
||||
const { onOpenChange } = renderPrompts();
|
||||
|
||||
expect(onOpenChange).toHaveBeenLastCalledWith(true);
|
||||
expect(screen.getByRole('listbox', { name: 'Prompts' })).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2);
|
||||
expect(input()).toHaveAttribute('aria-activedescendant', 'prompt-item-0');
|
||||
});
|
||||
|
||||
it('keeps the text typed after the slash as the search when it opens', () => {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = '/tra';
|
||||
document.body.appendChild(textarea);
|
||||
render(
|
||||
<PromptsPopover
|
||||
textAreaRef={{ current: textarea }}
|
||||
placeholder="Prompts"
|
||||
prompts={prompts}
|
||||
isLoading={false}
|
||||
onClose={jest.fn()}
|
||||
onSelectPrompt={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(input()).toHaveValue('tra');
|
||||
expect(screen.getAllByRole('option').map((option) => option.textContent)).toEqual([
|
||||
'translate',
|
||||
]);
|
||||
expect(textarea.value).toBe('');
|
||||
});
|
||||
|
||||
it('hands an Enter pick to the host after closing, without submitting the form', () => {
|
||||
const { onClose, onSelectPrompt, textarea } = renderPrompts();
|
||||
textarea.value = 'draft /';
|
||||
|
||||
fireEvent.keyDown(input(), { key: 'ArrowDown' });
|
||||
const notPrevented = fireEvent.keyDown(input(), { key: 'Enter' });
|
||||
|
||||
expect(notPrevented).toBe(false);
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
expect(onSelectPrompt).toHaveBeenCalledWith(
|
||||
prompts[1],
|
||||
expect.objectContaining({ key: 'Enter' }),
|
||||
);
|
||||
expect(textarea.value).toBe('draft ');
|
||||
});
|
||||
|
||||
it("leaves Tab's default to the host", () => {
|
||||
const keepsFocus = jest.fn((_prompt: Prompt, event?: React.KeyboardEvent) =>
|
||||
event?.preventDefault(),
|
||||
);
|
||||
renderPrompts({ onSelectPrompt: keepsFocus });
|
||||
const { onSelectPrompt: movesOn } = renderPrompts();
|
||||
|
||||
const [first, second] = screen.getAllByRole('combobox');
|
||||
expect(fireEvent.keyDown(first, { key: 'Tab' })).toBe(false);
|
||||
expect(keepsFocus).toHaveBeenCalledWith(prompts[0], expect.anything());
|
||||
expect(fireEvent.keyDown(second, { key: 'Tab' })).toBe(true);
|
||||
expect(movesOn).toHaveBeenCalledWith(prompts[0], expect.anything());
|
||||
});
|
||||
|
||||
it('closes and refocuses the draft on Enter with no matches', () => {
|
||||
const { onClose, onSelectPrompt, textarea } = renderPrompts();
|
||||
|
||||
fireEvent.change(input(), { target: { value: 'zzz' } });
|
||||
expect(fireEvent.keyDown(input(), { key: 'Enter' })).toBe(false);
|
||||
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
expect(onSelectPrompt).not.toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(textarea);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue