Jacky Zhao
2023-09-13 71d81bde1d12aa386ec70be31cc86a37a7426bce
quartz/plugins/emitters/contentIndex.ts
@@ -1,5 +1,6 @@
import { GlobalConfiguration } from "../../cfg"
import { getDate } from "../../components/Date"
import { escapeHTML } from "../../util/escape"
import { FilePath, FullSlug, SimpleSlug, simplifySlug } from "../../util/path"
import { QuartzEmitterPlugin } from "../types"
import path from "path"
@@ -17,19 +18,21 @@
interface Options {
  enableSiteMap: boolean
  enableRSS: boolean
  rssLimit?: number
  includeEmptyFiles: boolean
}
const defaultOptions: Options = {
  enableSiteMap: true,
  enableRSS: true,
  rssLimit: 10,
  includeEmptyFiles: true,
}
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndex): string {
  const base = cfg.baseUrl ?? ""
  const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<url>
    <loc>https://${base}/${encodeURIComponent(slug)}</loc>
    <loc>https://${base}/${encodeURI(slug)}</loc>
    <lastmod>${content.date?.toISOString()}</lastmod>
  </url>`
  const urls = Array.from(idx)
@@ -38,27 +41,31 @@
  return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}</urlset>`
}
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex): string {
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex, limit?: number): string {
  const base = cfg.baseUrl ?? ""
  const root = `https://${base}`
  const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item>
    <title>${content.title}</title>
    <link>${root}/${encodeURIComponent(slug)}</link>
    <guid>${root}/${encodeURIComponent(slug)}</guid>
    <title>${escapeHTML(content.title)}</title>
    <link>${root}/${encodeURI(slug)}</link>
    <guid>${root}/${encodeURI(slug)}</guid>
    <description>${content.description}</description>
    <pubDate>${content.date?.toUTCString()}</pubDate>
  </item>`
  const items = Array.from(idx)
    .map(([slug, content]) => createURLEntry(simplifySlug(slug), content))
    .slice(0, limit ?? idx.size)
    .join("")
  return `<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
    <channel>
      <title>${cfg.pageTitle}</title>
      <title>${escapeHTML(cfg.pageTitle)}</title>
      <link>${root}</link>
      <description>Recent content on ${cfg.pageTitle}</description>
      <description>${!!limit ? `Last ${limit} notes` : "Recent notes"} on ${
        cfg.pageTitle
      }</description>
      <generator>Quartz -- quartz.jzhao.xyz</generator>
      ${items}
    </channel>
@@ -101,7 +108,7 @@
      if (opts?.enableRSS) {
        emitted.push(
          await emit({
            content: generateRSSFeed(cfg, linkIndex),
            content: generateRSSFeed(cfg, linkIndex, opts.rssLimit),
            slug: "index" as FullSlug,
            ext: ".xml",
          }),