diff --git a/src/layouts/Layout.astro b/src/layouts/Layout.astro index c18052209c..865e87d390 100644 --- a/src/layouts/Layout.astro +++ b/src/layouts/Layout.astro @@ -19,6 +19,7 @@ import { defaultFavicons } from "../constants/icon"; import type { Favicon } from "../types/config"; import { pathsEqual, url } from "../utils/url-utils"; import "katex/dist/katex.css"; +import { getCollection } from "astro:content"; interface Props { title?: string; @@ -30,6 +31,50 @@ interface Props { let { title, banner, description, lang, setOGTypeArticle } = Astro.props; +let ogImage: string | undefined = undefined; + +if (banner && typeof banner === 'string' && banner.trim() !== '') { + if (banner.startsWith('http://') || banner.startsWith('https://')) { + ogImage = banner; + } else { + ogImage = new URL(banner, Astro.site || Astro.url.origin).href; + } +} + +const slug = Astro.url.pathname.split('/').filter(Boolean).pop(); + +interface PageData { + published?: Date | string; + updated?: Date | string; + tags?: string[]; +} + +let pageData: PageData = {}; + +try { + const allEntries = await getCollection("posts"); + const entry = allEntries.find(e => e.slug === slug); + if (entry) pageData = entry.data as PageData; +} catch (e) { + // No data, silent fail +} + +const formatDate = (date: Date | string | undefined): string | null => { + if (!date) return null; + if (date instanceof Date) { + return date.toISOString().split('T')[0]; + } + if (typeof date === 'string') { + return date.split('T')[0]; + } + return null; +}; + +const publishedDate = formatDate(pageData.published); +const updatedDate = formatDate(pageData.updated); + +const tags: string[] = pageData.tags || []; + // apply a class to the body element to decide the height of the banner, only used for initial page load // Swup can update the body for each page visit, but it's after the page transition, causing a delay for banner height change // so use Swup hooks instead to change the height immediately when a link is clicked @@ -81,23 +126,34 @@ const bannerOffset =