« get me outta code hell

track.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/track.js
blob: 5ccf4f8b9c0970e8b05b02b07b76f1f078cea030 (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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
import {inspect} from 'node:util';

import {colors} from '#cli';
import find from '#find';
import {empty} from '#sugar';

import {
  exitWithoutDependency,
  excludeFromList,
  exposeConstant,
  exposeDependency,
  exposeDependencyOrContinue,
  exposeUpdateValueOrContinue,
  input,
  raiseOutputWithoutDependency,
  templateCompositeFrom,
  withPropertyFromObject,
} from '#composite';

import {
  isBoolean,
  isColor,
  isContributionList,
  isDate,
  isFileExtension,
  oneOf,
} from '#validators';

import CacheableObject from './cacheable-object.js';

import Thing, {
  additionalFiles,
  commentary,
  commentatorArtists,
  contributionList,
  directory,
  duration,
  flag,
  name,
  referenceList,
  reverseReferenceList,
  simpleDate,
  singleReference,
  simpleString,
  urls,
  wikiData,
  withResolvedContribs,
  withResolvedReference,
  withReverseReferenceList,
} from './thing.js';

export class Track extends Thing {
  static [Thing.referenceType] = 'track';

  static [Thing.getPropertyDescriptors] = ({Album, ArtTag, Artist, Flash}) => ({
    // Update & expose

    name: name('Unnamed Track'),
    directory: directory(),

    duration: duration(),
    urls: urls(),
    dateFirstReleased: simpleDate(),

    color: [
      exposeUpdateValueOrContinue({
        validate: input.value(isColor),
      }),

      withContainingTrackSection(),

      withPropertyFromObject({
        object: '#trackSection',
        property: input.value('color'),
      }),

      exposeDependencyOrContinue({dependency: '#trackSection.color'}),

      withPropertyFromAlbum({
        property: input.value('color'),
      }),

      exposeDependency({dependency: '#album.color'}),
    ],

    // Controls how find.track works - it'll never be matched by a reference
    // just to the track's name, which means you don't have to always reference
    // some *other* (much more commonly referenced) track by directory instead
    // of more naturally by name.
    alwaysReferenceByDirectory: [
      exposeUpdateValueOrContinue({
        validate: input.value(isBoolean),
      }),

      excludeFromList({
        list: 'trackData',
        item: input.myself(),
      }),

      withOriginalRelease({
        data: '#trackData',
      }),

      exitWithoutDependency({
        dependency: '#originalRelease',
        value: input.value(false),
      }),

      withPropertyFromObject({
        object: '#originalRelease',
        property: input.value('name'),
      }),

      {
        dependencies: ['name', '#originalRelease.name'],
        compute: ({name, '#originalRelease.name': originalName}) =>
          name === originalName,
      },
    ],

    // Disables presenting the track as though it has its own unique artwork.
    // This flag should only be used in select circumstances, i.e. to override
    // an album's trackCoverArtists. This flag supercedes that property, as well
    // as the track's own coverArtists.
    disableUniqueCoverArt: flag(),

    // File extension for track's corresponding media file. This represents the
    // track's unique cover artwork, if any, and does not inherit the extension
    // of the album's main artwork. It does inherit trackCoverArtFileExtension,
    // if present on the album.
    coverArtFileExtension: [
      exitWithoutUniqueCoverArt(),

      exposeUpdateValueOrContinue({
        validate: input.value(isFileExtension),
      }),

      withPropertyFromAlbum({
        property: input.value('trackCoverArtFileExtension'),
      }),

      exposeDependencyOrContinue({dependency: '#album.trackCoverArtFileExtension'}),

      exposeConstant({
        value: input.value('jpg'),
      }),
    ],

    // Date of cover art release. Like coverArtFileExtension, this represents
    // only the track's own unique cover artwork, if any. This exposes only as
    // the track's own coverArtDate or its album's trackArtDate, so if neither
    // is specified, this value is null.
    coverArtDate: [
      withHasUniqueCoverArt(),

      exitWithoutDependency({
        dependency: '#hasUniqueCoverArt',
        mode: input.value('falsy'),
      }),

      exposeUpdateValueOrContinue({
        validate: input.value(isDate),
      }),

      withPropertyFromAlbum({
        property: input.value('trackArtDate'),
      }),

      exposeDependency({dependency: '#album.trackArtDate'}),
    ],

    commentary: commentary(),
    lyrics: simpleString(),

    additionalFiles: additionalFiles(),
    sheetMusicFiles: additionalFiles(),
    midiProjectFiles: additionalFiles(),

    originalReleaseTrack: singleReference({
      class: input.value(Track),
      find: input.value(find.track),
      data: 'trackData',
    }),

    // Internal use only - for directly identifying an album inside a track's
    // util.inspect display, if it isn't indirectly available (by way of being
    // included in an album's track list).
    dataSourceAlbum: singleReference({
      class: input.value(Album),
      find: input.value(find.album),
      data: 'albumData',
    }),

    artistContribs: [
      inheritFromOriginalRelease({property: 'artistContribs'}),

      withResolvedContribs({
        from: input.updateValue({validate: isContributionList}),
      }).outputs({
        '#resolvedContribs': '#artistContribs',
      }),

      exposeDependencyOrContinue({dependency: '#artistContribs'}),

      withPropertyFromAlbum({
        property: input.value('artistContribs'),
      }),

      exposeDependency({dependency: '#album.artistContribs'}),
    ],

    contributorContribs: [
      inheritFromOriginalRelease({
        property: input.value('contributorContribs'),
      }),

      contributionList(),
    ],

    // Cover artists aren't inherited from the original release, since it
    // typically varies by release and isn't defined by the musical qualities
    // of the track.
    coverArtistContribs: [
      exitWithoutUniqueCoverArt(),

      withResolvedContribs({
        from: input.updateValue({validate: isContributionList}),
      }).outputs({
        '#resolvedContribs': '#coverArtistContribs',
      }),

      exposeDependencyOrContinue({dependency: '#coverArtistContribs'}),

      withPropertyFromAlbum({
        property: input.value('trackCoverArtistContribs'),
      }),

      exposeDependency({dependency: '#album.trackCoverArtistContribs'}),
    ],

    referencedTracks: [
      inheritFromOriginalRelease({
        property: input.value('referencedTracks'),
      }),

      referenceList({
        class: input.value(Track),
        find: input.value(find.track),
        data: 'trackData',
      }),
    ],

    sampledTracks: [
      inheritFromOriginalRelease({
        property: input.value('sampledTracks'),
      }),

      referenceList({
        class: input.value(Track),
        find: input.value(find.track),
        data: 'trackData',
      }),
    ],

    artTags: referenceList({
      class: input.value(ArtTag),
      find: input.value(find.artTag),
      data: 'artTagData',
    }),

    // Update only

    albumData: wikiData(Album),
    artistData: wikiData(Artist),
    artTagData: wikiData(ArtTag),
    flashData: wikiData(Flash),
    trackData: wikiData(Track),

    // Expose only

    commentatorArtists: commentatorArtists(),

    album: [
      withAlbum(),
      exposeDependency({dependency: '#album'}),
    ],

    date: [
      exposeDependencyOrContinue({dependency: 'dateFirstReleased'}),

      withPropertyFromAlbum({
        property: input.value('date'),
      }),

      exposeDependency({dependency: '#album.date'}),
    ],

    // Whether or not the track has "unique" cover artwork - a cover which is
    // specifically associated with this track in particular, rather than with
    // the track's album as a whole. This is typically used to select between
    // displaying the track artwork and a fallback, such as the album artwork
    // or a placeholder. (This property is named hasUniqueCoverArt instead of
    // the usual hasCoverArt to emphasize that it does not inherit from the
    // album.)
    hasUniqueCoverArt: [
      withHasUniqueCoverArt(),
      exposeDependency({dependency: '#hasUniqueCoverArt'}),
    ],

    otherReleases: [
      exitWithoutDependency({
        dependency: 'trackData',
        mode: input.value('empty'),
      }),

      withOriginalRelease({
        selfIfOriginal: input.value(true),
      }),

      {
        flags: {expose: true},
        expose: {
          dependencies: [input.myself(), '#originalRelease', 'trackData'],
          compute: ({
            [input.myself()]: thisTrack,
            ['#originalRelease']: originalRelease,
            trackData,
          }) =>
            (originalRelease === thisTrack
              ? []
              : [originalRelease])
              .concat(trackData.filter(track =>
                track !== originalRelease &&
                track !== thisTrack &&
                track.originalReleaseTrack === originalRelease)),
        },
      },
    ],

    // Specifically exclude re-releases from this list - while it's useful to
    // get from a re-release to the tracks it references, re-releases aren't
    // generally relevant from the perspective of the tracks being referenced.
    // Filtering them from data here hides them from the corresponding field
    // on the site (obviously), and has the bonus of not counting them when
    // counting the number of times a track has been referenced, for use in
    // the "Tracks - by Times Referenced" listing page (or other data
    // processing).
    referencedByTracks: trackReverseReferenceList({
      list: input.value('referencedTracks'),
    }),

    // For the same reasoning, exclude re-releases from sampled tracks too.
    sampledByTracks: trackReverseReferenceList({
      list: input.value('sampledTracks'),
    }),

    featuredInFlashes: reverseReferenceList({
      data: 'flashData',
      list: input.value('featuredTracks'),
    }),
  });

  [inspect.custom](depth) {
    const parts = [];

    parts.push(Thing.prototype[inspect.custom].apply(this));

    if (CacheableObject.getUpdateValue(this, 'originalReleaseTrack')) {
      parts.unshift(`${colors.yellow('[rerelease]')} `);
    }

    let album;
    if (depth >= 0 && (album = this.album ?? this.dataSourceAlbum)) {
      const albumName = album.name;
      const albumIndex = album.tracks.indexOf(this);
      const trackNum =
        (albumIndex === -1
          ? '#?'
          : `#${albumIndex + 1}`);
      parts.push(` (${colors.yellow(trackNum)} in ${colors.green(albumName)})`);
    }

    return parts.join('');
  }
}

// Early exits with a value inherited from the original release, if
// this track is a rerelease, and otherwise continues with no further
// dependencies provided. If allowOverride is true, then the continuation
// will also be called if the original release exposed the requested
// property as null.
export const inheritFromOriginalRelease = templateCompositeFrom({
  annotation: `Track.inheritFromOriginalRelease`,

  inputs: {
    property: input({type: 'string'}),
    allowOverride: input({type: 'boolean', defaultValue: false}),
  },

  steps: () => [
    withOriginalRelease(),

    {
      dependencies: [
        '#originalRelease',
        input('property'),
        input('allowOverride'),
      ],

      compute: (continuation, {
        ['#originalRelease']: originalRelease,
        [input('property')]: originalProperty,
        [input('allowOverride')]: allowOverride,
      }) => {
        if (!originalRelease) return continuation();

        const value = originalRelease[originalProperty];
        if (allowOverride && value === null) return continuation();

        return continuation.exit(value);
      },
    },
  ],
});

// Gets the track's album. This will early exit if albumData is missing.
// By default, if there's no album whose list of tracks includes this track,
// the output dependency will be null; set {notFoundMode: 'exit'} to early
// exit instead.
export const withAlbum = templateCompositeFrom({
  annotation: `Track.withAlbum`,

  inputs: {
    notFoundMode: input({
      validate: oneOf('exit', 'null'),
      defaultValue: 'null',
    }),
  },

  outputs: ['#album'],

  steps: () => [
    raiseOutputWithoutDependency({
      dependency: 'albumData',
      mode: input.value('empty'),
      output: input.value({
        ['#album']: null,
      }),
    }),

    {
      dependencies: [input.myself(), 'albumData'],
      compute: (continuation, {
        [input.myself()]: track,
        ['albumData']: albumData,
      }) =>
        continuation({
          ['#album']:
            albumData.find(album => album.tracks.includes(track)),
        }),
    },

    raiseOutputWithoutDependency({
      dependency: '#album',
      output: input.value({
        ['#album']: null,
      }),
    }),

    {
      dependencies: ['#album'],
      compute: (continuation, {'#album': album}) =>
        continuation.raiseOutput({'#album': album}),
    },
  ],
});

// Gets a single property from this track's album, providing it as the same
// property name prefixed with '#album.' (by default). If the track's album
// isn't available, then by default, the property will be provided as null;
// set {notFoundMode: 'exit'} to early exit instead.
export const withPropertyFromAlbum = templateCompositeFrom({
  annotation: `withPropertyFromAlbum`,

  inputs: {
    property: input.staticValue({type: 'string'}),

    notFoundMode: input({
      validate: oneOf('exit', 'null'),
      defaultValue: 'null',
    }),
  },

  outputs: ({
    [input.staticValue('property')]: property,
  }) => ['#album.' + property],

  steps: () => [
    withAlbum({
      notFoundMode: input('notFoundMode'),
    }),

    withPropertyFromObject({
      object: '#album',
      property: input('property'),
    }),

    {
      dependencies: ['#value', input.staticValue('property')],
      compute: (continuation, {
        ['#value']: value,
        [input.staticValue('property')]: property,
      }) => continuation({
        ['#album.' + property]: value,
      }),
    },
  ],
});

// Gets the track section containing this track from its album's track list.
// If notFoundMode is set to 'exit', this will early exit if the album can't be
// found or if none of its trackSections includes the track for some reason.
export const withContainingTrackSection = templateCompositeFrom({
  annotation: `withContainingTrackSection`,

  inputs: {
    notFoundMode: input({
      validate: oneOf('exit', 'null'),
      defaultValue: 'null',
    }),
  },

  outputs: ['#trackSection'],

  steps: () => [
    withPropertyFromAlbum({
      property: input.value('trackSections'),
      notFoundMode: input('notFoundMode'),
    }),

    {
      dependencies: [
        input.myself(),
        input('notFoundMode'),
        '#album.trackSections',
      ],

      compute(continuation, {
        [input.myself()]: track,
        [input('notFoundMode')]: notFoundMode,
        ['#album.trackSections']: trackSections,
      }) {
        if (!trackSections) {
          return continuation.raiseOutput({
            ['#trackSection']: null,
          });
        }

        const trackSection =
          trackSections.find(({tracks}) => tracks.includes(track));

        if (trackSection) {
          return continuation.raiseOutput({
            ['#trackSection']: trackSection,
          });
        } else if (notFoundMode === 'exit') {
          return continuation.exit(null);
        } else {
          return continuation.raiseOutput({
            ['#trackSection']: null,
          });
        }
      },
    },
  ],
});

// Just includes the original release of this track as a dependency.
// If this track isn't a rerelease, then it'll provide null, unless the
// {selfIfOriginal} option is set, in which case it'll provide this track
// itself. Note that this will early exit if the original release is
// specified by reference and that reference doesn't resolve to anything.
// Outputs to '#originalRelease' by default.
export const withOriginalRelease = templateCompositeFrom({
  annotation: `withOriginalRelease`,

  inputs: {
    selfIfOriginal: input({type: 'boolean', defaultValue: false}),

    // todo: validate
    data: input({defaultDependency: 'trackData'}),
  },

  outputs: ['#originalRelease'],

  steps: () => [
    withResolvedReference({
      ref: 'originalReleaseTrack',
      data: input('data'),
      find: input.value(find.track),
      notFoundMode: input.value('exit'),
    }).outputs({
      ['#resolvedReference']: '#originalRelease',
    }),

    {
      dependencies: [
        input.myself(),
        input('selfIfOriginal'),
        '#originalRelease',
      ],

      compute: (continuation, {
        [input.myself()]: track,
        [input('selfIfOriginal')]: selfIfOriginal,
        ['#originalRelease']: originalRelease,
      }) =>
        continuation({
          ['#originalRelease']:
            (originalRelease ??
              (selfIfOriginal
                ? track
                : null)),
        }),
    },
  ],
});

// The algorithm for checking if a track has unique cover art is used in a
// couple places, so it's defined in full as a compositional step.
export const withHasUniqueCoverArt = templateCompositeFrom({
  annotation: 'withHasUniqueCoverArt',

  outputs: ['#hasUniqueCoverArt'],

  steps: () => [
    {
      dependencies: ['disableUniqueCoverArt'],
      compute: (continuation, {disableUniqueCoverArt}) =>
        (disableUniqueCoverArt
          ? continuation.raiseOutput({into: false})
          : continuation()),
    },

    withResolvedContribs({from: 'coverArtistContribs'}),

    {
      dependencies: ['#resolvedContribs'],
      compute: (continuation, {
        ['#resolvedContribs']: contribsFromTrack,
      }) =>
        (empty(contribsFromTrack)
          ? continuation()
          : continuation.raiseOutput({
              ['#hasUniqueCoverArt']:
                true,
            })),
    },

    withPropertyFromAlbum({
      property: input.value('trackCoverArtistContribs'),
    }),

    {
      dependencies: ['#album.trackCoverArtistContribs'],
      compute: (continuation, {
        ['#album.trackCoverArtistContribs']: contribsFromAlbum,
      }) =>
        continuation.raiseOutput({
          ['#hasUniqueCoverArt']:
            !empty(contribsFromAlbum),
        }),
    },
  ],
});

// Shorthand for checking if the track has unique cover art and exposing a
// fallback value if it isn't.
export const exitWithoutUniqueCoverArt = templateCompositeFrom({
  annotation: `exitWithoutUniqueCoverArt`,

  inputs: {
    value: input({null: true}),
  },

  steps: () => [
    withHasUniqueCoverArt(),

    exitWithoutDependency({
      dependency: '#hasUniqueCoverArt',
      mode: input.value('falsy'),
      value: input('value'),
    }),
  ],
});

export const trackReverseReferenceList = templateCompositeFrom({
  annotation: `trackReverseReferenceList`,

  compose: false,

  inputs: {
    list: input({type: 'string'}),
  },

  steps: () => [
    withReverseReferenceList({
      data: 'trackData',
      list: input('list'),
    }),

    {
      flags: {expose: true},
      expose: {
        dependencies: ['#reverseReferenceList'],
        compute: ({
          ['#reverseReferenceList']: reverseReferenceList,
        }) =>
          reverseReferenceList.filter(track => !track.originalReleaseTrack),
      },
    },
  ],
});