« get me outta code hell

hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/util')
-rw-r--r--src/util/cli.js2
-rw-r--r--src/util/colors.js27
-rw-r--r--src/util/find.js10
-rw-r--r--src/util/html.js18
-rw-r--r--src/util/io.js2
-rw-r--r--src/util/link.js33
-rw-r--r--src/util/magic-constants.js2
-rw-r--r--src/util/node-utils.js2
-rw-r--r--src/util/replacer.js21
-rw-r--r--src/util/serialize.js11
-rw-r--r--src/util/sugar.js64
-rw-r--r--src/util/urls.js19
-rw-r--r--src/util/wiki-data.js54
13 files changed, 118 insertions, 147 deletions
diff --git a/src/util/cli.js b/src/util/cli.js
index 99c0638c..f1a31900 100644
--- a/src/util/cli.js
+++ b/src/util/cli.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Utility functions for CLI- and de8ugging-rel8ted stuff.
 //
 // A 8unch of these depend on process.stdout 8eing availa8le, so they won't
diff --git a/src/util/colors.js b/src/util/colors.js
index 5848a820..a0cc7486 100644
--- a/src/util/colors.js
+++ b/src/util/colors.js
@@ -1,16 +1,25 @@
-/** @format */
-
 // Color and theming utility functions! Handy.
 
 // Graciously stolen from https://stackoverflow.com/a/54071699! ::::)
 // in: r,g,b in [0,1], out: h in [0,360) and s,l in [0,1]
 export function rgb2hsl(r, g, b) {
   let a = Math.max(r, g, b),
-    n = a - Math.min(r, g, b),
-    f = 1 - Math.abs(a + a - n - 1);
+      n = a - Math.min(r, g, b),
+      f = 1 - Math.abs(a + a - n - 1);
+
   let h =
-    n && (a == r ? (g - b) / n : a == g ? 2 + (b - r) / n : 4 + (r - g) / n);
-  return [60 * (h < 0 ? h + 6 : h), f ? n / f : 0, (a + a - n) / 2];
+    n &&
+      a == r
+        ? (g - b) / n
+        : a == g
+          ? 2 + (b - r) / n
+          : 4 + (r - g) / n;
+
+  return [
+    60 * (h < 0 ? h + 6 : h),
+    f ? n / f : 0,
+    (a + a - n) / 2
+  ];
 }
 
 export function getColors(primary) {
@@ -19,10 +28,10 @@ export function getColors(primary) {
     .match(/[0-9a-fA-F]{2,2}/g)
     .slice(0, 3)
     .map((val) => parseInt(val, 16) / 255);
+
   const [h, s, l] = rgb2hsl(r, g, b);
-  const dim = `hsl(${Math.round(h)}deg, ${Math.round(s * 50)}%, ${Math.round(
-    l * 80
-  )}%)`;
+
+  const dim = `hsl(${Math.round(h)}deg, ${Math.round(s * 50)}%, ${Math.round(l * 80)}%)`;
   const bg = `hsla(${Math.round(h)}deg, ${Math.round(s * 15)}%, 12%, 0.80)`;
 
   return {
diff --git a/src/util/find.js b/src/util/find.js
index 71026fa2..ed0a6809 100644
--- a/src/util/find.js
+++ b/src/util/find.js
@@ -1,5 +1,3 @@
-/** @format */
-
 import {color, logWarn} from './cli.js';
 
 import {inspect} from 'util';
@@ -26,9 +24,7 @@ function findHelper(keys, findFns = {}) {
   const byDirectory = findFns.byDirectory || matchDirectory;
   const byName = findFns.byName || matchName;
 
-  const keyRefRegex = new RegExp(
-    String.raw`^(?:(${keys.join('|')}):(?=\S))?(.*)$`
-  );
+  const keyRefRegex = new RegExp(String.raw`^(?:(${keys.join('|')}):(?=\S))?(.*)$`);
 
   // The mode argument here may be 'warn', 'error', or 'quiet'. 'error' throws
   // errors for null matches (with details about the error), while 'warn' and
@@ -37,9 +33,7 @@ function findHelper(keys, findFns = {}) {
   return (fullRef, data, {mode = 'warn'} = {}) => {
     if (!fullRef) return null;
     if (typeof fullRef !== 'string') {
-      throw new Error(
-        `Got a reference that is ${typeof fullRef}, not string: ${fullRef}`
-      );
+      throw new Error(`Got a reference that is ${typeof fullRef}, not string: ${fullRef}`);
     }
 
     if (!data) {
diff --git a/src/util/html.js b/src/util/html.js
index 752291e9..0a586223 100644
--- a/src/util/html.js
+++ b/src/util/html.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Some really simple functions for formatting HTML content.
 
 // COMPREHENSIVE!
@@ -116,16 +114,18 @@ export function escapeAttributeValue(value) {
 export function attributes(attribs) {
   return Object.entries(attribs)
     .map(([key, val]) => {
-      if (typeof val === 'undefined' || val === null) return [key, val, false];
-      else if (typeof val === 'string') return [key, val, true];
-      else if (typeof val === 'boolean') return [key, val, val];
-      else if (typeof val === 'number') return [key, val.toString(), true];
+      if (typeof val === 'undefined' || val === null)
+        return [key, val, false];
+      else if (typeof val === 'string')
+        return [key, val, true];
+      else if (typeof val === 'boolean')
+        return [key, val, val];
+      else if (typeof val === 'number')
+        return [key, val.toString(), true];
       else if (Array.isArray(val))
         return [key, val.filter(Boolean).join(' '), val.length > 0];
       else
-        throw new Error(
-          `Attribute value for ${key} should be primitive or array, got ${typeof val}`
-        );
+        throw new Error(`Attribute value for ${key} should be primitive or array, got ${typeof val}`);
     })
     .filter(([_key, _val, keep]) => keep)
     .map(([key, val]) =>
diff --git a/src/util/io.js b/src/util/io.js
index cfd6708d..6cc89b56 100644
--- a/src/util/io.js
+++ b/src/util/io.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Utility functions for interacting with files and other external data
 // interfacey constructs.
 
diff --git a/src/util/link.js b/src/util/link.js
index 8fe3c2f4..9de4c95a 100644
--- a/src/util/link.js
+++ b/src/util/link.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // This file is essentially one level of a8straction a8ove urls.js (and the
 // urlSpec it gets its paths from). It's a 8unch of utility functions which
 // take certain types of wiki data o8jects (colloquially known as "things")
@@ -35,18 +33,18 @@ export function getLinkThemeString(color) {
 const appendIndexHTMLRegex = /^(?!https?:\/\/).+\/$/;
 
 const linkHelper =
-  (hrefFn, {color = true, attr = null} = {}) =>
-  (
-    thing,
-    {
-      to,
-      text = '',
-      attributes = null,
-      class: className = '',
-      color: color2 = true,
-      hash = '',
-    }
-  ) => {
+  (hrefFn, {
+    color = true,
+    attr = null,
+  } = {}) =>
+  (thing, {
+    to,
+    text = '',
+    attributes = null,
+    class: className = '',
+    color: color2 = true,
+    hash = '',
+  }) => {
     let href = hrefFn(thing, {to});
 
     if (link.globalOptions.appendIndexHTML) {
@@ -88,6 +86,7 @@ const linkDirectory = (key, {expose = null, attr = null, ...conf} = {}) =>
 
 const linkPathname = (key, conf) =>
   linkHelper(({directory: pathname}, {to}) => to(key, pathname), conf);
+
 const linkIndex = (key, conf) =>
   linkHelper((_, {to}) => to('localized.' + key), conf);
 
@@ -143,8 +142,7 @@ const link = {
       to(
         'media.albumAdditionalFile',
         fakeFileObject.album.directory,
-        fakeFileObject.name
-      ),
+        fakeFileObject.name),
     {color: false}
   ),
   albumAdditionalFile: ({file, album}, {to}) =>
@@ -153,8 +151,7 @@ const link = {
         name: file,
         album,
       },
-      {to}
-    ),
+      {to}),
 
   media: linkPathname('media.path', {color: false}),
   root: linkPathname('shared.path', {color: false}),
diff --git a/src/util/magic-constants.js b/src/util/magic-constants.js
index dbdbcfda..73fdbc6d 100644
--- a/src/util/magic-constants.js
+++ b/src/util/magic-constants.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Magic constants only! These are hard-coded, and any use of them should be
 // considered a flaw in the codebase - areas where we use hard-coded behavior
 // to support one use of the wiki software (i.e. HSMusic, usually), rather than
diff --git a/src/util/node-utils.js b/src/util/node-utils.js
index df446654..252e920a 100644
--- a/src/util/node-utils.js
+++ b/src/util/node-utils.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Utility functions which are only relevant to particular Node.js constructs.
 
 import {fileURLToPath} from 'url';
diff --git a/src/util/replacer.js b/src/util/replacer.js
index ea5a674d..9d602ca9 100644
--- a/src/util/replacer.js
+++ b/src/util/replacer.js
@@ -1,15 +1,10 @@
-/** @format */
-
 import {logError, logWarn} from './cli.js';
 import {escapeRegex} from './sugar.js';
 
 export function validateReplacerSpec(replacerSpec, {find, link}) {
   let success = true;
 
-  for (const [
-    key,
-    {link: linkKey, find: findKey, html},
-  ] of Object.entries(replacerSpec)) {
+  for (const [key, {link: linkKey, find: findKey, html}] of Object.entries(replacerSpec)) {
     if (!html && !link[linkKey]) {
       logError`The replacer spec ${key} has invalid link key ${linkKey}! Specify it in link specs or fix typo.`;
       success = false;
@@ -436,14 +431,18 @@ function transformNodes(nodes, opts) {
   return nodes.map((node) => transformNode(node, opts)).join('');
 }
 
-export function transformInline(
-  input,
-  {replacerSpec, find, link, language, to, wikiData}
-) {
+export function transformInline(input, {
+  replacerSpec,
+  find,
+  language,
+  link,
+  to,
+  wikiData,
+}) {
   if (!replacerSpec) throw new Error('Expected replacerSpec');
   if (!find) throw new Error('Expected find');
-  if (!link) throw new Error('Expected link');
   if (!language) throw new Error('Expected language');
+  if (!link) throw new Error('Expected link');
   if (!to) throw new Error('Expected to');
   if (!wikiData) throw new Error('Expected wikiData');
 
diff --git a/src/util/serialize.js b/src/util/serialize.js
index 9aa8b0c5..73a31374 100644
--- a/src/util/serialize.js
+++ b/src/util/serialize.js
@@ -1,5 +1,3 @@
-/** @format */
-
 export function serializeLink(thing) {
   const ret = {};
   ret.name = thing.name;
@@ -25,11 +23,10 @@ export function serializeImagePaths(original, {thumb}) {
   };
 }
 
-export function serializeCover(
-  thing,
-  pathFunction,
-  {serializeImagePaths, urls}
-) {
+export function serializeCover(thing, pathFunction, {
+  serializeImagePaths,
+  urls,
+}) {
   const coverPath = pathFunction(thing, {
     to: urls.from('media.root').to,
   });
diff --git a/src/util/sugar.js b/src/util/sugar.js
index 24ae8639..808a7e1c 100644
--- a/src/util/sugar.js
+++ b/src/util/sugar.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Syntactic sugar! (Mostly.)
 // Generic functions - these are useful just a8out everywhere.
 //
@@ -17,9 +15,7 @@ import {color} from './cli.js';
 export function* splitArray(array, fn) {
   let lastIndex = 0;
   while (lastIndex < array.length) {
-    let nextIndex = array.findIndex(
-      (item, index) => index >= lastIndex && fn(item)
-    );
+    let nextIndex = array.findIndex((item, index) => index >= lastIndex && fn(item));
     if (nextIndex === -1) {
       nextIndex = array.length;
     }
@@ -54,8 +50,7 @@ export function accumulateSum(array, fn = x => x) {
     (accumulator, value, index, array) =>
       accumulator +
         fn(value, index, array) ?? 0,
-    0
-  );
+    0);
 }
 
 export const mapInPlace = (array, fn) =>
@@ -275,11 +270,10 @@ export function mapAggregate(array, fn, aggregateOpts) {
   return _mapAggregate('sync', null, array, fn, aggregateOpts);
 }
 
-export function mapAggregateAsync(
-  array,
-  fn,
-  {promiseAll = Promise.all.bind(Promise), ...aggregateOpts} = {}
-) {
+export function mapAggregateAsync(array, fn, {
+  promiseAll = Promise.all.bind(Promise),
+  ...aggregateOpts
+} = {}) {
   return _mapAggregate('async', promiseAll, array, fn, aggregateOpts);
 }
 
@@ -299,10 +293,11 @@ export function _mapAggregate(mode, promiseAll, array, fn, aggregateOpts) {
       .filter((value) => value !== failureSymbol);
     return {result, aggregate};
   } else {
-    return promiseAll(array.map(aggregate.wrapAsync(fn))).then((values) => {
-      const result = values.filter((value) => value !== failureSymbol);
-      return {result, aggregate};
-    });
+    return promiseAll(array.map(aggregate.wrapAsync(fn)))
+      .then((values) => {
+        const result = values.filter((value) => value !== failureSymbol);
+        return {result, aggregate};
+      });
   }
 }
 
@@ -317,11 +312,10 @@ export function filterAggregate(array, fn, aggregateOpts) {
   return _filterAggregate('sync', null, array, fn, aggregateOpts);
 }
 
-export async function filterAggregateAsync(
-  array,
-  fn,
-  {promiseAll = Promise.all.bind(Promise), ...aggregateOpts} = {}
-) {
+export async function filterAggregateAsync(array, fn, {
+  promiseAll = Promise.all.bind(Promise),
+  ...aggregateOpts
+} = {}) {
   return _filterAggregate('async', promiseAll, array, fn, aggregateOpts);
 }
 
@@ -357,24 +351,20 @@ function _filterAggregate(mode, promiseAll, array, fn, aggregateOpts) {
 
   if (mode === 'sync') {
     const result = array
-      .map(
-        aggregate.wrap((input, index, array) => {
-          const output = fn(input, index, array);
-          return {input, output};
-        })
-      )
+      .map(aggregate.wrap((input, index, array) => {
+        const output = fn(input, index, array);
+        return {input, output};
+      }))
       .filter(filterFunction)
       .map(mapFunction);
 
     return {result, aggregate};
   } else {
     return promiseAll(
-      array.map(
-        aggregate.wrapAsync(async (input, index, array) => {
-          const output = await fn(input, index, array);
-          return {input, output};
-        })
-      )
+      array.map(aggregate.wrapAsync(async (input, index, array) => {
+        const output = await fn(input, index, array);
+        return {input, output};
+      }))
     ).then((values) => {
       const result = values.filter(filterFunction).map(mapFunction);
 
@@ -414,10 +404,10 @@ export function _withAggregate(mode, aggregateOpts, fn) {
   }
 }
 
-export function showAggregate(
-  topError,
-  {pathToFile = (p) => p, showTraces = true} = {}
-) {
+export function showAggregate(topError, {
+  pathToFile = (p) => p,
+  showTraces = true,
+} = {}) {
   const recursive = (error, {level}) => {
     let header = showTraces
       ? `[${error.constructor.name || 'unnamed'}] ${
diff --git a/src/util/urls.js b/src/util/urls.js
index d86c047d..1f9cd9c0 100644
--- a/src/util/urls.js
+++ b/src/util/urls.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Code that deals with URLs (really the pathnames that get referenced all
 // throughout the gener8ted HTML). Most nota8ly here is generateURLs, which
 // is in charge of pre-gener8ting a complete network of template strings
@@ -28,9 +26,7 @@ export function generateURLs(urlSpec) {
     const group = obj[groupKey];
 
     if (!Object.hasOwn(group, subKey)) {
-      throw new Error(
-        `Expected valid subkey (got ${subKey} for group ${groupKey})`
-      );
+      throw new Error(`Expected valid subkey (got ${subKey} for group ${groupKey})`);
     }
 
     return {
@@ -47,9 +43,8 @@ export function generateURLs(urlSpec) {
   const generateTo = (fromPath, fromGroup) => {
     const A = trimLeadingSlash(fromPath);
 
-    const rebasePrefix = '../'.repeat(
-      (fromGroup.prefix || '').split('/').filter(Boolean).length
-    );
+    const rebasePrefix = '../'
+      .repeat((fromGroup.prefix || '').split('/').filter(Boolean).length);
 
     const pathHelper = (toPath, toGroup) => {
       let B = trimLeadingSlash(toPath);
@@ -117,14 +112,14 @@ export function generateURLs(urlSpec) {
   };
 
   const generateFrom = () => {
-    const map = withEntries(urlSpec, (entries) =>
-      entries.map(([key, group]) => [
+    const map = withEntries(
+      urlSpec,
+      (entries) => entries.map(([key, group]) => [
         key,
         withEntries(group.paths, (entries) =>
           entries.map(([key, path]) => [key, generateTo(path, group)])
         ),
-      ])
-    );
+      ]));
 
     const from = (key) => getValueForFullKey(map, key).value;
 
diff --git a/src/util/wiki-data.js b/src/util/wiki-data.js
index b0b0b2e0..7d2cfa9f 100644
--- a/src/util/wiki-data.js
+++ b/src/util/wiki-data.js
@@ -1,5 +1,3 @@
-/** @format */
-
 // Utility functions for interacting with wiki data.
 
 import {empty} from './sugar.js';
@@ -144,10 +142,9 @@ export function normalizeName(s) {
 // ...trackData]), because the initial sort places albums before tracks - and
 // sortByDirectory will handle the rest, given all directories are unique
 // except when album and track directories overlap with each other.
-export function sortByDirectory(
-  data,
-  {getDirectory = (o) => o.directory} = {}
-) {
+export function sortByDirectory(data, {
+  getDirectory = (o) => o.directory,
+} = {}) {
   return data.sort((a, b) => {
     const ad = getDirectory(a);
     const bd = getDirectory(b);
@@ -155,7 +152,9 @@ export function sortByDirectory(
   });
 }
 
-export function sortByName(data, {getName = (o) => o.name} = {}) {
+export function sortByName(data, {
+  getName = (o) => o.name,
+} = {}) {
   const nameMap = new Map();
   const normalizedNameMap = new Map();
   for (const o of data) {
@@ -178,7 +177,9 @@ export function sortByName(data, {getName = (o) => o.name} = {}) {
   });
 }
 
-export function sortByDate(data, {getDate = (o) => o.date} = {}) {
+export function sortByDate(data, {
+  getDate = (o) => o.date,
+} = {}) {
   return data.sort((a, b) => {
     const ad = getDate(a);
     const bd = getDate(b);
@@ -269,7 +270,10 @@ export function sortByConditions(data, conditions) {
 // Expects thing properties:
 //  * directory (or override getDirectory)
 //  * name (or override getName)
-export function sortAlphabetically(data, {getDirectory, getName} = {}) {
+export function sortAlphabetically(data, {
+  getDirectory,
+  getName,
+} = {}) {
   sortByDirectory(data, {getDirectory});
   sortByName(data, {getName});
   return data;
@@ -279,10 +283,11 @@ export function sortAlphabetically(data, {getDirectory, getName} = {}) {
 //  * directory (or override getDirectory)
 //  * name (or override getName)
 //  * date (or override getDate)
-export function sortChronologically(
-  data,
-  {getDirectory, getName, getDate} = {}
-) {
+export function sortChronologically(data, {
+  getDirectory,
+  getName,
+  getDate,
+} = {}) {
   sortAlphabetically(data, {getDirectory, getName});
   sortByDate(data, {getDate});
   return data;
@@ -296,7 +301,9 @@ export function sortChronologically(
 // release date but can be overridden) above all else.
 //
 // This function also works for data lists which contain only tracks.
-export function sortAlbumsTracksChronologically(data, {getDate} = {}) {
+export function sortAlbumsTracksChronologically(data, {
+  getDate,
+} = {}) {
   // Sort albums before tracks...
   sortByConditions(data, [(t) => t.album === undefined]);
 
@@ -320,9 +327,8 @@ export function sortAlbumsTracksChronologically(data, {getDate} = {}) {
 // Specific data utilities
 
 export function filterAlbumsByCommentary(albums) {
-  return albums.filter((album) =>
-    [album, ...album.tracks].some((x) => x.commentary)
-  );
+  return albums
+    .filter((album) => [album, ...album.tracks].some((x) => x.commentary));
 }
 
 export function getAlbumCover(album, {to}) {
@@ -387,12 +393,7 @@ export function getTrackCover(track, {to}) {
   if (!track.hasCoverArt) {
     return getAlbumCover(track.album, {to});
   } else {
-    return to(
-      'media.trackCover',
-      track.album.directory,
-      track.directory,
-      track.coverArtFileExtension
-    );
+    return to('media.trackCover', track.album.directory, track.directory, track.coverArtFileExtension);
   }
 }
 
@@ -455,11 +456,7 @@ export function getNewAdditions(numAlbums, {wikiData}) {
     const currentDate = sortedAlbums[i].dateAddedToWiki;
     const groupMap = new Map();
     const groupArray = [];
-    for (
-      let album;
-      (album = sortedAlbums[i]) && +album.dateAddedToWiki === +currentDate;
-      i++
-    ) {
+    for (let album; (album = sortedAlbums[i]) && +album.dateAddedToWiki === +currentDate; i++) {
       const primaryGroup = album.groups[0];
       if (groupMap.has(primaryGroup)) {
         groupMap.get(primaryGroup).push(album);
@@ -510,6 +507,7 @@ export function getNewReleases(numReleases, {wikiData}) {
   const latestFirst = albumData
     .filter((album) => album.isListedOnHomepage)
     .reverse();
+
   const majorReleases = latestFirst.filter((album) => album.isMajorRelease);
   majorReleases.splice(1);