« get me outta code hell

things.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things.js
blob: b5d6f1099feedba31832bd26a2d9a7b99393dd33 (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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// things.js: class definitions for various object types used across the wiki,
// most of which correspond to an output page, such as Track, Album, Artist

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

import {
    isBoolean,
    isColor,
    isCommentary,
    isCountingNumber,
    isContributionList,
    isDate,
    isDimensions,
    isDirectory,
    isDuration,
    isInstance,
    isFileExtension,
    isLanguageCode,
    isName,
    isNumber,
    isURL,
    isString,
    oneOf,
    validateArrayItems,
    validateInstanceOf,
    validateReference,
    validateReferenceList,
} from './validators.js';

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

import find from '../util/find.js';

// Stub classes (and their exports) at the top of the file - these are
// referenced later when we actually define static class fields. We deliberately
// define the classes and set their static fields in two separate steps so that
// every class coexists from the outset, and can be directly referenced in field
// definitions later.

// This list also acts as a quick table of contents for this JS file - use
// ctrl+F or similar to skip to a section.

// -> Thing
export class Thing extends CacheableObject {}

// -> Album
export class Album extends Thing {}
export class TrackGroup extends CacheableObject {}

// -> Track
export class Track extends Thing {}

// -> Artist
export class Artist extends Thing {}

// -> Group
export class Group extends Thing {}
export class GroupCategory extends CacheableObject {}

// -> ArtTag
export class ArtTag extends Thing {}

// -> NewsEntry
export class NewsEntry extends Thing {}

// -> StaticPage
export class StaticPage extends Thing {}

// -> HomepageLayout
export class HomepageLayout extends CacheableObject {}
export class HomepageLayoutRow extends CacheableObject {}
export class HomepageLayoutAlbumsRow extends HomepageLayoutRow {}

// -> Flash
export class Flash extends Thing {}
export class FlashAct extends CacheableObject {}

// -> WikiInfo
export class WikiInfo extends CacheableObject {}

// Before initializing property descriptors, set additional independent
// constants on the classes (which are referenced later).

Thing.referenceType = Symbol('Thing.referenceType');

Album[Thing.referenceType] = 'album';
Track[Thing.referenceType] = 'track';
Artist[Thing.referenceType] = 'artist';
Group[Thing.referenceType] = 'group';
ArtTag[Thing.referenceType] = 'tag';
NewsEntry[Thing.referenceType] = 'news-entry';
StaticPage[Thing.referenceType] = 'static';
Flash[Thing.referenceType] = 'flash';

// -> Thing: base class for wiki data types, providing wiki-specific utility
// functions on top of essential CacheableObject behavior.

// Regularly reused property descriptors, for ease of access and generally
// duplicating less code across wiki data types. These are specialized utility
// functions, so check each for how its own arguments behave!
Thing.common = {
    name: (defaultName) => ({
        flags: {update: true, expose: true},
        update: {validate: isName, default: defaultName}
    }),

    color: () => ({
        flags: {update: true, expose: true},
        update: {validate: isColor}
    }),

    directory: () => ({
        flags: {update: true, expose: true},
        update: {validate: isDirectory},
        expose: {
            dependencies: ['name'],
            transform(directory, { name }) {
                if (directory === null && name === null)
                    return null;
                else if (directory === null)
                    return getKebabCase(name);
                else
                    return directory;
            }
        }
    }),

    urls: () => ({
        flags: {update: true, expose: true},
        update: {validate: validateArrayItems(isURL)}
    }),

    // Straightforward flag descriptor for a variety of property purposes.
    // Provide a default value, true or false!
    flag: (defaultValue = false) => {
        if (typeof defaultValue !== 'boolean') {
            throw new TypeError(`Always set explicit defaults for flags!`);
        }

        return {
            flags: {update: true, expose: true},
            update: {validate: isBoolean, default: defaultValue}
        };
    },

    // General date type, used as the descriptor for a bunch of properties.
    // This isn't dynamic though - it won't inherit from a date stored on
    // another object, for example.
    simpleDate: () => ({
        flags: {update: true, expose: true},
        update: {validate: isDate}
    }),

    // General string type. This should probably generally be avoided in favor
    // of more specific validation, but using it makes it easy to find where we
    // might want to improve later, and it's a useful shorthand meanwhile.
    simpleString: () => ({
        flags: {update: true, expose: true},
        update: {validate: isString}
    }),

    // Super simple "contributions by reference" list, used for a variety of
    // properties (Artists, Cover Artists, etc). This is the property which is
    // externally provided, in the form:
    //
    //     [
    //         {who: 'Artist Name', what: 'Viola'},
    //         {who: 'artist:john-cena', what: null},
    //         ...
    //     ]
    //
    // ...processed from YAML, spreadsheet, or any other kind of input.
    contribsByRef: () => ({
        flags: {update: true, expose: true},
        update: {validate: isContributionList}
    }),

    // A reference list! Keep in mind this is for general references to wiki
    // objects of (usually) other Thing subclasses, not specifically leitmotif
    // references in tracks (although that property uses referenceList too!).
    //
    // The underlying function validateReferenceList expects a string like
    // 'artist' or 'track', but this utility keeps from having to hard-code the
    // string in multiple places by referencing the value saved on the class
    // instead.
    referenceList: thingClass => {
        const { [Thing.referenceType]: referenceType } = thingClass;
        if (!referenceType) {
            throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
        }

        return {
            flags: {update: true, expose: true},
            update: {validate: validateReferenceList(referenceType)}
        };
    },

    // Corresponding function for a single reference.
    singleReference: thingClass => {
        const { [Thing.referenceType]: referenceType } = thingClass;
        if (!referenceType) {
            throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
        }

        return {
            flags: {update: true, expose: true},
            update: {validate: validateReference(referenceType)}
        };
    },

    // Corresponding dynamic property to contribsByRef, which takes the values
    // in the provided property and searches the object's artistData for
    // matching actual Artist objects. The computed structure has the same form
    // as contribsByRef, but with Artist objects instead of string references:
    //
    //     [
    //         {who: (an Artist), what: 'Viola'},
    //         {who: (an Artist), what: null},
    //         ...
    //     ]
    //
    // Contributions whose "who" values don't match anything in artistData are
    // filtered out. (So if the list is all empty, chances are that either the
    // reference list is somehow messed up, or artistData isn't being provided
    // properly.)
    dynamicContribs: (contribsByRefProperty) => ({
        flags: {expose: true},
        expose: {
            dependencies: ['artistData', contribsByRefProperty],
            compute: ({ artistData, [contribsByRefProperty]: contribsByRef }) => (
                (contribsByRef && artistData
                    ? (contribsByRef
                        .map(({ who: ref, what }) => ({
                            who: find.artist(ref, {wikiData: {artistData}}),
                            what
                        }))
                        .filter(({ who }) => who))
                    : [])
            )
        }
    }),

    // General purpose wiki data constructor, for properties like artistData,
    // trackData, etc.
    wikiData: (thingClass) => ({
        flags: {update: true},
        update: {
            validate: validateArrayItems(validateInstanceOf(thingClass))
        }
    })
};

Thing.getReference = function(thing) {
    if (!thing.constructor[Thing.referenceType])
        throw TypeError(`Passed Thing is ${thing.constructor.name}, which provides no [Thing.referenceType]`);

    if (!thing.directory)
        throw TypeError(`Passed ${thing.constructor.name} is missing its directory`);

    return `${thing.constructor[Thing.referenceType]}:${thing.directory}`;
};

// -> Album

Album.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Album'),
    color: Thing.common.color(),
    directory: Thing.common.directory(),
    urls: Thing.common.urls(),

    date: Thing.common.simpleDate(),
    coverArtDate: Thing.common.simpleDate(),
    trackArtDate: Thing.common.simpleDate(),
    dateAddedToWiki: Thing.common.simpleDate(),

    artistContribsByRef: Thing.common.contribsByRef(),
    coverArtistContribsByRef: Thing.common.contribsByRef(),
    trackCoverArtistContribsByRef: Thing.common.contribsByRef(),
    wallpaperArtistContribsByRef: Thing.common.contribsByRef(),
    bannerArtistContribsByRef: Thing.common.contribsByRef(),

    groupsByRef: Thing.common.referenceList(Group),
    artTagsByRef: Thing.common.referenceList(ArtTag),

    trackGroups: {
        flags: {update: true, expose: true},

        update: {
            validate: validateArrayItems(validateInstanceOf(TrackGroup))
        }
    },

    wallpaperStyle: Thing.common.simpleString(),

    wallpaperFileExtension: {
        flags: {update: true, expose: true},
        update: {validate: isFileExtension}
    },

    bannerStyle: Thing.common.simpleString(),

    bannerFileExtension: {
        flags: {update: true, expose: true},
        update: {validate: isFileExtension}
    },

    bannerDimensions: {
        flags: {update: true, expose: true},
        update: {validate: isDimensions}
    },

    hasTrackArt: Thing.common.flag(true),
    isMajorRelease: Thing.common.flag(false),
    isListedOnHomepage: Thing.common.flag(true),

    commentary: {
        flags: {update: true, expose: true},
        update: {validate: isCommentary}
    },

    // Update only

    artistData: Thing.common.wikiData(Artist),
    trackData: Thing.common.wikiData(Track),

    // Expose only

    // Previously known as: (album).artists
    artistContribs: Thing.common.dynamicContribs('artistContribsByRef'),

    tracks: {
        flags: {expose: true},

        expose: {
            dependencies: ['trackGroups', 'trackData'],
            compute: ({ trackGroups, trackData }) => (
                (trackGroups && trackData
                    ? (trackGroups
                        .flatMap(group => group.tracksByRef ?? [])
                        .map(ref => find.track(ref, {wikiData: {trackData}}))
                        .filter(Boolean))
                    : [])
            )
        }
    },
};

TrackGroup.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Track Group'),
    color: Thing.common.color(),

    dateOriginallyReleased: Thing.common.simpleDate(),

    tracksByRef: Thing.common.referenceList(Track),

    isDefaultTrackGroup: Thing.common.flag(false),

    // Update only

    trackData: Thing.common.wikiData(Track),

    // Expose only

    tracks: {
        flags: {expose: true},

        expose: {
            dependencies: ['tracksByRef', 'trackData'],
            compute: ({ tracksByRef, trackData }) => (
                (tracksByRef && trackData
                    ? (tracksByRef
                        .map(ref => find.track(ref, {wikiData: {trackData}}))
                        .filter(Boolean))
                    : [])
            )
        }
    },
};

// -> Track

Track.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Track'),
    directory: Thing.common.directory(),

    duration: {
        flags: {update: true, expose: true},
        update: {validate: isDuration}
    },

    urls: Thing.common.urls(),
    dateFirstReleased: Thing.common.simpleDate(),
    coverArtDate: Thing.common.simpleDate(),

    hasCoverArt: Thing.common.flag(true),
    hasURLs: Thing.common.flag(true),

    referencedTracksByRef: Thing.common.referenceList(Track),
    artTagsByRef: Thing.common.referenceList(ArtTag),

    artistContribsByRef: Thing.common.contribsByRef(),
    contributorContribsByRef: Thing.common.contribsByRef(),
    coverArtistContribsByRef: Thing.common.contribsByRef(),

    // Previously known as: (track).aka
    originalReleaseTrackByRef: Thing.common.singleReference(Track),

    commentary: {
        flags: {update: true, expose: true},
        update: {validate: isCommentary}
    },

    lyrics: Thing.common.simpleString(),

    // Update only

    albumData: Thing.common.wikiData(Album),
    artistData: Thing.common.wikiData(Artist),
    artTagData: Thing.common.wikiData(ArtTag),

    // Expose only

    album: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData'],
            compute: ({ [Track.instance]: track, albumData }) => (
                albumData?.find(album => album.tracks.includes(track)) ?? null)
        }
    },

    date: {
        flags: {expose: true},

        expose: {
            dependencies: ['albumData', 'dateFirstReleased'],
            compute: ({ albumData, dateFirstReleased, [Track.instance]: track }) => (
                dateFirstReleased ??
                albumData?.find(album => album.tracks.includes(track))?.date ??
                null
            )
        }
    },

    // Previously known as: (track).artists
    artistContribs: Thing.common.dynamicContribs('artistContribsByRef'),

    artTags: {
        flags: {expose: true},

        expose: {
            dependencies: ['artTagsByRef', 'artTagData'],

            compute: ({ artTagsByRef, artTagData }) => (
                (artTagsByRef && artTagData
                    ? (artTagsByRef
                        .map(ref => find.tag(ref, {wikiData: {tagData: artTagData}}))
                        .filter(Boolean))
                    : [])
            )
        }
    }
};

// -> Artist

Artist.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Artist'),
    directory: Thing.common.directory(),
    urls: Thing.common.urls(),
    contextNotes: Thing.common.simpleString(),

    aliasRefs: Thing.common.referenceList(Artist),
};

// -> Group

Group.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Group'),
    directory: Thing.common.directory(),

    description: Thing.common.simpleString(),

    urls: Thing.common.urls(),

    // Expose only

    descriptionShort: {
        flags: {expose: true},

        expose: {
            dependencies: ['description'],
            compute: ({ description }) => description.split('<hr class="split">')[0]
        }
    }
};

GroupCategory.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Group Category'),
    color: Thing.common.color(),

    groupsByRef: Thing.common.referenceList(Group),
};

// -> ArtTag

ArtTag.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Art Tag'),
    directory: Thing.common.directory(),
    color: Thing.common.color(),
    isContentWarning: Thing.common.flag(false),
};

// -> NewsEntry

NewsEntry.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed News Entry'),
    directory: Thing.common.directory(),
    date: Thing.common.simpleDate(),

    content: Thing.common.simpleString(),

    // Expose only

    contentShort: {
        flags: {expose: true},

        expose: {
            dependencies: ['content'],

            compute({ content }) {
                return body.split('<hr class="split">')[0];
            }
        }
    },
};

// -> StaticPage

StaticPage.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Static Page'),

    nameShort: {
        flags: {update: true, expose: true},
        update: {validate: isName},

        expose: {
            dependencies: ['name'],
            transform: (value, { name }) => value ?? name
        }
    },

    directory: Thing.common.directory(),
    content: Thing.common.simpleString(),
    stylesheet: Thing.common.simpleString(),
    showInNavigationBar: Thing.common.flag(true),
};

// -> HomepageLayout

HomepageLayout.propertyDescriptors = {
    // Update & expose

    sidebarContent: Thing.common.simpleString(),

    rows: {
        flags: {update: true, expose: true},

        update: {
            validate: validateArrayItems(validateInstanceOf(HomepageLayoutRow))
        }
    },
};

HomepageLayoutRow.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Homepage Row'),

    type: {
        flags: {update: true, expose: true},

        update: {
            validate(value) {
                throw new Error(`'type' property validator must be overridden`);
            }
        }
    },

    color: Thing.common.color(),
};

HomepageLayoutAlbumsRow.propertyDescriptors = {
    ...HomepageLayoutRow.propertyDescriptors,

    // Update & expose

    type: {
        flags: {update: true, expose: true},
        update: {
            validate(value) {
                if (value !== 'albums') {
                    throw new TypeError(`Expected 'albums'`);
                }

                return true;
            }
        }
    },

    sourceGroupByRef: Thing.common.singleReference(Group),
    sourceAlbumsByRef: Thing.common.referenceList(Album),

    countAlbumsFromGroup: {
        flags: {update: true, expose: true},
        update: {validate: isCountingNumber}
    },

    actionLinks: {
        flags: {update: true, expose: true},
        update: {validate: validateArrayItems(isString)}
    },
};

// -> Flash

Flash.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Flash'),

    directory: {
        flags: {update: true, expose: true},
        update: {validate: isDirectory},

        // Flashes expose directory differently from other Things! Their
        // default directory is dependent on the page number (or ID), not
        // the name.
        expose: {
            dependencies: ['page'],
            transform(directory, { page }) {
                if (directory === null && page === null)
                    return null;
                else if (directory === null)
                    return page;
                else
                    return directory;
            }
        }
    },

    page: {
        flags: {update: true, expose: true},
        update: {validate: oneOf(isString, isNumber)},

        expose: {
            transform: value => value.toString()
        }
    },

    date: Thing.common.simpleDate(),

    coverArtFileExtension: {
        flags: {update: true, expose: true},
        update: {validate: isFileExtension}
    },

    featuredTracksByRef: Thing.common.referenceList(Track),

    contributorContribsByRef: Thing.common.contribsByRef(),

    urls: Thing.common.urls(),
};

FlashAct.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Flash Act'),
    color: Thing.common.color(),
    anchor: Thing.common.simpleString(),
    jump: Thing.common.simpleString(),
    jumpColor: Thing.common.color(),

    flashesByRef: Thing.common.referenceList(Flash),
};

// WikiInfo

WikiInfo.propertyDescriptors = {
    // Update & expose

    name: Thing.common.name('Unnamed Wiki'),

    // Displayed in nav bar.
    shortName: {
        flags: {update: true, expose: true},
        update: {validate: isName},

        expose: {
            dependencies: ['name'],
            transform: (value, { name }) => value ?? name
        }
    },

    color: Thing.common.color(),

    // One-line description used for <meta rel="description"> tag.
    description: Thing.common.simpleString(),

    footerContent: Thing.common.simpleString(),

    defaultLanguage: {
        flags: {update: true, expose: true},
        update: {validate: isLanguageCode}
    },

    canonicalBase: {
        flags: {update: true, expose: true},
        update: {validate: isURL}
    },

    // Feature toggles

    enableArtistAvatars: Thing.common.flag(false),
    enableFlashesAndGames: Thing.common.flag(false),
    enableListings: Thing.common.flag(false),
    enableNews: Thing.common.flag(false),
    enableArtTagUI: Thing.common.flag(false),
    enableGroupUI: Thing.common.flag(false),
};