@tansy/blog 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/text.js ADDED
@@ -0,0 +1,98 @@
1
+ /** Pure helpers, shared by the server half and the render module. No imports, so both can use them. */
2
+ export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3
+ /** Lowercase letters, digits and single hyphens, from any title. */
4
+ export function slugify(text) {
5
+ const slug = text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase()
6
+ .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80).replace(/-+$/, "");
7
+ return slug || "post";
8
+ }
9
+ const str = (value) => (typeof value === "string" ? value : "");
10
+ /** The words in a rich text document, one string per top-level node. */
11
+ function richTextParagraphs(doc) {
12
+ const words = (node) => {
13
+ if (!node || typeof node !== "object")
14
+ return "";
15
+ const { text, content } = node;
16
+ if (typeof text === "string")
17
+ return text;
18
+ if (!Array.isArray(content))
19
+ return "";
20
+ // Text runs with different marks sit side by side, so only block nodes get a space between them.
21
+ const inline = content.every((child) => typeof child?.text === "string" || child?.type === "hardBreak");
22
+ return content.map((child) => (child?.type === "hardBreak" ? " " : words(child))).join(inline ? "" : " ");
23
+ };
24
+ const content = doc?.content;
25
+ return Array.isArray(content) ? content.map(words).map((part) => part.replace(/\s+/g, " ").trim()).filter(Boolean) : [];
26
+ }
27
+ /** The prose in a post's blocks, in order. Code and embeds aren't prose. */
28
+ export function blockParagraphs(blocks) {
29
+ if (!Array.isArray(blocks))
30
+ return [];
31
+ return blocks.flatMap((block) => {
32
+ const value = block?.value ?? {};
33
+ switch (block?.type) {
34
+ case "blog_text":
35
+ case "blog_callout": return richTextParagraphs(value.body);
36
+ case "blog_quote": return [str(value.text)].filter(Boolean);
37
+ case "blog_image": return [str(value.caption)].filter(Boolean);
38
+ default: return [];
39
+ }
40
+ });
41
+ }
42
+ export const WORDS_PER_MINUTE = 220;
43
+ export function readingMinutes(blocks) {
44
+ const words = blockParagraphs(blocks).join(" ").split(/\s+/).filter(Boolean).length;
45
+ return Math.max(1, Math.ceil(words / WORDS_PER_MINUTE));
46
+ }
47
+ /** The first paragraph, cut at a word boundary. */
48
+ export function excerptOf(blocks, max = 160) {
49
+ const first = blockParagraphs(blocks)[0] ?? "";
50
+ if (first.length <= max)
51
+ return first;
52
+ const cut = first.slice(0, max - 1);
53
+ return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), max / 2)).trimEnd()}…`;
54
+ }
55
+ /** Only YouTube and Vimeo, as the plugin's frame-src lists only them. Anything else stays a link. */
56
+ export function embedUrl(url) {
57
+ let parsed;
58
+ try {
59
+ parsed = new URL(url);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ if (parsed.protocol !== "https:")
65
+ return null;
66
+ const host = parsed.hostname.replace(/^www\./, "");
67
+ const id = (value, pattern) => (value && pattern.test(value) ? value : null);
68
+ const youtube = /^[A-Za-z0-9_-]{6,20}$/;
69
+ let video = null;
70
+ if (host === "youtube.com" || host === "m.youtube.com")
71
+ video = id(parsed.pathname === "/watch" ? parsed.searchParams.get("v") : parsed.pathname.match(/^\/(?:embed|shorts)\/([^/]+)/)?.[1], youtube);
72
+ else if (host === "youtu.be")
73
+ video = id(parsed.pathname.slice(1), youtube);
74
+ if (video)
75
+ return `https://www.youtube-nocookie.com/embed/${video}`;
76
+ if (host === "vimeo.com") {
77
+ const vimeo = id(parsed.pathname.slice(1), /^\d{1,12}$/);
78
+ if (vimeo)
79
+ return `https://player.vimeo.com/video/${vimeo}`;
80
+ }
81
+ return null;
82
+ }
83
+ const XML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" };
84
+ export const escapeXml = (text) => text.replace(/[&<>"']/g, (c) => XML_ESCAPES[c]).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "");
85
+ const rfc822 = (iso) => new Date(iso).toUTCString();
86
+ export function rss({ title, siteUrl, feedUrl, items }) {
87
+ const entries = items.map((item) => `<item><title>${escapeXml(item.title)}</title><link>${escapeXml(item.url)}</link><guid isPermaLink="true">${escapeXml(item.url)}</guid><pubDate>${rfc822(item.publishedAt)}</pubDate>${item.summary ? `<description>${escapeXml(item.summary)}</description>` : ""}</item>`);
88
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>${escapeXml(title)}</title><link>${escapeXml(siteUrl)}</link><description>${escapeXml(title)}</description><atom:link href="${escapeXml(feedUrl)}" rel="self" type="application/rss+xml"/>${entries.join("")}</channel></rss>\n`;
89
+ }
90
+ export function atom({ title, siteUrl, feedUrl, items }) {
91
+ const updated = items.reduce((latest, item) => (item.updatedAt > latest ? item.updatedAt : latest), items[0]?.updatedAt ?? new Date(0).toISOString());
92
+ const entries = items.map((item) => `<entry><title>${escapeXml(item.title)}</title><link href="${escapeXml(item.url)}"/><id>${escapeXml(item.url)}</id><published>${escapeXml(item.publishedAt)}</published><updated>${escapeXml(item.updatedAt)}</updated>${item.summary ? `<summary>${escapeXml(item.summary)}</summary>` : ""}</entry>`);
93
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<feed xmlns="http://www.w3.org/2005/Atom"><title>${escapeXml(title)}</title><link href="${escapeXml(siteUrl)}"/><link rel="self" href="${escapeXml(feedUrl)}"/><id>${escapeXml(feedUrl)}</id><updated>${escapeXml(updated)}</updated>${entries.join("")}</feed>\n`;
94
+ }
95
+ /** The tag for a heading at `level`, kept between h2 and h6. */
96
+ export function headingTag(level = 2) {
97
+ return `h${Math.min(6, Math.max(2, Math.round(Number.isFinite(level) ? level : 2)))}`;
98
+ }