summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/commons/nav/user_merge_requests.js
blob: 8e694cca6a10052ae311faf08d7a7e7e5acfa329 (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
import Api from '~/api';

let channel;

function broadcastCount(newCount) {
  if (!channel) {
    return;
  }

  channel.postMessage(newCount);
}

function updateUserMergeRequestCounts(newCount) {
  const mergeRequestsCountEl = document.querySelector('.merge-requests-count');
  mergeRequestsCountEl.textContent = newCount.toLocaleString();
  mergeRequestsCountEl.classList.toggle('hidden', Number(newCount) === 0);
}

/**
 * Refresh user counts (and broadcast if open)
 */
export function refreshUserMergeRequestCounts() {
  return Api.userCounts()
    .then(({ data }) => {
      const count = data.merge_requests;

      updateUserMergeRequestCounts(count);
      broadcastCount(count);
    })
    .catch(ex => {
      console.error(ex); // eslint-disable-line no-console
    });
}

/**
 * Close the broadcast channel for user counts
 */
export function closeUserCountsBroadcast() {
  if (!channel) {
    return;
  }

  channel.close();
  channel = null;
}

/**
 * Open the broadcast channel for user counts, adds user id so we only update
 *
 * **Please note:**
 * Not supported in all browsers, but not polyfilling for now
 * to keep bundle size small and
 * no special functionality lost except cross tab notifications
 */
export function openUserCountsBroadcast() {
  closeUserCountsBroadcast();

  if (window.BroadcastChannel) {
    const currentUserId = typeof gon !== 'undefined' && gon && gon.current_user_id;
    if (currentUserId) {
      channel = new BroadcastChannel(`mr_count_channel_${currentUserId}`);
      channel.onmessage = ev => {
        updateUserMergeRequestCounts(ev.data);
      };
    }
  }
}