@homebound/form-state 2.26.2 → 2.26.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -104,6 +104,69 @@ See the [sample](https://github.com/homebound-team/form-state/blob/main/src/Form
104
104
 
105
105
  # Features
106
106
 
107
+ ## Incremental changedValue/dirty Management
108
+
109
+ In general, we have two types of forms:
110
+
111
+ - `autoSave` forms
112
+ - `submit` forms
113
+
114
+ ### autoSave forms
115
+
116
+ For auto save forms, the expectation is that you should:
117
+
118
+ - Pass `useFormState` an `init.input` and `init.map` that updates the form-state from the initial GraphQL request & any cache updates
119
+ - Pass `useFormState` an `autoSave` lambda that calls your GraphQL mutation, using `changedValue`.
120
+ - Have your `save` mutation response return the acked/updated entity/fragment
121
+
122
+ ```ts
123
+ autoSave: async () => {
124
+ const input = formState.changedValue;
125
+ await saveAuthor(input);
126
+ };
127
+ ```
128
+
129
+ With these in place, we will correctly handle interleaved edits/saves, i.e.:
130
+
131
+ 1. User changes `{ firstName: bob }`
132
+ 2. We submit `{ id: 1, firstName: bob }` to the backend
133
+ 3. While waiting for the response, the user sets `{ lastName: smith }`
134
+ 4. The GraphQL mutation acks that `{ id: 1, firstName: bob }` is committed
135
+ 5. The `init.map` updates `formState` to realize `firstName` is no longer dirty, but `lastName` keeps its WIP change
136
+ 6. formState will trigger a 2nd `autoSave` for just the `lastName` change
137
+
138
+ ### Submit forms
139
+
140
+ For submit forms, the expectation is that you should:
141
+
142
+ - Pass `useFormState` an `init.input` and `init.map` that updates the form-state from the initial GraphQL request & any cache updates
143
+ - In your `onClick` lambda, use `formState.changedValue` to call your GraphQL mutation
144
+ - Have your `save` mutation response return the acked/updated entity/fragment
145
+
146
+ If you do this, you should not have to call `commitChanges` manually, because code like:
147
+
148
+ ```ts
149
+ onClick: async () => {
150
+ const input = formState.changedValue;
151
+ await saveAuthor(input);
152
+ // checks if formState.dirty is true before closing
153
+ closeModal();
154
+ };
155
+ ```
156
+
157
+ Will "just work" because the control flow will be:
158
+
159
+ - User changes `{ firstName: bob }` and clicks Submit
160
+ - `onClick` runs and we submit `{ id: 1, firstName: bob }` to `saveAuthor`
161
+ - _Before_ the `await` promise resolves, the GraphQL response of `saveAuthor { ...AuthorFragment }` will:
162
+ - Update the apollo cache
163
+ - Re-render the `AuthorEditor` component with the new data
164
+ - Call `init.map` to update `formState` with the new data
165
+ - Realize the `firstName` is no longer dirty
166
+ - When `closeModal` runs, no "You have unsaved changes?" will appear
167
+
168
+ Basically, in a correctly-setup form, you should never have to call `commitChanges` manually, and doing so risks losing edits that the user made while any saves (either auto save or submit save) were in-flight.
169
+
107
170
  ## Fragments
108
171
 
109
172
  Normally, form-state expects all fields in the form to be inputs to the GraphQL mutation/wire call. For example, the `author.firstName` field will always be submitted to the `saveAuthor` mutation (albeit with `author.changedValue` you can have `firstName` conditionally included).
@@ -57,6 +57,10 @@ function newObjectState(config, parentState, parentInstance, parentListState, in
57
57
  field = (0, listField_1.newListFieldState)(originalCopy, instance, getObjectState, key, config.rules || [], config, { type: "object", config: config.config }, (_d = config.strictOrder) !== null && _d !== void 0 ? _d : true, maybeAutoSave);
58
58
  }
59
59
  else if (config.type === "object") {
60
+ // Because our objectField will fundamentally want to do `child.firstName.set(...)` or
61
+ // even `child.firstName !== undefined`, etc., we "simplify" things by always setting
62
+ // an empty object, for our child valueFields/listFields to use/read from, although
63
+ // we then have to "oh right ignore {}" in places like `dirty`.
60
64
  if (!instance[key]) {
61
65
  instance[key] = {};
62
66
  }
@@ -131,7 +135,10 @@ function newObjectState(config, parentState, parentInstance, parentListState, in
131
135
  return getFields(this).flatMap((f) => f.errors.map((e) => `${f.key}: ${e}`));
132
136
  },
133
137
  get dirty() {
134
- return getFields(this).some((f) => f.dirty) || this.isUnset();
138
+ return (getFields(this).some((f) => f.dirty) ||
139
+ // `isUnset` checks if our `parent[key] === undefined`, which can mean "surely we're dirty",
140
+ // but as long as we've got some keys actually set
141
+ (this.isUnset() && !(0, utils_1.areEqual)(this.value, {})));
135
142
  },
136
143
  get isNewEntity() {
137
144
  const idField = getFields(this).find((f) => f._isIdKey);
@@ -207,7 +214,11 @@ function newObjectState(config, parentState, parentInstance, parentListState, in
207
214
  // look dirty, but if we're new we should include them anyway.
208
215
  (this.isNewEntity && f._kind === "value" && f.value !== undefined) ||
209
216
  // ...or they're non-empty sub-objects
210
- (this.isNewEntity && f._kind === "object" && Object.entries(f.changedValue).length > 0) ||
217
+ (this.isNewEntity &&
218
+ f._kind === "object" &&
219
+ // Child objects that are unset will have `changedValue = null`
220
+ f.changedValue &&
221
+ Object.entries(f.changedValue).length > 0) ||
211
222
  // ...or they're non-empty sub-lists
212
223
  (this.isNewEntity && f._kind === "list" && ((_a = f.value) === null || _a === void 0 ? void 0 : _a.length) > 0)) {
213
224
  result[f.key] = f.changedValue;
@@ -100,7 +100,8 @@ function newValueFieldState(parentCopy, parentInstance, parentState, key, rules,
100
100
  if (this.readOnly && !opts.resetting && !opts.refreshing) {
101
101
  throw new Error(`${String(key)} is currently readOnly`);
102
102
  }
103
- if (opts.refreshing && this.dirty && this.value !== value) {
103
+ const isAckingUnset = this.value === null && (value === null || value === undefined);
104
+ if (opts.refreshing && this.dirty && this.value !== value && !isAckingUnset) {
104
105
  // Ignore incoming values if we have changes (this.dirty) unless our latest change (this.value)
105
106
  // matches the incoming value (value), b/c if it does we should accept it and reset originalValue
106
107
  // so that we're no longer dirty.
@@ -595,6 +595,19 @@ describe("formState", () => {
595
595
  a1.firstName.set("a1");
596
596
  expect(a1.dirty).toBeFalsy();
597
597
  });
598
+ it("realizes object fields set to null aren't actually dirty", () => {
599
+ // Given we started off with a `object: undefined`
600
+ const a1 = createAuthorWithAddressInputState({ address: undefined });
601
+ expect(a1.address.dirty).toBe(false);
602
+ expect(a1.address.value).toEqual({});
603
+ // And it's later set to null, i.e. from a mutation returning `{ address: null }`
604
+ a1.set({ firstName: "a1", address: null });
605
+ // Then we convert it to `{}` to potentially hold data
606
+ expect(a1.address.value).toEqual({});
607
+ // But we don't consider the address dirty
608
+ expect(a1.address.dirty).toBe(false);
609
+ expect(a1.changedValue).toEqual({ firstName: "a1" });
610
+ });
598
611
  it("knows an object's field of type object is dirty", () => {
599
612
  const a1 = createAuthorInputState({
600
613
  books: [{ title: "b1", classification: formStateDomain_1.dd100 }],
@@ -722,6 +735,13 @@ describe("formState", () => {
722
735
  expect(a1.firstName.value).toBeNull();
723
736
  expect(a1.originalValue.firstName).toBe("asdf");
724
737
  expect(a1.firstName.dirty).toBeTruthy();
738
+ // And when the server acks as null
739
+ a1.set({ firstName: undefined }, { refreshing: true });
740
+ // Then it's no longer dirty
741
+ expect(a1.firstName.dirty).toBe(false);
742
+ expect(a1.firstName.originalValue).toBe(undefined);
743
+ expect(a1.firstName.value).toBe(undefined);
744
+ expect(a1.changedValue).toEqual({});
725
745
  });
726
746
  it("initializes null values to be undefined", () => {
727
747
  // Given a property that is initially set to null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@homebound/form-state",
3
- "version": "2.26.2",
3
+ "version": "2.26.4",
4
4
  "author": "Homebound",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",