summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pages/projects/pipeline_schedules/shared/components/interval_pattern_input.vue
blob: 242c5a1a97bff94bb5448c4ff85f6c5124c36a26 (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
<script>
import {
  GlFormRadio,
  GlFormRadioGroup,
  GlIcon,
  GlLink,
  GlSprintf,
  GlTooltipDirective,
} from '@gitlab/ui';
import { getWeekdayNames } from '~/lib/utils/datetime_utility';
import { __, s__, sprintf } from '~/locale';
import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';

const KEY_EVERY_DAY = 'everyDay';
const KEY_EVERY_WEEK = 'everyWeek';
const KEY_EVERY_MONTH = 'everyMonth';
const KEY_CUSTOM = 'custom';

export default {
  components: {
    GlFormRadio,
    GlFormRadioGroup,
    GlIcon,
    GlLink,
    GlSprintf,
  },
  directives: {
    GlTooltip: GlTooltipDirective,
  },
  mixins: [glFeatureFlagMixin()],
  props: {
    initialCronInterval: {
      type: String,
      required: false,
      default: '',
    },
    dailyLimit: {
      type: String,
      required: false,
      default: '',
    },
    sendNativeErrors: {
      type: Boolean,
      required: false,
      default: true,
    },
  },
  data() {
    return {
      isEditingCustom: false,
      randomHour: this.generateRandomHour(),
      randomWeekDayIndex: this.generateRandomWeekDayIndex(),
      randomDay: this.generateRandomDay(),
      inputNameAttribute: 'schedule[cron]',
      radioValue: this.initialCronInterval ? KEY_CUSTOM : KEY_EVERY_DAY,
      cronInterval: this.initialCronInterval,
      cronSyntaxUrl: 'https://docs.gitlab.com/ee/topics/cron/',
    };
  },
  computed: {
    cronIntervalPresets() {
      return {
        [KEY_EVERY_DAY]: `0 ${this.randomHour} * * *`,
        [KEY_EVERY_WEEK]: `0 ${this.randomHour} * * ${this.randomWeekDayIndex}`,
        [KEY_EVERY_MONTH]: `0 ${this.randomHour} ${this.randomDay} * *`,
      };
    },
    formattedTime() {
      if (this.randomHour > 12) {
        return `${this.randomHour - 12}:00pm`;
      } else if (this.randomHour === 12) {
        return `12:00pm`;
      }
      return `${this.randomHour}:00am`;
    },
    radioOptions() {
      return [
        {
          value: KEY_EVERY_DAY,
          text: sprintf(__(`Every day (at %{time})`), { time: this.formattedTime }),
        },
        {
          value: KEY_EVERY_WEEK,
          text: sprintf(__('Every week (%{weekday} at %{time})'), {
            weekday: this.weekday,
            time: this.formattedTime,
          }),
        },
        {
          value: KEY_EVERY_MONTH,
          text: sprintf(__('Every month (Day %{day} at %{time})'), {
            day: this.randomDay,
            time: this.formattedTime,
          }),
        },
        {
          value: KEY_CUSTOM,
          text: s__('PipelineScheduleIntervalPattern|Custom (%{linkStart}Learn more.%{linkEnd})'),
          link: this.cronSyntaxUrl,
        },
      ];
    },
    weekday() {
      return getWeekdayNames()[this.randomWeekDayIndex];
    },
    parsedDailyLimit() {
      return this.dailyLimit ? (24 * 60) / this.dailyLimit : null;
    },
    scheduleDailyLimitMsg() {
      return sprintf(
        __(
          'Scheduled pipelines cannot run more frequently than once per %{limit} minutes. A pipeline configured to run more frequently only starts after %{limit} minutes have elapsed since the last time it ran.',
        ),
        { limit: this.parsedDailyLimit },
      );
    },
  },
  watch: {
    cronInterval() {
      // updates field validation state when model changes, as
      // glFieldError only updates on input.
      if (this.sendNativeErrors) {
        this.$nextTick(() => {
          gl.pipelineScheduleFieldErrors.updateFormValidityState();
        });
      }
    },
    radioValue: {
      immediate: true,
      handler(val) {
        if (val !== KEY_CUSTOM) {
          this.cronInterval = this.cronIntervalPresets[val];
        }
      },
    },
  },
  methods: {
    onCustomInput() {
      this.radioValue = KEY_CUSTOM;
    },
    generateRandomHour() {
      return Math.floor(Math.random() * 23);
    },
    generateRandomWeekDayIndex() {
      return Math.floor(Math.random() * 6);
    },
    generateRandomDay() {
      return Math.floor(Math.random() * 28);
    },
    showDailyLimitMessage({ value }) {
      return value === KEY_CUSTOM && this.dailyLimit;
    },
  },
};
</script>

<template>
  <div>
    <gl-form-radio-group v-model="radioValue" :name="inputNameAttribute">
      <gl-form-radio
        v-for="option in radioOptions"
        :key="option.value"
        :value="option.value"
        :data-testid="option.value"
      >
        <gl-sprintf v-if="option.link" :message="option.text">
          <template #link="{ content }">
            <gl-link :href="option.link" target="_blank" class="gl-font-sm">
              {{ content }}
            </gl-link>
          </template>
        </gl-sprintf>

        <template v-else>{{ option.text }}</template>

        <gl-icon
          v-if="showDailyLimitMessage(option)"
          v-gl-tooltip.hover
          name="question"
          :title="scheduleDailyLimitMsg"
        />
      </gl-form-radio>
    </gl-form-radio-group>
    <input
      id="schedule_cron"
      v-model="cronInterval"
      :placeholder="__('Define a custom pattern with cron syntax')"
      :name="inputNameAttribute"
      class="form-control inline cron-interval-input gl-form-input"
      type="text"
      required="true"
      @input="onCustomInput"
    />
  </div>
</template>