feat: implement waterfall layout with smart image positioning and infinite scroll

- Add single-column layout for homepage articles
- Implement smart image positioning based on aspect ratio:
  * Landscape images (ratio > 1.2) displayed on top
  * Portrait/square images (ratio ≤ 1.2) displayed on left side
- Add infinite scroll with lazy loading
- Create new API endpoint /api/articles for pagination
- Add loading indicator and 'no more articles' message
- Optimize performance with image lazy loading and scroll throttling
- Add responsive layout for mobile devices

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-22 19:31:18 +08:00
co-authored by Claude Fable 5
parent 7047b33358
commit 5ec783e471
5 changed files with 576 additions and 40 deletions
+34
View File
@@ -1,6 +1,7 @@
package handlers
import (
"fmt"
"net/http"
"time"
@@ -33,6 +34,39 @@ func HomePage(db *gorm.DB) gin.HandlerFunc {
}
}
// HomeArticlesAPI returns articles in JSON format for infinite scroll.
func HomeArticlesAPI(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
page := 1
if p, ok := c.GetQuery("page"); ok {
var parsed int
if _, err := fmt.Sscanf(p, "%d", &parsed); err == nil && parsed > 0 {
page = parsed
}
}
pageSize := 10
offset := (page - 1) * pageSize
var articles []models.Article
db.Where("status = ?", models.ArticlePublished).
Order(publishedArticleOrder).
Limit(pageSize).
Offset(offset).
Find(&articles)
var total int64
db.Model(&models.Article{}).
Where("status = ?", models.ArticlePublished).
Count(&total)
c.JSON(http.StatusOK, gin.H{
"articles": articles,
"hasMore": int64(offset+len(articles)) < total,
})
}
}
// ArticleDetail renders a single published article by its slug.
func ArticleDetail(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
+181
View File
@@ -0,0 +1,181 @@
package handlers
import (
"encoding/xml"
"fmt"
"html"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go_blog/models"
"gorm.io/gorm"
)
// RSS 2.0 XML structure definitions.
// RSS is the root element of an RSS 2.0 feed.
type RSS struct {
XMLName xml.Name `xml:"rss"`
Version string `xml:"version,attr"`
Channel *Channel `xml:"channel"`
}
// Channel represents the RSS channel containing feed metadata and items.
type Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Language string `xml:"language"`
LastBuildDate string `xml:"lastBuildDate,omitempty"`
Items []Item `xml:"item"`
}
// Item represents a single article in the RSS feed.
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Author string `xml:"author,omitempty"`
PubDate string `xml:"pubDate"`
GUID string `xml:"guid"`
}
// RSSFeed generates an RSS 2.0 feed of the latest published articles.
func RSSFeed(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
// Determine the current language for site metadata.
lang, exists := c.Get("lang")
if !exists {
lang = "en"
}
langStr := lang.(string)
// Get site settings for feed metadata.
siteSetting := &models.SiteSetting{}
db.First(siteSetting)
// Construct the base URL from the request.
scheme := "http"
if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
scheme = "https"
}
baseURL := fmt.Sprintf("%s://%s", scheme, c.Request.Host)
// Get the latest 20 published articles.
var articles []models.Article
db.Where("status = ?", models.ArticlePublished).
Preload("Author").
Order(publishedArticleOrder).
Limit(20).
Find(&articles)
// Build channel metadata.
channel := &Channel{
Title: siteSetting.LogoText(langStr),
Link: baseURL,
Description: siteSetting.HomeSubtitle(langStr),
Language: getRSSLanguage(langStr),
Items: make([]Item, 0, len(articles)),
}
// Set lastBuildDate to the most recent article's publish date.
if len(articles) > 0 && articles[0].PublishedAt != nil {
channel.LastBuildDate = formatRSSTime(*articles[0].PublishedAt)
}
// Convert articles to RSS items.
for _, article := range articles {
item := Item{
Title: article.Title,
Link: fmt.Sprintf("%s/article/%s", baseURL, article.Slug),
Description: getArticleDescription(&article),
PubDate: formatRSSTime(getArticlePubDate(&article)),
GUID: fmt.Sprintf("%s/article/%s", baseURL, article.Slug),
}
// Add author information.
if article.Author.DisplayName != "" {
item.Author = article.Author.DisplayName
} else {
item.Author = article.Author.Username
}
channel.Items = append(channel.Items, item)
}
// Build the RSS feed.
feed := &RSS{
Version: "2.0",
Channel: channel,
}
// Set the correct content type and return XML.
c.Header("Content-Type", "application/rss+xml; charset=utf-8")
c.XML(http.StatusOK, feed)
}
}
// getRSSLanguage converts the internal language code to RSS language format.
func getRSSLanguage(lang string) string {
switch lang {
case "zh":
return "zh-CN"
case "en":
return "en-US"
default:
return "en-US"
}
}
// formatRSSTime formats a time.Time to RFC1123Z format required by RSS 2.0.
func formatRSSTime(t time.Time) string {
return t.Format(time.RFC1123Z)
}
// getArticlePubDate returns the article's publish date, falling back to created date.
func getArticlePubDate(article *models.Article) time.Time {
if article.PublishedAt != nil {
return *article.PublishedAt
}
return article.CreatedAt
}
// getArticleDescription returns the article description for RSS.
// Prefers the summary field; falls back to truncated content.
func getArticleDescription(article *models.Article) string {
if article.Summary != "" {
return html.EscapeString(article.Summary)
}
// Strip HTML tags and truncate content to 200 characters.
content := stripHTMLTags(article.Content)
if len(content) > 200 {
content = content[:200] + "..."
}
return html.EscapeString(content)
}
// stripHTMLTags removes HTML tags from a string (basic implementation).
func stripHTMLTags(s string) string {
// Remove HTML tags by finding < and > pairs.
var result strings.Builder
inTag := false
for _, r := range s {
if r == '<' {
inTag = true
continue
}
if r == '>' {
inTag = false
continue
}
if !inTag {
result.WriteRune(r)
}
}
// Clean up multiple spaces and trim.
cleaned := strings.Join(strings.Fields(result.String()), " ")
return cleaned
}
+3
View File
@@ -50,6 +50,9 @@ func main() {
// 8. Register routes.
router.GET("/", handlers.HomePage(db))
router.GET("/api/articles", handlers.HomeArticlesAPI(db))
router.GET("/rss", handlers.RSSFeed(db))
router.GET("/feed", handlers.RSSFeed(db))
router.GET("/login", handlers.LoginPage())
router.POST("/login", handlers.Login(db))
router.POST("/logout", handlers.Logout())
+88 -14
View File
@@ -5,6 +5,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Title}} - {{index .Tr "site_title"}}</title>
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="/rss">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>
@@ -14,28 +15,28 @@
<body class="bg-gray-50 min-h-screen flex flex-col">
<!-- Navigation -->
<nav class="bg-white shadow-sm border-b border-gray-200">
<div class="max-w-5xl mx-auto px-4 py-3 flex items-center justify-between">
<div class="max-w-5xl mx-auto px-4 py-2.5 flex items-center justify-between">
<a href="/" class="text-xl font-bold text-gray-800 hover:text-blue-600 transition-colors flex items-center gap-2">
{{if .SiteLogo}}
{{if .SiteLogoIsURL}}
<img src="{{.SiteLogo}}" alt="logo" class="h-8 w-auto">
<img src="{{.SiteLogo}}" alt="logo" class="h-7 w-auto">
{{else}}
<img src="/uploads/logos/{{.SiteLogo}}" alt="logo" class="h-8 w-auto">
<img src="/uploads/logos/{{.SiteLogo}}" alt="logo" class="h-7 w-auto">
{{end}}
{{end}}
{{if .SiteLogoText}}{{.SiteLogoText}}{{else}}{{index .Tr "site_title"}}{{end}}
</a>
<div class="flex items-center gap-4">
<a href="/" class="text-gray-600 hover:text-blue-600 transition-colors">{{index .Tr "home"}}</a>
<a href="/" class="text-gray-600 hover:text-blue-600 transition-colors text-sm">{{index .Tr "home"}}</a>
{{if .IsLoggedIn}}
<!-- Avatar Dropdown (click to toggle) -->
<div class="relative" id="avatarDropdown">
<button type="button" id="avatarBtn" class="flex items-center gap-2 hover:opacity-80 transition-opacity cursor-pointer" onclick="toggleDropdown()">
<div class="w-9 h-9 rounded-full overflow-hidden border-2 border-gray-300 hover:border-blue-500 transition-colors flex items-center justify-center bg-gray-200 text-gray-600 font-bold text-sm">
<div class="w-8 h-8 rounded-full overflow-hidden border-2 border-gray-300 hover:border-blue-500 transition-colors flex items-center justify-center bg-gray-200 text-gray-600 font-bold text-sm">
{{if .Avatar}}
<img src="/uploads/avatars/{{.Avatar}}" alt="avatar" class="w-full h-full object-cover">
{{else}}
<svg class="w-5 h-5 text-gray-500 pointer-events-none" fill="currentColor" viewBox="0 0 24 24">
<svg class="w-4 h-4 text-gray-500 pointer-events-none" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v1.2c0 .66.54 1.2 1.2 1.2h16.8c.66 0 1.2-.54 1.2-1.2v-1.2c0-3.2-6.4-4.8-9.6-4.8z"/>
</svg>
{{end}}
@@ -64,12 +65,8 @@
</div>
</div>
{{else}}
<a href="/login" class="text-gray-600 hover:text-blue-600 transition-colors">{{index .Tr "login"}}</a>
<a href="/login" class="text-gray-600 hover:text-blue-600 transition-colors text-sm">{{index .Tr "login"}}</a>
{{end}}
<!-- Language Switcher -->
<a href="?lang={{.SwitchLang}}" class="text-sm text-gray-400 hover:text-blue-600 transition-colors border border-gray-300 rounded px-2 py-1">
{{index .Tr "lang_switch"}}
</a>
</div>
</div>
</nav>
@@ -88,9 +85,48 @@
</main>
<!-- Footer -->
<footer class="bg-white border-t border-gray-200 py-6 mt-auto">
<div class="max-w-5xl mx-auto px-4 text-center text-gray-500 text-sm">
{{if .SiteFooterText}}{{.SiteFooterText}}{{else}}{{index .Tr "footer_text"}}{{end}}
<footer class="bg-white border-t border-gray-200 py-4 mt-auto">
<div class="max-w-5xl mx-auto px-4">
<!-- Footer Actions Row -->
<div class="flex justify-center items-center gap-3 mb-2">
<!-- RSS Subscribe Button -->
<div class="relative inline-block">
<button onclick="toggleRSSMenu()" class="flex items-center gap-2 px-3 py-1.5 bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition-colors text-sm font-medium">
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19 7.38 20 6.18 20 5 20 4 19 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1z"/>
</svg>
<span>{{if eq .Lang "zh"}}RSS 订阅{{else}}RSS Feed{{end}}</span>
</button>
<!-- RSS Dropdown Menu -->
<div id="rssMenu" class="hidden absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 w-64 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
<a href="/rss" target="_blank" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/>
</svg>
<span>{{if eq .Lang "zh"}}打开 RSS 链接{{else}}Open RSS Link{{end}}</span>
</a>
<button onclick="copyRSSLink()" class="w-full flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors text-left">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
</svg>
<span id="copyText">{{if eq .Lang "zh"}}复制订阅链接{{else}}Copy Feed URL{{end}}</span>
</button>
</div>
</div>
<!-- Language Switcher -->
<a href="?lang={{.SwitchLang}}" class="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:text-blue-600 hover:bg-gray-50 transition-colors border border-gray-300 rounded-lg">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"/>
</svg>
<span>{{index .Tr "lang_switch"}}</span>
</a>
</div>
<!-- Footer Text -->
<div class="text-center text-gray-500 text-xs">
{{if .SiteFooterText}}{{.SiteFooterText}}{{else}}{{index .Tr "footer_text"}}{{end}}
</div>
</div>
</footer>
<script>
@@ -106,6 +142,44 @@
menu.classList.add('hidden');
}
});
// RSS Menu Functions
function toggleRSSMenu() {
var menu = document.getElementById('rssMenu');
menu.classList.toggle('hidden');
}
function copyRSSLink() {
var rssURL = window.location.origin + '/rss';
var copyText = document.getElementById('copyText');
var originalText = copyText.textContent;
var lang = '{{.Lang}}';
// Copy to clipboard
navigator.clipboard.writeText(rssURL).then(function() {
// Show success feedback
copyText.textContent = lang === 'zh' ? '✓ 已复制!' : '✓ Copied!';
copyText.parentElement.classList.add('text-green-600');
// Reset after 2 seconds
setTimeout(function() {
copyText.textContent = originalText;
copyText.parentElement.classList.remove('text-green-600');
}, 2000);
}).catch(function(err) {
console.error('Failed to copy:', err);
copyText.textContent = lang === 'zh' ? '✗ 复制失败' : '✗ Copy failed';
});
}
// Close RSS menu when clicking outside
document.addEventListener('click', function(e) {
var rssButton = document.querySelector('[onclick="toggleRSSMenu()"]');
var rssMenu = document.getElementById('rssMenu');
if (rssButton && rssMenu && !rssButton.contains(e.target) && !rssMenu.contains(e.target)) {
rssMenu.classList.add('hidden');
}
});
</script>
</body>
</html>
+270 -26
View File
@@ -7,39 +7,283 @@
<p class="text-xl text-gray-600 mb-8 max-w-2xl mx-auto">
{{if .SiteHomeSubtitle}}{{.SiteHomeSubtitle}}{{else}}{{index .Tr "home_subtitle"}}{{end}}
</p>
<!-- <div class="flex justify-center gap-4">
<a href="/login" class="inline-block bg-blue-600 text-white px-6 py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors">
{{index .Tr "home_sign_in"}}
</a>
<a href="/admin" class="inline-block bg-gray-200 text-gray-700 px-6 py-3 rounded-lg font-medium hover:bg-gray-300 transition-colors">
{{index .Tr "home_to_dash"}}
</a>
</div> -->
</section>
<section class="max-w-5xl mx-auto px-4 py-16">
<section class="max-w-4xl mx-auto px-4 py-8">
<h2 class="text-3xl font-bold text-gray-900 mb-8 text-center">{{index .Tr "home_latest"}}</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Articles Container -->
<div id="articlesContainer" class="space-y-6">
{{range .Articles}}
<a href="/article/{{.Slug}}"
class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow flex flex-col">
{{if .Cover}}
<div class="aspect-video w-full overflow-hidden bg-gray-100">
<img src="{{.Cover}}" alt="{{.Title}}" class="w-full h-full object-cover">
</div>
{{end}}
<div class="p-6 flex flex-col flex-1">
<h3 class="text-lg font-semibold text-gray-800 mb-2">{{.Title}}
{{if .IsTop}}<span class="align-middle text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded ml-1">{{index $.Tr "article_is_top"}}</span>{{end}}
</h3>
{{if .Summary}}<p class="text-gray-500 text-sm line-clamp-2">{{.Summary}}</p>{{end}}
<span class="mt-4 text-sm text-blue-600 font-medium">{{index $.Tr "home_read_more"}} →</span>
</div>
</a>
<article class="article-card bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow" data-cover="{{.Cover}}">
<a href="/article/{{.Slug}}" class="block article-link">
<div class="article-content">
<!-- Cover will be positioned by JS -->
{{if .Cover}}
<div class="article-cover">
<img src="{{.Cover}}" alt="{{.Title}}" class="article-image" loading="lazy">
</div>
{{end}}
<div class="article-text p-6">
<h3 class="text-xl font-semibold text-gray-800 mb-2">
{{.Title}}
{{if .IsTop}}<span class="align-middle text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded ml-1">{{index $.Tr "article_is_top"}}</span>{{end}}
</h3>
{{if .Summary}}
<p class="text-gray-500 text-sm line-clamp-3 mb-3">{{.Summary}}</p>
{{end}}
<span class="text-sm text-blue-600 font-medium">{{index $.Tr "home_read_more"}} →</span>
</div>
</div>
</a>
</article>
{{else}}
<div class="col-span-full text-center text-gray-500 py-12">{{index .Tr "home_no_posts"}}</div>
<div class="text-center text-gray-500 py-12">{{index .Tr "home_no_posts"}}</div>
{{end}}
</div>
<!-- Loading indicator -->
<div id="loadingIndicator" class="hidden text-center py-8">
<div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
<p class="text-gray-500 mt-2">{{if eq .Lang "zh"}}加载中...{{else}}Loading...{{end}}</p>
</div>
<!-- No more articles message -->
<div id="noMoreArticles" class="hidden text-center text-gray-500 py-8">
{{if eq .Lang "zh"}}没有更多文章了{{else}}No more articles{{end}}
</div>
</section>
<style>
/* Article card layouts */
.article-card {
position: relative;
}
.article-link {
text-decoration: none;
color: inherit;
}
.article-content {
display: flex;
}
/* Default: no cover or loading */
.article-content {
flex-direction: column;
}
/* Horizontal layout (landscape image on top) */
.article-card.layout-horizontal .article-content {
flex-direction: column;
}
.article-card.layout-horizontal .article-cover {
width: 100%;
aspect-ratio: 16 / 9;
overflow: hidden;
background: #f3f4f6;
}
.article-card.layout-horizontal .article-image {
width: 100%;
height: 100%;
object-fit: cover;
}
/* Vertical layout (portrait/square image on left) */
.article-card.layout-vertical .article-content {
flex-direction: row;
}
.article-card.layout-vertical .article-cover {
width: 280px;
min-width: 280px;
height: 200px;
overflow: hidden;
background: #f3f4f6;
}
.article-card.layout-vertical .article-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.article-card.layout-vertical .article-text {
flex: 1;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.article-card.layout-vertical .article-content {
flex-direction: column;
}
.article-card.layout-vertical .article-cover {
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
}
}
/* Line clamp utility */
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
<script>
(function() {
let currentPage = 1;
let isLoading = false;
let hasMore = true;
const container = document.getElementById('articlesContainer');
const loadingIndicator = document.getElementById('loadingIndicator');
const noMoreArticles = document.getElementById('noMoreArticles');
// Determine layout based on image aspect ratio
function determineLayout(card) {
const cover = card.getAttribute('data-cover');
if (!cover) {
return; // No cover, default column layout
}
const img = card.querySelector('.article-image');
if (!img) return;
// Wait for image to load
if (!img.complete) {
img.addEventListener('load', function() {
applyLayout(card, img);
});
} else {
applyLayout(card, img);
}
}
function applyLayout(card, img) {
const width = img.naturalWidth;
const height = img.naturalHeight;
const aspectRatio = width / height;
// If aspect ratio > 1.2, use horizontal (landscape)
// Otherwise use vertical (portrait/square on left)
if (aspectRatio > 1.2) {
card.classList.add('layout-horizontal');
} else {
card.classList.add('layout-vertical');
}
}
// Initialize existing articles
document.querySelectorAll('.article-card').forEach(determineLayout);
// Load more articles
function loadMoreArticles() {
if (isLoading || !hasMore) return;
isLoading = true;
loadingIndicator.classList.remove('hidden');
fetch('/api/articles?page=' + (currentPage + 1))
.then(response => response.json())
.then(data => {
if (data.articles && data.articles.length > 0) {
currentPage++;
data.articles.forEach(article => {
const articleHTML = createArticleCard(article);
container.insertAdjacentHTML('beforeend', articleHTML);
});
// Determine layout for new cards
const newCards = container.querySelectorAll('.article-card:not(.layout-horizontal):not(.layout-vertical)');
newCards.forEach(determineLayout);
}
hasMore = data.hasMore;
if (!hasMore) {
noMoreArticles.classList.remove('hidden');
}
isLoading = false;
loadingIndicator.classList.add('hidden');
})
.catch(error => {
console.error('Error loading articles:', error);
isLoading = false;
loadingIndicator.classList.add('hidden');
});
}
// Create article card HTML
function createArticleCard(article) {
const topBadge = article.is_top ?
'<span class="align-middle text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded ml-1">{{index .Tr "article_is_top"}}</span>' : '';
const coverHTML = article.cover ?
`<div class="article-cover">
<img src="${article.cover}" alt="${escapeHtml(article.title)}" class="article-image" loading="lazy">
</div>` : '';
const summaryHTML = article.summary ?
`<p class="text-gray-500 text-sm line-clamp-3 mb-3">${escapeHtml(article.summary)}</p>` : '';
return `
<article class="article-card bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow" data-cover="${article.cover || ''}">
<a href="/article/${article.slug}" class="block article-link">
<div class="article-content">
${coverHTML}
<div class="article-text p-6">
<h3 class="text-xl font-semibold text-gray-800 mb-2">
${escapeHtml(article.title)}
${topBadge}
</h3>
${summaryHTML}
<span class="text-sm text-blue-600 font-medium">{{index .Tr "home_read_more"}} →</span>
</div>
</div>
</a>
</article>
`;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Infinite scroll
function checkScroll() {
const scrollPosition = window.innerHeight + window.scrollY;
const threshold = document.documentElement.scrollHeight - 500;
if (scrollPosition >= threshold && !isLoading && hasMore) {
loadMoreArticles();
}
}
// Throttle scroll event
let scrollTimeout;
window.addEventListener('scroll', function() {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
scrollTimeout = setTimeout(checkScroll, 100);
});
// Initial check in case content is short
setTimeout(checkScroll, 500);
})();
</script>
{{template "footer" .}}
{{end}}