From 759f6aebe512e3602cefa454714b0c0e1358cb26 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:18:05 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=84=20refactor:=20Move=20the=20Skills?= =?UTF-8?q?=20Popover=20Into=20the=20Chat=20Package=20(#17675)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/Chat/Input/SkillsCommand.tsx | 209 ++---------------- .../Input/__tests__/SkillsCommand.spec.tsx | 67 ++---- .../mock/scenarios/composer-skills.spec.ts | 136 ++++++++++++ packages/chat/src/components.ts | 5 + .../components/composer/popover/Command.tsx | 8 + .../components/composer/popover/Skills.tsx | 118 ++++++++++ .../popover/__tests__/Skills.spec.tsx | 101 +++++++++ 7 files changed, 408 insertions(+), 236 deletions(-) create mode 100644 e2e/specs/mock/scenarios/composer-skills.spec.ts create mode 100644 packages/chat/src/components/composer/popover/Skills.tsx create mode 100644 packages/chat/src/components/composer/popover/__tests__/Skills.spec.tsx diff --git a/client/src/components/Chat/Input/SkillsCommand.tsx b/client/src/components/Chat/Input/SkillsCommand.tsx index 4bab5bd81b..a27dfe77b2 100644 --- a/client/src/components/Chat/Input/SkillsCommand.tsx +++ b/client/src/components/Chat/Input/SkillsCommand.tsx @@ -1,16 +1,10 @@ -import { memo, useState, useRef, useEffect, useMemo, useCallback } from 'react'; +import { memo, useEffect, useMemo, useCallback } from 'react'; import { ScrollText } from 'lucide-react'; import { useSetRecoilState } from 'recoil'; import { useSetAtom, useAtomValue } from 'jotai'; -import { AutoSizer, List } from 'react-virtualized'; -import { MentionItem } from '@librechat/chat/components'; -import { Input, Spinner, useCombobox, useRemScale } from '@librechat/client'; +import { SkillsPopover } from '@librechat/chat/components'; import { SkillsScope, resolveAgentSkillsScope } from 'librechat-data-provider'; -import { - pendingManualSkillsByConvoId, - showSkillsPopoverFamily, - useInitPopoverInput, -} from '@librechat/chat/react'; +import { pendingManualSkillsByConvoId, showSkillsPopoverFamily } from '@librechat/chat/react'; import type { TSkillSummary } from 'librechat-data-provider'; import type { MentionOption } from '~/common'; import { useLocalize, useSkillActiveState } from '~/hooks'; @@ -19,8 +13,6 @@ import { useAgentsMapContext } from '~/Providers'; import { ephemeralAgentByConvoId } from '~/store'; import { isEphemeralAgent } from '~/common'; -const commandChar = '$'; -const ROW_HEIGHT = 44; const skillIcon = ; /** @@ -91,7 +83,6 @@ function SkillsCommandContent({ agentId?: string | null; }) { const localize = useLocalize(); - const remScale = useRemScale(); const setShowSkillsPopover = useSetAtom(showSkillsPopoverFamily(index)); const setEphemeralAgent = useSetRecoilState(ephemeralAgentByConvoId(conversationId)); const setPendingManualSkills = useSetAtom(pendingManualSkillsByConvoId(conversationId)); @@ -172,34 +163,8 @@ function SkillsCommandContent({ return options; }, [data?.pages, agentSkillIds, isActive]); - const [activeIndex, setActiveIndex] = useState(0); - const timeoutRef = useRef(null); - const inputRef = useRef(null); - - const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({ - value: '', - options: skillOptions, - }); - - const initInputRef = useInitPopoverInput({ - inputRef, - textAreaRef, - commandChar, - preserveTextAfterCursor: true, - setSearchValue, - setOpen, - }); - const handleSelect = useCallback( - (mention?: MentionOption) => { - if (!mention) { - return; - } - - setSearchValue(''); - setOpen(false); - setShowSkillsPopover(false); - + (mention: { value: string }) => { setEphemeralAgent((prev) => { if (prev?.skills) { return prev; @@ -217,161 +182,25 @@ function SkillsCommandContent({ setPendingManualSkills((prev) => prev.includes(mention.value) ? prev : [...prev, mention.value], ); - - textAreaRef.current?.focus(); }, - [ - setSearchValue, - setOpen, - setShowSkillsPopover, - textAreaRef, - setEphemeralAgent, - setPendingManualSkills, - ], + [setEphemeralAgent, setPendingManualSkills], ); - useEffect(() => { - if (!open) { - setActiveIndex(0); - } - }, [open]); - - useEffect(() => { - setActiveIndex((prev) => Math.min(prev, Math.max(matches.length - 1, 0))); - }, [matches.length]); - - useEffect(() => { - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - }; - }, []); - - useEffect(() => { - const el = document.getElementById(`skill-item-${activeIndex}`); - el?.scrollIntoView({ behavior: 'instant', block: 'nearest' }); - }, [activeIndex]); - - const rowRenderer = ({ - index, - key, - style, - }: { - index: number; - key: string; - style: React.CSSProperties; - }) => { - const mention = matches[index] as MentionOption; - return ( - { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - timeoutRef.current = null; - handleSelect(mention); - }} - name={mention.label ?? ''} - icon={mention.icon} - description={mention.description} - isActive={index === activeIndex} - /> - ); - }; - return ( -
-
- { - if (e.key === 'Escape') { - setOpen(false); - setShowSkillsPopover(false); - textAreaRef.current?.focus(); - return; - } - 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) { - if (e.key === 'Enter') { - e.preventDefault(); - } - setOpen(false); - setShowSkillsPopover(false); - textAreaRef.current?.focus(); - return; - } - e.preventDefault(); - handleSelect(matches[activeIndex] as MentionOption | undefined); - } else if (e.key === 'Backspace' && searchValue === '') { - setOpen(false); - setShowSkillsPopover(false); - textAreaRef.current?.focus(); - } - }} - onChange={(e) => setSearchValue(e.target.value)} - onFocus={() => setOpen(true)} - onBlur={() => { - timeoutRef.current = setTimeout(() => { - setOpen(false); - setShowSkillsPopover(false); - }, 150); - }} - /> - {open && (isLoading || isFetchingNextPage) && matches.length === 0 && ( -
- -
- )} - {open && isError && ( -
- {localize('com_ui_skills_load_error')} -
- )} - {open && !isLoading && !isFetchingNextPage && !isError && matches.length === 0 && ( -
- {localize(searchValue ? 'com_ui_no_skills_found' : 'com_ui_skills_empty')} -
- )} - {open && matches.length > 0 && ( -
- - {({ width }) => ( - - )} - -
- )} -
-
+ setShowSkillsPopover(false)} + /> ); } diff --git a/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx b/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx index 2cb3c0a95a..625de37872 100644 --- a/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx +++ b/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx @@ -95,31 +95,6 @@ jest.mock('@librechat/client', () => { }; }); -/* react-virtualized renders nothing in jsdom without measured size; replace - AutoSizer + List with a flat ul so row clicks are exercised normally. */ -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
    {rows}
; - }, -})); - import SkillsCommand, { filterSkillsForPopover } from '../SkillsCommand'; const makeTextarea = (initial = '$', selectionStart = initial.length) => { @@ -207,7 +182,7 @@ describe('SkillsCommand', () => { expect(textAreaRef.current).toHaveValue('Keep this draft'); expect(textAreaRef.current?.selectionStart).toBe(0); - await user.click(await screen.findByRole('button', { name: /Brand Guidelines/i })); + await user.click(await screen.findByRole('option', { name: /Brand Guidelines/i })); expect(textAreaRef.current).toHaveValue('Keep this draft'); expect(document.activeElement).toBe(textAreaRef.current); @@ -219,7 +194,7 @@ describe('SkillsCommand', () => { render(); - await user.click(await screen.findByRole('button', { name: /Brand Guidelines/i })); + await user.click(await screen.findByRole('option', { name: /Brand Guidelines/i })); expect(textAreaRef.current).toHaveValue('Keep this $'); }); @@ -243,7 +218,7 @@ describe('SkillsCommand', () => { const textAreaRef = makeTextarea('$'); render(); - const skillButton = await screen.findByRole('button', { name: /Brand Guidelines/i }); + const skillButton = await screen.findByRole('option', { name: /Brand Guidelines/i }); await act(async () => { await user.click(skillButton); }); @@ -298,8 +273,8 @@ describe('SkillsCommand', () => { ); /* Only the skill whose _id is in agent.skills should appear. */ - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(await screen.findByRole('button', { name: /Style Guide/i })).toBeInTheDocument(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(await screen.findByRole('option', { name: /Style Guide/i })).toBeInTheDocument(); }); it('shows nothing when the agent has skills_enabled:false, regardless of allowlist', () => { @@ -325,8 +300,8 @@ describe('SkillsCommand', () => { />, ); - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull(); }); it('hides all skills for a persisted agent with skills_enabled undefined (default off)', async () => { @@ -355,8 +330,8 @@ describe('SkillsCommand', () => { /* Mirrors backend `resolveAgentScopedSkillIds`: persisted agents are off by default; the builder's `skills_enabled` master toggle is the only signal that activates skills for the agent. */ - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull(); }); it('shows the full catalog for a persisted agent with skills_enabled:true and empty allowlist', async () => { @@ -382,8 +357,8 @@ describe('SkillsCommand', () => { />, ); - expect(await screen.findByRole('button', { name: /Brand Guidelines/i })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /Style Guide/i })).toBeInTheDocument(); + expect(await screen.findByRole('option', { name: /Brand Guidelines/i })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: /Style Guide/i })).toBeInTheDocument(); }); it('shows no catalog entries for an enabled authoring-only agent', () => { @@ -415,8 +390,8 @@ describe('SkillsCommand', () => { />, ); - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull(); }); it('treats an ephemeral agent id as unscoped and shows the full ACL catalog', async () => { @@ -442,8 +417,8 @@ describe('SkillsCommand', () => { /* `ephemeral` doesn't start with `agent_`, so it's an ephemeral id; scope filter should be skipped and the full catalog displayed. */ - expect(await screen.findByRole('button', { name: /Brand Guidelines/i })).toBeInTheDocument(); - expect(await screen.findByRole('button', { name: /Style Guide/i })).toBeInTheDocument(); + expect(await screen.findByRole('option', { name: /Brand Guidelines/i })).toBeInTheDocument(); + expect(await screen.findByRole('option', { name: /Style Guide/i })).toBeInTheDocument(); }); it('fails closed for persisted agents while the agents map is hydrating', async () => { @@ -471,8 +446,8 @@ describe('SkillsCommand', () => { visibility we cannot prove the persisted agent opted in, so fail closed; otherwise the user can pick a skill the backend will then refuse for the turn. */ - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull(); }); it('fails closed when the agent id is set but missing from the agents map', () => { @@ -496,8 +471,8 @@ describe('SkillsCommand', () => { />, ); - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull(); }); it('hides inactive skills from the popover', () => { @@ -514,8 +489,8 @@ describe('SkillsCommand', () => { const textAreaRef = makeTextarea('$'); render(); - expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull(); - expect(screen.getByRole('button', { name: /Style Guide/i })).toBeInTheDocument(); + expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull(); + expect(screen.getByRole('option', { name: /Style Guide/i })).toBeInTheDocument(); }); it('resumes catalog pagination after an external refetch clears an error', () => { diff --git a/e2e/specs/mock/scenarios/composer-skills.spec.ts b/e2e/specs/mock/scenarios/composer-skills.spec.ts new file mode 100644 index 0000000000..4dbe5b1efb --- /dev/null +++ b/e2e/specs/mock/scenarios/composer-skills.spec.ts @@ -0,0 +1,136 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { + MOCK_ENDPOINTS, + NEW_CHAT_PATH, + requestJson, + sendMessage, + getAccessToken, + selectMockEndpoint, +} from '../helpers'; + +/** + * The `$` skills popover, drawn by the chat package's command popover: a combobox over the + * user's skills whose pick stages the skill for the next turn instead of writing it into the + * draft, and which says so when a search matches nothing. + */ +test.describe.configure({ timeout: 120_000 }); + +type SkillSummary = { _id: string; name: string }; + +const uniqueName = (prefix: string) => + `${prefix}-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e4)}`; + +async function createSkill(page: Page, name: string): Promise { + const token = await getAccessToken(page); + const skill = await requestJson(page, { + path: '/api/skills', + token, + method: 'POST', + body: { name, description: `Composer popover skill ${name}`, body: `# ${name}\n\nE2E.` }, + }); + expect(skill._id).toBeTruthy(); + return skill._id; +} + +async function deleteSkill(page: Page, id: string) { + const token = await getAccessToken(page); + await requestJson(page, { + path: `/api/skills/${encodeURIComponent(id)}`, + token, + method: 'DELETE', + }); +} + +async function withSkills(page: Page, names: string[], run: () => Promise) { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + const ids: string[] = []; + try { + for (const name of names) { + ids.push(await createSkill(page, name)); + } + await page.reload(); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + await run(); + } finally { + for (const id of ids) { + await deleteSkill(page, id); + } + } +} + +async function openSkills(page: Page) { + const textarea = page.getByRole('textbox', { name: 'Message input' }); + await textarea.click(); + await textarea.fill(''); + await textarea.pressSequentially('$'); + const combobox = page.getByRole('combobox', { name: /Select a Skill/ }); + await expect(combobox).toBeFocused(); + return { textarea, combobox }; +} + +test.describe('skills popover', () => { + test('keyboard moves and announces the active skill @scenario:skills-popover-keyboard-combobox', async ({ + page, + }) => { + const prefix = uniqueName('e2e-kbd'); + await withSkills(page, [`${prefix}-a`, `${prefix}-b`], async () => { + const { textarea, combobox } = await openSkills(page); + await combobox.fill(prefix); + await expect(page.getByRole('option')).toHaveCount(2); + await expect(combobox).toHaveAttribute('aria-activedescendant', 'skill-item-0'); + + await combobox.press('ArrowDown'); + await expect(combobox).toHaveAttribute('aria-activedescendant', 'skill-item-1'); + await expect(page.locator('[id="skill-item-1"]')).toHaveAttribute('aria-selected', 'true'); + + await combobox.press('Escape'); + await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0); + await expect(textarea).toBeFocused(); + }); + }); + + test('a pick stages the skill for the next turn @scenario:skills-popover-stages-skill', async ({ + page, + }) => { + const name = uniqueName('e2e-stage'); + await withSkills(page, [name], async () => { + const { textarea, combobox } = await openSkills(page); + await combobox.fill(name); + await expect(page.getByRole('option', { name: new RegExp(name) })).toBeVisible(); + await combobox.press('Enter'); + + await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0); + await expect(textarea).toBeFocused(); + await expect(textarea).toHaveValue(''); + await expect( + page + .getByTestId('composer-tray') + .getByTestId('composer-chip-skill') + .filter({ hasText: name }), + ).toBeVisible(); + + const response = await sendMessage(page, 'Use the staged skill'); + expect(response.ok()).toBeTruthy(); + expect( + (response.request().postDataJSON() as { manualSkills?: string[] }).manualSkills, + ).toEqual([name]); + }); + }); + + test('a search that matches nothing says so and Enter closes @scenario:skills-popover-no-match-notice', async ({ + page, + }) => { + await withSkills(page, [uniqueName('e2e-none')], async () => { + const { textarea, combobox } = await openSkills(page); + await combobox.fill('zzzz-no-such-skill'); + + await expect(page.getByRole('status').filter({ hasText: 'No skills found' })).toBeVisible(); + await expect(combobox).toHaveAttribute('aria-expanded', 'false'); + await combobox.press('Enter'); + + await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0); + await expect(textarea).toBeFocused(); + }); + }); +}); diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 0924ddcc05..8c190067dc 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -21,6 +21,7 @@ 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 SkillsPopover } from './components/composer/popover/Skills'; 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'; @@ -38,6 +39,10 @@ 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 { + SkillsPopoverProps, + SkillsPopoverNotices, +} from './components/composer/popover/Skills'; export type { CommandOption, CommandPopoverProps, diff --git a/packages/chat/src/components/composer/popover/Command.tsx b/packages/chat/src/components/composer/popover/Command.tsx index e923c82ef3..f5d476f967 100644 --- a/packages/chat/src/components/composer/popover/Command.tsx +++ b/packages/chat/src/components/composer/popover/Command.tsx @@ -35,6 +35,8 @@ export interface CommandPopoverProps { activeIndex: number; onActiveIndexChange: Dispatch>; isLoading?: boolean; + /** A message shown under the search field while open, such as an empty or failed list. */ + notice?: ReactNode; /** Enter or Tab on an option, or a click; the key event lets the caller decide its default. */ onSelect: (option: CommandOption, event?: KeyboardEvent) => void; /** The popover asks to close; a key event is present unless focus left the input. */ @@ -67,6 +69,7 @@ export default function CommandPopover({ activeIndex, onActiveIndexChange, isLoading = false, + notice, onSelect, onDismiss, }: CommandPopoverProps): React.JSX.Element { @@ -183,6 +186,11 @@ export default function CommandPopover({ )} + {open && notice != null && ( +
+ {notice} +
+ )}
; + /** Localized placeholder for the search field. */ + placeholder: string; + skills: CommandOption[]; + /** True while any page of the catalog is still loading. */ + isLoading: boolean; + isError: boolean; + notices: SkillsPopoverNotices; + /** A skill was picked; the popover has already closed and the draft keeps its text. */ + onSelectSkill: (skill: CommandOption) => void; + /** Hides the popover. */ + onClose: () => void; +} + +/** The `$` popover: picks a skill to invoke on the next turn. Text typed after the `$` stays in + * the draft, and the pick is handed to the host rather than written into the text. */ +export default function SkillsPopover({ + textAreaRef, + placeholder, + skills, + isLoading, + isError, + notices, + onSelectSkill, + onClose, +}: SkillsPopoverProps): React.JSX.Element { + const [activeIndex, setActiveIndex] = useState(0); + const inputRef = useRef(null); + + const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({ + value: '', + options: skills, + }); + + const initInputRef = useInitPopoverInput({ + inputRef, + textAreaRef, + commandChar: COMMAND_CHAR, + preserveTextAfterCursor: true, + setSearchValue, + setOpen, + }); + + useEffect(() => { + if (!open) { + setActiveIndex(0); + } + }, [open]); + + const handleSelect = (skill: CommandOption, e?: KeyboardEvent) => { + e?.preventDefault(); + setSearchValue(''); + setOpen(false); + onClose(); + onSelectSkill(skill); + textAreaRef.current?.focus(); + }; + + const handleDismiss = (reason: CommandDismissReason, e?: KeyboardEvent) => { + if (reason === 'commit' && e?.key === 'Enter') { + e.preventDefault(); + } + setOpen(false); + onClose(); + if (reason !== 'blur') { + textAreaRef.current?.focus(); + } + }; + + const notice = (() => { + if (isError) { + return notices.error; + } + if (isLoading || matches.length > 0) { + return undefined; + } + return searchValue ? notices.noMatch : notices.empty; + })(); + + return ( + setOpen(true)} + matches={matches as CommandOption[]} + activeIndex={activeIndex} + onActiveIndexChange={setActiveIndex} + isLoading={isLoading} + notice={notice} + onSelect={handleSelect} + onDismiss={handleDismiss} + /> + ); +} diff --git a/packages/chat/src/components/composer/popover/__tests__/Skills.spec.tsx b/packages/chat/src/components/composer/popover/__tests__/Skills.spec.tsx new file mode 100644 index 0000000000..a58e1a9364 --- /dev/null +++ b/packages/chat/src/components/composer/popover/__tests__/Skills.spec.tsx @@ -0,0 +1,101 @@ +/** + * @jest-environment jsdom + */ +import React from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import type { SkillsPopoverProps } from '../Skills'; +import type { CommandOption } from '../Command'; +import SkillsPopover from '../Skills'; + +/** + * The `$` popover's contract: text after the `$` stays in the draft, a pick goes to the host and + * never into the text, Enter and Tab on a skill are consumed, and an empty, unmatched or failed + * list says so in a status message. + */ + +const skills: CommandOption[] = [ + { type: 'skill', value: 'brand-guidelines', label: 'Brand Guidelines' }, + { type: 'skill', value: 'style-guide', label: 'Style Guide' }, +]; + +const notices = { error: 'Load failed', empty: 'No skills yet', noMatch: 'No match' }; + +beforeAll(() => { + Element.prototype.scrollIntoView = jest.fn(); +}); + +beforeEach(() => { + document.body.innerHTML = ''; +}); + +const renderSkills = (props: Partial = {}, draft = '$') => { + const textarea = document.createElement('textarea'); + textarea.value = draft; + document.body.appendChild(textarea); + textarea.setSelectionRange(1, 1); + const onClose = jest.fn(); + const onSelectSkill = jest.fn(); + render( + , + ); + return { textarea, onClose, onSelectSkill }; +}; + +const input = () => screen.getByRole('combobox'); + +describe('SkillsPopover', () => { + it('keeps the text after the cursor in the draft and hands the pick to the host', () => { + const { textarea, onClose, onSelectSkill } = renderSkills({}, '$ please review'); + + expect(textarea.value).toBe(' please review'); + fireEvent.keyDown(input(), { key: 'ArrowDown' }); + expect(fireEvent.keyDown(input(), { key: 'Tab' })).toBe(false); + + expect(onClose).toHaveBeenCalled(); + expect(onSelectSkill).toHaveBeenCalledWith(skills[1]); + expect(textarea.value).toBe(' please review'); + expect(document.activeElement).toBe(textarea); + }); + + it('lets Tab move on but consumes Enter when nothing matches', () => { + renderSkills(); + fireEvent.change(input(), { target: { value: 'zzz' } }); + + expect(screen.getByRole('status')).toHaveTextContent('No match'); + expect(fireEvent.keyDown(input(), { key: 'Tab' })).toBe(true); + }); + + it('consumes Enter when nothing matches and closes', () => { + const { onClose } = renderSkills(); + fireEvent.change(input(), { target: { value: 'zzz' } }); + + expect(fireEvent.keyDown(input(), { key: 'Enter' })).toBe(false); + expect(onClose).toHaveBeenCalled(); + }); + + it('says when there are no skills', () => { + renderSkills({ skills: [] }); + expect(screen.getByRole('status')).toHaveTextContent('No skills yet'); + }); + + it('says when the skills failed to load, keeping any already listed', () => { + renderSkills({ isError: true }); + expect(screen.getByRole('status')).toHaveTextContent('Load failed'); + expect(screen.getAllByRole('option')).toHaveLength(2); + }); + + it('shows no notice while the catalog is still loading', () => { + renderSkills({ skills: [], isLoading: true }); + expect(screen.queryByRole('status')).toBeNull(); + }); +});