add blog to project

This commit is contained in:
mahdiarghyani
2025-11-09 13:56:03 +03:30
parent 24a91baaf5
commit c7e5eb0713
26 changed files with 3310 additions and 11 deletions
+42
View File
@@ -0,0 +1,42 @@
<template>
<NuxtLink :to="localePath((post as any)._path)" class="block h-full">
<UCard class="h-full overflow-hidden hover:shadow-lg transition-shadow duration-300">
<div class="relative aspect-video w-full overflow-hidden -mx-6 -mt-6 mb-4">
<NuxtImg :src="post.image || '/img/blog/default-cover.jpg'" :alt="post.title" class="h-full w-full object-cover"
loading="lazy" width="600" height="338" format="webp" />
</div>
<h2 class="mb-2 text-xl font-semibold text-gray-900 dark:text-gray-100">
{{ post.title }}
</h2>
<p class="mb-4 line-clamp-2 text-gray-600 dark:text-gray-400">
{{ post.description }}
</p>
<div class="mb-4 flex flex-wrap items-center gap-2 text-sm text-gray-500 dark:text-gray-500">
<time :datetime="post.date">{{ formatDate(post.date) }}</time>
<span>•</span>
<span>{{ t('blog.readingTime', { minutes: calculateReadingTime(post) }) }}</span>
</div>
<div v-if="post.tags && post.tags.length > 0" class="flex flex-wrap gap-2">
<UBadge v-for="tag in post.tags" :key="tag" variant="subtle" size="sm">
{{ tag }}
</UBadge>
</div>
</UCard>
</NuxtLink>
</template>
<script setup lang="ts">
import type { BlogPost } from '~/types/blog'
defineProps<{
post: BlogPost
}>()
const { t } = useI18n()
const localePath = useLocalePath()
const { formatDate, calculateReadingTime } = useBlog()
</script>
+17
View File
@@ -0,0 +1,17 @@
<template>
<div class="flex min-h-[400px] items-center justify-center">
<div class="text-center">
<div class="mb-4 text-6xl">📝</div>
<h3 class="mb-2 text-xl font-semibold text-gray-900 dark:text-gray-100">
{{ t('blog.noResults') }}
</h3>
<p class="text-gray-600 dark:text-gray-400">
{{ t('blog.empty') }}
</p>
</div>
</div>
</template>
<script setup lang="ts">
const { t } = useI18n()
</script>
+73
View File
@@ -0,0 +1,73 @@
<script setup lang="ts">
import type { BlogPost } from '~/types/blog'
const props = defineProps<{
prev: BlogPost | null
next: BlogPost | null
}>()
const { t } = useI18n()
const localePath = useLocalePath()
const router = useRouter()
// Keyboard navigation
const handleKeydown = (event: KeyboardEvent) => {
if (event.key === 'ArrowLeft' && props.prev) {
router.push(localePath(props.prev._path))
} else if (event.key === 'ArrowRight' && props.next) {
router.push(localePath(props.next._path))
}
}
onMounted(() => {
window.addEventListener('keydown', handleKeydown)
})
onUnmounted(() => {
window.removeEventListener('keydown', handleKeydown)
})
</script>
<template>
<nav class="flex justify-between items-center gap-4 mt-12 pt-8 border-t border-gray-200 dark:border-gray-800">
<!-- Previous Post -->
<div class="flex-1">
<NuxtLink v-if="prev" :to="localePath(prev._path)" class="group block">
<UButton color="neutral" variant="ghost" size="lg" class="w-full justify-start">
<template #leading>
<UIcon name="i-heroicons-arrow-left" class="w-5 h-5" />
</template>
<div class="text-left">
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">
{{ t('blog.previousPost') }}
</div>
<div
class="text-sm font-medium text-gray-900 dark:text-gray-100 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors line-clamp-1">
{{ prev.title }}
</div>
</div>
</UButton>
</NuxtLink>
</div>
<!-- Next Post -->
<div class="flex-1">
<NuxtLink v-if="next" :to="localePath(next._path)" class="group block">
<UButton color="neutral" variant="ghost" size="lg" class="w-full justify-end">
<div class="text-right">
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">
{{ t('blog.nextPost') }}
</div>
<div
class="text-sm font-medium text-gray-900 dark:text-gray-100 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors line-clamp-1">
{{ next.title }}
</div>
</div>
<template #trailing>
<UIcon name="i-heroicons-arrow-right" class="w-5 h-5" />
</template>
</UButton>
</NuxtLink>
</div>
</nav>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import type { BlogPost } from '~/types/blog'
const props = defineProps<{
post: BlogPost
}>()
const { formatDate, calculateReadingTime } = useBlog()
const readingTime = computed(() => calculateReadingTime(props.post))
</script>
<template>
<article>
<header class="mb-8">
<!-- Cover Image -->
<NuxtImg v-if="post.image" :src="post.image" :alt="post.title" width="1200" height="630" format="webp"
class="w-full rounded-lg mb-6" />
<!-- Title -->
<h1 class="text-4xl md:text-5xl font-bold mb-4 text-gray-900 dark:text-gray-100">
{{ post.title }}
</h1>
<!-- Metadata -->
<div class="flex flex-wrap items-center gap-4 text-gray-600 dark:text-gray-400 mb-4">
<!-- Date -->
<time :datetime="post.date" class="flex items-center gap-2">
<UIcon name="i-heroicons-calendar" class="w-5 h-5" />
{{ formatDate(post.date) }}
</time>
<!-- Reading Time -->
<span class="flex items-center gap-2">
<UIcon name="i-heroicons-clock" class="w-5 h-5" />
{{ $t('blog.readingTime', { minutes: readingTime }) }}
</span>
<!-- Author -->
<span v-if="post.author" class="flex items-center gap-2">
<UIcon name="i-heroicons-user" class="w-5 h-5" />
{{ post.author }}
</span>
</div>
<!-- Tags -->
<div v-if="post.tags && post.tags.length > 0" class="flex flex-wrap gap-2">
<UBadge v-for="tag in post.tags" :key="tag" color="primary" variant="soft" size="md">
{{ tag }}
</UBadge>
</div>
</header>
</article>
</template>
+35
View File
@@ -0,0 +1,35 @@
<template>
<UInput :model-value="modelValue" :placeholder="t('blog.searchPlaceholder')" icon="i-heroicons-magnifying-glass"
size="lg" :ui="{ icon: { trailing: { pointer: '' } } }" @update:model-value="handleInput">
<template v-if="modelValue" #trailing>
<UButton color="gray" variant="link" icon="i-heroicons-x-mark-20-solid" :padded="false" @click="clearSearch" />
</template>
</UInput>
</template>
<script setup lang="ts">
import { useDebounceFn } from '@vueuse/core'
const props = defineProps<{
modelValue: string
}>()
const emit = defineEmits<{
'update:modelValue': [value: string]
}>()
const { t } = useI18n()
// Debounced input handler
const debouncedEmit = useDebounceFn((value: string) => {
emit('update:modelValue', value)
}, 300)
const handleInput = (value: string) => {
debouncedEmit(value)
}
const clearSearch = () => {
emit('update:modelValue', '')
}
</script>
+151
View File
@@ -0,0 +1,151 @@
<script setup lang="ts">
interface TocLink {
id: string
text: string
depth: number
children?: TocLink[]
}
const props = defineProps<{
toc: {
links: TocLink[]
}
}>()
const { t } = useI18n()
const activeId = ref<string>('')
// Check if TOC should be displayed (3+ headings)
const shouldShowToc = computed(() => {
const countLinks = (links: TocLink[]): number => {
return links.reduce((count, link) => {
return count + 1 + (link.children ? countLinks(link.children) : 0)
}, 0)
}
return countLinks(props.toc.links) >= 3
})
// Smooth scroll to heading
const scrollToHeading = (id: string) => {
const element = document.getElementById(id)
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' })
activeId.value = id
}
}
// Track active section with IntersectionObserver
onMounted(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
activeId.value = entry.target.id
}
})
},
{
rootMargin: '-80px 0px -80% 0px',
threshold: 0
}
)
// Observe all headings
const headings = document.querySelectorAll('article h2, article h3, article h4')
headings.forEach((heading) => observer.observe(heading))
// Cleanup
onUnmounted(() => {
headings.forEach((heading) => observer.unobserve(heading))
})
})
// Render TOC links recursively
const renderTocLinks = (links: TocLink[]) => {
return links
}
</script>
<template>
<aside v-if="shouldShowToc" class="toc-container">
<!-- Desktop: Sticky sidebar -->
<nav class="hidden lg:block sticky top-24 max-h-[calc(100vh-8rem)] overflow-y-auto">
<h3 class="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
{{ t('blog.tableOfContents') }}
</h3>
<ul class="space-y-2 text-sm">
<template v-for="link in toc.links" :key="link.id">
<li>
<a :href="`#${link.id}`" :class="[
'block py-1 transition-colors',
activeId === link.id
? 'text-primary-600 dark:text-primary-400 font-medium'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
]" @click.prevent="scrollToHeading(link.id)">
{{ link.text }}
</a>
<!-- Nested children (h3) -->
<ul v-if="link.children && link.children.length > 0" class="ml-4 mt-1 space-y-1">
<li v-for="child in link.children" :key="child.id">
<a :href="`#${child.id}`" :class="[
'block py-1 transition-colors',
activeId === child.id
? 'text-primary-600 dark:text-primary-400 font-medium'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
]" @click.prevent="scrollToHeading(child.id)">
{{ child.text }}
</a>
</li>
</ul>
</li>
</template>
</ul>
</nav>
<!-- Mobile: Collapsible accordion -->
<UAccordion class="lg:hidden mb-6" :items="[
{
label: t('blog.tableOfContents'),
icon: 'i-heroicons-list-bullet',
defaultOpen: false,
slot: 'toc'
}
]">
<template #toc>
<ul class="space-y-2 text-sm p-4">
<template v-for="link in toc.links" :key="link.id">
<li>
<a :href="`#${link.id}`" :class="[
'block py-1 transition-colors',
activeId === link.id
? 'text-primary-600 dark:text-primary-400 font-medium'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
]" @click.prevent="scrollToHeading(link.id)">
{{ link.text }}
</a>
<!-- Nested children (h3) -->
<ul v-if="link.children && link.children.length > 0" class="ml-4 mt-1 space-y-1">
<li v-for="child in link.children" :key="child.id">
<a :href="`#${child.id}`" :class="[
'block py-1 transition-colors',
activeId === child.id
? 'text-primary-600 dark:text-primary-400 font-medium'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
]" @click.prevent="scrollToHeading(child.id)">
{{ child.text }}
</a>
</li>
</ul>
</li>
</template>
</ul>
</template>
</UAccordion>
</aside>
</template>
<style scoped>
.toc-container {
@apply w-full;
}
</style>
+48
View File
@@ -0,0 +1,48 @@
<template>
<div v-if="tags.length > 0" class="overflow-x-auto">
<div class="flex flex-wrap gap-2">
<UButton :color="!modelValue ? 'primary' : 'gray'" :variant="!modelValue ? 'solid' : 'soft'" size="sm"
@click="selectTag(null)">
{{ t('blog.allPosts') }}
</UButton>
<UButton v-for="tag in tags" :key="tag" :color="modelValue === tag ? 'primary' : 'gray'"
:variant="modelValue === tag ? 'solid' : 'soft'" size="sm" @click="selectTag(tag)">
{{ tag }}
</UButton>
</div>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
tags: string[]
modelValue: string | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: string | null]
}>()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
// Read query parameter on mount to restore filter state
onMounted(() => {
const tagFromQuery = route.query.tag as string | undefined
if (tagFromQuery && props.tags.includes(tagFromQuery)) {
emit('update:modelValue', tagFromQuery)
}
})
// Select tag and update URL query parameter
const selectTag = async (tag: string | null) => {
emit('update:modelValue', tag)
// Update URL query parameter
await navigateTo({
query: tag ? { tag } : {}
})
}
</script>
+88
View File
@@ -0,0 +1,88 @@
import type { BlogPost } from '~/types/blog'
export function useBlog() {
const { locale } = useI18n()
/**
* Calculate reading time from word count
* @param content - Blog post content
* @returns Reading time in minutes
*/
const calculateReadingTime = (content: any): number => {
if (!content?.body?.children) return 0
const text = JSON.stringify(content.body.children)
const wordCount = text.split(/\s+/).length
return Math.ceil(wordCount / 200) // 200 words per minute
}
/**
* Format date for display
* @param dateString - ISO 8601 date string
* @returns Formatted date string
*/
const formatDate = (dateString: string): string => {
const date = new Date(dateString)
return new Intl.DateTimeFormat(locale.value, {
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(date)
}
/**
* Get all unique tags from posts
* @param posts - Array of blog posts
* @returns Sorted array of unique tags
*/
const extractUniqueTags = (posts: BlogPost[]): string[] => {
const tagSet = new Set<string>()
posts.forEach(post => {
post.tags?.forEach(tag => tagSet.add(tag))
})
return Array.from(tagSet).sort()
}
/**
* Get blog path for current locale
* @returns Locale-aware blog path
*/
const getBlogPath = (): string => {
return `${locale.value}/blog`
}
/**
* Filter posts by search query
*/
const filterPostsBySearch = (posts: BlogPost[], query: string): BlogPost[] => {
if (!query) return posts
const lowerQuery = query.toLowerCase()
return posts.filter(post =>
post.title?.toLowerCase().includes(lowerQuery) ||
post.description?.toLowerCase().includes(lowerQuery) ||
post.tags?.some(tag => tag.toLowerCase().includes(lowerQuery))
)
}
/**
* Filter posts by tag
* @param posts - Array of blog posts
* @param tag - Tag to filter by
* @returns Filtered array of posts
*/
const filterPostsByTag = (posts: BlogPost[], tag: string | null): BlogPost[] => {
if (!tag) return posts
return posts.filter(post => post.tags?.includes(tag))
}
return {
calculateReadingTime,
formatDate,
extractUniqueTags,
getBlogPath,
filterPostsBySearch,
filterPostsByTag
}
}
+176 -3
View File
@@ -1,7 +1,180 @@
<script setup lang="ts">
import type { BlogPost } from '~/types/blog'
const { locale, t } = useI18n()
const localePath = useLocalePath()
const route = useRoute()
const slug = Array.isArray(route.params.slug) ? route.params.slug : [route.params.slug]
// Fetch current post
const { data: post } = await useAsyncData<BlogPost>(`blog-post-${slug.join('/')}`, () =>
queryContent<BlogPost>(`/${locale.value}/blog`)
.where({ _path: `/${locale.value}/blog/${slug.join('/')}` })
.findOne()
)
if (!post.value) {
throw createError({
statusCode: 404,
message: 'Blog post not found',
fatal: true
})
}
// Fetch all posts for prev/next navigation
const { data: allPosts } = await useAsyncData<BlogPost[]>(`blog-posts-nav-${locale.value}`, () =>
queryContent<BlogPost>(`/${locale.value}/blog`)
.where({ draft: { $ne: true } })
.sort({ date: -1 })
.only(['title', '_path', 'date'])
.find()
)
// Calculate adjacent posts
const currentIndex = computed(() => {
if (!allPosts.value || !post.value) return -1
return allPosts.value.findIndex((p: BlogPost) => p._path === post.value!._path)
})
const prevPost = computed<BlogPost | null>(() => {
if (currentIndex.value === -1 || !allPosts.value) return null
return allPosts.value[currentIndex.value + 1] || null
})
const nextPost = computed<BlogPost | null>(() => {
if (currentIndex.value === -1 || !allPosts.value) return null
return allPosts.value[currentIndex.value - 1] || null
})
// SEO meta tags
const siteUrl = 'https://aliarghyani.com' // TODO: Move to runtime config
// Use Nuxt Content's built-in SEO helper
if (post.value) {
useContentHead(post as any)
}
// Additional custom meta tags
if (post.value) {
useSeoMeta({
title: `${post.value.title} | ${t('blog.title')}`,
description: post.value.description,
ogTitle: post.value.title,
ogDescription: post.value.description,
ogImage: post.value.image || '/img/blog/default-cover.jpg',
ogType: 'article',
ogUrl: `${siteUrl}${post.value._path}`,
twitterCard: 'summary_large_image',
twitterTitle: post.value.title,
twitterDescription: post.value.description,
twitterImage: post.value.image || '/img/blog/default-cover.jpg',
articlePublishedTime: post.value.date,
articleModifiedTime: post.value.updatedAt || post.value.date,
articleAuthor: post.value.author || 'Ali Arghyani',
articleTag: post.value.tags
})
// JSON-LD structured data
useHead({
script: [
{
type: 'application/ld+json',
textContent: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.value.title,
description: post.value.description,
image: post.value.image ? `${siteUrl}${post.value.image}` : `${siteUrl}/img/blog/default-cover.jpg`,
datePublished: post.value.date,
dateModified: post.value.updatedAt || post.value.date,
author: {
'@type': 'Person',
name: post.value.author || 'Ali Arghyani'
},
publisher: {
'@type': 'Person',
name: 'Ali Arghyani'
}
})
}
]
})
}
</script>
<template>
<UContainer>
<UAlert color="yellow" variant="soft" title="Blog disabled">
Nuxt Content is temporarily disabled. Blog post rendering will be restored later.
</UAlert>
<div v-if="post" class="py-8">
<!-- Breadcrumb Navigation -->
<UBreadcrumb :links="[
{ label: t('nav.home'), to: localePath('/') },
{ label: t('blog.title'), to: localePath('/blog') },
{ label: post.title }
]" class="mb-6" />
<!-- Back to Blog Link -->
<NuxtLink :to="localePath('/blog')"
class="inline-flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors mb-8">
<UIcon name="i-heroicons-arrow-left" class="w-4 h-4" />
{{ t('blog.backToBlog') }}
</NuxtLink>
<!-- Main Content Layout -->
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
<!-- Main Content -->
<div class="lg:col-span-8">
<!-- Blog Post Metadata -->
<BlogPost :post="post" />
<!-- Content Renderer -->
<article :dir="locale === 'fa' ? 'rtl' : 'ltr'" class="prose prose-lg dark:prose-invert max-w-none mt-8">
<ContentRenderer :value="post" />
</article>
<!-- Blog Navigation (Prev/Next) -->
<BlogNavigation :prev="prevPost" :next="nextPost" />
</div>
<!-- Sidebar: Table of Contents -->
<aside class="lg:col-span-4">
<BlogTableOfContents v-if="post.body?.toc" :toc="post.body.toc" />
</aside>
</div>
</div>
</UContainer>
</template>
<style scoped>
/* Force LTR for code blocks in RTL context */
article[dir="rtl"] :deep(pre),
article[dir="rtl"] :deep(code) {
direction: ltr;
text-align: left;
}
/* Ensure proper spacing and readability */
.prose {
@apply text-gray-700 dark:text-gray-300;
}
.prose :deep(h1),
.prose :deep(h2),
.prose :deep(h3),
.prose :deep(h4),
.prose :deep(h5),
.prose :deep(h6) {
@apply text-gray-900 dark:text-gray-100 font-semibold;
}
.prose :deep(a) {
@apply text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300;
}
.prose :deep(code) {
@apply text-sm;
}
.prose :deep(pre) {
@apply rounded-lg;
}
</style>
+62 -4
View File
@@ -8,15 +8,73 @@
</div>
</div>
<div class="rounded-xl border border-dashed border-gray-300 p-8 text-center text-gray-500 dark:border-gray-700 dark:text-gray-300">
Nuxt Content is temporarily disabled. Blog will be back soon.
<BlogSearch v-model="searchQuery" />
<BlogTagFilter v-model="selectedTag" :tags="allTags" class="my-6" />
<div v-if="filteredPosts.length > 0" class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
<BlogCard v-for="post in filteredPosts" :key="(post as any)._path" :post="post" />
</div>
<BlogEmpty v-else />
</UContainer>
</section>
</template>
<script setup lang="ts">
const { locale, t } = useI18n()
import type { BlogPost } from '~/types/blog'
// Blog listing requires @nuxt/content which is disabled for now
const { t, locale } = useI18n()
const { extractUniqueTags, filterPostsBySearch, filterPostsByTag } = useBlog()
// Fetch posts using queryCollection (Nuxt Content v3 API)
const { data: posts } = await useAsyncData<any[]>(
`blog-posts-${locale.value}`,
async () => {
try {
// Use queryCollection for Nuxt Content v3
const result = await queryCollection('blog').all()
if (!result || result.length === 0) {
return []
}
// Filter by locale and draft status, then sort by date
return result
.filter((post: any) =>
post.path?.startsWith(`/${locale.value}/blog/`) && post.draft !== true
)
.sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
} catch (error) {
console.error('Error fetching blog posts:', error)
return []
}
},
{
default: () => [],
watch: [locale],
server: true,
lazy: false
}
)
// Extract unique tags from all posts
const allTags = computed(() => {
return posts.value && Array.isArray(posts.value) ? extractUniqueTags(posts.value) : []
})
// Reactive refs for search and filter
const searchQuery = ref('')
const selectedTag = ref<string | null>(null)
// Filtered posts based on search and tag
const filteredPosts = computed<BlogPost[]>(() => {
if (!posts.value || !Array.isArray(posts.value) || posts.value.length === 0) return []
let filtered: BlogPost[] = [...posts.value]
filtered = filterPostsBySearch(filtered, searchQuery.value)
filtered = filterPostsByTag(filtered, selectedTag.value)
return filtered
})
</script>
+44
View File
@@ -0,0 +1,44 @@
import type { ParsedContent } from '@nuxt/content'
export interface BlogPost extends ParsedContent {
// Required fields
title: string
description: string
date: string // ISO 8601 format
tags: string[]
_path: string
// Optional fields
image?: string // Cover image path
author?: string
draft?: boolean
updatedAt?: string
// Custom SEO
head?: {
title?: string
description?: string
image?: string
}
// Body with TOC
body?: {
type: string
children: any[]
toc?: {
title: string
searchDepth: number
depth: number
links: Array<{
id: string
text: string
depth: number
children?: Array<{
id: string
text: string
depth: number
}>
}>
}
}
}