{"version":3,"file":"cart.js","sources":["../../../../../Flow.Showcase.Static.Bundler/Root/entrypoints/cart.ts"],"sourcesContent":["// @ts-nocheck\n\nimport eventBus from \"../modules/event-bus.module.ts\";\nimport { commonState } from \"../modules/common-state.module.ts\";\nimport { showPopup } from \"../modules/popup.module.ts\";\nimport { getQuantityAttributes } from \"../modules/cart.module.ts\";\n\n// @ts-ignore\nconst processedCartItemQuantityControls = new WeakSet();\n\n/**\n * инициализация для элементов которые добавляют продукты в корзину\n */\nfunction initHandleUpdateCart() {\n /**\n * @type {NodeListOf}\n */\n const elements = document.querySelectorAll(\"[data-handle-add-to-cart]\");\n\n for (const elem of elements) {\n // не навешиваем обработчики дважды\n if (processedCartItemQuantityControls.has(elem)) continue;\n\n if (elem instanceof HTMLInputElement) {\n // события элемнта input\n // При вводе, если введенное значение корректное, изменить количество товара\n elem.addEventListener(\"input\", () => {\n const attr = getQuantityAttributes(elem);\n let newQuantity = parseInt(elem.value);\n if (!Number.isNaN(newQuantity)) {\n attr.setQuantity(newQuantity, false);\n }\n });\n // При снятии фокуса, восстановить последнее корректное значение количества\n elem.addEventListener(\"focusout\", () => {\n const attr = getQuantityAttributes(elem);\n attr.resetInputValue();\n });\n // При нажатии Enter изменить количество товара\n elem.addEventListener(\"keydown\", (e) => {\n if (e.key === \"Enter\") {\n const attr = getQuantityAttributes(elem);\n let newQuantity = parseInt(elem.value);\n if (Number.isNaN(newQuantity)) {\n attr.resetInputValue();\n } else {\n attr.setQuantity(newQuantity);\n }\n }\n });\n }\n\n const isIncreaseControl = \"increase\" in elem.dataset;\n const isDecreaseControl = \"decrease\" in elem.dataset;\n if (elem instanceof HTMLButtonElement && (isIncreaseControl || isDecreaseControl)) {\n // события кнопок\n addQuantityButtonClickHandler(elem);\n\n if (isIncreaseControl === isDecreaseControl) {\n console.error(`Check quantity control button attributes. Forbidden \"increase\" and \"decrease\" attributes at once. Element: ${elem}`)\n continue;\n }\n\n if (isIncreaseControl) {\n const {quantity, quantityMax} = getQuantityAttributes(elem);\n elem.disabled = quantity >= quantityMax;\n }\n\n if (isDecreaseControl) {\n const {quantity, quantityMin} = getQuantityAttributes(elem);\n elem.disabled = quantity <= quantityMin;\n }\n\n }\n\n processedCartItemQuantityControls.add(elem);\n }\n\n /**\n * Добавить обработчик клика на кнопки изменения количества товара корзине\n * @param {HTMLButtonElement} elem\n */\n function addQuantityButtonClickHandler(elem) {\n elem.addEventListener(\"click\", () => {\n const attr = getQuantityAttributes(elem);\n let newQuantity = attr.quantity + attr.amountChange;\n attr.setQuantity(newQuantity);\n });\n }\n}\n\ninitHandleUpdateCart();\n\n// вписать новое кол-во во все элементы на странице которые содержат класс .js-cart-counter\neventBus.subscribe(\"cart-changed\", ({ total }) => {\n const elements = document.querySelectorAll(\".js-cart-counter\");\n for (const element of elements) {\n element.innerHTML = total;\n }\n});\n\nconst totalElements = document.querySelectorAll(\".js-cart-total\");\nconst subtotalElements = document.querySelectorAll(\".js-cart-subtotal\");\nconst discountElements = document.querySelectorAll(\".js-cart-discount\");\n// вписать сумму корзины во все элементы на странице которые содержат класс .js-cart-total\neventBus.subscribe(\"cart-changed\", ({ totalPrice, discountedTotal }) => {\n for (const element of totalElements) {\n if (discountedTotal !== null) {\n element.innerHTML = formatMoney(discountedTotal);\n } else {\n element.innerHTML = formatMoney(totalPrice);\n }\n }\n for (const element of subtotalElements) {\n element.innerHTML = formatMoney(totalPrice);\n }\n for (const element of discountElements) {\n if (discountedTotal !== null) {\n const diff = totalPrice.value - discountedTotal.value;\n element.innerHTML = formatMoney({value: diff, currency: totalPrice.currency})\n }\n }\n});\n\n// Показать уведомление при попытке добавить больше товара, чем есть в наличии\neventBus.subscribe(\"not-enough-products\", ({ message }) => {\n showPopup(message, 2000, 10);\n});\n\n/**\n * Преобразование денежной суммы в строку\n * @param {Object} param\n * @param {number} param.value сумма\n * @param {string} param.currency валюта\n */\nfunction formatMoney({ value, currency }) {\n /** @type {Intl.NumberFormatOptions} */\n const formatOptions = Number.isInteger(value)\n ? { style: \"decimal\", maximumFractionDigits: 0 }\n : {\n style: \"decimal\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n };\n const numberFormat = new Intl.NumberFormat(\"ru\", formatOptions);\n const formattedValue = numberFormat.format(value);\n let currencySymbol = commonState.localization.currencySymbols[currency];\n if (!currencySymbol) {\n currencySymbol = \"\";\n }\n if (commonState.localization.currentCulture === \"en\") {\n return `${currencySymbol} ${formattedValue}`;\n } else {\n return `${formattedValue} ${currencySymbol}`;\n }\n}\n"],"names":["processedCartItemQuantityControls","initHandleUpdateCart","elements","elem","attr","getQuantityAttributes","newQuantity","e","isIncreaseControl","isDecreaseControl","addQuantityButtonClickHandler","quantity","quantityMax","quantityMin","eventBus","total","element","totalElements","subtotalElements","discountElements","totalPrice","discountedTotal","formatMoney","diff","message","showPopup","value","currency","formatOptions","formattedValue","currencySymbol","commonState"],"mappings":"sOAQA,MAAMA,MAAwC,QAK9C,SAASC,GAAuB,CAItB,MAAAC,EAAW,SAAS,iBAAiB,2BAA2B,EAEtE,UAAWC,KAAQD,EAAU,CAErB,GAAAF,EAAkC,IAAIG,CAAI,EAAG,SAE7CA,aAAgB,mBAGXA,EAAA,iBAAiB,QAAS,IAAM,CAC3B,MAAAC,EAAOC,EAAsBF,CAAI,EACnC,IAAAG,EAAc,SAASH,EAAK,KAAK,EAChC,OAAO,MAAMG,CAAW,GACpBF,EAAA,YAAYE,EAAa,EAAK,CACvC,CACH,EAEIH,EAAA,iBAAiB,WAAY,IAAM,CACvBE,EAAsBF,CAAI,EAClC,gBAAgB,CAAA,CACxB,EAEIA,EAAA,iBAAiB,UAAYI,GAAM,CAChC,GAAAA,EAAE,MAAQ,QAAS,CACb,MAAAH,EAAOC,EAAsBF,CAAI,EACnC,IAAAG,EAAc,SAASH,EAAK,KAAK,EACjC,OAAO,MAAMG,CAAW,EACxBF,EAAK,gBAAgB,EAErBA,EAAK,YAAYE,CAAW,CAChC,CACJ,CACH,GAGC,MAAAE,EAAoB,aAAcL,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