Skip to content

Commit ac9ef69

Browse files
authored
Prevent Selection Sync From Stealing Focus (#118)
Prevent Selection Sync From Stealing Focus Fixes #117
1 parent abfc6d6 commit ac9ef69

File tree

4 files changed

+19
-4
lines changed

4 files changed

+19
-4
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ yarn-error.log*
3434
!.yarn/versions
3535

3636
.parcel-cache
37+
.vscode
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
describe("Testing the Cities Demo", () => {
2+
beforeEach(() => {
3+
cy.visit("http://localhost:3000/cities");
4+
});
5+
6+
it("Does not steel the selection when the selection prop changes", () => {
7+
cy.get("button").contains("Select San Francisco").click();
8+
cy.focused().invoke("is", "button").should("equal", true);
9+
cy.focused().should("have.text", "Select San Francisco");
10+
});
11+
});

packages/react-arborist/src/components/provider.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export function TreeProvider<T>({
6565
/* Change selection based on props */
6666
useEffect(() => {
6767
if (api.props.selection) {
68-
api.select(api.props.selection);
68+
api.select(api.props.selection, { focus: false });
6969
} else {
7070
api.deselectAll();
7171
}

packages/react-arborist/src/interfaces/tree-api.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -323,15 +323,18 @@ export class TreeApi<T> {
323323
this.focus(this.at(index));
324324
}
325325

326-
select(node: Identity, opts: { align?: Align } = {}) {
326+
select(node: Identity, opts: { align?: Align; focus?: boolean } = {}) {
327327
if (!node) return;
328+
const changeFocus = opts.focus !== false;
328329
const id = identify(node);
329-
this.dispatch(focus(id));
330+
if (changeFocus) this.dispatch(focus(id));
330331
this.dispatch(selection.only(id));
331332
this.dispatch(selection.anchor(id));
332333
this.dispatch(selection.mostRecent(id));
333334
this.scrollTo(id, opts.align);
334-
if (this.focusedNode) safeRun(this.props.onFocus, this.focusedNode);
335+
if (this.focusedNode && changeFocus) {
336+
safeRun(this.props.onFocus, this.focusedNode);
337+
}
335338
safeRun(this.props.onSelect, this.selectedNodes);
336339
}
337340

0 commit comments

Comments
 (0)