summaryrefslogtreecommitdiffstats
path: root/toolkit/components/satchel/megalist/aggregator/datasources/AddressesDataSource.sys.mjs
blob: f00df0b40b90dbfb9949ebd8267bdcedea6f11d3 (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
/* 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 { DataSourceBase } from "resource://gre/modules/megalist/aggregator/datasources/DataSourceBase.sys.mjs";
import { formAutofillStorage } from "resource://autofill/FormAutofillStorage.sys.mjs";

async function updateAddress(address, field, value) {
  try {
    const newAddress = {
      ...address,
      [field]: value ?? "",
    };

    formAutofillStorage.INTERNAL_FIELDS.forEach(
      name => delete newAddress[name]
    );
    formAutofillStorage.addresses.VALID_COMPUTED_FIELDS.forEach(
      name => delete newAddress[name]
    );

    if (address.guid) {
      await formAutofillStorage.addresses.update(address.guid, newAddress);
    } else {
      await formAutofillStorage.addresses.add(newAddress);
    }
  } catch (error) {
    //todo
    console.error("failed to modify address", error);
    return false;
  }

  return true;
}

/**
 * Data source for Addresses.
 *
 */

export class AddressesDataSource extends DataSourceBase {
  #namePrototype;
  #organizationPrototype;
  #streetAddressPrototype;
  #addressLevelOnePrototype;
  #addressLevelTwoPrototype;
  #addressLevelThreePrototype;
  #postalCodePrototype;
  #countryPrototype;
  #phonePrototype;
  #emailPrototype;

  #addressesDisabledMessage;
  #enabled;
  #header;

  constructor(...args) {
    super(...args);
    this.formatMessages(
      "addresses-section-label",
      "address-name-label",
      "address-phone-label",
      "address-email-label",
      "command-copy",
      "addresses-disabled",
      "command-delete",
      "command-edit",
      "addresses-command-create"
    ).then(
      ([
        headerLabel,
        nameLabel,
        phoneLabel,
        emailLabel,
        copyLabel,
        addressesDisabled,
        deleteLabel,
        editLabel,
        createLabel,
      ]) => {
        const copyCommand = { id: "Copy", label: copyLabel };
        const editCommand = { id: "Edit", label: editLabel };
        const deleteCommand = { id: "Delete", label: deleteLabel };
        this.#addressesDisabledMessage = addressesDisabled;
        this.#header = this.createHeaderLine(headerLabel);
        this.#header.commands.push({ id: "Create", label: createLabel });

        let self = this;

        function prototypeLine(label, key, options = {}) {
          return self.prototypeDataLine({
            label: { value: label },
            value: {
              get() {
                return this.editingValue ?? this.record[key];
              },
            },
            commands: {
              value: [copyCommand, editCommand, "-", deleteCommand],
            },
            executeEdit: {
              value() {
                this.editingValue = this.record[key] ?? "";
                this.refreshOnScreen();
              },
            },
            executeSave: {
              async value(value) {
                if (await updateAddress(this.record, key, value)) {
                  this.executeCancel();
                }
              },
            },
            ...options,
          });
        }

        this.#namePrototype = prototypeLine(nameLabel, "name", {
          start: { value: true },
        });
        this.#organizationPrototype = prototypeLine(
          "Organization",
          "organization"
        );
        this.#streetAddressPrototype = prototypeLine(
          "Street Address",
          "street-address"
        );
        this.#addressLevelThreePrototype = prototypeLine(
          "Neighbourhood",
          "address-level3"
        );
        this.#addressLevelTwoPrototype = prototypeLine(
          "City",
          "address-level2"
        );
        this.#addressLevelOnePrototype = prototypeLine(
          "Province",
          "address-level1"
        );
        this.#postalCodePrototype = prototypeLine("Postal Code", "postal-code");
        this.#countryPrototype = prototypeLine("Country", "country");
        this.#phonePrototype = prototypeLine(phoneLabel, "tel");
        this.#emailPrototype = prototypeLine(emailLabel, "email", {
          end: { value: true },
        });

        Services.obs.addObserver(this, "formautofill-storage-changed");
        Services.prefs.addObserver(
          "extensions.formautofill.addresses.enabled",
          this
        );
        this.#reloadDataSource();
      }
    );
  }

  async #reloadDataSource() {
    this.#enabled = Services.prefs.getBoolPref(
      "extensions.formautofill.addresses.enabled"
    );
    if (!this.#enabled) {
      this.#reloadEmptyDataSource();
      return;
    }

    await formAutofillStorage.initialize();
    const addresses = await formAutofillStorage.addresses.getAll();
    this.beforeReloadingDataSource();
    addresses.forEach(address => {
      const lineId = `${address.name}:${address.tel}`;

      this.addOrUpdateLine(address, lineId + "0", this.#namePrototype);
      this.addOrUpdateLine(address, lineId + "1", this.#organizationPrototype);
      this.addOrUpdateLine(address, lineId + "2", this.#streetAddressPrototype);
      this.addOrUpdateLine(
        address,
        lineId + "3",
        this.#addressLevelThreePrototype
      );
      this.addOrUpdateLine(
        address,
        lineId + "4",
        this.#addressLevelTwoPrototype
      );
      this.addOrUpdateLine(
        address,
        lineId + "5",
        this.#addressLevelOnePrototype
      );
      this.addOrUpdateLine(address, lineId + "6", this.#postalCodePrototype);
      this.addOrUpdateLine(address, lineId + "7", this.#countryPrototype);
      this.addOrUpdateLine(address, lineId + "8", this.#phonePrototype);
      this.addOrUpdateLine(address, lineId + "9", this.#emailPrototype);
    });
    this.afterReloadingDataSource();
  }

  /**
   * Enumerate all the lines provided by this data source.
   *
   * @param {string} searchText used to filter data
   */
  *enumerateLines(searchText) {
    if (this.#enabled === undefined) {
      // Async Fluent API makes it possible to have data source waiting
      // for the localized strings, which can be detected by undefined in #enabled.
      return;
    }

    yield this.#header;
    if (this.#header.collapsed || !this.#enabled) {
      return;
    }

    const stats = { total: 0, count: 0 };
    searchText = searchText.toUpperCase();
    yield* this.enumerateLinesForMatchingRecords(searchText, stats, address =>
      [
        "name",
        "organization",
        "street-address",
        "address-level3",
        "address-level2",
        "address-level1",
        "postal-code",
        "country",
        "tel",
        "email",
      ].some(key => address[key]?.toUpperCase().includes(searchText))
    );

    this.formatMessages({
      id:
        stats.count == stats.total
          ? "addresses-count"
          : "addresses-filtered-count",
      args: stats,
    }).then(([headerLabel]) => {
      this.#header.value = headerLabel;
    });
  }

  #reloadEmptyDataSource() {
    this.lines.length = 0;
    this.#header.value = this.#addressesDisabledMessage;
    this.refreshAllLinesOnScreen();
  }

  observe(_subj, topic, message) {
    if (
      topic == "formautofill-storage-changed" ||
      message == "extensions.formautofill.addresses.enabled"
    ) {
      this.#reloadDataSource();
    }
  }
}