« get me outta code hell

additional-names-box.js « client « js « static « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/static/js/client/additional-names-box.js
blob: 558ef06fde63b505e749cf458970219f70a53eac (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
/* eslint-env browser */

import {cssProp} from '../client-util.js';

import {info as hashLinkInfo} from './hash-link.js';

export const info = {
  id: 'additionalNamesBoxInfo',

  box: null,
  links: null,
  mainContentContainer: null,

  state: {
    visible: false,
  },
};

export function getPageReferences() {
  info.box =
    document.getElementById('additional-names-box');

  info.links =
    document.querySelectorAll('a[href="#additional-names-box"]');

  info.mainContentContainer =
    document.querySelector('#content .main-content-container');
}

export function addInternalListeners() {
  hashLinkInfo.event.beforeHashLinkScrolls.push(({target}) => {
    if (target === info.box) {
      return false;
    }
  });
}

export function addPageListeners() {
  for (const link of info.links) {
    link.addEventListener('click', domEvent => {
      handleAdditionalNamesBoxLinkClicked(domEvent);
    });
  }
}

function handleAdditionalNamesBoxLinkClicked(domEvent) {
  const {state} = info;

  domEvent.preventDefault();

  if (!info.box || !info.mainContentContainer) return;

  const margin =
    +(cssProp(info.box, 'scroll-margin-top').replace('px', ''));

  const {top} =
    (state.visible
      ? info.box.getBoundingClientRect()
      : info.mainContentContainer.getBoundingClientRect());

  if (top + 20 < margin || top > 0.4 * window.innerHeight) {
    if (!state.visible) {
      toggleAdditionalNamesBox();
    }

    window.scrollTo({
      top: window.scrollY + top - margin,
      behavior: 'smooth',
    });
  } else {
    toggleAdditionalNamesBox();
  }
}

export function toggleAdditionalNamesBox() {
  const {state} = info;

  state.visible = !state.visible;
  info.box.style.display =
    (state.visible
      ? 'block'
      : 'none');
}