summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pages/projects/pipeline_schedules/shared/components/timezone_dropdown.js
blob: 95ed9c7dc21d40b27685dea31776890db91d6183 (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
/* eslint-disable class-methods-use-this */

const defaultTimezone = 'UTC';

export default class TimezoneDropdown {
  constructor() {
    this.$dropdown = $('.js-timezone-dropdown');
    this.$dropdownToggle = this.$dropdown.find('.dropdown-toggle-text');
    this.$input = $('#schedule_cron_timezone');
    this.timezoneData = this.$dropdown.data('data');
    this.initDefaultTimezone();
    this.initDropdown();
  }

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

    this.setDropdownToggle();
  }

  formatUtcOffset(offset) {
    let prefix = '';

    if (offset > 0) {
      prefix = '+';
    } else if (offset < 0) {
      prefix = '-';
    }

    return `${prefix} ${Math.abs(offset / 3600)}`;
  }

  formatTimezone(item) {
    return `[UTC ${this.formatUtcOffset(item.offset)}] ${item.name}`;
  }

  initDefaultTimezone() {
    const initialValue = this.$input.val();

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

  setDropdownToggle() {
    const initialValue = this.$input.val();

    this.$dropdownToggle.text(initialValue);
  }

  updateInputValue({ selectedObj, e }) {
    e.preventDefault();
    this.$input.val(selectedObj.identifier);
    gl.pipelineScheduleFieldErrors.updateFormValidityState();
  }
}