Skip to content

Commit

Permalink
Merge pull request #87 from xfiveco/feature/add-to-cart-on-home
Browse files Browse the repository at this point in the history
Feature/add to cart on home
  • Loading branch information
marcinkrzeminski committed Jun 1, 2023
2 parents 31bf1a9 + 2618d91 commit 1ce8691
Show file tree
Hide file tree
Showing 5 changed files with 183 additions and 1 deletion.
2 changes: 1 addition & 1 deletion assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const pageClasses = {
compare: () => import('./theme/compare'),
createaccount: getLogin,
createaccount_thanks: getLogin,
default: noop,
default: () => import('./theme/home'),
editaccount: getAccount,
error: noop,
forgotpassword: getLogin,
Expand Down
3 changes: 3 additions & 0 deletions assets/js/theme/common/product-details.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import bannerUtils from './utils/banner-utils'
import currencySelector from '../global/currency-selector'
import q$, { q$$, parents } from '../global/selector'
import trigger from './utils/trigger'
import addToCartWithModal from '../custom/add-to-cart-modal'

export default class ProductDetails extends ProductDetailsBase {
constructor($scope, context, productAttributesData = {}) {
Expand Down Expand Up @@ -111,6 +112,8 @@ export default class ProductDetails extends ProductDetailsBase {
$productOptionsElement.style.display = 'block'

this.previewModal = modalFactory('.js-preview-modal')

addToCartWithModal('[data-button-type="add-cart"]', this.context, this.previewModal)
}

registerAddToCartValidation() {
Expand Down
157 changes: 157 additions & 0 deletions assets/js/theme/custom/add-to-cart-modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import utils from '@bigcommerce/stencil-utils'
import { normalizeFormData } from '../common/utils/api'
import currencySelector from '../global/currency-selector'
import q$, { q$$ } from '../global/selector'
import trigger from '../common/utils/trigger'

class AddToCartWithModal {
constructor($addToCartButtons, context, previewModal) {
this.$addToCartButtons = $addToCartButtons
this.previewModal = previewModal
this.context = context

this.init()
}

init() {
this.$addToCartButtons.forEach(($addToCartButton) => {
$addToCartButton.addEventListener('click', (event) => {
event.preventDefault()

const formData = new FormData()

new URL(event.target.href).searchParams.forEach((value, key) => formData.append(key, value))

// Add item to cart
utils.api.cart.itemAdd(normalizeFormData(formData), (err, response) => {
currencySelector(response.data.cart_id)

// Open preview modal and update content
if (this.previewModal) {
this.previewModal.open()

if (window.ApplePaySession) {
this.previewModal.$modal.classList.add('js-apple-pay-supported')
}

this.updateCartContent(this.previewModal, response.data.cart_item.id)
} else {
if (this.$overlay) {
this.$overlay.style.display = 'block'
}

// if no modal, redirect to the cart page
this.redirectTo(response.data.cart_item.cart_url || this.context.urls.cart)
}
})
})
})
}

/**
* Update cart content
*
* @param {Modal} modal
* @param {String} cartItemId
* @param {Function} onComplete
*/
updateCartContent(modal, cartItemId, onComplete) {
this.getCartContent(cartItemId, (err, response) => {
if (err) {
return
}

modal.updateContent(response)

// Update cart counter
const $body = q$('body')
const $cartQuantity = q$('[data-cart-quantity]', modal.$content)
const $cartCounter = q$('.js-nav-user-action .cart-count')
const quantity = $cartQuantity.dataset.cartQuantity || 0
const $promotionBanner = q$('.js-promotion-banner')
const $backToShopppingBtn = q$('.js-preview-cart-checkout > .js-reveal-close')
const $modalCloseBtn = q$('.js-preview-modal > .modal-close')
const bannerUpdateHandler = () => {
const $productContainer = q$('#main-content > .js-container') // #main-content is for jumping into that section in the page

$productContainer.append('<div class="js-loading-overlay js-pdp-update"></div>')
q$('.js-loading-overlay.js-pdp-update', $productContainer).style.display = 'block'
window.location.reload()
}

if ($cartCounter) {
$cartCounter.classList.add('cart-count-positive')
}

trigger($body, 'cart-quantity-update', quantity)

if (onComplete) {
onComplete(response)
}

if ($promotionBanner && $backToShopppingBtn) {
$backToShopppingBtn.addEventListener('click', bannerUpdateHandler)
$modalCloseBtn.addEventListener('click', bannerUpdateHandler)
}
})
}

/**
* Get cart contents
*
* @param {String} cartItemId
* @param {Function} onComplete
*/
getCartContent(cartItemId, onComplete) {
const options = {
template: 'cart/preview',
params: {
suggest: cartItemId,
},
config: {
cart: {
suggestions: {
limit: 4,
},
},
},
}

utils.api.cart.getContent(options, onComplete)
}

/**
* Redirect to url
*
* @param {String} url
*/
redirectTo(url) {
if (this.isRunningInIframe() && !window.iframeSdk) {
window.top.location = url
} else {
window.location = url
}
}

/**
* Checks if the current window is being run inside an iframe
* @returns {boolean}
*/
isRunningInIframe() {
try {
return window.self !== window.top
} catch (e) {
return true
}
}
}

export default function addToCartWithModal(buttonsSelector, context, previewModal) {
const $addToCartButtons = q$$(buttonsSelector)
if ($addToCartButtons.length === 0) {
return
}

/* eslint-disable no-new */
new AddToCartWithModal($addToCartButtons, context, previewModal)
}
15 changes: 15 additions & 0 deletions assets/js/theme/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import PageManager from './page-manager'
import addToCartWithModal from './custom/add-to-cart-modal'
import modalFactory from './global/modal'
import q$ from './global/selector'

export default class Home extends PageManager {
constructor($scope, context) {
super($scope, context)

this.$overlay = q$('.js-cart-item-add .js-loading-overlay')
this.previewModal = modalFactory('.js-preview-modal')

addToCartWithModal('[data-button-type="add-cart"]', this.context, this.previewModal)
}
}
7 changes: 7 additions & 0 deletions templates/pages/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,12 @@
{{/if}}
{{{region name="home_below_new_products"}}}
</div>

<div class="js-preview-modal is-modal-large js-reveal c-modal">
{{> components/common/modal/modal-close-btn }}

<div class="js-modal-content"></div>
<div class="js-loading-overlay"></div>
</div>
{{/partial}}
{{> layout/base}}

0 comments on commit 1ce8691

Please sign in to comment.