summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pages/admin/broadcast_messages/broadcast_message.js
blob: 40348e0b18adcb316b17847f81df06ba65bab50a (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
import $ from 'jquery';
import { debounce } from 'lodash';
import { createAlert } from '~/flash';
import axios from '~/lib/utils/axios_utils';
import { DEFAULT_DEBOUNCE_AND_THROTTLE_MS } from '~/lib/utils/constants';
import { __ } from '~/locale';

export default () => {
  const $broadcastMessageTheme = $('.js-broadcast-message-theme');
  const $broadcastMessageType = $('.js-broadcast-message-type');
  const $broadcastBannerMessagePreview = $('.js-broadcast-banner-message-preview [role="alert"]');
  const $broadcastMessage = $('.js-broadcast-message-message');
  const $jsBroadcastMessagePreview = $('#broadcast-message-preview');

  const reloadPreview = function reloadPreview() {
    const previewPath = $broadcastMessage.data('previewPath');
    const message = $broadcastMessage.val();
    const type = $broadcastMessageType.val();
    const theme = $broadcastMessageTheme.val();

    axios
      .post(previewPath, {
        broadcast_message: {
          message,
          broadcast_type: type,
          theme,
        },
      })
      .then(({ data }) => {
        $jsBroadcastMessagePreview.html(data);
      })
      .catch(() =>
        createAlert({
          message: __('An error occurred while rendering preview broadcast message'),
        }),
      );
  };

  $broadcastMessageTheme.on('change', reloadPreview);

  $broadcastMessageType.on('change', () => {
    const $broadcastMessageColorFormGroup = $('.js-broadcast-message-background-color-form-group');
    const $broadcastMessageDismissableFormGroup = $('.js-broadcast-message-dismissable-form-group');
    const $broadcastNotificationMessagePreview = $('.js-broadcast-notification-message-preview');

    $broadcastMessageColorFormGroup.toggleClass('hidden');
    $broadcastMessageDismissableFormGroup.toggleClass('hidden');
    $broadcastBannerMessagePreview.toggleClass('hidden');
    $broadcastNotificationMessagePreview.toggleClass('hidden');

    reloadPreview();
  });

  $broadcastMessage.on(
    'input',
    debounce(() => {
      reloadPreview();
    }, DEFAULT_DEBOUNCE_AND_THROTTLE_MS),
  );
};