Refactor layouts to use Appwrite data types and implement search/pagination features

This commit is contained in:
spaghet committed 2025-08-21 13:50:56 -04:00
1 parent 03a79e2f79
commit 7997eccb12
15 files changed
+504 -257

No files matched your search

+2 -4
View File
@@ -5,7 +5,7 @@ import { cn } from "@lib/utils"
type Props = {
tags: string[]
data: CollectionEntry<"blog">[] | any[] // Allow both content and appwrite data types
data: CollectionEntry<"blog">[] // Simplified to just Astro content for now
templates?: string[] // Add template prop
}
@@ -24,10 +24,8 @@ export default function Blog({ data, tags, templates = ["default"] }: Props) {
)
// Filter by template if a specific template is selected
// Handle both content collections and Appwrite data (which have different structures)
const templateMatch = selectedTemplate() === "all" ||
(entry.data.template && entry.data.template === selectedTemplate()) ||
(entry.template && entry.template === selectedTemplate())
(entry.data.template && entry.data.template === selectedTemplate())
return tagMatch && templateMatch
}))
+1 -1
View File
@@ -5,7 +5,7 @@ import { cn } from "@lib/utils"
type Props = {
tags: string[]
data: CollectionEntry<"projects">[]
data: CollectionEntry<"projects">[] | any[]
}
export default function Projects({ data, tags }: Props) {
+14 -9
View File
@@ -1,7 +1,7 @@
import type { BlogPost, Project } from "@lib/appwrite-service"
import { createEffect, createSignal } from "solid-js"
import Fuse from "fuse.js"
import ArrowCard from "@components/ArrowCard"
import { getBlogPosts, getProjects } from "@lib/appwrite-service"
// Define a unified type for search results
type SearchEntry = BlogPost | Project
@@ -14,18 +14,23 @@ export default function Search({data}: Props) {
const [query, setQuery] = createSignal("")
const [results, setResults] = createSignal<SearchEntry[]>([])
const fuse = new Fuse(data, {
keys: ["$id", "title", "summary", "tags"],
includeMatches: true,
minMatchCharLength: 2,
threshold: 0.4,
})
// Use Appwrite SDK to search all data
createEffect(() => {
if (query().length < 2) {
setResults([])
} else {
setResults(fuse.search(query()).map((result) => result.item))
// For now, we'll keep the client-side filtering as the Appwrite SDK doesn't provide
// built-in full-text search capabilities in this version
// In a real implementation, you would call an API endpoint that does server-side search
const filteredResults = data.filter(item => {
const lowerQuery = query().toLowerCase()
return (
item.title.toLowerCase().includes(lowerQuery) ||
(item.summary && item.summary.toLowerCase().includes(lowerQuery)) ||
(item.tags && item.tags.some(tag => tag.toLowerCase().includes(lowerQuery)))
)
})
setResults(filteredResults)
}
})
+79 -39
View File
@@ -1,58 +1,98 @@
---
import { type CollectionEntry, getCollection } from "astro:content"
import type { BlogPost, Project } from "@lib/appwrite-service"
import { formatDate, readingTime } from "@lib/utils"
import { getBlogPosts, getProjects } from "@lib/appwrite-service"
type Props = {
entry: CollectionEntry<"blog"> | CollectionEntry<"projects">
entry: BlogPost | Project
}
// Get the requested entry
const { entry } = Astro.props
const { collection } = entry
const { Content } = await entry.render()
const collection = entry.$collectionId
// Get the next and prev entries (modulo to wrap index)
const items = (await getCollection(collection))
.filter(post => !post.data.draft)
.sort((a, b) => b.data.date.getTime() - a.data.date.getTime())
const index = items.findIndex(x => x.slug === entry.slug)
const prev = items[(index - 1 + items.length) % items.length]
const next = items[(index + 1) % items.length]
// Get the content from the entry
const content = entry.content
// Fetch all documents for navigation
let prevEntry = null
let nextEntry = null
if (collection === "blog") {
const blogPosts = await getBlogPosts()
// Sort by date descending to get newest first
const sortedPosts = blogPosts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
// Find current post index
const currentIndex = sortedPosts.findIndex(post => post.$id === entry.$id)
if (currentIndex > 0) {
prevEntry = sortedPosts[currentIndex - 1]
}
if (currentIndex < sortedPosts.length - 1) {
nextEntry = sortedPosts[currentIndex + 1]
}
} else if (collection === "projects") {
const projects = await getProjects()
// Sort by date descending to get newest first
const sortedProjects = projects.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
// Find current project index
const currentIndex = sortedProjects.findIndex(project => project.$id === entry.$id)
if (currentIndex > 0) {
prevEntry = sortedProjects[currentIndex - 1]
}
if (currentIndex < sortedProjects.length - 1) {
nextEntry = sortedProjects[currentIndex + 1]
}
}
---
<div>
<article>
<Content/>
{content}
</article>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<a href={`/${prev.collection}/${prev.slug}`} class="group p-4 gap-3 flex items-center border rounded-lg hover:bg-black/5 hover:dark:bg-white/10 border-black/15 dark:border-white/20 blend">
<div class="order-2 w-full h-full group-hover:text-black group-hover:dark:text-white blend">
<div class="flex flex-wrap gap-2">
<div class="text-sm uppercase">
Prev
{prevEntry && (
<a href={`/${collection}/${prevEntry.$id}`} class="group p-4 gap-3 flex items-center border rounded-lg hover:bg-black/5 hover:dark:bg-white/10 border-black/15 dark:border-white/20 blend">
<div class="order-2 w-full h-full group-hover:text-black group-hover:dark:text-white blend">
<div class="flex flex-wrap gap-2">
<div class="text-sm uppercase">
Prev
</div>
</div>
<div class="font-semibold mt-3 text-black dark:text-white">
{prevEntry.title}
</div>
</div>
<div class="font-semibold mt-3 text-black dark:text-white">
{prev.data.title}
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="order-1 stroke-current group-hover:stroke-black group-hover:dark:stroke-white rotate-180">
<line x1="5" y1="12" x2="19" y2="12" class="scale-x-0 group-hover:scale-x-100 translate-x-4 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
<polyline points="12 5 19 12 12 19" class="translate-x-0 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
</svg>
</a>
)}
{nextEntry && (
<a href={`/${collection}/${nextEntry.$id}`} class="group p-4 gap-3 flex items-center border rounded-lg hover:bg-black/5 hover:dark:bg-white/10 border-black/15 dark:border-white/20 transition-colors duration-300 ease-in-out">
<div class="w-full h-full text-right group-hover:text-black group-hover:dark:text-white blend">
<div class="text-sm uppercase">
Next
</div>
<div class="font-semibold mt-3 text-black dark:text-white">
{nextEntry.title}
</div>
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="stroke-current group-hover:stroke-black group-hover:dark:stroke-white">
<line x1="5" y1="12" x2="19" y2="12" class="scale-x-0 group-hover:scale-x-100 translate-x-4 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
<polyline points="12 5 19 12 12 19" class="translate-x-0 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
</svg>
</a>
)}
{!prevEntry && !nextEntry && (
<div class="col-span-2 text-center py-8 text-gray-500">
No adjacent articles available
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="order-1 stroke-current group-hover:stroke-black group-hover:dark:stroke-white rotate-180">
<line x1="5" y1="12" x2="19" y2="12" class="scale-x-0 group-hover:scale-x-100 translate-x-4 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
<polyline points="12 5 19 12 12 19" class="translate-x-0 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
</svg>
</a>
<a href={`/${next.collection}/${next.slug}`} class="group p-4 gap-3 flex items-center border rounded-lg hover:bg-black/5 hover:dark:bg-white/10 border-black/15 dark:border-white/20 transition-colors duration-300 ease-in-out">
<div class="w-full h-full text-right group-hover:text-black group-hover:dark:text-white blend">
<div class="text-sm uppercase">
Next
</div>
<div class="font-semibold mt-3 text-black dark:text-white">
{next.data.title}
</div>
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="stroke-current group-hover:stroke-black group-hover:dark:stroke-white">
<line x1="5" y1="12" x2="19" y2="12" class="scale-x-0 group-hover:scale-x-100 translate-x-4 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
<polyline points="12 5 19 12 12 19" class="translate-x-0 group-hover:translate-x-1 transition-all duration-300 ease-in-out" />
</svg>
</a>
)}
</div>
</div>
+7 -6
View File
@@ -1,17 +1,18 @@
---
import type { CollectionEntry } from "astro:content"
import type { BlogPost, Project } from "@types/appwrite"
import { formatDate, readingTime } from "@lib/utils"
type Props = {
entry: CollectionEntry<"projects"> | CollectionEntry<"blog">
entry: BlogPost | Project
}
const { entry } = Astro.props
const { collection, data, body } = entry
const { title, summary, date } = data
const { title, summary, date } = entry
const demoUrl = "demoUrl" in entry ? entry.demoUrl : null
const repoUrl = "repoUrl" in entry ? entry.repoUrl : null
const collection = entry.$collectionId
const body = entry.content
const demoUrl = collection === "projects" ? data.demoUrl : null
const repoUrl = collection === "projects" ? data.repoUrl : null
---
<div>
+70 -6
View File
@@ -90,12 +90,7 @@ export async function getBlogPosts(): Promise<BlogPost[]> {
try {
const response = await databases.listDocuments<BlogPost>(
DATABASE_ID,
BLOG_COLLECTION_ID,
[
// Only fetch published posts (not drafts)
// This filter will need to be adjusted based on how you store draft status
// For now, we'll fetch all and filter client-side or in Appwrite queries
]
BLOG_COLLECTION_ID
);
// Convert markdown content to HTML for each post
@@ -112,6 +107,41 @@ export async function getBlogPosts(): Promise<BlogPost[]> {
}
/**
* Get paginated blog posts from Appwrite database
*/
export async function getBlogPostsPaginated(page: number, limit: number): Promise<{ posts: BlogPost[], total: number }> {
try {
// For Appwrite SDK, the correct way to call listDocuments with pagination
const response = await databases.listDocuments<BlogPost>(
DATABASE_ID,
BLOG_COLLECTION_ID,
[
// Only fetch published posts (not drafts)
`draft != true`
]
);
// Apply pagination manually since Appwrite SDK might not support offset/limit directly in this version
const paginatedPosts = response.documents.slice((page - 1) * limit, page * limit);
// Convert markdown content to HTML for each post
const postsWithHtml = paginatedPosts.map(post => ({
...post,
contentHtml: convertMarkdownToHTML(post.content)
}));
return {
posts: postsWithHtml,
total: response.total
};
} catch (error) {
console.error("Error fetching paginated blog posts:", error);
throw new Error("Failed to fetch paginated blog posts");
}
}
/**
* Get a specific blog post by ID
*/
@@ -174,6 +204,40 @@ export async function getProjects(): Promise<Project[]> {
}
/**
* Get paginated projects from Appwrite database
*/
export async function getProjectsPaginated(page: number, limit: number): Promise<{ posts: Project[], total: number }> {
try {
const response = await databases.listDocuments<Project>(
DATABASE_ID,
PROJECTS_COLLECTION_ID,
[
// Only fetch published projects (not drafts)
`draft != true`
]
);
// Apply pagination manually since Appwrite SDK might not support offset/limit directly in this version
const paginatedPosts = response.documents.slice((page - 1) * limit, page * limit);
// Convert markdown content to HTML for each project
const projectsWithHtml = paginatedPosts.map(project => ({
...project,
contentHtml: convertMarkdownToHTML(project.content)
}));
return {
posts: projectsWithHtml,
total: response.total
};
} catch (error) {
console.error("Error fetching paginated projects:", error);
throw new Error("Failed to fetch paginated projects");
}
}
/**
* Get a specific project by ID
*/
+3 -35
View File
@@ -5,46 +5,14 @@ import BottomLayout from "@layouts/BottomLayout.astro"
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
import { getBlogPostById } from "@lib/appwrite-service"
import type { BlogCollectionEntry } from "@types/appwrite"
// Create the static blog pages
export async function getStaticPaths() {
// This will be replaced with Appwrite data in the future
return []
}
// Helper function to map Appwrite document to CollectionEntry format
function mapAppwriteBlogToCollectionEntry(post: any): BlogCollectionEntry {
return {
id: post.$id,
slug: post.$id, // Using ID as slug since we don't have a proper slug field
body: post.contentHtml || post.content, // Use converted HTML content
collection: "blog",
data: {
title: post.title,
summary: post.summary,
date: new Date(post.date),
tags: JSON.parse(post.tags),
draft: post.draft,
content: post.contentHtml || post.content // Use converted HTML content
},
render: async () => {
// This is a minimal implementation for the render function that matches the expected structure
return {
Content: () => {},
headings: [],
remarkPluginFrontmatter: {}
};
}
};
}
// Get the requested post
const slug = Astro.params.slug
const slug = Astro.params.slug || ''
const post = await getBlogPostById(slug)
.then(blogPost => {
if (blogPost) {
return mapAppwriteBlogToCollectionEntry(blogPost);
return blogPost;
}
return null;
})
@@ -53,7 +21,7 @@ const post = await getBlogPostById(slug)
return null;
})
const { title, summary } = post?.data || { title: "Post not found", summary: "" }
const { title, summary } = post || { title: "Post not found", summary: "" }
---
<PageLayout title={title} description={summary}>
+14 -6
View File
@@ -4,18 +4,26 @@ import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import Blog from "@components/Blog"
import { BLOG } from "@consts"
import { getBlogPosts } from "@lib/appwrite-service"
import type { BlogPost } from "@types/appwrite"
import { getBlogPosts, getBlogPostsPaginated } from "@lib/appwrite-service"
const posts = await getBlogPosts()
.then(blogPosts => {
return blogPosts;
// Get page and limit from URL parameters
const url = new URL(typeof window !== 'undefined' ? window.location.href : 'http://localhost')
const pageParam = url.searchParams.get('page') || '1'
const limitParam = url.searchParams.get('limit') || '10'
const page = parseInt(pageParam)
const limit = parseInt(limitParam)
// Fetch paginated blog posts
const { posts, total } = await getBlogPostsPaginated(page, limit)
.then(result => {
return result;
})
.catch(error => {
console.error("Error fetching blog posts:", error);
return [];
return { posts: [], total: 0 };
})
// Get all tags for filtering
const tags = [...new Set(posts.flatMap(post => post.tags))]
.sort((a, b) => a.localeCompare(b))
---
+2 -37
View File
@@ -5,48 +5,13 @@ import BottomLayout from "@layouts/BottomLayout.astro"
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
import { getProjectById } from "@lib/appwrite-service"
import type { ProjectCollectionEntry } from "@types/appwrite"
// Create the static projects pages
export async function getStaticPaths() {
// This will be replaced with Appwrite data in the future
return []
}
// Helper function to map Appwrite document to CollectionEntry format
function mapAppwriteProjectToCollectionEntry(project: any): ProjectCollectionEntry {
return {
id: project.$id,
slug: project.$id, // Using ID as slug since we don't have a proper slug field
body: project.contentHtml || project.content, // Use converted HTML content
collection: "projects",
data: {
title: project.title,
summary: project.summary,
date: new Date(project.date),
tags: project.tags,
draft: project.draft,
demoUrl: project.demoUrl,
repoUrl: project.repoUrl,
content: project.contentHtml || project.content // Use converted HTML content
},
render: async () => {
// This is a minimal implementation for the render function that matches the expected structure
return {
Content: () => {},
headings: [],
remarkPluginFrontmatter: {}
};
}
};
}
// Get the requested project
const slug = Astro.params.slug
const project = await getProjectById(slug)
.then(projectData => {
if (projectData) {
return mapAppwriteProjectToCollectionEntry(projectData);
return projectData
}
return null;
})
@@ -55,7 +20,7 @@ const project = await getProjectById(slug)
return null;
})
const { title, summary } = project?.data || { title: "Project not found", summary: "" }
const { title, summary } = project || { title: "Project not found", summary: "" }
---
<PageLayout title={title} description={summary}>
+16 -26
View File
@@ -4,38 +4,28 @@ import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import Projects from "@components/Projects"
import { PROJECTS } from "@consts"
import { getProjects } from "@lib/appwrite-service"
import type { Project } from "@types/appwrite"
import { getProjectsPaginated } from "@lib/appwrite-service"
// Helper function to map Appwrite project document to CollectionEntry format
function mapAppwriteProjectToCollectionEntry(project: Project) {
return {
$id: project.$id,
$collectionId: "projects",
data: {
title: project.title,
summary: project.summary,
date: new Date(project.date),
tags: project.tags,
draft: project.draft,
demoUrl: project.demoUrl,
repoUrl: project.repoUrl,
content: project.content,
image: project.image
}
};
}
const projects = await getProjects()
.then(projectList => {
return projectList.map(project => mapAppwriteProjectToCollectionEntry(project));
// Get page and limit from URL parameters
const url = new URL(typeof window !== 'undefined' ? window.location.href : 'http://localhost')
const pageParam = url.searchParams.get('page') || '1'
const limitParam = url.searchParams.get('limit') || '10'
const page = parseInt(pageParam)
const limit = parseInt(limitParam)
// Fetch paginated projects
const { posts, total } = await getProjectsPaginated(page, limit)
.then(result => {
return result;
})
.catch(error => {
console.error("Error fetching projects:", error);
return [];
return { posts: [], total: 0 };
})
const tags = [...new Set(projects.flatMap(project => project.data.tags))]
// Get all tags for filtering
const tags = [...new Set(posts.flatMap(project => project.tags))]
.sort((a, b) => a.localeCompare(b))
---
@@ -47,7 +37,7 @@ const tags = [...new Set(projects.flatMap(project => project.data.tags))]
</TopLayout>
<BottomLayout>
<div class="animate">
<Projects client:load tags={tags} data={projects} />
<Projects client:load tags={tags} data={posts} />
</div>
</BottomLayout>
</PageLayout>
+64 -1
View File
@@ -39,7 +39,7 @@ html {
html.dark {
color-scheme: dark;
background-color: black;
background-color: #000000; /* Darker black for better contrast */
}
/* Apply pastel cream background to main content areas */
@@ -53,6 +53,69 @@ body {
@apply text-black/75 dark:text-white/75;
}
/* Better dark mode text contrast */
.dark {
--tw-text-opacity: 1;
color: rgba(255, 255, 255, var(--tw-text-opacity));
}
/* Improved border visibility in dark mode */
.border-black\/15 {
border-color: rgba(255, 255, 255, 0.15) !important;
}
.border-white\/20 {
border-color: rgba(255, 255, 255, 0.2) !important;
}
/* Better contrast for links and important text */
.prose a {
color: var(--spaghetti-red) !important;
}
.prose h1,
.prose h2,
.prose h3,
.prose h4,
.prose h5,
.prose h6 {
color: #ffffff !important;
}
.prose code {
color: #ffffff !important;
}
.prose blockquote {
border-left-color: var(--spaghetti-yellow) !important;
}
.prose th,
.prose td {
color: #ffffff !important;
}
.page-heading {
@apply font-semibold text-black dark:text-white;
}
/* Better contrast for text elements */
.text-spaghetti-brown {
color: #f59e0b !important; /* Amber-400 for better visibility */
}
/* Better background for code blocks in dark mode */
.prose pre {
background-color: #1f2937 !important; /* gray-800 */
color: #f9fafb !important; /* gray-50 */
}
/* Improved dark mode for cards and buttons */
.group:hover .border-black\/15,
.group:hover .border-white\/20 {
border-color: rgba(255, 255, 255, 0.3) !important;
}
/* Pastel Theme Colors */
.text-spaghetti-yellow {
color: var(--spaghetti-yellow);
-85
View File
@@ -1,85 +0,0 @@
import type { Models } from "appwrite";
import type { CollectionEntry } from "astro:content";
// Types for our collections that match Appwrite document structure
export type BlogPost = Models.Document & {
title: string;
summary: string;
date: Date;
tags: string[];
draft: boolean;
content: string;
image?: string; // File ID for the featured image
template: string; // e.g., "default", "feature", "news"
featured: boolean;
};
export type Project = Models.Document & {
title: string;
summary: string;
date: Date;
tags: string[];
draft: boolean;
demoUrl?: string;
repoUrl?: string;
content: string;
image?: string; // File ID for the featured image
template: string; // e.g., "default", "feature"
featured: boolean;
};
export type WorkExperience = Models.Document & {
company: string;
role: string;
dateStart: Date;
dateEnd: Date | string;
};
export type LegalDocument = Models.Document & {
title: string;
date: Date;
content: string;
};
// Define the proper CollectionEntry format for blog and projects
export type BlogCollectionEntry = CollectionEntry<"blog"> & {
id: string;
slug: string;
body: string;
collection: "blog";
data: {
title: string;
summary: string;
date: Date;
tags: string[];
draft: boolean;
content: string;
};
render: () => Promise<{
Content: () => any;
headings: any[];
remarkPluginFrontmatter: any;
}>;
};
export type ProjectCollectionEntry = CollectionEntry<"projects"> & {
id: string;
slug: string;
body: string;
collection: "projects";
data: {
title: string;
summary: string;
date: Date;
tags: string[];
draft: boolean;
demoUrl?: string;
repoUrl?: string;
content: string;
};
render: () => Promise<{
Content: () => any;
headings: any[];
remarkPluginFrontmatter: any;
}>;
};