feat: massive refactor

This commit is contained in:
Cory Dransfeldt 2024-10-09 18:10:28 -07:00
parent d424082c95
commit 1880790c05
No known key found for this signature in database
38 changed files with 245 additions and 761 deletions

View file

@ -6,6 +6,7 @@ const BASE_URL = 'https://coryd.dev'
const md = markdownIt()
const normalizeWord = (word) => {
if (!word) return ''
const wordMap = {
'ai': 'AI',
'css': 'CSS',
@ -14,12 +15,12 @@ const normalizeWord = (word) => {
'macos': 'macOS',
'tv': 'TV'
}
return wordMap[word.toLowerCase()] || word.charAt(0).toUpperCase() + word.slice(1)
return wordMap[word?.toLowerCase()] || word?.charAt(0).toUpperCase() + word.slice(1)
}
const tagsToHashtags = (item) => {
const tags = item?.tags || []
if (tags.length) return tags.map(tag => '#' + tag.split(' ').map(normalizeWord).join('')).join(' ')
const tags = item?.['tags'] || []
if (tags.length) return tags.map(tag => '#' + normalizeWord(tag)).join(' ')
return ''
}
@ -40,7 +41,7 @@ export const processContent = (collection) => {
{ method: 'fromISO' },
{ method: 'fromFormat', format: 'yyyy-MM-dd' },
{ method: 'fromFormat', format: 'MM/dd/yyyy' },
{ method: 'fromFormat', format: 'dd-MM-yyyy' },
{ method: 'fromFormat', format: 'dd-MM-yyyy' }
]
for (const { method, format } of formats) {
@ -115,16 +116,16 @@ export const processContent = (collection) => {
if (item['type'] === 'album-release') hashTags = ' #Music #NewMusic'
if (item['type'] === 'concert') hashTags = ' #Music #Concert'
if (item?.['authors']?.['mastodon']) {
const mastoUrl = new URL(item['authors']['mastodon'])
if (item?.['author']?.['mastodon']) {
const mastoUrl = new URL(item['author']['mastodon'])
attribution = `${mastoUrl.pathname.replace('/', '')}@${mastoUrl.host}`
} else if (item?.['authors']?.['name']) {
attribution = item['authors']['name']
} else if (item?.['author']?.['name']) {
attribution = item['author']['name']
}
let url = item['url'] || item['link']
if (url && !isValidUrl(url)) url = absoluteUrl(url)
if (item['type'] === 'concert') url = `${item['artistUrl'] ? item['artistUrl'] : BASE_URL + '/music/concerts'}?t=${DateTime.fromISO(item['date']).toMillis()}${item['artistUrl'] ? '#concerts' : ''}`
if (item['type'] === 'concert') url = `${item['artist']?.['url'] ? item['artist']['url'] : BASE_URL + '/music/concerts'}?t=${DateTime.fromISO(item['date']).toMillis()}${item['artist']?.['url'] ? '#concerts' : ''}`
const content = {
url,
@ -149,12 +150,12 @@ export const processContent = (collection) => {
}
const movieData = movies['movies'].filter((movie) => movie['rating'])
const showData = tv['shows'].filter((show) => show['episodes']?.[0]?.['last_watched_at'])
const bookData = books.all.filter((book) => book['rating'])
const showData = tv['shows'].filter((show) => show?.['episode']?.['formatted_episode'])
const bookData = books['all'].filter((book) => book['rating'])
addItemToIndex(posts, '📝', (item) => item['url'], (item) => item['title'], (item) => item['tags'])
addItemToIndex(links, '🔗', (item) => item['link'], (item) => item['title'], (item) => item['tags'])
addItemToIndex(artists, '🎙️', (item) => item['url'], (item) => `${item['name']} (${item['country']}) - ${item['genre']['name']}`, (item) => `['${item['genre']}']`)
addItemToIndex(artists, '🎙️', (item) => item['url'], (item) => `${item['name']} (${item['country']}) - ${item['genre']?.['name']}`, (item) => `['${item['genre']}']`)
addItemToIndex(genres, '🎵', (item) => item['url'], (item) => item['name'], (item) => item.artists.map(artist => artist['name_string']))
if (movieData) addItemToIndex(movieData, '🎥', (item) => item['url'], (item) => `${item['title']} (${item['rating']})`, (item) => item['tags'])
if (showData) addItemToIndex(showData, '📺', (item) => item['url'], (item) => `${item['title']} (${item['year']})`, (item) => item['tags'])
@ -167,13 +168,13 @@ export const processContent = (collection) => {
addContent(concerts, '🎤', (item) => `${item['artistNameString'] ? item['artistNameString'] : item['artist']['name']} at ${item['venue']['name'].split(',')[0].trim()}`, (item) => item['date'])
addContent([...albumReleases['current']].reverse(), '📆', (item) => `${item['title']} by ${item['artist']['name']}`, (item) => item['release_date'])
addSiteMapContent(posts, (item) => item.title, (item) => item.date)
addSiteMapContent(pages, (item) => item.title, (item) => item.date)
addSiteMapContent(artists, (item) => item.name, (item) => item.date)
addSiteMapContent(genres, (item) => item.name, (item) => item.date)
addSiteMapContent(movies['movies'], (item) => item.title, (item) => item.date)
addSiteMapContent(books.all, (item) => item.title, (item) => item.date)
addSiteMapContent(tv?.['shows'], (item) => item.title, (item) => item.date)
addSiteMapContent(posts, (item) => item['title'], (item) => item['date'])
addSiteMapContent(pages, (item) => item['title'], (item) => item['date'])
addSiteMapContent(artists, (item) => item['name'], (item) => item['date'])
addSiteMapContent(genres, (item) => item['name'], (item) => item['date'])
addSiteMapContent(movies['movies'], (item) => item['title'], (item) => item['date'])
addSiteMapContent(books.all, (item) => item['title'], (item) => item['date'])
addSiteMapContent(tv?.['shows'], (item) => item['title'], (item) => item['date'])
return {
searchIndex,
@ -197,7 +198,7 @@ export const albumReleasesCalendar = (collection) => {
if (!all || all.length === 0) return ''
const events = all.map(album => {
const date = DateTime.fromFormat(album.date, 'MMMM d, yyyy')
const date = DateTime.fromFormat(album['date'], 'MMMM d, yyyy')
if (!date.isValid) return null
return {
@ -206,8 +207,8 @@ export const albumReleasesCalendar = (collection) => {
startOutputType: 'local',
title: `Release: ${album['artist']['name']} - ${album['title']}`,
description: `Check out this new album release: ${album['url']}. Read more about ${album['artist']['name']} at https://coryd.dev${album['artist']['url']}`,
url: album.url,
uid: `${date.toFormat('yyyyMMdd')}-${album['artist']['name']}-${album.title}@coryd.dev`,
url: album['url'],
uid: `${date.toFormat('yyyyMMdd')}-${album['artist']['name']}-${album['title']}@coryd.dev`,
timestamp: DateTime.now().toUTC().toFormat("yyyyMMdd'T'HHmmss'Z'")
}
}).filter(event => event !== null)

View file

@ -14,13 +14,13 @@ export default {
const md = markdownIt({ html: true, linkify: true })
md.use(markdownItAnchor, {
level: [1, 2],
permalink: markdownItAnchor.permalink.headerLink({ safariReaderFix: true })
permalink: markdownItAnchor['permalink']['headerLink']({ safariReaderFix: true })
})
md.use(markdownItFootnote)
md.renderer.rules.footnote_ref = (tokens, idx) => `<sup>${tokens[idx].meta.id + 1}</sup>`
md.renderer.rules.footnote_block_open = () => '<hr class="footnotes-sep">\n<section class="footnotes">\n<ol class="footnotes-list">\n'
md.renderer.rules.footnote_open = (tokens, idx) => `<li id="fn${tokens[idx].meta.id + 1}" class="footnote-item"> `
md.renderer.rules.footnote_anchor = () => ''
md.renderer['rules']['footnote_ref'] = (tokens, idx) => `<sup>${tokens[idx]['meta']['id'] + 1}</sup>`
md.renderer['rules']['footnote_block_open'] = () => '<hr class="footnotes-sep">\n<section class="footnotes">\n<ol class="footnotes-list">\n'
md.renderer['rules']['footnote_open'] = (tokens, idx) => `<li id="fn${tokens[idx]['meta']['id'] + 1}" class="footnote-item"> `
md.renderer['rules']['footnote_anchor'] = () => ''
return md
}
@ -30,7 +30,7 @@ export default {
const md = mdGenerator()
const dateKey = Object.keys(entry).find(key => key.includes('date'))
const {
artist, authors, backdrop, content, description, image, link, rating, review,
artist, author, backdrop, content, description, image, link, rating, review,
slug, title, url, tags, type
} = entry
@ -41,36 +41,36 @@ export default {
}
const feedNote = '<hr/><p>This is a full text feed, but not all content can be rendered perfectly within the feed. If something looks off, feel free to <a href="https://coryd.dev">visit my site</a> for the original post.</p>'
processedEntry.url = (url?.includes('http')) ? url : new URL(slug || url, BASE_URL).toString()
processedEntry['url'] = (url?.includes('http')) ? url : new URL(slug || url, BASE_URL).toString()
if (link) {
processedEntry.title = `${title} via ${authors?.name || 'Unknown'}`
processedEntry.url = link
processedEntry.author = {
name: authors?.name || 'Unknown',
url: authors?.url || '',
mastodon: authors?.mastodon || '',
rss: authors?.rss_feed || ''
processedEntry['title'] = `${title} via ${author?.['name'] || 'Unknown'}`
processedEntry['url'] = link
processedEntry['author'] = {
name: author?.['name'] || 'Unknown',
url: author?.['url'] || '',
mastodon: author?.['mastodon'] || '',
rss: author?.['rss_feed'] || ''
}
processedEntry.excerpt = sanitizeHtml(md.render(description || ''))
processedEntry['excerpt'] = sanitizeHtml(md.render(description || ''))
} else if (['book', 'movie'].includes(type)) {
processedEntry.excerpt = sanitizeHtml(md.render(review || description || ''))
processedEntry['excerpt'] = sanitizeHtml(md.render(review || description || ''))
} else if (type === 'album-release') {
let sanitizedDescription = sanitizeHtml(md.render(description || ''))
let truncatedDescription = truncate(sanitizedDescription, { length: 500, reserveLastWord: true, ellipsis: '...' })
if (sanitizedDescription.length > 500) truncatedDescription += ` <p><a href="${artist?.url}">Read more about ${artist?.name}</a></p>`
processedEntry.excerpt = truncatedDescription
if (artist?.['name'] && artist?.['url'] && sanitizedDescription.length > 500) truncatedDescription += ` <p><a href="${artist['url']}">Read more about ${artist['name']}</a></p>`
processedEntry['excerpt'] = truncatedDescription
} else if (slug && content) {
processedEntry.excerpt = sanitizeHtml(md.render(content) + feedNote, { disallowedTagsMode: 'completelyDiscard' })
processedEntry['excerpt'] = sanitizeHtml(md.render(content) + feedNote, { disallowedTagsMode: 'completelyDiscard' })
} else if (description) {
processedEntry.excerpt = description
processedEntry['excerpt'] = description
}
processedEntry.image = backdrop || image
processedEntry['image'] = backdrop || image
if (rating) processedEntry.rating = rating
if (tags) processedEntry.tags = tags
if (type === 'album-release' && artist) processedEntry.title = `${title} by ${artist['name']}`
if (rating) processedEntry['rating'] = rating
if (tags) processedEntry['tags'] = tags
if (type === 'album-release' && artist) processedEntry['title'] = `${title} by ${artist['name']}`
posts.push(processedEntry)
})

View file

@ -10,6 +10,7 @@ export default {
const mediaData = limit ? media.slice(0, limit) : media
return mediaData.map((item) => {
let normalized = {
title: item['title'],
image: item['image'],
url: item['url'],
type: item['type']
@ -17,22 +18,18 @@ export default {
switch (item['type']) {
case 'artist':
normalized.title = item['title']
normalized.alt = `${item['plays']} plays of ${item['title']}`
normalized.subtext = `${item['plays']} plays`
break
case 'album':
normalized.title = item['title']
normalized.alt = `${item['title']} by ${item['artist']}`
normalized.subtext = `${item['artist']}`
break
case 'album-release':
normalized.title = item['title']
normalized.alt = `${item['title']} by ${item['artist']['name']}`
normalized.subtext = `${item['artist']['name']} / ${item['date']}`
break
case 'movie':
normalized.title = item['title']
normalized.alt = item['title']
normalized.rating = item['rating']
normalized.favorite = item['favorite']
@ -46,10 +43,8 @@ export default {
}
break
case 'tv':
case 'tv-range':
normalized.title = item['name']
normalized.alt = `${item['subtext']} ${item['type'] === 'tv' ? 'of' : 'from'} ${item['name']}`
normalized.subtext = item['subtext']
normalized.alt = item['formatted_episode']
normalized.subtext = item['formatted_episode']
break
}
@ -57,29 +52,16 @@ export default {
})
},
calculatePlayPercentage: (plays, mostPlayed) => `${plays/mostPlayed * 100}%`,
bookStatus: (books, status) => books.filter(book => book.status === status),
bookStatus: (books, status) => books.filter(book => book['status'] === status),
bookFavorites: (books) => books.filter(book => book.favorite === true),
bookYearLinks: (years) => years.sort((a, b) => b.value - a.value).map((year, index) => {
const separator = index < years.length - 1 ? ' / ' : ''
return `<a href="/books/years/${year.value}">${year.value}</a>${separator}`
}).join(''),
bookSortDescending: (books) => books.filter(book => !isNaN(DateTime.fromISO(book.date).toMillis())).sort((a, b) => {
const dateA = DateTime.fromISO(a.date)
const dateB = DateTime.fromISO(b.date)
return dateB - dateA
}),
bookFinishedYear: (books, year) => books.filter(book => {
if (book.status === 'finished' && book.date) return parseInt(book.date.split('-')[0]) === year
if (book['status'] === 'finished' && book['year']) return parseInt(book['year']) === parseInt(year)
return ''
}),
currentBookCount: (books) => {
const year = DateTime.now().year
return books.filter(book => {
if (book.status === 'finished' && book.date) return parseInt(book.date.split('-')[0]) === year
return ''
}).length
},
getLastWatched: (show) => show?.['episodes'][show['episodes']?.length - 1]?.['last_watched_at'],
sortByPlaysDescending: (data, key) => data.sort((a, b) => b[key] - a[key]),
mediaLinks: (data, type, count = 10) => {
if (!data || !type) return ''