Utility Functions
Relevant source files
The following files were used as context for generating this wiki page:
Utility functions in the Charlotte project encapsulate common, reusable logic, promoting a clean and maintainable codebase. These helpers are primarily located in the src/utils/ directory and handle tasks such as content processing, URL generation, and user settings management. By abstracting this logic, the main components and pages can focus on their primary responsibilities, leading to a more modular and scalable architecture.
This document provides a technical overview of the key utility modules, their functions, and their interactions within the application.
Content Utilities
The content-utils.ts module is central to fetching and organizing the blog's content, including posts, tags, and categories. It interacts directly with Astro's content collections API.
Sources: src/utils/content-utils.ts
Key Functions
| Function | Description |
|---|---|
getSortedPosts() | Fetches all non-draft posts, sorts them by publication date (newest first), applies pinned post ordering, and injects next/previous post slugs and titles. |
getSortedPostsList() | Similar to getSortedPosts but returns a lighter version of the post objects without the body, optimized for list views. |
getTagList() | Aggregates all tags from all posts, counts their occurrences, and returns a sorted list of unique tags. |
getCategoryList() | Aggregates all categories, counts post occurrences for each, handles uncategorized posts, and returns a sorted list of categories with their corresponding URLs. |
Sources: src/utils/content-utils.ts:77-195
Pinned Post Logic
The application supports pinning posts to the top of the main list. This logic is handled within getSortedPosts and getSortedPostsList by the applyPinnedOrdering function.
- Retrieve Pinned Slugs: It reads the
pinnedPostarray fromsiteConfig. - Filter Posts: It separates the date-sorted posts into two groups: those whose slugs match the pinned list and all others.
- Order and Combine: It orders the pinned posts according to their sequence in the
siteConfigarray and then appends the remaining (non-pinned) posts. - Set
isPinnedFlag: A booleanisPinnedproperty is added to the post's data object for use in the UI.
The following diagram illustrates the flow for retrieving and sorting posts, including the pinned post logic.
Category and Tag Aggregation
The getCategoryList function demonstrates how content is aggregated. It iterates through all posts, counts occurrences for each category, and handles posts without a category by assigning them to a localized "uncategorized" group.
URL Utilities
The url-utils.ts module provides helpers for constructing absolute and relative URLs consistently throughout the site, respecting the base path configuration.
Sources: src/utils/url-utils.ts
Core Functions
url(path: string): The main function that takes a relative path and prepends the Astro base path (import.meta.env.BASE_URL) to it, ensuring links work correctly regardless of the deployment subdirectory.getPostUrlBySlug(slug: string): A specialized function that constructs the full URL for a blog post given its slug (e.g.,/posts/my-first-post).getCategoryUrl(category: string): Creates a URL for a category archive page, properly encoding the category name to be used as a query parameter (e.g.,/archive?category=My+Category).
This diagram shows how a final post URL is generated.
Settings Utilities
User-facing settings, such as the color scheme (theme), are managed by functions in setting-utils.ts. These utilities interact with localStorage to persist user preferences and manipulate the DOM to apply them.
Sources: src/utils/setting-utils.ts
Theme Management
The theme system supports three modes: light, dark, and auto (system preference).
| Function | Description |
|---|---|
getStoredTheme() | Retrieves the user's theme preference from localStorage. If not set, it returns the defaultTheme from siteConfig. |
setTheme(mode) | Stores the selected theme mode (light, dark, or auto) in localStorage and calls applyThemeToDocument to update the UI. |
applyThemeToDocument(mode) | Applies the theme by adding or removing the dark class on the <html> element based on the selected mode and the system's prefers-color-scheme media query. |
Sources: src/utils/setting-utils.ts:10-40
The sequence diagram below shows the process of a user switching the theme.
Script Utilities
The project includes utility scripts in the scripts/ directory for development and content management tasks.
Sources: scripts/new-post.js
New Post Creation
The scripts/new-post.js script automates the creation of new Markdown post files. It accepts a filename as an argument and generates a new .md file in src/content/posts/ with pre-populated frontmatter.
A key utility function within this script is getDate(), which formats the current date into a YYYY-MM-DD string for the published field.
// from scripts/new-post.js
function getDate() {
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0");
const day = String(today.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
Sources: scripts/new-post.js:6-14
The script ensures a file extension is present, creates subdirectories if needed, and prevents overwriting existing files.
Sources: scripts/new-post.js:16-47
Miscellaneous Utilities
Other small, single-purpose utilities are used across the application, such as for generating RSS/Atom feeds.
XML Character Stripping
In the RSS and Atom feed generation files, a utility function stripInvalidXmlChars is defined to remove control characters that are invalid in XML documents, preventing feed parsing errors. This ensures that post content is safe for inclusion in the feeds.
// from src/pages/rss.xml.ts
function stripInvalidXmlChars(str: string): string {
return str.replace(
// biome-ignore lint/suspicious/noControlCharactersInRegex: https://www.w3.org/TR/xml/#charsets
/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]/g,
"",
);
}
Sources: src/pages/rss.xml.ts:11-17, src/pages/atom.xml.ts:11-17
Conclusion
The utility functions in the Charlotte project are essential for abstracting complexity and ensuring consistency. By centralizing logic for content management, URL construction, settings persistence, and data sanitization, the utilities provide a robust foundation for the rest of the application. This separation of concerns makes the codebase easier to understand, test, and extend.