summaryrefslogtreecommitdiffstats
path: root/toolkit/components/formautofill/shared/FormAutofillHandler.sys.mjs
blob: 49f79be77a9377ee35b4fe43059bc4b7bd472cfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { FormAutofill } from "resource://autofill/FormAutofill.sys.mjs";
import { FormAutofillUtils } from "resource://gre/modules/shared/FormAutofillUtils.sys.mjs";

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  FormAutofillAddressSection:
    "resource://gre/modules/shared/FormAutofillSection.sys.mjs",
  FormAutofillCreditCardSection:
    "resource://gre/modules/shared/FormAutofillSection.sys.mjs",
  FormAutofillHeuristics:
    "resource://gre/modules/shared/FormAutofillHeuristics.sys.mjs",
  FormLikeFactory: "resource://gre/modules/FormLikeFactory.sys.mjs",
  FormSection: "resource://gre/modules/shared/FormAutofillHeuristics.sys.mjs",
});

const { FIELD_STATES } = FormAutofillUtils;

/**
 * Handles profile autofill for a DOM Form element.
 */
export class FormAutofillHandler {
  // The window to which this form belongs
  window = null;

  // A WindowUtils reference of which Window the form belongs
  winUtils = null;

  // DOM Form element to which this object is attached
  form = null;

  // An array of section that are found in this form
  sections = [];

  // The section contains the focused input
  #focusedSection = null;

  // Caches the element to section mapping
  #cachedSectionByElement = new WeakMap();

  // Keeps track of filled state for all identified elements
  #filledStateByElement = new WeakMap();
  /**
   * Array of collected data about relevant form fields.  Each item is an object
   * storing the identifying details of the field and a reference to the
   * originally associated element from the form.
   *
   * The "section", "addressType", "contactType", and "fieldName" values are
   * used to identify the exact field when the serializable data is received
   * from the backend.  There cannot be multiple fields which have
   * the same exact combination of these values.
   *
   * A direct reference to the associated element cannot be sent to the user
   * interface because processing may be done in the parent process.
   */
  fieldDetails = null;

  /**
   * Initialize the form from `FormLike` object to handle the section or form
   * operations.
   *
   * @param {FormLike} form Form that need to be auto filled
   * @param {Function} onFormSubmitted Function that can be invoked
   *                   to simulate form submission. Function is passed
   *                   four arguments: (1) a FormLike for the form being
   *                   submitted, (2) the reason for infering the form
   *                   submission (3) the corresponding Window, and (4)
   *                   the responsible FormAutofillHandler.
   * @param {Function} onAutofillCallback Function that can be invoked
   *                   when we want to suggest autofill on a form.
   */
  constructor(form, onFormSubmitted = () => {}, onAutofillCallback = () => {}) {
    this._updateForm(form);

    this.window = this.form.rootElement.ownerGlobal;
    this.winUtils = this.window.windowUtils;

    // Enum for form autofill MANUALLY_MANAGED_STATES values
    this.FIELD_STATE_ENUM = {
      // not themed
      [FIELD_STATES.NORMAL]: null,
      // highlighted
      [FIELD_STATES.AUTO_FILLED]: "autofill",
      // highlighted && grey color text
      [FIELD_STATES.PREVIEW]: "-moz-autofill-preview",
    };

    /**
     * This function is used if the form handler (or one of its sections)
     * determines that it needs to act as if the form had been submitted.
     */
    this.onFormSubmitted = formSubmissionReason => {
      onFormSubmitted(this.form, formSubmissionReason, this.window, this);
    };

    this.onAutofillCallback = onAutofillCallback;

    ChromeUtils.defineLazyGetter(this, "log", () =>
      FormAutofill.defineLogGetter(this, "FormAutofillHandler")
    );
  }

  handleEvent(event) {
    switch (event.type) {
      case "input": {
        if (!event.isTrusted) {
          return;
        }
        const target = event.target;
        const targetFieldDetail = this.getFieldDetailByElement(target);
        const isCreditCardField = FormAutofillUtils.isCreditCardField(
          targetFieldDetail.fieldName
        );

        // If the user manually blanks a credit card field, then
        // we want the popup to be activated.
        if (
          !HTMLSelectElement.isInstance(target) &&
          isCreditCardField &&
          target.value === ""
        ) {
          this.onAutofillCallback();
        }

        if (this.getFilledStateByElement(target) == FIELD_STATES.NORMAL) {
          return;
        }

        this.changeFieldState(targetFieldDetail, FIELD_STATES.NORMAL);
        const section = this.getSectionByElement(targetFieldDetail.element);
        section?.clearFilled(targetFieldDetail);
      }
    }
  }

  set focusedInput(element) {
    const section = this.getSectionByElement(element);
    if (!section) {
      return;
    }

    this.#focusedSection = section;
    this.#focusedSection.focusedInput = element;
  }

  getSectionByElement(element) {
    const section =
      this.#cachedSectionByElement.get(element) ??
      this.sections.find(s => s.getFieldDetailByElement(element));
    if (!section) {
      return null;
    }

    this.#cachedSectionByElement.set(element, section);
    return section;
  }

  getFieldDetailByElement(element) {
    for (const section of this.sections) {
      const detail = section.getFieldDetailByElement(element);
      if (detail) {
        return detail;
      }
    }
    return null;
  }

  get activeSection() {
    return this.#focusedSection;
  }

  /**
   * Check the form is necessary to be updated. This function should be able to
   * detect any changes including all control elements in the form.
   *
   * @param {HTMLElement} element The element supposed to be in the form.
   * @returns {boolean} FormAutofillHandler.form is updated or not.
   */
  updateFormIfNeeded(element) {
    // When the following condition happens, FormAutofillHandler.form should be
    // updated:
    // * The count of form controls is changed.
    // * When the element can not be found in the current form.
    //
    // However, we should improve the function to detect the element changes.
    // e.g. a tel field is changed from type="hidden" to type="tel".

    let _formLike;
    const getFormLike = () => {
      if (!_formLike) {
        _formLike = lazy.FormLikeFactory.createFromField(element);
      }
      return _formLike;
    };

    const currentForm = element.form ?? getFormLike();
    if (currentForm.elements.length != this.form.elements.length) {
      this.log.debug("The count of form elements is changed.");
      this._updateForm(getFormLike());
      return true;
    }

    if (!this.form.elements.includes(element)) {
      this.log.debug("The element can not be found in the current form.");
      this._updateForm(getFormLike());
      return true;
    }

    return false;
  }

  /**
   * Update the form with a new FormLike, and the related fields should be
   * updated or clear to ensure the data consistency.
   *
   * @param {FormLike} form a new FormLike to replace the original one.
   */
  _updateForm(form) {
    this.form = form;

    this.fieldDetails = null;

    this.sections = [];
    this.#cachedSectionByElement = new WeakMap();
  }

  /**
   * Set fieldDetails from the form about fields that can be autofilled.
   *
   * @returns {Array} The valid address and credit card details.
   */
  collectFormFields(ignoreInvalid = true) {
    const sections = lazy.FormAutofillHeuristics.getFormInfo(this.form);
    const allValidDetails = [];
    for (const section of sections) {
      // We don't support csc field, so remove csc fields from section
      const fieldDetails = section.fieldDetails.filter(
        f => !["cc-csc"].includes(f.fieldName)
      );
      if (!fieldDetails.length) {
        continue;
      }

      let autofillableSection;
      if (section.type == lazy.FormSection.ADDRESS) {
        autofillableSection = new lazy.FormAutofillAddressSection(
          fieldDetails,
          this
        );
      } else {
        autofillableSection = new lazy.FormAutofillCreditCardSection(
          fieldDetails,
          this
        );
      }

      // Do not include section that is either disabled or invalid.
      // We only include invalid section for testing purpose.
      if (
        !autofillableSection.isEnabled() ||
        (ignoreInvalid && !autofillableSection.isValidSection())
      ) {
        continue;
      }

      this.sections.push(autofillableSection);
      allValidDetails.push(...autofillableSection.fieldDetails);
    }

    this.fieldDetails = allValidDetails;
    return allValidDetails;
  }

  #hasFilledSection() {
    return this.sections.some(section => section.isFilled());
  }

  getFilledStateByElement(element) {
    return this.#filledStateByElement.get(element);
  }

  /**
   * Change the state of a field to correspond with different presentations.
   *
   * @param {object} fieldDetail
   *        A fieldDetail of which its element is about to update the state.
   * @param {string} nextState
   *        Used to determine the next state
   */
  changeFieldState(fieldDetail, nextState) {
    const element = fieldDetail.element;
    if (!element) {
      this.log.warn(
        fieldDetail.fieldName,
        "is unreachable while changing state"
      );
      return;
    }
    if (!(nextState in this.FIELD_STATE_ENUM)) {
      this.log.warn(
        fieldDetail.fieldName,
        "is trying to change to an invalid state"
      );
      return;
    }

    if (this.#filledStateByElement.get(element) == nextState) {
      return;
    }

    let nextStateValue = null;
    for (const [state, mmStateValue] of Object.entries(this.FIELD_STATE_ENUM)) {
      // The NORMAL state is simply the absence of other manually
      // managed states so we never need to add or remove it.
      if (!mmStateValue) {
        continue;
      }

      if (state == nextState) {
        nextStateValue = mmStateValue;
      } else {
        this.winUtils.removeManuallyManagedState(element, mmStateValue);
      }
    }

    if (nextStateValue) {
      this.winUtils.addManuallyManagedState(element, nextStateValue);
    }

    if (nextState == FIELD_STATES.AUTO_FILLED) {
      element.addEventListener("input", this, { mozSystemGroup: true });
    }

    this.#filledStateByElement.set(element, nextState);
  }

  /**
   * Processes form fields that can be autofilled, and populates them with the
   * profile provided by backend.
   *
   * @param {object} profile
   *        A profile to be filled in.
   */
  async autofillFormFields(profile) {
    const noFilledSectionsPreviously = !this.#hasFilledSection();
    await this.activeSection.autofillFields(profile);

    const onChangeHandler = e => {
      if (!e.isTrusted) {
        return;
      }
      if (e.type == "reset") {
        this.sections.map(section => section.resetFieldStates());
      }
      // Unregister listeners once no field is in AUTO_FILLED state.
      if (!this.#hasFilledSection()) {
        this.form.rootElement.removeEventListener("input", onChangeHandler, {
          mozSystemGroup: true,
        });
        this.form.rootElement.removeEventListener("reset", onChangeHandler, {
          mozSystemGroup: true,
        });
      }
    };

    if (noFilledSectionsPreviously) {
      // Handle the highlight style resetting caused by user's correction afterward.
      this.log.debug("register change handler for filled form:", this.form);
      this.form.rootElement.addEventListener("input", onChangeHandler, {
        mozSystemGroup: true,
      });
      this.form.rootElement.addEventListener("reset", onChangeHandler, {
        mozSystemGroup: true,
      });
    }
  }

  /**
   * Collect the filled sections within submitted form and convert all the valid
   * field data into multiple records.
   *
   * @returns {object} records
   *          {Array.<Object>} records.address
   *          {Array.<Object>} records.creditCard
   */
  createRecords() {
    const records = {
      address: [],
      creditCard: [],
    };

    for (const section of this.sections) {
      const secRecord = section.createRecord();
      if (!secRecord) {
        continue;
      }
      if (section instanceof lazy.FormAutofillAddressSection) {
        records.address.push(secRecord);
      } else if (section instanceof lazy.FormAutofillCreditCardSection) {
        records.creditCard.push(secRecord);
      } else {
        throw new Error("Unknown section type");
      }
    }

    return records;
  }
}