Skip to content
Draft
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
261 changes: 260 additions & 1 deletion libs/components/src/filter-menu/filter-menu.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { MenuTriggerForDirective } from "../menu/menu-trigger-for.directive";
import { TooltipDirective } from "../tooltip";

import { FilterMenuComponent } from "./filter-menu.component";
import { FilterOptionComponent } from "./filter-option.component";
import { FilterOptionComponent, FilterOptionNode } from "./filter-option.component";
import { FilterSectionComponent } from "./filter-section.component";
import { FILTER_HOST, FilterHost, FilterOptionRow } from "./filter-tokens";

Expand Down Expand Up @@ -693,3 +693,262 @@ describe("FilterMenuComponent host counts", () => {
expect(filterHost.optionCounts).toHaveBeenCalledWith("vault", [["org-1"], ["org-2"]]);
});
});

@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [FilterMenuComponent, FilterOptionComponent, NgTemplateOutlet],
template: `
<bit-filter-menu #chip key="letters" placeholderText="Letters" multiple>
<bit-filter-option [value]="'alpha'" disabled>Alpha</bit-filter-option>
<bit-filter-option [value]="'beta'"
>Beta
<bit-filter-option [value]="'beta-one'">Beta one</bit-filter-option>
<bit-filter-option [value]="'beta-two'">Beta two</bit-filter-option>
</bit-filter-option>
<bit-filter-option [value]="'gamma'"
>Gamma
<bit-filter-option [value]="'gamma-one'">Gamma one</bit-filter-option>
</bit-filter-option>
<bit-filter-option [value]="'delta'">Delta</bit-filter-option>
</bit-filter-menu>
@if (showRows()) {
<ng-container *ngTemplateOutlet="chip.optionsTemplate()!"></ng-container>
}
`,
})
class TreeKeyboardHostComponent {
readonly showRows = signal(false);
}

const letterOptions = (): FilterOptionNode<string>[] =>
["Alpha", "Beta", "Gamma", "Delta"].map((label) => ({ value: label.toLowerCase(), label }));

@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [FilterMenuComponent, NgTemplateOutlet],
template: `
<bit-filter-menu
#chip
key="letters"
placeholderText="Letters"
multiple
[options]="options()"
></bit-filter-menu>
@if (showRows()) {
<ng-container *ngTemplateOutlet="chip.optionsTemplate()!"></ng-container>
}
`,
})
class TreeKeyboardDataHostComponent {
readonly options = signal(letterOptions());
readonly showRows = signal(false);
}

describe("FilterMenuComponent tree keyboard navigation", () => {
let fixture: ComponentFixture<{ showRows: WritableSignal<boolean> }>;

const chip = () =>
fixture.debugElement.query(By.directive(FilterMenuComponent))
.componentInstance as FilterMenuComponent;

const rows = () =>
fixture.debugElement
.queryAll(By.css('[role="treeitem"]'))
.map((row) => row.nativeElement as HTMLElement);

const label = (row: Element | null) =>
row?.querySelector("[data-filter-row-label]")?.textContent?.trim();

const labels = () => rows().map(label);

const row = (text: string) => rows().find((el) => label(el) === text)!;

const focused = () => label(document.activeElement);

const tabStops = () =>
rows()
.filter((el) => el.tabIndex === 0)
.map(label);

/** Sends a key to the focused row, returning whether the tree claimed it. */
const press = (key: string): boolean => {
const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
document.activeElement!.dispatchEvent(event);
fixture.detectChanges();
return event.defaultPrevented;
};

const focus = (text: string) => {
row(text).focus();
fixture.detectChanges();
};

const render = <T extends { showRows: WritableSignal<boolean> }>(hostType: Type<T>) => {
const created = TestBed.createComponent(hostType);
fixture = created;
fixture.detectChanges();
fixture.componentInstance.showRows.set(true);
fixture.detectChanges();
return created;
};

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TreeKeyboardHostComponent],
providers: [{ provide: I18nService, useValue: mockI18nService }],
}).compileComponents();

render(TreeKeyboardHostComponent);
});

it("starts with the tab stop on the first enabled row", () => {
expect(labels()).toEqual(["Alpha", "Beta", "Gamma", "Delta"]);
expect(tabStops()).toEqual(["Beta"]);
});

it("moves one row at a time with the arrow keys and stops at either end", () => {
focus("Gamma");

press("ArrowDown");
expect(focused()).toBe("Delta");
press("ArrowDown");
expect(focused()).toBe("Delta");

press("ArrowUp");
press("ArrowUp");
expect(focused()).toBe("Beta");
});

it("lets the arrow keys reach a disabled row, so its label can still be read", () => {
focus("Beta");

press("ArrowUp");
expect(focused()).toBe("Alpha");
press("ArrowUp");
expect(focused()).toBe("Alpha");
});

it("jumps to the first and last row with Home and End", () => {
focus("Beta");

press("End");
expect(focused()).toBe("Delta");

press("Home");
expect(focused()).toBe("Alpha");
});

it("keeps a single tab stop, on whichever row last had focus", () => {
focus("Beta");
press("ArrowDown");

expect(tabStops()).toEqual(["Gamma"]);
});

it("opens a closed parent with ArrowRight, then steps into its first child", () => {
focus("Beta");

press("ArrowRight");
expect(labels()).toEqual(["Alpha", "Beta", "Beta one", "Beta two", "Gamma", "Delta"]);
expect(focused()).toBe("Beta");

press("ArrowRight");
expect(focused()).toBe("Beta one");
});

it("steps out to the parent with ArrowLeft, then closes it", () => {
focus("Beta");
press("ArrowRight");
focus("Beta two");

press("ArrowLeft");
expect(focused()).toBe("Beta");

press("ArrowLeft");
expect(labels()).toEqual(["Alpha", "Beta", "Gamma", "Delta"]);
expect(focused()).toBe("Beta");
});

it("leaves a top-level row with nothing to open where it is", () => {
focus("Delta");

press("ArrowLeft");
expect(focused()).toBe("Delta");
press("ArrowRight");
expect(focused()).toBe("Delta");
expect(labels()).toEqual(["Alpha", "Beta", "Gamma", "Delta"]);
});

it("opens every parent at the focused row's level with *", () => {
focus("Delta");

press("*");
// Focus follows the option on the render after its position changes.
fixture.detectChanges();

expect(labels()).toEqual([
"Alpha",
"Beta",
"Beta one",
"Beta two",
"Gamma",
"Gamma one",
"Delta",
]);
expect(focused()).toBe("Delta");
});

it("toggles the focused option with Enter and with Space", () => {
focus("Delta");

press("Enter");
expect(chip().value()).toEqual(["delta"]);

press(" ");
expect(chip().value()).toEqual([]);
});

it("does not toggle a disabled option", () => {
focus("Alpha");

press("Enter");
press(" ");

expect(chip().value()).toBeUndefined();
});

it("claims the keys it handles and leaves the rest to the browser", () => {
focus("Beta");

expect(press("ArrowDown")).toBe(true);
expect(press("Home")).toBe(true);
expect(press("Tab")).toBe(false);
expect(press("a")).toBe(false);
});

it("keeps its place when a consumer rebuilds the options while a row has focus", () => {
const data = render(TreeKeyboardDataHostComponent);
focus("Gamma");

data.componentInstance.options.set(letterOptions());
fixture.detectChanges();
fixture.detectChanges();

expect(tabStops()).toEqual(["Gamma"]);
expect(focused()).toBe("Gamma");
press("ArrowDown");
expect(focused()).toBe("Delta");
});

it("goes straight from a leaf to its parent with ArrowLeft, even after ArrowRight on the leaf", () => {
focus("Beta");
press("ArrowRight");
focus("Beta one");

press("ArrowRight");
press("ArrowLeft");

expect(focused()).toBe("Beta");
});
});
10 changes: 0 additions & 10 deletions libs/components/src/filter-menu/filter-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,16 +276,6 @@ export type FilterTreeNode = {
groupEnd: boolean;
};

/** The parts of a tree row's behaviour only the tree that draws it can answer. */
export interface FilterTreeHost {
activateNode(node: FilterTreeNode): void;
parentRow<T>(row: T): T | null;
childRows<T>(row: T): T[];
}

/** Provided by `bit-filter-menu`'s tree; injected by its rows. */
export const FILTER_TREE_HOST = new InjectionToken<FilterTreeHost>("FilterTreeHost");

/**
* The selection state and actions `bit-filter-menu` provides to the `bit-filter-tree` that
* renders its options. The menu holds the selected values; the tree only draws the rows, so
Expand Down
70 changes: 7 additions & 63 deletions libs/components/src/filter-menu/filter-tree-row.directive.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
import { TreeKeyManagerItem } from "@angular/cdk/a11y";
import {
Directive,
ElementRef,
computed,
contentChild,
inject,
input,
signal,
} from "@angular/core";
import { Directive, ElementRef, contentChild, inject, input } from "@angular/core";

import { TooltipDirective } from "../tooltip";

import { FILTER_TREE_HOST, FilterTreeHost, FilterTreeNode } from "./filter-tokens";

/** One row of a multi-select filter menu's tree, adapting it to CDK's {@link TreeKeyManagerItem}. */
/** One row of a multi-select filter menu's tree: its tab stop, its focus, and its label tooltip. */
@Directive({
selector: "[bitFilterTreeRow]",
exportAs: "bitFilterTreeRow",
host: {
"[tabindex]": "tabbable() ? 0 : -1",
"(focus)": "onFocus()",
"(blur)": "labelTooltip()?.hideTooltip()",
},
})
export class FilterTreeRowDirective implements TreeKeyManagerItem {
export class FilterTreeRowDirective {
private readonly el = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly host = inject<FilterTreeHost>(FILTER_TREE_HOST);

readonly node = input.required<FilterTreeNode>({ alias: "bitFilterTreeRow" });

/** Whether this row currently holds the tree's single tab stop. */
readonly tabbable = signal(false);

readonly isDisabled = computed(() => this.node().row.disabled());
/** Whether this row holds the tree's single tab stop. */
readonly tabbable = input(false);

/** `focusin` only bubbles up, so the row opens its label's tooltip itself. */
protected readonly labelTooltip = contentChild(TooltipDirective);
Expand All @@ -44,50 +27,11 @@ export class FilterTreeRowDirective implements TreeKeyManagerItem {
}
}

/** @see TreeKeyManagerItem.getLabel โ€” the manager's typeahead matches on this. */
getLabel(): string {
return this.node().row.label();
}

activate(): void {
if (!this.isDisabled()) {
this.host.activateNode(this.node());
}
}

getParent(): FilterTreeRowDirective | null {
return this.host.parentRow(this);
}

getChildren(): FilterTreeRowDirective[] {
return this.host.childRows(this);
}

isExpanded = (): boolean => this.node().expanded;

expand(): void {
if (!this.isExpanded()) {
this.node().row.toggleExpanded();
}
}

collapse(): void {
if (this.isExpanded()) {
this.node().row.toggleExpanded();
}
}

focus(): void {
this.tabbable.set(true);
this.el.nativeElement.focus();
}

unfocus(): void {
this.tabbable.set(false);
}

/** Becomes the tab stop without stealing focus โ€” how the manager seeds the tree. */
makeFocusable(): void {
this.tabbable.set(true);
hasFocus(): boolean {
return this.el.nativeElement.matches(":focus");
}
}
Loading
Loading