Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/bits/src/lib/toolbar/toolbar-keyboard.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,27 @@ describe("Services > ", () => {
service.onKeyDown(rightButtonPressEvent);
expect(spy).toHaveBeenCalled();
});

it("should not hijack keyboard events coming from a search input", () => {
const searchInput = document.createElement("input");
searchInput.type = "search";
document.body.appendChild(searchInput);

const event = {
...keyboardEventMock,
target: searchInput,
} as KeyboardEvent;

const preventSpy = spyOn(event, "preventDefault");
const navSpy = spyOn(service as any, "navigateByArrow");

service.onKeyDown(event);

expect(preventSpy).not.toHaveBeenCalled();
expect(navSpy).not.toHaveBeenCalled();

searchInput.remove();
});
});
});
});
23 changes: 23 additions & 0 deletions packages/bits/src/lib/toolbar/toolbar-keyboard.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ export class ToolbarKeyboardService {
}

public onKeyDown(event: KeyboardEvent): void {
// Allow native keyboard handling inside search inputs (e.g. arrow keys move caret)
// instead of hijacking navigation for the whole toolbar.
const target = event.target as HTMLElement | null;
if (this.isSearchTarget(target)) {
return;
}

const { code } = event;

if (
Expand All @@ -49,6 +56,22 @@ export class ToolbarKeyboardService {
}
}

private isSearchTarget(target: HTMLElement | null): boolean {
if (!target) {
return false;
}

// Common ways a search input can be marked in DOM.
// - <input type="search">
// - role="searchbox"
// - a class/data attribute containing "search"
const el = target.closest?.(
"input[type=\"search\"], [role=\"searchbox\"], .search, [class*=\"search\"], [data-testid*=\"search\"], [data-automation-id*=\"search\"]"
) as HTMLElement | null;

return !!el;
}

private navigateByArrow(code: KEYBOARD_CODE): void {
const activeEl = document.activeElement;
const activeIndex = this.toolbarItems.indexOf(activeEl as HTMLElement);
Expand Down