Welcome to mirror list, hosted at ThFree Co, Russian Federation.

timezone_dropdown.js « components « shared « pipeline_schedules « projects « pages « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a20a0526f12b1cffba41089ccbecd3c9c3d3bd06 (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
const defaultTimezone = { name: 'UTC', offset: 0 };
const defaults = {
  $inputEl: null,
  $dropdownEl: null,
  onSelectTimezone: null,
  displayFormat: item => item.name,
};

export const formatUtcOffset = offset => {
  const parsed = parseInt(offset, 10);
  if (Number.isNaN(parsed) || parsed === 0) {
    return `0`;
  }
  const prefix = offset > 0 ? '+' : '-';
  return `${prefix} ${Math.abs(offset / 3600)}`;
};

export const formatTimezone = item => `[UTC ${formatUtcOffset(item.offset)}] ${item.name}`;

export const findTimezoneByIdentifier = (tzList = [], identifier = null) => {
  if (tzList && tzList.length && identifier && identifier.length) {
    return tzList.find(tz => tz.identifier === identifier) || null;
  }
  return null;
};

export default class TimezoneDropdown {
  constructor({ $dropdownEl, $inputEl, onSelectTimezone, displayFormat } = defaults) {
    this.$dropdown = $dropdownEl;
    this.$dropdownToggle = this.$dropdown.find('.dropdown-toggle-text');
    this.$input = $inputEl;
    this.timezoneData = this.$dropdown.data('data');

    this.onSelectTimezone = onSelectTimezone;
    this.displayFormat = displayFormat || defaults.displayFormat;

    this.initialTimezone =
      findTimezoneByIdentifier(this.timezoneData, this.$input.val()) || defaultTimezone;

    this.initDefaultTimezone();
    this.initDropdown();
  }

  initDropdown() {
    this.$dropdown.glDropdown({
      data: this.timezoneData,
      filterable: true,
      selectable: true,
      toggleLabel: this.displayFormat,
      search: {
        fields: ['name'],
      },
      clicked: cfg => this.updateInputValue(cfg),
      text: item => formatTimezone(item),
    });

    this.setDropdownToggle(this.displayFormat(this.initialTimezone));
  }

  initDefaultTimezone() {
    if (!this.$input.val()) {
      this.$input.val(defaultTimezone.name);
    }
  }

  setDropdownToggle(dropdownText) {
    this.$dropdownToggle.text(dropdownText);
  }

  updateInputValue({ selectedObj, e }) {
    e.preventDefault();
    this.$input.val(selectedObj.identifier);
    if (this.onSelectTimezone) {
      this.onSelectTimezone({ selectedObj, e });
    }
  }
}