Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix: scope ComboBox Enter-key highlight check to its own cmdk list

Khuram Niaz1f479d9c569e
diff --git a/__tests__/ComboBox.spec.tsx b/__tests__/ComboBox.spec.tsx
new file mode 100644
index 0000000..adbbd7b
--- /dev/null
+++ b/__tests__/ComboBox.spec.tsx
@@ -0,0 +1,308 @@
+import { Combobox } from "@/components/ComboBox";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { addCompany } from "@/actions/company.actions";
+import { createLocation, createJobSource } from "@/actions/job.actions";
+import { createJobTitle } from "@/actions/jobtitle.actions";
+import { createActivityType } from "@/actions/activity.actions";
+import { toast } from "@/components/ui/use-toast";
+import { useForm } from "react-hook-form";
+import { Form, FormField, FormItem } from "@/components/ui/form";
+import {
+ Command,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+
+vi.mock("@/actions/company.actions", () => ({
+ addCompany: vi.fn(),
+}));
+
+vi.mock("@/actions/job.actions", () => ({
+ createLocation: vi.fn(),
+ createJobSource: vi.fn(),
+}));
+
+vi.mock("@/actions/jobtitle.actions", () => ({
+ createJobTitle: vi.fn(),
+}));
+
+vi.mock("@/actions/activity.actions", () => ({
+ createActivityType: vi.fn(),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+// jsdom lacks scrollIntoView, which cmdk calls when selecting an item
+Element.prototype.scrollIntoView = vi.fn();
+
+const companies = [
+ { id: "existing-id", value: "metallica inc", label: "Metallica Inc" },
+ { id: "other-id", value: "acme corp", label: "Acme Corp" },
+];
+
+function Harness({
+ onChange,
+ creatable = true,
+ name = "company",
+ options = companies,
+}: {
+ onChange: (v: string) => void;
+ creatable?: boolean;
+ name?: string;
+ options?: { id: string; value: string; label: string }[];
+}) {
+ const form = useForm({ defaultValues: { [name]: "" } });
+ return (
+ <Form {...form}>
+ <FormField
+ control={form.control}
+ name={name}
+ render={({ field }) => (
+ <FormItem>
+ <Combobox
+ options={[...options]}
+ field={{
+ ...field,
+ onChange: (v: string) => {
+ onChange(v);
+ field.onChange(v);
+ },
+ }}
+ creatable={creatable}
+ />
+ </FormItem>
+ )}
+ />
+ </Form>
+ );
+}
+
+type HarnessProps = Partial<React.ComponentProps<typeof Harness>>;
+
+async function openCombobox(props: HarnessProps = {}) {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<Harness onChange={onChange} {...props} />);
+
+ await user.click(screen.getByRole("combobox"));
+ const label = props.name ?? "company";
+ const input = screen.getByPlaceholderText(
+ new RegExp(`Search ${label}`, "i")
+ ) as HTMLInputElement;
+ return { user, onChange, input };
+}
+
+beforeEach(() => {
+ vi.mocked(addCompany).mockResolvedValue({
+ success: true,
+ data: { id: "new-id", label: "acme", value: "acme" },
+ } as never);
+});
+
+describe("Combobox Enter key", () => {
+ describe("creating", () => {
+ it("creates a new option when nothing matches the search", async () => {
+ const { user, input } = await openCombobox();
+
+ await user.type(input, "Zebra{Enter}");
+
+ await waitFor(() =>
+ expect(addCompany).toHaveBeenCalledWith({ company: "Zebra" })
+ );
+ });
+
+ it("trims surrounding whitespace before creating", async () => {
+ const { user, input } = await openCombobox();
+
+ await user.type(input, " Zebra {Enter}");
+
+ await waitFor(() =>
+ expect(addCompany).toHaveBeenCalledWith({ company: "Zebra" })
+ );
+ });
+
+ it("selects the created option and closes the popover", async () => {
+ const { user, input, onChange } = await openCombobox();
+
+ await user.type(input, "Zebra{Enter}");
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("new-id"));
+ await waitFor(() =>
+ expect(screen.queryByPlaceholderText(/Search company/i)).toBeNull()
+ );
+ });
+
+ it("routes to the right action for each field name", async () => {
+ vi.mocked(createJobTitle).mockResolvedValue({ id: "t1" } as never);
+ const { user, input } = await openCombobox({
+ name: "title",
+ options: [],
+ });
+
+ await user.type(input, "Staff Engineer{Enter}");
+
+ await waitFor(() =>
+ expect(createJobTitle).toHaveBeenCalledWith("Staff Engineer")
+ );
+ expect(addCompany).not.toHaveBeenCalled();
+ });
+
+ it("routes activityType to createActivityType", async () => {
+ vi.mocked(createActivityType).mockResolvedValue({ id: "a1" } as never);
+ const { user, input } = await openCombobox({
+ name: "activityType",
+ options: [],
+ });
+
+ await user.type(input, "Networking{Enter}");
+
+ await waitFor(() =>
+ expect(createActivityType).toHaveBeenCalledWith("Networking")
+ );
+ });
+ });
+
+ describe("not creating", () => {
+ it("does nothing on Enter with an empty input", async () => {
+ const { user, input, onChange } = await openCombobox({ options: [] });
+
+ await user.type(input, "{Enter}");
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(addCompany).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does nothing on Enter with a whitespace-only input", async () => {
+ const { user, input, onChange } = await openCombobox({ options: [] });
+
+ await user.type(input, " {Enter}");
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(addCompany).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does not create when the combobox is not creatable", async () => {
+ const { user, input, onChange } = await openCombobox({
+ creatable: false,
+ options: [],
+ });
+
+ await user.type(input, "Zebra{Enter}");
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(addCompany).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does not create on non-Enter keys", async () => {
+ const { user, input } = await openCombobox({ options: [] });
+
+ await user.type(input, "Zebra");
+ await user.keyboard("{Escape}");
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(addCompany).not.toHaveBeenCalled();
+ });
+
+ it("selects an exact match instead of creating a duplicate", async () => {
+ const { user, input, onChange } = await openCombobox();
+
+ await user.type(input, "Acme Corp{Enter}");
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("other-id"));
+ expect(addCompany).not.toHaveBeenCalled();
+ });
+
+ it("matches case-insensitively when selecting an existing option", async () => {
+ const { user, input, onChange } = await openCombobox();
+
+ await user.type(input, "ACME CORP{Enter}");
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("other-id"));
+ expect(addCompany).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("preserving cmdk defaults", () => {
+ it("still selects an arrow-key highlighted option on Enter", async () => {
+ const { user, input, onChange } = await openCombobox();
+
+ await user.type(input, "{ArrowDown}");
+ await user.keyboard("{Enter}");
+
+ await waitFor(() => expect(onChange).toHaveBeenCalled());
+ expect(addCompany).not.toHaveBeenCalled();
+ expect(input).toBeDefined();
+ });
+
+ it("is not blocked by a highlighted item in an unrelated cmdk list", async () => {
+ const user = userEvent.setup();
+ render(
+ <>
+ {/* A second cmdk list mounted elsewhere in the document, e.g. the
+ skills TagInput popover mid-close-animation */}
+ <Command>
+ <CommandList>
+ <CommandGroup>
+ <CommandItem value="unrelated">Unrelated</CommandItem>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ <Harness onChange={vi.fn()} />
+ </>
+ );
+
+ await user.click(screen.getByRole("combobox"));
+ await user.type(
+ screen.getByPlaceholderText(/Search company/i),
+ "Zebra{Enter}"
+ );
+
+ await waitFor(() =>
+ expect(addCompany).toHaveBeenCalledWith({ company: "Zebra" })
+ );
+ });
+ });
+
+ describe("creation failures", () => {
+ it("surfaces an error toast when location creation fails", async () => {
+ vi.mocked(createLocation).mockResolvedValue({
+ success: false,
+ message: "Location already exists",
+ data: undefined,
+ } as never);
+ const { user, input, onChange } = await openCombobox({
+ name: "location",
+ options: [],
+ });
+
+ await user.type(input, "Toronto{Enter}");
+
+ await waitFor(() => expect(toast).toHaveBeenCalled());
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("surfaces an error toast when source creation fails", async () => {
+ vi.mocked(createJobSource).mockResolvedValue({
+ success: false,
+ message: "Source already exists",
+ data: undefined,
+ } as never);
+ const { user, input, onChange } = await openCombobox({
+ name: "source",
+ options: [],
+ });
+
+ await user.type(input, "Referral{Enter}");
+
+ await waitFor(() => expect(toast).toHaveBeenCalled());
+ expect(onChange).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/e2e/add-job.spec.ts b/e2e/add-job.spec.ts
index 0e8ce02..936d762 100644
--- a/e2e/add-job.spec.ts
+++ b/e2e/add-job.spec.ts
@@ -325,6 +325,74 @@ test.describe("Add New Job", () => {
await expect(page.getByText(jobText).first()).toBeVisible();
});
+ test("should create title, company and location with the Enter key", async ({
+ page,
+ cleanup,
+ }) => {
+ const jobText = uniqueName("developer test title enter create");
+ const suffix = jobText.replace(/\s+/g, "-");
+ await createNewJob(page, jobText, cleanup, { useEnterKey: true });
+ await expect(page.getByRole("row", { name: jobText }).first()).toBeVisible();
+
+ await page
+ .getByRole("row", { name: jobText })
+ .getByTestId("job-actions-menu-btn")
+ .first()
+ .click();
+ await page.getByRole("menuitem", { name: "Edit Job" }).click();
+ await expect(page.getByLabel("Job Title")).toContainText(jobText);
+ await expect(page.getByLabel("Company")).toContainText(`company ${suffix}`);
+ await expect(page.getByLabel("Job Location")).toContainText(
+ `location ${suffix}`,
+ );
+ });
+
+ test("should select an existing company with the Enter key instead of duplicating it", async ({
+ page,
+ cleanup,
+ }) => {
+ const firstJobText = uniqueName("developer test title enter reuse first");
+ const secondJobText = uniqueName("developer test title enter reuse second");
+ const sharedCompany = `company ${firstJobText.replace(/\s+/g, "-")}`;
+
+ await createNewJob(page, firstJobText, cleanup);
+ await expect(
+ page.getByRole("row", { name: firstJobText }).first(),
+ ).toBeVisible();
+
+ // The company already exists, so cmdk highlights it and Enter must select
+ // rather than fall through to ComboBox's create branch.
+ await createNewJob(page, secondJobText, cleanup, {
+ company: sharedCompany,
+ useEnterKey: true,
+ });
+ await expect(
+ page.getByRole("row", { name: secondJobText }).first(),
+ ).toBeVisible();
+
+ await expect(
+ page.getByRole("row", { name: secondJobText }).getByText(sharedCompany),
+ ).toBeVisible();
+ });
+
+ test("should not create or submit when Enter is pressed on an empty combobox search", async ({
+ page,
+ }) => {
+ // No cleanup needed: nothing should be created by this test.
+ await page.getByRole("button", { name: "Job", exact: true }).click();
+ await expect(page.getByTestId("add-job-dialog-title")).toBeVisible();
+
+ await page.getByLabel("Job Title").click();
+ const input = page.getByPlaceholder("Create or Search title");
+ await input.click();
+ await input.press("Enter");
+
+ // The popover stays open and the dialog must not submit.
+ await expect(input).toBeVisible();
+ await expect(page.getByTestId("add-job-dialog-title")).toBeVisible();
+ await expect(page.getByText("Job title is required.")).not.toBeVisible();
+ });
+
test("should add and persist a skill tag on a job", async ({
page,
cleanup,
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 6f8cdb6..ca75858 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -45,6 +45,28 @@ export async function selectOrCreate(
await expect(input).not.toBeVisible({ timeout: 15000 });
}
+// Same contract as selectOrCreate, but commits with the Enter key instead of
+// clicking the option — ComboBox handles Enter itself on the create path and
+// defers to cmdk when an option is highlighted, so both branches are covered.
+export async function selectOrCreateWithEnter(
+ page: Page,
+ label: string,
+ placeholder: string,
+ value: string,
+) {
+ await page.getByLabel(label).click();
+ const input = page.getByPlaceholder(placeholder);
+ await input.click();
+ await input.fill(value);
+ const createOption = page.getByText(`Create: ${value}`);
+ const existingOption = page.getByRole("option", { name: value, exact: true });
+ await expect(createOption.or(existingOption).first()).toBeVisible();
+ await input.press("Enter");
+ // Same rationale as selectOrCreate: wait for the popover to close, not the
+ // trigger label, which renders blank after an inline create.
+ await expect(input).not.toBeVisible({ timeout: 15000 });
+}
+
export async function createNewJob(
page: Page,
jobText: string,
@@ -54,6 +76,7 @@ export async function createNewJob(
beforeSave?: (page: Page) => Promise<void>;
company?: string;
location?: string;
+ useEnterKey?: boolean;
},
): Promise<string> {
const suffix = jobText.replace(/\s+/g, "-");
@@ -77,16 +100,12 @@ export async function createNewJob(
// Register each Library item the moment it's persisted (the "Create" click
// saves it via its own server action), so a failure before the job is saved
// still tears the item down.
- await selectOrCreate(page, "Job Title", "Create or Search title", jobText);
+ const pick = options?.useEnterKey ? selectOrCreateWithEnter : selectOrCreate;
+ await pick(page, "Job Title", "Create or Search title", jobText);
cleanup.title(jobText);
- await selectOrCreate(page, "Company", "Create or Search company", companyText);
+ await pick(page, "Company", "Create or Search company", companyText);
cleanup.company(companyText);
- await selectOrCreate(
- page,
- "Job Location",
- "Create or Search location",
- locationText,
- );
+ await pick(page, "Job Location", "Create or Search location", locationText);
cleanup.location(locationText);
await page.getByText("Part-time").click();
diff --git a/src/components/ComboBox.tsx b/src/components/ComboBox.tsx
index 572dc55..5fb4bce 100644
--- a/src/components/ComboBox.tsx
+++ b/src/components/ComboBox.tsx
@@ -43,9 +43,10 @@ export function Combobox({ options, field, creatable }: ComboboxProps) {
const handleEnterKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key !== "Enter") return;
- const hasHighlightedItem = !!document.querySelector(
- '[cmdk-item][aria-selected="true"]'
- );
+ // Scope to this Command; a global query matches other mounted cmdk lists
+ const hasHighlightedItem = !!e.currentTarget
+ .closest("[cmdk-root]")
+ ?.querySelector('[cmdk-item][aria-selected="true"]');
if (hasHighlightedItem) return;
@@ -99,6 +100,7 @@ export function Combobox({ options, field, creatable }: ComboboxProps) {
default:
break;
}
+ if (!response?.id) return;
options.unshift(response);
field.onChange(response.id);
setIsPopoverOpen(false);