90 lines
2.4 KiB
TypeScript
90 lines
2.4 KiB
TypeScript
import type howItWorksPage from "../messages/en/pages/howItWorks.json";
|
|
|
|
const HOW_IT_WORKS_WORDS_PER_MINUTE = 200;
|
|
|
|
type HowItWorksMessages = typeof howItWorksPage;
|
|
|
|
export type HowItWorksGuideBlock =
|
|
| { type: "p"; lead?: string; text: string }
|
|
| { type: "figure"; src: string; caption: string }
|
|
| { type: "ruleFigure" }
|
|
| { type: "shareRow" };
|
|
|
|
const MARKDOWN_LINK = /\[([^\]]+)\]\(([^)]+)\)/g;
|
|
|
|
export function asHowItWorksGuideBlock(
|
|
block: HowItWorksMessages["sections"][number]["blocks"][number],
|
|
): HowItWorksGuideBlock {
|
|
return block as HowItWorksGuideBlock;
|
|
}
|
|
|
|
export function stripGuideMarkup(text: string): string {
|
|
return text.replace(MARKDOWN_LINK, "$1");
|
|
}
|
|
|
|
function blockPlainText(
|
|
block: HowItWorksGuideBlock,
|
|
caption: string,
|
|
): string {
|
|
if (block.type === "p") {
|
|
return [block.lead, block.text].filter(Boolean).join(" ");
|
|
}
|
|
if (block.type === "figure") {
|
|
return block.caption;
|
|
}
|
|
if (block.type === "ruleFigure") {
|
|
return caption;
|
|
}
|
|
return "";
|
|
}
|
|
|
|
/** Visible guide copy used to set the byline read time. */
|
|
export function collectHowItWorksGuideText(page: HowItWorksMessages): string {
|
|
const parts: string[] = [];
|
|
for (const section of page.sections) {
|
|
parts.push(section.heading);
|
|
for (const block of section.blocks) {
|
|
parts.push(
|
|
blockPlainText(asHowItWorksGuideBlock(block), page.teamRule.caption),
|
|
);
|
|
}
|
|
}
|
|
return stripGuideMarkup(parts.filter(Boolean).join(" "));
|
|
}
|
|
|
|
export function howItWorksReadMinutes(page: HowItWorksMessages): number {
|
|
const words = collectHowItWorksGuideText(page)
|
|
.trim()
|
|
.split(/\s+/)
|
|
.filter(Boolean).length;
|
|
return Math.max(1, Math.round(words / HOW_IT_WORKS_WORDS_PER_MINUTE));
|
|
}
|
|
|
|
export function formatHowItWorksDate(isoDate: string): string {
|
|
const date = new Date(`${isoDate}T00:00:00Z`);
|
|
return new Intl.DateTimeFormat("en-GB", {
|
|
day: "numeric",
|
|
month: "long",
|
|
year: "numeric",
|
|
timeZone: "UTC",
|
|
}).format(date);
|
|
}
|
|
|
|
export function formatHowItWorksByline(
|
|
page: HowItWorksMessages,
|
|
minutes: number,
|
|
): string {
|
|
return page.byline.template
|
|
.replace("{author}", page.banner.author)
|
|
.replace("{date}", formatHowItWorksDate(page.banner.date))
|
|
.replace("{minutes}", String(minutes));
|
|
}
|
|
|
|
export function howItWorksWikiMarkdown(
|
|
title: string,
|
|
description: string,
|
|
url: string,
|
|
): string {
|
|
return `[${title}](${url})\n\n${description}`;
|
|
}
|