« get me outta code hell

memorable-details.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/memorable-details.js
blob: 07482b295d5dc79ac94d83ef85a683f6a28bfb78 (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
/* eslint-env browser */

import {stitchArrays} from '../../shared-util/sugar.js';

export const info = {
  id: 'memorableDetailsInfo',

  details: null,
  ids: null,

  session: {
    openDetails: {
      type: 'json',
      maxLength: settings => settings.maxOpenDetailsStorage,
    },
  },

  settings: {
    maxOpenDetailsStorage: 1000,
  },
};

export function getPageReferences() {
  info.details =
    Array.from(document.querySelectorAll('details.memorable'));

  info.ids =
    info.details.map(details => details.getAttribute('data-memorable-id'));
}

export function mutatePageContent() {
  stitchArrays({
    details: info.details,
    id: info.ids,
  }).forEach(({details, id}) => {
      if (info.session.openDetails?.includes(id)) {
        details.open = true;
      }
    });
}

export function addPageListeners() {
  for (const [index, details] of info.details.entries()) {
    details.addEventListener('toggle', () => {
      handleDetailsToggled(index);
    });
  }
}

function handleDetailsToggled(index) {
  const details = info.details[index];
  const id = info.ids[index];

  if (details.open) {
    if (info.session.openDetails) {
      info.session.openDetails = [...info.session.openDetails, id];
    } else {
      info.session.openDetails = [id];
    }
  } else if (info.session.openDetails?.includes(id)) {
    info.session.openDetails =
      info.session.openDetails.filter(item => item !== id);
  }
}