"use strict"; import { ERROR_SERVER, PRODUCT_INFORMATION_NOT_FOUND } from '/js/constants.js'; import { showErrorMessage, setBasketLocalStorage, getBasketLocalStorage, checkingRelevanceValueBasket } from './utils.js'; /* ================================ ЗАЩИТА ШАБЛОНА card.html ================================ */ (function () { const path = window.location.pathname; if (path !== '/card.html') return; const params = new URLSearchParams(window.location.search); const productId = params.get('id'); if (!productId) { const meta = document.createElement('meta'); meta.name = 'robots'; meta.content = 'noindex, nofollow'; document.head.appendChild(meta); window.location.replace('/'); } })(); /* ================================ ОСНОВНОЙ КОД ================================ */ const wrapper = document.querySelector('.wrapper'); let productsData = []; // Формирование ссылки фабрики function formatFabricLink(fabricName) { if (!fabricName) return '#'; const FABRIC_LINKS = { 'ATLAS CONCORDE': 'atlas-concorde', 'ITALGRANITI': 'italgraniti', }; const special = FABRIC_LINKS[fabricName.toUpperCase()]; if (special) return special; return fabricName .toLowerCase() .replace(/\s+/g, '-') .replace(/[^a-z0-9-]/g, ''); } document.addEventListener('DOMContentLoaded', getProducts); async function getProducts() { try { if (!productsData.length) { const response = await fetch('/data/products.json'); if (!response.ok) { throw new Error(ERROR_SERVER); } productsData = await response.json(); } loadProductDetails(productsData); } catch (error) { showErrorMessage(ERROR_SERVER); console.error(error); } } function getParameterFromURL(parameter) { const params = new URLSearchParams(window.location.search); return params.get(parameter); } function loadProductDetails(data) { if (!data || !data.length) { showErrorMessage(ERROR_SERVER); return; } checkingRelevanceValueBasket(data); const productId = Number(getParameterFromURL('id')); if (!productId) { showErrorMessage(PRODUCT_INFORMATION_NOT_FOUND); return; } const currentProduct = data.find(p => p.id === productId); if (!currentProduct) { showErrorMessage(PRODUCT_INFORMATION_NOT_FOUND); return; } renderInfoProduct(currentProduct); } function renderInfoProduct(product) { const { id, img, title, fabric, collection, price, discount, descr, edizm, razmer, type } = product; const priceDiscount = price - ((price * discount) / 100); setCanonicalForCard(id); optimizePageSEO(title, type, fabric, priceDiscount, discount, descr); const fabricLink = formatFabricLink(fabric); const productHTML = `

${title}

${type}

Производитель: ${fabric}
Коллекция: ${collection}
${title}

${descr}

Размер: ${razmer}

${price.toFixed(0)} ₽/${edizm} ${priceDiscount.toFixed(0)} ₽/${edizm}
`; wrapper.insertAdjacentHTML('beforeend', productHTML); wrapper.querySelector('.product__add-to-cart') .addEventListener('click', () => addToCartHandler(id)); } /* ================================ SEO ================================ */ function setCanonicalForCard(productId) { const baseUrl = `${location.protocol}//${location.host}${location.pathname}`; const canonicalUrl = `${baseUrl}?id=${productId}`; let link = document.querySelector('link[rel="canonical"]'); if (!link) { link = document.createElement('link'); link.rel = 'canonical'; document.head.appendChild(link); } link.href = canonicalUrl; } function optimizePageSEO(title, type, fabric, price, discount, description) { document.title = `${type} ${title} от ${fabric} — ${price.toFixed(0)} ₽`; let meta = document.querySelector('meta[name="description"]'); if (!meta) { meta = document.createElement('meta'); meta.name = 'description'; document.head.appendChild(meta); } meta.content = `Купить ${type} ${title} от ${fabric}. Цена ${price.toFixed(0)} ₽. ${description.slice(0, 150)}`; addSchemaMarkup(title, fabric, price, description); } function addSchemaMarkup(title, brand, price, description) { const script = document.createElement('script'); script.type = 'application/ld+json'; script.textContent = JSON.stringify({ "@context": "https://schema.org", "@type": "Product", "name": title, "brand": { "@type": "Brand", "name": brand }, "description": description, "offers": { "@type": "Offer", "price": price, "priceCurrency": "RUB" } }); document.head.appendChild(script); } /* ================================ КОРЗИНА ================================ */ function addToCartHandler(productId) { const input = document.querySelector(`#quantity-${productId}`); const quantity = parseFloat(input.value); if (isNaN(quantity)) return; const basket = getBasketLocalStorage(); const item = basket.find(i => i.id === String(productId)); if (item) { item.quantity += quantity; } else { basket.push({ id: String(productId), quantity }); } setBasketLocalStorage(basket); }