summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/options/autofill_edit_address_overlay.js
blob: b5aec2d1561806fb319b62af252e921744b258dd (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  /** @const */ var Page = cr.ui.pageManager.Page;
  /** @const */ var PageManager = cr.ui.pageManager.PageManager;
  /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;

  /**
   * AutofillEditAddressOverlay class
   * Encapsulated handling of the 'Add Page' overlay page.
   * @constructor
   * @extends {cr.ui.pageManager.Page}
   */
  function AutofillEditAddressOverlay() {
    Page.call(this, 'autofillEditAddress',
              loadTimeData.getString('autofillEditAddressTitle'),
              'autofill-edit-address-overlay');
  }

  cr.addSingletonGetter(AutofillEditAddressOverlay);

  AutofillEditAddressOverlay.prototype = {
    __proto__: Page.prototype,

    /**
     * The GUID of the loaded address.
     * @type {string}
     */
    guid_: '',

    /**
     * The BCP 47 language code for the layout of input fields.
     * @type {string}
     */
    languageCode_: '',

    /**
     * The saved field values for the address. For example, if the user changes
     * from United States to Switzerland, then the State field will be hidden
     * and its value will be stored here. If the user changes back to United
     * States, then the State field will be restored to its previous value, as
     * stored in this object.
     * @type {Object}
     */
    savedFieldValues_: {},

    /** @override */
    initializePage: function() {
      Page.prototype.initializePage.call(this);

      this.createMultiValueLists_();

      var self = this;
      $('autofill-edit-address-cancel-button').onclick = function(event) {
        self.dismissOverlay_();
      };

      // TODO(jhawkins): Investigate other possible solutions.
      $('autofill-edit-address-apply-button').onclick = function(event) {
        // Blur active element to ensure that pending changes are committed.
        if (document.activeElement)
          document.activeElement.blur();
        // Blurring is delayed for list elements.  Queue save and close to
        // ensure that pending changes have been applied.
        setTimeout(function() {
          self.pageDiv.querySelector('[field=phone]').doneValidating().then(
              function() {
                self.saveAddress_();
                self.dismissOverlay_();
              });
        }, 0);
      };

      // Prevent 'blur' events on the OK and cancel buttons, which can trigger
      // insertion of new placeholder elements.  The addition of placeholders
      // affects layout, which interferes with being able to click on the
      // buttons.
      $('autofill-edit-address-apply-button').onmousedown = function(event) {
        event.preventDefault();
      };
      $('autofill-edit-address-cancel-button').onmousedown = function(event) {
        event.preventDefault();
      };

      this.guid_ = '';
      this.populateCountryList_();
      this.rebuildInputFields_(
          loadTimeData.getValue('autofillDefaultCountryComponents'));
      this.languageCode_ =
          loadTimeData.getString('autofillDefaultCountryLanguageCode');
      this.connectInputEvents_();
      this.setInputFields_({});
      this.getCountrySwitcher_().onchange = function(event) {
        self.countryChanged_();
      };
    },

    /**
    * Specifically catch the situations in which the overlay is cancelled
    * externally (e.g. by pressing <Esc>), so that the input fields and
    * GUID can be properly cleared.
    * @override
    */
    handleCancel: function() {
      this.dismissOverlay_();
    },

    /**
     * Creates, decorates and initializes the multi-value lists for phone and
     * email.
     * @private
     */
    createMultiValueLists_: function() {
      var list = this.pageDiv.querySelector('[field=phone]');
      options.autofillOptions.AutofillPhoneValuesList.decorate(list);
      list.autoExpands = true;

      list = this.pageDiv.querySelector('[field=email]');
      options.autofillOptions.AutofillValuesList.decorate(list);
      list.autoExpands = true;
    },

    /**
     * Updates the data model for the |list| with the values from |entries|.
     * @param {cr.ui.List} list The list to update.
     * @param {Array} entries The list of items to be added to the list.
     * @private
     */
    setMultiValueList_: function(list, entries) {
      // Add special entry for adding new values.
      var augmentedList = entries.slice();
      augmentedList.push(null);
      list.dataModel = new ArrayDataModel(augmentedList);

      // Update the status of the 'OK' button.
      this.inputFieldChanged_();

      list.dataModel.addEventListener('splice',
                                      this.inputFieldChanged_.bind(this));
      list.dataModel.addEventListener('change',
                                      this.inputFieldChanged_.bind(this));
    },

    /**
     * Clears any uncommitted input, resets the stored GUID and dismisses the
     * overlay.
     * @private
     */
    dismissOverlay_: function() {
      this.setInputFields_({});
      this.inputFieldChanged_();
      this.guid_ = '';
      this.languageCode_ = '';
      this.savedInputFields_ = {};
      PageManager.closeOverlay();
    },

    /**
     * @return {Element} The element used to switch countries.
     * @private
     */
    getCountrySwitcher_: function() {
      return this.pageDiv.querySelector('[field=country]');
    },

    /**
     * Returns all list elements.
     * @return {!NodeList} The list elements.
     * @private
     */
    getLists_: function() {
      return this.pageDiv.querySelectorAll('list[field]');
    },

    /**
     * Returns all text input elements.
     * @return {!NodeList} The text input elements.
     * @private
     */
    getTextFields_: function() {
      return this.pageDiv.querySelectorAll('textarea[field], input[field]');
    },

    /**
     * Creates a map from type => value for all text fields.
     * @return {Object} The mapping from field names to values.
     * @private
     */
    getInputFields_: function() {
      var address = {country: this.getCountrySwitcher_().value};

      var lists = this.getLists_();
      for (var i = 0; i < lists.length; i++) {
        address[lists[i].getAttribute('field')] =
            lists[i].dataModel.slice(0, lists[i].dataModel.length - 1);
      }

      var fields = this.getTextFields_();
      for (var i = 0; i < fields.length; i++) {
        address[fields[i].getAttribute('field')] = fields[i].value;
      }

      return address;
    },

    /**
     * Sets the value of each input field according to |address|.
     * @param {Object} address The object with values to use.
     * @private
     */
    setInputFields_: function(address) {
      this.getCountrySwitcher_().value = address.country || '';

      var lists = this.getLists_();
      for (var i = 0; i < lists.length; i++) {
        this.setMultiValueList_(
            lists[i], address[lists[i].getAttribute('field')] || []);
      }

      var fields = this.getTextFields_();
      for (var i = 0; i < fields.length; i++) {
        fields[i].value = address[fields[i].getAttribute('field')] || '';
      }
    },

    /**
     * Aggregates the values in the input fields into an array and sends the
     * array to the Autofill handler.
     * @private
     */
    saveAddress_: function() {
      var inputFields = this.getInputFields_();
      var address = [
        this.guid_,
        inputFields['fullName'] || [],
        inputFields['companyName'] || '',
        inputFields['addrLines'] || '',
        inputFields['dependentLocality'] || '',
        inputFields['city'] || '',
        inputFields['state'] || '',
        inputFields['postalCode'] || '',
        inputFields['sortingCode'] || '',
        inputFields['country'] || '',
        inputFields['phone'] || [],
        inputFields['email'] || [],
        this.languageCode_,
      ];
      chrome.send('setAddress', address);
    },

    /**
     * Connects each input field to the inputFieldChanged_() method that enables
     * or disables the 'Ok' button based on whether all the fields are empty or
     * not.
     * @private
     */
    connectInputEvents_: function() {
      var fields = this.getTextFields_();
      for (var i = 0; i < fields.length; i++) {
        fields[i].oninput = this.inputFieldChanged_.bind(this);
      }
    },

    /**
     * Disables the 'Ok' button if all of the fields are empty.
     * @private
     */
    inputFieldChanged_: function() {
      var disabled = !this.getCountrySwitcher_().value;
      if (disabled) {
        // Length of lists are tested for > 1 due to the "add" placeholder item
        // in the list.
        var lists = this.getLists_();
        for (var i = 0; i < lists.length; i++) {
          if (lists[i].items.length > 1) {
            disabled = false;
            break;
          }
        }
      }

      if (disabled) {
        var fields = this.getTextFields_();
        for (var i = 0; i < fields.length; i++) {
          if (fields[i].value) {
            disabled = false;
            break;
          }
        }
      }

      $('autofill-edit-address-apply-button').disabled = disabled;
    },

    /**
     * Updates the address fields appropriately for the selected country.
     * @private
     */
    countryChanged_: function() {
      var countryCode = this.getCountrySwitcher_().value;
      if (countryCode)
        chrome.send('loadAddressEditorComponents', [countryCode]);
      else
        this.inputFieldChanged_();
    },

    /**
     * Populates the country <select> list.
     * @private
     */
    populateCountryList_: function() {
      var countryList = loadTimeData.getValue('autofillCountrySelectList');

      // Add the countries to the country <select> list.
      var countrySelect = this.getCountrySwitcher_();
      // Add an empty option.
      countrySelect.appendChild(new Option('', ''));
      for (var i = 0; i < countryList.length; i++) {
        var option = new Option(countryList[i].name,
                                countryList[i].value);
        option.disabled = countryList[i].value == 'separator';
        countrySelect.appendChild(option);
      }
    },

    /**
     * Called to prepare the overlay when a new address is being added.
     * @private
     */
    prepForNewAddress_: function() {
      // Focus the first element.
      this.pageDiv.querySelector('input').focus();
    },

    /**
     * Loads the address data from |address|, sets the input fields based on
     * this data, and stores the GUID and language code of the address.
     * @param {!Object} address Lots of info about an address from the browser.
     * @private
     */
    loadAddress_: function(address) {
      this.rebuildInputFields_(address.components);
      this.setInputFields_(address);
      this.inputFieldChanged_();
      this.connectInputEvents_();
      this.guid_ = address.guid;
      this.languageCode_ = address.languageCode;
    },

    /**
     * Takes a snapshot of the input values, clears the input values, loads the
     * address input layout from |input.components|, restores the input values
     * from snapshot, and stores the |input.languageCode| for the address.
     * @param {{languageCode: string, components: Array.<Array.<Object>>}} input
     *     Info about how to layout inputs fields in this dialog.
     * @private
     */
    loadAddressComponents_: function(input) {
      var inputFields = this.getInputFields_();
      for (var fieldName in inputFields) {
        if (inputFields.hasOwnProperty(fieldName))
          this.savedFieldValues_[fieldName] = inputFields[fieldName];
      }
      this.rebuildInputFields_(input.components);
      this.setInputFields_(this.savedFieldValues_);
      this.inputFieldChanged_();
      this.connectInputEvents_();
      this.languageCode_ = input.languageCode;
    },

    /**
     * Clears address inputs and rebuilds the input fields according to
     * |components|.
     * @param {Array.<Array.<Object>>} components A list of information about
     *     each input field.
     * @private
     */
    rebuildInputFields_: function(components) {
      var content = $('autofill-edit-address-fields');
      content.innerHTML = '';

      var customContainerElements = {fullName: 'div'};
      var customInputElements = {fullName: 'list', addrLines: 'textarea'};

      for (var i in components) {
        var row = document.createElement('div');
        row.classList.add('input-group', 'settings-row');
        content.appendChild(row);

        for (var j in components[i]) {
          if (components[i][j].field == 'country')
            continue;

          var fieldContainer = document.createElement(
              customContainerElements[components[i][j].field] || 'label');
          row.appendChild(fieldContainer);

          var fieldName = document.createElement('div');
          fieldName.textContent = components[i][j].name;
          fieldContainer.appendChild(fieldName);

          var input = document.createElement(
              customInputElements[components[i][j].field] || 'input');
          input.setAttribute('field', components[i][j].field);
          input.classList.add(components[i][j].length);
          input.setAttribute('placeholder', components[i][j].placeholder || '');
          fieldContainer.appendChild(input);

          if (input.tagName == 'LIST') {
            options.autofillOptions.AutofillValuesList.decorate(input);
            input.autoExpands = true;
          }
        }
      }
    },
  };

  AutofillEditAddressOverlay.prepForNewAddress = function() {
    AutofillEditAddressOverlay.getInstance().prepForNewAddress_();
  };

  AutofillEditAddressOverlay.loadAddress = function(address) {
    AutofillEditAddressOverlay.getInstance().loadAddress_(address);
  };

  AutofillEditAddressOverlay.loadAddressComponents = function(input) {
    AutofillEditAddressOverlay.getInstance().loadAddressComponents_(input);
  };

  AutofillEditAddressOverlay.setTitle = function(title) {
    $('autofill-address-title').textContent = title;
  };

  AutofillEditAddressOverlay.setValidatedPhoneNumbers = function(numbers) {
    var instance = AutofillEditAddressOverlay.getInstance();
    var phoneList = instance.pageDiv.querySelector('[field=phone]');
    instance.setMultiValueList_(assertInstanceof(phoneList, cr.ui.List),
                                numbers);
    phoneList.didReceiveValidationResult();
  };

  // Export
  return {
    AutofillEditAddressOverlay: AutofillEditAddressOverlay
  };
});