summaryrefslogtreecommitdiffstats
path: root/comm/calendar/base/modules/utils/calPrintUtils.jsm
blob: ad7b022f3c9e0ec527a8e443f65bee5bf1f27626 (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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/* 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/. */

/**
 * Helpers for printing.
 *
 * This file detects when printing starts, and if it's the calendar that is
 * being printed, injects calendar-print.js into the printing UI.
 *
 * Also contains the code for formatting the to-be-printed document as chosen
 * by the user.
 */

// NOTE: This module should not be loaded directly, it is available when
// including calUtils.jsm under the cal.print namespace.

const EXPORTED_SYMBOLS = ["calprint"];

const lazy = {};
ChromeUtils.defineModuleGetter(lazy, "cal", "resource:///modules/calendar/calUtils.jsm");

var calprint = {
  ensureInitialized() {
    // Deliberate no-op. By calling this function from outside, you've ensured
    // the observer has been added.
  },

  async draw(document, type, startDate, endDate, filter, notDueTasks) {
    lazy.cal.view.colorTracker.addColorsToDocument(document);

    let listContainer = document.getElementById("list-container");
    while (listContainer.lastChild) {
      listContainer.lastChild.remove();
    }
    let monthContainer = document.getElementById("month-container");
    while (monthContainer.lastChild) {
      monthContainer.lastChild.remove();
    }
    let weekContainer = document.getElementById("week-container");
    while (weekContainer.lastChild) {
      weekContainer.lastChild.remove();
    }

    let taskContainer = document.getElementById("task-container");
    while (taskContainer.lastChild) {
      taskContainer.lastChild.remove();
    }
    document.getElementById("tasks-list-box").hidden = true;

    switch (type) {
      case "list":
        await listView.draw(document, startDate, endDate, filter, notDueTasks);
        break;
      case "monthGrid":
        await monthGridView.draw(document, startDate, endDate, filter, notDueTasks);
        break;
      case "weekPlanner":
        await weekPlannerView.draw(document, startDate, endDate, filter, notDueTasks);
        break;
    }
  },
};

/**
 * Serializes the given item by setting marked nodes to the item's content.
 * Has some expectations about the DOM document (in CSS-selector-speak), all
 * following nodes MUST exist.
 *
 * - #item-template will be cloned and filled, and modified:
 *   - .item-interval gets the time interval of the item.
 *   - .item-title gets the item title
 *   - .category-color-box gets a 2px solid border in category color
 *   - .calendar-color-box gets background color of the calendar
 *
 * @param document          The DOM Document to set things on
 * @param item              The item to serialize
 * @param dayContainer      The DOM Node to insert the container in
 */
function addItemToDaybox(document, item, boxDate, dayContainer) {
  // Clone our template
  let itemNode = document.getElementById("item-template").content.firstElementChild.cloneNode(true);
  itemNode.removeAttribute("id");
  itemNode.item = item;

  // Fill in details of the item
  let itemInterval = getItemIntervalString(item, boxDate);
  itemNode.querySelector(".item-interval").textContent = itemInterval;
  itemNode.querySelector(".item-title").textContent = item.title;

  // Fill in category details
  let categoriesArray = item.getCategories();
  if (categoriesArray.length > 0) {
    let cssClassesArray = categoriesArray.map(lazy.cal.view.formatStringForCSSRule);
    itemNode.style.borderInlineEnd = `2px solid var(--category-${cssClassesArray[0]}-color)`;
  }

  // Fill in calendar color
  let cssSafeId = lazy.cal.view.formatStringForCSSRule(item.calendar.id);
  itemNode.style.color = `var(--calendar-${cssSafeId}-forecolor)`;
  itemNode.style.backgroundColor = `var(--calendar-${cssSafeId}-backcolor)`;

  // Add it to the day container in the right order
  lazy.cal.data.binaryInsertNode(dayContainer, itemNode, item, lazy.cal.view.compareItems);
}

/**
 * Serializes the given item by setting marked nodes to the item's
 * content. Should be used for tasks with no start and due date. Has
 * some expectations about the DOM document (in CSS-selector-speak),
 * all following nodes MUST exist.
 *
 * - Nodes will be added to #task-container.
 * - #task-list-box will have the "hidden" attribute removed.
 * - #task-template will be cloned and filled, and modified:
 *   - .task-checkbox gets the "checked" attribute set, if completed
 *   - .task-title gets the item title.
 *
 * @param document          The DOM Document to set things on
 * @param item              The item to serialize
 */
function addItemToDayboxNodate(document, item) {
  let taskContainer = document.getElementById("task-container");
  let taskNode = document.getElementById("task-template").content.firstElementChild.cloneNode(true);
  taskNode.item = item;

  let taskListBox = document.getElementById("tasks-list-box");
  if (taskListBox.hasAttribute("hidden")) {
    let tasksTitle = document.getElementById("tasks-title");
    taskListBox.removeAttribute("hidden");
    tasksTitle.textContent = lazy.cal.l10n.getCalString("tasksWithNoDueDate");
  }

  // Fill in details of the task
  if (item.isCompleted) {
    taskNode.querySelector(".task-checkbox").setAttribute("checked", "checked");
  }

  taskNode.querySelector(".task-title").textContent = item.title;

  const collator = new Intl.Collator();
  lazy.cal.data.binaryInsertNode(
    taskContainer,
    taskNode,
    item,
    collator.compare,
    node => node.item.title
  );
}

/**
 * Get time interval string for the given item. Returns an empty string for all-day items.
 *
 * @param aItem     The item providing the interval
 * @returns The string describing the interval
 */
function getItemIntervalString(aItem, aBoxDate) {
  // omit time label for all-day items
  let formatter = lazy.cal.dtz.formatter;
  let startDate = aItem[lazy.cal.dtz.startDateProp(aItem)];
  let endDate = aItem[lazy.cal.dtz.endDateProp(aItem)];
  if ((startDate && startDate.isDate) || (endDate && endDate.isDate)) {
    return "";
  }

  // check for tasks without start and/or due date
  if (!startDate || !endDate) {
    return formatter.formatItemTimeInterval(aItem);
  }

  let defaultTimezone = lazy.cal.dtz.defaultTimezone;
  startDate = startDate.getInTimezone(defaultTimezone);
  endDate = endDate.getInTimezone(defaultTimezone);
  let start = startDate.clone();
  let end = endDate.clone();
  start.isDate = true;
  end.isDate = true;
  if (start.compare(end) == 0) {
    // Events that start and end in the same day.
    return formatter.formatTimeInterval(startDate, endDate);
  }
  // Events that span two or more days.
  let compareStart = aBoxDate.compare(start);
  let compareEnd = aBoxDate.compare(end);
  if (compareStart == 0) {
    return "\u21e4 " + formatter.formatTime(startDate); // unicode '⇤'
  } else if (compareStart > 0 && compareEnd < 0) {
    return "\u21ff"; // unicode '↔'
  } else if (compareEnd == 0) {
    return "\u21e5 " + formatter.formatTime(endDate); // unicode '⇥'
  }
  return "";
}

/**
 * Gets items from the composite calendar for printing.
 *
 * @param {calIDateTime} startDate
 * @param {calIDateTime} endDate
 * @param {integer} filter - calICalendar ITEM_FILTER flags
 * @param {boolean} notDueTasks - if true, include tasks with no due date
 * @returns {Promise<calIItemBase[]>}
 */
async function getItems(startDate, endDate, filter, notDueTasks) {
  let window = Services.wm.getMostRecentWindow("mail:3pane");
  let compositeCalendar = lazy.cal.view.getCompositeCalendar(window);

  let itemList = [];
  for await (let items of lazy.cal.iterate.streamValues(
    compositeCalendar.getItems(filter, 0, startDate, endDate)
  )) {
    if (!notDueTasks) {
      items = items.filter(i => !i.isTodo() || i.entryDate || i.dueDate);
    }
    itemList = itemList.concat(items);
  }
  return itemList;
}

/**
 * A simple list of calendar items.
 */
let listView = {
  /**
   * Create the list view.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} startDate - the first day of the months to be displayed
   * @param {calIDateTime} endDate - the first day of the month AFTER the
   *   months to be displayed
   * @param {integer} filter - calICalendar ITEM_FILTER flags
   * @param {boolean} notDueTasks - if true, include tasks with no due date
   */
  async draw(document, startDate, endDate, filter, notDueTasks) {
    let container = document.getElementById("list-container");
    let listItemTemplate = document.getElementById("list-item-template");

    // Get and sort items.
    let items = await getItems(startDate, endDate, filter, notDueTasks);
    items.sort((a, b) => {
      let start_a = a[lazy.cal.dtz.startDateProp(a)];
      if (!start_a) {
        return -1;
      }
      let start_b = b[lazy.cal.dtz.startDateProp(b)];
      if (!start_b) {
        return 1;
      }
      return start_a.compare(start_b);
    });

    // Display the items.
    for (let item of items) {
      let itemNode = listItemTemplate.content.firstElementChild.cloneNode(true);

      let setupTextRow = function (classKey, propValue, prefixKey) {
        if (propValue) {
          let prefix = lazy.cal.l10n.getCalString(prefixKey);
          itemNode.querySelector("." + classKey + "key").textContent = prefix;
          itemNode.querySelector("." + classKey).textContent = propValue;
        } else {
          let row = itemNode.querySelector("." + classKey + "row");
          if (
            row.nextSibling.nodeType == row.nextSibling.TEXT_NODE ||
            row.nextSibling.nodeType == row.nextSibling.CDATA_SECTION_NODE
          ) {
            row.nextSibling.remove();
          }
          row.remove();
        }
      };

      let itemStartDate = item[lazy.cal.dtz.startDateProp(item)];
      let itemEndDate = item[lazy.cal.dtz.endDateProp(item)];
      if (itemStartDate || itemEndDate) {
        // This is a task with a start or due date, format accordingly
        let prefixWhen = lazy.cal.l10n.getCalString("htmlPrefixWhen");
        itemNode.querySelector(".intervalkey").textContent = prefixWhen;

        let startNode = itemNode.querySelector(".dtstart");
        let dateString = lazy.cal.dtz.formatter.formatItemInterval(item);
        startNode.setAttribute("title", itemStartDate ? itemStartDate.icalString : "none");
        startNode.textContent = dateString;
      } else {
        let row = itemNode.querySelector(".intervalrow");
        row.remove();
        if (
          row.nextSibling &&
          (row.nextSibling.nodeType == row.nextSibling.TEXT_NODE ||
            row.nextSibling.nodeType == row.nextSibling.CDATA_SECTION_NODE)
        ) {
          row.nextSibling.remove();
        }
      }

      let itemTitle = item.isCompleted
        ? lazy.cal.l10n.getCalString("htmlTaskCompleted", [item.title])
        : item.title;
      setupTextRow("summary", itemTitle, "htmlPrefixTitle");

      setupTextRow("location", item.getProperty("LOCATION"), "htmlPrefixLocation");
      setupTextRow("description", item.getProperty("DESCRIPTION"), "htmlPrefixDescription");

      container.appendChild(itemNode);
    }

    // Set the page title.
    endDate.day--;
    document.title = lazy.cal.dtz.formatter.formatInterval(startDate, endDate);
  },
};

/**
 * A layout with one calendar month per page.
 */
let monthGridView = {
  dayTable: {},

  /**
   * Create the month grid view.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} startDate - the first day of the months to be displayed
   * @param {calIDateTime} endDate - the first day of the month AFTER the
   *   months to be displayed
   * @param {integer} filter - calICalendar ITEM_FILTER flags
   * @param {boolean} notDueTasks - if true, include tasks with no due date
   */
  async draw(document, startDate, endDate, filter, notDueTasks) {
    let container = document.getElementById("month-container");

    // Draw the month grid(s).
    let current = startDate.clone();
    do {
      container.appendChild(this.drawMonth(document, current));
      current.month += 1;
    } while (current.compare(endDate) < 0);

    // Extend the date range to include adjacent days that will be printed.
    startDate = lazy.cal.weekInfoService.getStartOfWeek(startDate);
    // Get the end of the week containing the last day of the month, not the
    // week containing the first day of the next month.
    endDate.day--;
    endDate = lazy.cal.weekInfoService.getEndOfWeek(endDate);
    endDate.day++; // Add a day to include items from the last day.

    // Get and display the items.
    let items = await getItems(startDate, endDate, filter, notDueTasks);
    let defaultTimezone = lazy.cal.dtz.defaultTimezone;
    for (let item of items) {
      let itemStartDate =
        item[lazy.cal.dtz.startDateProp(item)] || item[lazy.cal.dtz.endDateProp(item)];
      let itemEndDate =
        item[lazy.cal.dtz.endDateProp(item)] || item[lazy.cal.dtz.startDateProp(item)];

      if (!itemStartDate && !itemEndDate) {
        addItemToDayboxNodate(document, item);
        continue;
      }
      itemStartDate = itemStartDate.getInTimezone(defaultTimezone);
      itemEndDate = itemEndDate.getInTimezone(defaultTimezone);

      let boxDate = itemStartDate.clone();
      boxDate.isDate = true;
      for (boxDate; boxDate.compare(itemEndDate) < (itemEndDate.isDate ? 0 : 1); boxDate.day++) {
        let boxDateString = boxDate.icalString;
        if (boxDateString in this.dayTable) {
          for (let dayBox of this.dayTable[boxDateString]) {
            addItemToDaybox(document, item, boxDate, dayBox.querySelector(".items"));
          }
        }
      }
    }

    // Set the page title.
    let months = container.querySelectorAll("table");
    if (months.length == 1) {
      document.title = months[0].querySelector(".month-title").textContent;
    } else {
      document.title =
        months[0].querySelector(".month-title").textContent +
        " – " +
        months[months.length - 1].querySelector(".month-title").textContent;
    }
  },

  /**
   * Create one month from the template.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} startOfMonth - the first day of the month
   */
  drawMonth(document, startOfMonth) {
    let monthTemplate = document.getElementById("month-template");
    let month = monthTemplate.content.firstElementChild.cloneNode(true);

    // Set up the month title
    let monthName = lazy.cal.l10n.formatMonth(startOfMonth.month + 1, "calendar", "monthInYear");
    let monthTitle = lazy.cal.l10n.getCalString("monthInYear", [monthName, startOfMonth.year]);
    month.rows[0].cells[0].firstElementChild.textContent = monthTitle;

    // Set up the weekday titles
    let weekStart = Services.prefs.getIntPref("calendar.week.start", 0);
    for (let i = 0; i < 7; i++) {
      let dayNumber = ((i + weekStart) % 7) + 1;
      month.rows[1].cells[i].firstElementChild.textContent = lazy.cal.l10n.getDateFmtString(
        `day.${dayNumber}.Mmm`
      );
    }

    // Set up each week
    let endOfMonthView = lazy.cal.weekInfoService.getEndOfWeek(startOfMonth.endOfMonth);
    let startOfMonthView = lazy.cal.weekInfoService.getStartOfWeek(startOfMonth);
    let mainMonth = startOfMonth.month;

    for (
      let weekStart = startOfMonthView;
      weekStart.compare(endOfMonthView) < 0;
      weekStart.day += 7
    ) {
      month.tBodies[0].appendChild(this.drawWeek(document, weekStart, mainMonth));
    }

    return month;
  },

  /**
   * Create one week from the template.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} startOfWeek - the first day of the week
   * @param {number} mainMonth - the month that this week is being added to
   *   (for marking days that are in adjacent months)
   */
  drawWeek(document, startOfWeek, mainMonth) {
    const weekdayMap = [
      "d0sundaysoff",
      "d1mondaysoff",
      "d2tuesdaysoff",
      "d3wednesdaysoff",
      "d4thursdaysoff",
      "d5fridaysoff",
      "d6saturdaysoff",
    ];

    let weekTemplate = document.getElementById("month-week-template");
    let week = weekTemplate.content.firstElementChild.cloneNode(true);

    // Set up day numbers for all days in this week
    let date = startOfWeek.clone();
    for (let i = 0; i < 7; i++) {
      let dayBox = week.cells[i];
      dayBox.querySelector(".day-title").textContent = date.day;

      let weekDay = date.weekday;
      let dayOffPrefName = "calendar.week." + weekdayMap[weekDay];
      if (Services.prefs.getBoolPref(dayOffPrefName, false)) {
        dayBox.classList.add("day-off");
      }

      if (date.month != mainMonth) {
        dayBox.classList.add("out-of-month");
      }

      if (date.icalString in this.dayTable) {
        this.dayTable[date.icalString].push(dayBox);
      } else {
        this.dayTable[date.icalString] = [dayBox];
      }
      date.day++;
    }

    return week;
  },
};

/**
 * A layout with seven days per page. The week layout is NOT aware of the
 * start-of-week preferences. It always begins on a Monday.
 */
let weekPlannerView = {
  dayTable: {},

  /**
   * Create the week planner view.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} startDate - the Monday of the first week to be displayed
   * @param {calIDateTime} endDate - the Monday AFTER the last week to be displayed
   * @param {integer} filter - calICalendar ITEM_FILTER flags
   * @param {boolean} notDueTasks - if true, include tasks with no due date
   */
  async draw(document, startDate, endDate, filter, notDueTasks) {
    let container = document.getElementById("week-container");

    // Draw the week grid(s).
    for (let current = startDate.clone(); current.compare(endDate) < 0; current.day += 7) {
      container.appendChild(this.drawWeek(document, current));
    }

    // Get and display the items.
    let items = await getItems(startDate, endDate, filter, notDueTasks);
    let defaultTimezone = lazy.cal.dtz.defaultTimezone;
    for (let item of items) {
      let itemStartDate =
        item[lazy.cal.dtz.startDateProp(item)] || item[lazy.cal.dtz.endDateProp(item)];
      let itemEndDate =
        item[lazy.cal.dtz.endDateProp(item)] || item[lazy.cal.dtz.startDateProp(item)];

      if (!itemStartDate && !itemEndDate) {
        addItemToDayboxNodate(document, item);
        continue;
      }
      itemStartDate = itemStartDate.getInTimezone(defaultTimezone);
      itemEndDate = itemEndDate.getInTimezone(defaultTimezone);

      let boxDate = itemStartDate.clone();
      boxDate.isDate = true;
      for (boxDate; boxDate.compare(itemEndDate) < (itemEndDate.isDate ? 0 : 1); boxDate.day++) {
        let boxDateString = boxDate.icalString;
        if (boxDateString in this.dayTable) {
          addItemToDaybox(document, item, boxDate, this.dayTable[boxDateString]);
        }
      }
    }

    // Set the page title.
    let weeks = container.querySelectorAll("table");
    if (weeks.length == 1) {
      document.title = lazy.cal.l10n.getCalString("singleLongCalendarWeek", [weeks[0].number]);
    } else {
      document.title = lazy.cal.l10n.getCalString("severalLongCalendarWeeks", [
        weeks[0].number,
        weeks[weeks.length - 1].number,
      ]);
    }
  },

  /**
   * Create one week from the template.
   *
   * @param {HTMLDocument} document
   * @param {calIDateTime} monday - the Monday of the week
   */
  drawWeek(document, monday) {
    // In the order they appear on the page.
    const weekdayMap = [
      "d1mondaysoff",
      "d2tuesdaysoff",
      "d3wednesdaysoff",
      "d4thursdaysoff",
      "d5fridaysoff",
      "d6saturdaysoff",
      "d0sundaysoff",
    ];

    let weekTemplate = document.getElementById("week-template");
    let week = weekTemplate.content.firstElementChild.cloneNode(true);

    // Set up the week number title
    week.number = lazy.cal.weekInfoService.getWeekTitle(monday);
    week.querySelector(".week-title").textContent = lazy.cal.l10n.getCalString("WeekTitle", [
      week.number,
    ]);

    // Set up the day boxes
    let currentDate = monday.clone();
    for (let i = 0; i < 7; i++) {
      let day = week.rows[1].cells[i];

      let titleNode = day.querySelector(".day-title");
      titleNode.textContent = lazy.cal.dtz.formatter.formatDateLong(currentDate);

      this.dayTable[currentDate.icalString] = day.querySelector(".items");

      if (Services.prefs.getBoolPref("calendar.week." + weekdayMap[i], false)) {
        day.classList.add("day-off");
      }

      currentDate.day++;
    }

    return week;
  },
};

Services.obs.addObserver(
  {
    async observe(subDialogWindow) {
      if (!subDialogWindow.location.href.startsWith("chrome://global/content/print.html?")) {
        return;
      }

      await new Promise(resolve =>
        subDialogWindow.document.addEventListener("print-settings", resolve, { once: true })
      );

      if (
        subDialogWindow.PrintEventHandler.activeCurrentURI !=
        "chrome://calendar/content/printing-template.html"
      ) {
        return;
      }

      Services.scriptloader.loadSubScript(
        "chrome://calendar/content/widgets/calendar-minimonth.js",
        subDialogWindow
      );
      Services.scriptloader.loadSubScript(
        "chrome://calendar/content/calendar-print.js",
        subDialogWindow
      );
    },
  },
  "subdialog-loaded"
);