dika/src/page.js

26 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Подставляет тексты из файла переводов в страницу до отдачи: кнопки и поля подписаны
// сразу, а не после загрузки скрипта (DIK-18). Разметка: data-i — текст элемента,
// data-ph — placeholder, data-al — aria-label, data-ti — title.
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const ATTRS = { ph: "placeholder", al: "aria-label", ti: "title" };
export function pageKeys(html) {
return [...html.matchAll(/\bdata-(?:i|ph|al|ti)="(\w+)"/g)].map((m) => m[1]);
}
// Язык готов, если в его переводе есть все тексты русского и ни один не пустой (DIK-32).
const full = (ru, x) => Object.keys(ru).every((k) => (typeof ru[k] === "string"
? typeof x?.[k] === "string" && x[k].trim() !== ""
: ru[k] && typeof ru[k] === "object" ? x?.[k] && typeof x[k] === "object" && full(ru[k], x[k]) : true));
export function readyLangs(dicts) {
return Object.keys(dicts).filter((l) => l === "ru" || (dicts[l] && full(dicts.ru, dicts[l])));
}
// langs — готовые языки: кнопки остальных в страницу не попадают.
export function renderPage(html, t, langs = ["ru", "kk", "en"]) {
const has = (k) => typeof t[k] === "string";
return html.replace(/<button data-l="(\w+)"[^>]*>[^<]*<\/button>/g, (m, l) => (langs.includes(l) ? m : ""))
.replace(/\bdata-(ph|al|ti)="(\w+)"/g, (m, a, k) => (has(k) ? `${m} ${ATTRS[a]}="${esc(t[k])}"` : m))
.replace(/(<[^<>]*\bdata-i="(\w+)"[^<>]*>)(?=<\/)/g, (m, tag, k) => (has(k) ? tag + esc(t[k]) : m));
}