summaryrefslogtreecommitdiffstats
path: root/comm/calendar/base/content/dialogs/calendar-ics-file-dialog.js
blob: 41c85eeea9923e6d2a52126398b7d59b239dcc62 (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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/* 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/. */

/* globals addMenuItem, getItemsFromIcsFile, putItemsIntoCal,
           sortCalendarArray */

var { cal } = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm");

const gModel = {
  /** @type {calICalendar[]} */
  calendars: [],

  /** @type {Map(number -> calIItemBase)} */
  itemsToImport: new Map(),

  /** @type {nsIFile | null} */
  file: null,

  /** @type {Map(number -> CalendarItemSummary)} */
  itemSummaries: new Map(),
};

/**
 * Window load event handler.
 */
async function onWindowLoad() {
  // Workaround to add padding to the dialog buttons area which is in shadow dom.
  // If the padding value changes here it should also change in the CSS.
  let dialog = document.getElementsByTagName("dialog")[0];
  dialog.shadowRoot.querySelector(".dialog-button-box").style = "padding-inline: 10px;";

  gModel.file = window.arguments[0];
  document.getElementById("calendar-ics-file-dialog-file-path").value = gModel.file.path;

  let calendars = cal.manager.getCalendars();
  gModel.calendars = getCalendarsThatCanImport(calendars);
  if (!gModel.calendars.length) {
    // No calendars to import into. Show error dialog and close the window.
    cal.showError(await document.l10n.formatValue("calendar-ics-file-dialog-no-calendars"), window);
    window.close();
    return;
  }

  let composite = cal.view.getCompositeCalendar(window);
  let defaultCalendarId = composite && composite.defaultCalendar?.id;
  setUpCalendarMenu(gModel.calendars, defaultCalendarId);
  cal.view.colorTracker.registerWindow(window);

  // Finish laying out and displaying the window, then come back to do the hard work.
  Services.tm.dispatchToMainThread(async () => {
    let startTime = Date.now();

    getItemsFromIcsFile(gModel.file).forEach((item, index) => {
      gModel.itemsToImport.set(index, item);
    });
    if (gModel.itemsToImport.size == 0) {
      // No items to import, close the window. An error dialog has already been
      // shown by `getItemsFromIcsFile`.
      window.close();
      return;
    }

    // We know that if `getItemsFromIcsFile` took a long time, then `setUpItemSummaries` will also
    // take a long time. Show a loading message so the user knows something is happening.
    let loadingMessage = document.getElementById("calendar-ics-file-dialog-items-loading-message");
    if (Date.now() - startTime > 150) {
      loadingMessage.removeAttribute("hidden");
      await new Promise(resolve => requestAnimationFrame(resolve));
    }

    // Not much point filtering or sorting if there's only one event.
    if (gModel.itemsToImport.size == 1) {
      document.getElementById("calendar-ics-file-dialog-filters").collapsed = true;
    }

    await setUpItemSummaries();

    // Remove the loading message from the DOM to avoid it causing problems later.
    loadingMessage.remove();

    document.addEventListener("dialogaccept", importRemainingItems);
  });
}
window.addEventListener("load", onWindowLoad);

/**
 * Takes an array of calendars and returns a sorted array of the calendars
 * that can import items.
 *
 * @param {calICalendar[]} calendars - An array of calendars.
 * @returns {calICalendar[]} Sorted array of calendars that can import items.
 */
function getCalendarsThatCanImport(calendars) {
  let calendarsThatCanImport = calendars.filter(
    calendar =>
      !calendar.getProperty("disabled") &&
      !calendar.readOnly &&
      cal.acl.userCanAddItemsToCalendar(calendar)
  );
  return sortCalendarArray(calendarsThatCanImport);
}

/**
 * Add calendars to the calendar drop down menu, and select one.
 *
 * @param {calICalendar[]} calendars - An array of calendars.
 * @param {string | null} defaultCalendarId - ID of the default (currently selected) calendar.
 */
function setUpCalendarMenu(calendars, defaultCalendarId) {
  let menulist = document.getElementById("calendar-ics-file-dialog-calendar-menu");
  for (let calendar of calendars) {
    let menuitem = addMenuItem(menulist, calendar.name, calendar.name);
    let cssSafeId = cal.view.formatStringForCSSRule(calendar.id);
    menuitem.style.setProperty("--item-color", `var(--calendar-${cssSafeId}-backcolor)`);
    menuitem.classList.add("menuitem-iconic");
  }

  let index = defaultCalendarId
    ? calendars.findIndex(calendar => calendar.id == defaultCalendarId)
    : 0;

  menulist.selectedIndex = index == -1 ? 0 : index;
  updateCalendarMenu();
}

/**
 * Update to reflect a change in the selected calendar.
 */
function updateCalendarMenu() {
  let menulist = document.getElementById("calendar-ics-file-dialog-calendar-menu");
  menulist.style.setProperty(
    "--item-color",
    menulist.selectedItem.style.getPropertyValue("--item-color")
  );
}

/**
 * Display summaries of each calendar item from the file being imported.
 */
async function setUpItemSummaries() {
  let items = [...gModel.itemsToImport];
  let itemsContainer = document.getElementById("calendar-ics-file-dialog-items-container");

  // Sort the items, chronologically first, tasks without a date to the end,
  // then alphabetically.
  let collator = new Intl.Collator(undefined, { numeric: true });
  items.sort(([, a], [, b]) => {
    let aStartDate =
      a.startDate?.nativeTime ||
      a.entryDate?.nativeTime ||
      a.dueDate?.nativeTime ||
      Number.MAX_SAFE_INTEGER;
    let bStartDate =
      b.startDate?.nativeTime ||
      b.entryDate?.nativeTime ||
      b.dueDate?.nativeTime ||
      Number.MAX_SAFE_INTEGER;
    return aStartDate - bStartDate || collator.compare(a.title, b.title);
  });

  let [eventButtonText, taskButtonText] = await document.l10n.formatValues([
    "calendar-ics-file-dialog-import-event-button-label",
    "calendar-ics-file-dialog-import-task-button-label",
  ]);

  items.forEach(([index, item]) => {
    let itemFrame = document.createXULElement("vbox");
    itemFrame.classList.add("calendar-ics-file-dialog-item-frame");

    let importButton = document.createXULElement("button");
    importButton.classList.add("calendar-ics-file-dialog-item-import-button");
    importButton.setAttribute("label", item.isEvent() ? eventButtonText : taskButtonText);
    importButton.addEventListener("command", importSingleItem.bind(null, item, index));

    let buttonBox = document.createXULElement("hbox");
    buttonBox.setAttribute("pack", "end");
    buttonBox.setAttribute("align", "end");

    let summary = document.createXULElement("calendar-item-summary");
    summary.setAttribute("id", "import-item-summary-" + index);

    itemFrame.appendChild(summary);
    buttonBox.appendChild(importButton);
    itemFrame.appendChild(buttonBox);

    itemsContainer.appendChild(itemFrame);
    summary.item = item;

    summary.updateItemDetails();
    gModel.itemSummaries.set(index, summary);
  });
}

/**
 * Filter item summaries by search string.
 *
 * @param {searchString} [searchString] - Terms to search for.
 */
function filterItemSummaries(searchString = "") {
  let itemsContainer = document.getElementById("calendar-ics-file-dialog-items-container");

  searchString = searchString.trim();
  // Nothing to search for. Display all item summaries.
  if (!searchString) {
    gModel.itemSummaries.forEach(s => {
      s.closest(".calendar-ics-file-dialog-item-frame").hidden = false;
    });

    itemsContainer.scrollTo(0, 0);
    return;
  }

  searchString = searchString.toLowerCase().normalize();

  // Split the search string into tokens. Quoted strings are preserved.
  let searchTokens = [];
  let startIndex;
  while ((startIndex = searchString.indexOf('"')) != -1) {
    let endIndex = searchString.indexOf('"', startIndex + 1);
    if (endIndex == -1) {
      endIndex = searchString.length;
    }

    searchTokens.push(searchString.substring(startIndex + 1, endIndex));
    let query = searchString.substring(0, startIndex);
    if (endIndex < searchString.length) {
      query += searchString.substr(endIndex + 1);
    }

    searchString = query.trim();
  }

  if (searchString.length != 0) {
    searchTokens = searchTokens.concat(searchString.split(/\s+/));
  }

  // Check the title and description of each item for matches.
  gModel.itemSummaries.forEach(s => {
    let title, description;
    let matches = searchTokens.every(term => {
      if (title === undefined) {
        title = s.item.title.toLowerCase().normalize();
      }
      if (title?.includes(term)) {
        return true;
      }

      if (description === undefined) {
        description = s.item.getProperty("description")?.toLowerCase().normalize();
      }
      return description?.includes(term);
    });
    s.closest(".calendar-ics-file-dialog-item-frame").hidden = !matches;
  });

  itemsContainer.scrollTo(0, 0);
}

/**
 * Sort item summaries.
 *
 * @param {Event} event - The oncommand event that triggered this sort.
 */
function sortItemSummaries(event) {
  let [key, direction] = event.target.value.split(" ");

  let comparer;
  if (key == "title") {
    let collator = new Intl.Collator(undefined, { numeric: true });
    if (direction == "ascending") {
      comparer = (a, b) => collator.compare(a.item.title, b.item.title);
    } else {
      comparer = (a, b) => collator.compare(b.item.title, a.item.title);
    }
  } else if (key == "start") {
    if (direction == "ascending") {
      comparer = (a, b) => a.item.startDate.nativeTime - b.item.startDate.nativeTime;
    } else {
      comparer = (a, b) => b.item.startDate.nativeTime - a.item.startDate.nativeTime;
    }
  } else {
    // How did we get here?
    throw new Error(`Unexpected sort key: ${key}`);
  }

  let items = [...gModel.itemSummaries.values()].sort(comparer);
  let itemsContainer = document.getElementById("calendar-ics-file-dialog-items-container");
  for (let item of items) {
    itemsContainer.appendChild(item.closest(".calendar-ics-file-dialog-item-frame"));
  }
  itemsContainer.scrollTo(0, 0);

  for (let menuitem of document.querySelectorAll(
    "#calendar-ics-file-dialog-sort-popup > menuitem"
  )) {
    menuitem.checked = menuitem == event.target;
  }
}

/**
 * Get the currently selected calendar.
 *
 * @returns {calICalendar} The currently selected calendar.
 */
function getCurrentlySelectedCalendar() {
  let menulist = document.getElementById("calendar-ics-file-dialog-calendar-menu");
  let calendar = gModel.calendars[menulist.selectedIndex];
  return calendar;
}

/**
 * Handler for buttons that import a single item. The arguments are bound for
 * each button instance, except for the event argument.
 *
 * @param {calIItemBase} item - Calendar item.
 * @param {number} itemIndex - Index of the calendar item in the item array.
 * @param {string} filePath - Path to the file being imported.
 * @param {Event} event - The button event.
 */
async function importSingleItem(item, itemIndex, event) {
  let dialog = document.getElementsByTagName("dialog")[0];
  let acceptButton = dialog.getButton("accept");
  let cancelButton = dialog.getButton("cancel");

  acceptButton.disabled = true;
  cancelButton.disabled = true;

  let calendar = getCurrentlySelectedCalendar();

  await putItemsIntoCal(calendar, [item], {
    onDuplicate(item, error) {
      // TODO: CalCalendarManager already shows a not-very-useful error pop-up.
      // Once that is fixed, use this callback to display a proper error message.
    },
    onError(item, error) {
      // TODO: CalCalendarManager already shows a not-very-useful error pop-up.
      // Once that is fixed, use this callback to display a proper error message.
    },
  });

  event.target.closest(".calendar-ics-file-dialog-item-frame").remove();
  gModel.itemsToImport.delete(itemIndex);
  gModel.itemSummaries.delete(itemIndex);

  acceptButton.disabled = false;
  if (gModel.itemsToImport.size > 0) {
    // Change the cancel button label to Close, as we've done some work that
    // won't be cancelled.
    cancelButton.label = await document.l10n.formatValue(
      "calendar-ics-file-cancel-button-close-label"
    );
    cancelButton.disabled = false;
  } else {
    // No more items to import, remove the "Import All" option.
    document.removeEventListener("dialogaccept", importRemainingItems);

    cancelButton.hidden = true;
    acceptButton.label = await document.l10n.formatValue(
      "calendar-ics-file-accept-button-ok-label"
    );
  }
}

/**
 * "Import All" button command handler.
 *
 * @param {Event} event - Button command event.
 */
async function importRemainingItems(event) {
  event.preventDefault();

  let dialog = document.getElementsByTagName("dialog")[0];
  let acceptButton = dialog.getButton("accept");
  let cancelButton = dialog.getButton("cancel");

  acceptButton.disabled = true;
  cancelButton.disabled = true;

  let calendar = getCurrentlySelectedCalendar();
  let filteredSummaries = [...gModel.itemSummaries.values()].filter(
    summary => !summary.closest(".calendar-ics-file-dialog-item-frame").hidden
  );
  let remainingItems = filteredSummaries.map(summary => summary.item);

  let progressElement = document.getElementById("calendar-ics-file-dialog-progress");
  let duplicatesElement = document.getElementById("calendar-ics-file-dialog-duplicates-message");
  let errorsElement = document.getElementById("calendar-ics-file-dialog-errors-message");

  let optionsPane = document.getElementById("calendar-ics-file-dialog-options-pane");
  let progressPane = document.getElementById("calendar-ics-file-dialog-progress-pane");
  let resultPane = document.getElementById("calendar-ics-file-dialog-result-pane");

  let importListener = {
    count: 0,
    duplicatesCount: 0,
    errorsCount: 0,
    progressInterval: null,

    onStart() {
      progressElement.max = remainingItems.length;
      optionsPane.hidden = true;
      progressPane.hidden = false;

      this.progressInterval = setInterval(() => {
        progressElement.value = this.count;
      }, 50);
    },
    onDuplicate(item, error) {
      this.duplicatesCount++;
    },
    onError(item, error) {
      this.errorsCount++;
    },
    onProgress(count, total) {
      this.count = count;
    },
    async onEnd() {
      progressElement.value = this.count;
      clearInterval(this.progressInterval);

      document.l10n.setAttributes(duplicatesElement, "calendar-ics-file-import-duplicates", {
        duplicatesCount: this.duplicatesCount,
      });
      duplicatesElement.hidden = this.duplicatesCount == 0;
      document.l10n.setAttributes(errorsElement, "calendar-ics-file-import-errors", {
        errorsCount: this.errorsCount,
      });
      errorsElement.hidden = this.errorsCount == 0;

      let [acceptButtonLabel, cancelButtonLabel] = await document.l10n.formatValues([
        { id: "calendar-ics-file-accept-button-ok-label" },
        { id: "calendar-ics-file-cancel-button-close-label" },
      ]);

      filteredSummaries.forEach(summary => {
        let itemIndex = parseInt(summary.id.substring("import-item-summary-".length), 10);
        gModel.itemsToImport.delete(itemIndex);
        gModel.itemSummaries.delete(itemIndex);
        summary.closest(".calendar-ics-file-dialog-item-frame").remove();
      });

      document.getElementById("calendar-ics-file-dialog-search-input").value = "";
      filterItemSummaries();
      let itemsRemain = !!document.querySelector(".calendar-ics-file-dialog-item-frame");

      // An artificial delay so the progress pane doesn't appear then immediately disappear.
      setTimeout(() => {
        if (itemsRemain) {
          acceptButton.disabled = false;
          cancelButton.label = cancelButtonLabel;
          cancelButton.disabled = false;
        } else {
          acceptButton.label = acceptButtonLabel;
          acceptButton.disabled = false;
          cancelButton.hidden = true;
          document.removeEventListener("dialogaccept", importRemainingItems);
        }

        optionsPane.hidden = !itemsRemain;
        progressPane.hidden = true;
        resultPane.hidden = itemsRemain;
      }, 500);
    },
  };

  putItemsIntoCal(calendar, remainingItems, importListener);
}

/**
 * These functions are called via `putItemsIntoCal` in import-export.js so
 * they need to be defined in global scope but they don't need to do anything
 * in this case.
 */
function startBatchTransaction() {}
function endBatchTransaction() {}