@salla.sa/twilight-components 2.14.352 → 2.14.354

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/dist/cjs/bell-ring-BfKPinNo.js +13 -0
  2. package/dist/cjs/{interfaces-CX9-6aLf.js → camera-DytepEoK.js} +0 -11
  3. package/dist/cjs/cancel-De6vslRA.js +13 -0
  4. package/dist/cjs/cart-s-x1Fshk.js +13 -0
  5. package/dist/cjs/check-circle2-BDvlT4_n.js +13 -0
  6. package/dist/cjs/{check-CLRvuniI.js → check-x3w3-gpj.js} +2 -2
  7. package/dist/cjs/{filepond-XtsZ6xtH.js → filepond-CuKErtOy.js} +1 -1
  8. package/dist/cjs/{filepond-plugin-file-poster-Bj84Ypvg.js → filepond-plugin-file-poster-d-8BSuST.js} +1 -1
  9. package/dist/cjs/{filepond-plugin-file-validate-size-aYfb4yYH.js → filepond-plugin-file-validate-size-zgI_JcqY.js} +1 -1
  10. package/dist/cjs/{filepond-plugin-file-validate-type-CJsd6rXl.js → filepond-plugin-file-validate-type-Cy8IgG2P.js} +1 -1
  11. package/dist/cjs/{filepond-plugin-image-edit-DRlBSg36.js → filepond-plugin-image-edit-9ZAUzCvh.js} +1 -1
  12. package/dist/cjs/{filepond-plugin-image-exif-orientation-SY8c6DzI.js → filepond-plugin-image-exif-orientation-DzNe_tY2.js} +1 -1
  13. package/dist/cjs/{filepond-plugin-image-preview-iqhJmUmU.js → filepond-plugin-image-preview-Cfna6xTB.js} +1 -1
  14. package/dist/{esm/gift-C0JNGIpa.js → cjs/gift-CJ-3Yw_x.js} +4 -2
  15. package/dist/cjs/image-BoZ6Hums.js +13 -0
  16. package/dist/cjs/{index-Z-cyrNSM.js → index-Ce40E8tZ.js} +136 -12
  17. package/dist/cjs/{index-C7-280f4.js → index-ff-xJfhj.js} +1 -1
  18. package/dist/cjs/interfaces-CRqrf5RX.js +15 -0
  19. package/dist/cjs/keyboard_arrow_down-DHJ3FFZq.js +13 -0
  20. package/dist/cjs/keyboard_arrow_right-BayM_Il2.js +21 -0
  21. package/dist/cjs/loader.cjs.js +2 -2
  22. package/dist/cjs/minus-CCryh1qf.js +21 -0
  23. package/dist/cjs/salla-accordion-body_3.cjs.entry.js +775 -0
  24. package/dist/cjs/salla-accordion_6.cjs.entry.js +768 -0
  25. package/dist/cjs/salla-add-product-button_4.cjs.entry.js +2389 -0
  26. package/dist/cjs/salla-advertisement.cjs.entry.js +1 -1
  27. package/dist/cjs/salla-alert_2.cjs.entry.js +194 -0
  28. package/dist/cjs/salla-app-install-alert.cjs.entry.js +8 -3
  29. package/dist/cjs/salla-apps-icons.cjs.entry.js +1 -1
  30. package/dist/cjs/salla-booking-field_7.cjs.entry.js +1565 -0
  31. package/dist/cjs/{salla-cart-item-offers.cjs.entry.js → salla-cart-item-offers_2.cjs.entry.js} +104 -5
  32. package/dist/cjs/salla-comment-form_8.cjs.entry.js +1661 -0
  33. package/dist/cjs/salla-conditional-offer.cjs.entry.js +1 -1
  34. package/dist/cjs/salla-contacts.cjs.entry.js +3 -3
  35. package/dist/cjs/salla-count-down_2.cjs.entry.js +302 -0
  36. package/dist/cjs/salla-custom-fields.cjs.entry.js +4 -3
  37. package/dist/cjs/salla-filters-widget.cjs.entry.js +1 -1
  38. package/dist/cjs/salla-filters.cjs.entry.js +1 -1
  39. package/dist/cjs/salla-gifting.cjs.entry.js +488 -0
  40. package/dist/cjs/salla-hook.cjs.entry.js +1 -1
  41. package/dist/cjs/salla-infinite-scroll.cjs.entry.js +91 -0
  42. package/dist/cjs/salla-installment.cjs.entry.js +1 -1
  43. package/dist/cjs/salla-list-tile.cjs.entry.js +34 -0
  44. package/dist/cjs/salla-localization-modal.cjs.entry.js +137 -0
  45. package/dist/cjs/salla-login-modal.cjs.entry.js +320 -0
  46. package/dist/cjs/salla-loyalty-prize-item.cjs.entry.js +1 -1
  47. package/dist/cjs/salla-loyalty-program.cjs.entry.js +3 -3
  48. package/dist/cjs/salla-loyalty.cjs.entry.js +211 -0
  49. package/dist/cjs/salla-maintenance-alert.cjs.entry.js +40 -0
  50. package/dist/cjs/salla-menu.cjs.entry.js +139 -0
  51. package/dist/cjs/salla-metadata.cjs.entry.js +1 -1
  52. package/dist/cjs/salla-multiple-bundle-product-cart_2.cjs.entry.js +220 -0
  53. package/dist/cjs/salla-multiple-bundle-product-options-modal_2.cjs.entry.js +598 -0
  54. package/dist/cjs/salla-multiple-bundle-product.cjs.entry.js +69 -0
  55. package/dist/cjs/salla-notification-item.cjs.entry.js +1 -1
  56. package/dist/cjs/salla-notifications.cjs.entry.js +1 -1
  57. package/dist/cjs/salla-offer-modal.cjs.entry.js +206 -0
  58. package/dist/cjs/salla-offer.cjs.entry.js +1 -1
  59. package/dist/cjs/salla-order-details-multiple-bundle-product.cjs.entry.js +1 -1
  60. package/dist/cjs/salla-order-details-options.cjs.entry.js +1 -1
  61. package/dist/cjs/salla-order-details.cjs.entry.js +1 -1
  62. package/dist/cjs/salla-order-summary.cjs.entry.js +3 -3
  63. package/dist/cjs/salla-order-totals-card.cjs.entry.js +1 -1
  64. package/dist/cjs/salla-orders.cjs.entry.js +1 -1
  65. package/dist/cjs/salla-payments.cjs.entry.js +1 -1
  66. package/dist/cjs/salla-placeholder.cjs.entry.js +51 -0
  67. package/dist/cjs/salla-price-range.cjs.entry.js +1 -1
  68. package/dist/cjs/salla-product-size-guide.cjs.entry.js +66 -0
  69. package/dist/cjs/salla-products-list.cjs.entry.js +762 -0
  70. package/dist/cjs/salla-products-slider.cjs.entry.js +115 -0
  71. package/dist/cjs/salla-progress-bar.cjs.entry.js +73 -0
  72. package/dist/cjs/salla-quick-order.cjs.entry.js +239 -0
  73. package/dist/cjs/salla-rating-modal.cjs.entry.js +453 -0
  74. package/dist/cjs/salla-scopes.cjs.entry.js +180 -0
  75. package/dist/cjs/salla-search.cjs.entry.js +153 -0
  76. package/dist/cjs/salla-skeleton.cjs.entry.js +36 -0
  77. package/dist/cjs/salla-slider.cjs.entry.js +10389 -0
  78. package/dist/cjs/salla-social-share.cjs.entry.js +165 -0
  79. package/dist/cjs/salla-social.cjs.entry.js +3 -3
  80. package/dist/cjs/salla-tab-content_3.cjs.entry.js +157 -0
  81. package/dist/cjs/salla-tiered-offer.cjs.entry.js +1 -1
  82. package/dist/cjs/salla-tooltip.cjs.entry.js +1 -1
  83. package/dist/cjs/salla-trust-badges.cjs.entry.js +1 -1
  84. package/dist/cjs/salla-user-menu.cjs.entry.js +275 -0
  85. package/dist/cjs/salla-user-profile.cjs.entry.js +145 -0
  86. package/dist/cjs/salla-user-settings.cjs.entry.js +88 -0
  87. package/dist/cjs/salla-verify.cjs.entry.js +1 -1
  88. package/dist/cjs/salla-wallet.cjs.entry.js +1 -1
  89. package/dist/cjs/search-c7Aa7lM9.js +13 -0
  90. package/dist/cjs/{special-discount-OVG_9Kf9.js → special-discount-DC2oXurL.js} +0 -8
  91. package/dist/cjs/star-DGcH7Yso.js +13 -0
  92. package/dist/cjs/star2-R146a27p.js +13 -0
  93. package/dist/cjs/twilight.cjs.js +2 -2
  94. package/dist/cjs/{vanilla-picker-Dq7F5bE1.js → vanilla-picker-zQsXQIff.js} +1 -1
  95. package/dist/cjs/{whatsapp2-D7Sbg8Ey.js → whatsapp2-BdMd5Gx1.js} +2 -2
  96. package/dist/collection/collection-manifest.json +55 -1
  97. package/dist/collection/components/salla-add-product-button/salla-add-product-button.js +18 -6
  98. package/dist/collection/components/salla-app-install-alert/salla-app-install-alert.js +7 -2
  99. package/dist/collection/components/salla-color-picker/salla-color-picker.js +39 -8
  100. package/dist/collection/components/salla-maintenance-alert/salla-maintenance-alert.js +4 -2
  101. package/dist/collection/components/salla-product-options/salla-product-options.js +36 -3
  102. package/dist/collection/components/salla-products-list/salla-products-list.js +17 -11
  103. package/dist/components/index.js +2 -2
  104. package/dist/components/salla-add-product-button2.js +18 -6
  105. package/dist/components/salla-app-install-alert.js +7 -2
  106. package/dist/components/salla-color-picker2.js +38 -7
  107. package/dist/components/salla-maintenance-alert.js +4 -2
  108. package/dist/components/salla-product-options2.js +19 -2
  109. package/dist/components/salla-products-list2.js +17 -11
  110. package/dist/esm/bell-ring-D3mWkc-3.js +11 -0
  111. package/dist/esm/{interfaces-CBT_Nxny.js → camera-C6jIkM-X.js} +1 -12
  112. package/dist/esm/cancel-BsLF_HK7.js +11 -0
  113. package/dist/esm/cart-DY4LZmNP.js +11 -0
  114. package/dist/esm/{check-uTyAzPSy.js → check-BsXh13x8.js} +2 -2
  115. package/dist/esm/check-circle2-BV4kqbdL.js +11 -0
  116. package/dist/esm/{filepond-Dg4ZKM-u.js → filepond-DEzyRrdH.js} +1 -1
  117. package/dist/esm/{filepond-plugin-file-poster-BUIjdsnA.js → filepond-plugin-file-poster-DyLcCcHM.js} +1 -1
  118. package/dist/esm/{filepond-plugin-file-validate-size-DgZMMqmi.js → filepond-plugin-file-validate-size-Cxp5Yzea.js} +1 -1
  119. package/dist/esm/{filepond-plugin-file-validate-type-DA9tDSFr.js → filepond-plugin-file-validate-type-D2qNOQP4.js} +1 -1
  120. package/dist/esm/{filepond-plugin-image-edit-dotdnN4Z.js → filepond-plugin-image-edit-DndTlA7m.js} +1 -1
  121. package/dist/esm/{filepond-plugin-image-exif-orientation-oSI8aLU-.js → filepond-plugin-image-exif-orientation-CiT1CQoK.js} +1 -1
  122. package/dist/esm/{filepond-plugin-image-preview-DEefQK61.js → filepond-plugin-image-preview-DBG7keFZ.js} +1 -1
  123. package/dist/{cjs/gift-BPDUPIY_.js → esm/gift-BChI23pG.js} +2 -4
  124. package/dist/esm/image-C-tzSDxw.js +11 -0
  125. package/dist/esm/{index-D2-TtAhI.js → index-B74h9G6a.js} +137 -13
  126. package/dist/esm/{index-B7E8Tmgi.js → index-BLw7mdtM.js} +1 -1
  127. package/dist/esm/interfaces-OF8QcbMM.js +15 -0
  128. package/dist/esm/keyboard_arrow_down-DCZbpt2a.js +11 -0
  129. package/dist/esm/keyboard_arrow_right-Vqpj4CWE.js +18 -0
  130. package/dist/esm/loader.js +3 -3
  131. package/dist/esm/minus-DfeagqF1.js +18 -0
  132. package/dist/esm/salla-accordion-body_3.entry.js +771 -0
  133. package/dist/esm/salla-accordion_6.entry.js +761 -0
  134. package/dist/esm/salla-add-product-button_4.entry.js +2384 -0
  135. package/dist/esm/salla-advertisement.entry.js +1 -1
  136. package/dist/esm/salla-alert_2.entry.js +191 -0
  137. package/dist/esm/salla-app-install-alert.entry.js +8 -3
  138. package/dist/esm/salla-apps-icons.entry.js +1 -1
  139. package/dist/esm/salla-booking-field_7.entry.js +1539 -0
  140. package/dist/esm/{salla-cart-item-offers.entry.js → salla-cart-item-offers_2.entry.js} +104 -6
  141. package/dist/esm/salla-comment-form_8.entry.js +1652 -0
  142. package/dist/esm/salla-conditional-offer.entry.js +1 -1
  143. package/dist/esm/salla-contacts.entry.js +3 -3
  144. package/dist/esm/salla-count-down_2.entry.js +299 -0
  145. package/dist/esm/salla-custom-fields.entry.js +3 -2
  146. package/dist/esm/salla-filters-widget.entry.js +1 -1
  147. package/dist/esm/salla-filters.entry.js +1 -1
  148. package/dist/esm/salla-gifting.entry.js +486 -0
  149. package/dist/esm/salla-hook.entry.js +1 -1
  150. package/dist/esm/salla-infinite-scroll.entry.js +89 -0
  151. package/dist/esm/salla-installment.entry.js +1 -1
  152. package/dist/esm/salla-list-tile.entry.js +32 -0
  153. package/dist/esm/salla-localization-modal.entry.js +135 -0
  154. package/dist/esm/salla-login-modal.entry.js +318 -0
  155. package/dist/esm/salla-loyalty-prize-item.entry.js +1 -1
  156. package/dist/esm/salla-loyalty-program.entry.js +3 -3
  157. package/dist/esm/salla-loyalty.entry.js +209 -0
  158. package/dist/esm/salla-maintenance-alert.entry.js +38 -0
  159. package/dist/esm/salla-menu.entry.js +137 -0
  160. package/dist/esm/salla-metadata.entry.js +1 -1
  161. package/dist/esm/salla-multiple-bundle-product-cart_2.entry.js +217 -0
  162. package/dist/esm/salla-multiple-bundle-product-options-modal_2.entry.js +595 -0
  163. package/dist/esm/salla-multiple-bundle-product.entry.js +67 -0
  164. package/dist/esm/salla-notification-item.entry.js +1 -1
  165. package/dist/esm/salla-notifications.entry.js +1 -1
  166. package/dist/esm/salla-offer-modal.entry.js +204 -0
  167. package/dist/esm/salla-offer.entry.js +1 -1
  168. package/dist/esm/salla-order-details-multiple-bundle-product.entry.js +1 -1
  169. package/dist/esm/salla-order-details-options.entry.js +1 -1
  170. package/dist/esm/salla-order-details.entry.js +1 -1
  171. package/dist/esm/salla-order-summary.entry.js +3 -3
  172. package/dist/esm/salla-order-totals-card.entry.js +1 -1
  173. package/dist/esm/salla-orders.entry.js +1 -1
  174. package/dist/esm/salla-payments.entry.js +1 -1
  175. package/dist/esm/salla-placeholder.entry.js +49 -0
  176. package/dist/esm/salla-price-range.entry.js +1 -1
  177. package/dist/esm/salla-product-size-guide.entry.js +64 -0
  178. package/dist/esm/salla-products-list.entry.js +760 -0
  179. package/dist/esm/salla-products-slider.entry.js +113 -0
  180. package/dist/esm/salla-progress-bar.entry.js +71 -0
  181. package/dist/esm/salla-quick-order.entry.js +237 -0
  182. package/dist/esm/salla-rating-modal.entry.js +451 -0
  183. package/dist/esm/salla-scopes.entry.js +178 -0
  184. package/dist/esm/salla-search.entry.js +151 -0
  185. package/dist/esm/salla-skeleton.entry.js +34 -0
  186. package/dist/esm/salla-slider.entry.js +10387 -0
  187. package/dist/esm/salla-social-share.entry.js +163 -0
  188. package/dist/esm/salla-social.entry.js +2 -2
  189. package/dist/esm/salla-tab-content_3.entry.js +153 -0
  190. package/dist/esm/salla-tiered-offer.entry.js +1 -1
  191. package/dist/esm/salla-tooltip.entry.js +1 -1
  192. package/dist/esm/salla-trust-badges.entry.js +1 -1
  193. package/dist/esm/salla-user-menu.entry.js +273 -0
  194. package/dist/esm/salla-user-profile.entry.js +143 -0
  195. package/dist/esm/salla-user-settings.entry.js +86 -0
  196. package/dist/esm/salla-verify.entry.js +1 -1
  197. package/dist/esm/salla-wallet.entry.js +1 -1
  198. package/dist/esm/search-BscTeWDc.js +11 -0
  199. package/dist/esm/{special-discount-yRO-ZESF.js → special-discount-Ctkfc4K-.js} +1 -8
  200. package/dist/esm/star-ZT7ehBBk.js +11 -0
  201. package/dist/esm/star2-D4oPi1Ov.js +11 -0
  202. package/dist/esm/twilight.js +3 -3
  203. package/dist/esm/{vanilla-picker-DkUGzUrx.js → vanilla-picker-CtwkXTap.js} +1 -1
  204. package/dist/esm/{whatsapp2-DWksgowB.js → whatsapp2-CgR-T_ZS.js} +2 -2
  205. package/dist/twilight/{p-7b3ca138.entry.js → p-0134b4fd.entry.js} +1 -1
  206. package/dist/twilight/{p-0effc34b.entry.js → p-01daaaa6.entry.js} +1 -1
  207. package/dist/twilight/p-07da7390.entry.js +4 -0
  208. package/dist/twilight/{p-6ce3f119.entry.js → p-08badc32.entry.js} +1 -1
  209. package/dist/twilight/{p-4a594c06.entry.js → p-0aa5a12a.entry.js} +1 -1
  210. package/dist/twilight/{p-e73c28a8.entry.js → p-10dcd981.entry.js} +1 -1
  211. package/dist/twilight/{p-81df7a2e.entry.js → p-212a0710.entry.js} +1 -1
  212. package/dist/twilight/p-229275db.entry.js +4 -0
  213. package/dist/twilight/{p-fea62668.entry.js → p-232185ec.entry.js} +1 -1
  214. package/dist/twilight/{p-e5c01983.entry.js → p-2a927eac.entry.js} +1 -1
  215. package/dist/twilight/p-2d880232.entry.js +4 -0
  216. package/dist/twilight/p-2de9df64.entry.js +4 -0
  217. package/dist/twilight/p-309a0ba4.entry.js +4 -0
  218. package/dist/twilight/{p-6d886b96.entry.js → p-32732ca7.entry.js} +1 -1
  219. package/dist/twilight/{p-9d35196f.entry.js → p-32ca34ec.entry.js} +1 -1
  220. package/dist/twilight/{p-2aa0a4e2.entry.js → p-33093880.entry.js} +1 -1
  221. package/dist/twilight/p-3cffa4c9.entry.js +4 -0
  222. package/dist/twilight/p-3d0bb451.entry.js +4 -0
  223. package/dist/twilight/p-3e0d814c.entry.js +4 -0
  224. package/dist/twilight/p-4036d5dc.entry.js +4 -0
  225. package/dist/twilight/p-40fe4b01.entry.js +4 -0
  226. package/dist/twilight/p-47ac0ca5.entry.js +4 -0
  227. package/dist/twilight/{p-b9d0212c.entry.js → p-4cd9da44.entry.js} +1 -1
  228. package/dist/twilight/p-5c9281d3.entry.js +4 -0
  229. package/dist/twilight/p-5d044466.entry.js +4 -0
  230. package/dist/twilight/p-5d21334a.entry.js +4 -0
  231. package/dist/twilight/{p-e26cc25b.entry.js → p-654429df.entry.js} +1 -1
  232. package/dist/twilight/p-6b8453be.entry.js +4 -0
  233. package/dist/twilight/p-6be7bbb0.entry.js +4 -0
  234. package/dist/twilight/{p-67c327a8.entry.js → p-6c8f5c94.entry.js} +1 -1
  235. package/dist/twilight/{p-9b8f5399.entry.js → p-6fa02770.entry.js} +1 -1
  236. package/dist/twilight/p-7040ea33.entry.js +4 -0
  237. package/dist/twilight/p-8c189d76.entry.js +4 -0
  238. package/dist/twilight/p-8f1f052c.entry.js +4 -0
  239. package/dist/twilight/{p-6b0a03f6.entry.js → p-9051a540.entry.js} +1 -1
  240. package/dist/twilight/p-9f1c561f.entry.js +4 -0
  241. package/dist/twilight/{p-B0ba6Gec.js → p-B69XOH6h.js} +2 -2
  242. package/dist/twilight/{p-D2-TtAhI.js → p-B74h9G6a.js} +2 -2
  243. package/dist/twilight/{p-C0JNGIpa.js → p-BChI23pG.js} +1 -1
  244. package/dist/twilight/{p-DhcC83-2.js → p-BCxm-ISm.js} +1 -1
  245. package/dist/twilight/{p-Cmkcwiop.js → p-BPqZ249Z.js} +1 -1
  246. package/dist/twilight/p-BV4kqbdL.js +4 -0
  247. package/dist/twilight/p-BsLF_HK7.js +4 -0
  248. package/dist/twilight/{p-uTyAzPSy.js → p-BsXh13x8.js} +1 -1
  249. package/dist/twilight/p-BscTeWDc.js +4 -0
  250. package/dist/twilight/p-C-tzSDxw.js +4 -0
  251. package/dist/twilight/p-C6jIkM-X.js +4 -0
  252. package/dist/twilight/p-CO-PeZ27.js +4 -0
  253. package/dist/twilight/{p-DPqkW1aD.js → p-CQq81yb5.js} +2 -2
  254. package/dist/twilight/{p-DWksgowB.js → p-CgR-T_ZS.js} +1 -1
  255. package/dist/twilight/p-Ctkfc4K-.js +4 -0
  256. package/dist/twilight/p-D3mWkc-3.js +4 -0
  257. package/dist/twilight/p-D4oPi1Ov.js +4 -0
  258. package/dist/twilight/p-DCZbpt2a.js +4 -0
  259. package/dist/twilight/p-DY4LZmNP.js +4 -0
  260. package/dist/twilight/p-DfeagqF1.js +4 -0
  261. package/dist/twilight/{p-DJ557xys.js → p-DpsbV3x1.js} +1 -1
  262. package/dist/twilight/p-OF8QcbMM.js +4 -0
  263. package/dist/twilight/p-Vqpj4CWE.js +4 -0
  264. package/dist/twilight/p-ZT7ehBBk.js +4 -0
  265. package/dist/twilight/{p-q-O0srMP.js → p-_-aXm0Wb.js} +1 -1
  266. package/dist/twilight/p-a100bd38.entry.js +4 -0
  267. package/dist/twilight/{p-cf66ab4d.entry.js → p-a2756650.entry.js} +1 -1
  268. package/dist/twilight/{p-b1af2aca.entry.js → p-aab45a16.entry.js} +1 -1
  269. package/dist/twilight/p-aae761ff.entry.js +4 -0
  270. package/dist/twilight/p-afd61e47.entry.js +4 -0
  271. package/dist/twilight/p-b1fc6dfc.entry.js +4 -0
  272. package/dist/twilight/p-b206a0a1.entry.js +4 -0
  273. package/dist/twilight/p-b2332516.entry.js +4 -0
  274. package/dist/twilight/{p-6c2807c8.entry.js → p-b588ef46.entry.js} +1 -1
  275. package/dist/twilight/p-b71fc1b5.entry.js +4 -0
  276. package/dist/twilight/{p-_JhF_Kvb.js → p-bVqtOl1F.js} +1 -1
  277. package/dist/twilight/{p-a858523c.entry.js → p-bf65b263.entry.js} +1 -1
  278. package/dist/twilight/{p-d4faa0f6.entry.js → p-c56a47b0.entry.js} +1 -1
  279. package/dist/twilight/p-c73189e3.entry.js +4 -0
  280. package/dist/twilight/p-d1203242.entry.js +4 -0
  281. package/dist/twilight/p-d4edfed4.entry.js +4 -0
  282. package/dist/twilight/{p-f6ffc708.entry.js → p-d86ce978.entry.js} +1 -1
  283. package/dist/twilight/{p-8e7fa4a9.entry.js → p-d9e7973d.entry.js} +1 -1
  284. package/dist/twilight/p-e3e33238.entry.js +4 -0
  285. package/dist/twilight/p-e6bb7362.entry.js +4 -0
  286. package/dist/twilight/{p-30403778.entry.js → p-e7813c80.entry.js} +1 -1
  287. package/dist/twilight/p-ec2fd37e.entry.js +4 -0
  288. package/dist/twilight/{p-ed60a726.entry.js → p-ec77c523.entry.js} +1 -1
  289. package/dist/twilight/{p-b208650b.entry.js → p-efc18ce6.entry.js} +1 -1
  290. package/dist/twilight/p-f4039c40.entry.js +4 -0
  291. package/dist/twilight/p-f47b130c.entry.js +4 -0
  292. package/dist/twilight/{p-db526796.entry.js → p-f57ca123.entry.js} +1 -1
  293. package/dist/twilight/{p-933881d3.entry.js → p-f5ad6572.entry.js} +1 -1
  294. package/dist/twilight/p-fc65084f.entry.js +4 -0
  295. package/dist/twilight/p-fd81a311.entry.js +4 -0
  296. package/dist/twilight/{p-9fa5ffcf.entry.js → p-fe983809.entry.js} +1 -1
  297. package/dist/twilight/{p-Czq4p9Qp.js → p-i5J7XGS6.js} +1 -1
  298. package/dist/twilight/{p-C2bMx7q5.js → p-shFpk0H3.js} +1 -1
  299. package/dist/twilight/twilight.esm.js +1 -1
  300. package/dist/types/components/salla-add-product-button/salla-add-product-button.d.ts +5 -0
  301. package/dist/types/components/salla-app-install-alert/salla-app-install-alert.d.ts +3 -1
  302. package/dist/types/components/salla-color-picker/salla-color-picker.d.ts +10 -0
  303. package/dist/types/components/salla-product-options/salla-product-options.d.ts +8 -1
  304. package/dist/types/components/salla-products-list/salla-products-list.d.ts +2 -0
  305. package/dist/types/components.d.ts +4 -0
  306. package/package.json +5 -5
  307. package/dist/cjs/salla-accordion_62.cjs.entry.js +0 -22420
  308. package/dist/cjs/salla-review-card.cjs.entry.js +0 -183
  309. package/dist/cjs/salla-reviews-page.cjs.entry.js +0 -695
  310. package/dist/cjs/salla-reviews.cjs.entry.js +0 -106
  311. package/dist/esm/salla-accordion_62.entry.js +0 -22339
  312. package/dist/esm/salla-review-card.entry.js +0 -181
  313. package/dist/esm/salla-reviews-page.entry.js +0 -693
  314. package/dist/esm/salla-reviews.entry.js +0 -104
  315. package/dist/twilight/p-01bccbf2.entry.js +0 -4
  316. package/dist/twilight/p-22d83528.entry.js +0 -4
  317. package/dist/twilight/p-3a74b551.entry.js +0 -4
  318. package/dist/twilight/p-4e416704.entry.js +0 -4
  319. package/dist/twilight/p-5dbf4cec.entry.js +0 -4
  320. package/dist/twilight/p-CBT_Nxny.js +0 -4
  321. package/dist/twilight/p-Dz7o69vX.js +0 -4
  322. package/dist/twilight/p-a42d626d.entry.js +0 -4
  323. package/dist/twilight/p-yRO-ZESF.js +0 -4
  324. package/dist/cjs/{twitter-pOrUNjXi.js → facebook-DbXua6B9.js} +2 -2
  325. package/dist/esm/{twitter-Dz7o69vX.js → facebook-CO-PeZ27.js} +2 -2
@@ -0,0 +1,2384 @@
1
+ /*!
2
+ * Crafted with ❤ by Salla
3
+ */
4
+ import { r as registerInstance, c as createEvent, h, H as Host, a as getElement, e as axios } from './index-B74h9G6a.js';
5
+ import { P as PendingOrdersIcon } from './cart-DY4LZmNP.js';
6
+ import { B as BellRing } from './bell-ring-D3mWkc-3.js';
7
+ import { H as Helper } from './Helper-B5RLi6Xo.js';
8
+ import { i as iconCheck } from './check-BsXh13x8.js';
9
+ import { C as CameraIcon } from './camera-C6jIkM-X.js';
10
+ import './anime.es-CgtvEd63.js';
11
+
12
+ var WalletIcon = `<!-- Generated by IcoMoon.io -->
13
+ <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
14
+ <title>full-wallet</title>
15
+ <path d="M29 12h-26c-0.668-0.008-1.284-0.226-1.787-0.59l0.009 0.006c-0.744-0.552-1.222-1.428-1.222-2.416 0-1.657 1.343-3 2.999-3h6c0.552 0 1 0.448 1 1s-0.448 1-1 1v0h-6c-0.552 0-1 0.448-1 1 0 0.326 0.156 0.616 0.397 0.798l0.002 0.002c0.167 0.12 0.374 0.194 0.599 0.2l0.001 0h26c0.552 0 1 0.448 1 1s-0.448 1-1 1v0zM27 12c-0.552 0-1-0.448-1-1v0-3h-3c-0.552 0-1-0.448-1-1s0.448-1 1-1v0h4c0.552 0 1 0.448 1 1v0 4c0 0.552-0.448 1-1 1v0zM29 30h-26c-1.657 0-3-1.343-3-3v0-18c0-0.552 0.448-1 1-1s1 0.448 1 1v0 18c0 0.552 0.448 1 1 1v0h25v-5c0-0.552 0.448-1 1-1s1 0.448 1 1v0 6c0 0.552-0.448 1-1 1v0zM29 18c-0.552 0-1-0.448-1-1v0-6c0-0.552 0.448-1 1-1s1 0.448 1 1v0 6c0 0.552-0.448 1-1 1v0zM31 24h-7c-2.209 0-4-1.791-4-4s1.791-4 4-4v0h7c0.552 0 1 0.448 1 1v0 6c0 0.552-0.448 1-1 1v0zM24 18c-1.105 0-2 0.895-2 2s0.895 2 2 2v0h6v-4zM25 12c-0.001 0-0.001 0-0.002 0-0.389 0-0.726-0.222-0.891-0.546l-0.003-0.006-3.552-7.106-2.306 1.152c-0.13 0.066-0.284 0.105-0.447 0.105-0.552 0-1-0.448-1-1 0-0.39 0.223-0.727 0.548-0.892l0.006-0.003 3.2-1.6c0.13-0.067 0.284-0.106 0.447-0.106 0.39 0 0.727 0.223 0.892 0.548l0.003 0.006 4 8c0.067 0.13 0.106 0.285 0.106 0.448 0 0.552-0.448 1-1 1v0zM21 12c-0.001 0-0.001 0-0.002 0-0.389 0-0.726-0.222-0.891-0.546l-0.003-0.006-3.552-7.106-15.104 7.552c-0.13 0.066-0.284 0.105-0.447 0.105-0.552 0-1-0.448-1-1 0-0.39 0.223-0.727 0.548-0.892l0.006-0.003 16-8c0.13-0.067 0.284-0.106 0.447-0.106 0.39 0 0.727 0.223 0.892 0.548l0.003 0.006 4 8c0.067 0.13 0.106 0.285 0.106 0.448 0 0.552-0.448 1-1 1-0.001 0-0.001 0-0.002 0h0z"></path>
16
+ </svg>
17
+ `;
18
+
19
+ const sallaAddProductButtonCss = ":host{display:block}salla-add-product-button[width=wide]{width:100%}";
20
+
21
+ const SallaAddProductButton = class {
22
+ constructor(hostRef) {
23
+ registerInstance(this, hostRef);
24
+ this.success = createEvent(this, "success");
25
+ this.failed = createEvent(this, "failed");
26
+ this.hostAttributes = {};
27
+ /**
28
+ * Has Pre Order
29
+ */
30
+ this.hasPreOrder = false;
31
+ /**
32
+ * Product Status.Defaults to `sale`
33
+ */
34
+ this.productStatus = 'sale';
35
+ /**
36
+ * Product type. Defaults to `product`
37
+ */
38
+ this.productType = 'product';
39
+ this.selectedOptions = [];
40
+ this.buyNowText = salla.lang.get('pages.products.buy_now');
41
+ /** Use matchMedia instead of window.innerWidth to avoid forced reflow (Lighthouse/PageSpeed) */
42
+ this.isDesktopViewport = typeof window !== 'undefined' ? window.matchMedia('(min-width: 768px)').matches : true;
43
+ this.viewportMediaQuery = null;
44
+ this.onViewportChange = (e) => {
45
+ this.isDesktopViewport = e.matches;
46
+ this.btn?.setText((e.matches && !!this.passedLabel) ? this.passedLabel : this.getLabel());
47
+ };
48
+ salla.lang.onLoaded(() => {
49
+ this.buyNowText = salla.lang.get('pages.products.buy_now');
50
+ });
51
+ }
52
+ getLabel() {
53
+ if (this.productStatus === 'sale' && this.supportStickyBar && !this.isDesktopViewport && this.showQuickBuy && this.isApplePayActive) {
54
+ return PendingOrdersIcon;
55
+ }
56
+ if (this.hasPreOrder) {
57
+ return salla.lang.get('pages.products.pre_order_now');
58
+ }
59
+ if (this.productStatus === 'sale' && this.productType === 'booking') {
60
+ return salla.lang.get('pages.cart.book_now');
61
+ }
62
+ if (this.productStatus === 'sale') {
63
+ return salla.lang.get('pages.cart.add_to_cart');
64
+ }
65
+ if (this.productType !== 'donating') {
66
+ return salla.lang.get('pages.products.out_of_stock');
67
+ }
68
+ // donating
69
+ return salla.lang.get('pages.products.donation_exceed');
70
+ }
71
+ addProductToCart(event) {
72
+ if (this.productType === 'booking') {
73
+ event.preventDefault();
74
+ return this.addBookingProduct();
75
+ }
76
+ // we want to ignore the click action when the type of button is submit a form
77
+ if (this.hostAttributes.type === 'submit') {
78
+ return false;
79
+ }
80
+ event.preventDefault();
81
+ this.btn?.disable();
82
+ // Validate product options explicitly on Add to Cart click
83
+ const optionsEl = document.querySelector(`salla-product-options[product-id="${this.productId}"]`);
84
+ if (optionsEl && typeof optionsEl.validateAndScroll === 'function') {
85
+ return optionsEl.validateAndScroll()
86
+ .then(async (isValid) => {
87
+ // Call validate hook
88
+ const ctx = { isValid, component: this };
89
+ await salla.hooks.call('salla-add-product-button', 'validate', ctx);
90
+ if (!ctx.isValid) {
91
+ this.btn?.enable();
92
+ return;
93
+ }
94
+ return this._proceedAddToCart();
95
+ })
96
+ .catch(() => {
97
+ this.btn?.enable();
98
+ });
99
+ }
100
+ // Fallback if options component not found
101
+ return this._proceedAddToCart();
102
+ }
103
+ async _proceedAddToCart() {
104
+ /**
105
+ * by default the quick add is just an alias for add item function
106
+ * but its work only when the id is the only value is passed via the object
107
+ * so we will filter the object entities to remove null and zero values in case we don't want the normal add item action
108
+ */
109
+ const data = Object.entries({
110
+ id: this.productId,
111
+ donation_amount: this.donatingAmount,
112
+ quantity: this.quantity,
113
+ endpoint: 'quickAdd'
114
+ }).reduce((a, [k, v]) => (v ? (a[k] = v, a) : a), {});
115
+ // Use the potentially modified data
116
+ return salla.cart.addItem(data)
117
+ .then(async (response) => {
118
+ this.selectedOptions = [];
119
+ this.btn?.enable();
120
+ this.success.emit(response);
121
+ return response;
122
+ })
123
+ .catch(error => { this.failed.emit(error); this.btn?.enable(); });
124
+ }
125
+ addBookingProduct() {
126
+ if (salla.config.isGuest()) {
127
+ salla.auth.api.setAfterLoginEvent('booking::add', this.productId);
128
+ salla.event.dispatch('login::open');
129
+ return;
130
+ }
131
+ return salla.booking.add(this.productId)
132
+ .then(resp => this.success.emit(resp))
133
+ .catch(error => this.failed.emit(error));
134
+ }
135
+ getBtnAttributes() {
136
+ for (let i = 0; i < this.host.attributes.length; i++) {
137
+ if (!['id', 'class'].includes(this.host.attributes[i].name)) {
138
+ this.hostAttributes[this.host.attributes[i].name] = this.host.attributes[i].value;
139
+ }
140
+ }
141
+ return this.hostAttributes;
142
+ }
143
+ getQuickBuyBtnAttributes() {
144
+ return {
145
+ ...this.getBtnAttributes(),
146
+ type: this.supportStickyBar && !this.isDesktopViewport ? 'plain' : this.productType == 'donating' ? 'donate' : 'buy'
147
+ };
148
+ }
149
+ miniCheckoutWidget() {
150
+ let storeId = salla.config.get('store.id');
151
+ if (!storeId) {
152
+ return;
153
+ }
154
+ return h("salla-mini-checkout-widget", { language: salla.lang.locale, "store-id": storeId, config: { user: salla.config.get('user'), failure_url: window.location.href }, products: [this.productId], api: salla.config.get('store.api'), outline: true, "form-selector": "form.product-form", class: "s-add-product-button-mini-checkout" }, h("div", { slot: "widget-label", class: "s-add-product-button-mini-checkout-content" }, h("span", { innerHTML: WalletIcon }), this.buyNowText));
155
+ }
156
+ componentWillLoad() {
157
+ return salla.onReady()
158
+ .then(() => {
159
+ // this to fix not added hydrated class to html element after components loaded
160
+ document.documentElement.classList.add('hydrated');
161
+ this.showQuickBuy = this.quickBuy
162
+ && salla.config.get('store.settings.buy_now')
163
+ && this.productStatus == 'sale'
164
+ && this.productType !== 'booking';
165
+ this.isApplePayActive = window.ApplePaySession?.canMakePayments()
166
+ && salla.config.get('store.settings.payments')?.includes('apple_pay')
167
+ && salla.config.get('store.settings.is_salla_gateway', false);
168
+ this.passedLabel = this.host.innerHTML.replace('<!---->', '').trim();
169
+ if (!!this.passedLabel && this.isDesktopViewport) {
170
+ return this.btn?.setText(this.passedLabel);
171
+ }
172
+ if (this.host.getAttribute('type') === 'submit' && this.supportStickyBar) {
173
+ this.viewportMediaQuery = window.matchMedia('(min-width: 768px)');
174
+ this.viewportMediaQuery.addEventListener('change', this.onViewportChange);
175
+ }
176
+ });
177
+ }
178
+ render() {
179
+ //TODO:: find a better fix, this is a patch for issue that duplicates the buttons more than twice @see the screenshot inside this folder
180
+ if (this.host.closest('.swiper-slide')?.classList.contains('swiper-slide-duplicate')) {
181
+ return '';
182
+ }
183
+ if (this.hasSubscribedOptions) {
184
+ return h(Host, null, h("salla-product-availability", { ...this.getBtnAttributes(), "is-subscribed": true }, h("span", { class: "s-hidden" }, h("slot", null))));
185
+ }
186
+ if ((this.productStatus === 'out-and-notify' && this.channels) || this.hasOutOfStockOption) {
187
+ return h(Host, null, h("salla-product-availability", { ...this.getBtnAttributes() }, h("span", { class: "s-hidden" }, h("slot", null))));
188
+ }
189
+ return h(Host, { class: {
190
+ 's-add-product-button-with-quick-buy': this.showQuickBuy,
191
+ 's-add-product-button-with-sticky-bar': this.supportStickyBar,
192
+ 's-add-product-button-with-apple-pay': this.showQuickBuy && this.isApplePayActive
193
+ } }, h("div", { class: {
194
+ 's-add-product-button-main': this.showQuickBuy,
195
+ 'w-full': !document.getElementById('fast-checkout-js') || ['financial_support', 'donating'].includes(this.productType) // This is a temporary fix until all themes fully support the fast checkout -- To be removed later
196
+ } }, h("salla-button", { color: this.productStatus === 'sale' ? 'primary' : 'light', type: "button", fill: this.productStatus === 'sale' ? 'solid' : 'outline', ref: el => this.btn = el, onClick: event => this.addProductToCart(event), disabled: this.productStatus !== 'sale', ...this.getBtnAttributes(), "loader-position": "center" }, h("slot", null)), this.showQuickBuy && !!document.getElementById('fast-checkout-js') && !['financial_support', 'donating'].includes(this.productType) ? this.miniCheckoutWidget() : ''), this.showQuickBuy && this.isApplePayActive ? h("salla-quick-buy", { ...this.getQuickBuyBtnAttributes() }) : '');
197
+ }
198
+ async componentDidLoad() {
199
+ // Register this component for hooks system, already on it logic to run componentDidLoad trigger
200
+ await Salla.hooks.registerComponent('salla-add-product-button', this);
201
+ if (!this.notifyOptionsAvailability) {
202
+ return;
203
+ }
204
+ salla.event.on('product-options::change', async (data) => {
205
+ if (!['thumbnail', 'color', 'single-option'].includes(data.option.type)) {
206
+ return;
207
+ }
208
+ this.hasSubscribedOptions = false;
209
+ this.selectedOptions = await document.querySelector(`salla-product-options[product-id="${this.productId}"]`)?.getSelectedOptions();
210
+ this.hasOutOfStockOption = await document.querySelector(`salla-product-options[product-id="${this.productId}"]`)?.hasOutOfStockOption();
211
+ let subscribedDetails = salla.storage.get(`product-${this.productId}-subscribed-options`);
212
+ if (!subscribedDetails && !this.subscribedOptions || !this.hasOutOfStockOption) {
213
+ return;
214
+ }
215
+ if (salla.config.isGuest()) {
216
+ const parsedSubscribedDetails = subscribedDetails ? subscribedDetails.map(ids => ids.split(',').map(id => parseInt(id))) : [];
217
+ this.hasSubscribedOptions = parsedSubscribedDetails.length > 0 && parsedSubscribedDetails.some(ids => ids.every(id => this.selectedOptions.some(option => option.id === id)));
218
+ }
219
+ else {
220
+ this.hasSubscribedOptions = this.subscribedOptions && this.subscribedOptions !== 'null' && this.subscribedOptions !== '[]' ? JSON.parse(this.subscribedOptions).some(ids => ids.every(id => this.selectedOptions.some(option => option.id === id))) : false;
221
+ }
222
+ });
223
+ }
224
+ componentDidRender() {
225
+ //if label not passed, get label
226
+ if (!!this.passedLabel && (!this.supportStickyBar || this.isDesktopViewport)) {
227
+ // if passed label, set it
228
+ this.btn?.setText(this.passedLabel);
229
+ return;
230
+ }
231
+ this.btn?.setText(this.getLabel());
232
+ salla.lang.onLoaded(() => this.btn?.setText(this.getLabel()));
233
+ }
234
+ disconnectedCallback() {
235
+ this.viewportMediaQuery?.removeEventListener('change', this.onViewportChange);
236
+ }
237
+ get host() { return getElement(this); }
238
+ };
239
+ SallaAddProductButton.style = sallaAddProductButtonCss;
240
+
241
+ const sallaProductAvailabilityCss = "";
242
+
243
+ const SallaProductAvailability = class {
244
+ constructor(hostRef) {
245
+ registerInstance(this, hostRef);
246
+ this.isUser = salla.config.isUser();
247
+ this.translationLoaded = false;
248
+ /**
249
+ * Listen to product options availability.
250
+ */
251
+ this.notifyOptionsAvailability = false;
252
+ /**
253
+ * is current user already subscribed
254
+ */
255
+ this.isSubscribed = false;
256
+ this.handleSubmitOptions = async () => {
257
+ let payload = { id: this.productId };
258
+ if (!this.notifyOptionsAvailability) {
259
+ return payload;
260
+ }
261
+ let optionsElement = document.querySelector(`salla-product-options[product-id="${this.productId}"]`);
262
+ let options = Object.values(await optionsElement?.getSelectedOptionsData() || {});
263
+ //if all options not selected, show message && throw exception
264
+ if (options.length && !await optionsElement?.reportValidity()) {
265
+ let errorMessage = salla.lang.get('common.messages.required_fields');
266
+ salla.error(errorMessage);
267
+ throw errorMessage;
268
+ }
269
+ payload.options = [];
270
+ options.forEach(option => {
271
+ //inject numbers only, without zeros
272
+ if (option && !isNaN(option)) {
273
+ payload.options.push(Number(option));
274
+ }
275
+ });
276
+ return payload;
277
+ };
278
+ // helpers
279
+ this.typing = (e) => {
280
+ const error = e.target.nextElementSibling;
281
+ e.target.classList.remove('s-has-error');
282
+ error?.classList.contains('s-product-availability-error-msg') && (error.innerText = '');
283
+ e.keyCode === 13 && this.submit();
284
+ };
285
+ salla.lang.onLoaded(() => {
286
+ this.translationLoaded = true;
287
+ this.title_ = this.host.title || salla.lang.get('pages.products.notify_availability_title');
288
+ this.modal?.setTitle(this.title_);
289
+ });
290
+ if (!this.productId) {
291
+ this.productId = salla.config.get('page.id');
292
+ }
293
+ if (this.isUser)
294
+ return;
295
+ this.channelsWatcher(this.channels);
296
+ this.title_ = this.host.title || salla.lang.get('pages.products.notify_availability_title');
297
+ this.host.removeAttribute('title');
298
+ //todo:: fix this to cover options too
299
+ this.isVisitorSubscribed = !this.notifyOptionsAvailability ? salla.storage.get(`product-${this.productId}-subscribed`) : '';
300
+ }
301
+ channelsWatcher(newValue) {
302
+ this.channels_ = !!newValue ? newValue.split(',') : [];
303
+ }
304
+ openModel() {
305
+ this.handleSubmitOptions().then(isSuccess => isSuccess ? this.modal.open() : null);
306
+ }
307
+ async submit() {
308
+ let payload = await this.handleSubmitOptions();
309
+ if (this.isUser) {
310
+ return salla.api.product.availabilitySubscribe(payload)
311
+ .then(() => this.isSubscribed = true);
312
+ }
313
+ if (this.channels_.includes('sms')) {
314
+ let { phone, countryCode } = await this.mobileInput.getValues();
315
+ payload['country_code'] = countryCode;
316
+ payload['phone'] = phone;
317
+ }
318
+ if (this.channels_.includes('email')) {
319
+ this.email.value !== '' && (payload['email'] = this.email.value);
320
+ }
321
+ await this.validateform();
322
+ return this.btn.load()
323
+ .then(() => this.btn.disable())
324
+ .then(() => salla.api.product.availabilitySubscribe(payload))
325
+ .then(() => {
326
+ if (!this.notifyOptionsAvailability) {
327
+ salla.storage.set(`product-${this.productId}-subscribed`, true);
328
+ this.isSubscribed = true;
329
+ return;
330
+ }
331
+ if (payload.options.length) {
332
+ let options = salla.storage.get(`product-${this.productId}-subscribed-options`) || [];
333
+ let selectedOptionsString = payload.options.join(',');
334
+ if (!options.includes(selectedOptionsString)) {
335
+ options.push(selectedOptionsString);
336
+ salla.storage.set(`product-${this.productId}-subscribed-options`, options);
337
+ this.isSubscribed = true;
338
+ }
339
+ else {
340
+ salla.log('already subscribed to this options');
341
+ }
342
+ }
343
+ })
344
+ .then(() => this.btn.stop())
345
+ .then(() => this.modal.close())
346
+ .catch(() => this.btn.stop() && this.btn.enable());
347
+ }
348
+ async validateform() {
349
+ try {
350
+ if (this.channels_.includes('email')) {
351
+ const isEmailValid = Helper.isValidEmail(this.email.value);
352
+ if (isEmailValid)
353
+ return;
354
+ !isEmailValid && this.validateField(this.email, salla.lang.get('common.elements.email_is_valid'));
355
+ }
356
+ if (this.channels_.includes('sms')) {
357
+ const isPhoneValid = await this.mobileInput.isValid();
358
+ if (isPhoneValid)
359
+ return;
360
+ }
361
+ }
362
+ catch (error) {
363
+ throw ('Please insert required fields');
364
+ }
365
+ }
366
+ validateField(field, errorMsg) {
367
+ field.classList.add('s-has-error');
368
+ field.nextElementSibling['innerText'] = '* ' + errorMsg;
369
+ }
370
+ render() {
371
+ return (h(Host, { key: 'e5b3121a6e352338ff666ba419100150e838e0d2', class: "s-product-availability-wrap" }, this.isSubscribed || this.isVisitorSubscribed
372
+ ? h("div", { class: "s-product-availability-subscribed" }, h("span", { innerHTML: BellRing, class: "s-product-availability-subs-icon" }), salla.lang.get('pages.products.notify_availability_success'))
373
+ :
374
+ h("salla-button", { width: "wide", onClick: () => this.isUser ? this.submit() : this.openModel() }, salla.lang.get('pages.products.notify_availability')), this.isUser || this.isSubscribed || this.isVisitorSubscribed ? '' : this.renderModal()));
375
+ }
376
+ renderModal() {
377
+ return (h("salla-modal", { ref: modal => this.modal = modal, "modal-title": this.title_, subTitle: salla.lang.get('pages.products.notify_availability_subtitle'), width: "sm" }, h("span", { slot: 'icon', class: "s-product-availability-header-icon", innerHTML: BellRing }), h("div", { class: "s-product-availability-body" }, this.channels_.includes('email') ? [
378
+ h("label", { class: "s-product-availability-label" }, salla.lang.get('common.elements.email')),
379
+ h("input", { class: "s-product-availability-input", onKeyDown: e => this.typing(e), placeholder: salla.lang.get('common.elements.email_placeholder') || 'your@email.com', ref: el => this.email = el, type: "email" }),
380
+ h("span", { class: "s-product-availability-error-msg" })
381
+ ] : '', this.channels_.includes('sms') ? [
382
+ h("label", { class: "s-product-availability-label" }, salla.lang.get('common.elements.mobile')),
383
+ h("salla-tel-input", { ref: el => this.mobileInput = el, onKeyDown: e => this.typing(e) })
384
+ ] : ''), h("div", { slot: "footer", class: "s-product-availability-footer" }, h("salla-button", { class: "modal-cancel-btn", width: "wide", color: "light", fill: "outline", onClick: () => this.modal.close() }, salla.lang.get('common.elements.cancel')), h("salla-button", { class: "submit-btn", "loader-position": 'center', width: "wide", ref: btn => this.btn = btn, onClick: () => this.submit() }, salla.lang.get('common.elements.submit')))));
385
+ }
386
+ get host() { return getElement(this); }
387
+ static get watchers() { return {
388
+ "channels": ["channelsWatcher"]
389
+ }; }
390
+ };
391
+ SallaProductAvailability.style = sallaProductAvailabilityCss;
392
+
393
+ var DisplayType;
394
+ (function (DisplayType) {
395
+ DisplayType["COLOR"] = "color";
396
+ DisplayType["DATE"] = "date";
397
+ DisplayType["DATETIME"] = "datetime";
398
+ DisplayType["DONATION"] = "donation";
399
+ DisplayType["IMAGE"] = "image";
400
+ DisplayType["MULTIPLE_OPTIONS"] = "multiple-options";
401
+ DisplayType["NUMBER"] = "number";
402
+ DisplayType["SINGLE_OPTION"] = "single-option";
403
+ DisplayType["DIGITAL_CARD_VALUE"] = "digital-code-value";
404
+ DisplayType["COUNTRY"] = "country";
405
+ DisplayType["SPLITTER"] = "splitter";
406
+ DisplayType["TEXT"] = "text";
407
+ DisplayType["TEXTAREA"] = "textarea";
408
+ DisplayType["THUMBNAIL"] = "thumbnail";
409
+ DisplayType["TIME"] = "time";
410
+ DisplayType["RADIO"] = "radio";
411
+ DisplayType["CHECKBOX"] = "checkbox";
412
+ DisplayType["MAP"] = "map";
413
+ DisplayType["FILE"] = "file";
414
+ DisplayType["COLOR_PICKER"] = "color_picker";
415
+ DisplayType["BOOKING"] = "booking";
416
+ })(DisplayType || (DisplayType = {}));
417
+ var Currency;
418
+ (function (Currency) {
419
+ Currency["Sar"] = "SAR";
420
+ })(Currency || (Currency = {}));
421
+
422
+ var FileIcon = `<!-- Generated by IcoMoon.io -->
423
+ <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
424
+ <title>file-upload</title>
425
+ <path d="M21.333 24c0.341 0 0.683-0.131 0.943-0.391 0.521-0.521 0.521-1.364 0-1.885l-5.333-5.333c-0.123-0.123-0.271-0.22-0.433-0.288-0.327-0.135-0.693-0.135-1.019 0-0.163 0.068-0.311 0.165-0.433 0.288l-5.333 5.333c-0.521 0.521-0.521 1.364 0 1.885s1.364 0.521 1.885 0l3.057-3.057v10.115c0 0.736 0.597 1.333 1.333 1.333s1.333-0.597 1.333-1.333v-10.115l3.057 3.057c0.26 0.26 0.601 0.391 0.943 0.391zM28.943 9.724l-9.333-9.333c-0.249-0.251-0.589-0.391-0.943-0.391h-12c-2.205 0-4 1.795-4 4v24c0 2.205 1.795 4 4 4h4c0.736 0 1.333-0.597 1.333-1.333s-0.597-1.333-1.333-1.333h-4c-0.735 0-1.333-0.599-1.333-1.333v-24c0-0.735 0.599-1.333 1.333-1.333h11.448l8.552 8.552v16.781c0 0.735-0.599 1.333-1.333 1.333h-4c-0.736 0-1.333 0.597-1.333 1.333s0.597 1.333 1.333 1.333h4c2.205 0 4-1.795 4-4v-17.333c0-0.353-0.14-0.693-0.391-0.943z"></path>
426
+ </svg>
427
+ `;
428
+
429
+ const sallaProductOptionsCss = "";
430
+
431
+ const SallaProductOptions = class {
432
+ constructor(hostRef) {
433
+ registerInstance(this, hostRef);
434
+ this.changed = createEvent(this, "changed");
435
+ this.fileTypes = {
436
+ pdf: 'application/pdf',
437
+ png: 'image/png',
438
+ jpg: 'image/jpeg',
439
+ word: 'application/doc,application/ms-doc,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
440
+ exl: 'application/excel,application/vnd.ms-excel,application/x-excel,application/x-msexcel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
441
+ txt: 'text/plain',
442
+ };
443
+ this.outOfStockText = "";
444
+ this.donationAmount = salla.lang.get('pages.products.donation_amount');
445
+ this.selectDonationAmount = salla.lang.getWithDefault('pages.products.select_donation_amount', 'تحديد مبلغ التبرع');
446
+ this.selectAmount = salla.lang.getWithDefault('pages.products.select_amount', 'اختر المبلغ');
447
+ this.isCustomDonation = false;
448
+ this.selectedOptions = [];
449
+ this.canDisabled = false;
450
+ this.disableCardValue = true;
451
+ this.availableDigitalCardValues = [];
452
+ this.userInitiatedValidation = false;
453
+ this.isCartMode = false;
454
+ this.outSkus = [];
455
+ /**
456
+ * Avoid selection of previous default or selected card value option
457
+ * when switching between digital card country options for the 1st time
458
+ */
459
+ this.ignoreDefaultCardValue = false;
460
+ /**
461
+ * The id of the product to which the options are going to be fetched for.
462
+ */
463
+ this.productId = salla.config.get('page.id');
464
+ this.handleDonationOptions = (event, detail, type, _option) => {
465
+ // Donating-amount input only: onInput updates price and dispatches native change for form price watcher.
466
+ if (detail === 'custom' && type === 'input') {
467
+ const inputTarget = event.target;
468
+ salla.helpers.inputDigitsOnly(inputTarget);
469
+ salla.event.emit('product-options::donation-changed', {
470
+ id: this.productId,
471
+ price: inputTarget.value
472
+ });
473
+ inputTarget.dispatchEvent(new window.Event('change', { bubbles: true }));
474
+ return;
475
+ }
476
+ // Tab (radio) change: get value from the radio that fired.
477
+ const value = type === 'option' ? String(event.target?.value ?? '') : '';
478
+ if (type === 'option' && detail === 'custom') {
479
+ // "Custom" tab: stop propagation so form does not see change until user types in donating-amount input.
480
+ event.preventDefault();
481
+ event.stopPropagation();
482
+ event.stopImmediatePropagation();
483
+ }
484
+ this.isCustomDonation = value === 'custom';
485
+ if (this.donationInput) {
486
+ if (value === 'custom') {
487
+ this.donationInput.value = '';
488
+ this.donationInput.focus();
489
+ }
490
+ else {
491
+ this.donationInput.value = value;
492
+ }
493
+ if (detail === 'custom') {
494
+ return;
495
+ }
496
+ salla.event.emit('product-options::donation-changed', {
497
+ id: this.productId,
498
+ price: value
499
+ });
500
+ }
501
+ };
502
+ this.hideLabel = (option) => {
503
+ if (option.type === DisplayType.DONATION && (option.donation && !option.donation.can_donate)) {
504
+ return true;
505
+ }
506
+ return false;
507
+ };
508
+ this.getExpireDonationMessage = (option) => {
509
+ if (!option.donation) {
510
+ return;
511
+ }
512
+ const completed = option.donation.target_amount <= option.donation.collected_amount;
513
+ return h("div", { class: { "s-product-options-donation-message": true, "s-product-options-donation-completed": completed, "s-product-options-donation-expired": !completed } }, h("p", null, option.donation.target_message), h("span", { innerHTML: completed ? salla.money(option.donation.target_amount) : '' }));
514
+ };
515
+ salla.lang.onLoaded(() => {
516
+ this.outOfStockText = salla.lang.get("pages.products.out_of_stock");
517
+ this.donationAmount = salla.lang.get('pages.products.donation_amount');
518
+ this.selectDonationAmount = salla.lang.getWithDefault('pages.products.select_donation_amount', 'تحديد مبلغ التبرع');
519
+ this.selectAmount = salla.lang.getWithDefault('pages.products.select_amount', 'اختر المبلغ');
520
+ });
521
+ if (this.options) {
522
+ try {
523
+ this.setOptionsData(Array.isArray(this.options) ? this.options : JSON.parse(this.options));
524
+ return;
525
+ }
526
+ catch (e) {
527
+ salla.log('Bad json passed via options prop');
528
+ }
529
+ }
530
+ if (!Array.isArray(this.optionsData)) {
531
+ salla.log('Options is not an array[] ---> ', this.optionsData);
532
+ this.setOptionsData([]);
533
+ }
534
+ if (this.productId && !salla.url.is_page('cart')) {
535
+ salla.api.product.getDetails(this.productId, ['options']).then(resp => this.setOptionsData(resp.data.options));
536
+ }
537
+ }
538
+ /**
539
+ * Sets the options data for the product
540
+ * @param optionsData - Array of product options
541
+ */
542
+ async setOptionsData(optionsData) {
543
+ this.optionsData = optionsData;
544
+ const that = this;
545
+ this.optionsData[0]?.details?.forEach(function (detail) {
546
+ Object.entries(detail.skus_availability || {})
547
+ .filter(sku => !sku[1])
548
+ .map(sku => that.outSkus.push(Number(sku[0])));
549
+ });
550
+ }
551
+ /**
552
+ * Get the id's of the selected options.
553
+ * */
554
+ async getSelectedOptionsData() {
555
+ const selectedOptions = {};
556
+ const formData = this.host.getElementSallaData();
557
+ // Check if bundleContext is defined as a prop on the component before accessing it
558
+ const contextData = (typeof this.bundleContext !== 'undefined') ? this.bundleContext : null;
559
+ formData.forEach((value, key) => {
560
+ if (contextData) {
561
+ // Handle bundle naming convention: bundle[sectionId][index][options][optionId]
562
+ if (key.startsWith('bundle[') && key.includes('[options][')) {
563
+ const optionId = key.split('[options][')[1].replace(']', '');
564
+ selectedOptions[optionId] = value;
565
+ }
566
+ }
567
+ else {
568
+ // Handle standard naming convention: options[optionId]
569
+ if (key.startsWith('options[')) {
570
+ selectedOptions[key.replace('options[', '').replace(']', '')] = value;
571
+ }
572
+ }
573
+ });
574
+ return selectedOptions;
575
+ }
576
+ /**
577
+ * Report options form validity.
578
+ * */
579
+ async reportValidity() {
580
+ const requiredElements = this.host.querySelectorAll('[required]');
581
+ let pass = true;
582
+ for (let i = 0; i < requiredElements.length; i++) {
583
+ //if there is only one invalid option, return false
584
+ if ('reportValidity' in requiredElements[i] && !requiredElements[i].reportValidity()) {
585
+ pass = false;
586
+ }
587
+ }
588
+ return pass;
589
+ }
590
+ /**
591
+ * Return true if there is any out of stock options are selected and vise versa.
592
+ * */
593
+ async hasOutOfStockOption() {
594
+ return this.selectedOptions.some(option => option.is_out) || (this.selectedSkus?.length && this.selectedSkus?.every(sku => this.outSkus.includes(sku)));
595
+ }
596
+ /**
597
+ * Get selected options.
598
+ * */
599
+ async getSelectedOptions() {
600
+ return this.selectedOptions;
601
+ }
602
+ /**
603
+ * Get a specific option by its id.
604
+ * */
605
+ async getOption(option_id) {
606
+ return this.optionsData.find(option => option.id === option_id);
607
+ }
608
+ // @ts-ignore
609
+ invalidHandler(event, option) {
610
+ const closestProductOption = event.target.closest('.s-product-options-option');
611
+ if (!closestProductOption.classList.contains('s-product-options-option-error')) {
612
+ closestProductOption.classList.add('s-product-options-option-error');
613
+ }
614
+ if ((this.userInitiatedValidation || salla.helpers.isIOSDevice()) && !salla.url.is_page('cart')) {
615
+ const firstInvalidElement = this.host.querySelector('.s-product-options-option-error');
616
+ if (firstInvalidElement === closestProductOption) {
617
+ this.scrollToElement(closestProductOption);
618
+ }
619
+ }
620
+ }
621
+ scrollToElement(element) {
622
+ if (!element)
623
+ return;
624
+ element.scrollIntoView({ behavior: 'smooth', block: 'center' });
625
+ }
626
+ changedHandler(event, option, fireChangeEvent = true) {
627
+ const data = {
628
+ event: event,
629
+ option: option,
630
+ detail: null,
631
+ productId: this.productId
632
+ };
633
+ if (option.details) {
634
+ const detail = option.details.find((detail) => {
635
+ return Number(detail.id) === Number(event.target.value);
636
+ });
637
+ data.detail = detail;
638
+ }
639
+ if (option.type === 'country') {
640
+ this.handleCountryOptionChange(event, data.detail);
641
+ }
642
+ const optionElement = event.target.closest('.s-product-options-option');
643
+ if (event.target.value ||
644
+ ((option.type === DisplayType.FILE || option.type === DisplayType.IMAGE) && event.type === 'added') ||
645
+ (option.type === DisplayType.MAP && event.type === 'selected' && (event.target.lat && event.target.lng))) {
646
+ setTimeout(() => {
647
+ optionElement.classList.remove('s-product-options-option-error');
648
+ }, 200);
649
+ }
650
+ if (option.type === DisplayType.DONATION) {
651
+ salla.event.emit('product-options::donation-changed', {
652
+ id: this.productId,
653
+ price: event.target.value
654
+ });
655
+ }
656
+ this.setSelectedSkus();
657
+ this.handleRequiredMultipleOptions(option);
658
+ const index = this.selectedOptions.findIndex(opt => opt.option_id === data.option.id);
659
+ if (data.option.type === DisplayType.MULTIPLE_OPTIONS) {
660
+ // Handle multiple selections
661
+ const detailIndex = this.selectedOptions.findIndex(opt => opt.option_id === data.option.id && opt?.id === data.detail?.id);
662
+ if (detailIndex > -1) {
663
+ // If the option is already selected, remove it (unselect)
664
+ this.selectedOptions.splice(detailIndex, 1);
665
+ }
666
+ else {
667
+ // If the option is not selected, add it to the selectedOptions array
668
+ this.selectedOptions.push({ ...data.detail, option_id: data.option.id });
669
+ }
670
+ }
671
+ else {
672
+ // Handle single selection
673
+ if (!data.detail || Object.keys(data.detail).length === 0) {
674
+ // If there is no value for the single-select, remove it from the selectedOptions array
675
+ if (index > -1) {
676
+ this.selectedOptions.splice(index, 1);
677
+ }
678
+ }
679
+ else {
680
+ // If a value exists, update or add the selection
681
+ if (index > -1) {
682
+ // Replace the existing selection with the new one
683
+ this.selectedOptions[index] = { ...data.detail, option_id: data.option.id };
684
+ }
685
+ else {
686
+ // If no selection exists for this input, add the new selection
687
+ this.selectedOptions.push({ ...data.detail, option_id: data.option.id });
688
+ }
689
+ }
690
+ }
691
+ // Update optionsData directly
692
+ this.optionsData = this.optionsData.map(opt => {
693
+ if (opt.id === data.option.id) {
694
+ return {
695
+ ...opt,
696
+ details: opt.details.map(detail => ({
697
+ ...detail,
698
+ is_selected: data.option.type === DisplayType.MULTIPLE_OPTIONS
699
+ ? this.selectedOptions.some(selected => selected.id === detail.id)
700
+ : Number(detail.id) === Number(data.detail?.id),
701
+ value: data.detail?.value
702
+ }))
703
+ };
704
+ }
705
+ return opt;
706
+ });
707
+ // Emit the event only if fireChangeEvent is true
708
+ if (fireChangeEvent) {
709
+ this.changed.emit(data);
710
+ salla.event.emit('product-options::change', data);
711
+ }
712
+ }
713
+ /**
714
+ * loop throw all selected details, then get common sku, if it's only one, means we selected all of them;
715
+ */
716
+ setSelectedSkus() {
717
+ this.selectedSkus = this.selectedOptions.map(detail => Object.keys(detail.skus_availability || {}))
718
+ .reduce((p, c) => p.filter(e => c.includes(e)), []) // Initialize accumulator as an empty array
719
+ .map(sku => Number(sku));
720
+ }
721
+ handleRequiredMultipleOptions(option) {
722
+ if (option.type !== DisplayType.MULTIPLE_OPTIONS || !option.required) {
723
+ return;
724
+ }
725
+ const optionContainer = this.host.querySelector(`[data-option-id="${option.id}"]`);
726
+ const hasChecked = optionContainer.querySelectorAll('input:checked').length;
727
+ optionContainer.querySelectorAll('input').forEach(input => input.toggleAttribute('required', !hasChecked));
728
+ }
729
+ getLatLng(value, type) {
730
+ return value
731
+ ? value.split(',')[type === 'lat' ? 0 : 1]
732
+ : '';
733
+ }
734
+ getDisplayForType(option) {
735
+ if (this[`${option.type}Option`]) {
736
+ return this[`${option.type}Option`](option);
737
+ }
738
+ if (option.type === DisplayType.COLOR_PICKER) {
739
+ return this.colorPickerOption(option);
740
+ }
741
+ if (option.type === DisplayType.MULTIPLE_OPTIONS) {
742
+ return this.multipleOptions(option);
743
+ }
744
+ if (option.type === DisplayType.SINGLE_OPTION) {
745
+ return this.singleOption(option);
746
+ }
747
+ // Handle radio type as single option for bundle products
748
+ if (option.type === DisplayType.RADIO) {
749
+ return this.radioOption(option);
750
+ }
751
+ if (option.type === DisplayType.DIGITAL_CARD_VALUE) {
752
+ return this.digitalCardValuesOption(option);
753
+ }
754
+ if (option.type === DisplayType.COUNTRY) {
755
+ return this.countryOption(option);
756
+ }
757
+ if (option.type === DisplayType.BOOKING && salla.url.is_page("cart")) {
758
+ return h("salla-booking-field", { onInvalidInput: (e) => this.invalidHandler(e, option), option: option, productId: option.value });
759
+ }
760
+ salla.log(`Couldn't find options type(${option.type})😢`);
761
+ return '';
762
+ }
763
+ getOptionShownWhen(option) {
764
+ return option.visibility_condition
765
+ ? { "data-show-when": `options[${option.visibility_condition.option}] ${option.visibility_condition.operator} ${option.visibility_condition.value}` }
766
+ : {};
767
+ }
768
+ getAvailableDigitalCardSKUs(detail) {
769
+ const digitalCardOption = this.optionsData.find(({ type }) => type === 'digital-code-value');
770
+ if (!digitalCardOption)
771
+ throw new Error('product-options:: No digital card options found');
772
+ const outofStockSKUs = Object.keys(detail.skus_availability).filter(key => detail.skus_availability[key] === false);
773
+ this.availableDigitalCardValues = digitalCardOption.details.filter((op) => {
774
+ return !Object.keys(op.skus_availability).filter(SKU_key => outofStockSKUs.includes(SKU_key)).length;
775
+ });
776
+ }
777
+ handleCountryOptionChange(event, detail) {
778
+ event.stopImmediatePropagation();
779
+ this.ignoreDefaultCardValue = true;
780
+ const currentCardValue = this.host.querySelector("input[data-code-value]:checked");
781
+ if (currentCardValue)
782
+ currentCardValue.checked = false;
783
+ const digitalCardOption = this.optionsData.find(({ type }) => type === 'digital-code-value');
784
+ if (!digitalCardOption)
785
+ throw new Error('product-options:: No digital card options found');
786
+ this.getAvailableDigitalCardSKUs(detail);
787
+ }
788
+ getSelectedDigitalCardOptions(option) {
789
+ const selectedOption = option.details.find(detail => detail.is_selected);
790
+ const defaultOption = option.details.find(detail => !!detail.is_default) || option.details[0]; /*option.details[0] only applys for counrty options*/
791
+ if (!['digital-code-value', 'country'].includes(option.type))
792
+ return;
793
+ return selectedOption || defaultOption;
794
+ }
795
+ //we need the cart Id for productOption Image
796
+ async componentWillLoad() {
797
+ if (salla.url.is_page("cart")) {
798
+ this.disableCardValue = false;
799
+ this.fillSelectedOptions();
800
+ }
801
+ if (this.config) {
802
+ try {
803
+ this.optionConfig = typeof this.config === 'string' ? JSON.parse(this.config) : this.config;
804
+ }
805
+ catch (error) {
806
+ console.error('Failed to parse JSON in config prop:', error);
807
+ }
808
+ }
809
+ const shouldSelectDefaultOption = this.optionsData.filter(({ type }) => ["country", "digital-card-value"].includes(type)).length > 0 && salla.url.is_page('cart');
810
+ if (shouldSelectDefaultOption) {
811
+ const countryOption = this.optionsData.find(option => option.type === 'country');
812
+ const defaultSelection = countryOption && this.getSelectedDigitalCardOptions(countryOption);
813
+ if (defaultSelection) {
814
+ this.getAvailableDigitalCardSKUs(defaultSelection);
815
+ }
816
+ }
817
+ this.outOfStockText = salla.lang.get('pages.products.out_of_stock');
818
+ await salla.onReady();
819
+ this.canDisabled = !salla.config.get('store.settings.product.notify_options_availability') || salla.url.is_page('cart');
820
+ this.pasteHandler = this.handlePaste.bind(this);
821
+ document.addEventListener("paste", this.pasteHandler);
822
+ const needsCartId = (!salla.storage.get('cart.id') && this.optionsData.some(option => ['file', 'image'].includes(option.type)));
823
+ return needsCartId ? salla.api.cart.getCurrentCartId(false, "salla-product-options") : null;
824
+ }
825
+ disconnectedCallback() {
826
+ if (this.pasteHandler) {
827
+ document.removeEventListener("paste", this.pasteHandler);
828
+ }
829
+ }
830
+ /**
831
+ * This is a workaround for a bug in iOS 26 Safari, when pasting English text to RTL inputs, it adds extra text!!
832
+ * To avoid any break changes, we will make it only work on these conditions:
833
+ * - content_copyright is on
834
+ * - Apple Pay is enabled (means it's iOS/safari)
835
+ * - Input is an input or textarea
836
+ * - Salla form control
837
+ * - Options array
838
+ */
839
+ handlePaste(event) {
840
+ const target = event.target;
841
+ if (!Salla.helpers.isAppleDevice()
842
+ || !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)
843
+ || !target.classList.contains('s-form-control')
844
+ || !this.host.contains(target)) {
845
+ return;
846
+ }
847
+ // Prevent default paste (to avoid Safari inserting extra content)
848
+ event.preventDefault();
849
+ // Read only the clipboard data
850
+ const text = event.clipboardData?.getData("text") || "";
851
+ // Insert it manually at cursor if you want
852
+ const start = target.selectionStart;
853
+ const end = target.selectionEnd;
854
+ const newValue = target.value.slice(0, start) + text + target.value.slice(end);
855
+ target.value = newValue;
856
+ // Reset cursor position
857
+ target.setSelectionRange(start + text.length, start + text.length);
858
+ try {
859
+ target.dispatchEvent(new window.Event('change', { bubbles: true }));
860
+ }
861
+ catch (error) {
862
+ Salla.log('Error on change');
863
+ }
864
+ }
865
+ hideDigitalCardsOptions(option) {
866
+ return (this.disableCardValue && option.type === DisplayType.DIGITAL_CARD_VALUE && !salla.url.is_page("cart"));
867
+ }
868
+ render() {
869
+ if (this.optionsData?.length === 0) {
870
+ return;
871
+ }
872
+ return (h(Host, { class: "s-product-options-wrapper" }, h("salla-conditional-fields", null, this.optionsData.map((option) => h("div", { key: option.id, class: `s-product-options-option-container${option.visibility_condition || this.hideDigitalCardsOptions(option) ? ' hidden' : ''}`, "data-option-id": option.id, ...this.getOptionShownWhen(option) }, option.name === 'splitter' ?
873
+ this.splitterOption()
874
+ : h("div", { class: { "s-product-options-option": true, "s-product-options-option-booking": option.type === DisplayType.BOOKING && salla.url.is_page("cart") }, "data-option-type": option.type, "data-option-required": `${option.required}` }, h("label", { htmlFor: this.generateInputId(option.id), class: `s-product-options-option-label ${this.hideLabel(option) ? 's-product-options-option-label-hidden' : ''}` }, h("b", null, option.name, option.required && h("span", null, " * "), " "), h("small", null, option.placeholder)), h("div", { class: `s-product-options-option-content ${this.hideLabel(option) || (option.type === DisplayType.BOOKING && salla.url.is_page("cart")) ? 's-product-options-option-content-full-width' : ''}` }, this.getDisplayForType(option))))))));
875
+ }
876
+ generateUniqueKey(defaultValue) {
877
+ const contextData = this.bundleContext;
878
+ let baseKey = this.uniqueKey ? `${defaultValue}-${this.uniqueKey}` : defaultValue;
879
+ if (contextData) {
880
+ try {
881
+ // Handle both string and object types
882
+ const context = typeof contextData === 'string'
883
+ ? JSON.parse(contextData)
884
+ : contextData;
885
+ const { sectionId, productId } = context;
886
+ baseKey = `${baseKey}-bundle-${sectionId}-${productId}`;
887
+ }
888
+ catch (e) {
889
+ // If parsing fails, just use the base key
890
+ }
891
+ }
892
+ return baseKey;
893
+ }
894
+ /**
895
+ * Generate a valid HTML id for option inputs.
896
+ * @param optionId - The option ID
897
+ * @returns The formatted id string
898
+ */
899
+ generateInputId(optionId) {
900
+ return this.generateUniqueKey(`option-${optionId}`);
901
+ }
902
+ /**
903
+ * Generate the correct input name based on bundle context
904
+ * @param optionId - The option ID
905
+ * @returns The formatted input name
906
+ */
907
+ generateInputName(optionId) {
908
+ const contextData = this.bundleContext;
909
+ const baseOptionId = optionId.toString();
910
+ if (contextData) {
911
+ try {
912
+ // Handle both string and object types
913
+ const context = typeof contextData === 'string'
914
+ ? JSON.parse(contextData)
915
+ : contextData;
916
+ const { sectionId, productId } = context;
917
+ return `bundle[${sectionId}][${productId}][options][${baseOptionId}]`;
918
+ }
919
+ catch (e) {
920
+ return `options[${baseOptionId}]`;
921
+ }
922
+ }
923
+ return `options[${baseOptionId}]`;
924
+ }
925
+ fillSelectedOptions() {
926
+ this.selectedOptions = this.optionsData.reduce((acc, opt) => {
927
+ const selectedDetails = opt.details.filter(detail => detail.is_selected);
928
+ const mappedDetails = selectedDetails.map(detail => ({
929
+ ...detail,
930
+ option_id: opt.id
931
+ }));
932
+ return acc.concat(mappedDetails);
933
+ }, []);
934
+ }
935
+ async componentDidLoad() {
936
+ if (!this.optionsData?.length) {
937
+ return;
938
+ }
939
+ // Register for hooks — theme can call enterCartMode() here
940
+ await Salla.hooks.registerComponent('salla-product-options', this);
941
+ // Handle donation options
942
+ const selectedDonationOption = this.optionsData.find(option => option.type === DisplayType.DONATION)?.details?.find(detail => detail.is_selected);
943
+ if (selectedDonationOption) {
944
+ setTimeout(() => {
945
+ salla.event.emit('product-options::donation-changed', {
946
+ id: this.productId,
947
+ price: selectedDonationOption.additional_price
948
+ });
949
+ }, 1000);
950
+ }
951
+ // Handle pre-selected options on product page
952
+ // Skip if in cart mode (enterCartMode called by hook) or on cart page
953
+ // Call salla.product.getPrice() directly to avoid triggering form validation which causes unwanted scroll
954
+ if (!salla.url.is_page("cart") && !this.isCartMode) {
955
+ const pricingOptionTypes = [
956
+ DisplayType.SINGLE_OPTION,
957
+ DisplayType.MULTIPLE_OPTIONS,
958
+ DisplayType.COLOR,
959
+ DisplayType.THUMBNAIL,
960
+ DisplayType.DONATION,
961
+ DisplayType.DIGITAL_CARD_VALUE,
962
+ DisplayType.COUNTRY
963
+ ];
964
+ const hasPreSelectedPricingOption = this.optionsData.some(option => pricingOptionTypes.includes(option.type) &&
965
+ option.details?.some(detail => detail.is_selected));
966
+ if (hasPreSelectedPricingOption) {
967
+ // Use requestAnimationFrame to ensure DOM is fully painted before accessing form
968
+ requestAnimationFrame(() => {
969
+ try {
970
+ const form = this.host.closest('form');
971
+ if (!form)
972
+ return;
973
+ // Validate form belongs to this product to avoid conflicts on complex pages
974
+ const formData = new FormData(form);
975
+ const formProductId = formData.get('id') || formData.get('product_id');
976
+ if (formProductId && String(formProductId) !== String(this.productId))
977
+ return;
978
+ salla.product.getPrice(formData);
979
+ }
980
+ catch (e) {
981
+ salla.log('Error updating price for pre-selected options:', e);
982
+ }
983
+ });
984
+ }
985
+ }
986
+ }
987
+ /**
988
+ * Switch the component to cart-item mode: fill selected options,
989
+ * enable disabled-out-of-stock, and skip product price updates.
990
+ * Used by themes when treating a product page as a cart item editor.
991
+ */
992
+ async enterCartMode() {
993
+ this.isCartMode = true;
994
+ this.disableCardValue = false;
995
+ this.canDisabled = true;
996
+ this.fillSelectedOptions();
997
+ }
998
+ /**
999
+ * Enable user-initiated validation mode so invalid fields will scroll into view
1000
+ */
1001
+ async enableUserInitiatedValidation() {
1002
+ this.userInitiatedValidation = true;
1003
+ }
1004
+ /**
1005
+ * Validate options and trigger scrolling to the first invalid option if any
1006
+ */
1007
+ async validateAndScroll() {
1008
+ await this.enableUserInitiatedValidation();
1009
+ return this.reportValidity();
1010
+ }
1011
+ //@ts-ignore
1012
+ donationOption(option, product) {
1013
+ return h("div", { class: "s-product-options-donation-wrapper" }, option.donation?.can_donate ? [
1014
+ option.donation ?
1015
+ h("div", { key: option.id, class: "s-product-options-donation-progress" }, h("salla-progress-bar", { donation: option.donation }))
1016
+ : '',
1017
+ option.details.length ?
1018
+ [h("h4", { key: option.id }, this.selectAmount), h("div", { key: option.id, class: "s-product-options-donation-options" }, option.details.map((detail, i) => h("div", { key: option.id, class: "s-product-options-donation-options-item" }, h("input", { id: this.generateUniqueKey(`donation-option-${i}`), type: "radio", name: "donating_option", checked: detail.is_selected, value: detail.additional_price, onChange: e => this.handleDonationOptions(e, detail, 'option', option) }), h("label", { htmlFor: this.generateUniqueKey(`donation-option-${i}`) }, h("span", { innerHTML: salla.money(detail.name) })))), option.donation?.custom_amount_enabled ?
1019
+ h("div", { class: "s-product-options-donation-options-item" }, h("input", { id: this.generateUniqueKey("donation-option-custom"), type: "radio", name: "donating_option", value: "custom", onChange: e => this.handleDonationOptions(e, 'custom', 'option', option) }), h("label", { htmlFor: this.generateUniqueKey("donation-option-custom") }, h("span", null, " ", this.selectDonationAmount, " ")))
1020
+ : '')] : '',
1021
+ h("div", { key: option.id, class: { "s-product-options-donation-input-group": true, "shown": !option.details.length || (option.details.length && this.isCustomDonation) } }, h("input", { type: "text", id: "donating-amount", name: "donation_amount", class: "s-form-control", ref: el => { this.donationInput = el; }, value: option.details.length
1022
+ && option.details.some(detail => detail.is_selected)
1023
+ ? option.details.find(detail => detail.is_selected).additional_price
1024
+ : option.value,
1025
+ // required
1026
+ placeholder: option.placeholder, onInput: e => this.handleDonationOptions(e, 'custom', 'input', option), onBlur: e => this.changedHandler(e, option), onInvalid: (e) => this.invalidHandler(e, option) }), h("span", { class: "s-product-options-donation-amount-currency" }, salla.config.currency(salla.config.get('user.currency_code')).symbol))
1027
+ ] :
1028
+ this.getExpireDonationMessage(option));
1029
+ }
1030
+ fileUploader(option, additions = null) {
1031
+ return h("salla-file-upload", { ...(additions || {}), "payload-name": "file", value: option.value, "instant-upload": true, name: this.generateInputName(option.id), required: !option.visibility_condition && option.required, height: "120px", onAdded: (e) => this.changedHandler(e, option), url: salla.cart.api.getUploadImageEndpoint(), "form-data": { cart_item_id: this.productId, product_id: this.productId }, onInvalidInput: (e) => this.invalidHandler(e, option), class: { "s-product-options-image-input": true, required: option.required } }, h("div", { class: "s-product-options-filepond-placeholder" }, h("span", { class: "s-product-options-filepond-placeholder-icon", innerHTML: additions.accept?.split(',').every(type => type.includes('image'))
1032
+ ? CameraIcon
1033
+ : FileIcon }), h("p", { class: "s-product-options-filepond-placeholder-text" }, salla.lang.get('common.uploader.drag_and_drop')), h("span", { class: "filepond--label-action" }, salla.lang.get('common.uploader.browse'))));
1034
+ }
1035
+ //@ts-ignore
1036
+ imageOption(option) {
1037
+ return this.fileUploader(option, { accept: 'image/png,image/jpeg,image/jpg,image/gif' });
1038
+ }
1039
+ //@ts-ignore
1040
+ fileOption(option) {
1041
+ const types = option.details.map(detail => this.fileTypes[detail.name]).filter(Boolean);
1042
+ return types?.length
1043
+ ? this.fileUploader(option, { accept: types.join(',') })
1044
+ : 'File types not selected.';
1045
+ }
1046
+ // TODO: (ONLY FOR TESTING!) find a better way to make it testable, e.g. wrap it with a unique class like textOption
1047
+ //@ts-ignore
1048
+ numberOption(option) {
1049
+ return h("input", { type: "text", value: option.value, class: "s-form-control", required: !option.visibility_condition && option.required, id: this.generateInputId(option.id), name: this.generateInputName(option.id), placeholder: option.placeholder, onBlur: e => this.changedHandler(e, option), onInvalid: (e) => this.invalidHandler(e, option), onInput: e => salla.helpers.inputDigitsOnly(e.target) });
1050
+ }
1051
+ //@ts-ignore
1052
+ splitterOption() {
1053
+ return h("div", { class: "s-product-options-splitter" });
1054
+ }
1055
+ //@ts-ignore
1056
+ textOption(option) {
1057
+ return h("div", { class: "s-product-options-text" }, h("input", { type: "text", value: option.value, maxLength: option?.length, class: 's-form-control', required: !option.visibility_condition && option.required, id: this.generateInputId(option.id), name: this.generateInputName(option.id), placeholder: option.placeholder, onInvalid: (e) => this.invalidHandler(e, option), onChange: e => this.changedHandler(e, option) }));
1058
+ }
1059
+ //@ts-ignore
1060
+ textareaOption(option) {
1061
+ //todo::remove mt-1 class, and if it's okay to remove the tag itself will be great
1062
+ return h("div", { class: "s-product-options-textarea" }, h("div", { class: "mt-1" }, h("textarea", { rows: 4, value: option.value, maxLength: option?.length, class: "s-form-control", required: !option.visibility_condition && option.required, id: this.generateInputId(option.id), name: this.generateInputName(option.id), placeholder: option.placeholder, onInvalid: (e) => this.invalidHandler(e, option), onChange: (e) => this.changedHandler(e, option) })));
1063
+ }
1064
+ //@ts-ignore
1065
+ mapOption(option) {
1066
+ return h("salla-map", { zoom: 15, lat: this.getLatLng(option.value, 'lat'), lng: this.getLatLng(option.value, 'lng'), name: this.generateInputName(option.id), searchable: true, required: option.required, onInvalidInput: (e) => this.invalidHandler(e, option), onSelected: e => this.changedHandler(e, option) });
1067
+ }
1068
+ colorPickerOption(option) {
1069
+ return h("salla-color-picker", { onSubmitted: e => this.changedHandler(e, option), name: this.generateInputName(option.id), required: !option.visibility_condition && option.required, onInvalidInput: (e) => this.invalidHandler(e, option), color: option.value });
1070
+ }
1071
+ /**
1072
+ * ============= Date Time options =============
1073
+ */
1074
+ //@ts-ignore
1075
+ timeOption(option) {
1076
+ return h("salla-datetime-picker", { noCalendar: true, enableTime: true, dateFormat: "h:i K", value: option.value, placeholder: option.name, required: !option.visibility_condition && option.required, name: this.generateInputName(option.id), class: "s-product-options-time-element", onInvalidInput: (e) => this.invalidHandler(e, option), onPicked: e => this.changedHandler(e, option) });
1077
+ }
1078
+ //@ts-ignore
1079
+ dateOption(option) {
1080
+ //todo:: consider date-range @see https://github.com/SallaApp/theme-raed/blob/master/src/assets/js/partials/product-options.js#L8-L23
1081
+ return h("div", { class: "s-product-options-date-element" }, h("salla-datetime-picker", { value: option.value, placeholder: option.name, required: !option.visibility_condition && option.required, minDate: new Date(), name: this.generateInputName(option.id), onInvalidInput: (e) => this.invalidHandler(e, option), onPicked: e => this.changedHandler(e, option) }));
1082
+ }
1083
+ //@ts-ignore
1084
+ datetimeOption(option) {
1085
+ //todo:: consider date-range @see https://github.com/SallaApp/theme-raed/blob/master/src/assets/js/partials/product-options.js#L8-L23
1086
+ return h("div", { class: "s-product-options-datetime-element" }, h("salla-datetime-picker", { enableTime: true, value: option.value, dateFormat: "Y-m-d G:i:K", placeholder: option.name, required: !option.visibility_condition && option.required, name: this.generateInputName(option.id), maxDate: option.to_date_time, minDate: option.from_date_time, onInvalidInput: (e) => this.invalidHandler(e, option), onPicked: e => this.changedHandler(e, option) }));
1087
+ }
1088
+ /**
1089
+ * ============= Advanced options =============
1090
+ */
1091
+ getOptionDetailName(detail, outOfStock = true, optionType) {
1092
+ let detailName;
1093
+ if (optionType && optionType === DisplayType.COLOR) {
1094
+ detailName = detail.name
1095
+ + ((outOfStock && this.isOptionDetailOut(detail) && !salla.url.is_page("cart")) && !this.hideOutLabel ? ` <br/> <p> ${this.outOfStockText} </p>` : '')
1096
+ + (detail.additional_price ? ` <p> (${salla.money(detail.additional_price, false)}) </p>` : '');
1097
+ }
1098
+ if (!detailName) {
1099
+ detailName = detail.name
1100
+ + ((outOfStock && this.isOptionDetailOut(detail) && !salla.url.is_page("cart")) && !this.hideOutLabel ? ` - ${this.outOfStockText}` : '')
1101
+ + (detail.additional_price ? ` (${salla.money(detail.additional_price, false)})` : '');
1102
+ }
1103
+ //Some merchants adding price to the names of the options,
1104
+ //and because we are using this inside select option, we need to replace the html currency symbol with the store currency symbol
1105
+ return detailName.replace('<i class=sicon-sar></i>', salla.config.currency()?.symbol || 'ر.س');
1106
+ }
1107
+ isOptionDetailOut(detail) {
1108
+ if (detail.is_out || !detail.skus_availability || !this.selectedSkus?.length) {
1109
+ return detail.is_out;
1110
+ }
1111
+ const isDetailSelected = this.selectedOptions.filter(option => option.id === detail.id).length;
1112
+ //if the current options is the only selected option, so we are sure that it's not out, because there is no other options selected yet
1113
+ if (isDetailSelected && this.selectedOptions.length === 1) {
1114
+ return false;
1115
+ }
1116
+ //if current details has sku in the possible outSkus it's out for sure
1117
+ if (isDetailSelected) {
1118
+ //here we will get the possible outSkus for current selected options
1119
+ const outSelectableSkus = this.selectedSkus.filter(sku => this.outSkus.includes(sku));
1120
+ return Object.keys(detail.skus_availability).some(sku => outSelectableSkus.includes(Number(sku)));
1121
+ }
1122
+ return this.selectedOptions.some(option => option.is_out && option.option_id !== detail.option_id);
1123
+ }
1124
+ /**
1125
+ * Renders a single input element (radio or checkbox) for an option detail.
1126
+ * @param type - The type of input element ('radio' or 'checkbox').
1127
+ * @param detail - The detail object representing an option detail.
1128
+ * @param option - The parent option object containing the details.
1129
+ * @param isRequired - Indicates if the input is required based on the option's rules.
1130
+ * @param name - The name attribute for the input element.
1131
+ * @returns HTMLElement - A labeled input element.
1132
+ */
1133
+ renderInput(type, detail, option, isRequired, name, buttonStyle) {
1134
+ const id = this.generateUniqueKey(`${type}-${option.id}-${detail.id}`);
1135
+ const isDisabled = this.isOptionDetailOut(detail);
1136
+ return (h("label", { class: {
1137
+ "s-product-options-disabled": isDisabled,
1138
+ } }, h("input", { id: id, type: type, name: name, value: detail.id, disabled: isDisabled, required: isRequired, checked: detail.is_selected, onInvalid: (e) => this.invalidHandler(e, option), onChange: (e) => this.changedHandler(e, option) }), h("div", { class: { "s-product-options-grid-mode-span": buttonStyle, "s-product-options-disabled": isDisabled } }, this.getOptionDetailName(detail))));
1139
+ }
1140
+ /**
1141
+ * Renders a collection of input elements for all details of an option.
1142
+ * @param type - The type of input elements ('radio' or 'checkbox').
1143
+ * @param option - The parent option object containing the details.
1144
+ * @param isRequired - Indicates if the inputs are required based on the option's rules.
1145
+ * @returns HTMLElement[] - An array of labeled input elements.
1146
+ */
1147
+ renderOptionDetails(type, option, isRequired, buttonStyle = false) {
1148
+ const baseName = this.generateInputName(option.id);
1149
+ const name = type === 'radio' ? baseName : `${baseName}[]`;
1150
+ return option?.details.map((detail) => this.renderInput(type, detail, option, isRequired, name, buttonStyle));
1151
+ }
1152
+ /**
1153
+ * Renders a dropdown (select) element for a single-option selection.
1154
+ * @param option - The parent option object.
1155
+ * @returns HTMLElement - A select dropdown element with all option details.
1156
+ */
1157
+ renderSelect(option) {
1158
+ return (h("div", null, h("select", { id: this.generateInputId(option.id), name: this.generateInputName(option.id), required: !option.visibility_condition && option.required, class: "s-form-control", onInvalid: (e) => this.invalidHandler(e, option), onChange: (e) => this.changedHandler(e, option) }, h("option", { value: "" }, option.placeholder), option?.details.map((detail) => (h("option", { key: detail.id, value: detail.id, disabled: this.canDisabled && this.isOptionDetailOut(detail), selected: detail.is_selected }, this.getOptionDetailName(detail)))))));
1159
+ }
1160
+ /**
1161
+ * Renders a grid-based layout for option inputs (radio or checkbox).
1162
+ * @param type - The type of input elements ('radio' or 'checkbox').
1163
+ * @param option - The parent option object containing the details.
1164
+ * @param isRequired - Indicates if the inputs are required based on the option's rules.
1165
+ * @returns HTMLElement - A grid-based container with input elements.
1166
+ */
1167
+ renderButtonStyle(type, option, isRequired) {
1168
+ return (h("div", { class: "s-product-options-grid-mode" }, this.renderOptionDetails(type, option, isRequired, true)));
1169
+ }
1170
+ /**
1171
+ * Renders a single-option selection, either as a grid or dropdown, based on configuration.
1172
+ * @param option - The parent option object.
1173
+ * @returns HTMLElement - The rendered single-option element.
1174
+ */
1175
+ singleOption(option) {
1176
+ const buttonStyle = this.optionConfig?.['single-option']?.type === 'button';
1177
+ const isRequired = !option.visibility_condition && option.required;
1178
+ return buttonStyle
1179
+ ? this.renderButtonStyle('radio', option, isRequired)
1180
+ : this.renderSelect(option);
1181
+ }
1182
+ /**
1183
+ * Renders a multiple-option selection, either as a grid or list, based on configuration.
1184
+ * @param option - The parent option object.
1185
+ * @returns HTMLElement - The rendered multiple-option element.
1186
+ */
1187
+ multipleOptions(option) {
1188
+ const buttonStyle = this.optionConfig?.['multiple-option']?.type === 'button';
1189
+ const isRequired = option.required &&
1190
+ !option.details.some((detail) => detail.is_selected) &&
1191
+ !option.visibility_condition;
1192
+ return buttonStyle
1193
+ ? this.renderButtonStyle('checkbox', option, isRequired)
1194
+ : (h("div", { class: {
1195
+ 's-product-options-multiple-options-wrapper': true,
1196
+ required: option.required,
1197
+ } }, this.renderOptionDetails('checkbox', option, isRequired)));
1198
+ }
1199
+ /**
1200
+ * Renders a radio option selection (used for bundle products).
1201
+ * This is essentially the same as single option but with explicit radio handling.
1202
+ * @param option - The parent option object.
1203
+ * @returns HTMLElement - The rendered radio option element.
1204
+ */
1205
+ radioOption(option) {
1206
+ // Radio options behave the same as single options
1207
+ return this.singleOption(option);
1208
+ }
1209
+ //@ts-ignore
1210
+ colorOption(option) {
1211
+ return (h("fieldset", { class: "s-product-options-colors-wrapper" }, option?.details.map((detail) => (h("div", { class: "s-product-options-colors-item", key: detail.id }, h("input", { type: "radio", value: detail.id, required: !option.visibility_condition && option.required, checked: detail.is_selected, name: this.generateInputName(option.id), disabled: this.canDisabled && this.isOptionDetailOut(detail), id: this.generateUniqueKey(`color-${this.productId}-${option.id}-${detail.id}`), onInvalid: (e) => this.invalidHandler(e, option), onChange: (e) => this.changedHandler(e, option) }), h("label", { htmlFor: this.generateUniqueKey(`color-${this.productId}-${option.id}-${detail.id}`) }, h("span", { style: { backgroundColor: detail.color } }), h("div", { innerHTML: this.getOptionDetailName(detail, true, option.type) })))))));
1212
+ }
1213
+ //@ts-ignore
1214
+ thumbnailOption(option) {
1215
+ return h("div", { class: "s-product-options-thumbnails-wrapper" }, option.details.map((detail) => {
1216
+ return h("div", { key: detail.id }, h("input", { type: "radio", value: detail.id, "data-itemid": detail.id, required: !option.visibility_condition && option.required, checked: detail.is_selected, name: this.generateInputName(option.id), "data-img-id": detail.option_value, disabled: this.canDisabled && this.isOptionDetailOut(detail), id: this.generateUniqueKey(`option_${this.productId}-${option.id}_${detail.id}`), onInvalid: (e) => this.invalidHandler(e, option), onChange: (e) => this.changedHandler(e, option) }), h("label", { htmlFor: this.generateUniqueKey(`option_${this.productId}-${option.id}_${detail.id}`), "data-img-id": detail.option_value, class: "go-to-slide" }, h("img", { "data-src": detail.image, src: detail.image, title: detail.name, alt: detail.name }), h("span", { innerHTML: iconCheck, class: "s-product-options-thumbnails-icon" }), this.isOptionDetailOut(detail) ?
1217
+ [
1218
+ h("small", { key: detail.id, class: "s-product-options-thumbnails-stock-badge" }, this.outOfStockText),
1219
+ this.canDisabled ? h("div", { key: detail.id, class: "s-product-options-thumbnails-badge-overlay" }) : '',
1220
+ ]
1221
+ : ''), h("p", null, this.getOptionDetailName(detail, false), " "));
1222
+ }));
1223
+ }
1224
+ // Digital card options
1225
+ digitalCardValuesOption(option) {
1226
+ return h("div", { class: "s-product-options-digital-card-wrapper" }, this.availableDigitalCardValues.length > 0 ? this.availableDigitalCardValues.map((detail) => {
1227
+ const id = String(detail.id);
1228
+ return h("label", { htmlFor: this.generateUniqueKey(id.toString()), key: id, class: "s-product-options-digital-card-option" }, h("input", { type: "radio", "data-code-value": true, class: "s-form-control s-product-options-digital-card-input", value: detail.id, name: this.generateInputName(option.id), id: this.generateUniqueKey(id.toString()), required: !option.visibility_condition && option.required, onInvalid: (e) => this.invalidHandler(e, option), ...(!this.ignoreDefaultCardValue ? { defaultChecked: this.getSelectedDigitalCardOptions(option)?.id === detail.id } : {}) }), h("span", null, detail.name, " ", salla.config?.currency()?.symbol));
1229
+ })
1230
+ : h("div", { class: "s-product-options-digital-card-out-of-stock" }));
1231
+ }
1232
+ countryOption(option) {
1233
+ return h("div", { class: "s-product-options-digital-card-wrapper" }, option.details.map((detail) => {
1234
+ return h("label", { htmlFor: this.generateUniqueKey(detail.id.toString()), key: detail.id, class: { "s-product-options-digital-card-option": true, "s-product-options-digital-card-option-stock-out": detail.is_out } }, h("input", { id: this.generateUniqueKey(detail.id.toString()), type: "radio", class: "s-form-control s-product-options-digital-card-input", value: detail.id, name: this.generateInputName(option.id), disabled: detail.is_out, required: !option.visibility_condition && option.required, onInvalid: (e) => this.invalidHandler(e, option), onChange: e => this.changedHandler(e, option), onClick: () => { this.disableCardValue = false; }, ...(salla.url.is_page("cart") ? { defaultChecked: this.getSelectedDigitalCardOptions(option)?.id === detail.id } : {}) }), h("img", { loading: "lazy", alt: detail.code, height: 24, width: 24, class: "s-product-options-country-flag", src: `https://cdn.assets.salla.network/prod/admin/cp/assets/flags/1x1/${String(detail.code).toLocaleLowerCase()}.svg`, onError: e => {
1235
+ e.currentTarget.onerror = null;
1236
+ e.currentTarget.src =
1237
+ salla.url.cdn('images/globe.svg');
1238
+ } }), h("span", null, detail.name));
1239
+ }));
1240
+ }
1241
+ get host() { return getElement(this); }
1242
+ };
1243
+ SallaProductOptions.style = sallaProductOptionsCss;
1244
+
1245
+ var http = {
1246
+ request(method, url, data, successCb = null, errorCb = null) {
1247
+ return axios
1248
+ .request({url, data, method: method.toLowerCase(), responseType: 'json'})
1249
+ .then(successCb)
1250
+ .catch(errorCb);
1251
+ },
1252
+
1253
+ get(url, successCb = null, errorCb = null, data) {
1254
+ // return this.request('get', url, data, successCb, errorCb);
1255
+ return axios
1256
+ .get(url, {params: data})
1257
+ .then(successCb)
1258
+ .catch(errorCb);
1259
+ },
1260
+
1261
+ post(url, data, successCb = null, errorCb = null) {
1262
+ return this.request('post', url, data, successCb, errorCb);
1263
+ },
1264
+
1265
+ put(url, data, successCb = null, errorCb = null) {
1266
+ return this.request('put', url, data, successCb, errorCb);
1267
+ },
1268
+
1269
+ delete(url, data, successCb = null, errorCb = null) {
1270
+ return this.request('delete', url, data, successCb, errorCb);
1271
+ },
1272
+
1273
+ requestWithSupportAjax(url, payload, method = 'post') {
1274
+ return new Promise((resolve, reject) => {
1275
+ if (!window?.isLegacyTheme) {
1276
+ return this.request(method, url, payload, ({data}) => {
1277
+ return resolve(data);
1278
+ }, ({response}) => {
1279
+ return reject(response);
1280
+ })
1281
+ }
1282
+
1283
+ /**
1284
+ * @deprecated to support legacy themes
1285
+ */
1286
+ $.ajax({
1287
+ url: url,
1288
+ method: method.toUpperCase(),
1289
+ data: payload,
1290
+ async: false,
1291
+ success: function ({data}) {
1292
+ return resolve(data);
1293
+ },
1294
+ error: function ({response}) {
1295
+ return reject(response);
1296
+ }
1297
+ });
1298
+ })
1299
+ }
1300
+ };
1301
+
1302
+ var DetectOS = {
1303
+ options: [],
1304
+ header: [navigator.platform, navigator.userAgent, navigator.appVersion, navigator.vendor, window.opera],
1305
+ dataos: [
1306
+ {name: 'Windows Phone', value: 'Windows Phone', version: 'OS'},
1307
+ {name: 'Windows', value: 'Win', version: 'NT'},
1308
+ {name: 'iPhone', value: 'iPhone', version: 'OS'},
1309
+ {name: 'iPad', value: 'iPad', version: 'OS'},
1310
+ {name: 'Kindle', value: 'Silk', version: 'Silk'},
1311
+ {name: 'Android', value: 'Android', version: 'Android'},
1312
+ {name: 'PlayBook', value: 'PlayBook', version: 'OS'},
1313
+ {name: 'BlackBerry', value: 'BlackBerry', version: '/'},
1314
+ {name: 'Macintosh', value: 'Mac', version: 'OS X'},
1315
+ {name: 'Linux', value: 'Linux', version: 'rv'},
1316
+ {name: 'Palm', value: 'Palm', version: 'PalmOS'}
1317
+ ],
1318
+ databrowser: [
1319
+ {name: 'Chrome', value: 'Chrome', version: 'Chrome'},
1320
+ {name: 'Firefox', value: 'Firefox', version: 'Firefox'},
1321
+ {name: 'Safari', value: 'Safari', version: 'Version'},
1322
+ {name: 'Internet Explorer', value: 'MSIE', version: 'MSIE'},
1323
+ {name: 'Opera', value: 'Opera', version: 'Opera'},
1324
+ {name: 'BlackBerry', value: 'CLDC', version: 'CLDC'},
1325
+ {name: 'Mozilla', value: 'Mozilla', version: 'Mozilla'}
1326
+ ],
1327
+ init: function () {
1328
+ var agent = this.header.join(' '),
1329
+ os = this.matchItem(agent, this.dataos),
1330
+ browser = this.matchItem(agent, this.databrowser);
1331
+
1332
+ return {os: os, browser: browser};
1333
+ },
1334
+ matchItem: function (string, data) {
1335
+ var i = 0,
1336
+ j = 0,
1337
+ regex,
1338
+ regexv,
1339
+ match,
1340
+ matches,
1341
+ version;
1342
+
1343
+ for (i = 0; i < data.length; i += 1) {
1344
+ regex = new RegExp(data[i].value, 'i');
1345
+ match = regex.test(string);
1346
+ if (match) {
1347
+ regexv = new RegExp(data[i].version + '[- /:;]([\\d._]+)', 'i');
1348
+ matches = string.match(regexv);
1349
+ version = '';
1350
+ if (matches) {
1351
+ if (matches[1]) {
1352
+ matches = matches[1];
1353
+ }
1354
+ }
1355
+ if (matches) {
1356
+ matches = matches.split(/[._]+/);
1357
+ for (j = 0; j < matches.length; j += 1) {
1358
+ if (j === 0) {
1359
+ version += matches[j] + '.';
1360
+ } else {
1361
+ version += matches[j];
1362
+ }
1363
+ }
1364
+ } else {
1365
+ version = '0';
1366
+ }
1367
+ return {
1368
+ name: data[i].name,
1369
+ version: parseFloat(version)
1370
+ };
1371
+ }
1372
+ }
1373
+ return {name: 'unknown', version: 0};
1374
+ }
1375
+ };
1376
+
1377
+ /**
1378
+ * @typedef {Object} ApplePayPaymentContact
1379
+ * @property {string} phoneNumber
1380
+ * @property {string} emailAddress
1381
+ * @property {string} givenName
1382
+ * @property {string} familyName
1383
+ * @property {string} [phoneticGivenName]
1384
+ * @property {string} [phoneticFamilyName]
1385
+ * @property {string[]} addressLines
1386
+ * @property {string} [subLocality]
1387
+ * @property {string} locality
1388
+ * @property {string} postalCode
1389
+ * @property {string} [subAdministrativeArea]
1390
+ * @property {string} administrativeArea
1391
+ * @property {string} country
1392
+ * @property {string} countryCode
1393
+ */
1394
+
1395
+
1396
+ /**
1397
+ *
1398
+ * @param {SallaApplePay} SallaApplePay
1399
+ * @param {boolean} isAuthorized
1400
+ * @param {ApplePayPaymentContact} shippingContact
1401
+ *
1402
+ */
1403
+ async function mutateShippingContact(SallaApplePay, shippingContact, isAuthorized = false) {
1404
+ salla.logger.log('🍏 Pay: mutateShippingContact called', shippingContact, isAuthorized);
1405
+
1406
+ if (!SallaApplePay.detail.requiredShippingContactFields || SallaApplePay.detail.requiredShippingContactFields.length == 0) {
1407
+ return;
1408
+ }
1409
+
1410
+ if (isAuthorized) {
1411
+ if (isGuestCheckout()) {
1412
+
1413
+ if (
1414
+ !shippingContact.emailAddress ||
1415
+ !shippingContact.givenName ||
1416
+ !shippingContact.familyName ||
1417
+ !shippingContact.phoneNumber
1418
+ ) {
1419
+
1420
+ salla.logger.warn('🍏 Pay: Guest contact fields are required', shippingContact);
1421
+
1422
+ const errors = [];
1423
+ if (!shippingContact.emailAddress) {
1424
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'emailAddress', 'Email address is required'));
1425
+ }
1426
+
1427
+ if (!shippingContact.phoneNumber) {
1428
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'phoneNumber', 'Phone number is required'));
1429
+ }
1430
+
1431
+ if (!shippingContact.givenName || !shippingContact.familyName) {
1432
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'name', 'Name is required'));
1433
+ }
1434
+
1435
+ SallaApplePay.session.completePayment({
1436
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_CONTACT,
1437
+ errors: errors
1438
+ });
1439
+
1440
+ return;
1441
+ }
1442
+
1443
+ await updateGuestContact(SallaApplePay, shippingContact);
1444
+
1445
+ }
1446
+
1447
+ // if authorized and not guest checkout, do nothing address already added
1448
+ return;
1449
+ }
1450
+
1451
+ if (!SallaApplePay.detail.requiredShippingContactFields.includes('postalAddress')) {
1452
+ return;
1453
+ }
1454
+
1455
+ return http.post(
1456
+ SallaApplePay.detail.shippingContactSelected.url.replace('{id}', SallaApplePay.id),
1457
+ {
1458
+ 'country': shippingContact.country,
1459
+ 'city': shippingContact.locality,
1460
+ 'local': shippingContact.subLocality || shippingContact.administrativeArea || shippingContact.locality,
1461
+ 'description': shippingContact.subAdministrativeArea,
1462
+ 'street': shippingContact.addressLines?.join(", ") || shippingContact.administrativeArea,
1463
+ 'country_code': shippingContact.countryCode,
1464
+ 'postal_code': shippingContact.postalCode,
1465
+ },
1466
+ async ({ data }) => {
1467
+ if (typeof SallaApplePay.detail.shippingContactSelected.onSuccess === 'function') {
1468
+ SallaApplePay.detail.shippingContactSelected.onSuccess(data);
1469
+ }
1470
+
1471
+ SallaApplePay.address_id = data.data.address_id;
1472
+ SallaApplePay.shipping_methods = data.data.shipping_methods;
1473
+
1474
+ if (!SallaApplePay.shipping_methods || (SallaApplePay.shipping_methods && !SallaApplePay.shipping_methods.length)) {
1475
+ salla.logger.warn('🍏 Pay: We dont found any supported methods', data);
1476
+
1477
+ SallaApplePay.session.completeShippingContactSelection({
1478
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
1479
+ errors: [
1480
+ new window.ApplePayError('addressUnserviceable')
1481
+ ]
1482
+ });
1483
+
1484
+ return
1485
+ }
1486
+
1487
+ try {
1488
+ await SallaApplePay.selectApplePayShippingMethod(SallaApplePay.shipping_methods[0]);
1489
+ } catch (error) {
1490
+ salla.logger.warn('Failed set the shipping details to api', error);
1491
+
1492
+ SallaApplePay.session.completeShippingContactSelection({
1493
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
1494
+ errors: [
1495
+ new window.ApplePayError('addressUnserviceable')
1496
+ ]
1497
+ });
1498
+
1499
+ return;
1500
+ }
1501
+
1502
+ try {
1503
+ await SallaApplePay.recalculateTotal();
1504
+ } catch (error) {
1505
+ salla.logger.warn('🍏 Pay: Failed recalculate total', error);
1506
+
1507
+ SallaApplePay.session.completeShippingContactSelection({
1508
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
1509
+ errors: [
1510
+ new window.ApplePayError('addressUnserviceable')
1511
+ ]
1512
+ });
1513
+
1514
+ return;
1515
+ }
1516
+
1517
+ const updatedShippingContactSelection = {
1518
+ newTotal: SallaApplePay.prepareTotal(),
1519
+ newLineItems: SallaApplePay.prepareLineItems(),
1520
+ newShippingMethods: SallaApplePay.mappingShippingMethods(SallaApplePay.shipping_methods)
1521
+ };
1522
+
1523
+ salla.logger.log('🍏 Pay: completeShippingContactSelection', updatedShippingContactSelection);
1524
+
1525
+ SallaApplePay.session.completeShippingContactSelection(updatedShippingContactSelection);
1526
+ },
1527
+ ({ response }) => {
1528
+ salla.logger.warn('🍏 Pay: Failed add address via api', response);
1529
+
1530
+ if (typeof SallaApplePay.detail.shippingContactSelected.onFailed === 'function') {
1531
+ SallaApplePay.detail.shippingContactSelected.onFailed(response);
1532
+ }
1533
+
1534
+ // parse 422 errors
1535
+ let fields = response?.data?.error?.fields;
1536
+
1537
+ let errors = getApplePayErrors({
1538
+ countryCode: fields?.country_code && fields.country_code.length > 0 ? fields.country_code[0] : null,
1539
+ locality: fields?.city && fields.city.length > 0 ? fields.city[0] : null,
1540
+ country: fields?.country && fields.country.length > 0 ? fields.country[0] : null,
1541
+ });
1542
+
1543
+ if (errors.length === 0 && response?.data?.error?.message) {
1544
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'locality', response?.data?.error?.message));
1545
+ }
1546
+
1547
+ SallaApplePay.session.completeShippingContactSelection({
1548
+ newTotal: SallaApplePay.prepareTotal(),
1549
+ newLineItems: SallaApplePay.prepareLineItems(),
1550
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
1551
+ errors: errors
1552
+ });
1553
+ }
1554
+ );
1555
+ }
1556
+
1557
+ function isGuestCheckout() {
1558
+ return salla.config.isGuest() && salla.config.get('store.features').includes('guest-checkout');
1559
+ }
1560
+
1561
+ /**
1562
+ * Update guest contact
1563
+ *
1564
+ * @param {SallaApplePay} SallaApplePay
1565
+ * @param {ApplePayPaymentContact} shippingContact
1566
+ *
1567
+ */
1568
+ async function updateGuestContact(SallaApplePay, shippingContact) {
1569
+ salla.logger.log('🍏 Pay: Updating guest contact', shippingContact);
1570
+
1571
+ return new Promise((resolve, reject) => {
1572
+ http.post(
1573
+ SallaApplePay.detail.guestContactSelected.url.replace('{id}', SallaApplePay.id),
1574
+ {
1575
+ 'email': shippingContact.emailAddress || null,
1576
+ 'first_name': shippingContact.givenName || null,
1577
+ 'last_name': shippingContact.familyName || null,
1578
+ 'phone_number': shippingContact.phoneNumber || null,
1579
+ 'country_code': shippingContact.countryCode || null,
1580
+ },
1581
+ async ({ data }) => {
1582
+ if (typeof SallaApplePay.detail.guestContactSelected?.onSuccess === 'function') {
1583
+ SallaApplePay.detail.guestContactSelected.onSuccess(data);
1584
+ }
1585
+ resolve(data);
1586
+ },
1587
+ ({ response }) => {
1588
+ salla.logger.warn('🍏 Pay: Failed to update guest contact via api', response);
1589
+
1590
+ if (typeof SallaApplePay.detail.guestContactSelected?.onFailed === 'function') {
1591
+ SallaApplePay.detail.guestContactSelected.onFailed(response);
1592
+ }
1593
+
1594
+ // Reject the promise so it can be caught in onPaymentAuthorized
1595
+ reject({ response });
1596
+ }
1597
+ );
1598
+ });
1599
+ }
1600
+
1601
+ function getApplePayErrors(fields) {
1602
+ return Object.entries(fields)
1603
+ .filter(([field, messages]) => messages && messages.length > 0)
1604
+ .map(([field, messages]) => new window.ApplePayError('shippingContactInvalid', field, messages[0]));
1605
+ }
1606
+
1607
+ window.Salla = window.Salla || {};
1608
+ window.Salla.Payments = window.Salla.Payments || {};
1609
+
1610
+ /**
1611
+ * Full Example
1612
+ *
1613
+ * Salla.event.createAndDispatch('payments::apple-pay.start-transaction', {
1614
+ * amount: 1000,
1615
+ * validateMerchant: {
1616
+ * url: '{{ route('cp.marketplace.cart.pay', ['cart' => $cart]) }}',
1617
+ * // onFailed: (response) => {
1618
+ * // laravel.ajax.errorHandler(response);
1619
+ * // this.onCancel({}, response.data.error.message);
1620
+ * // },
1621
+ * // onSuccess: (response) => {
1622
+ * // laravel.ajax.successHandler(response);
1623
+ * // }
1624
+ * },
1625
+ * authorized: {
1626
+ * url: '{{ route('cp.marketplace.cart.confirm', ['cart' => $cart]) }}',
1627
+ * // onFailed: (response) => {
1628
+ * // laravel.ajax.errorHandler(response);
1629
+ * // this.onCancel({}, response.data.error.message);
1630
+ * // },
1631
+ * // onSuccess: (response) => {
1632
+ * // // nothing
1633
+ * // }
1634
+ * },
1635
+ * // onError: function (message) {
1636
+ * // laravel.alert(message);
1637
+ * // }
1638
+ * });
1639
+ */
1640
+ window.SallaApplePay = {
1641
+ session: null,
1642
+ detail: null,
1643
+ address_id: null,
1644
+ shipping_methods: [],
1645
+ total: undefined,
1646
+ request: undefined,
1647
+ id: undefined,
1648
+ countryCode: null,
1649
+ totals: [],
1650
+ shippingCompany: null,
1651
+ init: function () {
1652
+ document.removeEventListener('payments::apple-pay.start-transaction', SallaApplePay.startSession);
1653
+ Salla.event.addEventListener('payments::apple-pay.start-transaction', SallaApplePay.startSession);
1654
+ },
1655
+
1656
+ initDefault: function () {
1657
+ if (!SallaApplePay.detail.onError) {
1658
+ SallaApplePay.detail.onError = function (message) {
1659
+ salla.notify.error(message);
1660
+ };
1661
+ }
1662
+
1663
+ if (!SallaApplePay.detail.authorized.onFailed) {
1664
+ SallaApplePay.detail.authorized.onFailed = (response) => {
1665
+ salla.logger.log(JSON.stringify(response));
1666
+ salla.api.handleErrorResponse(response);
1667
+ SallaApplePay.onCancel({}, response.data.error.message);
1668
+ };
1669
+ }
1670
+
1671
+ if (!SallaApplePay.detail.validateMerchant.onFailed) {
1672
+ SallaApplePay.detail.validateMerchant.onFailed = (response) => {
1673
+ salla.logger.log(JSON.stringify(response));
1674
+ salla.api.handleErrorResponse(response);
1675
+ SallaApplePay.onCancel({}, response.data.error.message);
1676
+ };
1677
+ }
1678
+
1679
+ if (!SallaApplePay.detail.authorized.onSuccess) {
1680
+ SallaApplePay.detail.authorized.onSuccess = (response) => {
1681
+ salla.logger.log(JSON.stringify(response));
1682
+ salla.api.handleAfterResponseActions(response);
1683
+ };
1684
+ }
1685
+ },
1686
+
1687
+ prepareLineItems: function () {
1688
+ if (!SallaApplePay.detail?.items?.length) {
1689
+ SallaApplePay.detail.items = [
1690
+ {
1691
+ label: salla.lang.get('pages.cart.items_total'),
1692
+ amount: parseFloat(SallaApplePay.detail.amount).toString()
1693
+ }
1694
+ ];
1695
+ }
1696
+
1697
+ return SallaApplePay.detail.items;
1698
+ },
1699
+
1700
+ prepareTotal: function () {
1701
+ return {
1702
+ // apple ask to use business name
1703
+ label: window.location.hostname || 'Salla',
1704
+ //label: salla.lang.get('pages.cart.final_total'),
1705
+ amount: parseFloat(SallaApplePay.detail.amount).toString()
1706
+ }
1707
+ },
1708
+
1709
+ isPhysical() {
1710
+ return SallaApplePay.detail?.requiredShippingContactFields?.includes('postalAddress');
1711
+ },
1712
+
1713
+ startSession: async function (event) {
1714
+
1715
+ SallaApplePay.detail = event.detail || event;
1716
+
1717
+ salla.log('🍏 Pay: payments::apple-pay.start-transaction', SallaApplePay.detail);
1718
+
1719
+ SallaApplePay.initDefault();
1720
+
1721
+ let version = SallaApplePay.getApplePaySessionVersion();
1722
+ let supportedNetworks = SallaApplePay.detail.supportedNetworks || ['masterCard', 'visa'];
1723
+
1724
+ if (version === 5) {
1725
+ supportedNetworks.push('mada');
1726
+ }
1727
+
1728
+ SallaApplePay.request = {
1729
+ countryCode: SallaApplePay.detail.countryCode || 'SA',
1730
+ supportsCouponCode: true,
1731
+ couponCode: '',
1732
+ currencyCode: SallaApplePay.detail.currency || 'SAR',
1733
+ requiredShippingContactFields: SallaApplePay.detail.requiredShippingContactFields ? SallaApplePay.detail.requiredShippingContactFields : [],
1734
+ merchantCapabilities: ['supports3DS'],
1735
+ supportedNetworks: supportedNetworks,
1736
+ supportedCountries: SallaApplePay.detail.supportedCountries || ['SA'],
1737
+ total: SallaApplePay.prepareTotal(),
1738
+ shippingContact: SallaApplePay.detail.shippingContact ? SallaApplePay.detail.shippingContact : {},
1739
+ shippingMethods: SallaApplePay.detail.shippingMethods && SallaApplePay.detail.shippingMethods.length ? SallaApplePay.mappingShippingMethods(event.detail.shippingMethods) : [],
1740
+ lineItems: SallaApplePay.prepareLineItems()
1741
+ };
1742
+
1743
+ salla.log('🍏 Pay: init ', SallaApplePay.request);
1744
+
1745
+ // https://developer.apple.com/documentation/apple_pay_on_the_web/applepaypaymentrequest
1746
+ SallaApplePay.session = new ApplePaySession(version, SallaApplePay.request);
1747
+
1748
+ SallaApplePay.session.onshippingcontactselected = SallaApplePay.onShippingContactSelected;
1749
+ SallaApplePay.session.onshippingmethodselected = SallaApplePay.onShippingMethodSelected;
1750
+ SallaApplePay.session.onvalidatemerchant = SallaApplePay.onValidateMerchant;
1751
+ SallaApplePay.session.onpaymentauthorized = SallaApplePay.onPaymentAuthorized;
1752
+ SallaApplePay.session.oncancel = SallaApplePay.onCancel;
1753
+ SallaApplePay.session.oncouponcodechanged = SallaApplePay.onCouponCodeChanged;
1754
+ SallaApplePay.session.onpaymentmethodselected = SallaApplePay.onPaymentMethodSelected;
1755
+
1756
+ SallaApplePay.session.begin();
1757
+ },
1758
+ onPaymentMethodSelected: async (event) => {
1759
+ salla.logger.log('🍏 Pay: onPaymentMethodSelected', event);
1760
+
1761
+ // perform recalculate here only if digital product
1762
+ // if physical recalculate performed with shipping company
1763
+ if (!SallaApplePay.isPhysical()) {
1764
+ try {
1765
+ await SallaApplePay.recalculateTotal();
1766
+
1767
+ const updatedPaymentDetails = {
1768
+ newTotal: SallaApplePay.prepareTotal(),
1769
+ newLineItems: SallaApplePay.prepareLineItems()
1770
+ };
1771
+
1772
+ salla.logger.log('🍏 Pay: completePaymentMethodSelection', updatedPaymentDetails);
1773
+
1774
+ SallaApplePay.session.completePaymentMethodSelection(updatedPaymentDetails);
1775
+
1776
+ } catch (error) {
1777
+ salla.logger.warn('🍏 Pay: Failed recalculate total', error);
1778
+
1779
+ SallaApplePay.session.completePaymentMethodSelection({
1780
+ newTotal: SallaApplePay.prepareTotal(),
1781
+ newLineItems: SallaApplePay.prepareLineItems(),
1782
+ status: SallaApplePay.session.STATUS_FAILURE,
1783
+ errors: [new window.ApplePayError("unknown", undefined, error?.response?.data?.error?.message || error?.response?.data?.error?.code || 'Failed to recalculate total')]
1784
+ });
1785
+ }
1786
+ return;
1787
+ }
1788
+
1789
+ salla.logger.log('🍏 Pay: completePaymentMethodSelection', {
1790
+ newTotal: SallaApplePay.prepareTotal(),
1791
+ newLineItems: SallaApplePay.prepareLineItems(),
1792
+ });
1793
+
1794
+ SallaApplePay.session.completePaymentMethodSelection({
1795
+ newTotal: SallaApplePay.prepareTotal(),
1796
+ newLineItems: SallaApplePay.prepareLineItems(),
1797
+ });
1798
+ },
1799
+
1800
+ onCouponCodeChanged(event) {
1801
+ Salla.event.dispatch('payments::apple-pay.coupon.change', event);
1802
+
1803
+ return http.post(SallaApplePay.detail.onCouponCodeChanged.url.replace('{id}', SallaApplePay.id), {
1804
+ 'coupon': event.couponCode,
1805
+ 'payment_method': 'apple_pay',
1806
+ }, async ({ data }) => {
1807
+ if (typeof SallaApplePay.detail.onCouponCodeChanged.onSuccess === 'function') {
1808
+ SallaApplePay.detail.onCouponCodeChanged.onSuccess(data);
1809
+ }
1810
+
1811
+ salla.log('🍏 Pay: Coupon applied success');
1812
+
1813
+ await SallaApplePay.recalculateTotal();
1814
+
1815
+ SallaApplePay.session.completeCouponCodeChange({
1816
+ newTotal: SallaApplePay.prepareTotal(),
1817
+ newLineItems: SallaApplePay.prepareLineItems()
1818
+ });
1819
+ }, async (error) => {
1820
+ let response = error?.response;
1821
+
1822
+ Salla.event.dispatch('payments::apple-pay.coupon.failed', response);
1823
+
1824
+ // SallaApplePay.abortSession();
1825
+ if (typeof SallaApplePay.detail.onCouponCodeChanged.onFailed === 'function') {
1826
+ SallaApplePay.detail.onCouponCodeChanged.onFailed(response);
1827
+ }
1828
+
1829
+ await SallaApplePay.recalculateTotal();
1830
+
1831
+ SallaApplePay.session.completeCouponCodeChange({
1832
+ newTotal: SallaApplePay.prepareTotal(),
1833
+ newLineItems: SallaApplePay.prepareLineItems(),
1834
+ errors: [new window.ApplePayError('couponCodeInvalid')]
1835
+ });
1836
+ });
1837
+ },
1838
+
1839
+ onCancel: (event = {}, message = null) => {
1840
+ SallaApplePay.detail.onError(message || salla.lang.get('pages.checkout.payment_failed'));
1841
+ Salla.event.createAndDispatch('payments::apple-pay.canceled', event);
1842
+ },
1843
+
1844
+ /**
1845
+ * Confirm payment after authorization.
1846
+ *
1847
+ * @param event
1848
+ */
1849
+ onPaymentAuthorized: async (event) => {
1850
+ salla.logger.log('🍏 Pay: onPaymentAuthorized', event.payment);
1851
+
1852
+ // update guest details
1853
+ try {
1854
+ await mutateShippingContact(SallaApplePay, event.payment.shippingContact, true);
1855
+ } catch (error) {
1856
+ salla.logger.error('🍏 Pay: Failed to update guest contact details', error);
1857
+
1858
+ const response = error?.response || error;
1859
+
1860
+ // Parse backend errors for shipping contact fields
1861
+ const fields = response?.data?.error?.fields || {};
1862
+ const errors = [];
1863
+
1864
+ // Map backend field errors to Apple Pay contact field errors
1865
+ if (fields?.email && fields.email.length > 0) {
1866
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'emailAddress', fields.email[0]));
1867
+ }
1868
+
1869
+ if (fields?.phone && fields.phone.length > 0) {
1870
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'phoneNumber', fields.phone[0]));
1871
+ }
1872
+
1873
+ if (fields?.first_name && fields.first_name.length > 0) {
1874
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'name', fields.first_name[0]));
1875
+ } else if (fields?.last_name && fields.last_name.length > 0) {
1876
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'name', fields.last_name[0]));
1877
+ }
1878
+
1879
+ // If no specific field errors, use general error message
1880
+ if (errors.length === 0) {
1881
+ const errorMessage = response?.data?.error?.message || response?.data?.error?.code || 'Invalid shipping contact details';
1882
+ errors.push(new window.ApplePayError('shippingContactInvalid', 'name', errorMessage));
1883
+ }
1884
+
1885
+ Salla.event.dispatch('payments::apple-pay.authorized.failed', response);
1886
+
1887
+ if (typeof SallaApplePay.detail.authorized.onFailed === 'function') {
1888
+ SallaApplePay.detail.authorized.onFailed(response);
1889
+ }
1890
+
1891
+ // Complete shipping contact selection with invalid contact status
1892
+ SallaApplePay.session.completePayment({
1893
+ status: ApplePaySession.STATUS_INVALID_SHIPPING_CONTACT,
1894
+ errors: errors
1895
+ });
1896
+
1897
+ return;
1898
+ }
1899
+
1900
+ Salla.event.dispatch('payments::apple-pay.authorized.init', event);
1901
+ http.post(SallaApplePay.detail.authorized.url.replace('{id}', SallaApplePay.id), {
1902
+ payment_method: 'apple_pay',
1903
+ applepay_token: JSON.stringify(event.payment)
1904
+ }, ({ data }) => {
1905
+ Salla.event.dispatch('payments::apple-pay.authorized.success', data);
1906
+
1907
+ if (typeof SallaApplePay.detail.authorized.onSuccess === 'function') {
1908
+ SallaApplePay.detail.authorized.onSuccess(data);
1909
+ }
1910
+
1911
+ SallaApplePay.session.completePayment(ApplePaySession.STATUS_SUCCESS);
1912
+ }, (error) => {
1913
+
1914
+ let response = error?.response;
1915
+
1916
+ Salla.event.dispatch('payments::apple-pay.authorized.failed', response);
1917
+
1918
+ if (typeof SallaApplePay.detail.authorized.onFailed === 'function') {
1919
+ SallaApplePay.detail.authorized.onFailed(response);
1920
+ }
1921
+
1922
+ SallaApplePay.session.completePayment({
1923
+ status: ApplePaySession.STATUS_FAILURE,
1924
+ errors: [new window.ApplePayError("unknown", undefined, response?.data?.error?.message || response?.data?.error?.code || 'Failed to parse authorized response')]
1925
+ });
1926
+ });
1927
+ },
1928
+
1929
+ /**
1930
+ * Validate Submit.
1931
+ *
1932
+ * @param event
1933
+ */
1934
+ onValidateMerchant: async (event) => {
1935
+ try {
1936
+ // Dispatch event to initialize Apple Pay merchant validation
1937
+ Salla.event.dispatch('payments::apple-pay.validate-merchant.init', event);
1938
+
1939
+ // Post request to validate merchant
1940
+ const { data } = await http.post(SallaApplePay.detail.validateMerchant.url.replace('{id}', SallaApplePay.id), {
1941
+ validation_url: event.validationURL
1942
+ });
1943
+
1944
+ // Dispatch event on successful merchant validation
1945
+ Salla.event.dispatch('payments::apple-pay.validate-merchant.success', data);
1946
+
1947
+ // Define a function to handle the completion of merchant validation
1948
+ const completeMerchantValidation = (responseData) => {
1949
+ SallaApplePay.session.completeMerchantValidation(responseData);
1950
+ };
1951
+
1952
+ // Check if onSuccess function is defined in SallaApplePay.detail.validateMerchant
1953
+ if (typeof SallaApplePay.detail.validateMerchant.onSuccess === 'function') {
1954
+ // Call onSuccess function and handle response
1955
+ const response = await SallaApplePay.detail.validateMerchant.onSuccess(data);
1956
+ if (response?.redirect) {
1957
+ // Handle redirect if present
1958
+ window.location = response.redirect;
1959
+ return SallaApplePay.abortValidateMerchant(response);
1960
+ }
1961
+ }
1962
+ completeMerchantValidation(data.data);
1963
+ } catch (error) {
1964
+ // Handle errors
1965
+ console.error(error);
1966
+ SallaApplePay.abortValidateMerchant(error?.response);
1967
+ }
1968
+ },
1969
+
1970
+ abortValidateMerchant: (response = null) => {
1971
+
1972
+ SallaApplePay.abortSession();
1973
+ Salla.event.dispatch('payments::apple-pay.validate-merchant.failed', response);
1974
+
1975
+ if (typeof SallaApplePay.detail.validateMerchant.onFailed === 'function') {
1976
+ SallaApplePay.detail.validateMerchant.onFailed(response);
1977
+ }
1978
+ },
1979
+
1980
+ /**
1981
+ * Select Shipping Contact
1982
+ *
1983
+ * @param event
1984
+ */
1985
+ onShippingContactSelected: async (event) => {
1986
+ salla.logger.log('🍏 Pay: onShippingContactSelected', event.shippingContact);
1987
+
1988
+ // create address for shipping calculation
1989
+ await mutateShippingContact(SallaApplePay, event.shippingContact);
1990
+ },
1991
+
1992
+ /**
1993
+ * Select Shipping Method
1994
+ *
1995
+ * @param event
1996
+ *
1997
+ */
1998
+ onShippingMethodSelected: async (event) => {
1999
+
2000
+ let shipping_ids = event.shippingMethod.identifier.split(',');
2001
+ let shippingMethod = {
2002
+ ship_id: shipping_ids[0],
2003
+ private_ship_id: typeof shipping_ids[1] === 'undefined' ? null : shipping_ids[1],
2004
+ type: typeof shipping_ids[2] === 'undefined' ? null : shipping_ids[2],
2005
+ route_id: typeof shipping_ids[3] === 'undefined' ? null : shipping_ids[3],
2006
+ };
2007
+
2008
+ salla.logger.log('🍏 Pay: onShippingMethodSelected', {
2009
+ event,
2010
+ previous: SallaApplePay.shippingCompany,
2011
+ current: shippingMethod,
2012
+ });
2013
+
2014
+ if (SallaApplePay.shouldUpdateShippingCompany(shippingMethod)) {
2015
+ try {
2016
+
2017
+ await SallaApplePay.selectApplePayShippingMethod(shippingMethod);
2018
+
2019
+ await SallaApplePay.recalculateTotal();
2020
+
2021
+ } catch (error) {
2022
+ salla.logger.warn('🍏 Pay: Failed set the shipping details to api', error);
2023
+
2024
+ // todo :: find a better handling for error without abort session
2025
+ SallaApplePay.session.completeShippingMethodSelection({
2026
+ newTotal: SallaApplePay.prepareTotal(),
2027
+ newLineItems: SallaApplePay.prepareLineItems(),
2028
+ status: SallaApplePay.session.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
2029
+ errors: [
2030
+ new window.ApplePayError('addressUnserviceable')
2031
+ ]
2032
+ });
2033
+
2034
+ return;
2035
+ }
2036
+ }
2037
+
2038
+ salla.logger.log('🍏 Pay: completeShippingMethodSelection', {
2039
+ newTotal: SallaApplePay.prepareTotal(),
2040
+ newLineItems: SallaApplePay.prepareLineItems(),
2041
+ });
2042
+
2043
+ SallaApplePay.session.completeShippingMethodSelection({
2044
+ newTotal: SallaApplePay.prepareTotal(),
2045
+ newLineItems: SallaApplePay.prepareLineItems(),
2046
+ });
2047
+ },
2048
+
2049
+
2050
+ abortSession: () => {
2051
+ if (SallaApplePay.session) {
2052
+ SallaApplePay.session.abort();
2053
+ }
2054
+ },
2055
+
2056
+ shouldUpdateShippingCompany(shippingCompany) {
2057
+ return SallaApplePay.shippingCompany?.ship_id != shippingCompany?.ship_id || SallaApplePay.shippingCompany?.private_ship_id != shippingCompany?.private_ship_id
2058
+ },
2059
+
2060
+ getApplePaySessionVersion: () => {
2061
+ const userAgent = navigator.userAgent || navigator.vendor || window.opera;
2062
+
2063
+ if (userAgent === 'sallapp') {
2064
+ return 5;
2065
+ }
2066
+
2067
+ // can't handle custom user agent like sallapp
2068
+ let detection = DetectOS.init();
2069
+ let v = parseFloat(detection.os.version);
2070
+
2071
+ if (detection.os.name === 'Macintosh') {
2072
+ if (v < 10.142) {
2073
+ return 1;
2074
+ }
2075
+ } else {
2076
+ if (v < 12.11) {
2077
+ return 1;
2078
+ }
2079
+ }
2080
+
2081
+ return 5;
2082
+ },
2083
+
2084
+ recalculateTotal: () => {
2085
+ salla.logger.log('🍏 Pay: recalculate total');
2086
+
2087
+ return http.get(SallaApplePay.detail.recalculateTotal.url.replace('{id}', SallaApplePay.id), ({ data }) => {
2088
+ salla.logger.log('🍏 Pay: recalculate total success', data);
2089
+ let cart = data.data.initial_data?.cart || data.data.cart;
2090
+ let payments = data.data.initial_data?.payments || data.data.payments;
2091
+
2092
+ salla.logger.log('🍏 Pay: recalculate total success', {
2093
+ cart,
2094
+ payments
2095
+ });
2096
+
2097
+ // todo :: enhance response from backend
2098
+ SallaApplePay.detail.amount = payments?.gateways?.applePay?.supportedMultiCurrency ? cart.total_in_customer_currency : cart.total;
2099
+ SallaApplePay.detail.items = (cart.totals || cart.items).map((item) => {
2100
+ return {
2101
+ label: item.title,
2102
+ amount: (item.amount === 'مجاني' || item.amount === 'Free') ? 0 : item.amount.toString().replace('+', ''),
2103
+ };
2104
+ });
2105
+
2106
+ // lets remove last element (final total)
2107
+ SallaApplePay.detail.items.pop();
2108
+ SallaApplePay.totals = SallaApplePay.detail.items;
2109
+
2110
+ }, (error) => {
2111
+ salla.logger.warn('🍏 Pay: recalculate total failed', error);
2112
+
2113
+ // general error
2114
+ return error?.response?.data?.message;
2115
+ });
2116
+ },
2117
+
2118
+
2119
+ selectApplePayShippingMethod: (shippingMethod) => {
2120
+ salla.logger.log('🍏 Pay: select shipping method ', shippingMethod);
2121
+ SallaApplePay.shippingCompany = shippingMethod;
2122
+
2123
+ const payload = {
2124
+ address_id: SallaApplePay.address_id,
2125
+ company_id: shippingMethod.ship_id,
2126
+ private_company_id: shippingMethod.private_ship_id,
2127
+ type: shippingMethod.type || undefined,
2128
+ route_id: shippingMethod.route_id || undefined,
2129
+ payment_method: 'apple_pay'
2130
+ };
2131
+ return http.post(SallaApplePay.detail.shippingMethodSelected.url.replace('{id}', SallaApplePay.id), payload, ({ data }) => {
2132
+ if (typeof SallaApplePay.detail.shippingMethodSelected.onSuccess === 'function') {
2133
+ SallaApplePay.detail.shippingMethodSelected.onSuccess(data);
2134
+ }
2135
+
2136
+ // we don't have any data in this request, lets resolve the promise
2137
+ return true;
2138
+ }, (error) => {
2139
+ salla.logger.warn('🍏 Pay: Set shipping method failed', error);
2140
+
2141
+ if (typeof SallaApplePay.detail.shippingMethodSelected.onFailed === 'function') {
2142
+ SallaApplePay.detail.shippingMethodSelected.onFailed(error);
2143
+ }
2144
+
2145
+ // parse 422 errors
2146
+ let response = error?.response?.data?.error;
2147
+
2148
+ // address id is not valid
2149
+ if (response?.data?.fields?.address_id) {
2150
+ return response?.data?.fields?.address_id[0];
2151
+ }
2152
+
2153
+ // general error
2154
+ return response?.data?.message;
2155
+ });
2156
+ },
2157
+ mappingShippingMethods: methods => methods.map(method => ({
2158
+ 'label': method.shipping_title,
2159
+ 'amount': method.enable_free_shipping ? 0 : method.ship_cost,
2160
+ 'detail': '',
2161
+ 'identifier': method.ship_id.toString() + (method.private_ship_id ? ',' + method.private_ship_id.toString() : '') + (method.type ? ',' + method.type : '') + (method.route_id ? ',' + method.route_id : '')
2162
+ }))
2163
+ };
2164
+
2165
+ //applePay doesn't allow iframes
2166
+ // if (window.ApplePaySession && window.self === window.top && ApplePaySession.canMakePayments()) {
2167
+ if (window.ApplePaySession?.canMakePayments()) {
2168
+ SallaApplePay.init();
2169
+ } else {
2170
+ // You can hide the Apple Pay button easy with add data-show-if-apple-pay-supported to element like <div data-show-if-apple-pay-supported>
2171
+ document.querySelectorAll('data-show-if-apple-pay-supported').forEach(element => element.style.display = 'none');
2172
+ }
2173
+
2174
+ const sallaQuickBuyCss = ".s-quick-buy-button .s-button-text{display:flex}apple-pay-button{--apple-pay-button-width:100%;--apple-pay-button-height:40px;--apple-pay-button-border-radius:.75rem;--apple-pay-button-box-sizing:content-box}";
2175
+
2176
+ const SallaQuickBuy = class {
2177
+ constructor(hostRef) {
2178
+ registerInstance(this, hostRef);
2179
+ this.validationFailed = createEvent(this, "validationFailed");
2180
+ this.requireLogin = createEvent(this, "requireLogin");
2181
+ /**
2182
+ * Button type.
2183
+ *
2184
+ * @type {string}
2185
+ * @default buy
2186
+ **/
2187
+ this.type = 'buy';
2188
+ /**
2189
+ * Product options, if is empty will get the data from the document.querySelector('salla-product-options[product-id="X"]')
2190
+ *
2191
+ * @type {object}
2192
+ * @default {}
2193
+ */
2194
+ this.options = {};
2195
+ this.quickBuy = salla.lang.get('pages.products.buy_now');
2196
+ salla.lang.onLoaded(() => {
2197
+ this.quickBuy = salla.lang.get('pages.products.buy_now');
2198
+ });
2199
+ }
2200
+ async quickBuyHandler() {
2201
+ // user guest and guest-checkout not enabled
2202
+ if (salla.config.isGuest() && !this.isGuestCheckout()) {
2203
+ this.requireLogin.emit({ productId: this.productId });
2204
+ // todo (low) :: find a way to re-fire the method after success
2205
+ let afterLoginEvent = "salla-quick-buy::user.logged-in";
2206
+ salla.event.on(afterLoginEvent, () => this.settlePayment());
2207
+ salla.api.auth.setAfterLoginEvent(afterLoginEvent);
2208
+ return salla.auth.event.dispatch('login::open', { withoutReload: true });
2209
+ }
2210
+ await this.settlePayment();
2211
+ }
2212
+ async settlePayment() {
2213
+ let optionsElement = document.querySelector(`salla-product-options[product-id="${this.productId}"]`);
2214
+ //make sure all the required options are selected
2215
+ if (optionsElement && !await optionsElement.reportValidity()) {
2216
+ this.validationFailed.emit({ productId: this.productId });
2217
+ return salla.error(salla.lang.get('common.messages.required_fields'));
2218
+ }
2219
+ //use this way to get quantity too
2220
+ let data = this.host.getElementSallaData();
2221
+ // if the store doesn't have Apple Pay , just create a cart and then redirect to check out page
2222
+ if (!this.isApplePayActive) {
2223
+ // return salla.product.buyNow(this.productId, data);
2224
+ return salla.api.request('checkout/quick-purchase/' + this.productId, data, 'post')
2225
+ .then(resp => {
2226
+ if (resp.data.redirect) {
2227
+ window.location.href = resp.data.redirect;
2228
+ }
2229
+ return resp;
2230
+ });
2231
+ }
2232
+ data.is_applepay = true;
2233
+ if ('append' in data) {
2234
+ data.append('is_applepay', true);
2235
+ }
2236
+ // noinspection TypeScriptValidateJSTypes
2237
+ salla.event.dispatch('payments::apple-pay.start-transaction', {
2238
+ amount: this.amount, // 1000
2239
+ currency: this.currency || 'SAR', // SAR
2240
+ requiredShippingContactFields: this.getRequiredShippingContactFields(),
2241
+ shippingMethods: this.isRequireShipping ? [] : undefined,
2242
+ supportedNetworks: salla.config.get('store.settings.buy_now.networks'),
2243
+ supportedCountries: salla.config.get('store.settings.buy_now.countries'),
2244
+ countryCode: salla.config.get('store.store_country') || 'SA',
2245
+ validateMerchant: {
2246
+ url: salla.url.get('checkout/applepay/validate'),
2247
+ onSuccess: (response) => {
2248
+ if (this.applePayOnly && !this.productId) { // the cart is not passes
2249
+ if (!this.cartId) {
2250
+ salla.logger.warn('🍏 Pay: trying to create applePay transaction without cartId/ProductId !');
2251
+ return Promise.resolve(response);
2252
+ }
2253
+ window.SallaApplePay.id = this.cartId;
2254
+ salla.log('🍏 Pay: create checkout success: with id #' + this.cartId);
2255
+ return Promise.resolve(response);
2256
+ }
2257
+ return salla.api.request('checkout/quick-purchase/' + this.productId, typeof data == 'object' ? data : undefined, 'post', {}).then(response => {
2258
+ // if is redirect url returned for any reason, lets redirect the user to check out
2259
+ if (response?.data?.redirect) {
2260
+ salla.log('🍏 Pay: create checkout success: redirect exits, go to checkout page');
2261
+ window.location.href = response.data.redirect.url;
2262
+ return response;
2263
+ }
2264
+ // the cart is not ready to complete apply pay session
2265
+ if (!response?.data?.id) {
2266
+ salla.logger.warn('🍏 Pay: create checkout success: No id, or redirect');
2267
+ return response;
2268
+ }
2269
+ window.SallaApplePay.id = response.data.id;
2270
+ salla.log('🍏 Pay: create checkout success: with id #' + window.SallaApplePay.id);
2271
+ });
2272
+ }
2273
+ },
2274
+ authorized: {
2275
+ // submit checkout route
2276
+ url: salla.url.get('checkout/{id}/payments/submit'),
2277
+ onFailed: (response) => {
2278
+ window.SallaApplePay.onCancel({}, response?.data?.error?.message || response?.data?.error?.code || salla.lang.get('pages.checkout.payment_failed'));
2279
+ },
2280
+ onSuccess: (response) => {
2281
+ window.location.href = response.redirect.url;
2282
+ salla.log('🍏 Pay: authorized Success:: redirect to thank you page, order placed');
2283
+ }
2284
+ },
2285
+ shippingMethodSelected: this.isRequireShipping ? {
2286
+ url: salla.url.get('checkout/{id}/shipping/details'),
2287
+ } : undefined,
2288
+ shippingContactSelected: this.isRequireShipping ? {
2289
+ url: salla.url.get('checkout/{id}/address/add'),
2290
+ } : undefined,
2291
+ guestContactSelected: this.isGuestCheckout() ? {
2292
+ url: salla.url.get('checkout/{id}/customer'),
2293
+ } : undefined,
2294
+ onCouponCodeChanged: {
2295
+ url: salla.url.get('checkout/{id}/coupons')
2296
+ },
2297
+ recalculateTotal: {
2298
+ url: salla.url.get('checkout/{id}/payments/recalculate?payment_method=apple_pay')
2299
+ },
2300
+ onError: function (message) {
2301
+ salla.log(message);
2302
+ salla.notify.error(message);
2303
+ }
2304
+ });
2305
+ }
2306
+ isGuestCheckout() {
2307
+ return salla.config.isGuest() && salla.config.get('store.features').includes('guest-checkout');
2308
+ }
2309
+ getRequiredShippingContactFields() {
2310
+ let fields = [];
2311
+ if (this.isRequireShipping) {
2312
+ fields.push('postalAddress');
2313
+ }
2314
+ if (this.isGuestCheckout()) {
2315
+ fields.push('email', 'phone', 'name');
2316
+ }
2317
+ return fields;
2318
+ }
2319
+ componentWillLoad() {
2320
+ console.log('🍏 Pay: Quick Buy Component Loaded');
2321
+ const canMakePayments = typeof window !== 'undefined' && !!window.ApplePaySession?.canMakePayments?.();
2322
+ const storeHasApplePay = salla?.config?.get?.('store.settings.payments')?.includes?.('apple_pay') ?? true;
2323
+ const isSallaGateway = salla?.config?.get?.('store.settings.is_salla_gateway', false) ?? true;
2324
+ this.isApplePayActive = canMakePayments && storeHasApplePay && isSallaGateway;
2325
+ const runInit = async () => {
2326
+ if (!this.currency && salla?.config?.get) {
2327
+ this.currency = salla.config.get('store.settings.buy_now.multi_currency') ? salla.config.get('user.currency_code') : 'SAR';
2328
+ }
2329
+ if (!this.productId && salla?.config?.get && salla.url?.is_page) {
2330
+ this.productId = salla.config.get('page.id');
2331
+ }
2332
+ if (!this.applePayOnly && !this.productId) {
2333
+ salla?.logger?.warn?.('🍏 Pay: Failed load the quick buy, the product id is missing');
2334
+ return;
2335
+ }
2336
+ if ((!this.amount || !this.isRequireShipping) && this.productId && salla?.product?.getDetails) {
2337
+ await salla.product.getDetails(this.productId, []).then((response) => {
2338
+ this.amount = response.data.price;
2339
+ this.isRequireShipping = response?.data?.is_require_shipping || false;
2340
+ }).catch((error) => {
2341
+ salla?.logger?.warn?.('🍏 Pay: Failed load the quick buy, get the product details failed: ', error);
2342
+ });
2343
+ }
2344
+ if (this.type === 'donate' && salla?.event?.on) {
2345
+ salla.event.on('product-options::donation-changed', (data) => {
2346
+ if (String(data.id) !== String(this.productId))
2347
+ return;
2348
+ this.amount = data.price;
2349
+ });
2350
+ }
2351
+ else if (salla?.url?.is_page?.('product.single') && salla?.product?.event?.onPriceUpdated) {
2352
+ salla.product.event.onPriceUpdated(response => { this.amount = response.data.price; });
2353
+ }
2354
+ this.isApplePayActive = (salla?.helpers?.hasApplePay?.() ?? canMakePayments)
2355
+ && (salla?.config?.get?.('store.settings.payments')?.includes?.('apple_pay') ?? storeHasApplePay)
2356
+ && (salla?.config?.get?.('store.settings.is_salla_gateway', false) ?? isSallaGateway);
2357
+ if (!document.getElementById('apple-pay-sdk') && this.isApplePayActive) {
2358
+ const script = document.createElement('script');
2359
+ script.src = 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js';
2360
+ script.setAttribute('id', 'apple-pay-sdk');
2361
+ script.async = true;
2362
+ document.body.appendChild(script);
2363
+ }
2364
+ };
2365
+ return new Promise((resolve) => {
2366
+ if (typeof salla?.onReady === 'function') {
2367
+ salla.onReady(() => runInit().then(() => resolve(true)));
2368
+ }
2369
+ else {
2370
+ runInit().then(() => resolve(true));
2371
+ }
2372
+ });
2373
+ }
2374
+ render() {
2375
+ return h(Host, { key: '9a36fa6b7163dae6feed474712e3d0c3003d012c' }, this.quickBuyButton());
2376
+ }
2377
+ quickBuyButton() {
2378
+ return h("apple-pay-button", { locale: salla?.config?.get?.('user.language_code') || 'ar', onClick: () => this.quickBuyHandler(), "data-quick-purchase": "applepay", class: "s-quick-buy-apple-pay", "data-is-applepay": "1", buttonstyle: "black", type: this.type });
2379
+ }
2380
+ get host() { return getElement(this); }
2381
+ };
2382
+ SallaQuickBuy.style = sallaQuickBuyCss;
2383
+
2384
+ export { SallaAddProductButton as salla_add_product_button, SallaProductAvailability as salla_product_availability, SallaProductOptions as salla_product_options, SallaQuickBuy as salla_quick_buy };