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

widget.vue « widget « components « vue_merge_request_widget « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 54eb15c8ac8cbf47fa80f506e556b8311fcc8a1c (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
<script>
import { GlButton, GlLink, GlTooltipDirective, GlLoadingIcon } from '@gitlab/ui';
import * as Sentry from '@sentry/browser';
import { normalizeHeaders } from '~/lib/utils/common_utils';
import { logError } from '~/lib/logger';
import SafeHtml from '~/vue_shared/directives/safe_html';
import { sprintf, __ } from '~/locale';
import Poll from '~/lib/utils/poll';
import HelpPopover from '~/vue_shared/components/help_popover.vue';
import { DynamicScroller, DynamicScrollerItem } from 'vendor/vue-virtual-scroller';
import { EXTENSION_ICONS } from '../../constants';
import { createTelemetryHub } from '../extensions/telemetry';
import ContentRow from './widget_content_row.vue';
import DynamicContent from './dynamic_content.vue';
import StatusIcon from './status_icon.vue';
import ActionButtons from './action_buttons.vue';

const FETCH_TYPE_COLLAPSED = 'collapsed';
const FETCH_TYPE_EXPANDED = 'expanded';
const WIDGET_PREFIX = 'Widget';
const MISSING_RESPONSE_HEADERS =
  'MR Widget: raesponse object should contain status and headers object. Make sure to include that in your `fetchCollapsedData` and `fetchExpandedData` functions.';

export default {
  MISSING_RESPONSE_HEADERS,

  components: {
    ActionButtons,
    StatusIcon,
    GlLink,
    GlButton,
    GlLoadingIcon,
    ContentRow,
    DynamicContent,
    DynamicScroller,
    DynamicScrollerItem,
    HelpPopover,
  },
  directives: {
    GlTooltip: GlTooltipDirective,
    SafeHtml,
  },
  props: {
    /**
     * @param {value.collapsed} Object
     * @param {value.expanded} Object
     */
    value: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    loadingText: {
      type: String,
      required: false,
      default: __('Loading'),
    },
    errorText: {
      type: String,
      required: false,
      default: __('Failed to load'),
    },
    fetchCollapsedData: {
      type: Function,
      required: false,
      default: undefined,
    },
    fetchExpandedData: {
      type: Function,
      required: false,
      default: undefined,
    },
    // If the summary slot is not used, this value will be used as a fallback.
    summary: {
      type: String,
      required: false,
      default: undefined,
    },
    // If the content slot is not used, this value will be used as a fallback.
    content: {
      type: Array,
      required: false,
      default: undefined,
    },
    multiPolling: {
      type: Boolean,
      required: false,
      default: false,
    },
    statusIconName: {
      type: String,
      required: false,
      default: 'neutral',
      validator: (value) => Object.keys(EXTENSION_ICONS).indexOf(value) > -1,
    },
    isCollapsible: {
      type: Boolean,
      required: true,
    },
    /**
     * A button is composed of the following properties:
     *
     * {
     *   "id": string,
     *   "href": string,
     *   "dataMethod": string,
     *   "dataClipboardText": string,
     *   "icon": string,
     *   "variant": string,
     *   "loading": boolean,
     *   "testId":string,
     *   "text": string,
     *   "class": string | Object,
     *   "trackFullReportClicked": boolean,
     * }
     */
    actionButtons: {
      type: Array,
      required: false,
      default: () => [],
    },
    widgetName: {
      type: String,
      required: true,
      // see https://docs.gitlab.com/ee/development/fe_guide/merge_request_widget_extensions.html#add-new-widgets
      validator: (val) => val.startsWith(WIDGET_PREFIX),
    },
    telemetry: {
      type: Boolean,
      required: false,
      default: true,
    },
    /**
     * @typedef {Object} helpPopover
     * @property {Object} options
     * @property {String} options.title
     * @property {Object} content
     * @property {String} content.text
     * @property {String} content.learnMorePath
     */
    helpPopover: {
      type: Object,
      required: false,
      default: null,
    },
    // When this is provided, the widget will display an error message in the summary section.
    hasError: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      isExpandedForTheFirstTime: true,
      isCollapsed: true,
      isLoading: false,
      isLoadingExpandedContent: false,
      summaryError: null,
      contentError: null,
      telemetryHub: null,
    };
  },
  computed: {
    collapseButtonLabel() {
      return sprintf(this.isCollapsed ? __('Show details') : __('Hide details'));
    },
    summaryStatusIcon() {
      return this.summaryError ? this.$options.failedStatusIcon : this.statusIconName;
    },
    hasActionButtons() {
      return this.actionButtons.length > 0 || Boolean(this.$scopedSlots['action-buttons']);
    },
  },
  watch: {
    hasError: {
      handler(newValue) {
        this.summaryError = newValue ? this.errorText : null;
      },
      immediate: true,
    },
    isLoading(newValue) {
      this.$emit('is-loading', newValue);
    },
  },
  created() {
    if (this.telemetry) {
      this.telemetryHub = createTelemetryHub(this.widgetName);
    }
  },
  async mounted() {
    this.isLoading = true;
    this.telemetryHub?.viewed();

    try {
      if (this.fetchCollapsedData) {
        await this.fetch(this.fetchCollapsedData, FETCH_TYPE_COLLAPSED);
      }
    } catch {
      this.summaryError = this.errorText;
    }

    this.isLoading = false;
  },
  methods: {
    onActionClick(action) {
      if (action.trackFullReportClicked) {
        this.telemetryHub?.fullReportClicked();
      }
    },
    toggleCollapsed() {
      this.isCollapsed = !this.isCollapsed;

      if (this.isExpandedForTheFirstTime) {
        this.telemetryHub?.expanded({ type: this.summaryStatusIcon });

        if (typeof this.fetchExpandedData === 'function') {
          this.isExpandedForTheFirstTime = false;
          this.fetchExpandedContent();
        }
      }

      this.$emit('toggle', { expanded: !this.isCollapsed });
    },
    async fetchExpandedContent() {
      this.isLoadingExpandedContent = true;
      this.contentError = null;

      try {
        await this.fetch(this.fetchExpandedData, FETCH_TYPE_EXPANDED);
      } catch {
        this.contentError = this.errorText;

        // Reset these values so that we allow refetching
        this.isExpandedForTheFirstTime = true;
        this.isCollapsed = true;
      }

      this.isLoadingExpandedContent = false;
    },
    fetch(handler, dataType) {
      const requests = this.multiPolling ? handler() : [handler];

      const promises = requests.map((request) => {
        return new Promise((resolve, reject) => {
          const poll = new Poll({
            resource: {
              fetchData: () => request(),
            },
            method: 'fetchData',
            successCallback: (response) => {
              if (
                typeof response.status === 'undefined' ||
                typeof response.headers === 'undefined'
              ) {
                logError(MISSING_RESPONSE_HEADERS);
                throw new Error(MISSING_RESPONSE_HEADERS);
              }

              const headers = normalizeHeaders(response.headers);

              if (headers['POLL-INTERVAL']) {
                return;
              }

              resolve(response.data);
            },
            errorCallback: (e) => {
              Sentry.captureException(e);
              reject(e);
            },
          });

          poll.makeRequest();
        });
      });

      return Promise.all(promises).then((data) => {
        this.$emit('input', { ...this.value, [dataType]: this.multiPolling ? data : data[0] });
      });
    },
  },
  failedStatusIcon: EXTENSION_ICONS.failed,
  i18n: {
    learnMore: __('Learn more'),
  },
};
</script>

<template>
  <section class="media-section" data-testid="widget-extension">
    <div class="gl-px-5 gl-pr-4 gl-py-4 gl-align-items-center gl-display-flex">
      <status-icon
        :level="1"
        :name="widgetName"
        :is-loading="isLoading"
        :icon-name="summaryStatusIcon"
      />
      <div
        class="media-body gl-display-flex gl-flex-direction-row! gl-align-self-center"
        data-testid="widget-extension-top-level"
      >
        <div class="gl-flex-grow-1" data-testid="widget-extension-top-level-summary">
          <span v-if="summaryError">{{ summaryError }}</span>
          <slot v-else name="summary">{{ isLoading ? loadingText : summary }}</slot>
        </div>
        <div class="gl-display-flex">
          <help-popover
            v-if="helpPopover"
            icon="information-o"
            :options="helpPopover.options"
            :class="{ 'gl-mr-3': hasActionButtons }"
          >
            <template v-if="helpPopover.content">
              <p
                v-if="helpPopover.content.text"
                v-safe-html="helpPopover.content.text"
                class="gl-mb-0"
              ></p>
              <gl-link
                v-if="helpPopover.content.learnMorePath"
                :href="helpPopover.content.learnMorePath"
                target="_blank"
                class="gl-font-sm"
                >{{ $options.i18n.learnMore }}</gl-link
              >
            </template>
          </help-popover>
          <slot name="action-buttons">
            <action-buttons
              v-if="actionButtons.length > 0"
              :widget="widgetName"
              :tertiary-buttons="actionButtons"
              @clickedAction="onActionClick"
            />
          </slot>
        </div>
        <div
          v-if="isCollapsible"
          class="gl-border-l-1 gl-border-l-solid gl-border-gray-100 gl-ml-3 gl-pl-3 gl-h-6"
        >
          <gl-button
            v-gl-tooltip
            :title="collapseButtonLabel"
            :aria-expanded="`${!isCollapsed}`"
            :aria-label="collapseButtonLabel"
            :icon="isCollapsed ? 'chevron-lg-down' : 'chevron-lg-up'"
            category="tertiary"
            data-testid="toggle-button"
            size="small"
            data-qa-selector="expand_report_button"
            @click="toggleCollapsed"
          />
        </div>
      </div>
    </div>
    <div
      v-if="!isCollapsed || contentError"
      class="gl-relative gl-bg-gray-10"
      data-testid="widget-extension-collapsed-section"
    >
      <div v-if="isLoadingExpandedContent" class="report-block-container gl-text-center">
        <gl-loading-icon size="sm" inline /> {{ loadingText }}
      </div>
      <div v-else class="gl-pl-5 gl-display-flex" :class="{ 'gl-pr-5': $scopedSlots.content }">
        <content-row
          v-if="contentError"
          :level="2"
          :status-icon-name="$options.failedStatusIcon"
          :widget-name="widgetName"
        >
          <template #body>
            {{ contentError }}
          </template>
        </content-row>
        <div v-else class="gl-w-full">
          <slot name="content">
            <dynamic-scroller
              v-if="content"
              :items="content"
              :min-item-size="32"
              :style="{ maxHeight: '170px' }"
              data-testid="dynamic-content-scroller"
              class="gl-pr-5"
            >
              <template #default="{ item, index, active }">
                <dynamic-scroller-item :item="item" :active="active">
                  <dynamic-content
                    :key="item.id || index"
                    :data="item"
                    :widget-name="widgetName"
                    :level="2"
                  />
                </dynamic-scroller-item>
              </template>
            </dynamic-scroller>
          </slot>
        </div>
      </div>
    </div>
  </section>
</template>