diff --git a/astro.config.mjs b/astro.config.mjs index 34da094..e970b1d 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -6,8 +6,16 @@ import partytown from "@astrojs/partytown"; import tailwindcss from "tailwindcss"; import autoprefixer from "autoprefixer"; +const VERCEL_PREVIEW_SITE = + process.env.VERCEL_ENV === "preview" && process.env.VERCEL_BRANCH_URL + ? `https://${process.env.VERCEL_BRANCH_URL}` + : undefined; + +const site = VERCEL_PREVIEW_SITE || "https://www.jargons.dev"; + // https://astro.build/config export default defineConfig({ + site, integrations: [ mdx(), react(), diff --git a/constants.js b/constants.js index 0d2dfd7..6be0271 100644 --- a/constants.js +++ b/constants.js @@ -12,6 +12,8 @@ export const LABELS = { export const SITE_META_DESCRIPTION = "A community-driven dictionary that simplifies software, engineering and tech terms for all levels. Curated by contributors, jargons.dev offers clear, easy-to-understand definitions."; +export const SITE_META_SUBTITLE = "Jargons.dev"; + export const SITE_META_KEYWORDS = [ "dev jargon", "dev jargons", diff --git a/src/layouts/base.astro b/src/layouts/base.astro index 8d9e844..073cabb 100644 --- a/src/layouts/base.astro +++ b/src/layouts/base.astro @@ -2,17 +2,20 @@ import "@fontsource/inter"; import "@fontsource/ibm-plex-mono"; import "../base.css"; -import { SITE_META_KEYWORDS, SITE_META_DESCRIPTION } from "../../constants.js"; +import { SITE_META_KEYWORDS, SITE_META_DESCRIPTION, SITE_META_SUBTITLE } from "../../constants.js"; const MEASUREMENT_ID = import.meta.env.PUBLIC_GOOGLE_ANALYTICS_MEASUREMENT_ID; const { props, url } = Astro; +const siteOrigin = import.meta.env.DEV ? url.origin : Astro.site; +const canonicalUrl = new URL(url.pathname, siteOrigin); const { pageTitle, class: list, - ogImageUrl = `${url.origin}/og.png`, + keywords = SITE_META_KEYWORDS, + ogImageUrl = new URL("/og.png", siteOrigin).href, description = SITE_META_DESCRIPTION, - subtitle = "Developer Jargons", + subtitle = SITE_META_SUBTITLE, } = props; --- @@ -23,17 +26,17 @@ const { - + - + - - + + diff --git a/src/layouts/word.astro b/src/layouts/word.astro index aaa0e95..1f4c613 100644 --- a/src/layouts/word.astro +++ b/src/layouts/word.astro @@ -6,6 +6,7 @@ import BaseLayout from "./base.astro"; import { getCollection } from "astro:content"; import Navbar from "../components/navbar.astro"; import Search from "../components/islands/search.jsx"; +import { buildWordSlug, getExcerpt, getKeywords } from "../lib/utils/index.js"; import JAIFollowUpChatWidget, { JAIFollowUpChatWidgetTrigger, } from "../../apps/jai/components/follow-up-chat.jsx"; @@ -13,7 +14,14 @@ import JAIFollowUpChatWidget, { const { frontmatter } = Astro.props; const dictionary = await getCollection("dictionary"); const wordSlug = Astro.url.pathname.split("/").filter(Boolean).at(-1) ?? ""; -const ogImageUrl = `${Astro.url.origin}/api/open-graph/${encodeURIComponent(String(wordSlug))}.png`; +const word = dictionary.find((entry) => buildWordSlug(entry.id) === wordSlug); +const excerpt = getExcerpt(word?.body); +const keywords = getKeywords(frontmatter.title, word?.body); +const siteOrigin = import.meta.env.DEV ? Astro.url.origin : Astro.site; +const ogImageUrl = new URL( + `/api/open-graph/${encodeURIComponent(String(wordSlug))}.png`, + siteOrigin, +).href; /** * @todo implement a better way to resolve the `slug` used in the `editUrl` @@ -22,7 +30,12 @@ const ogImageUrl = `${Astro.url.origin}/api/open-graph/${encodeURIComponent(Stri const editUrl = `/editor/edit/${frontmatter.url.split("/")[3].split(".")[0]}`; --- - +
diff --git a/src/lib/utils/index.js b/src/lib/utils/index.js index 7d51472..b5b4c33 100644 --- a/src/lib/utils/index.js +++ b/src/lib/utils/index.js @@ -100,6 +100,90 @@ export function buildWordSlug(id) { return id.split(".")[0]; } +/** + * Get a plain-text excerpt from the first non-code paragraph of Markdown + * @param {string} body + * @returns {string} + */ +export function getExcerpt(body = "") { + const firstParagraph = body + .split(/\r?\n\s*\r?\n/) + .find( + (paragraph) => paragraph.trim() && !paragraph.trim().startsWith("```"), + ); + const normalized = (firstParagraph ?? "") + .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1") + .replace(/`([^`]+)`/g, "$1") + .replace(/[*_>#]/g, "") + .replace(/\s+/g, " ") + .trim(); + + if (normalized.length <= 320) return normalized; + + return `${normalized.slice(0, 317).trimEnd()}...`; +} + +/** + * Extract a short, deduplicated keyword list from a word title and definition + * @todo Consider adding more sophisticated keyword extraction logic - this can help improve the relevance of extracted keywords + * @param {string} title + * @param {string} body + * @returns {string[]} + */ +export function getKeywords(title = "", body = "") { + const stopWords = new Set([ + "about", + "after", + "also", + "and", + "are", + "as", + "at", + "be", + "by", + "for", + "from", + "has", + "have", + "into", + "is", + "it", + "its", + "of", + "on", + "or", + "that", + "the", + "their", + "this", + "to", + "using", + "was", + "were", + "which", + "with", + ]); + const normalizedTitle = title.trim().toLowerCase(); + const keywords = normalizedTitle ? [normalizedTitle] : []; + const seen = new Set(keywords); + const words = + `${title} ${getExcerpt(body)}`.match(/[\p{L}\p{N}+#.-]+/gu) ?? []; + + for (const word of words) { + const keyword = word.replace(/^[.-]+|[.-]+$/g, "").toLowerCase(); + if (keyword.length < 3 || stopWords.has(keyword) || seen.has(keyword)) { + continue; + } + + keywords.push(keyword); + seen.add(keyword); + + if (keywords.length === 12) break; + } + + return keywords; +} + /** * Get branch name from branch ref * @param {string} branchRef diff --git a/src/pages/api/open-graph/[...slug].png.js b/src/pages/api/open-graph/[...slug].png.js index 4cdc2cf..8913d63 100644 --- a/src/pages/api/open-graph/[...slug].png.js +++ b/src/pages/api/open-graph/[...slug].png.js @@ -4,6 +4,7 @@ import { Resvg } from "@resvg/resvg-js"; import fs from "node:fs"; import path from "node:path"; import { getCollection } from "astro:content"; +import { getExcerpt } from "../../../lib/utils/index.js"; export const prerender = true; @@ -76,22 +77,6 @@ function truncate(text, limit) { return `${normalized.slice(0, limit - 3).trimEnd()}...`; } -function getExcerpt(body = "") { - const firstParagraph = body - .split(/\r?\n\s*\r?\n/) - .find( - (paragraph) => paragraph.trim() && !paragraph.trim().startsWith("```"), - ); - - return truncate( - (firstParagraph ?? "") - .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1") - .replace(/`([^`]+)`/g, "$1") - .replace(/[*_>#]/g, ""), - 320, - ); -} - /** * Generate a share image for a dictionary entry. * @param {import("astro").APIContext} context diff --git a/tests/unit/utils/index.test.js b/tests/unit/utils/index.test.js index c89c2fb..eeb5472 100644 --- a/tests/unit/utils/index.test.js +++ b/tests/unit/utils/index.test.js @@ -10,6 +10,8 @@ import { buildStatsUrl, buildWordPathname, buildWordSlug, + getExcerpt, + getKeywords, toggleMarkdownListPrefix, continueMarkdownListOnEnter, toggleMarkdownWrap, @@ -438,3 +440,41 @@ describe("buildWordSlug", () => { expect(buildWordSlug("")).toBe(""); }); }); + +describe("getExcerpt", () => { + it("extracts and simplifies the first non-code paragraph", () => { + expect( + getExcerpt( + "```js\nignored()\n```\n\n**QUIC** uses [`UDP`](https://example.com) and `TLS`.\n\nA second paragraph.", + ), + ).toBe("QUIC uses UDP and TLS."); + }); + + it("truncates excerpts to 320 characters", () => { + expect(getExcerpt("a".repeat(321))).toBe(`${"a".repeat(317)}...`); + }); + + it("returns an empty string when no paragraph is available", () => { + expect(getExcerpt()).toBe(""); + }); +}); + +describe("getKeywords", () => { + it("extracts unique terms from the title and first definition paragraph", () => { + expect( + getKeywords("QUIC", "QUIC is a fast protocol using UDP and TCP."), + ).toEqual(["quic", "fast", "protocol", "udp", "tcp"]); + }); + + it("keeps a title keyword when the definition is empty", () => { + expect(getKeywords("C", "")).toEqual(["c"]); + }); + + it("limits the list to twelve keywords", () => { + const body = Array.from({ length: 20 }, (_, index) => `term${index}`).join( + " ", + ); + + expect(getKeywords("Example", body)).toHaveLength(12); + }); +});