client.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // This is the JS file that gets loaded on the client! It's only really used for
  2. // the random track feature right now - the idea is we only use it for stuff
  3. // that cannot 8e done at static-site compile time, 8y its fundamentally
  4. // ephemeral nature.
  5. //
  6. // Upd8: As of 04/02/2021, it's now used for info cards too! Nice.
  7. 'use strict';
  8. let albumData, artistData, flashData;
  9. let officialAlbumData, fandomAlbumData, artistNames;
  10. let ready = false;
  11. // Localiz8tion nonsense ----------------------------------
  12. const language = document.documentElement.getAttribute('lang');
  13. let list;
  14. if (
  15. typeof Intl === 'object' &&
  16. typeof Intl.ListFormat === 'function'
  17. ) {
  18. const getFormat = type => {
  19. const formatter = new Intl.ListFormat(language, {type});
  20. return formatter.format.bind(formatter);
  21. };
  22. list = {
  23. conjunction: getFormat('conjunction'),
  24. disjunction: getFormat('disjunction'),
  25. unit: getFormat('unit')
  26. };
  27. } else {
  28. // Not a gr8 mock we've got going here, 8ut it's *mostly* language-free.
  29. // We use the same mock for every list 'cuz we don't have any of the
  30. // necessary CLDR info to appropri8tely distinguish 8etween them.
  31. const arbitraryMock = array => array.join(', ');
  32. list = {
  33. conjunction: arbitraryMock,
  34. disjunction: arbitraryMock,
  35. unit: arbitraryMock
  36. };
  37. }
  38. // Miscellaneous helpers ----------------------------------
  39. function rebase(href, rebaseKey = 'rebaseLocalized') {
  40. const relative = document.documentElement.dataset[rebaseKey] + '/';
  41. if (relative) {
  42. return relative + href;
  43. } else {
  44. return href;
  45. }
  46. }
  47. function pick(array) {
  48. return array[Math.floor(Math.random() * array.length)];
  49. }
  50. function cssProp(el, key) {
  51. return getComputedStyle(el).getPropertyValue(key).trim();
  52. }
  53. function getRefDirectory(ref) {
  54. return ref.split(':')[1];
  55. }
  56. function getAlbum(el) {
  57. const directory = cssProp(el, '--album-directory');
  58. return albumData.find(album => album.directory === directory);
  59. }
  60. function getFlash(el) {
  61. const directory = cssProp(el, '--flash-directory');
  62. return flashData.find(flash => flash.directory === directory);
  63. }
  64. // TODO: These should pro8a8ly access some shared urlSpec path. We'd need to
  65. // separ8te the tooling around that into common-shared code too.
  66. const getLinkHref = (type, directory) => rebase(`${type}/${directory}`);
  67. const openAlbum = d => rebase(`album/${d}`);
  68. const openTrack = d => rebase(`track/${d}`);
  69. const openArtist = d => rebase(`artist/${d}`);
  70. const openFlash = d => rebase(`flash/${d}`);
  71. function getTrackListAndIndex() {
  72. const album = getAlbum(document.body);
  73. const directory = cssProp(document.body, '--track-directory');
  74. if (!directory && !album) return {};
  75. if (!directory) return {list: album.tracks};
  76. const trackIndex = album.tracks.findIndex(track => track.directory === directory);
  77. return {list: album.tracks, index: trackIndex};
  78. }
  79. function openRandomTrack() {
  80. const { list } = getTrackListAndIndex();
  81. if (!list) return;
  82. return openTrack(pick(list));
  83. }
  84. function getFlashListAndIndex() {
  85. const list = flashData.filter(flash => !flash.act8r8k)
  86. const flash = getFlash(document.body);
  87. if (!flash) return {list};
  88. const flashIndex = list.indexOf(flash);
  89. return {list, index: flashIndex};
  90. }
  91. // TODO: This should also use urlSpec.
  92. function fetchData(type, directory) {
  93. return fetch(rebase(`${type}/${directory}/data.json`, 'rebaseData'))
  94. .then(res => res.json());
  95. }
  96. // JS-based links -----------------------------------------
  97. for (const a of document.body.querySelectorAll('[data-random]')) {
  98. a.addEventListener('click', evt => {
  99. if (!ready) {
  100. evt.preventDefault();
  101. return;
  102. }
  103. setTimeout(() => {
  104. a.href = rebase('js-disabled');
  105. });
  106. switch (a.dataset.random) {
  107. case 'album': return a.href = openAlbum(pick(albumData).directory);
  108. case 'album-in-fandom': return a.href = openAlbum(pick(fandomAlbumData).directory);
  109. case 'album-in-official': return a.href = openAlbum(pick(officialAlbumData).directory);
  110. case 'track': return a.href = openTrack(getRefDirectory(pick(albumData.map(a => a.tracks).reduce((a, b) => a.concat(b), []))));
  111. case 'track-in-album': return a.href = openTrack(getRefDirectory(pick(getAlbum(a).tracks)));
  112. case 'track-in-fandom': return a.href = openTrack(getRefDirectory(pick(fandomAlbumData.reduce((acc, album) => acc.concat(album.tracks), []))));
  113. case 'track-in-official': return a.href = openTrack(getRefDirectory(pick(officialAlbumData.reduce((acc, album) => acc.concat(album.tracks), []))));
  114. case 'artist': return a.href = openArtist(pick(artistData).directory);
  115. case 'artist-more-than-one-contrib': return a.href = openArtist(pick(artistData.filter(artist => C.getArtistNumContributions(artist) > 1)).directory);
  116. }
  117. });
  118. }
  119. const next = document.getElementById('next-button');
  120. const previous = document.getElementById('previous-button');
  121. const random = document.getElementById('random-button');
  122. const prependTitle = (el, prepend) => {
  123. const existing = el.getAttribute('title');
  124. if (existing) {
  125. el.setAttribute('title', prepend + ' ' + existing);
  126. } else {
  127. el.setAttribute('title', prepend);
  128. }
  129. };
  130. if (next) prependTitle(next, '(Shift+N)');
  131. if (previous) prependTitle(previous, '(Shift+P)');
  132. if (random) prependTitle(random, '(Shift+R)');
  133. document.addEventListener('keypress', event => {
  134. if (event.shiftKey) {
  135. if (event.charCode === 'N'.charCodeAt(0)) {
  136. if (next) next.click();
  137. } else if (event.charCode === 'P'.charCodeAt(0)) {
  138. if (previous) previous.click();
  139. } else if (event.charCode === 'R'.charCodeAt(0)) {
  140. if (random && ready) random.click();
  141. }
  142. }
  143. });
  144. for (const reveal of document.querySelectorAll('.reveal')) {
  145. reveal.addEventListener('click', event => {
  146. if (!reveal.classList.contains('revealed')) {
  147. reveal.classList.add('revealed');
  148. event.preventDefault();
  149. event.stopPropagation();
  150. }
  151. });
  152. }
  153. const elements1 = document.getElementsByClassName('js-hide-once-data');
  154. const elements2 = document.getElementsByClassName('js-show-once-data');
  155. for (const element of elements1) element.style.display = 'block';
  156. fetch(rebase('data.json', 'rebaseShared')).then(data => data.json()).then(data => {
  157. albumData = data.albumData;
  158. artistData = data.artistData;
  159. flashData = data.flashData;
  160. officialAlbumData = albumData.filter(album => album.groups.includes('group:official'));
  161. fandomAlbumData = albumData.filter(album => !album.groups.includes('group:official'));
  162. artistNames = artistData.filter(artist => !artist.alias).map(artist => artist.name);
  163. for (const element of elements1) element.style.display = 'none';
  164. for (const element of elements2) element.style.display = 'block';
  165. ready = true;
  166. });
  167. // Data & info card ---------------------------------------
  168. const NORMAL_HOVER_INFO_DELAY = 750;
  169. const FAST_HOVER_INFO_DELAY = 250;
  170. const END_FAST_HOVER_DELAY = 500;
  171. const HIDE_HOVER_DELAY = 250;
  172. let fastHover = false;
  173. let endFastHoverTimeout = null;
  174. function colorLink(a, color) {
  175. if (color) {
  176. const { primary, dim } = C.getColors(color);
  177. a.style.setProperty('--primary-color', primary);
  178. a.style.setProperty('--dim-color', dim);
  179. }
  180. }
  181. function link(a, type, {name, directory, color}) {
  182. colorLink(a, color);
  183. a.innerText = name
  184. a.href = getLinkHref(type, directory);
  185. }
  186. function joinElements(type, elements) {
  187. // We can't use the Intl APIs with elements, 8ecuase it only oper8tes on
  188. // strings. So instead, we'll pass the element's outer HTML's (which means
  189. // the entire HTML of that element).
  190. //
  191. // That does mean this function returns a string, so always 8e sure to
  192. // set innerHTML when using it (not appendChild).
  193. return list[type](elements.map(el => el.outerHTML));
  194. }
  195. const infoCard = (() => {
  196. const container = document.getElementById('info-card-container');
  197. let cancelShow = false;
  198. let hideTimeout = null;
  199. let showing = false;
  200. container.addEventListener('mouseenter', cancelHide);
  201. container.addEventListener('mouseleave', readyHide);
  202. function show(type, target) {
  203. cancelShow = false;
  204. fetchData(type, target.dataset[type]).then(data => {
  205. // Manual DOM 'cuz we're laaaazy.
  206. if (cancelShow) {
  207. return;
  208. }
  209. showing = true;
  210. const rect = target.getBoundingClientRect();
  211. container.style.setProperty('--primary-color', data.color);
  212. container.style.top = window.scrollY + rect.bottom + 'px';
  213. container.style.left = window.scrollX + rect.left + 'px';
  214. // Use a short timeout to let a currently hidden (or not yet shown)
  215. // info card teleport to the position set a8ove. (If it's currently
  216. // shown, it'll transition to that position.)
  217. setTimeout(() => {
  218. container.classList.remove('hide');
  219. container.classList.add('show');
  220. }, 50);
  221. // 8asic details.
  222. const nameLink = container.querySelector('.info-card-name a');
  223. link(nameLink, 'track', data);
  224. const albumLink = container.querySelector('.info-card-album a');
  225. link(albumLink, 'album', data.album);
  226. const artistSpan = container.querySelector('.info-card-artists span');
  227. artistSpan.innerHTML = joinElements('conjunction', data.artists.map(({ artist }) => {
  228. const a = document.createElement('a');
  229. a.href = getLinkHref('artist', artist.directory);
  230. a.innerText = artist.name;
  231. return a;
  232. }));
  233. const coverArtistParagraph = container.querySelector('.info-card-cover-artists');
  234. const coverArtistSpan = coverArtistParagraph.querySelector('span');
  235. if (data.coverArtists.length) {
  236. coverArtistParagraph.style.display = 'block';
  237. coverArtistSpan.innerHTML = joinElements('conjunction', data.coverArtists.map(({ artist }) => {
  238. const a = document.createElement('a');
  239. a.href = getLinkHref('artist', artist.directory);
  240. a.innerText = artist.name;
  241. return a;
  242. }));
  243. } else {
  244. coverArtistParagraph.style.display = 'none';
  245. }
  246. // Cover art.
  247. const [ containerNoReveal, containerReveal ] = [
  248. container.querySelector('.info-card-art-container.no-reveal'),
  249. container.querySelector('.info-card-art-container.reveal')
  250. ];
  251. const [ containerShow, containerHide ] = (data.cover.warnings.length
  252. ? [containerReveal, containerNoReveal]
  253. : [containerNoReveal, containerReveal]);
  254. containerHide.style.display = 'none';
  255. containerShow.style.display = 'block';
  256. const img = containerShow.querySelector('.info-card-art');
  257. img.src = rebase(data.cover.paths.small, 'rebaseMedia');
  258. const imgLink = containerShow.querySelector('a');
  259. colorLink(imgLink, data.color);
  260. imgLink.href = rebase(data.cover.paths.original, 'rebaseMedia');
  261. if (containerShow === containerReveal) {
  262. const cw = containerShow.querySelector('.info-card-art-warnings');
  263. cw.innerText = list.unit(data.cover.warnings);
  264. const reveal = containerShow.querySelector('.reveal');
  265. reveal.classList.remove('revealed');
  266. }
  267. });
  268. }
  269. function hide() {
  270. container.classList.remove('show');
  271. container.classList.add('hide');
  272. cancelShow = true;
  273. showing = false;
  274. }
  275. function readyHide() {
  276. if (!hideTimeout && showing) {
  277. hideTimeout = setTimeout(hide, HIDE_HOVER_DELAY);
  278. }
  279. }
  280. function cancelHide() {
  281. if (hideTimeout) {
  282. clearTimeout(hideTimeout);
  283. hideTimeout = null;
  284. }
  285. }
  286. return {
  287. show,
  288. hide,
  289. readyHide,
  290. cancelHide
  291. };
  292. })();
  293. function makeInfoCardLinkHandlers(type) {
  294. let hoverTimeout = null;
  295. return {
  296. mouseenter(evt) {
  297. hoverTimeout = setTimeout(() => {
  298. fastHover = true;
  299. infoCard.show(type, evt.target);
  300. }, fastHover ? FAST_HOVER_INFO_DELAY : NORMAL_HOVER_INFO_DELAY);
  301. clearTimeout(endFastHoverTimeout);
  302. endFastHoverTimeout = null;
  303. infoCard.cancelHide();
  304. },
  305. mouseleave(evt) {
  306. clearTimeout(hoverTimeout);
  307. if (fastHover && !endFastHoverTimeout) {
  308. endFastHoverTimeout = setTimeout(() => {
  309. endFastHoverTimeout = null;
  310. fastHover = false;
  311. }, END_FAST_HOVER_DELAY);
  312. }
  313. infoCard.readyHide();
  314. }
  315. };
  316. }
  317. const infoCardLinkHandlers = {
  318. track: makeInfoCardLinkHandlers('track')
  319. };
  320. function addInfoCardLinkHandlers(type) {
  321. for (const a of document.querySelectorAll(`a[data-${type}]`)) {
  322. for (const [ eventName, handler ] of Object.entries(infoCardLinkHandlers[type])) {
  323. a.addEventListener(eventName, handler);
  324. }
  325. }
  326. }
  327. // Info cards are disa8led for now since they aren't quite ready for release,
  328. // 8ut you can try 'em out 8y setting this localStorage flag!
  329. //
  330. // localStorage.tryInfoCards = true;
  331. //
  332. if (localStorage.tryInfoCards) {
  333. addInfoCardLinkHandlers('track');
  334. }