Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
2 changes: 2 additions & 0 deletions constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
17 changes: 10 additions & 7 deletions src/layouts/base.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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;
---

Expand All @@ -23,17 +26,17 @@ const {
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<meta name="description" content={description} />
<meta name="keyword" content={SITE_META_KEYWORDS.join(",")} />
<meta name="keyword" content={keywords.join(",")} />

<meta property="og:url" content={url.href} />
<meta property="og:url" content={canonicalUrl.href} />
<meta property="og:type" content="website" />
<meta property="og:title" content={`${pageTitle} - ${subtitle}`} />
<meta property="og:description" content={description} />
<meta property="og:image" content={ogImageUrl} />

<meta name="twitter:card" content="summary_large_image" />
<meta property="twitter:domain" content={url.host} />
<meta property="twitter:url" content={url.href} />
<meta property="twitter:domain" content={canonicalUrl.host} />
<meta property="twitter:url" content={canonicalUrl.href} />
<meta name="twitter:title" content={`${pageTitle} - ${subtitle}`} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={ogImageUrl} />
Expand Down
17 changes: 15 additions & 2 deletions src/layouts/word.astro
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@ 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";

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`
Expand All @@ -22,7 +30,12 @@ const ogImageUrl = `${Astro.url.origin}/api/open-graph/${encodeURIComponent(Stri
const editUrl = `/editor/edit/${frontmatter.url.split("/")[3].split(".")[0]}`;
---

<BaseLayout pageTitle={frontmatter.title} ogImageUrl={ogImageUrl}>
<BaseLayout
pageTitle={frontmatter.title}
description={excerpt}
keywords={keywords}
ogImageUrl={ogImageUrl}
>
<div class="main-wrapper">
<Navbar>
<Search triggerSize="sm" dictionary={dictionary} client:load />
Expand Down
84 changes: 84 additions & 0 deletions src/lib/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 1 addition & 16 deletions src/pages/api/open-graph/[...slug].png.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/utils/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
buildStatsUrl,
buildWordPathname,
buildWordSlug,
getExcerpt,
getKeywords,
toggleMarkdownListPrefix,
continueMarkdownListOnEnter,
toggleMarkdownWrap,
Expand Down Expand Up @@ -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);
});
});
Loading