From f555688c7ffc336525b133b470a0aba0faa02095 Mon Sep 17 00:00:00 2001 From: Stephen Haberman Date: Fri, 10 Dec 2021 14:41:20 -0600 Subject: [PATCH] fix: Only blur if not refreshing, and if dirty. (#40) * fix: Only blur if not refreshing, and if dirty. * Add another test. --- src/formState.test.tsx | 37 +++++++++++++++++++++++++++++++++++++ src/formState.ts | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/formState.test.tsx b/src/formState.test.tsx index ebe8738..9170f07 100644 --- a/src/formState.test.tsx +++ b/src/formState.test.tsx @@ -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", () => { @@ -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({ favoriteColors: { type: "value" } }, {}); expect(a1.favoriteColors.dirty).toBeFalsy(); diff --git a/src/formState.ts b/src/formState.ts index 6b4404d..0ba4c03 100644 --- a/src/formState.ts +++ b/src/formState.ts @@ -696,7 +696,7 @@ function newValueFieldState( } // 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(); } },