Skip to content

Commit

Permalink
fix: Only blur if not refreshing, and if dirty. (#40)
Browse files Browse the repository at this point in the history
* fix: Only blur if not refreshing, and if dirty.

* Add another test.
  • Loading branch information
stephenh authored Dec 10, 2021
1 parent 1696c52 commit f555688
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
37 changes: 37 additions & 0 deletions src/formState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,10 @@ describe("formState", () => {
a1.firstName.value = "first";
// Then we call onBlur
expect(onBlur).toBeCalledTimes(1);
// And when we set a nested value
a1.books.rows[0].title.value = "title";
// Then we called onBlur again
expect(onBlur).toBeCalledTimes(2);
});

it("defers calling onBlur when setting a bound value", () => {
Expand All @@ -422,6 +426,39 @@ describe("formState", () => {
expect(onBlur).toBeCalledTimes(0);
});

it("skips onBlur when refreshing", () => {
const onBlur = jest.fn();
// Given an author listening for blur
const a1 = createAuthorInputState({ books: [{}] }, onBlur);
// When we programmatically set a field that isn't focused
(a1 as any).set({ firstName: "first" }, { refreshing: true });
// Then we don't call onBlur
expect(onBlur).toBeCalledTimes(0);
});

it("skips onBlur when resetting", () => {
const onBlur = jest.fn();
// Given an author listening for blur
const a1 = createAuthorInputState({ books: [{}] }, onBlur);
// And we called onBlur once
a1.set({ firstName: "first" });
expect(onBlur).toBeCalledTimes(1);
// When we reset
a1.reset();
// We don't call blur again
expect(onBlur).toBeCalledTimes(1);
});

it("skips onBlur when not dirty", () => {
const onBlur = jest.fn();
// Given an author listening for blur
const a1 = createAuthorInputState({ firstName: "first", books: [{}] }, onBlur);
// When we programmatically set a field to it's existing valued
a1.firstName.value = "first";
// Then we don't call onBlur
expect(onBlur).toBeCalledTimes(0);
});

it("knows list of primitives are dirty", () => {
const a1 = createObjectState<AuthorInput>({ favoriteColors: { type: "value" } }, {});
expect(a1.favoriteColors.dirty).toBeFalsy();
Expand Down
2 changes: 1 addition & 1 deletion src/formState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ function newValueFieldState<T, K extends keyof T>(
}
// If we're being set programmatically, i.e. we don't currently have focus,
// call blur to trigger any auto-saves.
if (!this._focused) {
if (!this._focused && !opts.refreshing && !opts.resetting && this.dirty) {
this.blur();
}
},
Expand Down

0 comments on commit f555688

Please sign in to comment.