summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/diffs/utils/discussions.js
blob: c404705d209427b757b5c22249d30ac8376166aa (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
function normalize(processable) {
  const { entry } = processable;
  const offset = entry.rootBounds.bottom - entry.boundingClientRect.top;
  const direction =
    offset < 0 ? 'Up' : 'Down'; /* eslint-disable-line @gitlab/require-i18n-strings */

  return {
    ...processable,
    entry: {
      time: entry.time,
      type: entry.isIntersecting ? 'intersection' : `scroll${direction}`,
    },
  };
}

function sort({ entry: alpha }, { entry: beta }) {
  const diff = alpha.time - beta.time;
  let order = 0;

  if (diff < 0) {
    order = -1;
  } else if (diff > 0) {
    order = 1;
  } else if (alpha.type === 'intersection' && beta.type === 'scrollUp') {
    order = 2;
  } else if (alpha.type === 'scrollUp' && beta.type === 'intersection') {
    order = -2;
  }

  return order;
}

function filter(entry) {
  return entry.type !== 'scrollDown';
}

export function discussionIntersectionObserverHandlerFactory() {
  let unprocessed = [];
  let timer = null;

  return (processable) => {
    unprocessed.push(processable);

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      unprocessed
        .map(normalize)
        .filter(filter)
        .sort(sort)
        .forEach((discussionObservationContainer) => {
          const {
            entry: { type },
            currentDiscussion,
            isFirstUnresolved,
            isDiffsPage,
            functions: { setCurrentDiscussionId, getPreviousUnresolvedDiscussionId },
          } = discussionObservationContainer;

          if (type === 'intersection') {
            setCurrentDiscussionId(currentDiscussion.id);
          } else if (type === 'scrollUp') {
            setCurrentDiscussionId(
              isFirstUnresolved
                ? null
                : getPreviousUnresolvedDiscussionId(currentDiscussion.id, isDiffsPage),
            );
          }
        });

      unprocessed = [];
    }, 0);
  };
}