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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ The fixture's parts have independent dimensions; changing one part does not auto

When closing the last view of a document, choose **Save and close**, **Close without saving**, or **Cancel**. A failed save leaves the document open. Already-started saves finish before the document closes.

In the model tree, Up/Down moves keyboard focus without changing selection; Enter or Space selects, Left/Right collapses or opens groups. Ctrl/Command with Enter or Space retains the existing multi-selection behavior.

On narrow screens, **Items / Properties** opens the model tree and editable dimensions. Camera, zoom and snap controls remain available; **Fit Content** frames the model after rotating or resizing the view. On larger screens the panels remain beside the workspace. Camera and zoom controls and command confirmation buttons can be reached by keyboard and activated with Enter or Space.

## Run locally
Expand Down
97 changes: 97 additions & 0 deletions packages/ui/src/project/tree/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import {
Annotation,
FolderNode,
I18n,
type IDocument,
type INode,
type INodeLinkedList,
Expand Down Expand Up @@ -33,12 +34,16 @@ export class Tree extends HTMLElement {
constructor(private document: IDocument) {
super();
this.className = style.panel;
this.setAttribute("role", "tree");
this.setAttribute("aria-label", I18n.translate("items.header"));
this.setAttribute("aria-multiselectable", "true");
this.initializeTree(document);
}

private initializeTree(document: IDocument) {
this.addAllNodes(document, this, document.modelManager.rootNode);
this.addEvents(this);
this.synchronizeTabStop();
}

connectedCallback() {
Expand Down Expand Up @@ -105,6 +110,7 @@ export class Tree extends HTMLElement {
ele.refreshVisibleIcon();
this.refreshGroupExpander(record.oldParent);
});
this.synchronizeTabStop();
};

private refreshGroupExpander(parent: INodeLinkedList | undefined) {
Expand All @@ -121,15 +127,18 @@ export class Tree extends HTMLElement {
private readonly handleSelectionChanged = (selected: INode[]) => {
this.lastSelected?.forEach((x) => {
this.nodeMap.get(x)?.removeStyle(style.selected);
this.nodeMap.get(x)?.setAttribute("aria-selected", "false");
this.selectedNodes.delete(x);
});
this.lastSelected = Array.from(selected);

selected.forEach((model) => {
this.selectedNodes.add(model);
this.nodeMap.get(model)?.addStyle(style.selected);
this.nodeMap.get(model)?.setAttribute("aria-selected", "true");
});
this.scrollToNode(selected);
this.synchronizeTabStop();
};

private ensureHasHTML(records: NodeRecord[]) {
Expand Down Expand Up @@ -179,6 +188,9 @@ export class Tree extends HTMLElement {
}

private addEvents(item: HTMLElement) {
item.addEventListener("tree-expansion-changed", this.onExpansionChanged);
item.addEventListener("keydown", this.onKeyDown);
item.addEventListener("focusin", this.onFocusIn);
item.addEventListener("dragstart", this.onDragStart);
item.addEventListener("dragover", this.onDragOver);
item.addEventListener("dragleave", this.onDragLeave);
Expand All @@ -189,6 +201,9 @@ export class Tree extends HTMLElement {
}

private removeEvents(item: HTMLElement) {
item.removeEventListener("tree-expansion-changed", this.onExpansionChanged);
item.removeEventListener("keydown", this.onKeyDown);
item.removeEventListener("focusin", this.onFocusIn);
item.removeEventListener("dragstart", this.onDragStart);
item.removeEventListener("dragover", this.onDragOver);
item.removeEventListener("dragleave", this.onDragLeave);
Expand All @@ -204,6 +219,88 @@ export class Tree extends HTMLElement {
return this.getTreeItem(item.parentElement);
}

private visibleItems(): TreeItem[] {
return Array.from(this.querySelectorAll<TreeItem>("tree-model, tree-group")).filter((item) => {
for (let parent = item.parentElement; parent && parent !== this; parent = parent.parentElement) {
if (parent instanceof TreeGroup && !parent.isExpanded) return false;
}
return true;
});
}

private synchronizeTabStop() {
const items = this.visibleItems();
const focused = this.getTreeItem(document.activeElement as HTMLElement);
const preferred =
focused && items.includes(focused)
? focused
: (items.find((item) => this.selectedNodes.has(item.node)) ??
items.find((item) => item.tabIndex === 0) ??
items[0]);
for (const item of this.nodeMap.values()) item.tabIndex = item === preferred ? 0 : -1;
}

private readonly onExpansionChanged = () => this.synchronizeTabStop();

private readonly onFocusIn = (event: FocusEvent) => {
const item = this.getTreeItem(event.target as HTMLElement);
if (item) {
for (const row of this.nodeMap.values()) row.tabIndex = row === item ? 0 : -1;
}
};

private focusItem(item: TreeItem | undefined) {
if (!item) return;
item.focus({ preventScroll: true });
item.mainElement().scrollIntoView({ block: "nearest" });
}

private readonly onKeyDown = (event: KeyboardEvent) => {
const item = this.getTreeItem(event.target as HTMLElement);
if (!item || event.target !== item || event.altKey) return;
const items = this.visibleItems();
const index = items.indexOf(item);
switch (event.key) {
case "ArrowDown":
this.focusItem(items[Math.min(index + 1, items.length - 1)]);
break;
case "ArrowUp":
this.focusItem(items[Math.max(index - 1, 0)]);
break;
case "Home":
this.focusItem(items[0]);
break;
case "End":
this.focusItem(items.at(-1));
break;
case "ArrowRight":
if (item instanceof TreeGroup) {
if (!item.isExpanded) item.isExpanded = true;
else
this.focusItem(
items[index + 1]?.node.parent === item.node ? items[index + 1] : undefined,
);
}
break;
case "ArrowLeft":
if (item instanceof TreeGroup && item.isExpanded) item.isExpanded = false;
else this.focusItem(item.node.parent ? this.nodeMap.get(item.node.parent) : undefined);
break;
case "Enter":
case " ":
if (!event.repeat && this.canSelect()) {
this.document.selection.setSelectedNodes([item.node], event.ctrlKey || event.metaKey);
this.handleLastClickItem(item.node);
}
break;
default:
return;
Comment on lines +296 to +297

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow Tab to leave the newly focusable tree

With a document active under the normal selection handler, Tab and Shift+Tab cannot move focus out of the tree. These keys take this default branch and bubble to HotkeyService.eventHandlerKeyDown(), which forwards them to SelectionHandler.keyDown(); its Tab branch unconditionally calls preventDefault() to cycle viewport highlights. The default ShowPropertyEventHandler inherits that behavior, so entering the new roving tab stop creates a keyboard trap even when no command is running. Handle Tab by stopping propagation without preventing its browser default, allowing users to reach the surrounding controls.

Useful? React with 👍 / 👎.

}
event.preventDefault();
event.stopPropagation();
Comment on lines +299 to +300

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve command confirmation while a picker is active

When a command is awaiting selection and keyboard focus is in the tree, Enter/Space now selects the row but never confirms the command. For example, Move started without a preselection awaits the multi-node picker in TransformedCommand.ensureSelectedModels(). Its confirmation is handled by SelectionHandler.keyDown() through the window listener in HotkeyService, but this handler unconditionally stops propagation, so the picker never receives confirmation. The same interception silently consumes Enter/Space when canSelect() is false during point picking. Preserve a way for these keys to reach the active command handler rather than swallowing them throughout command execution.

Useful? React with 👍 / 👎.

this.synchronizeTabStop();
};

private readonly onClick = (event: MouseEvent) => {
if (!this.canSelect()) return;

Expand Down
9 changes: 8 additions & 1 deletion packages/ui/src/project/tree/treeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ export abstract class TreeItem extends HTMLElement {
super();
this._node = node;
this.draggable = true;
this.tabIndex = -1;
this.setAttribute("role", "treeitem");
this.setAttribute("aria-label", node.name);
this.setAttribute("aria-selected", "false");
this.setAttribute("aria-keyshortcuts", "Enter Space");
this.name = label({
className: style.name,
textContent: new Binding(node, "name"),
Expand Down Expand Up @@ -74,7 +79,9 @@ export abstract class TreeItem extends HTMLElement {
}

private readonly onPropertyChanged = (property: string, model: INode) => {
if (property === "visible") {
if (property === "name") {
this.setAttribute("aria-label", model.name);
} else if (property === "visible") {
setSVGIcon(this.visibleIcon, this.getVisibleIcon());
} else if (property === "parentVisible") {
this.setVisibleStyle(model.parentVisible);
Expand Down
9 changes: 9 additions & 0 deletions packages/ui/src/project/tree/treeItemGroup.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,12 @@
flex-direction: row;
align-items: center;
}

tree-group:focus-visible {
outline: none;
}

tree-group:focus-visible > .container > .header {
outline: 2px solid var(--primary-color);
outline-offset: -2px;
}
8 changes: 8 additions & 0 deletions packages/ui/src/project/tree/treeItemGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export class TreeGroup extends TreeItem {

constructor(document: IDocument, node: INodeLinkedList) {
super(document, node);
this.items.setAttribute("role", "group");
this.expanderIcon = this.createExpanderIcon(node);
const typeIcon = this.createTypeIcon();
this.header = div(
Expand Down Expand Up @@ -51,6 +52,11 @@ export class TreeGroup extends TreeItem {
const hide =
!(this.node instanceof FolderNode) && (this.node as INodeLinkedList).firstChild === undefined;
this.expanderIcon.classList.toggle(style.hide, hide);
if (this.node instanceof FolderNode || (this.node as INodeLinkedList).firstChild !== undefined) {
this.setAttribute("aria-expanded", String(this._isExpanded));
} else {
this.removeAttribute("aria-expanded");
}
}

get isExpanded(): boolean {
Expand All @@ -59,8 +65,10 @@ export class TreeGroup extends TreeItem {

set isExpanded(value: boolean) {
this._isExpanded = value;
this.setAttribute("aria-expanded", String(value));
setSVGIcon(this.expanderIcon, this.getExpanderIcon());
this.items.classList.toggle(style.hide, !this._isExpanded);
this.dispatchEvent(new Event("tree-expansion-changed", { bubbles: true }));
}

mainElement(): HTMLElement {
Expand Down
5 changes: 5 additions & 0 deletions packages/ui/src/project/tree/treeModel.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@
.panel:hover {
background-color: var(--hover-background-color);
}

.panel:focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: -2px;
}
127 changes: 125 additions & 2 deletions packages/ui/test/tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
// See LICENSE file in the project root for full license information.

import type { IDocument, INode, INodeLinkedList, NodeRecord } from "@chili3d/core";
// test-utils must load BEFORE the core-mock helper so the real core module is
// fully cached by the time `rs.mock("@chili3d/core")` registers.
import { createMockDocument, type MockDocumentOverrides } from "@chili3d/core/test-utils";
import { afterEach, beforeEach, describe, expect, rs, test } from "@rstest/core";
// test-utils must load BEFORE the core-mock helper so the real core module is
// fully cached by the time `rs.mock("@chili3d/core")` registers.
import { ShortcutProfiles } from "../../core/src/command/shortcutProfiles";

// CSS modules under test
rs.mock("../src/project/tree/tree.module.css", () => ({
Expand Down Expand Up @@ -197,6 +198,128 @@ describe("Tree", () => {
document.body.innerHTML = "";
});

describe("keyboard model navigation", () => {
function key(item: HTMLElement, value: string, options: KeyboardEventInit = {}) {
item.dispatchEvent(
new KeyboardEvent("keydown", { key: value, bubbles: true, cancelable: true, ...options }),
);
}

test("exposes a named multiselect tree with one visible tab stop", () => {
fixture = createFixture();
expect(fixture.tree.getAttribute("role")).toBe("tree");
expect(fixture.tree.getAttribute("aria-multiselectable")).toBe("true");
const rows = Array.from(fixture.tree.querySelectorAll<HTMLElement>("[role=treeitem]"));
expect(rows).toHaveLength(4);
expect(rows.filter((row) => row.tabIndex === 0)).toHaveLength(1);
expect(rows.map((row) => row.getAttribute("aria-label"))).toEqual([
"root",
"groupA",
"model1",
"model2",
]);
});

test("arrow focus is independent of selection and Enter selects the focused model", () => {
fixture = createFixture();
fixture.doc.visual.eventHandler = Object.create(
NodeSelectionHandler.prototype,
) as IDocument["visual"]["eventHandler"];
const first = fixture.tree.treeItem(fixture.root as unknown as INode)!;
first.focus();
key(first, "End");
const last = fixture.tree.treeItem(fixture.model2 as unknown as INode)!;
expect(document.activeElement).toBe(last);
expect(fixture.doc.selection.setSelectedNodes).not.toHaveBeenCalled();
key(last, "Enter", { ctrlKey: true });
expect(fixture.doc.selection.setSelectedNodes).toHaveBeenCalledWith([fixture.model2], true);
});

test("collapsed descendants leave navigation and Right reopens the group", () => {
fixture = createFixture();
const group = fixture.tree.treeItem(fixture.groupA as unknown as INode) as TreeGroup;
group.focus();
key(group, "ArrowLeft");
expect(group.getAttribute("aria-expanded")).toBe("false");
expect(group.isExpanded).toBe(false);
key(group, "End");
expect(document.activeElement).toBe(group);
key(group, "ArrowRight");
expect(group.getAttribute("aria-expanded")).toBe("true");
key(group, "ArrowRight");
expect(document.activeElement).toBe(fixture.tree.treeItem(fixture.model1 as unknown as INode));
});

test("Revit M then V reaches window without toggling visibility", () => {
fixture = createFixture();
const model = fixture.tree.treeItem(fixture.model1 as unknown as INode)!;
const clicked = rs.fn();
const observed: string[] = [];
const onKey = (event: KeyboardEvent) => observed.push(event.key);
model.visibleIcon.addEventListener("click", clicked);
window.addEventListener("keydown", onKey);
try {
expect(ShortcutProfiles.Revit["modify.move"]).toBe("m+v");
model.focus();
key(model, "m");
key(model, "v");
expect(observed).toEqual(["m", "v"]);
expect(clicked).not.toHaveBeenCalled();
expect(fixture.model1.visible).toBe(true);
} finally {
window.removeEventListener("keydown", onKey);
}
});

test("configured letter sequences remain window-owned in every shortcut profile", () => {
fixture = createFixture();
const model = fixture.tree.treeItem(fixture.model1 as unknown as INode)!;
const observed: string[] = [];
const onKey = (event: KeyboardEvent) => observed.push(event.key);
window.addEventListener("keydown", onKey);
try {
for (const profile of Object.values(ShortcutProfiles)) {
for (const specification of Object.values(profile).flat()) {
if (typeof specification !== "string") continue;
const letters = specification
.split("+")
.filter((segment) => /^[a-z]$/i.test(segment));
observed.length = 0;
for (const letter of letters) key(model, letter);
expect(observed).toEqual(letters);
}
}
} finally {
window.removeEventListener("keydown", onKey);
}
});

test("pointer or toolbar collapse cannot leave the only tab stop hidden", () => {
fixture = createFixture();
const model = fixture.tree.treeItem(fixture.model1 as unknown as INode)!;
const group = fixture.tree.treeItem(fixture.groupA as unknown as INode) as TreeGroup;
model.focus();
group.isExpanded = false;
expect(model.tabIndex).toBe(-1);
const stops = fixture.tree.querySelectorAll<HTMLElement>("[tabindex='0']");
expect(stops).toHaveLength(1);
expect(stops[0]).toBe(fixture.tree.treeItem(fixture.root as unknown as INode));
});

test("selection semantics update without stealing keyboard focus", () => {
fixture = createFixture();
const first = fixture.tree.treeItem(fixture.model1 as unknown as INode)!;
const second = fixture.tree.treeItem(fixture.model2 as unknown as INode)!;
first.focus();
fixture.doc.emitSelection([fixture.model2 as unknown as INode]);
expect(document.activeElement).toBe(first);
expect(first.getAttribute("aria-selected")).toBe("false");
expect(second.getAttribute("aria-selected")).toBe("true");
expect(first.tabIndex).toBe(0);
expect(second.tabIndex).toBe(-1);
});
});

describe("data to tree mapping", () => {
test("should build tree-group and tree-model elements from node hierarchy", () => {
fixture = createFixture();
Expand Down
Loading