diff --git a/bun_plugins/onImport-markdown-loader.ts b/bun_plugins/onImport-markdown-loader.ts deleted file mode 100644 index 72e933e..0000000 --- a/bun_plugins/onImport-markdown-loader.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { main, type BunPlugin } from 'bun'; -import { loadMetadata } from "./utils"; -import matter from 'gray-matter'; -import { marked } from 'marked'; -import { AppShell } from "../src/frontend/AppShell"; -import AppShellPage from "../src/frontend/AppShell.html" with { type: "text" }; -import { renderToString } from "react-dom/server"; - -const markdownLoader: BunPlugin = { - name: 'markdown-loader', - setup(build) { - // Plugin implementation - build.onLoad({filter: /\.md$/}, async args => { - console.log("Loading markdown file:", args.path); - const {data, content } = matter(await Bun.file(args.path).text()); - loadMetadata(args.path, data); - const html = marked.parse(content); - - // JSX Approach - console.log(renderToString(AppShell({ post: html }))) - return { - contents: renderToString(AppShell({ post: html })), - loader: 'html', - }; - }); - }, -}; - -export default markdownLoader; diff --git a/bun_plugins/onImport-markdown-loader.tsx b/bun_plugins/onImport-markdown-loader.tsx new file mode 100644 index 0000000..57d42fc --- /dev/null +++ b/bun_plugins/onImport-markdown-loader.tsx @@ -0,0 +1,52 @@ +import type { BunPlugin } from 'bun'; +import React from 'react'; +import { renderToString } from "react-dom/server"; + +import matter from 'gray-matter'; +import { marked } from 'marked'; +import { addToDatabase } from "../src/db/index"; + +import { AppShell } from "../src/frontend/AppShell"; +import { Post } from "../src/frontend/pages/post"; + +// TODO: Add better type handling for if Markdown parsing fails +const markdownLoader: BunPlugin = { + name: 'markdown-loader', + setup(build) { + // Plugin implementation + build.onLoad({filter: /\.md$/}, async args => { + console.log("Loading markdown file:", args.path); + const {data, content } = matter(await Bun.file(args.path).text()); + + // Remove the title from content if it matches the frontmatter title to avoid duplicate H1s + let processedContent = content; + if (data.title) { + const titleHeadingRegex = new RegExp(`^#\\s+${data.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`, 'm'); + processedContent = content.replace(titleHeadingRegex, '').trim(); + } + + const bodyHtml = await marked.parse(processedContent); + // AppShell is required here for rendering. If used at route level + // Bun will only see an htmlBundle and fail to load anything + // Validate required fields + if (!data.title || !data.date) { + throw new Error(`Markdown files must include title and date in frontmatter: ${args.path}`); + } + const meta = { + title: data.title, + date: new Date(data.date), + readingTime: data.readingTime || `${Math.ceil(content.split(/\s+/).length / 200)} min read` + }; + const renderedHtml = renderToString(); + addToDatabase(args.path, meta, bodyHtml); // Load the post to the database for dynamic querying + + // JSX Approach + return { + contents: renderedHtml, + loader: 'html', + }; + }); + }, +}; + +export default markdownLoader; diff --git a/bun_plugins/onStartup-post-importer.ts b/bun_plugins/onStartup-post-importer.ts index 4a792f2..d1286f9 100644 --- a/bun_plugins/onStartup-post-importer.ts +++ b/bun_plugins/onStartup-post-importer.ts @@ -1,15 +1,28 @@ import matter from 'gray-matter'; -import { loadMetadata } from "./utils"; +import { marked } from 'marked'; +import { addToDatabase } from "../src/db/index"; // When the server starts, import all the blog post metadata into the database // Executed on startup because it's included in ./bunfig.toml +// Only import if not running in production (async () => { + if (process.env.NODE_ENV === 'production') return; + const glob = new Bun.Glob("**/*.md"); for await (const file of glob.scan("./content")) { const {data, content } = matter(await Bun.file(`./content/${file}`).text()); const route = `/${file.replace(/\.md$/, "")}`; - loadMetadata(route, data); + + // Remove the title from content if it matches the frontmatter title to avoid duplicate H1s + let processedContent = content; + if (data.title) { + const titleHeadingRegex = new RegExp(`^#\\s+${data.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`, 'm'); + processedContent = content.replace(titleHeadingRegex, '').trim(); + } + + const bodyHtml = await marked.parse(processedContent); + addToDatabase(route, data, bodyHtml); } console.log('Posts have been imported into db'); diff --git a/bun_plugins/utils.ts b/bun_plugins/utils.ts deleted file mode 100644 index 9051362..0000000 --- a/bun_plugins/utils.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { Database } from 'bun:sqlite'; -import path from 'path'; - -// Initialize the database if it doesn't exist -const dbPath = path.join(process.cwd(), 'blog_metadata.sqlite'); -const db = new Database(dbPath); - -// Create the posts table if it doesn't exist -db.run(` - CREATE TABLE IF NOT EXISTS posts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - path TEXT UNIQUE NOT NULL, - title TEXT, - date TEXT, - author TEXT, - tags TEXT, - published INTEGER, - summary TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP - ) -`); - -// Load metadata from the blog post into a SQLite database -// This allows us to index and make queries against the metadata -// to support functions like search, filtering, and sorting -export function loadMetadata(filePath: string, data: { [key: string]: any }) { - if (!data) return; - - try { - // Extract common fields - const { title, date, author, tags, published, summary } = data; - - // Log the values for debugging - // console.log('Metadata values:', { - // filePath: typeof filePath, - // title: typeof title, - // date: typeof date, - // author: typeof author, - // tags: typeof tags, - // published: typeof published, - // summary: typeof summary - // }); - - // Convert all values to strings or null explicitly - const values = [ - filePath ? String(filePath) : null, - title ? String(title) : null, - date ? String(date) : null, - author ? String(author) : null, - tags ? JSON.stringify(tags) : null, - published !== undefined ? (published ? 1 : 0) : null, - summary ? String(summary) : null - ]; - - // Log the prepared values - // console.log('Prepared values:', values); - - // Query to insert or replace metadata - const query = db.query(` - INSERT OR REPLACE INTO posts - (path, title, date, author, tags, published, summary, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) - `); - - query.run(...values); - - // console.log(`Stored metadata for: ${filePath}`); - } catch (error) { - // console.error(`Failed to store metadata for ${filePath}:`, error); - } -} diff --git a/bunfig.toml b/bunfig.toml index 4563137..918aa15 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -1,4 +1,4 @@ preload = ["./bun_plugins/onStartup-post-importer.ts"] [serve.static] -plugins = ["./bun_plugins/onImport-markdown-loader.ts"] +plugins = ["./bun_plugins/onImport-markdown-loader.tsx"] diff --git a/content/2025/09/typescript-tips.md b/content/2025/09/typescript-tips.md index 3b6522b..615577a 100644 --- a/content/2025/09/typescript-tips.md +++ b/content/2025/09/typescript-tips.md @@ -1,6 +1,7 @@ --- title: 5 TypeScript Tips I Wish I Knew Earlier date: 2025-09-18 +readingTime: 10 minutes tags: [TypeScript, JavaScript, Productivity] excerpt: Five practical TypeScript tips that will make your code more type-safe and your development experience smoother. From utility types to const assertions. draft: false @@ -8,7 +9,7 @@ draft: false # 5 TypeScript Tips I Wish I Knew Earlier -TypeScript is an amazing tool, but it takes time to learn all its features. Here are five tips that significantly improved my TypeScript development. +TypeScript is an amazing tool, but it takes time to learn all its features. Here are five tips that significantly improved my TypeScript development experience. ## 1. Use `satisfies` for Type Checking @@ -105,4 +106,3 @@ Use sparingly and only when you're absolutely sure. These tips have made my TypeScript code more robust and easier to maintain. The key is to leverage TypeScript's type system to catch errors at compile time rather than runtime. What are your favorite TypeScript features? Let me know! - diff --git a/content/2025/10/a-new-post.md b/content/2025/10/a-new-post.md index 201f38a..3e4ff5b 100644 --- a/content/2025/10/a-new-post.md +++ b/content/2025/10/a-new-post.md @@ -1,34 +1,82 @@ --- -title: Your Post Title +title: Modern Development Workflow date: 2025-10-21 -tags: [Web Development, TypeScript] -excerpt: A brief summary of your post (2-3 sentences). This will appear in post listings and search results. +tags: [Web Development, TypeScript, Productivity] +excerpt: Explore modern development workflows that boost productivity and code quality. Learn about hot module replacement, automated testing, and modern tooling. draft: false --- -# Your Post Title +# Modern Development Workflow -Your content here. You can use standard markdown syntax: +In today's fast-paced development environment, having an efficient workflow is crucial for maintaining productivity and code quality. -## Section Heading +## Hot Module Replacement -Write your paragraphs with proper spacing. - -### Subsection - -- Bullet points -- Another point -- And another -- with HMR - -**Bold text** and *italic text* are supported. +Hot Module Replacement (HMR) revolutionizes the development experience: ```typescript -// Code blocks work too -const example = "Hello World"; -console.log(example); +// Vite configuration with HMR +export default { + server: { + hmr: { + overlay: true + } + }, + plugins: [ + reactRefresh() + ] +} + +// During development, changes appear instantly +const Component = () => { + const [count, setCount] = useState(0); + return ( + + ); +}; ``` -> Blockquotes for important callouts or quotes. +## Tool Chain Essentials -This is just a template - delete this file or ignore it when writing your actual posts. +A modern tool chain should include: + +- **Fast builds**: Vite or Bun for lightning-fast compilation +- **Type safety**: TypeScript for catching errors at compile time +- **Code formatting**: Prettier for consistent code style +- **Linting**: ESLint for maintaining code quality + +## Automated Testing + +Integrate testing into your workflow: + +```typescript +// Component testing with React Testing Library +import { render, screen, fireEvent } from '@testing-library/react'; +import Counter from './Counter'; + +test('increment works correctly', () => { + render(); + + const button = screen.getByRole('button'); + fireEvent.click(button); + + expect(screen.getByText('Count: 1')).toBeInTheDocument(); +}); +``` + +## Best Practices + +- **Git hooks**: Pre-commit hooks for code quality checks +- **CI/CD**: Automated testing and deployment +- **Documentation**: Keep README files up to date +- **Code reviews**: Peer reviews for knowledge sharing + +## Conclusion + +A modern development workflow combines the right tools with good practices. Invest time in setting up your environment properly, and it will pay dividends in productivity throughout your project. + +--- + +*This post demonstrates the power of modern development tools and workflows.* diff --git a/index.tsx b/index.tsx index 9a98f1a..1f5105b 100644 --- a/index.tsx +++ b/index.tsx @@ -1,14 +1,69 @@ -import AppShellDemo from "./temp/appshell.html"; +import React from "react"; +// Database connection is now handled by the centralized db module +import { renderToString } from "react-dom/server"; import { AppShell } from "./src/frontend/AppShell"; +import { Home } from "./src/frontend/pages/home"; +import { NotFound } from "./src/frontend/pages/not-found"; +import demo from "./temp/appshell.html"; +import { Post } from "./src/frontend/pages/post"; +import { getPostWithTags } from "./src/db/index"; -async function blogPosts() { +async function blogPosts(hmr: boolean) { const glob = new Bun.Glob("**/*.md"); - const blogPosts: Record = {} + const blogPosts: Record = {}; for await (const file of glob.scan("./content")) { const post = await import(`./content/${file}`, { with: { type: "html" } }); const route = `/${file.replace(/\.md$/, "")}`; - blogPosts[route] = post.default; + if (hmr) { + // Use Bun Importer plugin for hot reloading in the browser + blogPosts[`/hmr${route}`] = post.default; + } else { + // Use the Database for sending just the HTML or the HTML and AppShell + blogPosts[route] = (req: Request) => { + const path = new URL(req.url).pathname; + const post = getPostWithTags(path); + if (!post) + return new Response(renderToString(), { + status: 404, + headers: { "Content-Type": "text/html" }, + }); + + const data = { + title: post.title, + summary: post.summary, + date: new Date(post.date), + readingTime: post.reading_time, + tags: post.tags || [], + }; + + // AppShell is already loaded, just send the
content + if (req.headers.get("shell-loaded") === "true") { + return new Response( + renderToString(), + { + headers: { + "Content-Type": "text/html", + }, + }, + ); + } + + // AppShell is not loaded, send the with the
content inside + return new Response( + renderToString( + + + , + ), + { + headers: { + "Content-Type": "text/html", + }, + }, + ); + }; + } } Object.keys(blogPosts).map((route) => { @@ -20,19 +75,62 @@ async function blogPosts() { Bun.serve({ development: { hmr: true, - console: true + console: true, }, routes: { - "/": AppShellDemo, - ... await blogPosts(), - "/content/*": { - async GET(req: Request) { - // Having trouble using Bun Bundler alongside a custom route handler to send - // different content depending on the request headers, will use /content subpath instead - // (unless I can figure it out) - return new Response("This will send the blog post content without the app shell") + // standard mounting of blog posts + ...(await blogPosts(false)), + + // hot module replacement in development mode + ...(process.env.NODE_ENV === "development" ? (await blogPosts(true)) : []), + + // Home page + "/": (req: Request) => { + // Extract URL parameters from the request to pass to the component + const url = new URL(req.url); + const searchParams = Object.fromEntries(url.searchParams.entries()); + + if (req.headers.get("shell-loaded") === "true") { + return new Response(renderToString(), { + headers: { + "Content-Type": "text/html", + }, + }); } + + return new Response( + renderToString( + + + , + ), + { + headers: { + "Content-Type": "text/html", + }, + }, + ); + }, + "/target": demo, + "/profile-picture.webp": () => { + return new Response(Bun.file("./src/public/profile-picture.webp"), { + headers: { + "Content-Type": "image/webp", + }, + }); + }, + "/*": (req) => { + if(req.headers.get("shell-loaded") === "true") { + return new Response(renderToString(), { + status: 404, + headers: { "Content-Type": "text/html" }, + }); + } + return new Response(renderToString(), { + status: 404, + headers: { "Content-Type": "text/html" }, + }); } - } -}) + }, +}); diff --git a/src/db/db.ts b/src/db/db.ts new file mode 100644 index 0000000..8e940e7 --- /dev/null +++ b/src/db/db.ts @@ -0,0 +1,66 @@ +import { Database } from 'bun:sqlite'; +import path from 'path'; + +// Singleton database connection +class DatabaseConnection { + private static instance: DatabaseConnection; + private db: Database; + + private constructor() { + // Initialize the database if it doesn't exist + const dbPath = path.join(process.cwd(), 'blog.sqlite'); + this.db = new Database(dbPath); + + // Initialize database schema + this.initializeDatabase(); + } + + public static getInstance(): DatabaseConnection { + if (!DatabaseConnection.instance) { + DatabaseConnection.instance = new DatabaseConnection(); + } + return DatabaseConnection.instance; + } + + public getDatabase(): Database { + return this.db; + } + + private initializeDatabase() { + // Create the posts table if it doesn't exist + this.db.run(` + CREATE TABLE IF NOT EXISTS posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + path TEXT UNIQUE NOT NULL, + title TEXT, + date TEXT, + reading_time TEXT, + summary TEXT, + content TEXT + ) + `); + + // Create the tags table if it doesn't exist + this.db.run(` + CREATE TABLE IF NOT EXISTS tags ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL + ) + `); + + // Create the post_tags junction table for many-to-many relationship + this.db.run(` + CREATE TABLE IF NOT EXISTS post_tags ( + post_id INTEGER, + tag_id INTEGER, + PRIMARY KEY (post_id, tag_id), + FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE, + FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE + ) + `); + } +} + +// Get the singleton database instance and export it +const dbConnection = DatabaseConnection.getInstance(); +export const db = dbConnection.getDatabase(); \ No newline at end of file diff --git a/src/db/index.ts b/src/db/index.ts new file mode 100644 index 0000000..4cac106 --- /dev/null +++ b/src/db/index.ts @@ -0,0 +1,7 @@ +// Import the database connection +export { db } from './db'; + +// Export all functions related to database operations +export * from './posts'; +export * from './tags'; +export * from './queries'; \ No newline at end of file diff --git a/src/db/posts.ts b/src/db/posts.ts new file mode 100644 index 0000000..8348aa3 --- /dev/null +++ b/src/db/posts.ts @@ -0,0 +1,165 @@ +import { db } from './db'; +import { getOrCreateTag } from './tags'; +import { getPostTags } from './tags'; + +// Load the blog post into a SQLite database +// This allows us to index and make queries against the metadata +// to support functions like search, filtering, and sorting +// as well as return either the post or the full AppShell with the post content +export function addToDatabase(filePath: string, data: { [key: string]: any }, content: string) { + if (!data) return; + + // Use a transaction to ensure data consistency + const transaction = db.transaction(() => { + try { + // Extract common fields + const { title, date, readingTime, tags, excerpt } = data; + + // Convert all values to strings or null explicitly (except tags) + const values = [ + filePath ? String(filePath) : null, + title ? String(title) : null, + date ? String(date) : null, + readingTime ? String(readingTime) : null, + excerpt ? String(excerpt) : null, + content ? String(content) : null + ]; + + // Query to insert or replace metadata (without tags) + const insertPost = db.query(` + INSERT OR REPLACE INTO posts + (path, title, date, reading_time, summary, content) + VALUES (?, ?, ?, ?, ?, ?) + `); + + insertPost.run(...values); + + // Get the post ID + const getPostId = db.query('SELECT id FROM posts WHERE path = ?'); + const postResult = getPostId.get(filePath) as { id: number } | undefined; + if (!postResult) { + throw new Error(`Failed to retrieve post ID for ${filePath}`); + } + + // Delete existing tag associations for this post + const deleteExistingTags = db.query('DELETE FROM post_tags WHERE post_id = ?'); + deleteExistingTags.run(postResult.id); + + // If tags exist, process them + if (tags && Array.isArray(tags)) { + // Insert into junction table + const insertPostTag = db.query('INSERT OR IGNORE INTO post_tags (post_id, tag_id) VALUES (?, ?)'); + + for (const tag of tags) { + const tagId = getOrCreateTag(String(tag)); + insertPostTag.run(postResult.id, tagId); + } + } + + } catch (error) { + console.error(`Failed to store ${filePath}:`, error); + throw error; // Re-throw to make the transaction fail + } + }); + + // Execute the transaction + try { + transaction(); + } catch (error) { + console.error(`Transaction failed for ${filePath}:`, error); + } +} + +// Returns the total number of posts + +export function getNumOfPosts() { + const queryCount = db.query('SELECT COUNT(*) AS count FROM posts'); + const numPosts = queryCount.get() as { count: number }; + + return numPosts.count; +} + +// Helper function to get post data with tags +export function getPostWithTags(postPath: string) { + const getPost = db.query(` + SELECT * FROM posts WHERE path = ? + `); + + const post = getPost.get(postPath) as any; + if (!post) return null; + + // Get tags for this post + if (post.id) { + post.tags = getPostTags(post.id); + } + + return post; +} + +// Get recent posts +export function getRecentPosts(limit: number = 10, offset: number = 0) { + const query = db.query(` + SELECT * FROM posts + WHERE path NOT LIKE '%.md' + ORDER BY date DESC + LIMIT ? OFFSET ? + `); + + const posts = query.all(limit, offset) as any[]; + + // Add tags to each post and clean up paths + return posts.map(post => ({ + ...post, + tags: getPostTags(post.id), + path: post.path.replace(/^.*\/content\//, '/').replace(/\.md$/, '') + })); +} + +// Get all posts +export function getAllPosts() { + const query = db.query(` + SELECT * FROM posts + ORDER BY date DESC + `); + + const posts = query.all() as any[]; + + // Add tags to each post + return posts.map(post => ({ + ...post, + tags: getPostTags(post.id) + })); +} + +// Helper function to get a post by its path +export function getPostByPath(path: string) { + const query = db.query(` + SELECT * FROM posts + WHERE path = ? + `); + + const post = query.get(path) as any; + if (!post) return null; + + // Get tags for this post + post.tags = getPostTags(post.id); + + return post; +} + +// Helper function to calculate read time +export function calculateReadTime(content: string): number { + const wordsPerMinute = 200; + const words = content.split(/\s+/).length; + return Math.max(1, Math.ceil(words / wordsPerMinute)); +} + +// Helper function to format date for display +export function formatDate(dateString: string): string { + const date = new Date(dateString); + return date.toLocaleDateString('en-US', { + year: 'numeric', + month: 'long', + day: 'numeric' + }); +} diff --git a/src/db/queries.ts b/src/db/queries.ts new file mode 100644 index 0000000..53264da --- /dev/null +++ b/src/db/queries.ts @@ -0,0 +1,109 @@ +import { db } from './db'; +import { parseTags } from './tags'; + +// Interface for blog post +export interface BlogPost { + id: number; + path: string; + title: string; + date: string; + author?: string; + tags: string | string[]; + summary?: string; + reading_time?: string; + content?: string; +} + +// Get posts by a single tag +export function getPostsByTag(tag: string): BlogPost[] { + const query = db.query(` + SELECT p.* FROM posts p + JOIN post_tags pt ON p.id = pt.post_id + JOIN tags t ON pt.tag_id = t.id + WHERE t.name = ? + ORDER BY p.date DESC + `); + + return query.all(tag) as BlogPost[]; +} + +// Get posts by multiple tags (AND logic - posts must contain ALL tags) +export function getPostsByTags(tags: string[]): BlogPost[] { + if (tags.length === 0) { + return getRecentPosts(); + } + + // Build query for multiple tags using JOIN and GROUP BY + const placeholders = tags.map(() => '?').join(','); + const query = db.query(` + SELECT p.* FROM posts p + JOIN post_tags pt ON p.id = pt.post_id + JOIN tags t ON pt.tag_id = t.id + WHERE t.name IN (${placeholders}) + AND p.path NOT LIKE '%.md' + GROUP BY p.id + HAVING COUNT(DISTINCT t.id) = ? + ORDER BY p.date DESC + `); + + return query.all(...tags, tags.length) as BlogPost[]; +} + +// Get recent posts with optional tag filtering +export function getRecentPostsByTags(tags: string[], limit: number = 10): BlogPost[] { + if (tags.length === 0) { + return getRecentPosts(limit); + } + + // Build query for posts with all specified tags + const placeholders = tags.map(() => '?').join(','); + const query = db.query(` + SELECT p.* FROM posts p + JOIN post_tags pt ON p.id = pt.post_id + JOIN tags t ON pt.tag_id = t.id + WHERE t.name IN (${placeholders}) + AND p.path NOT LIKE '%.md' + GROUP BY p.id + HAVING COUNT(DISTINCT t.id) = ? + ORDER BY p.date DESC + LIMIT ? + `); + + return query.all(...tags, tags.length, limit) as BlogPost[]; +} + +// Helper function to get recent posts +function getRecentPosts(limit: number = 10): BlogPost[] { + const query = db.query(` + SELECT * FROM posts + WHERE path NOT LIKE '%.md' + ORDER BY date DESC + LIMIT ? + `); + + return query.all(limit) as BlogPost[]; +} + +// Search posts by title or content +export function searchPosts(query: string, limit: number = 20): BlogPost[] { + const searchQuery = db.query(` + SELECT * FROM posts + WHERE (title LIKE ? OR content LIKE ?) + ORDER BY date DESC + LIMIT ? + `); + + const searchPattern = `%${query}%`; + return searchQuery.all(searchPattern, searchPattern, limit) as BlogPost[]; +} + +// Get posts by date range +export function getPostsByDateRange(startDate: string, endDate: string): BlogPost[] { + const dateQuery = db.query(` + SELECT * FROM posts + WHERE date BETWEEN ? AND ? + ORDER BY date DESC + `); + + return dateQuery.all(startDate, endDate) as BlogPost[]; +} \ No newline at end of file diff --git a/src/db/tags.ts b/src/db/tags.ts new file mode 100644 index 0000000..3c20cdb --- /dev/null +++ b/src/db/tags.ts @@ -0,0 +1,77 @@ +import { db } from './db'; + +// Helper function to get or create a tag and return its ID +export function getOrCreateTag(tagName: string): number { + // Try to find existing tag + const findTag = db.query('SELECT id FROM tags WHERE name = ?'); + const existingTag = findTag.get(tagName) as { id: number } | undefined; + + if (existingTag) { + return existingTag.id; + } + + // Create new tag if it doesn't exist + const insertTag = db.query('INSERT INTO tags (name) VALUES (?) RETURNING id'); + const result = insertTag.get(tagName) as { id: number }; + return result.id; +} + +// Helper function to get tags for a post +export function getPostTags(postId: number): string[] { + const query = db.query(` + SELECT t.name FROM tags t + JOIN post_tags pt ON t.id = pt.tag_id + WHERE pt.post_id = ? + `); + + const results = query.all(postId) as { name: string }[]; + return results.map(row => row.name); +} + +// Helper function to parse tags +export function parseTags(tags: string | string[]): string[] { + // If tags is already an array, return it directly + if (Array.isArray(tags)) { + return tags; + } + + // If tags is a string, try to parse as JSON + try { + return JSON.parse(tags || '[]'); + } catch { + // If parsing fails, assume it's a comma-separated string + if (typeof tags === 'string' && tags.trim()) { + return tags.split(',').map(tag => tag.trim()).filter(Boolean); + } + return []; + } +} + +// Get all unique tags from database +export function getAllTags(): { name: string; post_count: number }[] { + const query = db.query(` + SELECT t.name, COUNT(pt.post_id) as post_count + FROM tags t + JOIN post_tags pt ON t.id = pt.tag_id + JOIN posts p ON pt.post_id = p.id + GROUP BY t.id, t.name + ORDER BY post_count DESC, t.name ASC + `); + + return query.all() as { name: string; post_count: number }[]; +} + +// Update tag counts after changes (no longer needed with the new structure) +// The post_count is calculated dynamically in getAllTags() +// Keeping the function for backward compatibility +export function updateTagCounts() { + console.log("Tag counts are now calculated dynamically in getAllTags()"); +} + +// Initialize tags table and populate with existing tags +// This function is deprecated as we've restructured the database +// The new database structure is initialized in index.ts +// Kept for backward compatibility +export function initializeTagsTable() { + console.log("Tags table is now initialized in index.ts with the new structure"); +} \ No newline at end of file diff --git a/src/frontend/AppShell.tsx b/src/frontend/AppShell.tsx index d2beca0..b5aafda 100644 --- a/src/frontend/AppShell.tsx +++ b/src/frontend/AppShell.tsx @@ -1,59 +1,33 @@ -import React from 'react'; -import styles from '../public/styles.css' with { type: "text" }; -import headScript from '../public/head.js' with { type: "text" }; -import onLoadScript from '../public/onLoad.js' with { type: "text" }; +import React, { ReactNode } from 'react'; +import { minifyCSS, minifyJS } from './utils'; -// Helper: Minify CSS using simple but effective regex -function minifyCSS(css: string): string { - return css - .replace(/\/\*[\s\S]*?\*\//g, '') // Remove comments - .replace(/\s+/g, ' ') // Collapse whitespace - .replace(/\s*([{}:;,])\s*/g, '$1') // Remove space around delimiters - .trim(); -} +import styles from './styles.css' with { type: "text" }; +import headScript from './onLoad' with { type: "text" }; -// Helper: Minify JS/TS using Bun.Transpiler -function minifyJS(code: string): string { - const transpiler = new Bun.Transpiler({ - loader: 'ts', - minifyWhitespace: true, - }); +import { ThemePicker } from './components/theme-picker'; +import { ProfileBadge } from './components/profile-badge'; +import { TagPicker } from './components/tag-picker'; +import { PostArchive } from './components/post-archive'; - return transpiler.transformSync(code); -} - -export function AppShell(props: { post: any }) { +export function AppShell({ children }: { children: ReactNode }) { return ( - + + + Caleb's Blog - - - +