Files
leecat.art/_config/filters.js

93 lines
2.4 KiB
JavaScript
Raw Normal View History

import { DateTime } from "luxon";
2026-05-14 09:19:05 -07:00
export default function (eleventyConfig) {
2026-02-19 12:07:10 -08:00
// Return the keys used in an object
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter("getKeys", (target) => {
2026-02-19 12:07:10 -08:00
return Object.keys(target);
});
/* Exclude all posts with given URLs from a collection list */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter(
"excludeFromCollection",
function (collection = [], urls = [this.ctx.page.url]) {
return collection.filter((post) => urls.indexOf(post.url) === -1);
},
);
/* Filter a collection by a set of tags, returning any that share one or more tags */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter(
"filterByTags",
function (collection = [], ...requiredTags) {
return collection.filter((post) => {
return requiredTags.flat().some((tag) => post.data.tags.includes(tag));
});
},
);
/* Return n elements from a list */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter("head", (collection = [], n) => {
if (!Array.isArray(collection) || collection.length === 0) {
return [];
}
2026-05-14 09:19:05 -07:00
if (n < 0) {
return collection.slice(n);
}
return collection.slice(0, n);
});
/* For <time> elements */
eleventyConfig.addFilter("htmlDateString", (dateObj) => {
2026-05-14 09:19:05 -07:00
return DateTime.fromJSDate(dateObj, { zone: "utc" }).toFormat("yyyy-LL-dd");
});
/* What it says on the tin */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter("randomize", function (array) {
// Create a copy of the array to avoid modifying the original
let shuffledArray = array.slice();
// Fisher-Yates shuffle algorithm
for (let i = shuffledArray.length - 1; i > 0; i--) {
2026-05-14 09:19:05 -07:00
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [
shuffledArray[j],
shuffledArray[i],
];
}
return shuffledArray;
});
2026-02-19 12:07:10 -08:00
/* Human-readable dates */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter("readableDate", (dateObj) => {
2026-05-14 09:18:15 -07:00
return DateTime.fromJSDate(dateObj, { zone: "utc" }).toLocaleString(
DateTime.DATE_FULL,
);
2026-02-19 12:07:10 -08:00
});
/* Filter out structural tags */
eleventyConfig.addFilter("removeBasicTags", (tags) => {
2026-05-14 09:19:05 -07:00
return tags.filter(
(tag) =>
[
"all",
"posts",
"gallery",
"reference",
"tagPagination",
"blur",
].indexOf(tag) === -1,
);
});
2026-02-19 12:07:10 -08:00
/* What it says on the tin */
2026-05-14 09:19:05 -07:00
eleventyConfig.addFilter("sortAlphabetically", (strings) =>
(strings || []).sort((b, a) => b.localeCompare(a)),
2026-02-19 12:07:10 -08:00
);
2026-02-20 08:02:52 -08:00
/* Remove year from image filenames for OG metadata file path */
2026-02-19 17:54:01 -08:00
eleventyConfig.addFilter("toOgFilename", (filename) => {
return filename.split("/")[1];
2026-02-19 21:07:01 -08:00
});
2026-05-14 09:19:05 -07:00
}