-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add feature related post #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
61c21cc
feat: add feature related post
pharmacist-sabot 9a8cf93
refactor(blog): harden related posts logic and optimize collection usage
pharmacist-sabot 28611b5
chore(ts): remove redundant type annotation from default param
pharmacist-sabot a6cc17b
chore(ts): remove redundant string type annotation
pharmacist-sabot 2b8add6
refactor(blog): remove redundant nullish checks for default params
pharmacist-sabot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- | ||
| import type { CollectionEntry } from 'astro:content'; | ||
|
|
||
| import BlogPostCard from './BlogPostCard.astro'; | ||
|
|
||
| type Props = { | ||
| relatedPosts: CollectionEntry<'blog'>[]; | ||
| }; | ||
|
|
||
| const { relatedPosts } = Astro.props; | ||
| --- | ||
|
|
||
| { | ||
| relatedPosts.length > 0 && ( | ||
| <section class="related-posts"> | ||
| <h2 class="related-posts-heading">You might also like</h2> | ||
| <div class="related-posts-grid"> | ||
| {relatedPosts.map(post => ( | ||
| <div class="grid-item" data-post-id={post.slug}> | ||
| <BlogPostCard post={post} /> | ||
| </div> | ||
| ))} | ||
| </div> | ||
| </section> | ||
| ) | ||
| } | ||
|
|
||
| <style> | ||
| .related-posts { | ||
| margin-top: 4rem; | ||
| padding-top: 3rem; | ||
| border-top: 1px solid var(--card-border-color); | ||
| } | ||
|
|
||
| .related-posts-heading { | ||
| font-family: var(--font-serif); | ||
| font-size: clamp(1.3rem, 4vw, 1.6rem); | ||
| text-align: center; | ||
| margin-bottom: 2rem; | ||
| color: var(--font-color); | ||
| } | ||
|
|
||
| .related-posts-grid { | ||
| display: grid; | ||
| grid-template-columns: repeat(3, 1fr); | ||
| gap: 1.5rem; | ||
| } | ||
|
|
||
| .grid-item { | ||
| height: 100%; | ||
| } | ||
|
|
||
| @media (max-width: 1024px) { | ||
| .related-posts-grid { | ||
| grid-template-columns: repeat(2, 1fr); | ||
| } | ||
| } | ||
|
|
||
| @media (max-width: 768px) { | ||
| .related-posts { | ||
| margin-top: 3rem; | ||
| padding-top: 2rem; | ||
| } | ||
|
|
||
| .related-posts-grid { | ||
| grid-template-columns: 1fr; | ||
| gap: 1.25rem; | ||
| } | ||
|
|
||
| .related-posts-heading { | ||
| margin-bottom: 1.5rem; | ||
| } | ||
| } | ||
| </style> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import type { CollectionEntry } from 'astro:content'; | ||
|
|
||
| import { getCollection } from 'astro:content'; | ||
|
|
||
| /** | ||
| * Cached blog posts collection. | ||
| * Since Astro pre-renders pages at build time, this module-level cache | ||
| * ensures the collection is fetched only once during the build process, | ||
| * avoiding redundant queries across multiple page renders. | ||
| */ | ||
| let cachedPosts: CollectionEntry<'blog'>[] | null = null; | ||
|
|
||
| /** | ||
| * Get all blog posts with caching. | ||
| * Results are cached at the module level to avoid repeated collection fetches. | ||
| */ | ||
| export async function getAllBlogPosts(): Promise<CollectionEntry<'blog'>[]> { | ||
| if (cachedPosts === null) { | ||
| cachedPosts = await getCollection('blog'); | ||
| } | ||
| return cachedPosts; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import type { CollectionEntry } from 'astro:content'; | ||
|
|
||
| /** | ||
| * Safely parse a date, returning 0 for invalid dates | ||
| */ | ||
| function safeGetTime(date: Date | string | undefined): number { | ||
| if (!date) | ||
| return 0; | ||
| const parsed = new Date(date); | ||
| return Number.isNaN(parsed.getTime()) ? 0 : parsed.getTime(); | ||
| } | ||
|
|
||
| /** | ||
| * Calculate related posts based on tags and category matching. | ||
| * Uses a scoring system: +2 points per matching tag, +1 point for matching category. | ||
| * Falls back to most recent posts if no related posts are found. | ||
| */ | ||
| export function getRelatedPosts( | ||
| allPosts: CollectionEntry<'blog'>[], | ||
| currentSlug: string, | ||
| currentTags: string[] = [], | ||
| currentCategory = '', | ||
| limit = 3, | ||
| ): CollectionEntry<'blog'>[] { | ||
| // Filter out the current post and posts without valid pubDate | ||
| const otherPosts = allPosts.filter( | ||
| post => post.slug !== currentSlug && post.data.pubDate, | ||
| ); | ||
|
|
||
| // Calculate scores for each post | ||
| const scoredPosts = otherPosts.map((post) => { | ||
| let score = 0; | ||
|
|
||
| // +2 points for each matching tag | ||
| const postTags = post.data.tags ?? []; | ||
| for (const tag of postTags) { | ||
| if (currentTags.includes(tag)) { | ||
| score += 2; | ||
| } | ||
| } | ||
|
|
||
| // +1 point for matching category | ||
| if (currentCategory && post.data.category === currentCategory) { | ||
| score += 1; | ||
| } | ||
|
|
||
| return { post, score }; | ||
| }); | ||
|
|
||
| // Sort by score (descending), then by pubDate (descending) for tie-breaking | ||
| scoredPosts.sort((a, b) => { | ||
| if (b.score !== a.score) { | ||
| return b.score - a.score; | ||
| } | ||
| // Tie-breaker: newer posts first | ||
| return safeGetTime(b.post.data.pubDate) - safeGetTime(a.post.data.pubDate); | ||
| }); | ||
|
|
||
| // Check if we have any posts with score > 0 | ||
| const postsWithScore = scoredPosts.filter(item => item.score > 0); | ||
|
|
||
| if (postsWithScore.length > 0) { | ||
| // Return top 'limit' related posts | ||
| return postsWithScore.slice(0, limit).map(item => item.post); | ||
| } | ||
|
|
||
| // Fallback: return most recent posts if no related posts found | ||
| const recentPosts = [...otherPosts].sort( | ||
| (a, b) => safeGetTime(b.data.pubDate) - safeGetTime(a.data.pubDate), | ||
| ); | ||
|
|
||
| return recentPosts.slice(0, limit); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: pharmacist-sabot/rxdevnotes
Length of output: 2075
🏁 Script executed:
Repository: pharmacist-sabot/rxdevnotes
Length of output: 1069
🏁 Script executed:
Repository: pharmacist-sabot/rxdevnotes
Length of output: 2219
🏁 Script executed:
Repository: pharmacist-sabot/rxdevnotes
Length of output: 3191
Consider adding draft post support if needed. The codebase currently lacks a
draftfield in the blog collection schema and has no draft filtering logic. If draft posts are needed, add adraft: z.boolean().optional()field to the schema insrc/content/config.tsand implement filtering ingetAllBlogPosts()to exclude them (e.g.,await getCollection('blog').then(posts => posts.filter(p => !p.data.draft))). Currently, thegetRelatedPosts()function only filters bypubDateand slug, which is insufficient for draft post handling.🤖 Prompt for AI Agents