« get me outta code hell

client.js « static « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/static/client.js
blob: ebe8604f9dd6d7525a9a3aed52f58a69c84818e7 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/* eslint-env browser */

// This is the JS file that gets loaded on the client! It's only really used for
// the random track feature right now - the idea is we only use it for stuff
// that cannot 8e done at static-site compile time, 8y its fundamentally
// ephemeral nature.
//
// Upd8: As of 04/02/2021, it's now used for info cards too! Nice.

import {getColors} from '../util/colors.js';

import {getArtistNumContributions} from '../util/wiki-data.js';

let albumData, artistData;
let officialAlbumData, fandomAlbumData;

let ready = false;

// Localiz8tion nonsense ----------------------------------

const language = document.documentElement.getAttribute('lang');

let list;
if (typeof Intl === 'object' && typeof Intl.ListFormat === 'function') {
  const getFormat = (type) => {
    const formatter = new Intl.ListFormat(language, {type});
    return formatter.format.bind(formatter);
  };

  list = {
    conjunction: getFormat('conjunction'),
    disjunction: getFormat('disjunction'),
    unit: getFormat('unit'),
  };
} else {
  // Not a gr8 mock we've got going here, 8ut it's *mostly* language-free.
  // We use the same mock for every list 'cuz we don't have any of the
  // necessary CLDR info to appropri8tely distinguish 8etween them.
  const arbitraryMock = (array) => array.join(', ');

  list = {
    conjunction: arbitraryMock,
    disjunction: arbitraryMock,
    unit: arbitraryMock,
  };
}

// Miscellaneous helpers ----------------------------------

function rebase(href, rebaseKey = 'rebaseLocalized') {
  const relative = (document.documentElement.dataset[rebaseKey] || '.') + '/';
  if (relative) {
    return relative + href;
  } else {
    return href;
  }
}

function pick(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function cssProp(el, key) {
  return getComputedStyle(el).getPropertyValue(key).trim();
}

function getRefDirectory(ref) {
  return ref.split(':')[1];
}

function getAlbum(el) {
  const directory = cssProp(el, '--album-directory');
  return albumData.find((album) => album.directory === directory);
}

// TODO: These should pro8a8ly access some shared urlSpec path. We'd need to
// separ8te the tooling around that into common-shared code too.
const getLinkHref = (type, directory) => rebase(`${type}/${directory}`);
const openAlbum = (d) => rebase(`album/${d}`);
const openTrack = (d) => rebase(`track/${d}`);
const openArtist = (d) => rebase(`artist/${d}`);

// TODO: This should also use urlSpec.
function fetchData(type, directory) {
  return fetch(rebase(`${type}/${directory}/data.json`, 'rebaseData')).then(
    (res) => res.json()
  );
}

// JS-based links -----------------------------------------

for (const a of document.body.querySelectorAll('[data-random]')) {
  a.addEventListener('click', (evt) => {
    if (!ready) {
      evt.preventDefault();
      return;
    }

    setTimeout(() => {
      a.href = rebase('js-disabled');
    });
    switch (a.dataset.random) {
      case 'album':
        return (a.href = openAlbum(pick(albumData).directory));
      case 'album-in-fandom':
        return (a.href = openAlbum(pick(fandomAlbumData).directory));
      case 'album-in-official':
        return (a.href = openAlbum(pick(officialAlbumData).directory));
      case 'track':
        return (a.href = openTrack(
          getRefDirectory(
            pick(
              albumData.map((a) => a.tracks).reduce((a, b) => a.concat(b), [])
            )
          )
        ));
      case 'track-in-album':
        return (a.href = openTrack(getRefDirectory(pick(getAlbum(a).tracks))));
      case 'track-in-fandom':
        return (a.href = openTrack(
          getRefDirectory(
            pick(
              fandomAlbumData.reduce(
                (acc, album) => acc.concat(album.tracks),
                []
              )
            )
          )
        ));
      case 'track-in-official':
        return (a.href = openTrack(
          getRefDirectory(
            pick(
              officialAlbumData.reduce(
                (acc, album) => acc.concat(album.tracks),
                []
              )
            )
          )
        ));
      case 'artist':
        return (a.href = openArtist(pick(artistData).directory));
      case 'artist-more-than-one-contrib':
        return (a.href = openArtist(
          pick(
            artistData.filter((artist) => getArtistNumContributions(artist) > 1)
          ).directory
        ));
    }
  });
}

const next = document.getElementById('next-button');
const previous = document.getElementById('previous-button');
const random = document.getElementById('random-button');

const prependTitle = (el, prepend) => {
  const existing = el.getAttribute('title');
  if (existing) {
    el.setAttribute('title', prepend + ' ' + existing);
  } else {
    el.setAttribute('title', prepend);
  }
};

if (next) prependTitle(next, '(Shift+N)');
if (previous) prependTitle(previous, '(Shift+P)');
if (random) prependTitle(random, '(Shift+R)');

document.addEventListener('keypress', (event) => {
  if (event.shiftKey) {
    if (event.charCode === 'N'.charCodeAt(0)) {
      if (next) next.click();
    } else if (event.charCode === 'P'.charCodeAt(0)) {
      if (previous) previous.click();
    } else if (event.charCode === 'R'.charCodeAt(0)) {
      if (random && ready) random.click();
    }
  }
});

for (const reveal of document.querySelectorAll('.reveal')) {
  reveal.addEventListener('click', (event) => {
    if (!reveal.classList.contains('revealed')) {
      reveal.classList.add('revealed');
      event.preventDefault();
      event.stopPropagation();
    }
  });
}

const elements1 = document.getElementsByClassName('js-hide-once-data');
const elements2 = document.getElementsByClassName('js-show-once-data');

for (const element of elements1) element.style.display = 'block';

fetch(rebase('data.json', 'rebaseShared'))
  .then((data) => data.json())
  .then((data) => {
    albumData = data.albumData;
    artistData = data.artistData;

    officialAlbumData = albumData.filter((album) =>
      album.groups.includes('group:official')
    );
    fandomAlbumData = albumData.filter(
      (album) => !album.groups.includes('group:official')
    );

    for (const element of elements1) element.style.display = 'none';
    for (const element of elements2) element.style.display = 'block';

    ready = true;
  });

// Data & info card ---------------------------------------

const NORMAL_HOVER_INFO_DELAY = 750;
const FAST_HOVER_INFO_DELAY = 250;
const END_FAST_HOVER_DELAY = 500;
const HIDE_HOVER_DELAY = 250;

let fastHover = false;
let endFastHoverTimeout = null;

function colorLink(a, color) {
  console.warn('Info card link colors temporarily disabled: chroma.js required, no dependency linking for client.js yet');
  return;

  // eslint-disable-next-line no-unreachable
  const chroma = {};

  if (color) {
    const {primary, dim} = getColors(color, {chroma});
    a.style.setProperty('--primary-color', primary);
    a.style.setProperty('--dim-color', dim);
  }
}

function link(a, type, {name, directory, color}) {
  colorLink(a, color);
  a.innerText = name;
  a.href = getLinkHref(type, directory);
}

function joinElements(type, elements) {
  // We can't use the Intl APIs with elements, 8ecuase it only oper8tes on
  // strings. So instead, we'll pass the element's outer HTML's (which means
  // the entire HTML of that element).
  //
  // That does mean this function returns a string, so always 8e sure to
  // set innerHTML when using it (not appendChild).

  return list[type](elements.map((el) => el.outerHTML));
}

const infoCard = (() => {
  const container = document.getElementById('info-card-container');

  let cancelShow = false;
  let hideTimeout = null;
  let showing = false;

  container.addEventListener('mouseenter', cancelHide);
  container.addEventListener('mouseleave', readyHide);

  function show(type, target) {
    cancelShow = false;

    fetchData(type, target.dataset[type]).then((data) => {
      // Manual DOM 'cuz we're laaaazy.

      if (cancelShow) {
        return;
      }

      showing = true;

      const rect = target.getBoundingClientRect();

      container.style.setProperty('--primary-color', data.color);

      container.style.top = window.scrollY + rect.bottom + 'px';
      container.style.left = window.scrollX + rect.left + 'px';

      // Use a short timeout to let a currently hidden (or not yet shown)
      // info card teleport to the position set a8ove. (If it's currently
      // shown, it'll transition to that position.)
      setTimeout(() => {
        container.classList.remove('hide');
        container.classList.add('show');
      }, 50);

      // 8asic details.

      const nameLink = container.querySelector('.info-card-name a');
      link(nameLink, 'track', data);

      const albumLink = container.querySelector('.info-card-album a');
      link(albumLink, 'album', data.album);

      const artistSpan = container.querySelector('.info-card-artists span');
      artistSpan.innerHTML = joinElements(
        'conjunction',
        data.artists.map(({artist}) => {
          const a = document.createElement('a');
          a.href = getLinkHref('artist', artist.directory);
          a.innerText = artist.name;
          return a;
        })
      );

      const coverArtistParagraph = container.querySelector(
        '.info-card-cover-artists'
      );
      const coverArtistSpan = coverArtistParagraph.querySelector('span');
      if (data.coverArtists.length) {
        coverArtistParagraph.style.display = 'block';
        coverArtistSpan.innerHTML = joinElements(
          'conjunction',
          data.coverArtists.map(({artist}) => {
            const a = document.createElement('a');
            a.href = getLinkHref('artist', artist.directory);
            a.innerText = artist.name;
            return a;
          })
        );
      } else {
        coverArtistParagraph.style.display = 'none';
      }

      // Cover art.

      const [containerNoReveal, containerReveal] = [
        container.querySelector('.info-card-art-container.no-reveal'),
        container.querySelector('.info-card-art-container.reveal'),
      ];

      const [containerShow, containerHide] = data.cover.warnings.length
        ? [containerReveal, containerNoReveal]
        : [containerNoReveal, containerReveal];

      containerHide.style.display = 'none';
      containerShow.style.display = 'block';

      const img = containerShow.querySelector('.info-card-art');
      img.src = rebase(data.cover.paths.small, 'rebaseMedia');

      const imgLink = containerShow.querySelector('a');
      colorLink(imgLink, data.color);
      imgLink.href = rebase(data.cover.paths.original, 'rebaseMedia');

      if (containerShow === containerReveal) {
        const cw = containerShow.querySelector('.info-card-art-warnings');
        cw.innerText = list.unit(data.cover.warnings);

        const reveal = containerShow.querySelector('.reveal');
        reveal.classList.remove('revealed');
      }
    });
  }

  function hide() {
    container.classList.remove('show');
    container.classList.add('hide');
    cancelShow = true;
    showing = false;
  }

  function readyHide() {
    if (!hideTimeout && showing) {
      hideTimeout = setTimeout(hide, HIDE_HOVER_DELAY);
    }
  }

  function cancelHide() {
    if (hideTimeout) {
      clearTimeout(hideTimeout);
      hideTimeout = null;
    }
  }

  return {
    show,
    hide,
    readyHide,
    cancelHide,
  };
})();

function makeInfoCardLinkHandlers(type) {
  let hoverTimeout = null;

  return {
    mouseenter(evt) {
      hoverTimeout = setTimeout(
        () => {
          fastHover = true;
          infoCard.show(type, evt.target);
        },
        fastHover ? FAST_HOVER_INFO_DELAY : NORMAL_HOVER_INFO_DELAY);

      clearTimeout(endFastHoverTimeout);
      endFastHoverTimeout = null;

      infoCard.cancelHide();
    },

    mouseleave() {
      clearTimeout(hoverTimeout);

      if (fastHover && !endFastHoverTimeout) {
        endFastHoverTimeout = setTimeout(() => {
          endFastHoverTimeout = null;
          fastHover = false;
        }, END_FAST_HOVER_DELAY);
      }

      infoCard.readyHide();
    },
  };
}

const infoCardLinkHandlers = {
  track: makeInfoCardLinkHandlers('track'),
};

function addInfoCardLinkHandlers(type) {
  for (const a of document.querySelectorAll(`a[data-${type}]`)) {
    for (const [eventName, handler] of Object.entries(
      infoCardLinkHandlers[type]
    )) {
      a.addEventListener(eventName, handler);
    }
  }
}

// Info cards are disa8led for now since they aren't quite ready for release,
// 8ut you can try 'em out 8y setting this localStorage flag!
//
//     localStorage.tryInfoCards = true;
//
if (localStorage.tryInfoCards) {
  addInfoCardLinkHandlers('track');
}

// Sticky content heading ---------------------------------

const stickyHeadingInfo = Array.from(document.querySelectorAll('.content-sticky-heading-container'))
  .map(stickyContainer => {
    const {parentElement: contentContainer} = stickyContainer;
    const stickySubheading = stickyContainer.querySelector('.content-sticky-subheading');
    const contentHeadings = Array.from(contentContainer.querySelectorAll('.content-heading'));

    return {
      contentContainer,
      contentHeadings,
      stickyContainer,
      stickySubheading,
      state: {
        displayedHeading: null,
      },
    };
  });

const topOfViewInside = (el, scroll = window.scrollY) => (
  scroll > el.offsetTop &&
  scroll < el.offsetTop + el.offsetHeight
);

function updateStickyHeading() {
  for (const {
    contentContainer,
    contentHeadings,
    stickyContainer,
    stickySubheading,
    state,
  } of stickyHeadingInfo) {
    let closestHeading = null;

    if (topOfViewInside(contentContainer)) {
      if (stickySubheading.childNodes.length === 0) {
        // &nbsp; to ensure correct basic line height
        stickySubheading.appendChild(document.createTextNode('\xA0'));
      }

      const stickyRect = stickyContainer.getBoundingClientRect();
      const subheadingRect = stickySubheading.getBoundingClientRect();
      const stickyBottom = stickyRect.bottom + subheadingRect.height;

      // This array is reversed so that we're starting from the bottom when
      // iterating over it.
      for (let i = contentHeadings.length - 1; i >= 0; i--) {
        const heading = contentHeadings[i];
        const headingRect = heading.getBoundingClientRect();
        if (headingRect.y + headingRect.height / 1.5 < stickyBottom) {
          closestHeading = heading;
          break;
        }
      }
    }

    if (state.displayedHeading !== closestHeading) {
      if (closestHeading) {
        // Array.from needed to iterate over a live array with for..of
        for (const child of Array.from(stickySubheading.childNodes)) {
          child.remove();
        }

        for (const child of closestHeading.childNodes) {
          if (child.tagName === 'A') {
            for (const grandchild of child.childNodes) {
              stickySubheading.appendChild(grandchild.cloneNode(true));
            }
          } else {
            stickySubheading.appendChild(child.cloneNode(true));
          }
        }

        stickySubheading.classList.add('visible');
      } else {
        stickySubheading.classList.remove('visible');
      }

      state.displayedHeading = closestHeading;
    }
  }
}

document.addEventListener('scroll', updateStickyHeading);

updateStickyHeading();