import library from "./licensed-media.json" with { type: "json" };
const themes = {
ai: ["#142f35", "#a6e2ce", "Технология"],
safety: ["#3c3129", "#f3cc91", "Безопасность"],
business: ["#243a30", "#cbe3a4", "Экономика"],
games: ["#34304b", "#dcd1ff", "Игровой мир"],
tech: ["#243447", "#c1d9f3", "Устройство"],
family: ["#493637", "#f3d1b2", "Маршрут"],
};
const catalog = [
["darwin", "family", /дарвиновск|darwinmuseum\.ru/i],
["vdnh", "family", /вднх|vdnh\.ru/i],
["zoo", "family", /московск[а-я]* зоопарк|moscowzoo\.ru/i],
["rpi", "tech", /raspberry pi 5\b/i],
["barking", "safety", /\bbarking\b|баркинг/i],
];
function escape(value) {
return String(value).replace(
/[&<>"]/g,
(char) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[char],
);
}
function lines(text, maxLength, maxLines) {
const words = text.trim().split(/\s+/);
const result = [""];
for (const word of words) {
const current = result.length - 1;
if (result[current] && (result[current] + " " + word).length > maxLength) {
if (result.length === maxLines) {
result[current] = result[current].replace(/[.,;:–—-]+$/, "") + "…";
break;
}
result.push(word);
} else {
result[current] = [result[current], word].filter(Boolean).join(" ");
}
}
return result;
}
function comparisonRows(text, accent) {
// Only draw bars for an explicit before/after pair in matching physical units.
const pair =
/(?:^|\s)с[ \u00a0]+([$€₽]?)\s*(\d+(?:[.,]\d+)?)\s*(%|ГБ|МБ|мс|Вт|₽|км)?\s+до\s+([$€₽]?)\s*(\d+(?:[.,]\d+)?)\s*(%|ГБ|МБ|мс|Вт|₽|км)?(?=[.,;:\s]|$)/i.exec(
text,
);
if (!pair) return null;
const unitA = pair[1] || pair[3] || "",
unitB = pair[4] || pair[6] || "";
if (!unitB || (unitA && unitA.toLowerCase() !== unitB.toLowerCase()))
return null;
const values = [pair[2], pair[5]].map((s) => Number(s.replace(",", ".")));
if (!Math.max(...values)) return null;
const subject = (
text.split(/(?<=[.!?])\s+/).find((t) => t.includes(pair[0].trim())) || ""
).trim();
const title = lines(subject, 60, 2);
const heading = title
.map(
(line, i) =>
'' +
escape(line) +
"",
)
.join("");
return (
heading +
values
.map((v, i) => {
const y = 215 + i * 86;
const w = Math.round((v / Math.max(...values)) * 500);
return (
'' +
["Было", "Стало"][i] +
'' +
escape(v.toLocaleString("ru-RU") + " " + unitB) +
""
);
})
.join("")
);
}
function fieldNotes(story, section) {
const [ink, accent, label] = themes[section] ?? themes.tech;
const facts = (story.facts ?? []).filter(
(item) => typeof item === "string" && item.trim(),
);
const notes = facts.length
? facts.slice(0, 3)
: [story.summary, story.why].filter(Boolean);
if (!notes.length) throw new Error("Article has no evidence to illustrate");
const chart = comparisonRows(
[story.title, story.summary, ...notes].join(". "),
accent,
);
const rows =
chart ||
notes
.map((fact, i) => {
const y = 160 + i * (275 / Math.max(2, notes.length));
const wrapped = lines(fact, 48, 2);
const words = wrapped
.map(
(line, j) =>
'' +
escape(line) +
"",
)
.join("");
return (
'' +
words +
""
);
})
.join("");
return (
'"
);
}
export async function ensureStoryImage(story, { section, date, put }) {
if (story.image?.src) return story;
const context = [story.title, story.url, story.summary].join(" ");
const match = catalog.find(
([id, tab, expression]) =>
library[id] && section === tab && expression.test(context),
);
if (match) return { ...story, image: library[match[0]] };
if (
section === "ai" &&
/github\.com\/openai\/codex\/releases/i.test(story.url)
) {
return {
...story,
image: {
src: "/assets/media/codex-cli.webp",
alt: "Терминальный интерфейс Codex CLI",
credit: "OpenAI · Apache-2.0 · иллюстрация интерфейса",
sourceUrl:
"https://github.com/openai/codex/blob/rust-v0.169.0/.github/codex-cli-splash.png",
},
};
}
const digest = new Uint8Array(
await crypto.subtle.digest("SHA-256", new TextEncoder().encode(story.url)),
);
const shortId = Array.from(digest.slice(0, 12), (b) =>
b.toString(16).padStart(2, "0"),
).join("");
const key = "media/" + date + "/" + section + "-" + shortId + ".svg";
await put(key, fieldNotes(story, section), "image/svg+xml; charset=utf-8");
const detail = (story.facts?.length ? story.facts : [story.summary]).join(
". ",
);
return {
...story,
image: {
src: "/" + key,
alt: detail,
credit: "Графика редакции по материалу " + story.source,
sourceUrl: story.url,
},
};
}