diff options
Diffstat (limited to 'src/data/things')
| -rw-r--r-- | src/data/things/additional-file.js | 13 | ||||
| -rw-r--r-- | src/data/things/additional-name.js | 14 | ||||
| -rw-r--r-- | src/data/things/album.js | 897 | ||||
| -rw-r--r-- | src/data/things/art-tag.js | 100 | ||||
| -rw-r--r-- | src/data/things/artist.js | 191 | ||||
| -rw-r--r-- | src/data/things/artwork.js | 274 | ||||
| -rw-r--r-- | src/data/things/content.js | 223 | ||||
| -rw-r--r-- | src/data/things/contribution.js | 239 | ||||
| -rw-r--r-- | src/data/things/flash.js | 210 | ||||
| -rw-r--r-- | src/data/things/group.js | 160 | ||||
| -rw-r--r-- | src/data/things/homepage-layout.js | 77 | ||||
| -rw-r--r-- | src/data/things/index.js | 96 | ||||
| -rw-r--r-- | src/data/things/language.js | 234 | ||||
| -rw-r--r-- | src/data/things/news-entry.js | 9 | ||||
| -rw-r--r-- | src/data/things/sorting-rule.js | 36 | ||||
| -rw-r--r-- | src/data/things/static-page.js | 13 | ||||
| -rw-r--r-- | src/data/things/track.js | 1089 | ||||
| -rw-r--r-- | src/data/things/wiki-info.js | 109 |
18 files changed, 2504 insertions, 1480 deletions
diff --git a/src/data/things/additional-file.js b/src/data/things/additional-file.js index 2ddc688a..b15f62e0 100644 --- a/src/data/things/additional-file.js +++ b/src/data/things/additional-file.js @@ -2,13 +2,12 @@ import {input} from '#composite'; import Thing from '#thing'; import {isString, validateArrayItems} from '#validators'; -import {contentString, simpleString, thing} from '#composite/wiki-properties'; - import {exposeConstant, exposeUpdateValueOrContinue} from '#composite/control-flow'; +import {contentString, simpleString, thing} from '#composite/wiki-properties'; export class AdditionalFile extends Thing { - static [Thing.getPropertyDescriptors] = ({}) => ({ + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose thing: thing(), @@ -26,6 +25,14 @@ export class AdditionalFile extends Thing { value: input.value([]), }), ], + + // Expose only + + isAdditionalFile: [ + exposeConstant({ + value: input.value(true), + }), + ], }); static [Thing.yamlDocumentSpec] = { diff --git a/src/data/things/additional-name.js b/src/data/things/additional-name.js index b96fcd50..99f3ee46 100644 --- a/src/data/things/additional-name.js +++ b/src/data/things/additional-name.js @@ -1,15 +1,25 @@ +import {input} from '#composite'; import Thing from '#thing'; -import {contentString, simpleString, thing} from '#composite/wiki-properties'; +import {exposeConstant} from '#composite/control-flow'; +import {contentString, thing} from '#composite/wiki-properties'; export class AdditionalName extends Thing { - static [Thing.getPropertyDescriptors] = ({}) => ({ + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose thing: thing(), name: contentString(), annotation: contentString(), + + // Expose only + + isAdditionalName: [ + exposeConstant({ + value: input.value(true), + }), + ], }); static [Thing.yamlDocumentSpec] = { diff --git a/src/data/things/album.js b/src/data/things/album.js index 7a7b387d..31d94ef1 100644 --- a/src/data/things/album.js +++ b/src/data/things/album.js @@ -3,14 +3,22 @@ export const DATA_ALBUM_DIRECTORY = 'album'; import * as path from 'node:path'; import {inspect} from 'node:util'; -import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; +import {input, V} from '#composite'; import {traverse} from '#node-utils'; import {sortAlbumsTracksChronologically, sortChronologically} from '#sort'; -import {accumulateSum, empty} from '#sugar'; +import {empty} from '#sugar'; import Thing from '#thing'; -import {isColor, isDate, isDirectory, isNumber} from '#validators'; + +import { + is, + isBoolean, + isColor, + isContributionList, + isDate, + isDirectory, + isNumber, +} from '#validators'; import { parseAdditionalFiles, @@ -25,29 +33,40 @@ import { parseWallpaperParts, } from '#yaml'; -import {exitWithoutDependency, exposeDependency, exposeUpdateValueOrContinue} - from '#composite/control-flow'; -import {withPropertyFromObject} from '#composite/data'; - -import {exitWithoutContribs, withDirectory, withCoverArtDate} +import {withRecontextualizedContributionList, withResolvedContribs} from '#composite/wiki-data'; import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; + +import { + withFlattenedList, + withLengthOfList, + withNearbyItemFromList, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; + +import { color, commentatorArtists, constitutibleArtwork, constitutibleArtworkList, contentString, - contribsPresent, contributionList, dimensions, directory, fileExtension, flag, + hasArtwork, name, referencedArtworkList, referenceList, - reverseReferenceList, simpleDate, simpleString, soupyFind, @@ -59,12 +78,15 @@ import { wikiData, } from '#composite/wiki-properties'; -import {withHasCoverArt, withTracks} from '#composite/things/album'; -import {withAlbum, withContinueCountingFrom, withStartCountingFrom} - from '#composite/things/track-section'; - export class Album extends Thing { static [Thing.referenceType] = 'album'; + static [Thing.wikiData] = 'albumData'; + + static [Thing.constitutibleProperties] = [ + 'coverArtworks', + 'wallpaperArtwork', + 'bannerArtwork', + ]; static [Thing.getPropertyDescriptors] = ({ AdditionalFile, @@ -74,13 +96,16 @@ export class Album extends Thing { CommentaryEntry, CreditingSourcesEntry, Group, - Track, TrackSection, WikiInfo, }) => ({ - // Update & expose + // > Update & expose - Internal relationships + + trackSections: thingList(V(TrackSection)), - name: name('Unnamed Album'), + // > Update & expose - Identifying metadata + + name: name(V('Unnamed Album')), directory: directory(), directorySuffix: [ @@ -88,156 +113,143 @@ export class Album extends Thing { validate: input.value(isDirectory), }), - withDirectory(), - - exposeDependency({ - dependency: '#directory', - }), + exposeDependency('directory'), ], - alwaysReferenceByDirectory: flag(false), - alwaysReferenceTracksByDirectory: flag(false), - suffixTrackDirectories: flag(false), + alwaysReferenceByDirectory: flag(V(false)), + alwaysReferenceTracksByDirectory: flag(V(false)), + suffixTrackDirectories: flag(V(false)), - color: color(), - urls: urls(), + style: [ + exposeUpdateValueOrContinue({ + validate: input.value(is(...[ + 'album', + 'single', + ])), + }), - additionalNames: thingList({ - class: input.value(AdditionalName), - }), + exposeConstant(V('album')), + ], bandcampAlbumIdentifier: simpleString(), bandcampArtworkIdentifier: simpleString(), + additionalNames: thingList(V(AdditionalName)), + date: simpleDate(), - trackArtDate: simpleDate(), dateAddedToWiki: simpleDate(), - coverArtDate: [ - withCoverArtDate({ - from: input.updateValue({ - validate: isDate, - }), + // > Update & expose - Credits and contributors + + artistContribs: contributionList({ + artistProperty: input.value('albumArtistContributions'), + }), + + trackArtistText: contentString(), + + trackArtistContribs: [ + withResolvedContribs({ + from: input.updateValue({validate: isContributionList}), + thingProperty: input.thisProperty(), + artistProperty: input.value('albumTrackArtistContributions'), + }).outputs({ + '#resolvedContribs': '#trackArtistContribs', }), - exposeDependency({dependency: '#coverArtDate'}), - ], + exposeDependencyOrContinue('#trackArtistContribs', V('empty')), - coverArtFileExtension: [ - exitWithoutContribs({contribs: 'coverArtistContribs'}), - fileExtension('jpg'), + withRecontextualizedContributionList('artistContribs', { + artistProperty: input.value('albumTrackArtistContributions'), + }), + + exposeDependency('#artistContribs'), ], - trackCoverArtFileExtension: fileExtension('jpg'), + // > Update & expose - General configuration - wallpaperFileExtension: [ - exitWithoutContribs({contribs: 'wallpaperArtistContribs'}), - fileExtension('jpg'), - ], + countTracksInArtistTotals: flag(V(true)), - bannerFileExtension: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - fileExtension('jpg'), - ], + showAlbumInTracksWithoutArtists: flag(V(false)), - wallpaperStyle: [ - exitWithoutContribs({contribs: 'wallpaperArtistContribs'}), - simpleString(), - ], + hasTrackNumbers: flag(V(true)), + isListedOnHomepage: flag(V(true)), + isListedInGalleries: flag(V(true)), - wallpaperParts: [ - exitWithoutContribs({ - contribs: 'wallpaperArtistContribs', + hideDuration: flag(V(false)), + + // > Update & expose - General metadata + + color: color(), + + urls: urls(), + + // > Update & expose - Artworks + + coverArtworks: [ + exitWithoutDependency('hasCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), - wallpaperParts(), + constitutibleArtworkList.fromYAMLFieldSpec + .call(this, 'Cover Artwork'), ], - bannerStyle: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - simpleString(), - ], + coverArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumCoverArtistContributions'), + }), - coverArtDimensions: [ - exitWithoutContribs({contribs: 'coverArtistContribs'}), - dimensions(), - ], + coverArtDate: [ + exitWithoutDependency('hasCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), - trackDimensions: dimensions(), + exposeUpdateValueOrContinue({ + validate: input.value(isDate), + }), - bannerDimensions: [ - exitWithoutContribs({contribs: 'bannerArtistContribs'}), - dimensions(), + exposeDependency('date'), ], - wallpaperArtwork: [ - exitWithoutDependency({ - dependency: 'wallpaperArtistContribs', - mode: input.value('empty'), + coverArtFileExtension: [ + exitWithoutDependency('hasCoverArt', { value: input.value(null), + mode: input.value('falsy'), }), - constitutibleArtwork.fromYAMLFieldSpec - .call(this, 'Wallpaper Artwork'), + fileExtension(V('jpg')), ], - bannerArtwork: [ - exitWithoutDependency({ - dependency: 'bannerArtistContribs', - mode: input.value('empty'), + coverArtDimensions: [ + exitWithoutDependency('hasCoverArt', { value: input.value(null), + mode: input.value('falsy'), }), - constitutibleArtwork.fromYAMLFieldSpec - .call(this, 'Banner Artwork'), + dimensions(), ], - coverArtworks: [ - withHasCoverArt(), - - exitWithoutDependency({ - dependency: '#hasCoverArt', - mode: input.value('falsy'), + artTags: [ + exitWithoutDependency('hasCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), - constitutibleArtworkList.fromYAMLFieldSpec - .call(this, 'Cover Artwork'), + referenceList({ + class: input.value(ArtTag), + find: soupyFind.input('artTag'), + }), ], - hasTrackNumbers: flag(true), - isListedOnHomepage: flag(true), - isListedInGalleries: flag(true), - - commentary: thingList({ - class: input.value(CommentaryEntry), - }), - - creditSources: thingList({ - class: input.value(CreditingSourcesEntry), - }), - - additionalFiles: thingList({ - class: input.value(AdditionalFile), - }), - - trackSections: thingList({ - class: input.value(TrackSection), - }), - - artistContribs: contributionList({ - date: 'date', - artistProperty: input.value('albumArtistContributions'), - }), - - coverArtistContribs: [ - withCoverArtDate(), - - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumCoverArtistContributions'), + referencedArtworks: [ + exitWithoutDependency('hasCoverArt', { + value: input.value([]), + mode: input.value('falsy'), }), + + referencedArtworkList(), ], trackCoverArtistContribs: contributionList({ @@ -250,80 +262,150 @@ export class Album extends Thing { artistProperty: input.value('trackCoverArtistContributions'), }), - wallpaperArtistContribs: [ - withCoverArtDate(), + trackArtDate: simpleDate(), + + trackCoverArtFileExtension: fileExtension(V('jpg')), - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumWallpaperArtistContributions'), + trackDimensions: dimensions(), + + wallpaperArtwork: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Wallpaper Artwork'), ], - bannerArtistContribs: [ - withCoverArtDate(), + wallpaperArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumWallpaperArtistContributions'), + }), - contributionList({ - date: '#coverArtDate', - artistProperty: input.value('albumBannerArtistContributions'), + wallpaperFileExtension: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + fileExtension(V('jpg')), ], - groups: referenceList({ - class: input.value(Group), - find: soupyFind.input('group'), - }), + wallpaperStyle: [ + exitWithoutDependency('hasWallpaperArt', { + value: input.value(null), + mode: input.value('falsy'), + }), - artTags: [ - exitWithoutContribs({ - contribs: 'coverArtistContribs', + simpleString(), + ], + + wallpaperParts: [ + exitWithoutDependency('hasWallpaperArt', { value: input.value([]), + mode: input.value('falsy'), }), - referenceList({ - class: input.value(ArtTag), - find: soupyFind.input('artTag'), + wallpaperParts(), + ], + + bannerArtwork: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), + + constitutibleArtwork.fromYAMLFieldSpec + .call(this, 'Banner Artwork'), ], - referencedArtworks: [ - exitWithoutContribs({ - contribs: 'coverArtistContribs', - value: input.value([]), + bannerArtistContribs: contributionList({ + date: 'coverArtDate', + artistProperty: input.value('albumBannerArtistContributions'), + }), + + bannerFileExtension: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), }), - referencedArtworkList(), + fileExtension(V('jpg')), ], - // Update only + bannerDimensions: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + dimensions(), + ], + + bannerStyle: [ + exitWithoutDependency('hasBannerArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + simpleString(), + ], + + // > Update & expose - Groups + + groups: referenceList({ + class: input.value(Group), + find: soupyFind.input('group'), + }), + + // > Update & expose - Content entries + + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), + + // > Update & expose - Additional files + + additionalFiles: thingList(V(AdditionalFile)), + + // > Update only find: soupyFind(), reverse: soupyReverse(), // used for referencedArtworkList (mixedFind) - artworkData: wikiData({ - class: input.value(Artwork), - }), + artworkData: wikiData(V(Artwork)), // used for withMatchingContributionPresets (indirectly by Contribution) - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + wikiInfo: thing(V(WikiInfo)), - // Expose only + // > Expose only + + isAlbum: exposeConstant(V(true)), commentatorArtists: commentatorArtists(), - hasCoverArt: [ - withHasCoverArt(), - exposeDependency({dependency: '#hasCoverArt'}), - ], + hasCoverArt: hasArtwork({ + contribs: '_coverArtistContribs', + artworks: '_coverArtworks', + }), + + hasWallpaperArt: hasArtwork({ + contribs: '_wallpaperArtistContribs', + artwork: '_wallpaperArtwork', + }), - hasWallpaperArt: contribsPresent({contribs: 'wallpaperArtistContribs'}), - hasBannerArt: contribsPresent({contribs: 'bannerArtistContribs'}), + hasBannerArt: hasArtwork({ + contribs: '_bannerArtistContribs', + artwork: '_bannerArtwork', + }), tracks: [ - withTracks(), - exposeDependency({dependency: '#tracks'}), + exitWithoutDependency('trackSections', V([])), + + withPropertyFromList('trackSections', V('tracks')), + withFlattenedList('#trackSections.tracks'), + exposeDependency('#flattenedList'), ], }); @@ -378,8 +460,22 @@ export class Album extends Thing { bindTo: 'albumData', getMatchableNames: album => - (album.alwaysReferenceByDirectory - ? [] + (album.alwaysReferenceByDirectory + ? [] + : [album.name]), + }, + + albumSinglesOnly: { + referencing: ['album'], + + bindTo: 'albumData', + + incldue: album => + album.style === 'single', + + getMatchableNames: album => + (album.alwaysReferenceByDirectory + ? [] : [album.name]), }, @@ -396,8 +492,8 @@ export class Album extends Thing { album.hasCoverArt, getMatchableNames: album => - (album.alwaysReferenceByDirectory - ? [] + (album.alwaysReferenceByDirectory + ? [] : [album.name]), }, @@ -428,20 +524,6 @@ export class Album extends Thing { }; static [Thing.reverseSpecs] = { - albumsWhoseTracksInclude: { - bindTo: 'albumData', - - referencing: album => [album], - referenced: album => album.tracks, - }, - - albumsWhoseTrackSectionsInclude: { - bindTo: 'albumData', - - referencing: album => [album], - referenced: album => album.trackSections, - }, - albumsWhoseArtworksFeature: { bindTo: 'albumData', @@ -459,6 +541,9 @@ export class Album extends Thing { albumArtistContributionsBy: soupyReverse.contributionsBy('albumData', 'artistContribs'), + albumTrackArtistContributionsBy: + soupyReverse.contributionsBy('albumData', 'trackArtistContribs'), + albumCoverArtistContributionsBy: soupyReverse.artworkContributionsBy('albumData', 'coverArtworks'), @@ -478,21 +563,15 @@ export class Album extends Thing { static [Thing.yamlDocumentSpec] = { fields: { - 'Album': {property: 'name'}, + // Identifying metadata + 'Album': {property: 'name'}, 'Directory': {property: 'directory'}, 'Directory Suffix': {property: 'directorySuffix'}, 'Suffix Track Directories': {property: 'suffixTrackDirectories'}, - 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, - 'Always Reference Tracks By Directory': { - property: 'alwaysReferenceTracksByDirectory', - }, - - 'Additional Names': { - property: 'additionalNames', - transform: parseAdditionalNames, - }, + 'Always Reference Tracks By Directory': {property: 'alwaysReferenceTracksByDirectory'}, + 'Style': {property: 'style'}, 'Bandcamp Album ID': { property: 'bandcampAlbumIdentifier', @@ -504,18 +583,61 @@ export class Album extends Thing { transform: String, }, + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, + 'Date': { property: 'date', transform: parseDate, }, - 'Color': {property: 'color'}, - 'URLs': {property: 'urls'}, + 'Date Added': { + property: 'dateAddedToWiki', + transform: parseDate, + }, + + // Credits and contributors + + 'Artists': { + property: 'artistContribs', + transform: parseContributors, + }, + + 'Track Artist Text': { + property: 'trackArtistText', + }, + + 'Track Artists': { + property: 'trackArtistContribs', + transform: parseContributors, + }, + + // General configuration + + 'Count Tracks In Artist Totals': {property: 'countTracksInArtistTotals'}, + + 'Show Album In Tracks Without Artists': { + property: 'showAlbumInTracksWithoutArtists', + }, 'Has Track Numbers': {property: 'hasTrackNumbers'}, 'Listed on Homepage': {property: 'isListedOnHomepage'}, 'Listed in Galleries': {property: 'isListedInGalleries'}, + 'Hide Duration': {property: 'hideDuration'}, + + // General metadata + + 'Color': {property: 'color'}, + + 'URLs': {property: 'urls'}, + + // Artworks + // (Note - this YAML section is deliberately ordered differently + // than the corresponding property descriptors.) + 'Cover Artwork': { property: 'coverArtworks', transform: @@ -559,27 +681,29 @@ export class Album extends Thing { }), }, + 'Cover Artists': { + property: 'coverArtistContribs', + transform: parseContributors, + }, + 'Cover Art Date': { property: 'coverArtDate', transform: parseDate, }, - 'Default Track Cover Art Date': { - property: 'trackArtDate', - transform: parseDate, + 'Cover Art Dimensions': { + property: 'coverArtDimensions', + transform: parseDimensions, }, - 'Date Added': { - property: 'dateAddedToWiki', - transform: parseDate, + 'Default Track Cover Artists': { + property: 'trackCoverArtistContribs', + transform: parseContributors, }, - 'Cover Art File Extension': {property: 'coverArtFileExtension'}, - 'Track Art File Extension': {property: 'trackCoverArtFileExtension'}, - - 'Cover Art Dimensions': { - property: 'coverArtDimensions', - transform: parseDimensions, + 'Default Track Cover Art Date': { + property: 'trackArtDate', + transform: parseDate, }, 'Default Track Dimensions': { @@ -593,7 +717,6 @@ export class Album extends Thing { }, 'Wallpaper Style': {property: 'wallpaperStyle'}, - 'Wallpaper File Extension': {property: 'wallpaperFileExtension'}, 'Wallpaper Parts': { property: 'wallpaperParts', @@ -605,58 +728,70 @@ export class Album extends Thing { transform: parseContributors, }, - 'Banner Style': {property: 'bannerStyle'}, - 'Banner File Extension': {property: 'bannerFileExtension'}, - 'Banner Dimensions': { property: 'bannerDimensions', transform: parseDimensions, }, - 'Commentary': { - property: 'commentary', - transform: parseCommentary, - }, + 'Banner Style': {property: 'bannerStyle'}, - 'Credit Sources': { - property: 'creditSources', - transform: parseCreditingSources, - }, + 'Cover Art File Extension': {property: 'coverArtFileExtension'}, + 'Track Art File Extension': {property: 'trackCoverArtFileExtension'}, + 'Wallpaper File Extension': {property: 'wallpaperFileExtension'}, + 'Banner File Extension': {property: 'bannerFileExtension'}, - 'Additional Files': { - property: 'additionalFiles', - transform: parseAdditionalFiles, - }, + 'Art Tags': {property: 'artTags'}, 'Referenced Artworks': { property: 'referencedArtworks', transform: parseAnnotatedReferences, }, - 'Franchises': {ignore: true}, + // Groups - 'Artists': { - property: 'artistContribs', - transform: parseContributors, + 'Groups': {property: 'groups'}, + + // Content entries + + 'Commentary': { + property: 'commentary', + transform: parseCommentary, }, - 'Cover Artists': { - property: 'coverArtistContribs', - transform: parseContributors, + 'Crediting Sources': { + property: 'creditingSources', + transform: parseCreditingSources, }, - 'Default Track Cover Artists': { - property: 'trackCoverArtistContribs', - transform: parseContributors, + // Additional files + + 'Additional Files': { + property: 'additionalFiles', + transform: parseAdditionalFiles, }, - 'Groups': {property: 'groups'}, - 'Art Tags': {property: 'artTags'}, + // Shenanigans + 'Franchises': {ignore: true}, 'Review Points': {ignore: true}, }, invalidFieldCombinations: [ + {message: `Move commentary on singles to the track`, fields: [ + ['Style', 'single'], + 'Commentary', + ]}, + + {message: `Move crediting sources on singles to the track`, fields: [ + ['Style', 'single'], + 'Crediting Sources', + ]}, + + {message: `Move additional names on singles to the track`, fields: [ + ['Style', 'single'], + 'Additional Names', + ]}, + {message: `Specify one wallpaper style or multiple wallpaper parts, not both`, fields: [ 'Wallpaper Parts', 'Wallpaper Style', @@ -688,100 +823,48 @@ export class Album extends Thing { ? TrackSection : Track), - save(results) { - const albumData = []; - const trackSectionData = []; - const trackData = []; - - const artworkData = []; - const commentaryData = []; - const creditingSourceData = []; - const lyricsData = []; - - for (const {header: album, entries} of results) { - const trackSections = []; - - let currentTrackSection = new TrackSection(); - let currentTrackSectionTracks = []; - - Object.assign(currentTrackSection, { - name: `Default Track Section`, - isDefaultTrackSection: true, - }); - - const albumRef = Thing.getReference(album); - - const closeCurrentTrackSection = () => { - if ( - currentTrackSection.isDefaultTrackSection && - empty(currentTrackSectionTracks) - ) { - return; - } - - currentTrackSection.tracks = - currentTrackSectionTracks; - - trackSections.push(currentTrackSection); - trackSectionData.push(currentTrackSection); - }; - - for (const entry of entries) { - if (entry instanceof TrackSection) { - closeCurrentTrackSection(); - currentTrackSection = entry; - currentTrackSectionTracks = []; - continue; - } - - currentTrackSectionTracks.push(entry); - trackData.push(entry); - - // Set the track's album before accessing its list of artworks. - // The existence of its artwork objects may depend on access to - // its album's 'Default Track Cover Artists'. - entry.album = album; - - artworkData.push(...entry.trackArtworks); - commentaryData.push(...entry.commentary); - creditingSourceData.push(...entry.creditSources); - - // TODO: As exposed, Track.lyrics tries to inherit from the main - // release, which is impossible before the data's been linked. - // We just use the update value here. But it's icky! - lyricsData.push(...CacheableObject.getUpdateValue(entry, 'lyrics') ?? []); - } - - closeCurrentTrackSection(); + connect({header: album, entries}) { + const trackSections = []; - albumData.push(album); + let currentTrackSection = new TrackSection(); + let currentTrackSectionTracks = []; - artworkData.push(...album.coverArtworks); + Object.assign(currentTrackSection, { + name: `Default Track Section`, + isDefaultTrackSection: true, + }); - if (album.bannerArtwork) { - artworkData.push(album.bannerArtwork); + const closeCurrentTrackSection = () => { + if ( + currentTrackSection.isDefaultTrackSection && + empty(currentTrackSectionTracks) + ) { + return; } - if (album.wallpaperArtwork) { - artworkData.push(album.wallpaperArtwork); + currentTrackSection.tracks = currentTrackSectionTracks; + currentTrackSection.album = album; + + trackSections.push(currentTrackSection); + }; + + for (const entry of entries) { + if (entry instanceof TrackSection) { + closeCurrentTrackSection(); + currentTrackSection = entry; + currentTrackSectionTracks = []; + continue; } - commentaryData.push(...album.commentary); - creditingSourceData.push(...album.creditSources); + entry.album = album; + entry.trackSection = currentTrackSection; - album.trackSections = trackSections; + currentTrackSectionTracks.push(entry); } - return { - albumData, - trackSectionData, - trackData, + closeCurrentTrackSection(); - artworkData, - commentaryData, - creditingSourceData, - lyricsData, - }; + album.trackSections = trackSections; }, sort({albumData, trackData}) { @@ -835,56 +918,120 @@ export class Album extends Thing { artwork.fileExtension, ]; } + + // As of writing, albums don't even have a `duration` property... + // so this function will never be called... but the message stands... + countOwnContributionInDurationTotals(_contrib) { + return false; + } } export class TrackSection extends Thing { static [Thing.friendlyName] = `Track Section`; static [Thing.referenceType] = `track-section`; + static [Thing.wikiData] = 'trackSectionData'; - static [Thing.getPropertyDescriptors] = ({Album, Track}) => ({ + static [Thing.getPropertyDescriptors] = ({Track}) => ({ // Update & expose - name: name('Unnamed Track Section'), + album: thing(V(Album)), + + name: name(V('Unnamed Track Section')), unqualifiedDirectory: directory(), + directorySuffix: [ + exposeUpdateValueOrContinue({ + validate: input.value(isDirectory), + }), + + withPropertyFromObject({ + object: 'album', + property: input.value('directorySuffix'), + }), + + exposeDependency({dependency: '#album.directorySuffix'}), + ], + + suffixTrackDirectories: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withPropertyFromObject({ + object: 'album', + property: input.value('suffixTrackDirectories'), + }), + + exposeDependency({dependency: '#album.suffixTrackDirectories'}), + ], + color: [ exposeUpdateValueOrContinue({ validate: input.value(isColor), }), - withAlbum(), - withPropertyFromObject({ - object: '#album', + object: 'album', property: input.value('color'), }), exposeDependency({dependency: '#album.color'}), ], + hasTrackNumbers: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withPropertyFromObject('album', V('hasTrackNumbers')), + exposeDependency('#album.hasTrackNumbers'), + ], + startCountingFrom: [ - withStartCountingFrom({ - from: input.updateValue({validate: isNumber}), + exposeUpdateValueOrContinue({ + validate: input.value(isNumber), + }), + + withPropertyFromObject('album', V('hasTrackNumbers')), + exitWithoutDependency('#album.hasTrackNumbers', V(1), V('falsy')), + + withPropertyFromObject('album', V('trackSections')), + + withNearbyItemFromList({ + list: '#album.trackSections', + item: input.myself(), + offset: input.value(-1), + }).outputs({ + '#nearbyItem': '#previousTrackSection', }), - exposeDependency({dependency: '#startCountingFrom'}), + exitWithoutDependency('#previousTrackSection', V(1)), + + withPropertyFromObject('#previousTrackSection', V('continueCountingFrom')), + exposeDependency('#previousTrackSection.continueCountingFrom'), ], dateOriginallyReleased: simpleDate(), - isDefaultTrackSection: flag(false), + countTracksInArtistTotals: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), - description: contentString(), + withPropertyFromObject({ + object: 'album', + property: input.value('countTracksInArtistTotals'), + }), - album: [ - withAlbum(), - exposeDependency({dependency: '#album'}), + exposeDependency({dependency: '#album.countTracksInArtistTotals'}), ], - tracks: thingList({ - class: input.value(Track), - }), + isDefaultTrackSection: flag(V(false)), + + description: contentString(), + + tracks: thingList(V(Track)), // Update only @@ -892,38 +1039,51 @@ export class TrackSection extends Thing { // Expose only - directory: [ - withAlbum(), + isTrackSection: [ + exposeConstant({ + value: input.value(true), + }), + ], + directory: [ exitWithoutDependency({ - dependency: '#album', + dependency: 'album', }), withPropertyFromObject({ - object: '#album', + object: 'album', property: input.value('directory'), }), - withDirectory({ - directory: 'unqualifiedDirectory', - }).outputs({ - '#directory': '#unqualifiedDirectory', - }), - { - dependencies: ['#album.directory', '#unqualifiedDirectory'], + dependencies: ['#album.directory', 'unqualifiedDirectory'], compute: ({ ['#album.directory']: albumDirectory, - ['#unqualifiedDirectory']: unqualifiedDirectory, + ['unqualifiedDirectory']: unqualifiedDirectory, }) => albumDirectory + '/' + unqualifiedDirectory, }, ], continueCountingFrom: [ - withContinueCountingFrom(), + withPropertyFromObject('album', V('hasTrackNumbers')), + exitWithoutDependency('#album.hasTrackNumbers', V(null), V('falsy')), - exposeDependency({dependency: '#continueCountingFrom'}), + { + dependencies: ['hasTrackNumbers', 'startCountingFrom'], + compute: (continuation, {hasTrackNumbers, startCountingFrom}) => + (hasTrackNumbers + ? continuation() + : continuation.exit(startCountingFrom)), + }, + + withLengthOfList('tracks'), + + { + dependencies: ['startCountingFrom', '#tracks.length'], + compute: ({startCountingFrom, '#tracks.length': tracks}) => + startCountingFrom + tracks, + }, ], }); @@ -941,19 +1101,14 @@ export class TrackSection extends Thing { }, }; - static [Thing.reverseSpecs] = { - trackSectionsWhichInclude: { - bindTo: 'trackSectionData', - - referencing: trackSection => [trackSection], - referenced: trackSection => trackSection.tracks, - }, - }; - static [Thing.yamlDocumentSpec] = { fields: { 'Section': {property: 'name'}, + 'Directory Suffix': {property: 'directorySuffix'}, + 'Suffix Track Directories': {property: 'suffixTrackDirectories'}, + 'Color': {property: 'color'}, + 'Has Track Numbers': {property: 'hasTrackNumbers'}, 'Start Counting From': {property: 'startCountingFrom'}, 'Date Originally Released': { @@ -961,6 +1116,8 @@ export class TrackSection extends Thing { transform: parseDate, }, + 'Count Tracks In Artist Totals': {property: 'countTracksInArtistTotals'}, + 'Description': {property: 'description'}, }, }; @@ -970,11 +1127,13 @@ export class TrackSection extends Thing { parts.push(Thing.prototype[inspect.custom].apply(this)); - if (depth >= 0) { + if (depth >= 0) showAlbum: { let album = null; try { album = this.album; - } catch {} + } catch { + break showAlbum; + } let first = null; try { @@ -986,22 +1145,20 @@ export class TrackSection extends Thing { last = this.tracks.at(-1).trackNumber; } catch {} - if (album) { - const albumName = album.name; - const albumIndex = album.trackSections.indexOf(this); + const albumName = album.name; + const albumIndex = album.trackSections.indexOf(this); - const num = - (albumIndex === -1 - ? 'indeterminate position' - : `#${albumIndex + 1}`); + const num = + (albumIndex === -1 + ? 'indeterminate position' + : `#${albumIndex + 1}`); - const range = - (albumIndex >= 0 && first !== null && last !== null - ? `: ${first}-${last}` - : ''); + const range = + (albumIndex >= 0 && first !== null && last !== null + ? `: ${first}-${last}` + : ''); - parts.push(` (${colors.yellow(num + range)} in ${colors.green(albumName)})`); - } + parts.push(` (${colors.yellow(num + range)} in ${colors.green(`"${albumName}"`)})`); } return parts.join(''); diff --git a/src/data/things/art-tag.js b/src/data/things/art-tag.js index 0ec1ff31..f4fedf49 100644 --- a/src/data/things/art-tag.js +++ b/src/data/things/art-tag.js @@ -1,15 +1,22 @@ +export const DATA_ART_TAGS_DIRECTORY = 'art-tags'; export const ART_TAG_DATA_FILE = 'tags.yaml'; -import {input} from '#composite'; -import find from '#find'; -import {sortAlphabetically, sortAlbumsTracksChronologically} from '#sort'; +import {readFile} from 'node:fs/promises'; +import * as path from 'node:path'; + +import {input, V} from '#composite'; +import {traverse} from '#node-utils'; +import {sortAlphabetically} from '#sort'; import Thing from '#thing'; import {unique} from '#sugar'; import {isName} from '#validators'; import {parseAdditionalNames, parseAnnotatedReferences} from '#yaml'; -import {exitWithoutDependency, exposeDependency, exposeUpdateValueOrContinue} - from '#composite/control-flow'; +import { + exitWithoutDependency, + exposeConstant, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; import { annotatedReferenceList, @@ -24,27 +31,20 @@ import { soupyReverse, thingList, urls, - wikiData, } from '#composite/wiki-properties'; -import {withAllDescendantArtTags, withAncestorArtTagBaobabTree} - from '#composite/things/art-tag'; - export class ArtTag extends Thing { static [Thing.referenceType] = 'tag'; static [Thing.friendlyName] = `Art Tag`; + static [Thing.wikiData] = 'artTagData'; - static [Thing.getPropertyDescriptors] = ({ - AdditionalName, - Album, - Track, - }) => ({ + static [Thing.getPropertyDescriptors] = ({AdditionalName}) => ({ // Update & expose - name: name('Unnamed Art Tag'), + name: name(V('Unnamed Art Tag')), directory: directory(), color: color(), - isContentWarning: flag(false), + isContentWarning: flag(V(false)), extraReadingURLs: urls(), nameShort: [ @@ -59,9 +59,7 @@ export class ArtTag extends Thing { }, ], - additionalNames: thingList({ - class: input.value(AdditionalName), - }), + additionalNames: thingList(V(AdditionalName)), description: contentString(), @@ -85,9 +83,11 @@ export class ArtTag extends Thing { // Expose only + isArtTag: exposeConstant(V(true)), + descriptionShort: [ - exitWithoutDependency({ - dependency: 'description', + exitWithoutDependency('description', { + value: input.value(null), mode: input.value('falsy'), }), @@ -103,29 +103,51 @@ export class ArtTag extends Thing { }), indirectlyFeaturedInArtworks: [ - withAllDescendantArtTags(), - { - dependencies: ['#allDescendantArtTags'], - compute: ({'#allDescendantArtTags': allDescendantArtTags}) => + dependencies: ['allDescendantArtTags'], + compute: ({allDescendantArtTags}) => unique( allDescendantArtTags .flatMap(artTag => artTag.directlyFeaturedInArtworks)), }, ], + // All the art tags which descend from this one - that means its own direct + // descendants, plus all the direct and indirect descendants of each of those! + // The results aren't specially sorted, but they won't contain any duplicates + // (for example if two descendant tags both route deeper to end up including + // some of the same tags). allDescendantArtTags: [ - withAllDescendantArtTags(), - exposeDependency({dependency: '#allDescendantArtTags'}), + { + dependencies: ['directDescendantArtTags'], + compute: ({directDescendantArtTags}) => + unique([ + ...directDescendantArtTags, + ...directDescendantArtTags.flatMap(artTag => artTag.allDescendantArtTags), + ]), + }, ], directAncestorArtTags: reverseReferenceList({ reverse: soupyReverse.input('artTagsWhichDirectlyAncestor'), }), + // All the art tags which are ancestors of this one as a "baobab tree" - + // what you'd typically think of as roots are all up in the air! Since this + // really is backwards from the way that the art tag tree is written in data, + // chances are pretty good that there will be many of the exact same "leaf" + // nodes - art tags which don't themselves have any ancestors. In the actual + // data structure, each node is a Map, with keys for each ancestor and values + // for each ancestor's own baobab (thus a branching structure, just like normal + // trees in this regard). ancestorArtTagBaobabTree: [ - withAncestorArtTagBaobabTree(), - exposeDependency({dependency: '#ancestorArtTagBaobabTree'}), + { + dependencies: ['directAncestorArtTags'], + compute: ({directAncestorArtTags}) => + new Map( + directAncestorArtTags + .map(artTag => [artTag, artTag.ancestorArtTagBaobabTree])), + }, ], }); @@ -180,16 +202,26 @@ export class ArtTag extends Thing { }; static [Thing.getYamlLoadingSpec] = ({ - documentModes: {allInOne}, + documentModes: {allTogether}, thingConstructors: {ArtTag}, }) => ({ title: `Process art tags file`, - file: ART_TAG_DATA_FILE, - documentMode: allInOne, - documentThing: ArtTag, + files: dataPath => + Promise.allSettled([ + readFile(path.join(dataPath, ART_TAG_DATA_FILE)) + .then(() => [ART_TAG_DATA_FILE]), + + traverse(path.join(dataPath, DATA_ART_TAGS_DIRECTORY), { + filterFile: name => path.extname(name) === '.yaml', + prefixPath: DATA_ART_TAGS_DIRECTORY, + }), + ]).then(results => results + .filter(({status}) => status === 'fulfilled') + .flatMap(({value}) => value)), - save: (results) => ({artTagData: results}), + documentMode: allTogether, + documentThing: ArtTag, sort({artTagData}) { sortAlphabetically(artTagData); diff --git a/src/data/things/artist.js b/src/data/things/artist.js index 9e329c74..a2ed0b74 100644 --- a/src/data/things/artist.js +++ b/src/data/things/artist.js @@ -4,15 +4,21 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; -import {sortAlphabetically} from '#sort'; -import {stitchArrays} from '#sugar'; +import {input, V} from '#composite'; import Thing from '#thing'; -import {isName, validateArrayItems} from '#validators'; -import {getKebabCase} from '#wiki-data'; -import {parseArtwork} from '#yaml'; +import {parseArtistAliases, parseArtwork} from '#yaml'; -import {exitWithoutDependency} from '#composite/control-flow'; +import { + sortAlbumsTracksChronologically, + sortArtworksChronologically, + sortAlphabetically, + sortContributionsChronologically, +} from '#sort'; + +import {exitWithoutDependency, exposeConstant, exposeDependency} + from '#composite/control-flow'; +import {withFilteredList, withPropertyFromList} from '#composite/data'; +import {withContributionListSums} from '#composite/wiki-data'; import { constitutibleArtwork, @@ -22,53 +28,46 @@ import { flag, name, reverseReferenceList, - singleReference, soupyFind, soupyReverse, + thing, + thingList, urls, - wikiData, } from '#composite/wiki-properties'; -import {artistTotalDuration} from '#composite/things/artist'; - export class Artist extends Thing { static [Thing.referenceType] = 'artist'; - static [Thing.wikiDataArray] = 'artistData'; + static [Thing.wikiData] = 'artistData'; - static [Thing.getPropertyDescriptors] = ({Album, Flash, Group, Track}) => ({ + static [Thing.constitutibleProperties] = [ + 'avatarArtwork', // from inline fields + ]; + + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed Artist'), + name: name(V('Unnamed Artist')), directory: directory(), urls: urls(), contextNotes: contentString(), - hasAvatar: flag(false), - avatarFileExtension: fileExtension('jpg'), + hasAvatar: flag(V(false)), + avatarFileExtension: fileExtension(V('jpg')), avatarArtwork: [ - exitWithoutDependency({ - dependency: 'hasAvatar', + exitWithoutDependency('hasAvatar', { value: input.value(null), + mode: input.value('falsy'), }), constitutibleArtwork.fromYAMLFieldSpec .call(this, 'Avatar Artwork'), ], - aliasNames: { - flags: {update: true, expose: true}, - update: {validate: validateArrayItems(isName)}, - expose: {transform: (names) => names ?? []}, - }, - - isAlias: flag(), - - aliasedArtist: singleReference({ - class: input.value(Artist), - find: soupyFind.input('artist'), - }), + isAlias: flag(V(false)), + artistAliases: thingList(V(Artist)), + aliasedArtist: thing(V(Artist)), // Update only @@ -77,6 +76,8 @@ export class Artist extends Thing { // Expose only + isArtist: exposeConstant(V(true)), + trackArtistContributions: reverseReferenceList({ reverse: soupyReverse.input('trackArtistContributionsBy'), }), @@ -97,6 +98,10 @@ export class Artist extends Thing { reverse: soupyReverse.input('albumArtistContributionsBy'), }), + albumTrackArtistContributions: reverseReferenceList({ + reverse: soupyReverse.input('albumTrackArtistContributionsBy'), + }), + albumCoverArtistContributions: reverseReferenceList({ reverse: soupyReverse.input('albumCoverArtistContributionsBy'), }), @@ -125,7 +130,76 @@ export class Artist extends Thing { reverse: soupyReverse.input('groupsCloselyLinkedTo'), }), - totalDuration: artistTotalDuration(), + musicContributions: [ + { + dependencies: [ + 'trackArtistContributions', + 'trackContributorContributions', + ], + + compute: (continuation, { + trackArtistContributions, + trackContributorContributions, + }) => continuation({ + ['#contributions']: [ + ...trackArtistContributions, + ...trackContributorContributions, + ], + }), + }, + + { + dependencies: ['#contributions'], + compute: ({'#contributions': contributions}) => + sortContributionsChronologically( + contributions, + sortAlbumsTracksChronologically), + }, + ], + + artworkContributions: [ + { + dependencies: [ + 'trackCoverArtistContributions', + 'albumCoverArtistContributions', + 'albumWallpaperArtistContributions', + 'albumBannerArtistContributions', + ], + + compute: (continuation, { + trackCoverArtistContributions, + albumCoverArtistContributions, + albumWallpaperArtistContributions, + albumBannerArtistContributions, + }) => continuation({ + ['#contributions']: [ + ...trackCoverArtistContributions, + ...albumCoverArtistContributions, + ...albumWallpaperArtistContributions, + ...albumBannerArtistContributions, + ], + }), + }, + + { + dependencies: ['#contributions'], + compute: ({'#contributions': contributions}) => + sortContributionsChronologically( + contributions, + sortArtworksChronologically), + }, + ], + + totalDuration: [ + withPropertyFromList('musicContributions', V('thing')), + withPropertyFromList('#musicContributions.thing', V('isMainRelease')), + + withFilteredList('musicContributions', '#musicContributions.thing.isMainRelease') + .outputs({'#filteredList': '#mainReleaseContributions'}), + + withContributionListSums('#mainReleaseContributions'), + exposeDependency('#contributionListDuration'), + ], }); static [Thing.getSerializeDescriptors] = ({ @@ -139,8 +213,6 @@ export class Artist extends Thing { hasAvatar: S.id, avatarFileExtension: S.id, - aliasNames: S.id, - tracksAsCommentator: S.toRefs, albumsAsCommentator: S.toRefs, }); @@ -171,17 +243,9 @@ export class Artist extends Thing { // in the original's alias list. This is honestly a bit awkward, but it // avoids artist aliases conflicting with each other when checking for // duplicate directories. - for (const aliasName of originalArtist.aliasNames) { - // These are trouble. We should be accessing aliases' directories - // directly, but artists currently don't expose a reverse reference - // list for aliases. (This is pending a cleanup of "reverse reference" - // behavior in general.) It doesn't actually cause problems *here* - // because alias directories are computed from their names 100% of the - // time, but that *is* an assumption this code makes. - if (aliasName === artist.name) continue; - if (artist.directory === getKebabCase(aliasName)) { - return []; - } + for (const alias of originalArtist.artistAliases) { + if (alias === artist) break; + if (alias.directory === artist.directory) return []; } // And, aliases never return just a blank string. This part is pretty @@ -221,7 +285,10 @@ export class Artist extends Thing { 'Has Avatar': {property: 'hasAvatar'}, 'Avatar File Extension': {property: 'avatarFileExtension'}, - 'Aliases': {property: 'aliasNames'}, + 'Aliases': { + property: 'artistAliases', + transform: parseArtistAliases, + }, 'Dead URLs': {ignore: true}, @@ -239,38 +306,6 @@ export class Artist extends Thing { documentMode: allInOne, documentThing: Artist, - save(results) { - const artists = results; - - const artistRefs = - artists.map(artist => Thing.getReference(artist)); - - const artistAliasNames = - artists.map(artist => artist.aliasNames); - - const artistAliases = - stitchArrays({ - originalArtistRef: artistRefs, - aliasNames: artistAliasNames, - }).flatMap(({originalArtistRef, aliasNames}) => - aliasNames.map(name => { - const alias = new Artist(); - alias.name = name; - alias.isAlias = true; - alias.aliasedArtist = originalArtistRef; - return alias; - })); - - const artistData = [...artists, ...artistAliases]; - - const artworkData = - artistData - .filter(artist => artist.hasAvatar) - .map(artist => artist.avatarArtwork); - - return {artistData, artworkData}; - }, - sort({artistData}) { sortAlphabetically(artistData); }, @@ -287,7 +322,7 @@ export class Artist extends Thing { let aliasedArtist; try { aliasedArtist = this.aliasedArtist.name; - } catch (_error) { + } catch { aliasedArtist = CacheableObject.getUpdateValue(this, 'aliasedArtist'); } diff --git a/src/data/things/artwork.js b/src/data/things/artwork.js index ac70159c..c1aafa8f 100644 --- a/src/data/things/artwork.js +++ b/src/data/things/artwork.js @@ -1,6 +1,7 @@ import {inspect} from 'node:util'; -import {input} from '#composite'; +import {colors} from '#cli'; +import {input, V} from '#composite'; import find from '#find'; import Thing from '#thing'; @@ -24,17 +25,25 @@ import { parseDimensions, } from '#yaml'; -import {withIndexInList, withPropertyFromObject} from '#composite/data'; - import { exitWithoutDependency, exposeConstant, exposeDependency, exposeDependencyOrContinue, exposeUpdateValueOrContinue, + flipFilter, } from '#composite/control-flow'; import { + withFilteredList, + withNearbyItemFromList, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; + +import { + constituteFrom, + constituteOrContinue, withRecontextualizedContributionList, withResolvedAnnotatedReferenceList, withResolvedContribs, @@ -53,21 +62,18 @@ import { wikiData, } from '#composite/wiki-properties'; -import { - withAttachedArtwork, - withContainingArtworkList, - withContribsFromAttachedArtwork, - withPropertyFromAttachedArtwork, - withDate, -} from '#composite/things/artwork'; +import {withContainingArtworkList} from '#composite/things/artwork'; export class Artwork extends Thing { static [Thing.referenceType] = 'artwork'; + static [Thing.wikiData] = 'artworkData'; + + static [Thing.constitutibleProperties] = [ + // Contributions currently aren't being observed for constitution. + // 'artistContribs', // from attached artwork or thing + ]; - static [Thing.getPropertyDescriptors] = ({ - ArtTag, - Contribution, - }) => ({ + static [Thing.getPropertyDescriptors] = ({ArtTag}) => ({ // Update & expose unqualifiedDirectory: directory({ @@ -79,51 +85,28 @@ export class Artwork extends Thing { label: simpleString(), source: contentString(), + originDetails: contentString(), + showFilename: simpleString(), dateFromThingProperty: simpleString(), date: [ - withDate({ - from: input.updateValue({validate: isDate}), + exposeUpdateValueOrContinue({ + validate: input.value(isDate), }), - exposeDependency({dependency: '#date'}), + constituteFrom('thing', 'dateFromThingProperty'), ], fileExtensionFromThingProperty: simpleString(), fileExtension: [ - { - compute: (continuation) => continuation({ - ['#default']: 'jpg', - }), - }, - exposeUpdateValueOrContinue({ validate: input.value(isFileExtension), }), - exitWithoutDependency({ - dependency: 'thing', - value: '#default', - }), - - exitWithoutDependency({ - dependency: 'fileExtensionFromThingProperty', - value: '#default', - }), - - withPropertyFromObject({ - object: 'thing', - property: 'fileExtensionFromThingProperty', - }), - - exposeDependencyOrContinue({ - dependency: '#value', - }), - - exposeDependency({ - dependency: '#default', + constituteFrom('thing', 'fileExtensionFromThingProperty', { + else: input.value('jpg'), }), ], @@ -134,78 +117,40 @@ export class Artwork extends Thing { validate: input.value(isDimensions), }), - exitWithoutDependency({ - dependency: 'dimensionsFromThingProperty', - value: input.value(null), - }), - - withPropertyFromObject({ - object: 'thing', - property: 'dimensionsFromThingProperty', - }).outputs({ - ['#value']: '#dimensionsFromThing', - }), - - exitWithoutDependency({ - dependency: 'dimensionsFromThingProperty', - value: input.value(null), - }), - - exposeDependencyOrContinue({ - dependency: '#dimensionsFromThing', - }), - - exposeConstant({ - value: input.value(null), - }), + constituteFrom('thing', 'dimensionsFromThingProperty'), ], - attachAbove: flag(false), + attachAbove: flag(V(false)), artistContribsFromThingProperty: simpleString(), artistContribsArtistProperty: simpleString(), artistContribs: [ - withDate(), - withResolvedContribs({ from: input.updateValue({validate: isContributionList}), - date: '#date', + date: 'date', + thingProperty: input.thisProperty(), artistProperty: 'artistContribsArtistProperty', }), - exposeDependencyOrContinue({ - dependency: '#resolvedContribs', - mode: input.value('empty'), - }), - - withContribsFromAttachedArtwork(), + exposeDependencyOrContinue('#resolvedContribs', V('empty')), - exposeDependencyOrContinue({ - dependency: '#attachedArtwork.artistContribs', - }), + withPropertyFromObject('attachedArtwork', V('artistContribs')), - exitWithoutDependency({ - dependency: 'artistContribsFromThingProperty', - value: input.value([]), - }), + withRecontextualizedContributionList('#attachedArtwork.artistContribs'), + exposeDependencyOrContinue('#attachedArtwork.artistContribs'), - withPropertyFromObject({ - object: 'thing', - property: 'artistContribsFromThingProperty', - }).outputs({ - ['#value']: '#artistContribs', - }), + exitWithoutDependency('artistContribsFromThingProperty', V([])), - withRecontextualizedContributionList({ - list: '#artistContribs', - }), + withPropertyFromObject('thing', 'artistContribsFromThingProperty') + .outputs({'#value': '#artistContribsFromThing'}), - exposeDependency({ - dependency: '#artistContribs', - }), + withRecontextualizedContributionList('#artistContribsFromThing'), + exposeDependency('#artistContribsFromThing'), ], + style: simpleString(), + artTagsFromThingProperty: simpleString(), artTags: [ @@ -214,42 +159,14 @@ export class Artwork extends Thing { validate: validateReferenceList(ArtTag[Thing.referenceType]), }), - find: soupyFind.input('artTag'), }), - exposeDependencyOrContinue({ - dependency: '#resolvedReferenceList', - mode: input.value('empty'), - }), + exposeDependencyOrContinue('#resolvedReferenceList', V('empty')), - withPropertyFromAttachedArtwork({ - property: input.value('artTags'), - }), - - exposeDependencyOrContinue({ - dependency: '#attachedArtwork.artTags', - }), + constituteOrContinue('attachedArtwork', V('artTags'), V('empty')), - exitWithoutDependency({ - dependency: 'artTagsFromThingProperty', - value: input.value([]), - }), - - withPropertyFromObject({ - object: 'thing', - property: 'artTagsFromThingProperty', - }).outputs({ - ['#value']: '#artTags', - }), - - exposeDependencyOrContinue({ - dependency: '#artTags', - }), - - exposeConstant({ - value: input.value([]), - }), + constituteFrom('thing', 'artTagsFromThingProperty', V([])), ], referencedArtworksFromThingProperty: simpleString(), @@ -279,35 +196,16 @@ export class Artwork extends Thing { })), }), - data: 'artworkData', + data: '_artworkData', find: '#find', thing: input.value('artwork'), }), - exposeDependencyOrContinue({ - dependency: '#resolvedAnnotatedReferenceList', - mode: input.value('empty'), - }), - - exitWithoutDependency({ - dependency: 'referencedArtworksFromThingProperty', - value: input.value([]), - }), - - withPropertyFromObject({ - object: 'thing', - property: 'referencedArtworksFromThingProperty', - }).outputs({ - ['#value']: '#referencedArtworks', - }), - - exposeDependencyOrContinue({ - dependency: '#referencedArtworks', - }), + exposeDependencyOrContinue('#resolvedAnnotatedReferenceList', V('empty')), - exposeConstant({ - value: input.value([]), + constituteFrom('thing', 'referencedArtworksFromThingProperty', { + else: input.value([]), }), ], @@ -317,23 +215,19 @@ export class Artwork extends Thing { reverse: soupyReverse(), // used for referencedArtworks (mixedFind) - artworkData: wikiData({ - class: input.value(Artwork), - }), + artworkData: wikiData(V(Artwork)), // Expose only + isArtwork: exposeConstant(V(true)), + referencedByArtworks: reverseReferenceList({ reverse: soupyReverse.input('artworksWhichReference'), }), isMainArtwork: [ withContainingArtworkList(), - - exitWithoutDependency({ - dependency: '#containingArtworkList', - value: input.value(null), - }), + exitWithoutDependency('#containingArtworkList'), { dependencies: [input.myself(), '#containingArtworkList'], @@ -347,11 +241,7 @@ export class Artwork extends Thing { mainArtwork: [ withContainingArtworkList(), - - exitWithoutDependency({ - dependency: '#containingArtworkList', - value: input.value(null), - }), + exitWithoutDependency('#containingArtworkList'), { dependencies: ['#containingArtworkList'], @@ -361,16 +251,50 @@ export class Artwork extends Thing { ], attachedArtwork: [ - withAttachedArtwork(), + exitWithoutDependency('attachAbove', { + value: input.value(null), + mode: input.value('falsy'), + }), + + withContainingArtworkList(), + + withPropertyFromList('#containingArtworkList', V('attachAbove')), + + flipFilter('#containingArtworkList.attachAbove') + .outputs({'#containingArtworkList.attachAbove': '#filterNotAttached'}), - exposeDependency({ - dependency: '#attachedArtwork', + withNearbyItemFromList({ + list: '#containingArtworkList', + item: input.myself(), + offset: input.value(-1), + filter: '#filterNotAttached', }), + + exposeDependency('#nearbyItem'), ], attachingArtworks: reverseReferenceList({ reverse: soupyReverse.input('artworksWhichAttach'), }), + + groups: [ + withPropertyFromObject('thing', V('groups')), + exposeDependencyOrContinue('#thing.groups'), + + exposeConstant(V([])), + ], + + contentWarningArtTags: [ + withPropertyFromList('artTags', V('isContentWarning')), + withFilteredList('artTags', '#artTags.isContentWarning'), + exposeDependency('#filteredList'), + ], + + contentWarnings: [ + withPropertyFromList('contentWarningArtTags', V('name')), + exposeDependency('#contentWarningArtTags.name'), + ], + }); static [Thing.yamlDocumentSpec] = { @@ -385,6 +309,8 @@ export class Artwork extends Thing { 'Label': {property: 'label'}, 'Source': {property: 'source'}, + 'Origin Details': {property: 'originDetails'}, + 'Show Filename': {property: 'showFilename'}, 'Date': { property: 'date', @@ -398,6 +324,8 @@ export class Artwork extends Thing { transform: parseContributors, }, + 'Style': {property: 'style'}, + 'Tags': {property: 'artTags'}, 'Referenced Artworks': { @@ -456,6 +384,18 @@ export class Artwork extends Thing { return this.thing.getOwnArtworkPath(this); } + countOwnContributionInContributionTotals(contrib) { + if (this.attachAbove) { + return false; + } + + if (contrib.annotation?.startsWith('edits for wiki')) { + return false; + } + + return true; + } + [inspect.custom](depth, options, inspect) { const parts = []; diff --git a/src/data/things/content.js b/src/data/things/content.js index cf8fa1f4..64d03e69 100644 --- a/src/data/things/content.js +++ b/src/data/things/content.js @@ -1,10 +1,13 @@ -import {input} from '#composite'; -import find from '#find'; +import {input, V} from '#composite'; +import {transposeArrays} from '#sugar'; import Thing from '#thing'; -import {is, isDate} from '#validators'; +import {is, isDate, validateReferenceList} from '#validators'; import {parseDate} from '#yaml'; -import {contentString, referenceList, simpleDate, soupyFind, thing} +import {withFilteredList, withMappedList, withPropertyFromList} + from '#composite/data'; +import {withResolvedReferenceList} from '#composite/wiki-data'; +import {contentString, simpleDate, soupyFind, thing} from '#composite/wiki-properties'; import { @@ -17,22 +20,34 @@ import { } from '#composite/control-flow'; import { - contentArtists, hasAnnotationPart, - withAnnotationParts, - withHasAnnotationPart, - withSourceText, - withSourceURLs, + withAnnotationPartNodeLists, + withExpressedOrImplicitArtistReferences, withWebArchiveDate, } from '#composite/things/content'; export class ContentEntry extends Thing { - static [Thing.getPropertyDescriptors] = ({Artist}) => ({ + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose thing: thing(), - artists: contentArtists(), + artists: [ + withExpressedOrImplicitArtistReferences({ + from: input.updateValue({ + validate: validateReferenceList('artist'), + }), + }), + + exitWithoutDependency('#artistReferences', V([])), + + withResolvedReferenceList({ + list: '#artistReferences', + find: soupyFind.input('artist'), + }), + + exposeDependency('#resolvedReferenceList'), + ], artistText: contentString(), @@ -51,6 +66,8 @@ export class ContentEntry extends Thing { }, accessKind: [ + exitWithoutDependency('_accessDate'), + exposeUpdateValueOrContinue({ validate: input.value( is(...[ @@ -61,9 +78,7 @@ export class ContentEntry extends Thing { withWebArchiveDate(), - withResultOfAvailabilityCheck({ - from: '#webArchiveDate', - }), + withResultOfAvailabilityCheck({from: '#webArchiveDate'}), { dependencies: ['#availability'], @@ -73,13 +88,10 @@ export class ContentEntry extends Thing { : continuation()), }, - exposeConstant({ - value: input.value(null), - }), + exposeConstant(V('accessed')), ], date: simpleDate(), - secondDate: simpleDate(), accessDate: [ @@ -93,9 +105,7 @@ export class ContentEntry extends Thing { dependency: '#webArchiveDate', }), - exposeConstant({ - value: input.value(null), - }), + exposeConstant(V(null)), ], body: contentString(), @@ -106,22 +116,114 @@ export class ContentEntry extends Thing { // Expose only + isContentEntry: exposeConstant(V(true)), + annotationParts: [ - withAnnotationParts({ - mode: input.value('strings'), - }), + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstNodes']: + nodeLists.map(list => list.at(0)), + + ['#lastNodes']: + nodeLists.map(list => list.at(-1)), + }), + }, - exposeDependency({dependency: '#annotationParts'}), + withPropertyFromList('#firstNodes', V('i')) + .outputs({'#firstNodes.i': '#startIndices'}), + + withPropertyFromList('#lastNodes', V('iEnd')) + .outputs({'#lastNodes.iEnd': '#endIndices'}), + + { + dependencies: [ + 'annotation', + '#startIndices', + '#endIndices', + ], + + compute: ({ + ['annotation']: annotation, + ['#startIndices']: startIndices, + ['#endIndices']: endIndices, + }) => + transposeArrays([startIndices, endIndices]) + .map(([start, end]) => + annotation.slice(start, end)), + }, ], sourceText: [ - withSourceText(), - exposeDependency({dependency: '#sourceText'}), + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstPartWithExternalLink']: + nodeLists + .find(nodes => nodes + .some(node => node.type === 'external-link')) ?? + null, + }), + }, + + exitWithoutDependency('#firstPartWithExternalLink'), + + { + dependencies: ['annotation', '#firstPartWithExternalLink'], + compute: ({ + ['annotation']: annotation, + ['#firstPartWithExternalLink']: nodes, + }) => + annotation.slice( + nodes.at(0).i, + nodes.at(-1).iEnd), + }, ], sourceURLs: [ - withSourceURLs(), - exposeDependency({dependency: '#sourceURLs'}), + withAnnotationPartNodeLists(), + + { + dependencies: ['#annotationPartNodeLists'], + compute: (continuation, { + ['#annotationPartNodeLists']: nodeLists, + }) => continuation({ + ['#firstPartWithExternalLink']: + nodeLists + .find(nodes => nodes + .some(node => node.type === 'external-link')) ?? + null, + }), + }, + + exitWithoutDependency('#firstPartWithExternalLink', V([])), + + withMappedList({ + list: '#firstPartWithExternalLink', + map: input.value(node => node.type === 'external-link'), + }).outputs({ + '#mappedList': '#externalLinkFilter', + }), + + withFilteredList({ + list: '#firstPartWithExternalLink', + filter: '#externalLinkFilter', + }), + + withMappedList({ + list: '#filteredList', + map: input.value(node => node.data.href), + }), + + exposeDependency('#mappedList'), ], }); @@ -145,9 +247,17 @@ export class ContentEntry extends Thing { } export class CommentaryEntry extends ContentEntry { + static [Thing.wikiData] = 'commentaryData'; + static [Thing.getPropertyDescriptors] = () => ({ // Expose only + isCommentaryEntry: [ + exposeConstant({ + value: input.value(true), + }), + ], + isWikiEditorCommentary: hasAnnotationPart({ part: input.value('wiki editor'), }), @@ -155,28 +265,23 @@ export class CommentaryEntry extends ContentEntry { } export class LyricsEntry extends ContentEntry { + static [Thing.wikiData] = 'lyricsData'; + static [Thing.getPropertyDescriptors] = () => ({ - // Expose only + // Update & expose - isWikiLyrics: hasAnnotationPart({ - part: input.value('wiki lyrics'), - }), + originDetails: contentString(), - hasSquareBracketAnnotations: [ - withHasAnnotationPart({ - part: input.value('wiki lyrics'), - }), + // Expose only - exitWithoutDependency({ - dependency: '#hasAnnotationPart', - mode: input.value('falsy'), - value: input.value(false), - }), + isLyricsEntry: exposeConstant(V(true)), - exitWithoutDependency({ - dependency: 'body', - value: input.value(false), - }), + isWikiLyrics: hasAnnotationPart(V('wiki lyrics')), + helpNeeded: hasAnnotationPart(V('help needed')), + + hasSquareBracketAnnotations: [ + exitWithoutDependency('isWikiLyrics', V(false), V('falsy')), + exitWithoutDependency('body', V(false)), { dependencies: ['body'], @@ -185,6 +290,30 @@ export class LyricsEntry extends ContentEntry { }, ], }); + + static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(ContentEntry, { + fields: { + 'Origin Details': {property: 'originDetails'}, + }, + }); +} + +export class CreditingSourcesEntry extends ContentEntry { + static [Thing.wikiData] = 'creditingSourceData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Expose only + + isCreditingSourcesEntry: exposeConstant(V(true)), + }); } -export class CreditingSourcesEntry extends ContentEntry {} +export class ReferencingSourcesEntry extends ContentEntry { + static [Thing.wikiData] = 'referencingSourceData'; + + static [Thing.getPropertyDescriptors] = () => ({ + // Expose only + + isReferencingSourceEntry: exposeConstant(V(true)), + }); +} diff --git a/src/data/things/contribution.js b/src/data/things/contribution.js index c92fafb4..393a60b4 100644 --- a/src/data/things/contribution.js +++ b/src/data/things/contribution.js @@ -2,13 +2,21 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; +import {input, V} from '#composite'; import {empty} from '#sugar'; import Thing from '#thing'; -import {isStringNonEmpty, isThing, validateReference} from '#validators'; +import {isBoolean, isStringNonEmpty, isThing} from '#validators'; -import {exitWithoutDependency, exposeDependency} from '#composite/control-flow'; -import {flag, simpleDate, soupyFind} from '#composite/wiki-properties'; +import {simpleDate, singleReference, soupyFind} + from '#composite/wiki-properties'; + +import { + exitWithoutDependency, + exposeConstant, + exposeDependency, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; import { withFilteredList, @@ -19,12 +27,8 @@ import { import { inheritFromContributionPresets, - thingPropertyMatches, - thingReferenceTypeMatches, withContainingReverseContributionList, - withContributionArtist, withContributionContext, - withMatchingContributionPresets, } from '#composite/things/contribution'; export class Contribution extends Thing { @@ -48,17 +52,9 @@ export class Contribution extends Thing { date: simpleDate(), - artist: [ - withContributionArtist({ - ref: input.updateValue({ - validate: validateReference('artist'), - }), - }), - - exposeDependency({ - dependency: '#artist', - }), - ], + artist: singleReference({ + find: soupyFind.input('artist'), + }), annotation: { flags: {update: true, expose: true}, @@ -66,19 +62,55 @@ export class Contribution extends Thing { }, countInContributionTotals: [ - inheritFromContributionPresets({ - property: input.thisProperty(), + inheritFromContributionPresets(), + + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - flag(true), + { + dependencies: ['thing', input.myself()], + compute: (continuation, { + ['thing']: thing, + [input.myself()]: contribution, + }) => + (thing.countOwnContributionInContributionTotals?.(contribution) + ? true + : thing.countOwnContributionInContributionTotals + ? false + : continuation()), + }, + + exposeConstant(V(true)), ], countInDurationTotals: [ - inheritFromContributionPresets({ - property: input.thisProperty(), + inheritFromContributionPresets(), + + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - flag(true), + withPropertyFromObject('thing', V('duration')), + exitWithoutDependency('#thing.duration', { + value: input.value(false), + mode: input.value('falsy'), + }), + + { + dependencies: ['thing', input.myself()], + compute: (continuation, { + ['thing']: thing, + [input.myself()]: contribution, + }) => + (thing.countOwnContributionInDurationTotals?.(contribution) + ? true + : thing.countOwnContributionInDurationTotals + ? false + : continuation()), + }, + + exposeConstant(V(true)), ], // Update only @@ -87,6 +119,8 @@ export class Contribution extends Thing { // Expose only + isContribution: exposeConstant(V(true)), + context: [ withContributionContext(), @@ -107,11 +141,43 @@ export class Contribution extends Thing { ], matchingPresets: [ - withMatchingContributionPresets(), - - exposeDependency({ - dependency: '#matchingContributionPresets', + withPropertyFromObject('thing', { + property: input.value('wikiInfo'), + internal: input.value(true), }), + + exitWithoutDependency('#thing.wikiInfo', V([])), + + withPropertyFromObject('#thing.wikiInfo', V('contributionPresets')) + .outputs({'#thing.wikiInfo.contributionPresets': '#contributionPresets'}), + + exitWithoutDependency('#contributionPresets', V([]), V('empty')), + + withContributionContext(), + + // TODO: implementing this with compositional filters would be fun + { + dependencies: [ + '#contributionPresets', + '#contributionTarget', + '#contributionProperty', + 'annotation', + ], + + compute: ({ + ['#contributionPresets']: presets, + ['#contributionTarget']: target, + ['#contributionProperty']: property, + ['annotation']: annotation, + }) => + presets.filter(preset => + preset.context[0] === target && + preset.context.slice(1).includes(property) && + // For now, only match if the annotation is a complete match. + // Partial matches (e.g. because the contribution includes "two" + // annotations, separated by commas) don't count. + preset.annotation === annotation), + }, ], // All the contributions from the list which includes this contribution. @@ -119,27 +185,13 @@ export class Contribution extends Thing { // artist, but also this very contribution. It doesn't mix contributions // exposed on different properties. associatedContributions: [ - exitWithoutDependency({ - dependency: 'thing', - value: input.value([]), - }), + exitWithoutDependency('thing', V([])), + exitWithoutDependency('thingProperty', V([])), - exitWithoutDependency({ - dependency: 'thingProperty', - value: input.value([]), - }), + withPropertyFromObject('thing', 'thingProperty') + .outputs({'#value': '#contributions'}), - withPropertyFromObject({ - object: 'thing', - property: 'thingProperty', - }).outputs({ - '#value': '#contributions', - }), - - withPropertyFromList({ - list: '#contributions', - property: input.value('annotation'), - }), + withPropertyFromList('#contributions', V('annotation')), { dependencies: ['#contributions.annotation', 'annotation'], @@ -155,88 +207,37 @@ export class Contribution extends Thing { }), }, - withFilteredList({ - list: '#contributions', - filter: '#likeContributionsFilter', - }).outputs({ - '#filteredList': '#contributions', - }), + withFilteredList('#contributions', '#likeContributionsFilter') + .outputs({'#filteredList': '#contributions'}), - exposeDependency({ - dependency: '#contributions', - }), + exposeDependency('#contributions'), ], - isArtistContribution: thingPropertyMatches({ - value: input.value('artistContribs'), - }), - - isContributorContribution: thingPropertyMatches({ - value: input.value('contributorContribs'), - }), - - isCoverArtistContribution: thingPropertyMatches({ - value: input.value('coverArtistContribs'), - }), - - isBannerArtistContribution: thingPropertyMatches({ - value: input.value('bannerArtistContribs'), - }), - - isWallpaperArtistContribution: thingPropertyMatches({ - value: input.value('wallpaperArtistContribs'), - }), - - isForTrack: thingReferenceTypeMatches({ - value: input.value('track'), - }), - - isForAlbum: thingReferenceTypeMatches({ - value: input.value('album'), - }), - - isForFlash: thingReferenceTypeMatches({ - value: input.value('flash'), - }), - previousBySameArtist: [ - withContainingReverseContributionList().outputs({ - '#containingReverseContributionList': '#list', - }), - - exitWithoutDependency({ - dependency: '#list', - }), + withContainingReverseContributionList() + .outputs({'#containingReverseContributionList': '#list'}), - withNearbyItemFromList({ - list: '#list', - item: input.myself(), - offset: input.value(-1), - }), + exitWithoutDependency('#list'), - exposeDependency({ - dependency: '#nearbyItem', - }), + withNearbyItemFromList('#list', input.myself(), V(-1)), + exposeDependency('#nearbyItem'), ], nextBySameArtist: [ - withContainingReverseContributionList().outputs({ - '#containingReverseContributionList': '#list', - }), + withContainingReverseContributionList() + .outputs({'#containingReverseContributionList': '#list'}), - exitWithoutDependency({ - dependency: '#list', - }), + exitWithoutDependency('#list'), - withNearbyItemFromList({ - list: '#list', - item: input.myself(), - offset: input.value(+1), - }), + withNearbyItemFromList('#list', input.myself(), V(+1)), + exposeDependency('#nearbyItem'), + ], - exposeDependency({ - dependency: '#nearbyItem', - }), + groups: [ + withPropertyFromObject('thing', V('groups')), + exposeDependencyOrContinue('#thing.groups'), + + exposeConstant(V([])), ], }); @@ -259,7 +260,7 @@ export class Contribution extends Thing { let artist; try { artist = this.artist; - } catch (_error) { + } catch { // Computing artist might crash for any reason - don't distract from // other errors as a result of inspecting this contribution. } diff --git a/src/data/things/flash.js b/src/data/things/flash.js index 11b19ebc..b595ec58 100644 --- a/src/data/things/flash.js +++ b/src/data/things/flash.js @@ -1,7 +1,6 @@ export const FLASH_DATA_FILE = 'flashes.yaml'; -import {input} from '#composite'; -import {empty} from '#sugar'; +import {input, V} from '#composite'; import {sortFlashesChronologically} from '#sort'; import Thing from '#thing'; import {anyOf, isColor, isContentString, isDirectory, isNumber, isString} @@ -22,7 +21,6 @@ import {withPropertyFromObject} from '#composite/data'; import { exposeConstant, exposeDependency, - exposeDependencyOrContinue, exposeUpdateValueOrContinue, } from '#composite/control-flow'; @@ -43,26 +41,29 @@ import { thing, thingList, urls, - wikiData, } from '#composite/wiki-properties'; -import {withFlashAct} from '#composite/things/flash'; -import {withFlashSide} from '#composite/things/flash-act'; - export class Flash extends Thing { static [Thing.referenceType] = 'flash'; + static [Thing.wikiData] = 'flashData'; + + static [Thing.constitutibleProperties] = [ + 'coverArtwork', // from inline fields + ]; static [Thing.getPropertyDescriptors] = ({ AdditionalName, CommentaryEntry, CreditingSourcesEntry, - Track, FlashAct, + Track, WikiInfo, }) => ({ // Update & expose - name: name('Unnamed Flash'), + act: thing(V(FlashAct)), + + name: name(V('Unnamed Flash')), directory: { flags: {update: true, expose: true}, @@ -95,19 +96,13 @@ export class Flash extends Thing { validate: input.value(isColor), }), - withFlashAct(), - - withPropertyFromObject({ - object: '#flashAct', - property: input.value('color'), - }), - - exposeDependency({dependency: '#flashAct.color'}), + withPropertyFromObject('act', V('color')), + exposeDependency('#act.color'), ], date: simpleDate(), - coverArtFileExtension: fileExtension('jpg'), + coverArtFileExtension: fileExtension(V('jpg')), coverArtDimensions: dimensions(), @@ -116,7 +111,6 @@ export class Flash extends Thing { .call(this, 'Cover Artwork'), contributorContribs: contributionList({ - date: 'date', artistProperty: input.value('flashContributorContributions'), }), @@ -127,17 +121,10 @@ export class Flash extends Thing { urls: urls(), - additionalNames: thingList({ - class: input.value(AdditionalName), - }), - - commentary: thingList({ - class: input.value(CommentaryEntry), - }), + additionalNames: thingList(V(AdditionalName)), - creditSources: thingList({ - class: input.value(CreditingSourcesEntry), - }), + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), // Update only @@ -145,28 +132,17 @@ export class Flash extends Thing { reverse: soupyReverse(), // used for withMatchingContributionPresets (indirectly by Contribution) - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + wikiInfo: thing(V(WikiInfo)), // Expose only - commentatorArtists: commentatorArtists(), + isFlash: exposeConstant(V(true)), - act: [ - withFlashAct(), - exposeDependency({dependency: '#flashAct'}), - ], + commentatorArtists: commentatorArtists(), side: [ - withFlashAct(), - - withPropertyFromObject({ - object: '#flashAct', - property: input.value('side'), - }), - - exposeDependency({dependency: '#flashAct.side'}), + withPropertyFromObject('act', V('side')), + exposeDependency('#act.side'), ], }); @@ -257,8 +233,8 @@ export class Flash extends Thing { transform: parseCommentary, }, - 'Credit Sources': { - property: 'creditSources', + 'Crediting Sources': { + property: 'creditingSources', transform: parseCreditingSources, }, @@ -278,11 +254,14 @@ export class Flash extends Thing { export class FlashAct extends Thing { static [Thing.referenceType] = 'flash-act'; static [Thing.friendlyName] = `Flash Act`; + static [Thing.wikiData] = 'flashActData'; - static [Thing.getPropertyDescriptors] = () => ({ + static [Thing.getPropertyDescriptors] = ({Flash, FlashSide}) => ({ // Update & expose - name: name('Unnamed Flash Act'), + side: thing(V(FlashSide)), + + name: name(V('Unnamed Flash Act')), directory: directory(), color: color(), @@ -291,26 +270,11 @@ export class FlashAct extends Thing { validate: input.value(isContentString), }), - withFlashSide(), - - withPropertyFromObject({ - object: '#flashSide', - property: input.value('listTerminology'), - }), - - exposeDependencyOrContinue({ - dependency: '#flashSide.listTerminology', - }), - - exposeConstant({ - value: input.value(null), - }), + withPropertyFromObject('side', V('listTerminology')), + exposeDependency('#side.listTerminology'), ], - flashes: referenceList({ - class: input.value(Flash), - find: soupyFind.input('flash'), - }), + flashes: thingList(V(Flash)), // Update only @@ -319,10 +283,7 @@ export class FlashAct extends Thing { // Expose only - side: [ - withFlashSide(), - exposeDependency({dependency: '#flashSide'}), - ], + isFlashAct: exposeConstant(V(true)), }); static [Thing.findSpecs] = { @@ -357,23 +318,25 @@ export class FlashAct extends Thing { export class FlashSide extends Thing { static [Thing.referenceType] = 'flash-side'; static [Thing.friendlyName] = `Flash Side`; + static [Thing.wikiData] = 'flashSideData'; - static [Thing.getPropertyDescriptors] = () => ({ + static [Thing.getPropertyDescriptors] = ({FlashAct}) => ({ // Update & expose - name: name('Unnamed Flash Side'), + name: name(V('Unnamed Flash Side')), directory: directory(), color: color(), listTerminology: contentString(), - acts: referenceList({ - class: input.value(FlashAct), - find: soupyFind.input('flashAct'), - }), + acts: thingList(V(FlashAct)), // Update only find: soupyFind(), + + // Expose only + + isFlashSide: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -416,62 +379,61 @@ export class FlashSide extends Thing { ? FlashAct : Flash), - save(results) { - // JavaScript likes you. + connect(results) { + let thing, i; - if (!empty(results) && !(results[0] instanceof FlashSide)) { - throw new Error(`Expected a side at top of flash data file`); - } + for (i = 0; thing = results[i]; i++) { + if (thing.isFlashSide) { + const side = thing; + const acts = []; - let index = 0; - let thing; - for (; thing = results[index]; index++) { - const flashSide = thing; - const flashActRefs = []; + for (i++; thing = results[i]; i++) { + if (thing.isFlashAct) { + const act = thing; + const flashes = []; - if (results[index + 1] instanceof Flash) { - throw new Error(`Expected an act to immediately follow a side`); - } + for (i++; thing = results[i]; i++) { + if (thing.isFlash) { + const flash = thing; + + flash.act = act; + flashes.push(flash); - for ( - index++; - (thing = results[index]) && thing instanceof FlashAct; - index++ - ) { - const flashAct = thing; - const flashRefs = []; - for ( - index++; - (thing = results[index]) && thing instanceof Flash; - index++ - ) { - flashRefs.push(Thing.getReference(thing)); + continue; + } + + i--; + break; + } + + act.side = side; + act.flashes = flashes; + acts.push(act); + + continue; + } + + if (thing.isFlash) { + throw new Error(`Flashes must be under an act`); + } + + i--; + break; } - index--; - flashAct.flashes = flashRefs; - flashActRefs.push(Thing.getReference(flashAct)); - } - index--; - flashSide.acts = flashActRefs; - } - const flashData = results.filter(x => x instanceof Flash); - const flashActData = results.filter(x => x instanceof FlashAct); - const flashSideData = results.filter(x => x instanceof FlashSide); + side.acts = acts; - const artworkData = flashData.map(flash => flash.coverArtwork); - const commentaryData = flashData.flatMap(flash => flash.commentary); - const creditingSourceData = flashData.flatMap(flash => flash.creditSources); + continue; + } - return { - flashData, - flashActData, - flashSideData, + if (thing.isFlashAct) { + throw new Error(`Acts must be under a side`); + } - artworkData, - commentaryData, - creditingSourceData, - }; + if (thing.isFlash) { + throw new Error(`Flashes must be under a side and act`); + } + } }, sort({flashData}) { diff --git a/src/data/things/group.js b/src/data/things/group.js index b40d15b4..cc5f4cb8 100644 --- a/src/data/things/group.js +++ b/src/data/things/group.js @@ -1,31 +1,66 @@ export const GROUP_DATA_FILE = 'groups.yaml'; -import {input} from '#composite'; +import {inspect} from 'node:util'; + +import {colors} from '#cli'; +import {input, V} from '#composite'; import Thing from '#thing'; +import {is, isBoolean} from '#validators'; import {parseAnnotatedReferences, parseSerieses} from '#yaml'; +import {withPropertyFromObject} from '#composite/data'; +import {withUniqueReferencingThing} from '#composite/wiki-data'; + +import { + exposeConstant, + exposeDependencyOrContinue, + exposeUpdateValueOrContinue, +} from '#composite/control-flow'; + import { annotatedReferenceList, color, contentString, directory, + flag, name, referenceList, - seriesList, soupyFind, + soupyReverse, + thing, + thingList, urls, - wikiData, } from '#composite/wiki-properties'; export class Group extends Thing { static [Thing.referenceType] = 'group'; + static [Thing.wikiData] = 'groupData'; - static [Thing.getPropertyDescriptors] = ({Album, Artist}) => ({ + static [Thing.getPropertyDescriptors] = ({Album, Artist, Series}) => ({ // Update & expose - name: name('Unnamed Group'), + name: name(V('Unnamed Group')), directory: directory(), + excludeFromGalleryTabs: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), + }), + + withUniqueReferencingThing({ + reverse: soupyReverse.input('groupCategoriesWhichInclude'), + }).outputs({ + '#uniqueReferencingThing': '#category', + }), + + withPropertyFromObject('#category', V('excludeGroupsFromGalleryTabs')), + exposeDependencyOrContinue('#category.excludeGroupsFromGalleryTabs'), + + exposeConstant(V(false)), + ], + + divideAlbumsByStyle: flag(V(false)), + description: contentString(), urls: urls(), @@ -43,17 +78,17 @@ export class Group extends Thing { find: soupyFind.input('album'), }), - serieses: seriesList({ - group: input.myself(), - }), + serieses: thingList(V(Series)), // Update only find: soupyFind(), - reverse: soupyFind(), + reverse: soupyReverse(), // Expose only + isGroup: exposeConstant(V(true)), + descriptionShort: { flags: {expose: true}, @@ -70,8 +105,8 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'reverse'], - compute: ({this: group, reverse}) => + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => reverse.albumsWhoseGroupsInclude(group), }, }, @@ -80,8 +115,8 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'reverse'], - compute: ({this: group, reverse}) => + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => reverse.groupCategoriesWhichInclude(group, {unique: true}) ?.color, }, @@ -91,8 +126,8 @@ export class Group extends Thing { flags: {expose: true}, expose: { - dependencies: ['this', 'reverse'], - compute: ({this: group, reverse}) => + dependencies: ['this', '_reverse'], + compute: ({this: group, _reverse: reverse}) => reverse.groupCategoriesWhichInclude(group, {unique: true}) ?? null, }, @@ -129,6 +164,10 @@ export class Group extends Thing { fields: { 'Group': {property: 'name'}, 'Directory': {property: 'directory'}, + + 'Exclude From Gallery Tabs': {property: 'excludeFromGalleryTabs'}, + 'Divide Albums By Style': {property: 'divideAlbumsByStyle'}, + 'Description': {property: 'description'}, 'URLs': {property: 'urls'}, @@ -165,7 +204,7 @@ export class Group extends Thing { ? GroupCategory : Group), - save(results) { + connect(results) { let groupCategory; let groupRefs = []; @@ -189,11 +228,6 @@ export class Group extends Thing { if (groupCategory) { Object.assign(groupCategory, {groups: groupRefs}); } - - const groupData = results.filter(x => x instanceof Group); - const groupCategoryData = results.filter(x => x instanceof GroupCategory); - - return {groupData, groupCategoryData}; }, // Groups aren't sorted at all, always preserving the order in the data @@ -205,13 +239,16 @@ export class Group extends Thing { export class GroupCategory extends Thing { static [Thing.referenceType] = 'group-category'; static [Thing.friendlyName] = `Group Category`; + static [Thing.wikiData] = 'groupCategoryData'; static [Thing.getPropertyDescriptors] = ({Group}) => ({ // Update & expose - name: name('Unnamed Group Category'), + name: name(V('Unnamed Group Category')), directory: directory(), + excludeGroupsFromGalleryTabs: flag(V(false)), + color: color(), groups: referenceList({ @@ -222,6 +259,10 @@ export class GroupCategory extends Thing { // Update only find: soupyFind(), + + // Expose only + + isGroupCategory: exposeConstant(V(true)), }); static [Thing.reverseSpecs] = { @@ -236,7 +277,82 @@ export class GroupCategory extends Thing { static [Thing.yamlDocumentSpec] = { fields: { 'Category': {property: 'name'}, + 'Color': {property: 'color'}, + + 'Exclude Groups From Gallery Tabs': { + property: 'excludeGroupsFromGalleryTabs', + }, }, }; } + +export class Series extends Thing { + static [Thing.wikiData] = 'seriesData'; + + static [Thing.getPropertyDescriptors] = ({Album, Group}) => ({ + // Update & expose + + name: name(V('Unnamed Series')), + + showAlbumArtists: { + flags: {update: true, expose: true}, + update: { + validate: + is('all', 'differing', 'none'), + }, + }, + + description: contentString(), + + group: thing(V(Group)), + + albums: referenceList({ + class: input.value(Album), + find: soupyFind.input('album'), + }), + + // Update only + + find: soupyFind(), + }); + + static [Thing.yamlDocumentSpec] = { + fields: { + 'Name': {property: 'name'}, + + 'Description': {property: 'description'}, + + 'Show Album Artists': {property: 'showAlbumArtists'}, + + 'Albums': {property: 'albums'}, + }, + }; + + [inspect.custom](depth, options, inspect) { + const parts = []; + + parts.push(Thing.prototype[inspect.custom].apply(this)); + + if (depth >= 0) showGroup: { + let group = null; + try { + group = this.group; + } catch { + break showGroup; + } + + const groupName = group.name; + const groupIndex = group.serieses.indexOf(this); + + const num = + (groupIndex === -1 + ? 'indeterminate position' + : `#${groupIndex + 1}`); + + parts.push(` (${colors.yellow(num)} in ${colors.green(`"${groupName}"`)})`); + } + + return parts.join(''); + } +} diff --git a/src/data/things/homepage-layout.js b/src/data/things/homepage-layout.js index 82bad2d3..c4dc2812 100644 --- a/src/data/things/homepage-layout.js +++ b/src/data/things/homepage-layout.js @@ -3,7 +3,7 @@ export const HOMEPAGE_LAYOUT_DATA_FILE = 'homepage.yaml'; import {inspect} from 'node:util'; import {colors} from '#cli'; -import {input} from '#composite'; +import {input, V} from '#composite'; import Thing from '#thing'; import {empty} from '#sugar'; @@ -17,7 +17,7 @@ import { validateReference, } from '#validators'; -import {exposeDependency} from '#composite/control-flow'; +import {exposeConstant, exposeDependency} from '#composite/control-flow'; import {withResolvedReference} from '#composite/wiki-data'; import { @@ -32,6 +32,8 @@ import { export class HomepageLayout extends Thing { static [Thing.friendlyName] = `Homepage Layout`; + static [Thing.wikiData] = 'homepageLayout'; + static [Thing.oneInstancePerWiki] = true; static [Thing.getPropertyDescriptors] = ({HomepageLayoutSection}) => ({ // Update & expose @@ -44,9 +46,11 @@ export class HomepageLayout extends Thing { expose: {transform: value => value ?? []}, }, - sections: thingList({ - class: input.value(HomepageLayoutSection), - }), + sections: thingList(V(HomepageLayoutSection)), + + // Expose only + + isHomepageLayout: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -63,7 +67,6 @@ export class HomepageLayout extends Thing { thingConstructors: { HomepageLayout, HomepageLayoutSection, - HomepageLayoutAlbumsRow, }, }) => ({ title: `Process homepage layout file`, @@ -95,7 +98,7 @@ export class HomepageLayout extends Thing { return null; }, - save(results) { + connect(results) { if (!empty(results) && !(results[0] instanceof HomepageLayout)) { throw new Error(`Expected 'Homepage' document at top of homepage layout file`); } @@ -138,8 +141,6 @@ export class HomepageLayout extends Thing { closeCurrentSection(); homepageLayout.sections = sections; - - return {homepageLayout}; }, }); } @@ -150,13 +151,15 @@ export class HomepageLayoutSection extends Thing { static [Thing.getPropertyDescriptors] = ({HomepageLayoutRow}) => ({ // Update & expose - name: name(`Unnamed Homepage Section`), + name: name(V(`Unnamed Homepage Section`)), color: color(), - rows: thingList({ - class: input.value(HomepageLayoutRow), - }), + rows: thingList(V(HomepageLayoutRow)), + + // Expose only + + isHomepageLayoutSection: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -173,9 +176,7 @@ export class HomepageLayoutRow extends Thing { static [Thing.getPropertyDescriptors] = ({HomepageLayoutSection}) => ({ // Update & expose - section: thing({ - class: input.value(HomepageLayoutSection), - }), + section: thing(V(HomepageLayoutSection)), // Update only @@ -183,6 +184,8 @@ export class HomepageLayoutRow extends Thing { // Expose only + isHomepageLayoutRow: exposeConstant(V(true)), + type: { flags: {expose: true}, @@ -222,9 +225,7 @@ export class HomepageLayoutRow extends Thing { export class HomepageLayoutActionsRow extends HomepageLayoutRow { static [Thing.friendlyName] = `Homepage Actions Row`; - static [Thing.getPropertyDescriptors] = (opts) => ({ - ...HomepageLayoutRow[Thing.getPropertyDescriptors](opts), - + static [Thing.getPropertyDescriptors] = () => ({ // Update & expose actionLinks: { @@ -234,25 +235,21 @@ export class HomepageLayoutActionsRow extends HomepageLayoutRow { // Expose only - type: { - flags: {expose: true}, - expose: {compute: () => 'actions'}, - }, + isHomepageLayoutActionsRow: exposeConstant(V(true)), + type: exposeConstant(V('actions')), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(HomepageLayoutRow, { + static [Thing.yamlDocumentSpec] = { fields: { 'Actions': {property: 'actionLinks'}, }, - }); + }; } export class HomepageLayoutAlbumCarouselRow extends HomepageLayoutRow { static [Thing.friendlyName] = `Homepage Album Carousel Row`; - static [Thing.getPropertyDescriptors] = (opts, {Album, Group} = opts) => ({ - ...HomepageLayoutRow[Thing.getPropertyDescriptors](opts), - + static [Thing.getPropertyDescriptors] = (opts, {Album} = opts) => ({ // Update & expose albums: referenceList({ @@ -262,25 +259,21 @@ export class HomepageLayoutAlbumCarouselRow extends HomepageLayoutRow { // Expose only - type: { - flags: {expose: true}, - expose: {compute: () => 'album carousel'}, - }, + isHomepageLayoutAlbumCarouselRow: exposeConstant(V(true)), + type: exposeConstant(V('album carousel')), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(HomepageLayoutRow, { + static [Thing.yamlDocumentSpec] = { fields: { 'Albums': {property: 'albums'}, }, - }); + }; } export class HomepageLayoutAlbumGridRow extends HomepageLayoutRow { static [Thing.friendlyName] = `Homepage Album Grid Row`; static [Thing.getPropertyDescriptors] = (opts, {Album, Group} = opts) => ({ - ...HomepageLayoutRow[Thing.getPropertyDescriptors](opts), - // Update & expose sourceGroup: [ @@ -307,7 +300,7 @@ export class HomepageLayoutAlbumGridRow extends HomepageLayoutRow { find: soupyFind.input('group'), }), - exposeDependency({dependency: '#resolvedReference'}), + exposeDependency('#resolvedReference'), ], sourceAlbums: referenceList({ @@ -322,17 +315,15 @@ export class HomepageLayoutAlbumGridRow extends HomepageLayoutRow { // Expose only - type: { - flags: {expose: true}, - expose: {compute: () => 'album grid'}, - }, + isHomepageLayoutAlbumGridRow: exposeConstant(V(true)), + type: exposeConstant(V('album grid')), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(HomepageLayoutRow, { + static [Thing.yamlDocumentSpec] = { fields: { 'Group': {property: 'sourceGroup'}, 'Count': {property: 'countAlbumsFromGroup'}, 'Albums': {property: 'sourceAlbums'}, }, - }); + }; } diff --git a/src/data/things/index.js b/src/data/things/index.js index 11307b50..09765fd2 100644 --- a/src/data/things/index.js +++ b/src/data/things/index.js @@ -6,7 +6,7 @@ import CacheableObject from '#cacheable-object'; import {logError} from '#cli'; import {compositeFrom} from '#composite'; import * as serialize from '#serialize'; -import {withEntries} from '#sugar'; +import {empty} from '#sugar'; import Thing from '#thing'; import * as additionalFileClasses from './additional-file.js'; @@ -58,6 +58,7 @@ const __dirname = path.dirname( function niceShowAggregate(error, ...opts) { showAggregate(error, { pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)), + showClasses: false, ...opts, }); } @@ -90,25 +91,39 @@ function errorDuplicateClassNames() { } function flattenClassLists() { - let allClassesUnsorted = Object.create(null); - + let remaining = []; for (const classes of Object.values(allClassLists)) { - for (const [name, constructor] of Object.entries(classes)) { + for (const constructor of Object.values(classes)) { if (typeof constructor !== 'function') continue; if (!(constructor.prototype instanceof Thing)) continue; - allClassesUnsorted[name] = constructor; + remaining.push(constructor); + } + } + + let sorted = []; + while (true) { + if (sorted[0]) { + const superclass = Object.getPrototypeOf(sorted[0]); + if (superclass !== Thing) { + if (sorted.includes(superclass)) { + sorted.unshift(...sorted.splice(sorted.indexOf(superclass), 1)); + } else { + sorted.unshift(superclass); + } + continue; + } + } + + if (!empty(remaining)) { + sorted.unshift(remaining.shift()); + } else { + break; } } - // Sort subclasses after their superclasses. - Object.assign(allClasses, - withEntries(allClassesUnsorted, entries => - entries.sort(({[1]: A}, {[1]: B}) => - (A.prototype instanceof B - ? +1 - : B.prototype instanceof A - ? -1 - : 0)))); + for (const constructor of sorted) { + allClasses[constructor.name] = constructor; + } } function descriptorAggregateHelper({ @@ -138,6 +153,15 @@ function descriptorAggregateHelper({ } catch (error) { niceShowAggregate(error); showFailedClasses(failedClasses); + + /* + if (error.errors) { + for (const sub of error.errors) { + console.error(sub); + } + } + */ + return false; } } @@ -167,10 +191,10 @@ function evaluatePropertyDescriptors() { } } - constructor[CacheableObject.propertyDescriptors] = { - ...constructor[CacheableObject.propertyDescriptors] ?? {}, - ...results, - }; + constructor[CacheableObject.propertyDescriptors] = + Object.create(constructor[CacheableObject.propertyDescriptors] ?? null); + + Object.assign(constructor[CacheableObject.propertyDescriptors], results); }, showFailedClasses(failedClasses) { @@ -200,6 +224,27 @@ function evaluateSerializeDescriptors() { }); } +function finalizeYamlDocumentSpecs() { + return descriptorAggregateHelper({ + message: `Errors finalizing Thing YAML document specs`, + + op(constructor) { + const superclass = Object.getPrototypeOf(constructor); + if ( + constructor[Thing.yamlDocumentSpec] && + superclass[Thing.yamlDocumentSpec] + ) { + constructor[Thing.yamlDocumentSpec] = + Thing.extendDocumentSpec(superclass, constructor[Thing.yamlDocumentSpec]); + } + }, + + showFailedClasses(failedClasses) { + logError`Failed to finalize YAML document specs for classes: ${failedClasses.join(', ')}`; + }, + }); +} + function finalizeCacheableObjectPrototypes() { return descriptorAggregateHelper({ message: `Errors finalizing Thing class prototypes`, @@ -214,19 +259,14 @@ function finalizeCacheableObjectPrototypes() { }); } -if (!errorDuplicateClassNames()) - process.exit(1); +if (!errorDuplicateClassNames()) process.exit(1); flattenClassLists(); -if (!evaluatePropertyDescriptors()) - process.exit(1); - -if (!evaluateSerializeDescriptors()) - process.exit(1); - -if (!finalizeCacheableObjectPrototypes()) - process.exit(1); +if (!evaluatePropertyDescriptors()) process.exit(1); +if (!evaluateSerializeDescriptors()) process.exit(1); +if (!finalizeYamlDocumentSpecs()) process.exit(1); +if (!finalizeCacheableObjectPrototypes()) process.exit(1); Object.assign(allClasses, {Thing}); diff --git a/src/data/things/language.js b/src/data/things/language.js index 4e23cf7f..7f3f43de 100644 --- a/src/data/things/language.js +++ b/src/data/things/language.js @@ -1,24 +1,25 @@ -import { Temporal, toTemporalInstant } from '@js-temporal/polyfill'; +import {Temporal, toTemporalInstant} from '@js-temporal/polyfill'; import {withAggregate} from '#aggregate'; -import CacheableObject from '#cacheable-object'; import {logWarn} from '#cli'; +import {input, V} from '#composite'; import * as html from '#html'; -import {empty} from '#sugar'; -import {isLanguageCode} from '#validators'; +import {accumulateSum, empty, withEntries} from '#sugar'; +import {isLanguageCode, isObject} from '#validators'; import Thing from '#thing'; +import {languageOptionRegex} from '#wiki-data'; import { + externalLinkSpec, getExternalLinkStringOfStyleFromDescriptors, getExternalLinkStringsFromDescriptors, isExternalLinkContext, - isExternalLinkSpec, isExternalLinkStyle, } from '#external-links'; -import {externalFunction, flag, name} from '#composite/wiki-properties'; - -export const languageOptionRegex = /{(?<name>[A-Z0-9_]+)}/g; +import {exitWithoutDependency, exposeConstant} + from '#composite/control-flow'; +import {flag, name} from '#composite/wiki-properties'; export class Language extends Thing { static [Thing.getPropertyDescriptors] = () => ({ @@ -34,7 +35,7 @@ export class Language extends Thing { // Human-readable name. This should be the language's own native name, not // localized to any other language. - name: name(`Unnamed Language`), + name: name(V(`Unnamed Language`)), // Language code specific to JavaScript's Internationalization (Intl) API. // Usually this will be the same as the language's general code, but it @@ -56,20 +57,29 @@ export class Language extends Thing { // with languages that are currently in development and not ready for // formal release, or which are just kept hidden as "experimental zones" // for wiki development or content testing. - hidden: flag(false), + hidden: flag(V(false)), // Mapping of translation keys to values (strings). Generally, don't // access this object directly - use methods instead. - strings: { - flags: {update: true, expose: true}, - update: {validate: (t) => typeof t === 'object'}, + strings: [ + { + dependencies: [ + input.updateValue({validate: isObject}), + 'inheritedStrings', + ], + + compute: (continuation, { + [input.updateValue()]: strings, + ['inheritedStrings']: inheritedStrings, + }) => + (strings && inheritedStrings + ? continuation() + : strings ?? inheritedStrings), + }, - expose: { + { dependencies: ['inheritedStrings', 'code'], transform(strings, {inheritedStrings, code}) { - if (!strings && !inheritedStrings) return null; - if (!inheritedStrings) return strings; - const validStrings = { ...inheritedStrings, ...strings, @@ -98,6 +108,7 @@ export class Language extends Thing { logWarn`- Missing options: ${missingOptionNames.join(', ')}`; if (!empty(misplacedOptionNames)) logWarn`- Unexpected options: ${misplacedOptionNames.join(', ')}`; + validStrings[key] = inheritedStrings[key]; } } @@ -105,7 +116,7 @@ export class Language extends Thing { return validStrings; }, }, - }, + ], // May be provided to specify "default" strings, generally (but not // necessarily) inherited from another Language object. @@ -114,34 +125,22 @@ export class Language extends Thing { update: {validate: (t) => typeof t === 'object'}, }, - // List of descriptors for providing to external link utilities when using - // language.formatExternalLink - refer to #external-links for info. - externalLinkSpec: { - flags: {update: true, expose: true}, - update: {validate: isExternalLinkSpec}, - }, - - // Update only - - escapeHTML: externalFunction(), - // Expose only - onlyIfOptions: { - flags: {expose: true}, - expose: { - compute: () => Symbol.for(`language.onlyIfOptions`), - }, - }, + isLanguage: exposeConstant(V(true)), + + onlyIfOptions: exposeConstant(V(Symbol.for(`language.onlyIfOptions`))), intl_date: this.#intlHelper(Intl.DateTimeFormat, {full: true}), intl_dateYear: this.#intlHelper(Intl.DateTimeFormat, {year: 'numeric'}), + intl_dateMonthDay: this.#intlHelper(Intl.DateTimeFormat, {month: 'numeric', day: 'numeric'}), intl_number: this.#intlHelper(Intl.NumberFormat), intl_listConjunction: this.#intlHelper(Intl.ListFormat, {type: 'conjunction'}), intl_listDisjunction: this.#intlHelper(Intl.ListFormat, {type: 'disjunction'}), intl_listUnit: this.#intlHelper(Intl.ListFormat, {type: 'unit'}), intl_pluralCardinal: this.#intlHelper(Intl.PluralRules, {type: 'cardinal'}), intl_pluralOrdinal: this.#intlHelper(Intl.PluralRules, {type: 'ordinal'}), + intl_wordSegmenter: this.#intlHelper(Intl.Segmenter, {granularity: 'word'}), validKeys: { flags: {expose: true}, @@ -159,19 +158,16 @@ export class Language extends Thing { }, // TODO: This currently isn't used. Is it still needed? - strings_htmlEscaped: { - flags: {expose: true}, - expose: { - dependencies: ['strings', 'inheritedStrings', 'escapeHTML'], - compute({strings, inheritedStrings, escapeHTML}) { - if (!(strings || inheritedStrings) || !escapeHTML) return null; - const allStrings = {...inheritedStrings, ...strings}; - return Object.fromEntries( - Object.entries(allStrings).map(([k, v]) => [k, escapeHTML(v)]) - ); - }, + strings_htmlEscaped: [ + exitWithoutDependency('strings'), + + { + dependencies: ['strings'], + compute: ({strings}) => + withEntries(strings, entries => entries + .map(([key, value]) => [key, html.escape(value)])), }, - }, + ], }); static #intlHelper (constructor, opts) { @@ -192,18 +188,35 @@ export class Language extends Thing { return this.formatString(...args); } + $order(...args) { + return this.orderStringOptions(...args); + } + assertIntlAvailable(property) { if (!this[property]) { throw new Error(`Intl API ${property} unavailable`); } } + countWords(text) { + this.assertIntlAvailable('intl_wordSegmenter'); + + const string = html.resolve(text, {normalize: 'plain'}); + const segments = this.intl_wordSegmenter.segment(string); + + return accumulateSum(segments, segment => segment.isWordLike ? 1 : 0); + } + getUnitForm(value) { this.assertIntlAvailable('intl_pluralCardinal'); return this.intl_pluralCardinal.select(value); } formatString(...args) { + if (typeof args.at(-1) === 'function') { + throw new Error(`Passed function - did you mean language.encapsulate() instead?`); + } + const hasOptions = typeof args.at(-1) === 'object' && args.at(-1) !== null; @@ -211,19 +224,14 @@ export class Language extends Thing { const key = this.#joinKeyParts(hasOptions ? args.slice(0, -1) : args); + const template = + this.#getStringTemplateFromFormedKey(key); + const options = (hasOptions ? args.at(-1) : {}); - if (!this.strings) { - throw new Error(`Strings unavailable`); - } - - if (!this.validKeys.includes(key)) { - throw new Error(`Invalid key ${key} accessed`); - } - const constantCasify = name => name .replace(/[A-Z]/g, '_$&') @@ -264,8 +272,7 @@ export class Language extends Thing { ])); const output = this.#iterateOverTemplate({ - template: this.strings[key], - + template, match: languageOptionRegex, insert: ({name: optionName}, canceledForming) => { @@ -310,7 +317,7 @@ export class Language extends Thing { return undefined; } - return optionValue; + return this.sanitize(optionValue); }, }); @@ -345,6 +352,46 @@ export class Language extends Thing { return output; } + orderStringOptions(...args) { + let slice = null, at = null, parts = null; + if (args.length >= 2 && typeof args.at(-1) === 'number') { + if (args.length >= 3 && typeof args.at(-2) === 'number') { + slice = [args.at(-2), args.at(-1)]; + parts = args.slice(0, -2); + } else { + at = args.at(-1); + parts = args.slice(0, -1); + } + } else { + parts = args; + } + + const template = this.getStringTemplate(...parts); + const matches = Array.from(template.matchAll(languageOptionRegex)); + const options = matches.map(({groups}) => groups.name); + + if (slice !== null) return options.slice(...slice); + if (at !== null) return options.at(at); + return options; + } + + getStringTemplate(...args) { + const key = this.#joinKeyParts(args); + return this.#getStringTemplateFromFormedKey(key); + } + + #getStringTemplateFromFormedKey(key) { + if (!this.strings) { + throw new Error(`Strings unavailable`); + } + + if (!this.validKeys.includes(key)) { + throw new Error(`Invalid key ${key} accessed`); + } + + return this.strings[key]; + } + #iterateOverTemplate({ template, match: regexp, @@ -375,26 +422,22 @@ export class Language extends Thing { partInProgress += template.slice(lastIndex, match.index); - // Sanitize string arguments in particular. These are taken to come from - // (raw) data and may include special characters that aren't meant to be - // rendered as HTML markup. - const sanitizedInsertion = - this.#sanitizeValueForInsertion(insertion); - - if (typeof sanitizedInsertion === 'string') { - // Join consecutive strings together. - partInProgress += sanitizedInsertion; - } else if ( - sanitizedInsertion instanceof html.Tag && - sanitizedInsertion.contentOnly - ) { - // Collapse string-only tag contents onto the current string part. - partInProgress += sanitizedInsertion.toString(); - } else { - // Push the string part in progress, then the insertion as-is. - outputParts.push(partInProgress); - outputParts.push(sanitizedInsertion); + const insertionItems = html.smush(insertion).content; + if (insertionItems.length === 1 && typeof insertionItems[0] !== 'string') { + // Push the insertion exactly as it is, rather than manipulating. + if (partInProgress) outputParts.push(partInProgress); + outputParts.push(insertion); partInProgress = ''; + } else for (const insertionItem of insertionItems) { + if (typeof insertionItem === 'string') { + // Join consecutive strings together. + partInProgress += insertionItem; + } else { + // Push the string part in progress, then the insertion as-is. + if (partInProgress) outputParts.push(partInProgress); + outputParts.push(insertionItem); + partInProgress = ''; + } } lastIndex = match.index + match[0].length; @@ -426,14 +469,9 @@ export class Language extends Thing { // html.Tag objects - gets left as-is, preserving the value exactly as it's // provided. #sanitizeValueForInsertion(value) { - const escapeHTML = CacheableObject.getUpdateValue(this, 'escapeHTML'); - if (!escapeHTML) { - throw new Error(`escapeHTML unavailable`); - } - switch (typeof value) { case 'string': - return escapeHTML(value); + return html.escape(value); case 'number': case 'boolean': @@ -510,6 +548,15 @@ export class Language extends Thing { return this.intl_dateYear.format(date); } + formatMonthDay(date) { + if (date === null || date === undefined) { + return html.blank(); + } + + this.assertIntlAvailable('intl_dateMonthDay'); + return this.intl_dateMonthDay.format(date); + } + formatYearRange(startDate, endDate) { // formatYearRange expects both values to be present, but if both are null // or both are undefined, that's just blank content. @@ -688,10 +735,6 @@ export class Language extends Thing { style = 'platform', context = 'generic', } = {}) { - if (!this.externalLinkSpec) { - throw new TypeError(`externalLinkSpec unavailable`); - } - // Null or undefined url is blank content. if (url === null || url === undefined) { return html.blank(); @@ -700,7 +743,7 @@ export class Language extends Thing { isExternalLinkContext(context); if (style === 'all') { - return getExternalLinkStringsFromDescriptors(url, this.externalLinkSpec, { + return getExternalLinkStringsFromDescriptors(url, externalLinkSpec, { language: this, context, }); @@ -709,7 +752,7 @@ export class Language extends Thing { isExternalLinkStyle(style); const result = - getExternalLinkStringOfStyleFromDescriptors(url, style, this.externalLinkSpec, { + getExternalLinkStringOfStyleFromDescriptors(url, style, externalLinkSpec, { language: this, context, }); @@ -865,6 +908,18 @@ export class Language extends Thing { } } + typicallyLowerCase(string) { + // Utter nonsense implementation, so this only works on strings, + // not actual HTML content, and may rudely disrespect *intentful* + // capitalization of whatever goes into it. + + if (typeof string !== 'string') return string; + if (string.length <= 1) return string; + if (/^\S+?[A-Z]/.test(string)) return string; + + return string[0].toLowerCase() + string.slice(1); + } + // Utility function to quickly provide a useful string key // (generally a prefix) to stuff nested beneath it. encapsulate(...args) { @@ -923,7 +978,6 @@ Object.assign(Language.prototype, { countArtworks: countHelper('artworks'), countCommentaryEntries: countHelper('commentaryEntries', 'entries'), countContributions: countHelper('contributions'), - countCoverArts: countHelper('coverArts'), countDays: countHelper('days'), countFlashes: countHelper('flashes'), countMonths: countHelper('months'), diff --git a/src/data/things/news-entry.js b/src/data/things/news-entry.js index 43d1638e..bb35d11b 100644 --- a/src/data/things/news-entry.js +++ b/src/data/things/news-entry.js @@ -1,20 +1,23 @@ export const NEWS_DATA_FILE = 'news.yaml'; +import {V} from '#composite'; import {sortChronologically} from '#sort'; import Thing from '#thing'; import {parseDate} from '#yaml'; +import {exposeConstant} from '#composite/control-flow'; import {contentString, directory, name, simpleDate} from '#composite/wiki-properties'; export class NewsEntry extends Thing { static [Thing.referenceType] = 'news-entry'; static [Thing.friendlyName] = `News Entry`; + static [Thing.wikiData] = 'newsData'; static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed News Entry'), + name: name(V('Unnamed News Entry')), directory: directory(), date: simpleDate(), @@ -22,6 +25,8 @@ export class NewsEntry extends Thing { // Expose only + isNewsEntry: exposeConstant(V(true)), + contentShort: { flags: {expose: true}, @@ -64,8 +69,6 @@ export class NewsEntry extends Thing { documentMode: allInOne, documentThing: NewsEntry, - save: (results) => ({newsData: results}), - sort({newsData}) { sortChronologically(newsData, {latestFirst: true}); }, diff --git a/src/data/things/sorting-rule.js b/src/data/things/sorting-rule.js index b169a541..101a4966 100644 --- a/src/data/things/sorting-rule.js +++ b/src/data/things/sorting-rule.js @@ -3,7 +3,7 @@ export const SORTING_RULE_DATA_FILE = 'sorting-rules.yaml'; import {readFile, writeFile} from 'node:fs/promises'; import * as path from 'node:path'; -import {input} from '#composite'; +import {V} from '#composite'; import {chunkByProperties, compareArrays, unique} from '#sugar'; import Thing from '#thing'; import {isObject, isStringNonEmpty, anyOf, strictArrayOf} from '#validators'; @@ -22,6 +22,7 @@ import { reorderDocumentsInYAMLSourceText, } from '#yaml'; +import {exposeConstant} from '#composite/control-flow'; import {flag} from '#composite/wiki-properties'; function isSelectFollowingEntry(value) { @@ -37,16 +38,21 @@ function isSelectFollowingEntry(value) { export class SortingRule extends Thing { static [Thing.friendlyName] = `Sorting Rule`; + static [Thing.wikiData] = 'sortingRules'; static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - active: flag(true), + active: flag(V(true)), message: { flags: {update: true, expose: true}, update: {validate: isStringNonEmpty}, }, + + // Expose only + + isSortingRule: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { @@ -68,8 +74,6 @@ export class SortingRule extends Thing { (document['Sort Documents'] ? DocumentSortingRule : null), - - save: (results) => ({sortingRules: results}), }); check(opts) { @@ -119,17 +123,21 @@ export class ThingSortingRule extends SortingRule { validate: strictArrayOf(isStringNonEmpty), }, }, + + // Expose only + + isThingSortingRule: exposeConstant(V(true)), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(SortingRule, { + static [Thing.yamlDocumentSpec] = { fields: { 'By Properties': {property: 'properties'}, }, - }); + }; sort(sortable) { if (this.properties) { - for (const property of this.properties.slice().reverse()) { + for (const property of this.properties.toReversed()) { const get = thing => thing[property]; const lc = property.toLowerCase(); @@ -218,9 +226,13 @@ export class DocumentSortingRule extends ThingSortingRule { flags: {update: true, expose: true}, update: {validate: isStringNonEmpty}, }, + + // Expose only + + isDocumentSortingRule: exposeConstant(V(true)), }); - static [Thing.yamlDocumentSpec] = Thing.extendDocumentSpec(ThingSortingRule, { + static [Thing.yamlDocumentSpec] = { fields: { 'Sort Documents': {property: 'filename'}, 'Select Documents Following': {property: 'selectDocumentsFollowing'}, @@ -233,7 +245,7 @@ export class DocumentSortingRule extends ThingSortingRule { 'Select Documents Under', ]}, ], - }); + }; static async apply(rule, {wikiData, dataPath, dry}) { const oldLayout = getThingLayoutForFilename(rule.filename, wikiData); @@ -261,10 +273,8 @@ export class DocumentSortingRule extends ThingSortingRule { } static async* applyAll(rules, {wikiData, dataPath, dry}) { - rules = - rules - .slice() - .sort((a, b) => a.filename.localeCompare(b.filename, 'en')); + rules = rules + .toSorted((a, b) => a.filename.localeCompare(b.filename, 'en')); for (const {chunk, filename} of chunkByProperties(rules, ['filename'])) { const initialLayout = getThingLayoutForFilename(filename, wikiData); diff --git a/src/data/things/static-page.js b/src/data/things/static-page.js index 52a09c31..999072d3 100644 --- a/src/data/things/static-page.js +++ b/src/data/things/static-page.js @@ -2,22 +2,25 @@ export const DATA_STATIC_PAGE_DIRECTORY = 'static-page'; import * as path from 'node:path'; +import {V} from '#composite'; import {traverse} from '#node-utils'; import {sortAlphabetically} from '#sort'; import Thing from '#thing'; import {isName} from '#validators'; +import {exposeConstant} from '#composite/control-flow'; import {contentString, directory, flag, name, simpleString} from '#composite/wiki-properties'; export class StaticPage extends Thing { static [Thing.referenceType] = 'static'; static [Thing.friendlyName] = `Static Page`; + static [Thing.wikiData] = 'staticPageData'; static [Thing.getPropertyDescriptors] = () => ({ // Update & expose - name: name('Unnamed Static Page'), + name: name(V('Unnamed Static Page')), nameShort: { flags: {update: true, expose: true}, @@ -35,7 +38,11 @@ export class StaticPage extends Thing { script: simpleString(), content: contentString(), - absoluteLinks: flag(), + absoluteLinks: flag(V(false)), + + // Expose only + + isStaticPage: exposeConstant(V(true)), }); static [Thing.findSpecs] = { @@ -76,8 +83,6 @@ export class StaticPage extends Thing { documentMode: onePerFile, documentThing: StaticPage, - save: (results) => ({staticPageData: results}), - sort({staticPageData}) { sortAlphabetically(staticPageData); }, diff --git a/src/data/things/track.js b/src/data/things/track.js index 557ba2a7..ab7511a8 100644 --- a/src/data/things/track.js +++ b/src/data/things/track.js @@ -2,10 +2,21 @@ import {inspect} from 'node:util'; import CacheableObject from '#cacheable-object'; import {colors} from '#cli'; -import {input} from '#composite'; +import {input, V} from '#composite'; +import {onlyItem} from '#sugar'; +import {sortByDate} from '#sort'; import Thing from '#thing'; -import {isBoolean, isColor, isContributionList, isDate, isFileExtension} - from '#validators'; +import {getKebabCase} from '#wiki-data'; + +import { + isBoolean, + isColor, + isContentString, + isContributionList, + isDate, + isFileExtension, + validateReference, +} from '#validators'; import { parseAdditionalFiles, @@ -15,26 +26,41 @@ import { parseCommentary, parseContributors, parseCreditingSources, + parseReferencingSources, parseDate, parseDimensions, parseDuration, parseLyrics, } from '#yaml'; -import {withPropertyFromObject} from '#composite/data'; - import { + exitWithoutDependency, + exitWithoutUpdateValue, exposeConstant, exposeDependency, exposeDependencyOrContinue, exposeUpdateValueOrContinue, exposeWhetherDependencyAvailable, + withAvailabilityFilter, + withResultOfAvailabilityCheck, } from '#composite/control-flow'; import { + fillMissingListItems, + withFilteredList, + withFlattenedList, + withIndexInList, + withMappedList, + withPropertiesFromObject, + withPropertyFromList, + withPropertyFromObject, +} from '#composite/data'; + +import { withRecontextualizedContributionList, withRedatedContributionList, withResolvedContribs, + withResolvedReference, } from '#composite/wiki-data'; import { @@ -52,7 +78,6 @@ import { reverseReferenceList, simpleDate, simpleString, - singleReference, soupyFind, soupyReverse, thing, @@ -62,26 +87,22 @@ import { } from '#composite/wiki-properties'; import { - exitWithoutUniqueCoverArt, inheritContributionListFromMainRelease, inheritFromMainRelease, - withAllReleases, - withAlwaysReferenceByDirectory, - withContainingTrackSection, - withCoverArtistContribs, - withDate, - withDirectorySuffix, - withHasUniqueCoverArt, - withMainRelease, - withOtherReleases, - withPropertyFromAlbum, - withSuffixDirectoryFromAlbum, - withTrackArtDate, - withTrackNumber, } from '#composite/things/track'; export class Track extends Thing { static [Thing.referenceType] = 'track'; + static [Thing.wikiData] = 'trackData'; + + static [Thing.constitutibleProperties] = [ + // Contributions currently aren't being observed for constitution. + // 'artistContribs', // from main release or album + // 'contributorContribs', // from main release + // 'coverArtistContribs', // from main release + + 'trackArtworks', // from inline fields + ]; static [Thing.getPropertyDescriptors] = ({ AdditionalFile, @@ -91,265 +112,370 @@ export class Track extends Thing { Artwork, CommentaryEntry, CreditingSourcesEntry, - Flash, LyricsEntry, + ReferencingSourcesEntry, TrackSection, WikiInfo, }) => ({ - // Update & expose - - name: name('Unnamed Track'), + // > Update & expose - Internal relationships - directory: [ - withDirectorySuffix(), + album: thing(V(Album)), + trackSection: thing(V(TrackSection)), - directory({ - suffix: '#directorySuffix', - }), - ], + // > Update & expose - Identifying metadata - suffixDirectoryFromAlbum: [ - { - dependencies: [ - input.updateValue({validate: isBoolean}), - ], + name: name(V('Unnamed Track')), + nameText: contentString(), - compute: (continuation, { - [input.updateValue()]: value, - }) => continuation({ - ['#flagValue']: value ?? false, - }), - }, + directory: directory({ + suffix: 'directorySuffix', + }), - withSuffixDirectoryFromAlbum({ - flagValue: '#flagValue', + suffixDirectoryFromAlbum: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - exposeDependency({ - dependency: '#suffixDirectoryFromAlbum', - }) + withPropertyFromObject('trackSection', V('suffixTrackDirectories')), + exposeDependency('#trackSection.suffixTrackDirectories'), ], - album: thing({ - class: input.value(Album), - }), - - additionalNames: thingList({ - class: input.value(AdditionalName), - }), - - bandcampTrackIdentifier: simpleString(), - bandcampArtworkIdentifier: simpleString(), - - duration: duration(), - urls: urls(), - dateFirstReleased: simpleDate(), - - 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(isColor), + validate: input.value(isBoolean), }), - withContainingTrackSection(), + withPropertyFromObject('album', V('alwaysReferenceTracksByDirectory')), - withPropertyFromObject({ - object: '#trackSection', - property: input.value('color'), + // Falsy mode means this exposes true if the album's property is true, + // but continues if the property is false (which is also the default). + exposeDependencyOrContinue({ + dependency: '#album.alwaysReferenceTracksByDirectory', + mode: input.value('falsy'), }), - exposeDependencyOrContinue({dependency: '#trackSection.color'}), - - withPropertyFromAlbum({ - property: input.value('color'), - }), + exitWithoutDependency('_mainRelease', V(false)), + exitWithoutDependency('mainReleaseTrack', V(false)), - exposeDependency({dependency: '#album.color'}), - ], + withPropertyFromObject('mainReleaseTrack', V('name')), - alwaysReferenceByDirectory: [ - withAlwaysReferenceByDirectory(), - exposeDependency({dependency: '#alwaysReferenceByDirectory'}), + { + dependencies: ['name', '#mainReleaseTrack.name'], + compute: ({ + ['name']: name, + ['#mainReleaseTrack.name']: mainReleaseName, + }) => + getKebabCase(name) === + getKebabCase(mainReleaseName), + }, ], - // 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), + // Album or track. The exposed value is really just what's provided here, + // whether or not a matching track is found on a provided album, for + // example. When presenting or processing, read `mainReleaseTrack`. + mainRelease: [ + exitWithoutUpdateValue({ + validate: input.value( + validateReference(['album', 'track'])), }), - withPropertyFromAlbum({ - property: input.value('trackCoverArtFileExtension'), - }), + { + dependencies: ['name'], + transform: (ref, continuation, {name: ownName}) => + (ref === 'same name single' + ? continuation(ref, { + ['#albumOrTrackReference']: null, + ['#sameNameSingleReference']: ownName, + }) + : continuation(ref, { + ['#albumOrTrackReference']: ref, + ['#sameNameSingleReference']: null, + })), + }, - exposeDependencyOrContinue({dependency: '#album.trackCoverArtFileExtension'}), + withResolvedReference({ + ref: '#albumOrTrackReference', + find: soupyFind.input('trackMainReleasesOnly'), + }).outputs({ + '#resolvedReference': '#matchingTrack', + }), - exposeConstant({ - value: input.value('jpg'), + withResolvedReference({ + ref: '#albumOrTrackReference', + find: soupyFind.input('album'), + }).outputs({ + '#resolvedReference': '#matchingAlbum', }), - ], - coverArtDate: [ - withTrackArtDate({ - from: input.updateValue({ - validate: isDate, + withResolvedReference({ + ref: '#sameNameSingleReference', + find: soupyFind.input('albumSinglesOnly'), + findOptions: input.value({ + fuzz: { + capitalization: true, + kebab: true, + }, }), + }).outputs({ + '#resolvedReference': '#sameNameSingle', }), - exposeDependency({dependency: '#trackArtDate'}), - ], + exposeDependencyOrContinue('#sameNameSingle'), - coverArtDimensions: [ - exitWithoutUniqueCoverArt(), + { + dependencies: [ + '#matchingTrack', + '#matchingAlbum', + ], - exposeUpdateValueOrContinue(), + compute: (continuation, { + ['#matchingTrack']: matchingTrack, + ['#matchingAlbum']: matchingAlbum, + }) => + (matchingTrack && matchingAlbum + ? continuation() + : matchingTrack ?? matchingAlbum + ? matchingTrack ?? matchingAlbum + : null), + }, - withPropertyFromAlbum({ - property: input.value('trackDimensions'), - }), + withPropertyFromObject( '#matchingAlbum', V('tracks')), - exposeDependencyOrContinue({dependency: '#album.trackDimensions'}), + { + dependencies: [ + '#matchingAlbum.tracks', + '#matchingTrack', + ], - dimensions(), + compute: ({ + ['#matchingAlbum.tracks']: matchingAlbumTracks, + ['#matchingTrack']: matchingTrack, + }) => + (matchingAlbumTracks.includes(matchingTrack) + ? matchingTrack + : null), + }, ], - commentary: thingList({ - class: input.value(CommentaryEntry), - }), + bandcampTrackIdentifier: simpleString(), + bandcampArtworkIdentifier: simpleString(), - creditSources: thingList({ - class: input.value(CreditingSourcesEntry), - }), + additionalNames: thingList(V(AdditionalName)), - lyrics: [ - // TODO: Inherited lyrics are literally the same objects, so of course - // their .thing properties aren't going to point back to this one, and - // certainly couldn't be recontextualized... - inheritFromMainRelease(), + dateFirstReleased: simpleDate(), - thingList({ - class: input.value(LyricsEntry), + // > Update & expose - Credits and contributors + + artistText: [ + exposeUpdateValueOrContinue({ + validate: input.value(isContentString), }), - ], - additionalFiles: thingList({ - class: input.value(AdditionalFile), - }), + withPropertyFromObject('album', V('trackArtistText')), + exposeDependency('#album.trackArtistText'), + ], - sheetMusicFiles: thingList({ - class: input.value(AdditionalFile), - }), + artistTextInLists: [ + exposeUpdateValueOrContinue({ + validate: input.value(isContentString), + }), - midiProjectFiles: thingList({ - class: input.value(AdditionalFile), - }), + exposeDependencyOrContinue('_artistText'), - mainReleaseTrack: singleReference({ - class: input.value(Track), - find: soupyFind.input('track'), - }), + withPropertyFromObject('album', V('trackArtistText')), + exposeDependency('#album.trackArtistText'), + ], artistContribs: [ - inheritContributionListFromMainRelease(), - - withDate(), - withResolvedContribs({ from: input.updateValue({validate: isContributionList}), + date: 'date', thingProperty: input.thisProperty(), artistProperty: input.value('trackArtistContributions'), - date: '#date', }).outputs({ '#resolvedContribs': '#artistContribs', }), - exposeDependencyOrContinue({ - dependency: '#artistContribs', - mode: input.value('empty'), - }), + exposeDependencyOrContinue('#artistContribs', V('empty')), - withPropertyFromAlbum({ - property: input.value('artistContribs'), - }), + // Specifically inherit artist contributions later than artist contribs. + // Secondary releases' artists may differ from the main release. + inheritContributionListFromMainRelease(), + + withPropertyFromObject('album', V('trackArtistContribs')), withRecontextualizedContributionList({ - list: '#album.artistContribs', + list: '#album.trackArtistContribs', artistProperty: input.value('trackArtistContributions'), }), withRedatedContributionList({ - list: '#album.artistContribs', - date: '#date', + list: '#album.trackArtistContribs', + date: 'date', }), - exposeDependency({dependency: '#album.artistContribs'}), + exposeDependency('#album.trackArtistContribs'), ], contributorContribs: [ inheritContributionListFromMainRelease(), - withDate(), - contributionList({ - date: '#date', + date: 'date', artistProperty: input.value('trackContributorContributions'), }), ], - coverArtistContribs: [ - withCoverArtistContribs({ - from: input.updateValue({ - validate: isContributionList, - }), + // > Update & expose - General configuration + + countInArtistTotals: [ + exposeUpdateValueOrContinue({ + validate: input.value(isBoolean), }), - exposeDependency({dependency: '#coverArtistContribs'}), + withPropertyFromObject('trackSection', V('countTracksInArtistTotals')), + exposeDependency('#trackSection.countTracksInArtistTotals'), ], - referencedTracks: [ - inheritFromMainRelease({ - notFoundValue: input.value([]), - }), + disableUniqueCoverArt: flag(V(false)), + disableDate: flag(V(false)), - referenceList({ - class: input.value(Track), - find: soupyFind.input('track'), + // > Update & expose - General metadata + + duration: duration(), + + color: [ + exposeUpdateValueOrContinue({ + validate: input.value(isColor), }), + + withPropertyFromObject('trackSection', V('color')), + exposeDependencyOrContinue('#trackSection.color'), + + withPropertyFromObject('album', V('color')), + exposeDependency('#album.color'), ], - sampledTracks: [ - inheritFromMainRelease({ - notFoundValue: input.value([]), + needsLyrics: [ + exposeUpdateValueOrContinue({ + mode: input.value('falsy'), + validate: input.value(isBoolean), }), - referenceList({ - class: input.value(Track), - find: soupyFind.input('track'), + exitWithoutDependency('_lyrics', { + value: input.value(false), + mode: input.value('empty'), }), + + withPropertyFromList('_lyrics', V('helpNeeded')), + + { + dependencies: ['#lyrics.helpNeeded'], + compute: ({ + ['#lyrics.helpNeeded']: helpNeeded, + }) => + helpNeeded.includes(true) + }, ], + urls: urls(), + + // > Update & expose - Artworks + trackArtworks: [ - exitWithoutUniqueCoverArt({ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), constitutibleArtworkList.fromYAMLFieldSpec .call(this, 'Track Artwork'), ], + coverArtistContribs: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value([]), + mode: input.value('falsy'), + }), + + withResolvedContribs({ + from: input.updateValue({validate: isContributionList}), + date: 'coverArtDate', + thingProperty: input.value('coverArtistContribs'), + artistProperty: input.value('trackCoverArtistContributions'), + }), + + exposeDependencyOrContinue('#resolvedContribs', V('empty')), + + withPropertyFromObject('album', V('trackCoverArtistContribs')), + + withRecontextualizedContributionList({ + list: '#album.trackCoverArtistContribs', + artistProperty: input.value('trackCoverArtistContributions'), + }), + + withRedatedContributionList({ + list: '#album.trackCoverArtistContribs', + date: 'coverArtDate', + }), + + exposeDependency('#album.trackCoverArtistContribs'), + ], + + coverArtDate: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + exposeUpdateValueOrContinue({ + validate: input.value(isDate), + }), + + withPropertyFromObject('album', V('trackArtDate')), + exposeDependencyOrContinue('#album.trackArtDate'), + + exposeDependency('date'), + ], + + coverArtFileExtension: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + exposeUpdateValueOrContinue({ + validate: input.value(isFileExtension), + }), + + withPropertyFromObject('album', V('trackCoverArtFileExtension')), + exposeDependencyOrContinue('#album.trackCoverArtFileExtension'), + + exposeConstant(V('jpg')), + ], + + coverArtDimensions: [ + exitWithoutDependency('hasUniqueCoverArt', { + value: input.value(null), + mode: input.value('falsy'), + }), + + exposeUpdateValueOrContinue(), + + withPropertyFromObject('album', V('trackDimensions')), + exposeDependencyOrContinue('#album.trackDimensions'), + + dimensions(), + ], + artTags: [ - exitWithoutUniqueCoverArt({ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), referenceList({ @@ -359,67 +485,341 @@ export class Track extends Thing { ], referencedArtworks: [ - exitWithoutUniqueCoverArt({ + exitWithoutDependency('hasUniqueCoverArt', { value: input.value([]), + mode: input.value('falsy'), }), referencedArtworkList(), ], - // Update only + // > Update & expose - Referenced tracks + + previousProductionTracks: [ + inheritFromMainRelease(), + + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), + }), + ], + + referencedTracks: [ + inheritFromMainRelease(), + + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), + }), + ], + + sampledTracks: [ + inheritFromMainRelease(), + + referenceList({ + class: input.value(Track), + find: soupyFind.input('trackMainReleasesOnly'), + }), + ], + + // > Update & expose - Additional files + + additionalFiles: thingList(V(AdditionalFile)), + sheetMusicFiles: thingList(V(AdditionalFile)), + midiProjectFiles: thingList(V(AdditionalFile)), + + // > Update & expose - Content entries + + lyrics: [ + // TODO: Inherited lyrics are literally the same objects, so of course + // their .thing properties aren't going to point back to this one, and + // certainly couldn't be recontextualized... + inheritFromMainRelease(), + + thingList(V(LyricsEntry)), + ], + + commentary: thingList(V(CommentaryEntry)), + creditingSources: thingList(V(CreditingSourcesEntry)), + referencingSources: thingList(V(ReferencingSourcesEntry)), + + // > Update only find: soupyFind(), reverse: soupyReverse(), // used for referencedArtworkList (mixedFind) - artworkData: wikiData({ - class: input.value(Artwork), - }), - - // used for withAlwaysReferenceByDirectory (for some reason) - trackData: wikiData({ - class: input.value(Track), - }), + artworkData: wikiData(V(Artwork)), // used for withMatchingContributionPresets (indirectly by Contribution) - wikiInfo: thing({ - class: input.value(WikiInfo), - }), + wikiInfo: thing(V(WikiInfo)), - // Expose only + // > Expose only + + isTrack: exposeConstant(V(true)), commentatorArtists: commentatorArtists(), + directorySuffix: [ + exitWithoutDependency('suffixDirectoryFromAlbum', { + value: input.value(null), + mode: input.value('falsy'), + }), + + withPropertyFromObject('trackSection', V('directorySuffix')), + exposeDependency('#trackSection.directorySuffix'), + ], + date: [ - withDate(), - exposeDependency({dependency: '#date'}), + { + dependencies: ['disableDate'], + compute: (continuation, {disableDate}) => + (disableDate + ? null + : continuation()), + }, + + exposeDependencyOrContinue('dateFirstReleased'), + + withPropertyFromObject('album', V('date')), + exposeDependency('#album.date'), ], trackNumber: [ - withTrackNumber(), - exposeDependency({dependency: '#trackNumber'}), + // Zero is the fallback, not one, but in most albums the first track + // (and its intended output by this composition) will be one. + + exitWithoutDependency('trackSection', V(0)), + withPropertiesFromObject('trackSection', V(['tracks', 'startCountingFrom'])), + + withIndexInList('#trackSection.tracks', input.myself()), + exitWithoutDependency('#index', V(0), V('index')), + + { + dependencies: ['#trackSection.startCountingFrom', '#index'], + compute: ({ + ['#trackSection.startCountingFrom']: startCountingFrom, + ['#index']: index, + }) => startCountingFrom + index, + }, ], + // 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 is based only around the presence of *specified* + // cover artist contributions, not whether the references to artists on those + // contributions actually resolve to anything. It completely evades interacting + // with find/replace. hasUniqueCoverArt: [ - withHasUniqueCoverArt(), - exposeDependency({dependency: '#hasUniqueCoverArt'}), - ], + { + dependencies: ['disableUniqueCoverArt'], + compute: (continuation, {disableUniqueCoverArt}) => + (disableUniqueCoverArt + ? false + : continuation()), + }, + + withResultOfAvailabilityCheck({ + from: '_coverArtistContribs', + mode: input.value('empty'), + }), + + { + dependencies: ['#availability'], + compute: (continuation, { + ['#availability']: availability, + }) => + (availability + ? true + : continuation()), + }, + + withPropertyFromObject('album', { + property: input.value('trackCoverArtistContribs'), + internal: input.value(true), + }), - isMainRelease: [ - withMainRelease(), + withResultOfAvailabilityCheck({ + from: '#album.trackCoverArtistContribs', + mode: input.value('empty'), + }), + + { + dependencies: ['#availability'], + compute: (continuation, { + ['#availability']: availability, + }) => + (availability + ? true + : continuation()), + }, + + exitWithoutDependency('_trackArtworks', { + value: input.value(false), + mode: input.value('empty'), + }), + + withPropertyFromList('_trackArtworks', { + property: input.value('artistContribs'), + internal: input.value(true), + }), + + // Since we're getting the update value for each artwork's artistContribs, + // it may not be set at all, and in that case won't be exposing as []. + fillMissingListItems('#trackArtworks.artistContribs', V([])), + + withFlattenedList('#trackArtworks.artistContribs'), exposeWhetherDependencyAvailable({ - dependency: '#mainRelease', - negate: input.value(true), + dependency: '#flattenedList', + mode: input.value('empty'), }), ], - isSecondaryRelease: [ - withMainRelease(), + isMainRelease: + exposeWhetherDependencyAvailable({ + dependency: 'mainReleaseTrack', + negate: input.value(true), + }), + isSecondaryRelease: exposeWhetherDependencyAvailable({ - dependency: '#mainRelease', + dependency: 'mainReleaseTrack', }), + + mainReleaseTrack: [ + exitWithoutDependency('mainRelease'), + + withPropertyFromObject('mainRelease', V('isTrack')), + + { + dependencies: ['mainRelease', '#mainRelease.isTrack'], + compute: (continuation, { + ['mainRelease']: mainRelease, + ['#mainRelease.isTrack']: mainReleaseIsTrack, + }) => + (mainReleaseIsTrack + ? mainRelease + : continuation()), + }, + + { + dependencies: ['name', '_directory'], + compute: (continuation, { + ['name']: ownName, + ['_directory']: ownDirectory, + }) => { + const ownNameKebabed = getKebabCase(ownName); + + return continuation({ + ['#mapItsNameLikeName']: + name => getKebabCase(name) === ownNameKebabed, + + ['#mapItsDirectoryLikeDirectory']: + (ownDirectory + ? directory => directory === ownDirectory + : () => false), + + ['#mapItsNameLikeDirectory']: + (ownDirectory + ? name => getKebabCase(name) === ownDirectory + : () => false), + + ['#mapItsDirectoryLikeName']: + directory => directory === ownNameKebabed, + }); + }, + }, + + withPropertyFromObject('mainRelease', V('tracks')), + + withPropertyFromList('#mainRelease.tracks', { + property: input.value('mainRelease'), + internal: input.value(true), + }), + + withAvailabilityFilter({from: '#mainRelease.tracks.mainRelease'}), + + withMappedList({ + list: '#availabilityFilter', + map: input.value(item => !item), + }).outputs({ + '#mappedList': '#availabilityFilter', + }), + + withFilteredList('#mainRelease.tracks', '#availabilityFilter') + .outputs({'#filteredList': '#mainRelease.tracks'}), + + withPropertyFromList('#mainRelease.tracks', V('name')), + + withPropertyFromList('#mainRelease.tracks', { + property: input.value('directory'), + internal: input.value(true), + }), + + withMappedList('#mainRelease.tracks.name', '#mapItsNameLikeName') + .outputs({'#mappedList': '#filterItsNameLikeName'}), + + withMappedList('#mainRelease.tracks.directory', '#mapItsDirectoryLikeDirectory') + .outputs({'#mappedList': '#filterItsDirectoryLikeDirectory'}), + + withMappedList('#mainRelease.tracks.name', '#mapItsNameLikeDirectory') + .outputs({'#mappedList': '#filterItsNameLikeDirectory'}), + + withMappedList('#mainRelease.tracks.directory', '#mapItsDirectoryLikeName') + .outputs({'#mappedList': '#filterItsDirectoryLikeName'}), + + withFilteredList('#mainRelease.tracks', '#filterItsNameLikeName') + .outputs({'#filteredList': '#matchingItsNameLikeName'}), + + withFilteredList('#mainRelease.tracks', '#filterItsDirectoryLikeDirectory') + .outputs({'#filteredList': '#matchingItsDirectoryLikeDirectory'}), + + withFilteredList('#mainRelease.tracks', '#filterItsNameLikeDirectory') + .outputs({'#filteredList': '#matchingItsNameLikeDirectory'}), + + withFilteredList('#mainRelease.tracks', '#filterItsDirectoryLikeName') + .outputs({'#filteredList': '#matchingItsDirectoryLikeName'}), + + { + dependencies: [ + '#matchingItsNameLikeName', + '#matchingItsDirectoryLikeDirectory', + '#matchingItsNameLikeDirectory', + '#matchingItsDirectoryLikeName', + ], + + compute: (continuation, { + ['#matchingItsNameLikeName']: NLN, + ['#matchingItsDirectoryLikeDirectory']: DLD, + ['#matchingItsNameLikeDirectory']: NLD, + ['#matchingItsDirectoryLikeName']: DLN, + }) => continuation({ + ['#mainReleaseTrack']: + onlyItem(DLD) ?? + onlyItem(NLN) ?? + onlyItem(DLN) ?? + onlyItem(NLD) ?? + null, + }), + }, + + { + dependencies: ['#mainReleaseTrack', input.myself()], + compute: ({ + ['#mainReleaseTrack']: mainReleaseTrack, + [input.myself()]: thisTrack, + }) => + (mainReleaseTrack === thisTrack + ? null + : mainReleaseTrack), + }, ], // Only has any value for main releases, because secondary releases @@ -429,15 +829,70 @@ export class Track extends Thing { }), allReleases: [ - withAllReleases(), - exposeDependency({dependency: '#allReleases'}), + { + dependencies: [ + 'mainReleaseTrack', + 'secondaryReleases', + input.myself(), + ], + + compute: (continuation, { + mainReleaseTrack, + secondaryReleases, + [input.myself()]: thisTrack, + }) => + (mainReleaseTrack + ? continuation({ + ['#mainReleaseTrack']: mainReleaseTrack, + ['#secondaryReleaseTracks']: mainReleaseTrack.secondaryReleases, + }) + : continuation({ + ['#mainReleaseTrack']: thisTrack, + ['#secondaryReleaseTracks']: secondaryReleases, + })), + }, + + { + dependencies: [ + '#mainReleaseTrack', + '#secondaryReleaseTracks', + ], + + compute: ({ + ['#mainReleaseTrack']: mainReleaseTrack, + ['#secondaryReleaseTracks']: secondaryReleaseTracks, + }) => + sortByDate([mainReleaseTrack, ...secondaryReleaseTracks]), + }, ], otherReleases: [ - withOtherReleases(), - exposeDependency({dependency: '#otherReleases'}), + { + dependencies: [input.myself(), 'allReleases'], + compute: ({ + [input.myself()]: thisTrack, + ['allReleases']: allReleases, + }) => + allReleases.filter(track => track !== thisTrack), + }, + ], + + commentaryFromMainRelease: [ + exitWithoutDependency('mainReleaseTrack', V([])), + + withPropertyFromObject('mainReleaseTrack', V('commentary')), + exposeDependency('#mainReleaseTrack.commentary'), + ], + + groups: [ + withPropertyFromObject('album', V('groups')), + exposeDependency('#album.groups'), ], + followingProductionTracks: reverseReferenceList({ + reverse: soupyReverse.input('tracksWhichAreFollowingProductionsOf'), + }), + referencedByTracks: reverseReferenceList({ reverse: soupyReverse.input('tracksWhichReference'), }), @@ -453,14 +908,14 @@ export class Track extends Thing { static [Thing.yamlDocumentSpec] = { fields: { + // Identifying metadata + 'Track': {property: 'name'}, + 'Track Text': {property: 'nameText'}, 'Directory': {property: 'directory'}, 'Suffix Directory': {property: 'suffixDirectoryFromAlbum'}, - - 'Additional Names': { - property: 'additionalNames', - transform: parseAdditionalNames, - }, + 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, + 'Main Release': {property: 'mainRelease'}, 'Bandcamp Track ID': { property: 'bandcampTrackIdentifier', @@ -472,17 +927,86 @@ export class Track extends Thing { transform: String, }, + 'Additional Names': { + property: 'additionalNames', + transform: parseAdditionalNames, + }, + + 'Date First Released': { + property: 'dateFirstReleased', + transform: parseDate, + }, + + // Credits and contributors + + 'Artist Text': {property: 'artistText'}, + 'Artist Text In Lists': {property: 'artistTextInLists'}, + + 'Artists': { + property: 'artistContribs', + transform: parseContributors, + }, + + 'Contributors': { + property: 'contributorContribs', + transform: parseContributors, + }, + + // General configuration + + 'Count In Artist Totals': {property: 'countInArtistTotals'}, + + 'Has Cover Art': { + property: 'disableUniqueCoverArt', + transform: value => + (typeof value === 'boolean' + ? !value + : value), + }, + + 'Has Date': { + property: 'disableDate', + transform: value => + (typeof value === 'boolean' + ? !value + : value), + }, + + // General metadata + 'Duration': { property: 'duration', transform: parseDuration, }, 'Color': {property: 'color'}, + + 'Needs Lyrics': { + property: 'needsLyrics', + }, + 'URLs': {property: 'urls'}, - 'Date First Released': { - property: 'dateFirstReleased', - transform: parseDate, + // Artworks + + 'Track Artwork': { + property: 'trackArtworks', + transform: + parseArtwork({ + thingProperty: 'trackArtworks', + dimensionsFromThingProperty: 'coverArtDimensions', + fileExtensionFromThingProperty: 'coverArtFileExtension', + dateFromThingProperty: 'coverArtDate', + artTagsFromThingProperty: 'artTags', + referencedArtworksFromThingProperty: 'referencedArtworks', + artistContribsFromThingProperty: 'coverArtistContribs', + artistContribsArtistProperty: 'trackCoverArtistContributions', + }), + }, + + 'Cover Artists': { + property: 'coverArtistContribs', + transform: parseContributors, }, 'Cover Art Date': { @@ -497,30 +1021,20 @@ export class Track extends Thing { transform: parseDimensions, }, - 'Has Cover Art': { - property: 'disableUniqueCoverArt', - transform: value => - (typeof value === 'boolean' - ? !value - : value), - }, - - 'Always Reference By Directory': {property: 'alwaysReferenceByDirectory'}, + 'Art Tags': {property: 'artTags'}, - 'Lyrics': { - property: 'lyrics', - transform: parseLyrics, + 'Referenced Artworks': { + property: 'referencedArtworks', + transform: parseAnnotatedReferences, }, - 'Commentary': { - property: 'commentary', - transform: parseCommentary, - }, + // Referenced tracks - 'Credit Sources': { - property: 'creditSources', - transform: parseCreditingSources, - }, + 'Previous Productions': {property: 'previousProductionTracks'}, + 'Referenced Tracks': {property: 'referencedTracks'}, + 'Sampled Tracks': {property: 'sampledTracks'}, + + // Additional files 'Additional Files': { property: 'additionalFiles', @@ -537,54 +1051,41 @@ export class Track extends Thing { transform: parseAdditionalFiles, }, - 'Main Release': {property: 'mainReleaseTrack'}, - 'Referenced Tracks': {property: 'referencedTracks'}, - 'Sampled Tracks': {property: 'sampledTracks'}, + // Content entries - 'Referenced Artworks': { - property: 'referencedArtworks', - transform: parseAnnotatedReferences, - }, - - 'Franchises': {ignore: true}, - 'Inherit Franchises': {ignore: true}, - - 'Artists': { - property: 'artistContribs', - transform: parseContributors, + 'Lyrics': { + property: 'lyrics', + transform: parseLyrics, }, - 'Contributors': { - property: 'contributorContribs', - transform: parseContributors, + 'Commentary': { + property: 'commentary', + transform: parseCommentary, }, - 'Cover Artists': { - property: 'coverArtistContribs', - transform: parseContributors, + 'Crediting Sources': { + property: 'creditingSources', + transform: parseCreditingSources, }, - 'Track Artwork': { - property: 'trackArtworks', - transform: - parseArtwork({ - thingProperty: 'trackArtworks', - dimensionsFromThingProperty: 'coverArtDimensions', - fileExtensionFromThingProperty: 'coverArtFileExtension', - dateFromThingProperty: 'coverArtDate', - artTagsFromThingProperty: 'artTags', - referencedArtworksFromThingProperty: 'referencedArtworks', - artistContribsFromThingProperty: 'coverArtistContribs', - artistContribsArtistProperty: 'trackCoverArtistContributions', - }), + 'Referencing Sources': { + property: 'referencingSources', + transform: parseReferencingSources, }, - 'Art Tags': {property: 'artTags'}, + // Shenanigans + 'Franchises': {ignore: true}, + 'Inherit Franchises': {ignore: true}, 'Review Points': {ignore: true}, }, invalidFieldCombinations: [ + {message: `Secondary releases never count in artist totals`, fields: [ + 'Main Release', + 'Count In Artist Totals', + ]}, + {message: `Secondary releases inherit references from the main one`, fields: [ 'Main Release', 'Referenced Tracks', @@ -595,11 +1096,6 @@ export class Track extends Thing { 'Sampled Tracks', ]}, - {message: `Secondary releases inherit artists from the main one`, fields: [ - 'Main Release', - 'Artists', - ]}, - {message: `Secondary releases inherit contributors from the main one`, fields: [ 'Main Release', 'Contributors', @@ -641,7 +1137,7 @@ export class Track extends Thing { bindTo: 'trackData', include: track => - !CacheableObject.getUpdateValue(track, 'mainReleaseTrack'), + !CacheableObject.getUpdateValue(track, 'mainRelease'), // It's still necessary to check alwaysReferenceByDirectory here, since // it may be set manually (with `Always Reference By Directory: true`), @@ -741,6 +1237,13 @@ export class Track extends Thing { referencing: track => track.isSecondaryRelease ? [track] : [], referenced: track => [track.mainReleaseTrack], }, + + tracksWhichAreFollowingProductionsOf: { + bindTo: 'trackData', + + referencing: track => track.isMainRelease ? [track] : [], + referenced: track => track.previousProductionTracks, + }, }; // Track YAML loading is handled in album.js. @@ -771,12 +1274,36 @@ export class Track extends Thing { ]; } + countOwnContributionInContributionTotals(_contrib) { + if (!this.countInArtistTotals) { + return false; + } + + if (this.isSecondaryRelease) { + return false; + } + + return true; + } + + countOwnContributionInDurationTotals(_contrib) { + if (!this.countInArtistTotals) { + return false; + } + + if (this.isSecondaryRelease) { + return false; + } + + return true; + } + [inspect.custom](depth) { const parts = []; parts.push(Thing.prototype[inspect.custom].apply(this)); - if (CacheableObject.getUpdateValue(this, 'mainReleaseTrack')) { + if (CacheableObject.getUpdateValue(this, 'mainRelease')) { parts.unshift(`${colors.yellow('[secrelease]')} `); } diff --git a/src/data/things/wiki-info.js b/src/data/things/wiki-info.js index 590598be..26b69ba6 100644 --- a/src/data/things/wiki-info.js +++ b/src/data/things/wiki-info.js @@ -1,29 +1,35 @@ export const WIKI_INFO_FILE = 'wiki-info.yaml'; -import {input} from '#composite'; +import {input, V} from '#composite'; import Thing from '#thing'; -import {parseContributionPresets} from '#yaml'; +import {isBoolean, isContributionPresetList, isLanguageCode, isName} + from '#validators'; +import {parseContributionPresets, parseWallpaperParts} from '#yaml'; + +import {exitWithoutDependency, exposeConstant} from '#composite/control-flow'; import { - isBoolean, - isColor, - isContributionPresetList, - isLanguageCode, - isName, - isURL, -} from '#validators'; - -import {exitWithoutDependency} from '#composite/control-flow'; -import {contentString, flag, name, referenceList, soupyFind} - from '#composite/wiki-properties'; + canonicalBase, + color, + contentString, + fileExtension, + flag, + name, + referenceList, + simpleString, + soupyFind, + wallpaperParts, +} from '#composite/wiki-properties'; export class WikiInfo extends Thing { static [Thing.friendlyName] = `Wiki Info`; + static [Thing.wikiData] = 'wikiInfo'; + static [Thing.oneInstancePerWiki] = true; static [Thing.getPropertyDescriptors] = ({Group}) => ({ // Update & expose - name: name('Unnamed Wiki'), + name: name(V('Unnamed Wiki')), // Displayed in nav bar. nameShort: { @@ -36,14 +42,7 @@ export class WikiInfo extends Thing { }, }, - color: { - flags: {update: true, expose: true}, - update: {validate: isColor}, - - expose: { - transform: color => color ?? '#0088ff', - }, - }, + color: color(V('#0088ff')), // One-line description used for <meta rel="description"> tag. description: contentString(), @@ -55,18 +54,12 @@ export class WikiInfo extends Thing { update: {validate: isLanguageCode}, }, - canonicalBase: { - flags: {update: true, expose: true}, - update: {validate: isURL}, - expose: { - transform: (value) => - (value === null - ? null - : value.endsWith('/') - ? value - : value + '/'), - }, - }, + canonicalBase: canonicalBase(), + canonicalMediaBase: canonicalBase(), + + wikiWallpaperFileExtension: fileExtension(V('jpg')), + wikiWallpaperStyle: simpleString(), + wikiWallpaperParts: wallpaperParts(), divideTrackListsByGroups: referenceList({ class: input.value(Group), @@ -79,20 +72,19 @@ export class WikiInfo extends Thing { }, // Feature toggles - enableFlashesAndGames: flag(false), - enableListings: flag(false), - enableNews: flag(false), - enableArtTagUI: flag(false), - enableGroupUI: flag(false), + enableFlashesAndGames: flag(V(false)), + enableListings: flag(V(false)), + enableNews: flag(V(false)), + enableArtTagUI: flag(V(false)), + enableGroupUI: flag(V(false)), enableSearch: [ - exitWithoutDependency({ - dependency: 'searchDataAvailable', - mode: input.value('falsy'), + exitWithoutDependency('_searchDataAvailable', { value: input.value(false), + mode: input.value('falsy'), }), - flag(true), + flag(V(true)), ], // Update only @@ -106,24 +98,45 @@ export class WikiInfo extends Thing { default: false, }, }, + + // Expose only + + isWikiInfo: exposeConstant(V(true)), }); static [Thing.yamlDocumentSpec] = { fields: { 'Name': {property: 'name'}, 'Short Name': {property: 'nameShort'}, + 'Color': {property: 'color'}, + 'Description': {property: 'description'}, + 'Footer Content': {property: 'footerContent'}, + 'Default Language': {property: 'defaultLanguage'}, + 'Canonical Base': {property: 'canonicalBase'}, - 'Divide Track Lists By Groups': {property: 'divideTrackListsByGroups'}, + 'Canonical Media Base': {property: 'canonicalMediaBase'}, + + 'Wiki Wallpaper File Extension': {property: 'wikiWallpaperFileExtension'}, + + 'Wiki Wallpaper Style': {property: 'wikiWallpaperStyle'}, + + 'Wiki Wallpaper Parts': { + property: 'wikiWallpaperParts', + transform: parseWallpaperParts, + }, + 'Enable Flashes & Games': {property: 'enableFlashesAndGames'}, 'Enable Listings': {property: 'enableListings'}, 'Enable News': {property: 'enableNews'}, 'Enable Art Tag UI': {property: 'enableArtTagUI'}, 'Enable Group UI': {property: 'enableGroupUI'}, + 'Divide Track Lists By Groups': {property: 'divideTrackListsByGroups'}, + 'Contribution Presets': { property: 'contributionPresets', transform: parseContributionPresets, @@ -140,13 +153,5 @@ export class WikiInfo extends Thing { documentMode: oneDocumentTotal, documentThing: WikiInfo, - - save(wikiInfo) { - if (!wikiInfo) { - return; - } - - return {wikiInfo}; - }, }); } |