const canonicalPattern = /^\/(?:[a-z0-9]+(?:-[a-z0-9]+)*\/)*$/; const personalRoutes = new Set(['/checkout/successo/', '/newsletter-disiscrizione/']); export function languageDestination(button, document, location) { const {languageCode: code, languageEnabled: enabled, languagePath: path, languageCanonical: canonical} = button.dataset; if (button.disabled || enabled !== 'true' || !['it', 'en'].includes(code) || !canonicalPattern.test(canonical ?? '') || /^\/(en|ja)\//.test(canonical) || personalRoutes.has(canonical)) return null; const sourceLanguage = document.documentElement.lang; if (!['it', 'en'].includes(sourceLanguage)) return null; const sourcePath = (sourceLanguage === 'en' ? '/en' : '') + canonical; const currentPath = location.pathname.endsWith('/') ? location.pathname : location.pathname + '/'; if (currentPath !== sourcePath || path !== (code === 'en' ? '/en' : '') + canonical) return null; const destination = new URL(path, location.origin); // Keep only public shop filters, never customer details, tokens, return URLs // or checkout/session identifiers. Language does not select a market. if (canonical === '/negozio/') { const allowed = new Set(['linea', 'formato', 'confezione', 'pronta-spedizione']); for (const [key, value] of new URLSearchParams(location.search)) { if (allowed.has(key) && value.length <= 64 && !/[<>\x00-\x1f\x7f]/.test(value)) { destination.searchParams.append(key, value); } } } const fragment = location.hash.slice(1); if (/^[a-z][a-z0-9-]*$/.test(fragment) && document.getElementById(fragment)) destination.hash = fragment; return destination.pathname + destination.search + destination.hash; } export function initLanguageSelector(document = globalThis.document, navigate) { const view = document.defaultView; const go = navigate ?? (path => view.location.assign(path)); document.querySelectorAll('[data-language-code]').forEach(button => { if (button.dataset.languageInitialized === 'true') return; button.dataset.languageInitialized = 'true'; button.addEventListener('click', () => { const destination = languageDestination(button, document, view.location); if (!destination) return; // Language persists in localized URLs, not a new storage key. A shared // URL always determines the language; never redirect automatically. if (button.dataset.languageCode === document.documentElement.lang) { document.querySelector('[data-drawer="regional"] [data-drawer-close="regional"]')?.click(); return; } go(destination); }); }); } if (typeof document !== 'undefined') { initLanguageSelector(document); document.addEventListener('astro:page-load', () => initLanguageSelector(document)); }