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
4 changes: 4 additions & 0 deletions .changes/scrollto-latest-call-wins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
type: fix
---
A newer `tree.scrollTo()` call now replaces an older one that is still waiting for its row, so the list no longer jumps back to the older target when that row appears later. Scrolls that focusing or selecting a node start never replace a pending call.
4 changes: 4 additions & 0 deletions .changes/scrollto-surface-scroll-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
type: feature
---
`tree.scrollTo()` no longer swallows errors thrown while scrolling to a node. It still ignores the case where the id never appears, but any other error now rejects the returned promise instead of failing silently. Scrolls that focusing, selecting or editing a node start on their own still never reject. It also always returns a promise now, including when the id is empty.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -967,7 +967,7 @@ Returns true if the node with _id_ is internal and is under the dragged node.

_tree_.**scrollTo**(_id_, _[align]_)

Scroll to the node with _id_. If this node is not visible, this method will open all its parents. The align argument can be _"auto" | "smart" | "center" | "end" | "start"_.
Scroll to the node with _id_. If this node is not visible, this method will open all its parents. The align argument can be _"auto" | "smart" | "center" | "end" | "start"_. Returns a promise. It resolves once the node is scrolled into view, when a newer _scrollTo_ call replaces this one, or after about a second if no node with _id_ appears. It rejects if scrolling itself throws.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the updates, both look good. One small mismatch: this now says scrollTo returns a promise, but scrollTo(null) (or any falsy id) hits the early if (!identity) return; and returns undefined. JS callers who write tree.scrollTo(selectedId).then(...) with a null id would get a TypeError. Returning Promise.resolve() from that early exit would make the docs hold in every case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, fixed in e69895d. The early exit now returns Promise.resolve(), so scrollTo returns a promise for any id. It still leaves a pending call alone. Added a test for null and ""; both fail without the change. The changeset mentions it too.


_tree_.**scrollToOffset**(_offset_)

Expand Down
74 changes: 74 additions & 0 deletions modules/react-arborist/src/interfaces/tree-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,84 @@ describe("scrollTo stops waiting for an id that never appears (#403)", () => {
const done = api.scrollTo("missing");
jest.runAllTimers();
await done;
expect(jest.getTimerCount()).toBe(0);
expect(list.current.scrollToItem).not.toHaveBeenCalled();
});
});

describe("scrollTo returns a promise even without an id", () => {
test.each([null, ""])("%p", async (id) => {
const store = createStore(rootReducer);
const list = { current: { scrollToItem: jest.fn() } as any };
const api = new TreeApi(store, { data: rowData }, list, { current: null });
await expect(api.scrollTo(id)).resolves.toBeUndefined();
expect(list.current.scrollToItem).not.toHaveBeenCalled();
});
});

describe("scrollTo surfaces errors thrown while scrolling", () => {
function setup() {
const store = createStore(rootReducer);
const scrollToItem = jest.fn(() => {
throw new Error("scroll failed");
});
const list = { current: { scrollToItem } as any };
return { api: new TreeApi(store, { data: rowData }, list, { current: null }), scrollToItem };
}

test("rejects with the error from scrollToItem", async () => {
const { api } = setup();
await expect(api.scrollTo("b")).rejects.toThrow("scroll failed");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This covers the public promise, but nothing exercises the internal callers. A test that makes scrollToItem throw, calls api.select("b") or api.focus("b"), and checks that no unhandled rejection escapes would have caught the issue on tree-api.ts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in c35f357: focus, select, selectMulti, selectContiguous and edit each run against a scrollToItem that throws. All five fail without the fix. A process.on("unhandledRejection") spy doesn't work here, because Jest gives each test file its own process (it saw 0 calls), so the tests rely on Node rethrowing the unhandled rejection, which fails the running test.

});

test.each(["focus", "select", "selectMulti", "selectContiguous", "edit"] as const)(
"%s does not turn it into an unhandled rejection",
async (method) => {
const { api, scrollToItem } = setup();
api[method]("b");
// Node rethrows an unhandled rejection once the task ends, which fails this test.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(scrollToItem).toHaveBeenCalled();
},
);
});

describe("a newer scrollTo replaces an older one that is still waiting", () => {
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());

test("the older call does not scroll when its row appears later", async () => {
const store = createStore(rootReducer);
const list = { current: { scrollToItem: jest.fn() } as any };
const api = new TreeApi(store, { data: rowData }, list, { current: null });
const older = api.scrollTo("late");
await api.scrollTo("b");
api.update({ data: [...rowData, { id: "late" }] });
jest.runAllTimers();
await older;
expect(jest.getTimerCount()).toBe(0);
expect(list.current.scrollToItem).toHaveBeenCalledTimes(1);
expect(list.current.scrollToItem).toHaveBeenCalledWith(1, "smart");
});

test("a scroll started by select() does not replace it", async () => {
const store = createStore(rootReducer);
const list = { current: { scrollToItem: jest.fn() } as any };
const api = new TreeApi(store, { data: rowData }, list, { current: null });
const pending = api.scrollTo("late");
// What the controlled `selection` effect in provider.tsx does.
api.select("b", { focus: false });
api.update({ data: [...rowData, { id: "late" }] });
jest.runAllTimers();
await pending;
expect(jest.getTimerCount()).toBe(0);
expect(list.current.scrollToItem.mock.calls).toEqual([
[1, "smart"],
[3, "smart"],
]);
});
});

describe("scrollToOffset / scrollOffset set and read the vertical position (#194)", () => {
const data = [{ id: "a" }, { id: "b" }, { id: "c" }];

Expand Down
56 changes: 36 additions & 20 deletions modules/react-arborist/src/interfaces/tree-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class TreeApi<T> {
* the last hover of a frame wins, whichever row produced it. */
private pendingHover: { drop: DropResult | null; cursor: Cursor | null } | null = null;
private hoverThrottle = createAnimationFrameThrottle();
private scrollToken = 0;

constructor(
public store: Store<RootState, Actions>,
Expand Down Expand Up @@ -348,7 +349,7 @@ export class TreeApi<T> {
edit(node: string | IdObj | T): Promise<EditResult> {
const id = this.identify(node);
this.resolveEdit({ cancelled: true });
this.scrollTo(id);
this.scrollQuietly(id);
this.dispatch(edit(id));
this.redrawList(this.get(id)?.rowIndex ?? 0);
return new Promise((resolve) => {
Expand Down Expand Up @@ -413,7 +414,7 @@ export class TreeApi<T> {
this.select(node);
} else {
this.dispatch(focus(this.identify(node)));
if (opts.scroll !== false) this.scrollTo(node);
if (opts.scroll !== false) this.scrollQuietly(node);
if (this.focusedNode) safeRun(this.props.onFocus, this.focusedNode);
}
}
Expand Down Expand Up @@ -456,7 +457,7 @@ export class TreeApi<T> {
mostRecent: id,
});
}
this.scrollTo(id, opts.align);
this.scrollQuietly(id, opts.align);
if (this.focusedNode && changeFocus) {
safeRun(this.props.onFocus, this.focusedNode);
}
Expand All @@ -479,7 +480,7 @@ export class TreeApi<T> {
this.dispatch(selection.anchor(node.id));
this.dispatch(selection.mostRecent(node.id));
}
this.scrollTo(node, opts.align);
this.scrollQuietly(node, opts.align);
if (this.focusedNode && changeFocus) {
safeRun(this.props.onFocus, this.focusedNode);
}
Expand All @@ -499,7 +500,7 @@ export class TreeApi<T> {
this.dispatch(selection.add(selectableNodes.map((n) => n.id)));
this.dispatch(selection.mostRecent(id));
}
this.scrollTo(id);
this.scrollQuietly(id);
if (this.focusedNode) safeRun(this.props.onFocus, this.focusedNode);
safeRun(this.props.onSelect, this.selectedNodes);
}
Expand Down Expand Up @@ -732,7 +733,7 @@ export class TreeApi<T> {
}
}
this.redrawList();
this.scrollTo(this.focusedNode);
this.scrollQuietly(this.focusedNode);
}
}

Expand All @@ -753,23 +754,38 @@ export class TreeApi<T> {
/* Scrolling */

scrollTo(identity: Identity | T, align: Align = "smart") {
if (!identity) return Promise.resolve();
const token = ++this.scrollToken;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for adding scrollQuietly, that takes care of the unhandled rejections. One follow-on: since scrollQuietly goes through scrollTo, internal scrolls also bump scrollToken, so any focus or selection change cancels an explicit tree.scrollTo(id) that's still waiting for its row.

A user clicking another row winning seems fine. The case that worries me is a controlled selection prop. The effect in components/provider.tsx calls api.select(api.props.selection, { focus: false }), which scrolls. So an app that adds a node, calls tree.scrollTo(newId) and updates selection in the same handler gets its scrollTo silently cancelled when that effect runs after the next render. Before this PR both scrolls would have run.

Could internal scrolls skip the token bump (or use their own), so only public scrollTo calls replace each other?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 1fdc44d. scrollTo and scrollQuietly now share a private scrollWhenReady(id, align, superseded). Only scrollTo bumps the token, and internal scrolls are never superseded, so they don't cancel each other or a pending scrollTo, same as before this PR.

Added a test for your case: scrollTo("late") is pending, select("b", { focus: false }) runs (what the controlled selection effect does), then late appears and still gets scrolled to. It fails on c35f357.

return this.scrollWhenReady(this.identify(identity), align, () => token !== this.scrollToken);
}

/* For scrolls that are a side effect of focus, selection or editing. Nobody
awaits them, so a rejection would surface as an unhandled one. They also
leave the token alone, so a controlled selection update can't cancel a
pending scrollTo(). */
private scrollQuietly(identity: Identity | T, align: Align = "smart") {
if (!identity) return;
const id = this.identify(identity);
this.scrollWhenReady(this.identify(identity), align, () => false).catch(() => {});
}

private scrollWhenReady(id: string, align: Align, superseded: () => boolean) {
this.openParents(id);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two small questions, not blockers:

  • openParents(id) runs before the cancellation check, so a call that's later replaced still leaves its target's ancestors expanded. That seems reasonable (the call did happen), just confirming it's intended.
  • The if (!identity) return; early return comes before ++this.scrollToken, so scrollTo(null) can't cancel a pending wait. Intended?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both intended:

  • openParents runs synchronously when the call is made, so by the time a newer call replaces it, the ancestors are already open; only the scroll is cancelled. Collapsing them again would mean tracking which folders that call opened, and could close one the user opened in the meantime.
  • scrollTo(null) has no target, so it leaves a pending call alone. openSiblings calls scrollTo(this.focusedNode), which is null when nothing is focused. If null cancelled, that call would silently drop an unrelated pending scroll.

return utils
.waitFor(() => id in this.idToIndex)
.then(() => {
const index = this.idToIndex[id];
if (index === undefined) return;
this.list.current?.scrollToItem(index, align);
/* react-window only scrolls vertically. A deeply nested node is
indented by level * indent and can sit past the right edge when rows
overflow horizontally, so bring it into view ourselves (#220). */
this.scrollToNodeHorizontally(this.get(id));
})
.catch(() => {
// Id: ${id} never appeared in the list.
});
.waitFor(() => superseded() || id in this.idToIndex)
.then(
() => {
if (superseded()) return;
const index = this.idToIndex[id];
if (index === undefined) return;
this.list.current?.scrollToItem(index, align);
/* react-window only scrolls vertically. A deeply nested node is
indented by level * indent and can sit past the right edge when rows
overflow horizontally, so bring it into view ourselves (#220). */
this.scrollToNodeHorizontally(this.get(id));
},
// Only waitFor giving up is ignored; errors thrown while scrolling reject.
() => {},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Now that errors thrown inside the .then reject instead of being swallowed, the internal callers turn them into unhandled rejections. scrollTo is called without a catch from lines 352, 417, 460, 483, 503 and 736 (focus, select, selectMulti, edit, the focused-node re-scroll and others), so a throwing scrollToItem during a click now surfaces as "Uncaught (in promise)" where it used to be silent.

Maybe give those call sites a .catch(() => {}), or route them through a private helper that does, so only the promise returned to a user's own tree.scrollTo() call can reject?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c35f357. The six internal call sites now go through a private scrollQuietly() that adds .catch(() => {}), so only the promise from a user's own tree.scrollTo() can reject. The changeset says that now too.

);
}

/**
Expand Down
2 changes: 2 additions & 0 deletions modules/react-arborist/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ test("waitFor rejects after checking fn WAIT_FOR_TRIES times", async () => {
const done = expect(waitFor(fn)).rejects.toBeUndefined();
jest.runAllTimers();
await done;
expect(jest.getTimerCount()).toBe(0);
expect(fn).toHaveBeenCalledTimes(WAIT_FOR_TRIES);
});

Expand All @@ -16,4 +17,5 @@ test("waitFor resolves when fn first returns true on the last try", async () =>
const done = expect(waitFor(() => ++calls === WAIT_FOR_TRIES)).resolves.toBeUndefined();
jest.runAllTimers();
await done;
expect(jest.getTimerCount()).toBe(0);
});
Loading