'use client'; import { useState, useEffect } from 'react'; import Link from 'next/link'; import SEOHead from '../../../components/SEOHead'; // Category icons mapping const categoryIcons = { company: ( ), industry: ( ), technology: ( ), product: ( ), }; // Helper function to convert article keys to slugs const getSlugFromKey = (key: string) => { // If key is already a slug format, return as is if (key.includes('-')) { return key; } const slugMap: { [key: string]: string } = { article1: 'cloudtech-new-platform', article2: 'cloud-trends-2024', article3: 'optimize-cloud-server', article4: 'rds-new-features', article5: 'cloud-security-practices', article6: 'iso-27001-certification', }; return slugMap[key] || key; }; interface NewsPageProps { params: { locale: string }; } export default function NewsPage({ params }: NewsPageProps) { const currentLang = params.locale || 'zh-CN'; const [translations, setTranslations] = useState({}); const [commonTranslations, setCommonTranslations] = useState({}); const [loading, setLoading] = useState(true); const [selectedCategory, setSelectedCategory] = useState('all'); const [isMenuOpen, setIsMenuOpen] = useState(false); const [searchTerm, setSearchTerm] = useState(''); const [sortBy, setSortBy] = useState('date'); useEffect(() => { const loadTranslations = async () => { try { const [newsRes, commonRes] = await Promise.all([ fetch(`/locales/${currentLang}/news.json`), fetch(`/locales/${currentLang}/common.json`), ]); const [newsData, commonData] = await Promise.all([ newsRes.json(), commonRes.json(), ]); // Load markdown articles and extract frontmatter // 动态获取实际存在的文章列表 const articlesApiRes = await fetch(`/api/articles/${currentLang}`); const articlesApiData = await articlesApiRes.json(); const articleSlugs = articlesApiData.articles || []; const articlesData: any = {}; for (const slug of articleSlugs) { try { const markdownRes = await fetch(`/docs/${currentLang}/news/${slug}.md`); if (markdownRes.ok) { const markdownContent = await markdownRes.text(); const { frontmatter } = parseMarkdown(markdownContent); if (frontmatter.title) { articlesData[slug] = frontmatter; } } } catch (error) { console.warn(`Failed to load article ${slug}:`, error); // Fallback to JSON data if markdown is not available const jsonKey = getJsonKeyFromSlug(slug); if (newsData.articles && newsData.articles[jsonKey]) { articlesData[slug] = newsData.articles[jsonKey]; } } } // Merge markdown data with JSON translations const mergedNewsData = { ...newsData, articles: articlesData, }; setTranslations(mergedNewsData); setCommonTranslations(commonData); setLoading(false); } catch (error) { console.error('Failed to load translations:', error); setLoading(false); } }; loadTranslations(); }, [currentLang]); // Helper function to parse markdown frontmatter const parseMarkdown = (markdown: string) => { // 更强健的正则表达式,处理各种换行符情况 const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/; const match = markdown.match(frontmatterRegex); if (!match) { return { frontmatter: {}, content: markdown, }; } const frontmatterText = match[1]; const content = match[2]; // Enhanced YAML parser for frontmatter const frontmatter: any = {}; frontmatterText.split('\n').forEach((line) => { const colonIndex = line.indexOf(':'); if (colonIndex === -1) return; const key = line.substring(0, colonIndex).trim(); const value = line.substring(colonIndex + 1).trim(); if (key && value) { if (key === 'tags') { // Handle array format: [tag1, tag2, tag3] if (value.startsWith('[') && value.endsWith(']')) { frontmatter[key] = value .slice(1, -1) // Remove brackets .split(',') .map((tag) => tag.trim().replace(/['"]/g, '')) .filter((tag) => tag.length > 0); } else { frontmatter[key] = [value.replace(/['"]/g, '')]; } } else if (key === 'featured') { // Handle boolean values frontmatter[key] = value.toLowerCase() === 'true'; } else { // Handle string values frontmatter[key] = value.replace(/^['"]|['"]$/g, ''); } } }); return { frontmatter, content }; }; // Helper function to map slugs to JSON keys for fallback const getJsonKeyFromSlug = (slug: string) => { const slugMap: { [key: string]: string } = { 'cloudtech-new-platform': 'article1', 'cloud-trends-2024': 'article2', 'optimize-cloud-server': 'article3', 'rds-new-features': 'article4', 'cloud-security-practices': 'article5', 'iso-27001-certification': 'article6', }; return slugMap[slug] || slug; }; if (loading) { return (

Loading news...

); } const t = translations; const common = commonTranslations; // Filter and sort articles let filteredArticles = Object.entries(t.articles || {}); // Filter by category if (selectedCategory !== 'all') { filteredArticles = filteredArticles.filter( ([_, article]: [string, any]) => article.category === selectedCategory, ); } // Filter by search term if (searchTerm) { filteredArticles = filteredArticles.filter( ([_, article]: [string, any]) => article.title.toLowerCase().includes(searchTerm.toLowerCase()) || article.summary.toLowerCase().includes(searchTerm.toLowerCase()), ); } // Sort articles filteredArticles.sort(([_, a]: [string, any], [__, b]: [string, any]) => { if (sortBy === 'date') { return new Date(b.date).getTime() - new Date(a.date).getTime(); } return a.title.localeCompare(b.title); }); // Get featured article (latest) const featuredArticle = Object.entries(t.articles || {})[0] as [string, any] | undefined; return ( <>
{/* Navigation */} {/* Hero Section with Enhanced Design */}
{/* Background decorative elements */}

{t.title}

{t.subtitle}

{/* Search Bar */}
setSearchTerm(e.target.value)} className="w-full px-6 py-4 pl-12 bg-white/20 backdrop-blur-sm border border-white/30 rounded-2xl text-white placeholder-white/70 focus:outline-none focus:ring-2 focus:ring-white/50" data-oid="0y8rl1i" />
{/* Featured Article */} {featuredArticle && (

{currentLang === 'en' ? 'Featured News' : '精选新闻'}

{t.categories?.[(featuredArticle[1] as any).category]} {(featuredArticle[1] as any).date}

{(featuredArticle[1] as any).title}

{(featuredArticle[1] as any).summary}

{(featuredArticle[1] as any).author} {common.hero?.learn || 'Read More'}
)} {/* Filter and Sort Controls */}
{/* Category Filter */}
{Object.entries(t.categories || {}).map(([key, category]: [string, any]) => ( ))}
{/* Sort Control */}
{currentLang === 'en' ? 'Sort by:' : '排序:'}
{/* Articles Grid */}
{filteredArticles.length === 0 ? (

{currentLang === 'en' ? 'No articles found' : '未找到相关文章'}

{currentLang === 'en' ? 'Try adjusting your search or filter criteria' : '请尝试调整搜索或筛选条件'}

) : ( <>

{selectedCategory === 'all' ? currentLang === 'en' ? 'Latest News' : '最新资讯' : t.categories?.[selectedCategory]}

{currentLang === 'en' ? `Found ${filteredArticles.length} articles` : `找到 ${filteredArticles.length} 篇文章`}

{filteredArticles.map( ([key, article]: [string, any], index) => (
{/* Article Image Placeholder */}
{ categoryIcons[ article.category as keyof typeof categoryIcons ] }
{t.categories?.[article.category]} {article.date}

{article.title}

{article.summary}

{article.author}
{common.hero?.learn || 'Read More'}
), )}
)}
{/* Newsletter Subscription */}

{currentLang === 'en' ? 'Stay Updated with Our Latest News' : '订阅我们的最新资讯'}

{currentLang === 'en' ? 'Get the latest cloud computing insights, industry trends, and product updates delivered to your inbox.' : '获取最新的云计算洞察、行业趋势和产品更新,直接发送到您的邮箱。'}

{/* Footer */}
); }