chore: normalize formatting

This commit is contained in:
Cory Dransfeldt 2024-10-19 19:50:10 -07:00
parent 01ed2ac3b3
commit 2f6cfbe7ae
No known key found for this signature in database
61 changed files with 921 additions and 743 deletions

View file

@ -1,37 +1,45 @@
import { DateTime } from 'luxon'
import ics from 'ics'
import { DateTime } from "luxon";
import ics from "ics";
export const albumReleasesCalendar = (collection) => {
const collectionData = collection.getAll()[0]
const { data } = collectionData
const { albumReleases: { all } } = data
if (!all || all.length === 0) return ''
const collectionData = collection.getAll()[0];
const { data } = collectionData;
const {
albumReleases: { all },
} = data;
if (!all || all.length === 0) return "";
const events = all.map(album => {
const date = DateTime.fromISO(album['release_date'])
if (!date.isValid) return null
const events = all
.map((album) => {
const date = DateTime.fromISO(album["release_date"]);
if (!date.isValid) return null;
return {
start: [date.year, date.month, date.day],
startInputType: 'local',
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`,
timestamp: DateTime.now().toUTC().toFormat("yyyyMMdd'T'HHmmss'Z'")
}
}).filter(event => event !== null)
return {
start: [date.year, date.month, date.day],
startInputType: "local",
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`,
timestamp: DateTime.now().toUTC().toFormat("yyyyMMdd'T'HHmmss'Z'"),
};
})
.filter((event) => event !== null);
const { error, value } = ics.createEvents(events, { calName: 'Album releases calendar / coryd.dev' })
const { error, value } = ics.createEvents(events, {
calName: "Album releases calendar / coryd.dev",
});
if (error) {
console.error('Error creating events: ', error)
console.error("Error creating events: ", error);
events.forEach((event, index) => {
console.error(`Event ${index}:`, event)
})
return ''
console.error(`Event ${index}:`, event);
});
return "";
}
return value
}
return value;
};

View file

@ -1,59 +1,75 @@
import fs from 'fs'
import path from 'path'
import { minify } from 'terser'
import fs from "fs";
import path from "path";
import { minify } from "terser";
const errorPages = ['404', '500', '1000', 'broken', 'error', 'js-challenge', 'not-allowed', 'rate-limit']
const errorPages = [
"404",
"500",
"1000",
"broken",
"error",
"js-challenge",
"not-allowed",
"rate-limit",
];
export const copyErrorPages = () => {
errorPages.forEach((errorPage) => {
const sourcePath = path.join('_site', errorPage, 'index.html')
const destinationPath = path.join('_site', `${errorPage}.html`)
const directoryPath = path.join('_site', errorPage)
const sourcePath = path.join("_site", errorPage, "index.html");
const destinationPath = path.join("_site", `${errorPage}.html`);
const directoryPath = path.join("_site", errorPage);
fs.copyFile(sourcePath, destinationPath, (err) => {
if (err) {
console.error(`Error copying ${errorPage} page:`, err)
return
console.error(`Error copying ${errorPage} page:`, err);
return;
}
fs.unlink(sourcePath, (unlinkErr) => {
if (unlinkErr) {
console.error(`Error deleting source file for ${errorPage} page:`, unlinkErr)
return
console.error(
`Error deleting source file for ${errorPage} page:`,
unlinkErr
);
return;
}
fs.rmdir(directoryPath, (rmdirErr) => {
if (rmdirErr) console.error(`Error removing directory for ${errorPage} page:`, rmdirErr)
})
})
})
})
}
if (rmdirErr)
console.error(
`Error removing directory for ${errorPage} page:`,
rmdirErr
);
});
});
});
});
};
export const minifyJsComponents = async () => {
const scriptsDir = '_site/assets/scripts'
const scriptsDir = "_site/assets/scripts";
const minifyJsFilesInDir = async (dir) => {
const files = fs.readdirSync(dir)
const files = fs.readdirSync(dir);
for (const fileName of files) {
const filePath = path.join(dir, fileName)
const stat = fs.statSync(filePath)
const filePath = path.join(dir, fileName);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
await minifyJsFilesInDir(filePath)
} else if (fileName.endsWith('.js')) {
const fileContent = fs.readFileSync(filePath, 'utf8')
const minified = await minify(fileContent)
await minifyJsFilesInDir(filePath);
} else if (fileName.endsWith(".js")) {
const fileContent = fs.readFileSync(filePath, "utf8");
const minified = await minify(fileContent);
if (minified.error) {
console.error(`Error minifying ${filePath}:`, minified.error)
console.error(`Error minifying ${filePath}:`, minified.error);
} else {
fs.writeFileSync(filePath, minified.code)
fs.writeFileSync(filePath, minified.code);
}
} else {
console.log(`No .js files to minify in ${filePath}`)
console.log(`No .js files to minify in ${filePath}`);
}
}
}
};
await minifyJsFilesInDir(scriptsDir)
}
await minifyJsFilesInDir(scriptsDir);
};

View file

@ -1,26 +1,26 @@
export default {
stringToRFC822Date: (dateString) => {
const date = new Date(dateString)
const date = new Date(dateString);
if (isNaN(date)) return ''
if (isNaN(date)) return "";
const options = {
weekday: 'short',
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('en-GB', options)
weekday: "short",
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZoneName: "short",
};
const formatter = new Intl.DateTimeFormat("en-GB", options);
return formatter.format(date).replace(',', '')
return formatter.format(date).replace(",", "");
},
stringToRFC3339: (dateString) => {
const date = new Date(dateString)
const date = new Date(dateString);
return isNaN(date) ? '' : date.toISOString()
}
}
return isNaN(date) ? "" : date.toISOString();
},
};

View file

@ -1,18 +1,19 @@
import truncateHtml from 'truncate-html'
import { shuffleArray } from '../utilities/index.js'
import truncateHtml from "truncate-html";
import { shuffleArray } from "../utilities/index.js";
export default {
encodeAmp: (string) => {
if (!string) return
const pattern = /&(?!(?:[a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+);)/g
const replacement = '&'
return string.replace(pattern, replacement)
if (!string) return;
const pattern = /&(?!(?:[a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+);)/g;
const replacement = "&";
return string.replace(pattern, replacement);
},
replaceQuotes: (string) => string.replace(/"/g, '"'),
formatNumber: (number) => number.toLocaleString('en-US'),
htmlTruncate: (content, limit = 50) => truncateHtml(content, limit, {
byWords: true,
ellipsis: '...'
}),
replaceQuotes: (string) => string.replace(/"/g, """),
formatNumber: (number) => number.toLocaleString("en-US"),
htmlTruncate: (content, limit = 50) =>
truncateHtml(content, limit, {
byWords: true,
ellipsis: "...",
}),
shuffleArray,
}
};

View file

@ -1,11 +1,11 @@
import dates from './dates.js'
import general from './general.js'
import media from './media.js'
import navigation from './navigation.js'
import dates from "./dates.js";
import general from "./general.js";
import media from "./media.js";
import navigation from "./navigation.js";
export default {
...dates,
...general,
...media,
...navigation,
}
};

View file

@ -1,35 +1,43 @@
export default {
filterBooksByStatus: (books, status) => books.filter(book => book['status'] === status),
findFavoriteBooks: (books) => books.filter(book => book['favorite'] === true),
bookYearLinks: (years) => years
.sort((a, b) => b['value'] - a['value'])
.map((year, index) => `<a href="/books/years/${year['value']}">${year['value']}</a>${index < years.length - 1 ? ' / ' : ''}`)
.join(''),
filterBooksByStatus: (books, status) =>
books.filter((book) => book["status"] === status),
findFavoriteBooks: (books) =>
books.filter((book) => book["favorite"] === true),
bookYearLinks: (years) =>
years
.sort((a, b) => b["value"] - a["value"])
.map(
(year, index) =>
`<a href="/books/years/${year["value"]}">${year["value"]}</a>${
index < years.length - 1 ? " / " : ""
}`
)
.join(""),
mediaLinks: (data, type, count = 10) => {
if (!data || !type) return ''
if (!data || !type) return "";
const dataSlice = data.slice(0, count)
if (dataSlice.length === 0) return null
const dataSlice = data.slice(0, count);
if (dataSlice.length === 0) return null;
const buildLink = (item) => {
switch (type) {
case 'genre':
return `<a href="${item['genre_url']}">${item['genre_name']}</a>`
case 'artist':
return `<a href="${item['url']}">${item['name']}</a>`
case 'book':
return `<a href="${item['url']}">${item['title']}</a>`
case "genre":
return `<a href="${item["genre_url"]}">${item["genre_name"]}</a>`;
case "artist":
return `<a href="${item["url"]}">${item["name"]}</a>`;
case "book":
return `<a href="${item["url"]}">${item["title"]}</a>`;
default:
return ''
return "";
}
}
};
if (dataSlice.length === 1) return buildLink(dataSlice[0])
if (dataSlice.length === 1) return buildLink(dataSlice[0]);
const links = dataSlice.map(buildLink)
const allButLast = links.slice(0, -1).join(', ')
const last = links[links.length - 1]
const links = dataSlice.map(buildLink);
const allButLast = links.slice(0, -1).join(", ");
const last = links[links.length - 1];
return `${allButLast} and ${last}`
}
}
return `${allButLast} and ${last}`;
},
};

View file

@ -1,3 +1,5 @@
export default {
isLinkActive: (category, page) => page.includes(category) && page.split('/').filter(a => a !== '').length <= 1
}
isLinkActive: (category, page) =>
page.includes(category) &&
page.split("/").filter((a) => a !== "").length <= 1,
};

View file

@ -1,33 +1,33 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import postcss from 'postcss'
import postcssImport from 'postcss-import'
import postcssImportExtGlob from 'postcss-import-ext-glob'
import autoprefixer from 'autoprefixer'
import cssnano from 'cssnano'
import fs from "node:fs/promises";
import path from "node:path";
import postcss from "postcss";
import postcssImport from "postcss-import";
import postcssImportExtGlob from "postcss-import-ext-glob";
import autoprefixer from "autoprefixer";
import cssnano from "cssnano";
export const cssConfig = (eleventyConfig) => {
eleventyConfig.addTemplateFormats('css')
eleventyConfig.addExtension('css', {
outputFileExtension: 'css',
eleventyConfig.addTemplateFormats("css");
eleventyConfig.addExtension("css", {
outputFileExtension: "css",
compile: async (inputContent, inputPath) => {
const outputPath = '_site/assets/css/index.css'
const outputPath = "_site/assets/css/index.css";
if (inputPath.endsWith('index.css')) {
if (inputPath.endsWith("index.css")) {
return async () => {
let result = await postcss([
postcssImportExtGlob,
postcssImport,
autoprefixer,
cssnano,
]).process(inputContent, { from: inputPath })
]).process(inputContent, { from: inputPath });
await fs.mkdir(path.dirname(outputPath), { recursive: true })
await fs.writeFile(outputPath, result.css)
await fs.mkdir(path.dirname(outputPath), { recursive: true });
await fs.writeFile(outputPath, result.css);
return result.css
}
return result.css;
};
}
},
})
}
});
};

View file

@ -1,27 +1,28 @@
export const shuffleArray = array => {
const shuffled = [...array]
export const shuffleArray = (array) => {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1))
let temp = shuffled[i]
shuffled[i] = shuffled[j]
shuffled[j] = temp
let j = Math.floor(Math.random() * (i + 1));
let temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
return shuffled
}
return shuffled;
};
export const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
export const regionNames = new Intl.DisplayNames(["en"], { type: "region" });
export const getCountryName = (countryCode) => regionNames.of(countryCode.trim()) || countryCode.trim()
export const getCountryName = (countryCode) =>
regionNames.of(countryCode.trim()) || countryCode.trim();
export const parseCountryField = (countryField) => {
if (!countryField) return null
if (!countryField) return null;
const delimiters = [',', '/', '&', 'and']
let countries = [countryField]
const delimiters = [",", "/", "&", "and"];
let countries = [countryField];
delimiters.forEach(delimiter => {
countries = countries.flatMap(country => country.split(delimiter))
})
delimiters.forEach((delimiter) => {
countries = countries.flatMap((country) => country.split(delimiter));
});
return countries.map(getCountryName).join(', ')
}
return countries.map(getCountryName).join(", ");
};