treker-po-trenirovkam-i-pit.../recipes.js

103 lines
5.2 KiB
JavaScript
Raw Permalink 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.

/* global RecipesCore, RecipeMessages */
'use strict';
const app = document.getElementById('app');
const names = { ru: 'Русский', kk: 'Қазақша', en: 'English' };
const requested = new URLSearchParams(location.search).get('lang') || navigator.language.split('-')[0];
let lang = Object.hasOwn(names, requested) ? requested : 'ru';
document.documentElement.lang = lang;
document.title = RecipeMessages[lang].title;
app.textContent = RecipeMessages[lang].loading;
let data, translations;
const counts = new Map();
const e = (tag, text, className) => {
const node = document.createElement(tag);
if (text != null) node.textContent = text;
if (className) node.className = className;
return node;
};
function nutrients(values, t) {
const box = e('div', null, 'nutrition');
values.forEach((value, i) => {
const cell = e('div');
cell.append(e('strong', new Intl.NumberFormat(lang, { maximumFractionDigits: i ? 1 : 0 }).format(value)), e('span', t.nutrition[i]));
box.append(cell);
});
return box;
}
function card(recipe, t) {
const count = counts.get(recipe.id) || 1;
const text = t.recipes[recipe.id];
const article = e('article'); article.dataset.recipe = recipe.id;
const figure = e('figure');
const img = e('img'); img.src = `/assets/${recipe.id}.jpg`; img.alt = text.title; img.width = 900; img.height = 600;
img.addEventListener('error', () => { img.replaceWith(e('p', t.photo, 'photo-error')); });
figure.append(img, e('span', `${recipe.minutes} ${t.minutes}`, 'time'));
const content = e('div', null, 'content');
const title = e('h2', text.title); title.id = `title-${recipe.id}`;
article.setAttribute('aria-labelledby', title.id);
const controls = e('div', null, 'controls');
const minus = e('button', '−'); minus.type = 'button'; minus.setAttribute('aria-label', t.less); minus.disabled = count === 1;
const plus = e('button', '+'); plus.type = 'button'; plus.setAttribute('aria-label', t.more); plus.disabled = count === 8;
const output = e('output', count); output.setAttribute('aria-live', 'polite'); output.setAttribute('aria-label', t.servings);
const change = (delta) => {
counts.set(recipe.id, RecipesCore.portions(count + delta));
const replacement = card(recipe, translations[lang]);
article.replaceWith(replacement);
const buttons = replacement.querySelectorAll('.controls button');
const target = buttons[delta < 0 ? 0 : 1];
(target.disabled ? buttons[delta < 0 ? 1 : 0] : target).focus();
};
minus.onclick = () => change(-1); plus.onclick = () => change(1);
controls.append(minus, output, plus);
const servings = e('div', null, 'servings'); servings.append(e('span', t.servings), controls);
const ingredients = e('ul', null, 'ingredients');
for (const [id, grams] of recipe.ingredients) {
const item = e('li'); item.append(e('span', t.foods[id]), e('b', `${grams * count} ${t.grams}`)); ingredients.append(item);
}
const steps = e('ol'); for (const step of text.steps) steps.append(e('li', step));
content.append(title, servings, e('p', t.perServing, 'small'), nutrients(RecipesCore.nutrition(recipe, data.foods), t));
if (count > 1) content.append(e('p', t.total, 'small total'), nutrients(RecipesCore.nutrition(recipe, data.foods, count), t));
content.append(e('h3', t.ingredients), e('p', t.raw, 'small'), ingredients, e('h3', t.steps), steps);
article.append(figure, content); return article;
}
function render() {
const t = translations[lang];
document.documentElement.lang = lang; document.title = t.title;
const header = e('header'), intro = e('div');
intro.append(e('p', t.eyebrow, 'eyebrow'), e('h1', t.title), e('p', t.intro));
const label = e('label', t.language), select = e('select');
select.id = 'language';
for (const [code, name] of Object.entries(names)) {
const option = e('option', name); option.value = code; option.selected = code === lang; select.append(option);
}
select.onchange = () => {
lang = select.value;
const url = new URL(location.href); url.searchParams.set('lang', lang); history.replaceState(null, '', url);
render(); document.getElementById('language').focus();
};
label.append(select); header.append(intro, label);
const grid = e('div', null, 'grid'); for (const recipe of data.recipes) grid.append(card(recipe, t));
app.replaceChildren(header, grid, e('p', t.note, 'note'), e('footer', t.footer));
app.setAttribute('aria-busy', 'false'); document.body.dataset.loaded = 'true';
}
async function load() {
app.setAttribute('aria-busy', 'true');
try {
const responses = await Promise.all(['/recipes.data.json', '/recipes.i18n.json'].map(url => fetch(url)));
if (responses.some(response => !response.ok)) throw new Error('catalog unavailable');
[data, translations] = await Promise.all(responses.map(response => response.json()));
render();
} catch {
// Error text lives in the translation resource, including the offline fallback.
const fallback = RecipeMessages;
app.replaceChildren();
if (fallback) {
const box = e('div', null, 'failure'); box.setAttribute('role', 'alert');
const retry = e('button', fallback[lang].retry); retry.onclick = load;
box.append(e('p', fallback[lang].error), retry); app.append(box);
}
app.setAttribute('aria-busy', 'false');
}
}
load();