id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-on-localhost_c9a9d2c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nimport useProduct from '../../../ProductContext/useProduct'\nimport { path, isEmpty, compose } from 'ramda'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport withToast from '../../../Styleguide/withToast'\nimport OrderFormContext from '../../../StoreResources/OrderFormContext'\nimport ProductPrice from '../ProductPrice'\nimport { graphql } from 'react-apollo'\n\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport { BuyButton } from './index'\nimport { transformAssemblyOptions, sumAssembliesPrice } from './assemblyUtils'\nimport { loader } from 'graphql.macro'\n\nconst addToCartMutation = loader('./mutations/addToCart.gql')\nconst setOpenMinicartMutation = loader('./mutations/setOpenMinicart.gql')\nconst installedApp = loader('./queries/installedApp.gql')\nconst { useOrderForm } = OrderFormContext\n\nconst MESSAGE_CSS_HANDLES = [\n 'buyButtonText',\n 'buttonDataContainer',\n 'buttonItemsPrice',\n]\n\nconst CHECKOUT_URL = {\n V0: '/checkout/#/cart',\n V1: '/cart',\n}\n\nconst BuyButtonMessage = ({ showItemsPrice, skuItems }) => {\n const handles = useCssHandles(MESSAGE_CSS_HANDLES)\n if (!showItemsPrice) {\n return (\n <FormattedMessage id=\"store/buy-button.add-to-cart\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n )\n }\n\n const totalPrice = skuItems.reduce((acc, item) => {\n const itemPrice =\n item.sellingPriceWithAssemblies != null\n ? item.sellingPriceWithAssemblies\n : item.price\n const itemCost = itemPrice * item.quantity\n return acc + itemCost\n }, 0)\n\n return (\n <div\n className={`${handles.buttonDataContainer} flex w-100 justify-between items-center`}\n >\n <FormattedMessage id=\"store/buy-button.add-to-cart\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n <ProductPrice\n showLabels={false}\n showListPrice={false}\n sellingPrice={totalPrice}\n className={handles.buttonItemsPrice}\n />\n </div>\n )\n}\nconst BuyButtonWrapper = ({\n intl,\n addToCart,\n showToast,\n onAddStart,\n onAddFinish,\n children,\n isOneClickBuy,\n shouldOpenMinicart,\n setMinicartOpen,\n showItemsPrice,\n available: propAvailable,\n skuItems: propSkuItems,\n large: propLarge,\n disabled: propDisabled,\n shouldAddToCart,\n customToastURL,\n showTooltipOnSkuNotSelected,\n checkoutVersion,\n}) => {\n const orderFormContext = useOrderForm()\n const valuesFromContext = useProduct()\n\n const isEmptyContext = !valuesFromContext || isEmpty(valuesFromContext)\n\n const product = valuesFromContext && valuesFromContext.product\n const selectedItem = valuesFromContext && valuesFromContext.selectedItem\n const assemblyOptions = valuesFromContext && valuesFromContext.assemblyOptions\n const selectedSeller = path(['selectedItem', 'sellers', 0], valuesFromContext)\n const selectedQuantity =\n valuesFromContext && valuesFromContext.selectedQuantity != null\n ? valuesFromContext.selectedQuantity\n : 1\n\n const skuItems =\n isEmptyContext || propSkuItems != null\n ? propSkuItems\n : EnhancedBuyButton.mapCatalogItemToCart({\n product,\n selectedItem,\n selectedQuantity,\n selectedSeller,\n assemblyOptions,\n })\n\n const large = isEmptyContext || propLarge != null ? propLarge : true\n\n const available =\n isEmptyContext || propAvailable != null\n ? propAvailable\n : selectedSeller &&\n selectedSeller.commertialOffer &&\n selectedSeller.commertialOffer.AvailableQuantity > 0\n\n const groupsValidArray =\n (assemblyOptions &&\n assemblyOptions.areGroupsValid &&\n Object.values(assemblyOptions.areGroupsValid)) ||\n []\n\n const areAssemblyGroupsValid = groupsValidArray.every(Boolean)\n const disabled =\n isEmptyContext || propDisabled != null\n ? propDisabled\n : !areAssemblyGroupsValid\n\n const version =\n checkoutVersion &&\n checkoutVersion.installedAppPublic &&\n checkoutVersion.installedAppPublic.version\n\n const checkoutUrl =\n version && parseInt(version.split('.')[0]) > 0\n ? CHECKOUT_URL.V1\n : CHECKOUT_URL.V0\n\n return (\n <BuyButton\n intl={intl}\n addToCart={addToCart}\n onAddStart={onAddStart}\n onAddFinish={onAddFinish}\n showToast={showToast}\n orderFormContext={orderFormContext}\n skuItems={skuItems}\n large={large}\n available={available}\n isOneClickBuy={isOneClickBuy}\n shouldOpenMinicart={shouldOpenMinicart}\n setMinicartOpen={setMinicartOpen}\n disabled={disabled}\n customToastURL={customToastURL}\n shouldAddToCart={shouldAddToCart}\n showTooltipOnSkuNotSelected={showTooltipOnSkuNotSelected}\n checkoutUrl={checkoutUrl}\n >\n {children || (\n <BuyButtonMessage showItemsPrice={showItemsPrice} skuItems={skuItems} />\n )}\n </BuyButton>\n )\n}\n\nconst withAddToCart = graphql(addToCartMutation, {\n name: 'addToCart',\n props: ({ addToCart }) => ({\n addToCart: items => addToCart({ variables: { items } }),\n }),\n})\n\nconst withOpenMinicart = graphql(setOpenMinicartMutation, {\n name: 'setMinicartOpen',\n props: ({ setMinicartOpen }) => ({\n setMinicartOpen: isOpen => setMinicartOpen({ variables: { isOpen } }),\n }),\n})\n\nconst withCheckoutVersion = graphql(installedApp, {\n name: 'checkoutVersion',\n options: {\n ssr: false,\n variables: {\n slug: 'vtex.checkout',\n },\n },\n})\n\nconst EnhancedBuyButton = compose(\n withAddToCart,\n withOpenMinicart,\n withCheckoutVersion,\n withToast,\n injectIntl\n)(BuyButtonWrapper)\n\n// This function is public available to be used only by vtex.product-summary.\n// We do not garantee this API will not change and might happen breaking change anytime.\nEnhancedBuyButton.mapCatalogItemToCart = function mapCatalogItemToCart({\n product,\n selectedItem,\n selectedQuantity,\n selectedSeller,\n assemblyOptions,\n}) {\n return (\n product &&\n selectedItem &&\n selectedSeller &&\n selectedSeller.commertialOffer && [\n {\n index: 0,\n quantity: selectedQuantity,\n detailUrl: `/${product.linkText}/p`,\n name: product.productName,\n brand: product.brand,\n category:\n product.categories && product.categories.length > 0\n ? product.categories[0]\n : '',\n productRefId: product.productReference,\n seller: selectedSeller.sellerId,\n price: selectedSeller.commertialOffer.Price,\n listPrice: selectedSeller.commertialOffer.ListPrice,\n variant: selectedItem.name,\n skuId: selectedItem.itemId,\n imageUrl: path(['images', '0', 'imageUrl'], selectedItem),\n ...transformAssemblyOptions(\n path(['items'], assemblyOptions),\n path(['inputValues'], assemblyOptions),\n selectedSeller.commertialOffer.Price,\n selectedQuantity\n ),\n sellingPriceWithAssemblies:\n selectedSeller.commertialOffer.Price +\n sumAssembliesPrice(path(['items'], assemblyOptions) || {}),\n },\n ]\n )\n}\n\nexport default EnhancedBuyButton\n\n```"
}
] |
code_store-on-localhost_75b180e8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable react-hooks/exhaustive-deps */\nimport PropTypes from 'prop-types'\nimport React, { useContext, useCallback, useState, useEffect } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { path } from 'ramda'\nimport ContentLoader from 'react-content-loader'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport PWAContext from '../../../StoreResources/PWAContext'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport useProduct from '../../../ProductContext/useProduct'\nimport ProductDispatchContext from '../../../ProductContext/ProductDispatchContext'\n\nimport Button from '../../../Styleguide/Button'\nimport ToastContext from '../../../Styleguide/ToastContext'\nimport Tooltip from '../../../Styleguide/Tooltip'\nimport useMarketingSessionParams from './hooks/useMarketingSessionParams'\n\nconst { useProductDispatch } = ProductDispatchContext\nconst { usePWA } = PWAContext\nconst CONSTANTS = {\n SUCCESS_MESSAGE_ID: 'store/buybutton.buy-success',\n SELECT_SKU_ERROR_ID: 'store/buybutton.select-sku-variations',\n OFFLINE_BUY_MESSAGE_ID: 'store/buybutton.buy-offline-success',\n DUPLICATE_CART_ITEM_ID: 'store/buybutton.buy-success-duplicate',\n ERROR_MESSAGE_ID: 'store/buybutton.add-failure',\n SEE_CART_ID: 'store/buybutton.see-cart',\n TOAST_TIMEOUT: 3000,\n}\n\nconst CSS_HANDLES = ['buyButtonContainer', 'buyButtonText']\n\nconst isTooltipNeeded = ({\n showTooltipOnSkuNotSelected,\n skuSelector,\n}) => {\n if (showTooltipOnSkuNotSelected && !skuSelector.areAllVariationsSelected) {\n return {\n showTooltip: true,\n labelId: CONSTANTS.SELECT_SKU_ERROR_ID,\n }\n }\n return {\n showTooltip: false,\n }\n}\n\nconst skuItemToMinicartItem = item => {\n return {\n // Important for the mutation\n id: item.skuId,\n seller: item.seller,\n options: item.options,\n quantity: item.quantity,\n\n // Fields for optmistic cart\n sellingPrice: item.price,\n skuName: item.variant,\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrl,\n name: item.name,\n listPrice: item.listPrice,\n assemblyOptions: item.assemblyOptions,\n sellingPriceWithAssemblies: item.sellingPriceWithAssemblies,\n\n // Fields for Analytics\n brand: item.brand,\n category: item.category,\n productRefId: item.productRefId,\n }\n}\n\nconst useCallCartFinishIfPending = (orderFormContext, isAddingToCart, addToCartAndFinish) => {\n const orderFormLoading = orderFormContext && orderFormContext.loading\n useEffect(() => {\n if (!orderFormLoading && isAddingToCart) {\n addToCartAndFinish()\n }\n }, [orderFormLoading])\n}\n\n/**\n * BuyButton Component.\n * Adds a list of sku items to the cart.\n */\nexport const BuyButton = ({\n intl,\n large,\n addToCart,\n skuItems,\n onAddStart,\n onAddFinish,\n setMinicartOpen,\n available = true,\n orderFormContext,\n isOneClickBuy = false,\n children,\n disabled: disabledProp,\n shouldAddToCart = true,\n shouldOpenMinicart = false,\n showTooltipOnSkuNotSelected = true,\n checkoutUrl,\n customToastURL = checkoutUrl,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const [isAddingToCart, setAddingToCart] = useState(false)\n const { showToast } = useContext(ToastContext)\n const {\n skuSelector = {\n areAllVariationsSelected: true,\n },\n } = useProduct()\n const dispatch = useProductDispatch()\n const { settings = {}, showInstallPrompt } = usePWA() || {}\n const { promptOnCustomEvent } = settings\n const translateMessage = useCallback(id => intl.formatMessage({ id: id }), [\n intl,\n ])\n const orderFormItems = path(['orderForm', 'items'], orderFormContext)\n const { utmParams, utmiParams } = useMarketingSessionParams()\n\n const resolveToastMessage = (success, isNewItem) => {\n if (!success) return translateMessage(CONSTANTS.ERROR_MESSAGE_ID)\n if (!isNewItem) return translateMessage(CONSTANTS.DUPLICATE_CART_ITEM_ID)\n\n const isOffline = window && window.navigator && !window.navigator.onLine\n const checkForOffline = !isOffline\n ? translateMessage(CONSTANTS.SUCCESS_MESSAGE_ID)\n : translateMessage(CONSTANTS.OFFLINE_BUY_MESSAGE_ID)\n\n return checkForOffline\n }\n\n const toastMessage = ({ success, isNewItem }) => {\n const message = resolveToastMessage(success, isNewItem)\n\n const action = success\n ? {\n label: translateMessage(CONSTANTS.SEE_CART_ID),\n href: customToastURL,\n }\n : undefined\n\n showToast({ message, action })\n }\n\n const { rootPath = '' } = useRuntime()\n const fullCheckoutUrl = rootPath + checkoutUrl\n\n const beforeAddToCart = event => {\n event.stopPropagation()\n event.preventDefault()\n\n setAddingToCart(true)\n onAddStart && onAddStart()\n }\n\n const addToCartAndFinish = async () => {\n let showToastMessage\n try {\n const minicartItems = skuItems.map(skuItemToMinicartItem)\n const localStateMutationResult = !isOneClickBuy\n ? await addToCart(minicartItems)\n : null\n const linkStateItems =\n localStateMutationResult && localStateMutationResult.data.addToCart\n const callOrderFormDirectly = !linkStateItems\n\n let success = null\n if (callOrderFormDirectly) {\n const variables = {\n orderFormId: orderFormContext.orderForm.orderFormId,\n items: skuItems.map(item => ({\n id: item.skuId,\n seller: item.seller,\n options: item.options,\n quantity: item.quantity,\n })),\n ...(utmParams ? {utmParams} : {}),\n ...(utmiParams ? {utmiParams} : {}),\n }\n const mutationRes = await orderFormContext.addItem({ variables })\n const { items } = mutationRes.data.addItem\n\n success = skuItems.filter(\n skuItem =>\n !!items.find(\n ({ id, seller }) =>\n id === skuItem.skuId && seller === skuItem.seller\n )\n )\n await orderFormContext.refetch().catch(() => null)\n }\n\n const addedItem =\n (linkStateItems &&\n skuItems.filter(\n skuItem =>\n !!linkStateItems.find(\n ({ id, seller }) =>\n id === skuItem.skuId && seller === skuItem.seller\n )\n )) ||\n success\n\n const foundItem =\n addedItem.length &&\n orderFormItems &&\n orderFormItems.filter(\n item =>\n item.id === addedItem[0].skuId &&\n item.seller === addedItem[0].seller\n ).length > 0\n\n success = addedItem\n\n showToastMessage = () =>\n toastMessage({\n success: success && success.length >= 1,\n isNewItem: !foundItem,\n })\n\n /* PWA */\n if (promptOnCustomEvent === 'addToCart' && showInstallPrompt) {\n showInstallPrompt()\n }\n\n shouldOpenMinicart && !isOneClickBuy && setMinicartOpen(true)\n } catch (err) {\n console.error(err)\n showToastMessage = () => toastMessage(false)\n }\n\n setTimeout(() => {\n setAddingToCart(false)\n showToastMessage()\n if (isOneClickBuy) {\n window.location.assign(fullCheckoutUrl)\n }\n onAddFinish && onAddFinish()\n }, 500)\n }\n\n const handleAddToCart = async event => {\n beforeAddToCart(event)\n await addToCartAndFinish()\n }\n\n useCallCartFinishIfPending(orderFormContext, isAddingToCart, addToCartAndFinish)\n\n const handleClick = e => {\n if (dispatch) {\n dispatch({ type: 'SET_BUY_BUTTON_CLICKED', args: { clicked: true } })\n }\n\n if (skuSelector.areAllVariationsSelected && shouldAddToCart) {\n if (orderFormContext && orderFormContext.loading) {\n // Just call the before add to cart function and the useEffect hook will call the finish part when apropriate\n beforeAddToCart(e)\n } else {\n handleAddToCart(e)\n }\n }\n }\n\n if (!skuItems) {\n return <ContentLoader />\n }\n\n const disabled = disabledProp || !available\n const unavailableLabel = (\n <FormattedMessage id=\"store/buyButton-label-unavailable\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n )\n\n const ButtonWithLabel = <Button\n block={large}\n disabled={disabled}\n onClick={handleClick}\n isLoading={isAddingToCart}\n >\n {available ? children : unavailableLabel}\n </Button>\n\n const { showTooltip, labelId } = isTooltipNeeded({\n showTooltipOnSkuNotSelected,\n skuSelector,\n })\n\n const tooltipLabel = showTooltip &&\n <span className={handles.errorMessage}>\n <FormattedMessage id={labelId} />\n </span>\n\n return !showTooltip ? (\n ButtonWithLabel\n ) : (\n <Tooltip trigger=\"click\" label={tooltipLabel}>\n {ButtonWithLabel}\n </Tooltip>\n )\n}\n\nBuyButton.propTypes = {\n /** SKU Items to be added to the cart */\n skuItems: PropTypes.arrayOf(\n PropTypes.shape({\n /** Specification of which product will be added to the cart */\n skuId: PropTypes.string.isRequired,\n /** Quantity of the product sku to be added to the cart */\n quantity: PropTypes.number.isRequired,\n /** Which seller is being referenced by the button */\n seller: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /* Sku name */\n name: PropTypes.string.isRequired,\n /* Sku price */\n price: PropTypes.number.isRequired,\n /* Sku variant */\n variant: PropTypes.string,\n /* Sku brand */\n brand: PropTypes.string.isRequired,\n /* Sku options. In delivery, for examples, are the pizza options */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n /* Option id */\n id: PropTypes.string.isRequired,\n /* Option quantity */\n quantity: PropTypes.number.isRequired,\n /* Option assembly id */\n assemblyId: PropTypes.string.isRequired,\n /* Option seller */\n seller: PropTypes.string,\n })\n ),\n })\n ),\n /** Component children that will be displayed inside of the button **/\n children: PropTypes.node.isRequired,\n /** Should redirect to checkout after adding to cart */\n isOneClickBuy: PropTypes.bool,\n /** Should open the Minicart after click */\n shouldOpenMinicart: PropTypes.bool,\n /** If it should add to cart when clicked */\n shouldAddToCart: PropTypes.bool,\n /** Set style to large */\n large: PropTypes.bool,\n /** If the product is available or not*/\n available: PropTypes.bool,\n /** If it should a tooltip when you click the button but there's no SKU selected */\n showTooltipOnSkuNotSelected: PropTypes.bool,\n /** Function used to show toasts (messages) to user */\n showToast: PropTypes.func,\n /** Function to be called on the start of add to cart click event */\n onAddStart: PropTypes.func,\n /** Function to be called on the end of add to cart event */\n onAddFinish: PropTypes.func,\n /** Add to cart mutation */\n addToCart: PropTypes.func.isRequired,\n /** Open Minicart mutation */\n setMinicartOpen: PropTypes.func.isRequired,\n /** The orderFormContext object */\n orderFormContext: PropTypes.object,\n /** If the button is disabled or not */\n disabled: PropTypes.bool,\n /** A custom URL for the `VIEW CART` button inside the toast */\n customToastURL: PropTypes.string,\n /** The URL to the cart **/\n checkoutUrl: PropTypes.string,\n}\n\nexport default BuyButton\n\n```"
}
] |
code_store-on-localhost_d17ec57b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/DiscountBadge/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* DiscountBadge CSS Module.\n*/\n\n.discountContainer {\n}\n.discountInsideContainer {\n}\n\n```"
}
] |
code_store-on-localhost_d6fc6742
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/DiscountBadge/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable react/style-prop-object */\nimport React from 'react'\nimport { FormattedNumber } from 'react-intl'\nimport PropTypes from 'prop-types'\n\nimport IOMessage from '../../../NativeTypes/IOMessage'\n\nimport styles from './styles.css'\n\nconst calculateDiscountTax = (listPrice, sellingPrice) => {\n return (listPrice - sellingPrice) / listPrice\n}\n\n/**\n * The discount badge component. It receives the product's list and selling prices\n * and calculates the discount percent to show it in the product's sumary.\n */\nconst DiscountBadge = ({ listPrice, sellingPrice, label = '', children }) => {\n const percent = calculateDiscountTax(listPrice, sellingPrice)\n const shouldShowPercentage = percent && percent >= 0.01\n\n return (\n <div className={`${styles.discountContainer} relative dib`}>\n {shouldShowPercentage ? (\n <div\n className={`${styles.discountInsideContainer} t-mini white absolute right-0 pv2 ph3 bg-emphasis z-1`}\n >\n <IOMessage id={label}>\n {labelValue => (\n <>\n {!labelValue && '-'}\n <FormattedNumber value={percent} style=\"percent\" />{' '}\n {labelValue && ' '}\n {labelValue && <span>{labelValue}</span>}\n </>\n )}\n </IOMessage>\n </div>\n ) : null}\n {children}\n </div>\n )\n}\n\nDiscountBadge.propTypes = {\n /** The product's default price */\n listPrice: PropTypes.number.isRequired,\n /** The product's price with discount */\n sellingPrice: PropTypes.number.isRequired,\n /** Label to track the discount percent */\n label: PropTypes.string,\n /** Image element */\n children: PropTypes.node.isRequired,\n}\n\nexport default DiscountBadge\n\n```"
}
] |
code_store-on-localhost_644f7dfe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Greeting/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* Greeting CSS Module\n*/\n.greetingContainer {\n}\n.message {\n}\n.firstName {\n}\n\n```"
}
] |
code_store-on-localhost_87bb62ef
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Greeting/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Fragment } from 'react'\nimport { compose, branch, renderComponent } from 'recompose'\nimport { FormattedMessage } from 'react-intl'\nimport { path } from 'ramda'\nimport { graphql } from 'react-apollo'\nimport { loader } from 'graphql.macro'\n\nimport Loader from './Loader'\n\nimport styles from './styles.css'\n\nconst orderFormQuery = loader('./queries/orderForm.gql')\n\nconst Wrapper = ({ children }) => (\n <div\n className={`${\n styles.greetingContainer\n } mh4 pv4 t-heading-4 c-on-base nowrap`}\n >\n {children}\n </div>\n)\n\nconst withWrapper = Component => props => (\n <Wrapper>\n <Component {...props} />\n </Wrapper>\n)\n\nconst Greeting = ({ orderForm }) => {\n const firstName = path(['clientProfileData', 'firstName'], orderForm) || null\n return (\n firstName && (\n <Wrapper>\n <Fragment>\n <span className={styles.message}>\n <FormattedMessage id=\"store/greeting\" />,\n </span>\n <span className={`${styles.firstName} pl2 b`}>{firstName}</span>\n </Fragment>\n </Wrapper>\n )\n )\n}\n\nGreeting.propTypes = {\n orderForm: PropTypes.shape({\n clientProfileData: PropTypes.shape({\n firstName: PropTypes.string,\n }),\n }),\n}\n\nconst withLinkStateOrderForm = graphql(orderFormQuery, {\n props: ({ data: { minicart } }) => ({\n orderForm: minicart && minicart.orderForm && JSON.parse(minicart.orderForm),\n }),\n})\n\nexport default compose(\n withLinkStateOrderForm,\n branch(({ loading }) => loading, renderComponent(withWrapper(Loader)))\n)(Greeting)\n\n```"
}
] |
code_store-on-localhost_6c8e4c31
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Greeting/Loader.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport ContentLoader from 'react-content-loader'\n\nconst GreetingLoading = props => (\n <ContentLoader\n height={32}\n width={300}\n speed={2}\n primaryColor=\"#f3f3f3\"\n secondaryColor=\"#ecebeb\"\n className=\"v-mid\"\n data-testid=\"greeting-loader\"\n {...props}\n >\n <rect rx=\"1\" ry=\"1\" width=\"300\" height=\"32\" />\n </ContentLoader>\n)\n\nexport default GreetingLoading\n\n```"
}
] |
code_store-on-localhost_7a9ac3a4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Notification/notificationBar.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { memo } from 'react'\nimport { string } from 'prop-types'\nimport NotificationContent from './notificationContent'\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport formatIOMessage from '../../../NativeTypes/formatIOMessage'\nimport { injectIntl } from 'react-intl'\n\nimport styles from './styles.css'\n\nconst NotificationBar = ({ content, intl }) => {\n return (\n content && (\n <div\n className={`${\n styles.notificationBarContainer\n } bg-base--inverted c-on-base--inverted w-100`}\n >\n <div\n className={`${\n styles.notificationBarInner\n } min-h-large flex items-center justify-center`}\n >\n <NotificationContent content={formatIOMessage({ id: content, intl })} />\n </div>\n </div>\n )\n )\n}\n\nNotificationBar.propTypes = {\n content: string,\n}\n\nNotificationBar.defaultProps = {\n content: '',\n}\n\nNotificationBar.schema = {\n title: 'admin/editor.notification-bar.title'\n}\n\nexport default hoistNonReactStatics(injectIntl(NotificationBar), memo(NotificationBar))\n\n```"
}
] |
code_store-on-localhost_84a2bd4a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Notification/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.notificationBarContainer {}\n.notificationBarInner {}\n.notificationContent {}\n\n```"
}
] |
code_store-on-localhost_47a53575
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Notification/notificationInline.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { memo } from 'react'\nimport { string } from 'prop-types'\nimport NotificationContent from './notificationContent'\n\nconst NotificationInline = ({ content }) => {\n return content && <NotificationContent content={content} />\n}\n\nNotificationInline.propTypes = {\n content: string,\n}\n\nNotificationInline.defaultProps = {\n content: '',\n}\n\nNotificationInline.schema = {\n title: 'admin/editor.notification-bar.title',\n description: 'admin/editor.notification-bar.description',\n type: 'object',\n properties: {\n content: {\n title: 'admin/editor.notification-bar.content.title',\n description: 'admin/editor.notification-bar.content.description',\n type: 'string',\n default: '',\n },\n },\n}\n\nexport default memo(NotificationInline)\n\n```"
}
] |
code_store-on-localhost_d60d5530
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Notification/notificationContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { memo } from 'react'\nimport { string } from 'prop-types'\nimport insane from 'insane'\n\nimport styles from './styles.css'\n\nconst NotificationContent = ({ content }) => {\n const safeContent = { __html: insane(content) }\n return (\n <div\n className={styles.notificationContent}\n dangerouslySetInnerHTML={safeContent}\n />\n )\n}\n\nNotificationContent.propTypes = {\n content: string,\n}\n\nNotificationContent.defaultProps = {\n content: '',\n}\n\nexport default memo(NotificationContent)\n\n```"
}
] |
code_store-on-localhost_61442a64
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductDescription/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport { path } from 'ramda'\n\nimport ProductDescription from './index'\n\nconst ProductDescriptionWrapper = props => {\n const valuesFromContext = useContext(ProductContext)\n const description =\n props.description != null\n ? props.description\n : path(['product', 'description'], valuesFromContext)\n\n return (\n <ProductDescription\n title={props.title}\n description={description}\n collapseContent={props.collapseContent}\n />\n )\n}\n\nProductDescriptionWrapper.schema = {\n title: 'admin/editor.product-description.title',\n}\n\nProductDescriptionWrapper.defaultProps = {\n collapseContent: true,\n}\n\nexport default ProductDescriptionWrapper\n\n```"
}
] |
code_store-on-localhost_d73c8cbe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductDescription/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { memo, useMemo } from 'react'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport HtmlParser from 'react-html-parser'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\nimport formatIOMessage from '../../../NativeTypes/formatIOMessage'\n\nimport GradientCollapse from '../GradientCollapse/index'\n\nconst CSS_HANDLES = [\n 'productDescriptionContainer',\n 'productDescriptionTitle',\n 'productDescriptionText',\n]\n\n/**\n * Product Description Component.\n * Render the description of a product\n */\nconst ProductDescription = ({ description, collapseContent, title, intl }) => {\n if (!description) {\n return null\n }\n\n const descriptionParsed = useMemo(() => HtmlParser(description), [\n description,\n ])\n\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <div className={handles.productDescriptionContainer}>\n <FormattedMessage id=\"store/product-description.title\">\n {txt => (\n <h2\n className={`${handles.productDescriptionTitle} t-heading-5 mb5 mt0`}\n >\n {title ? formatIOMessage({ id: title, intl }) : txt}\n </h2>\n )}\n </FormattedMessage>\n\n <div className={`${handles.productDescriptionText} c-muted-1`}>\n {collapseContent ? (\n <GradientCollapse collapseHeight={220}>\n {descriptionParsed}\n </GradientCollapse>\n ) : (\n descriptionParsed\n )}\n </div>\n </div>\n )\n}\n\nProductDescription.propTypes = {\n title: PropTypes.string,\n /** Product description string */\n description: PropTypes.string,\n collapseContent: PropTypes.bool,\n}\n\nexport default injectIntl(memo(ProductDescription))\n\n```"
}
] |
code_store-on-localhost_1ed1d2f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/module/images.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { head } from 'ramda'\n\nexport const imageUrlForSize = (imageUrl: string, size: number) => {\n if (!imageUrl) {\n return ''\n }\n const urlSplitted = imageUrl.split('/')\n const idsStringIdx = urlSplitted.findIndex(content => content === 'ids')\n if (idsStringIdx < 0 || idsStringIdx === urlSplitted.length - 1)\n return imageUrl\n const sizeStringIdx = idsStringIdx + 1\n const sizeString = urlSplitted[sizeStringIdx]\n const imageId = head(sizeString.split('-'))\n const newSizeString = `${imageId}-${size * 2}-auto`\n return [\n ...urlSplitted.slice(0, sizeStringIdx),\n newSizeString,\n ...urlSplitted.slice(sizeStringIdx + 1),\n ].join('/')\n}\n\nexport const VARIATION_IMG_SIZE = 40\nexport const IMAGE_DEFAULT_SIZE = 900\nexport const THUMB_SIZE = 150\n\n```"
}
] |
code_store-on-localhost_15ae1e41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Animation/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { ANIMATIONS } from './animation'\n\nconst ANIMATION_TRANSFER = 110\nconst ANIMATION_TRANSFER_ENTER = 0\nconst ANIMATION_TIME = 0.4\n\n/**\n * Animation component\n */\nexport default class Animation extends Component {\n static propTypes = {\n /* Object to be animated */\n children: PropTypes.node.isRequired,\n /* Active the animation */\n isActive: PropTypes.bool,\n /* Classname to the animation */\n className: PropTypes.string,\n /* Type of animation */\n type: PropTypes.oneOf([\n 'drawerLeft',\n 'drawerRight',\n 'drawerTop',\n 'drawerBottom',\n ]),\n /* The animation's duration in seconds */\n duration: PropTypes.number,\n /* The active animation deslocation in percentage */\n transfer: PropTypes.number,\n /* The not active animation deslocation in percentage */\n transferEnter: PropTypes.number,\n }\n\n static defaultProps = {\n className: '',\n type: 'drawerLeft',\n duration: ANIMATION_TIME,\n transfer: ANIMATION_TRANSFER,\n transferEnter: ANIMATION_TRANSFER_ENTER,\n }\n\n get animation() {\n const { isActive, type, duration, transfer, transferEnter } = this.props\n let animation = ANIMATIONS[type]\n if (isActive) {\n animation = animation['from'](duration, transferEnter)\n } else {\n animation = animation['leave'](duration, transfer)\n }\n return animation\n }\n\n render() {\n const { className, children } = this.props\n\n return (\n <div className={className} style={this.animation}>\n {children}\n </div>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_4251ba1e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Animation/animation.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst DRAWER_HORIZONTAL = 'drawerHorizontal'\nconst DRAWER_VERTICAL = 'drawerVertical'\n\nexport const DRAWER_ANIMATION = {\n [DRAWER_HORIZONTAL]: (duration, transfer) => ({\n transform: `translateX(${transfer}%)`,\n transition: `transform ${duration}s ease-in-out`,\n }),\n [DRAWER_VERTICAL]: (duration, transfer) => ({\n transform: `translateY(${transfer}%)`,\n transition: `transform ${duration}s ease-in-out`,\n }),\n}\n\nexport const ANIMATIONS = {\n drawerLeft: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, -transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, transfer),\n },\n drawerRight: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, -transfer),\n },\n drawerTop: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, -transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, transfer),\n },\n drawerBottom: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, -transfer),\n },\n}\n\n```"
}
] |
code_store-on-localhost_9ef0f763
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/slider.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.arrowRight:before {\n display: inline-block;\n width: 48px;\n height: 48px;\n background: url(./images/stre-right.svg); \n content: '';\n}\n.arrowLeft:before {\n display: inline-block;\n width: 48px;\n height: 48px;\n background: url(./images/stre-left.svg); \n content: '';\n}\n\n.dots {}\n```"
}
] |
code_store-on-localhost_885f0fdf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/global.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@import url('~slick-carousel/slick/slick.css');\n@import url('~slick-carousel/slick/slick-theme.css');\n@import url('./slider.css');\n\n/* Fixes uneven arrows distance */\n.slick-prev, .slick-next {\n width: inherit !important;\n height: inherit !important;\n}\n\n/* Clearfix for left arrow */\n.slick-prev {\n left: 0 !important;\n}\n\n/* Clearfix for right arrow */\n.slick-next {\n right: 0 !important;\n}\n\n.slick-dots {\n position: inherit !important;\n}\n\n\n```"
}
] |
code_store-on-localhost_8d0288e3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport Slider from 'react-slick'\nimport ReactResizeDetector from 'react-resize-detector'\nimport { NoSSR } from '../../../../../../vtex.render-runtime'\n\nimport Dots from './components/Dots'\nimport Arrow from './components/Arrow'\n\nimport getItemsPerPage from './utils/ItemsPerPage'\n\nimport './global.css'\nimport slider from './slider.css'\n\nconst VTEXClasses = {\n ARROW_RIGHT_CLASS: `${slider.arrowRight}`,\n ARROW_LEFT_CLASS: `${slider.arrowLeft}`,\n DOTS_CLASS: `${slider.dots}`,\n}\n\n/**\n * Slick Slider Component.\n */\nexport default class SlickSlider extends Component {\n static propTypes = {\n /** Array of items to be rendered inside the slider. */\n children: PropTypes.array.isRequired,\n /** Slider settings. */\n sliderSettings: PropTypes.object,\n /** Makes the items per page to adapt by the slider width. */\n adaptToScreen: PropTypes.bool,\n /** Default item width, it's necessary when the adaptToScreen is true. */\n defaultItemWidth: PropTypes.number,\n /** If the scroll of items is by page or not. */\n scrollByPage: PropTypes.bool,\n /** SSR fallback. */\n ssrFallback: PropTypes.element,\n /** Left arrow custom classes */\n leftArrowClasses: PropTypes.string,\n /** Right arrow custom classes */\n rightArrowClasses: PropTypes.string,\n /** Dots custom classes */\n dotsClasses: PropTypes.string,\n }\n\n getSettings(slideWidth) {\n const {\n sliderSettings,\n adaptToScreen,\n scrollByPage,\n defaultItemWidth,\n children,\n leftArrowClasses,\n rightArrowClasses,\n dotsClasses,\n } = this.props\n const itemsPerPage = getItemsPerPage(\n this._slick,\n slideWidth,\n defaultItemWidth,\n sliderSettings.slidesToShow\n )\n const settings = { ...sliderSettings }\n const numItems = children.length\n\n settings.nextArrow = settings.nextArrow || (\n <Arrow\n customClasses={rightArrowClasses}\n cssClass={VTEXClasses.ARROW_RIGHT_CLASS}\n />\n )\n settings.prevArrow = settings.prevArrow || (\n <Arrow\n customClasses={leftArrowClasses}\n cssClass={VTEXClasses.ARROW_LEFT_CLASS}\n />\n )\n settings.appendDots = dots => (\n <Dots\n dots={dots}\n customClass={dotsClasses}\n cssClass={VTEXClasses.DOTS_CLASS}\n />\n )\n\n if (adaptToScreen) {\n settings.slidesToShow = itemsPerPage\n }\n\n if (scrollByPage) {\n settings.slidesToScroll = settings.slidesToShow\n }\n if (settings.infinite === undefined) {\n settings.infinite = settings.slidesToScroll < numItems\n }\n return settings\n }\n\n render() {\n const component = (\n <ReactResizeDetector handleWidth>\n {width => (\n <Slider\n {...this.getSettings(width)}\n ref={c => {\n this._slick = c\n }}\n >\n {this.props.children}\n </Slider>\n )}\n </ReactResizeDetector>\n )\n if (this.props.ssrFallback) {\n return <NoSSR onSSR={this.props.ssrFallback}>{component}</NoSSR>\n }\n return component\n }\n}\n\n```"
}
] |
code_store-on-localhost_f89a6f8b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductBrand/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { useContext } from 'react'\nimport { Query } from 'react-apollo'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport { changeImageUrlSize } from './urlHelpers'\nimport { loader } from 'graphql.macro'\n\nconst brandLogoQuery = loader('./productBrand.gql')\n\nconst DISPLAY_MODE = {\n LOGO: 'logo',\n TEXT: 'text',\n}\n\nconst CSS_HANDLES = [\n 'productBrandContainer',\n 'productBrandName',\n 'productBrandLogo',\n 'productBrandLogoWrapper',\n 'productBrandLogoLink',\n 'productBrandLogoSpacer',\n 'productBrandNameSpacer',\n]\n\nconst shouldExcludeBrand = (brandName, brandId, excludeList) => {\n if (Array.isArray(excludeList)) {\n return excludeList.includes(brandName) || excludeList.includes(brandId)\n }\n return false\n}\n\nconst useBrandInfoProps = (brandName, brandId) => {\n const productContext = useContext(ProductContext)\n const product = productContext && productContext.product\n if ((brandName && brandId) || !product) {\n return { brandName, brandId }\n }\n return { brandName: product.brand, brandId: product.brandId }\n}\n\nconst ProductBrand = ({\n displayMode = DISPLAY_MODE.LOGO,\n fallbackToText = true,\n loadingPlaceholder = DISPLAY_MODE.LOGO,\n /** TODO: decide whether the prop width should be supported\n * It makes sense at surface, but setting both width and height\n * messes with the alignment of the logo, due to how our image\n * server handles resizing. */\n height = 100,\n excludeBrands,\n logoWithLink,\n brandName: brandNameProp,\n brandId: brandIdProp,\n}) => {\n const { brandName, brandId } = useBrandInfoProps(brandNameProp, brandIdProp)\n const handles = useCssHandles(CSS_HANDLES)\n\n if (!brandName || !brandId) {\n return null\n }\n\n /** Certain brands (e.g. placeholder brands) can be filtered out via theme config */\n if (shouldExcludeBrand(brandName, brandId, excludeBrands)) {\n return null\n }\n\n const brandNameElement = (\n <span className={`${handles.productBrandName}`}>{brandName}</span>\n )\n\n const BrandContainer = ({ children }) => (\n <div className={`${handles.productBrandContainer}`}>{children}</div>\n )\n\n if (displayMode === DISPLAY_MODE.TEXT) {\n return <BrandContainer>{brandNameElement}</BrandContainer>\n }\n\n if (!height) {\n console.warn(\n 'ProductBrand: It is strongly recommended that the height of the logo should be set, to avoid shifting positions of elements while the logo is loading.'\n )\n }\n\n return (\n <Query query={brandLogoQuery} ssr={false} variables={{ id: brandId }}>\n {query => {\n const { data } = query\n if (data && data.brand) {\n const { imageUrl } = data.brand\n if (imageUrl) {\n const dpi = (window && window.devicePixelRatio) || 1\n const logoLink = '/' + brandName + '/b'\n const logoImage = (\n <img\n className={`${handles.productBrandLogo}`}\n src={changeImageUrlSize(\n `/arquivos/ids${imageUrl}`,\n undefined,\n height ? height * dpi : undefined\n )}\n alt={brandName}\n style={{\n height: height || 'auto',\n }}\n />\n )\n\n return (\n <BrandContainer>\n <div\n style={{\n height,\n }}\n className={`${handles.productBrandLogoWrapper}`}\n >\n {/** TODO: Use a smarter Image component that handles VTEX image resizing etc. */}\n {logoWithLink ? (\n <a\n href={logoLink}\n className={`${handles.productBrandLogoLink}`}\n data-testid=\"logo-redirect\"\n >\n {' '}\n {logoImage}{' '}\n </a>\n ) : (\n logoImage\n )}\n </div>\n </BrandContainer>\n )\n }\n\n /** If imageUrl is exactly null, it means no brand\n * logo was uploaded. So it falls back to the brand name,\n * if said fallback is enabled. */\n if (imageUrl === null && fallbackToText) {\n return <BrandContainer>{brandNameElement}</BrandContainer>\n }\n }\n\n /** Renders an empty spacer in the size of the preferred\n * type (i.e. if most brands have no logo, it should render\n * a placeholder in the size of the brand name text; if\n * most brands do have a logo, it should render a spacer\n * in the size of the predefined image size)\n */\n if (loadingPlaceholder === DISPLAY_MODE.LOGO) {\n return (\n <BrandContainer>\n <div\n style={{\n height,\n }}\n className={`${handles.productBrandLogoSpacer}`}\n />\n </BrandContainer>\n )\n }\n if (loadingPlaceholder === DISPLAY_MODE.TEXT && fallbackToText) {\n return (\n <BrandContainer>\n <span className={`${handles.productBrandNameSpacer} o-0`}>\n {brandNameElement}\n </span>\n </BrandContainer>\n )\n }\n\n return null\n }}\n </Query>\n )\n}\n\nProductBrand.propTypes = {\n /** Brand name */\n brandName: PropTypes.string,\n /** Brand id */\n brandId: PropTypes.number,\n /** Whether it should be displayed as a logo or as a text */\n displayMode: PropTypes.oneOf(Object.values(DISPLAY_MODE)),\n /** Whether the loading placeholder should have the size of the logo or the text */\n loadingPlaceholder: PropTypes.oneOf(Object.values(DISPLAY_MODE)),\n /** Whether it should display the name of the brand if there is no logo */\n fallbackToText: PropTypes.bool,\n /** List of brands that should be hidden, if any */\n excludeBrands: PropTypes.arrayOf(\n PropTypes.oneOfType([PropTypes.number, PropTypes.string])\n ),\n /** Height of the logo */\n height: PropTypes.number,\n /** CSS Handler */\n blockClass: PropTypes.string,\n logoWithLink: PropTypes.bool,\n}\n\nexport default ProductBrand\n\n```"
}
] |
code_store-on-localhost_2741c83d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductBrand/productBrand.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Brand($id: Int) {\n brand(id: $id) {\n imageUrl\n }\n}\n\n```"
}
] |
code_store-on-localhost_197ba1a8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductBrand/urlHelpers.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n\nconst httpRegex = new RegExp(/http:\\/\\//)\n\nexport function toHttps(url) {\n return url.replace(httpRegex, 'https://')\n}\n\nexport function cleanImageUrl(imageUrl) {\n const result = baseUrlRegex.exec(imageUrl)\n if (result.length > 0) return result[0]\n}\n\nfunction replaceLegacyFileManagerUrl(imageUrl, width, height) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n if (!isLegacyUrl) return imageUrl\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize(\n imageUrl,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n) {\n if (!imageUrl) return\n typeof width === 'number' && (width = Math.min(width, MAX_WIDTH))\n typeof height === 'number' && (height = Math.min(height, MAX_HEIGHT))\n\n const normalizedImageUrl = replaceLegacyFileManagerUrl(\n imageUrl,\n width,\n height\n )\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\n```"
}
] |
code_store-on-localhost_abd14e4f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/InfoCard/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport classNames from 'classnames'\nimport insane from 'insane'\nimport { bool, string, oneOf } from 'prop-types'\nimport { values } from 'ramda'\nimport React, { memo, useMemo } from 'react'\nimport { injectIntl } from 'react-intl'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport formatIOMessage from '../../../NativeTypes/formatIOMessage'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport CallToAction from './CallToAction'\nimport LinkWrapper from './LinkWrapper'\nimport {\n textPositionTypes,\n textAlignmentTypes,\n callToActionModeTypes,\n textPostionValues,\n textAlignmentValues,\n} from './SchemaTypes'\n\nconst justifyTokens = {\n [textPostionValues.LEFT]: 'justify-start',\n [textPostionValues.CENTER]: 'justify-center',\n [textPostionValues.RIGHT]: 'justify-end',\n}\n\nconst alignTokens = {\n [textAlignmentValues.LEFT]: 'tl',\n [textAlignmentValues.CENTER]: 'tc',\n [textAlignmentValues.RIGHT]: 'tr',\n}\n\nconst itemsTokens = {\n [textAlignmentValues.LEFT]: 'items-start',\n [textAlignmentValues.CENTER]: 'items-center',\n [textAlignmentValues.RIGHT]: 'items-end',\n}\n\nconst flexOrderTokens = {\n [textPostionValues.LEFT]: 'flex-row',\n [textPostionValues.RIGHT]: 'flex-row-reverse',\n}\n\nconst defaultValues = {\n textPosition: textPositionTypes.TEXT_POSITION_LEFT.value,\n textAlignment: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n}\n\nconst getEnumValues = enumObject => values(enumObject).map(({ value }) => value)\nconst getEnumNames = enumObject => values(enumObject).map(({ name }) => name)\n\nconst safelyGetToken = (tokenMap, valueWanted, propName) =>\n tokenMap[valueWanted] || defaultValues[propName]\n\nconst getImageUrl = (isMobile, imageUrl, mobileImageUrl) =>\n !!mobileImageUrl && isMobile ? mobileImageUrl : imageUrl\n\nconst sanitizerConfig = {\n allowedTags: ['p', 'span', 'a', 'div', 'br'],\n allowedAttributes: {\n a: ['class', 'href', 'title', 'target'],\n span: ['class'],\n p: ['class'],\n div: ['class'],\n },\n}\n\nconst sanitizeHtml = input => (input ? insane(input, sanitizerConfig) : null)\n\nconst CSS_HANDLES = [\n 'infoCardContainer',\n 'infoCardTextContainer',\n 'infoCardHeadline',\n 'infoCardSubhead',\n 'infoCardImageContainer',\n 'infoCardImage',\n]\n\nconst InfoCard = ({\n isFullModeStyle,\n headline,\n subhead,\n callToActionMode,\n callToActionText,\n callToActionUrl,\n textPosition,\n textAlignment,\n imageUrl,\n mobileImageUrl,\n imageActionUrl,\n intl,\n htmlId,\n}) => {\n const {\n hints: { mobile },\n } = useRuntime()\n const handles = useCssHandles(CSS_HANDLES)\n const paddingClass =\n textPosition === textPostionValues.LEFT ? 'pr4-ns' : 'pl4-ns'\n\n // We ignore textAlignment tokens when full image mode\n const alignToken = isFullModeStyle\n ? safelyGetToken(alignTokens, textPosition, 'textPosition')\n : safelyGetToken(alignTokens, textAlignment, 'textAlignment')\n const itemsToken = isFullModeStyle\n ? safelyGetToken(itemsTokens, textPosition, 'textPosition')\n : safelyGetToken(itemsTokens, textAlignment, 'textAlignment')\n const justifyToken = safelyGetToken(\n justifyTokens,\n textPosition,\n 'textPosition'\n )\n const flexOrderToken = safelyGetToken(\n flexOrderTokens,\n textPosition,\n 'textPosition'\n )\n\n const finalImageUrl = getImageUrl(\n mobile,\n formatIOMessage({ id: imageUrl, intl }),\n formatIOMessage({ id: mobileImageUrl, intl })\n )\n\n const containerStyle = isFullModeStyle\n ? { backgroundImage: `url(${finalImageUrl})`, backgroundSize: 'cover' }\n : {}\n\n const containerClasses = classNames(\n `${handles.infoCardContainer} items-center`,\n {\n [`flex-ns ${flexOrderToken} bg-base ph2-ns pb2 justify-between`]: !isFullModeStyle,\n [`bg-center bb b--muted-4 flex ${justifyToken}`]: isFullModeStyle,\n }\n )\n\n const textContainerClasses = classNames(\n `${handles.infoCardTextContainer} flex flex-column mw-100`,\n {\n [`w-50-ns ph3-s ${itemsToken} ${paddingClass}`]: !isFullModeStyle,\n [`mh8-ns mh4-s w-40-ns ${itemsToken}`]: isFullModeStyle,\n }\n )\n\n const headlineClasses = `${handles.infoCardHeadline} t-heading-2 mt6 ${alignToken} c-on-base mw-100`\n\n const subheadClasses = `${handles.infoCardSubhead} t-body mt6 c-on-base ${alignToken} mw-100`\n\n const sanitizedHeadline = useMemo(\n () => sanitizeHtml(formatIOMessage({ id: headline, intl })),\n [headline, intl]\n )\n\n const sanitizedSubhead = useMemo(\n () => sanitizeHtml(formatIOMessage({ id: subhead, intl })),\n [intl, subhead]\n )\n\n return (\n <LinkWrapper\n imageActionUrl={formatIOMessage({ id: imageActionUrl, intl })}\n extraCondition={!isFullModeStyle}\n linkProps={{ className: 'no-underline' }}\n >\n <div\n className={containerClasses}\n style={containerStyle}\n data-testid=\"container\"\n id={htmlId}\n >\n <div className={textContainerClasses}>\n {headline && (\n <div\n className={headlineClasses}\n dangerouslySetInnerHTML={{ __html: sanitizedHeadline }}\n />\n )}\n {subhead && (\n <div\n className={subheadClasses}\n dangerouslySetInnerHTML={{ __html: sanitizedSubhead }}\n />\n )}\n <CallToAction\n mode={callToActionMode}\n text={formatIOMessage({ id: callToActionText, intl })}\n url={formatIOMessage({ id: callToActionUrl, intl })}\n />\n </div>\n {!isFullModeStyle && (\n <div className={`${handles.infoCardImageContainer} w-50-ns`}>\n <LinkWrapper\n imageActionUrl={formatIOMessage({ id: imageActionUrl, intl })}\n >\n <img\n className={handles.infoCardImage}\n src={finalImageUrl}\n style={{ objectFit: 'cover' }}\n alt=\"\"\n data-testid=\"half-image\"\n />\n </LinkWrapper>\n </div>\n )}\n </div>\n </LinkWrapper>\n )\n}\n\nconst MemoizedInfoCard = memo(injectIntl(InfoCard))\n\nMemoizedInfoCard.propTypes = {\n blockClass: string,\n isFullModeStyle: bool,\n textPosition: oneOf(getEnumValues(textPositionTypes)),\n headline: string,\n subhead: string,\n callToActionMode: oneOf(getEnumValues(callToActionModeTypes)),\n callToActionText: string,\n callToActionUrl: string,\n imageUrl: string,\n mobileImageUrl: string,\n textAlignment: oneOf(getEnumValues(textAlignmentTypes)),\n imageActionUrl: string,\n htmlId: string,\n}\n\nMemoizedInfoCard.defaultProps = {\n isFullModeStyle: false,\n textPosition: textPositionTypes.TEXT_POSITION_LEFT.value,\n headline: '',\n subhead: '',\n callToActionMode: callToActionModeTypes.CALL_ACTION_BUTTON.value,\n callToActionText: '',\n callToActionUrl: '',\n imageUrl: '',\n mobileImageUrl: '',\n textAlignment: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n}\n\nMemoizedInfoCard.schema = {\n title: 'admin/editor.info-card.title',\n description: 'admin/editor.info-card.description',\n type: 'object',\n properties: {\n isFullModeStyle: {\n title: 'admin/editor.info-card.isFullModeStyle.title',\n description: 'admin/editor.info-card.isFullModeStyle.description',\n type: 'boolean',\n default: false,\n isLayout: true,\n },\n textPosition: {\n title: 'admin/editor.info-card.textPosition.title',\n description: 'admin/editor.info-card.textPosition.description',\n type: 'string',\n enum: getEnumValues(textPositionTypes),\n enumNames: getEnumNames(textPositionTypes),\n default: textPositionTypes.TEXT_POSITION_LEFT.value,\n isLayout: true,\n },\n callToActionMode: {\n title: 'admin/editor.info-card.callToActionMode.title',\n description: 'admin/editor.info-card.callToActionMode.description',\n type: 'string',\n enum: getEnumValues(callToActionModeTypes),\n enumNames: getEnumNames(callToActionModeTypes),\n default: callToActionModeTypes.CALL_ACTION_BUTTON.value,\n isLayout: true,\n },\n textAlignment: {\n title: 'admin/editor.info-card.textAlignment.title',\n description: 'admin/editor.info-card.textAlignment.description',\n type: 'string',\n default: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n enum: getEnumValues(textAlignmentTypes),\n enumNames: getEnumNames(textAlignmentTypes),\n isLayout: true,\n },\n blockClass: {\n title: 'admin/editor.blockClass.title',\n description: 'admin/editor.blockClass.description',\n type: 'string',\n isLayout: true,\n },\n },\n}\n\nexport default MemoizedInfoCard\n\n```"
}
] |
code_store-on-localhost_5d27effd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/InfoCard/CallToAction.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport Button from '../../../Styleguide/Button'\nimport { Link } from '../../../../../../vtex.render-runtime'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport { callActionValues } from './SchemaTypes'\n\nconst CSS_HANDLES = ['infoCardCallActionContainer', 'infoCardCallActionText']\n\nconst CallToAction = ({ mode, text, url }) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n if (mode === callActionValues.NONE) {\n return null\n }\n\n const ActionWrapper = ({ mode, text }) => {\n if (mode === callActionValues.BUTTON) {\n return <Button onClick={() => {}}>{text}</Button>\n }\n\n // Mode is link\n return (\n <p\n className={`${handles.infoCardCallActionText} link t-body b underline c-action-primary`}\n >\n {text}\n </p>\n )\n }\n\n return (\n <Link className={`${handles.infoCardCallActionContainer} mt6 mb6`} to={url}>\n <ActionWrapper text={text} mode={mode} />\n </Link>\n )\n}\n\nexport default CallToAction\n\n```"
}
] |
code_store-on-localhost_e244bff7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/InfoCard/SchemaTypes.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const textPostionValues = {\n LEFT: 'left',\n CENTER: 'center',\n RIGHT: 'right',\n}\n\nexport const textAlignmentValues = {\n LEFT: 'left',\n CENTER: 'center',\n RIGHT: 'right',\n}\n\nexport const callActionValues = {\n NONE: 'none',\n BUTTON: 'button',\n LINK: 'link',\n}\n\nexport const textPositionTypes = {\n TEXT_POSITION_LEFT: {\n name: 'admin/editor.info-card.textPosition.left',\n value: textPostionValues.LEFT,\n },\n TEXT_POSITION_CENTER: {\n name: 'admin/editor.info-card.textPosition.center',\n value: textPostionValues.CENTER,\n },\n TEXT_POSITION_RIGHT: {\n name: 'admin/editor.info-card.textPosition.right',\n value: textPostionValues.RIGHT,\n },\n}\n\nexport const textAlignmentTypes = {\n TEXT_ALIGNMENT_LEFT: {\n name: 'admin/editor.info-card.textAlignment.left',\n value: textAlignmentValues.LEFT,\n },\n TEXT_ALIGNMENT_CENTER: {\n name: 'admin/editor.info-card.textAlignment.center',\n value: textAlignmentValues.CENTER,\n },\n TEXT_ALIGNMENT_RIGHT: {\n name: 'admin/editor.info-card.textAlignment.right',\n value: textAlignmentValues.RIGHT,\n },\n}\n\nexport const callToActionModeTypes = {\n CALL_ACTION_NONE: {\n name: 'admin/editor.info-card.callAction.none',\n value: callActionValues.NONE,\n },\n CALL_ACTION_BUTTON: {\n name: 'admin/editor.info-card.callAction.button',\n value: callActionValues.BUTTON,\n },\n CALL_ACTION_LINK: {\n name: 'admin/editor.info-card.callAction.link',\n value: callActionValues.LINK,\n },\n}\n\n```"
}
] |
code_store-on-localhost_66e22874
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/InfoCard/LinkWrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { bool, string, object, node } from 'prop-types'\nimport { Link } from '../../../../../../vtex.render-runtime'\n\nconst LinkWrapper = ({\n imageActionUrl,\n children,\n extraCondition,\n linkProps = {},\n}) => {\n if (!imageActionUrl || imageActionUrl.length === 0 || extraCondition) {\n return <Fragment>{children}</Fragment>\n }\n\n return (\n <Link {...linkProps} to={imageActionUrl}>\n {children}\n </Link>\n )\n}\n\nLinkWrapper.propTypes = {\n imageActionUrl: string,\n children: node,\n extraCondition: bool,\n linkProps: object,\n}\n\nexport default LinkWrapper\n\n```"
}
] |
code_store-on-localhost_df8d3a86
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductSpecifications/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport useProduct from '../../../ProductContext/useProduct'\nimport { isEmpty, propOr, propEq } from 'ramda'\n\nimport ProductSpecifications from './index'\n\nconst getSpecifications = productContext => {\n if (!productContext || isEmpty(productContext)) {\n return []\n }\n const { product } = productContext\n const specificationGroups = propOr([], 'specificationGroups', product)\n const groupWithAll = specificationGroups.find(\n propEq('name', 'allSpecifications')\n )\n const allSpecifications = groupWithAll ? groupWithAll.specifications : []\n return allSpecifications\n}\n\nconst ProductSpecificationsWrapper = ({\n hiddenSpecifications,\n visibleSpecifications,\n specifications: propsSpecifications,\n tabsMode, // This is a legacy prop passed by product-details\n showSpecificationsTab = false,\n collapsible = 'always',\n}) => {\n const productContext = useProduct()\n\n const specifications =\n propsSpecifications || getSpecifications(productContext)\n\n return (\n <ProductSpecifications\n hiddenSpecifications={hiddenSpecifications}\n visibleSpecifications={visibleSpecifications}\n tabsMode={tabsMode != null ? tabsMode : showSpecificationsTab}\n specifications={specifications}\n collapsible={collapsible}\n />\n )\n}\n\nProductSpecificationsWrapper.getSchema = () => {\n return {\n title: 'admin/editor.product-specifications.title',\n description: '',\n type: 'object',\n properties: {\n hiddenSpecifications: {\n items: {\n default: '',\n type: 'string',\n title: 'admin/editor.product-specifications.items.title'\n },\n description: 'admin/editor.product-specifications.hidden-specifications.description',\n title: 'admin/editor.product-specifications.hidden-specifications.title',\n type: 'array'\n },\n visibleSpecifications: {\n items: {\n default: '',\n type: 'string',\n title: 'admin/editor.product-specifications.items.title'\n },\n description: 'admin/editor.product-specifications.visible-specifications.description',\n title: 'admin/editor.product-specifications.visible-specifications.title',\n type: 'array'\n }\n }\n }\n}\n\nexport default ProductSpecificationsWrapper\n\n```"
}
] |
code_store-on-localhost_1bf7a9e6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductSpecifications/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useState } from 'react'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage } from 'react-intl'\nimport HtmlParser from 'react-html-parser'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\nimport Tabs from '../../../Styleguide/Tabs'\nimport Tab from '../../../Styleguide/Tab'\nimport useDevice from '../../../DeviceDetector/useDevice'\n\nimport GradientCollapse from '../GradientCollapse/index'\n\nconst CSS_HANDLES = [\n 'specificationsTableContainer',\n 'specificationsTabsContainer',\n 'specificationsTitle',\n 'specificationsTable',\n 'specificationsTab',\n 'specificationsTablePropertyHeading',\n 'specificationsTableSpecificationHeading',\n 'specificationItemProperty',\n 'specificationItemSpecifications',\n]\n\n/**\n * Product Specification Component.\n * Render the technical specifications of a product. Can be displayed in two views: Table view or Tabs view.\n */\nconst ProductSpecifications = ({\n tabsMode,\n specifications,\n collapsible = 'always',\n hiddenSpecifications,\n visibleSpecifications,\n shouldCollapseInTabChange,\n}) => {\n const [currentTab, setCurrentTab] = useState(0)\n const [collapsed, setCollapsed] = useState(true)\n const handles = useCssHandles(CSS_HANDLES)\n const { isMobile } = useDevice()\n\n const shouldBeCollapsible = Boolean(\n collapsible === 'always' ||\n (collapsible === 'mobileOnly' && isMobile) ||\n (collapsible === 'desktopOnly' && !isMobile)\n )\n\n const handleTabChange = tabIndex => {\n setCurrentTab(tabIndex)\n if (shouldCollapseInTabChange) {\n setCollapsed(true)\n }\n }\n\n const getSpecificationItems = () => {\n const mappedSpecifications = specifications.map(specification => {\n return {\n property: specification.name,\n specifications: specification.values.join(\", \"),\n }\n })\n\n if (visibleSpecifications && hiddenSpecifications) {\n console.warn(\n 'A product-specification block is using both visibleSpecifications and hiddenSpecifications props at the same time. Please choose only one of them.'\n )\n\n return mappedSpecifications\n }\n\n if (visibleSpecifications) {\n return mappedSpecifications.filter(specification =>\n visibleSpecifications.find(\n filter =>\n specification.property.toLowerCase() === filter.toLowerCase()\n )\n )\n }\n if (hiddenSpecifications) {\n return mappedSpecifications.filter(\n specification =>\n !hiddenSpecifications.find(\n filter =>\n specification.property.toLowerCase() === filter.toLowerCase()\n )\n )\n }\n\n return mappedSpecifications\n }\n\n const specificationItems = getSpecificationItems()\n\n const specificationTitle = (\n <FormattedMessage id=\"store/technicalspecifications.title\">\n {txt => (\n <h2 className={`${handles.specificationsTitle} t-heading-5 mb5 mt0`}>\n {HtmlParser(txt)}\n </h2>\n )}\n </FormattedMessage>\n )\n\n const specificationsTable = (\n <table\n className={`${handles.specificationsTable} w-100 bg-base border-collapse`}\n >\n <thead>\n <tr>\n <th\n className={`${handles.specificationsTablePropertyHeading} w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5`}\n >\n <FormattedMessage id=\"store/product-description.property\" />\n </th>\n <th\n className={`${handles.specificationsTableSpecificationHeading} w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5`}\n >\n <FormattedMessage id=\"store/product-description.specification\" />\n </th>\n </tr>\n </thead>\n <tbody>\n {specificationItems.map((specification, i) => (\n <tr key={i}>\n <td\n className={`${handles.specificationItemProperty} w-50 b--muted-4 bb pa5`}\n >\n {HtmlParser(specification.property)}\n </td>\n <td\n className={`${handles.specificationItemSpecifications} w-50 b--muted-4 bb pa5`}\n >\n {HtmlParser(specification.specifications)}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )\n\n const tableView = (\n <Fragment>\n {specifications.length > 0 && (\n <div\n className={`${handles.specificationsTableContainer} mt9 mt0-l pl8-l`}\n >\n {specificationTitle}\n {shouldBeCollapsible ? (\n <GradientCollapse\n collapseHeight={220}\n collapsed={collapsed}\n onCollapsedChange={(_, newValue) => setCollapsed(newValue)}\n >\n {specificationsTable}\n </GradientCollapse>\n ) : (\n specificationsTable\n )}\n </div>\n )}\n </Fragment>\n )\n\n const tabsView = (\n <div className={`${handles.specificationsTabsContainer} pt8`}>\n {specificationTitle}\n <Tabs fullWidth>\n {specificationItems.map((specification, i) => (\n <Tab\n key={i}\n label={HtmlParser(specification.property)}\n active={currentTab === i}\n onClick={() => handleTabChange(i)}\n >\n <div className={`${handles.specificationsTab} pb8 c-muted-1 pv6`}>\n {shouldBeCollapsible ? (\n <GradientCollapse\n collapseHeight={220}\n collapsed={collapsed}\n onCollapsedChange={(_, newValue) => setCollapsed(newValue)}\n >\n {HtmlParser(specification.specifications)}\n </GradientCollapse>\n ) : (\n HtmlParser(specification.specifications)\n )}\n </div>\n </Tab>\n ))}\n </Tabs>\n </div>\n )\n\n return tabsMode ? tabsView : tableView\n}\n\nProductSpecifications.defaultProps = {\n specifications: [],\n tabsMode: false,\n shouldCollapseInTabChange: false,\n}\n\nProductSpecifications.propTypes = {\n /** Specifications that will be displayed on the table */\n specifications: PropTypes.arrayOf(\n PropTypes.shape({\n /** Specification name */\n name: PropTypes.string.isRequired,\n /** Specifications value */\n values: PropTypes.arrayOf(PropTypes.string).isRequired,\n })\n ),\n /** If should collapse when a tab is changed */\n shouldCollapseInTabChange: PropTypes.bool,\n /** Tabs mode view */\n tabsMode: PropTypes.bool,\n /** Specifications which will be shown exclusively (optional) */\n visibleSpecifications: PropTypes.array,\n /** Specifications which will be hidden (optional) */\n hiddenSpecifications: PropTypes.array,\n collapsible: PropTypes.oneOf([\n 'always',\n 'never',\n 'desktopOnly',\n 'mobileOnly',\n ]),\n}\n\nexport default ProductSpecifications\n\n```"
}
] |
code_store-on-localhost_c5d46530
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Container/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nimport styles from './Container.css'\n\nconst render = ({ className, children, ...props }, ref) => {\n const classes = classNames(\n styles.container,\n 'ph3 ph5-m ph2-xl mw9 center',\n className\n )\n\n return (\n <section {...props} className={classes} ref={ref}>\n {children}\n </section>\n )\n}\n\nrender.displayName = 'Container'\n\nconst Container = React.forwardRef(render)\n\nContainer.propTypes = {\n children: PropTypes.node,\n className: PropTypes.string,\n}\n\nexport default Container\n\n```"
}
] |
code_store-on-localhost_b5e33d3a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* Product Image CSS Module\n*/\n\n.productVideo { }\n\n.productImage { }\n\n.carouselGaleryCursor {\n cursor: url('./components/Carousel/cursor.svg') 8 8, default;\n}\n\n.carouselGaleryThumbs :global(.swiper-slide) {\n height: auto;\n}\n\n.carouselIconCaretRight,\n.carouselIconCaretLeft {\n stroke: white;\n stroke-width: 0.5px;\n -webkit-filter: drop-shadow(0px 1px 1px #cacbcc);\n filter: drop-shadow(0px 1px 1px #cacbcc);\n}\n\n.carouselCursorDefault:hover {\n cursor: default;\n}\n\n.carouselImagePlaceholder {\n}\n\n/** Overrides figure css declaration from vtex-tachyons, which\n * for some reason adds margin to all figure elements */\n.figure {\n margin: 0;\n}\n\n.gradientBaseBottom {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(transparent, white);\n}\n\n.gradientBaseTop {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(white, transparent);\n}\n\n.gradientBaseRight {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(90deg, transparent, white);\n}\n\n.gradientBaseLeft {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(90deg, white, transparent);\n}\n\n```"
}
] |
code_store-on-localhost_68aaf90c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo } from 'react'\nimport useProduct from '../../../ProductContext/useProduct'\nimport useResponsiveValues from '../../../ResponsiveValues/useResponsiveValues'\nimport { path, map, pick } from 'ramda'\n\nimport ProductImages from './index'\nimport generateImageConfig from './utils/generateImageConfig'\nimport { THUMBS_ORIENTATION, THUMBS_POSITION_HORIZONTAL } from './utils/enums'\n\nconst ProductImagesWrapper = props => {\n const valuesFromContext = useProduct() || {}\n const { aspectRatio, maxHeight, showNavigationArrows, showPaginationDots } = useResponsiveValues(\n pick(['aspectRatio', 'maxHeight', 'showNavigationArrows', 'showPaginationDots'], props)\n )\n const { selectedItem } = valuesFromContext\n const images = useMemo(\n () =>\n props.images != null\n ? props.images\n : map(generateImageConfig, path(['images'], selectedItem) || []),\n [props.images, selectedItem]\n )\n\n const videos = useMemo(\n () =>\n props.videos != null\n ? props.videos\n : path(['videos'], selectedItem) || [],\n [props.videos, selectedItem]\n )\n\n return (\n <ProductImages\n images={images}\n videos={videos}\n zoomProps={props.zoomProps}\n hiddenImages={props.hiddenImages}\n position={props.position || props.thumbnailPosition} //thumbnailPosition is a legacy prop from product-details\n displayThumbnailsArrows={props.displayThumbnailsArrows}\n thumbnailsOrientation={props.thumbnailsOrientation}\n zoomMode={props.zoomMode}\n zoomFactor={props.zoomFactor}\n aspectRatio={aspectRatio}\n maxHeight={maxHeight}\n thumbnailAspectRatio={props.thumbnailAspectRatio}\n thumbnailMaxHeight={props.thumbnailMaxHeight}\n showNavigationArrows={showNavigationArrows}\n showPaginationDots={showPaginationDots}\n // Deprecated\n zoomProps={props.zoomProps}\n />\n )\n}\n\nProductImagesWrapper.getSchema = ({ zoomProps: { zoomType } = {} }) => ({\n title: 'admin/editor.product-images.title',\n description: 'admin/editor.product-images.description',\n type: 'object',\n properties: {\n zoomProps: {\n title: 'admin/editor.product-images.zoomOptions.title',\n type: 'object',\n properties: {\n zoomType: {\n title: 'admin/editor.product-images.zoomType.title',\n type: 'string',\n enum: ['gallery', 'in-page', 'no-zoom'],\n enumNames: [\n 'admin/editor.product-images.gallery',\n 'admin/editor.product-images.in-page',\n 'admin/editor.product-images.no-zoom',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: 'no-zoom',\n },\n ...(zoomType === 'gallery' && {\n bgOpacity: {\n title: 'admin/editor.product-images.bgopacity.title',\n type: 'number',\n minimum: 0.0,\n maximum: 1.0,\n multipleOf: 0.01,\n default: 0.8,\n },\n }),\n },\n },\n thumbnailsOrientation: {\n title: 'admin/editor.product-images.thumbnailsOrientation.title',\n type: 'string',\n enum: [THUMBS_ORIENTATION.VERTICAL, THUMBS_ORIENTATION.HORIZONTAL],\n enumNames: [\n 'admin/editor.product-images.vertical',\n 'admin/editor.product-images.horizontal',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: THUMBS_ORIENTATION.VERTICAL,\n isLayout: true,\n },\n position: {\n title: 'admin/editor.product-images.position.title',\n description: 'admin/editor.product-images.position.description',\n type: 'string',\n enum: [THUMBS_POSITION_HORIZONTAL.LEFT, THUMBS_POSITION_HORIZONTAL.RIGHT],\n enumNames: [\n 'admin/editor.product-images.left',\n 'admin/editor.product-images.right',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: THUMBS_POSITION_HORIZONTAL.LEFT,\n isLayout: true,\n },\n displayThumbnailsArrows: {\n title: 'admin/editor.product-images.displayThumbnailsArrows.title',\n type: 'boolean',\n default: false,\n isLayout: true,\n },\n },\n})\n\nexport default ProductImagesWrapper\n\n```"
}
] |
code_store-on-localhost_6bf8e404
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { useMemo } from 'react'\n\nimport Carousel from './components/Carousel'\nimport {\n THUMBS_ORIENTATION,\n THUMBS_POSITION_HORIZONTAL,\n DEFAULT_EXCLUDE_IMAGE_WITH,\n} from './utils/enums'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nconst CSS_HANDLES = ['content', 'productImagesContainer']\n\nconst ProductImages = ({\n position,\n displayThumbnailsArrows,\n hiddenImages,\n images: allImages,\n videos,\n thumbnailsOrientation,\n aspectRatio,\n maxHeight,\n thumbnailAspectRatio,\n thumbnailMaxHeight,\n showNavigationArrows,\n showPaginationDots,\n zoomMode,\n zoomFactor,\n // Deprecated\n zoomProps,\n}) => {\n if (hiddenImages && !Array.isArray(hiddenImages)) {\n hiddenImages = [hiddenImages]\n }\n\n const excludeImageRegexes = hiddenImages && hiddenImages.map(text => new RegExp(text, 'i'))\n const handles = useCssHandles(CSS_HANDLES)\n\n const images = allImages.filter(image =>\n !image.imageLabel || !excludeImageRegexes.some(regex => regex.test(image.imageLabel))\n )\n\n const slides = useMemo(() => {\n if (!images.length && !videos.length) return []\n\n return [\n ...images.map(image => ({\n type: 'image',\n url: image.imageUrls ? image.imageUrls[0] : image.imageUrl,\n alt: image.imageText,\n thumbUrl: image.thumbnailUrl || image.imageUrl,\n })),\n ...videos.map(video => ({\n type: 'video',\n src: video.videoUrl,\n thumbWidth: 300,\n })),\n ]\n }, [images, videos])\n\n return (\n <div className={`${handles.productImagesContainer} ${handles.content} w-100`}>\n <Carousel\n slides={slides}\n position={position}\n displayThumbnailsArrows={displayThumbnailsArrows}\n thumbnailsOrientation={thumbnailsOrientation}\n aspectRatio={aspectRatio}\n maxHeight={maxHeight}\n thumbnailAspectRatio={thumbnailAspectRatio}\n thumbnailMaxHeight={thumbnailMaxHeight}\n showNavigationArrows={showNavigationArrows}\n showPaginationDots={showPaginationDots}\n zoomMode={zoomMode}\n zoomFactor={zoomFactor}\n // Deprecated\n zoomProps={zoomProps}\n />\n </div>\n )\n}\n\nProductImages.propTypes = {\n /** The position of the thumbs */\n position: PropTypes.oneOf([\n THUMBS_POSITION_HORIZONTAL.LEFT,\n THUMBS_POSITION_HORIZONTAL.RIGHT,\n ]),\n thumbnailsOrientation: PropTypes.oneOf([\n THUMBS_ORIENTATION.VERTICAL,\n THUMBS_ORIENTATION.HORIZONTAL,\n ]),\n /** This is a necessary prop if you're using SKUSelector to display color images\n * (like a image with only green to represent an SKU of something green) and you\n * want to not display this image in the ProductImages component, to do this you\n * just have to upload the image in the catalog with the value of this prop inside the imageText property */\n hiddenImages: PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.arrayOf(PropTypes.string),\n ]),\n /** Array of images to be passed for the Thumbnail Slider component as a props */\n images: PropTypes.arrayOf(\n PropTypes.shape({\n /** URL of the image */\n imageUrls: PropTypes.arrayOf(PropTypes.string.isRequired),\n /** Size thresholds used to choose each image */\n thresholds: PropTypes.arrayOf(PropTypes.number),\n /** URL of the image thumbnail */\n thumbnailUrl: PropTypes.string,\n /** Text that describes the image */\n imageText: PropTypes.string.isRequired,\n })\n ),\n videos: PropTypes.arrayOf(\n PropTypes.shape({\n videoUrl: PropTypes.string,\n })\n ),\n zoomProps: PropTypes.shape({\n zoomType: PropTypes.string,\n }),\n displayThumbnailsArrows: PropTypes.bool,\n}\n\nProductImages.defaultProps = {\n images: [],\n position: THUMBS_POSITION_HORIZONTAL.LEFT,\n zoomProps: { zoomType: 'in-page' },\n thumbnailsOrientation: THUMBS_ORIENTATION.VERTICAL,\n displayThumbnailsArrows: false,\n hiddenImages: DEFAULT_EXCLUDE_IMAGE_WITH,\n}\n\nexport default ProductImages\n\n```"
}
] |
code_store-on-localhost_95e76c92
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Logo/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.sizeDesktop {\n max-width: 150px;\n max-height: 75px;\n min-width: 120px;\n}\n\n.sizeMobile {\n max-width: 90px;\n max-height: 40px;\n min-width: 72px;\n}\n\n```"
}
] |
code_store-on-localhost_5b479fd2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Logo/Placeholder.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nexport default ({ width, height, title }) => (\n <svg\n width={width}\n height={height}\n viewBox=\"0 0 142 80\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <title>{title}</title>\n <rect width=\"142\" height=\"80\" fill=\"#F2F4F5\" stroke=\"#E3E4E6\" />\n <path\n d=\"M84.8156 47.5402L77.8157 33.9407C77.5479 33.4222 77.0282 33.0703 76.4349 33.0108C75.8434 32.9445 75.2572 33.1876 74.8844 33.6381L68.8854 40.9206L64.9707 38.386C64.5717 38.1293 64.08 38.0392 63.6162 38.1412C63.149 38.2432 62.7447 38.5271 62.4997 38.9249L57.2497 47.4246C56.9242 47.9499 56.9172 48.6026 57.227 49.1381C57.5367 49.6719 58.1195 50 58.7495 50H83.2494C83.8567 50 84.4184 49.694 84.7386 49.1925C85.0589 48.691 85.0851 48.0655 84.8156 47.5402Z\"\n fill=\"#CACBCC\"\n />\n <path\n d=\"M67.5 33C69.433 33 71 31.433 71 29.5C71 27.567 69.433 26 67.5 26C65.567 26 64 27.567 64 29.5C64 31.433 65.567 33 67.5 33Z\"\n fill=\"#CACBCC\"\n />\n <defs>\n <clipPath id=\"clip0\">\n <rect width=\"127\" height=\"65\" fill=\"white\" />\n </clipPath>\n </defs>\n </svg>\n)\n\n```"
}
] |
code_store-on-localhost_6a2fc135
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Logo/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { Link, useRuntime } from '../../../../../../vtex.render-runtime'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n// import * as Amp from 'react-amphtml'\n\nimport Placeholder from './Placeholder'\n\nimport styles from './styles.css'\n\nconst CSS_HANDLES = ['logoLink', 'logoImage', 'logoContainer']\n\n/**\n * Logo of the store\n */\nconst Logo = ({\n url,\n href,\n width,\n height,\n title,\n mobileWidth,\n mobileHeight,\n}) => {\n const {\n // amp,\n account,\n hints: { mobile },\n } = useRuntime()\n const handles = useCssHandles(CSS_HANDLES)\n const logoClassNames = classNames('store-logo', handles.logoContainer, {\n [styles.sizeDesktop]: !mobile,\n [styles.sizeMobile]: mobile,\n })\n\n const imgWidth = mobile && mobileWidth ? mobileWidth : width\n const imgHeight = mobile && mobileHeight ? mobileHeight : height\n\n const imageUrl = url && url.replace(/{{account}}/g, account)\n\n let image = null\n\n // if (amp && url) {\n // image = (\n // <Amp.AmpImg\n // specName=\"default\"\n // width={imgWidth}\n // height={imgHeight}\n // alt={title}\n // src={imageUrl}\n // className={handles.logoImage}\n // />\n // )\n // } else if (url) {\n image = (\n <img\n src={imageUrl}\n width={imgWidth}\n height={imgHeight}\n alt={title}\n className={handles.logoImage}\n />\n )\n // }\n\n const logo = (\n <span className={`${logoClassNames} pv4 ph6`}>\n {url ? (\n image\n ) : (\n <Placeholder width={width} height={height} title={title} />\n )}\n </span>\n )\n\n return href ? (\n <Link to={href} className={handles.logoLink}>\n {logo}\n </Link>\n ) : (\n logo\n )\n}\n\nLogo.propTypes = {\n /** URL of the logo */\n url: PropTypes.string,\n /** Title to be displayed as alt text */\n title: PropTypes.string.isRequired,\n /** Logo's width */\n width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /** Logo's height */\n height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n}\n\nLogo.schema = {\n title: 'admin/editor.logo.title',\n description: 'admin/editor.logo.description',\n type: 'object',\n properties: {\n href: {\n title: 'admin/editor.logo.href.title',\n description: 'admin/editor.logo.href.description',\n type: 'string',\n },\n url: {\n title: 'admin/editor.logo.url.title',\n description: 'admin/editor.logo.url.description',\n type: 'string',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n width: {\n title: 'admin/editor.logo.width.title',\n description: 'admin/editor.logo.width.description',\n type: 'number',\n isLayout: true,\n },\n height: {\n title: 'admin/editor.logo.height.title',\n description: 'admin/editor.logo.height.description',\n type: 'number',\n isLayout: true,\n },\n title: {\n title: 'admin/editor.logo.title.title',\n description: 'admin/editor.logo.title.description',\n type: 'string',\n },\n mobileWidth: {\n title: 'admin/editor.logo.mobileWidth.title',\n description: 'admin/editor.logo.mobileWidth.description',\n type: 'number',\n isLayout: true,\n },\n mobileHeight: {\n title: 'admin/editor.logo.mobileHeight.title',\n description: 'admin/editor.logo.mobileHeight.description',\n type: 'number',\n isLayout: true,\n },\n },\n}\n\nexport default Logo\n\n```"
}
] |
code_store-on-localhost_05f9943f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/GradientCollapse/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* GradientCollapse CSS Modules\n*/\n\n.fadeBottom {\n background-image: linear-gradient(transparent, white);\n}\n\n.pointerEventsNone {\n pointer-events: none;\n}\n\n.pointerEventsAuto {\n pointer-events: auto;\n}\n```"
}
] |
code_store-on-localhost_dddd6590
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/GradientCollapse/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useState, useRef, useLayoutEffect } from 'react'\nimport PropTypes from 'prop-types'\nimport { Transition } from 'react-transition-group'\nimport debounce from 'debounce'\nimport { FormattedMessage } from 'react-intl'\nimport classNames from 'classnames'\nimport styles from './styles.css'\n\nconst transitionStyle = transitionTime => ({\n transition: `${transitionTime}ms ease-in-out`,\n})\n\nconst fadeBottomClasses = state =>\n classNames(styles.fadeBottom, { 'o-0': state === 'entered' }, 'w-100 h-50')\nconst pointerEventsAutoClasses = state =>\n classNames(\n styles.pointerEventsAuto,\n {\n 'bg-transparent': state === 'entered',\n 'bg-base': state != 'entered',\n },\n 'tc w-100'\n )\n\nfunction GradientCollapse(props) {\n const {\n children,\n collapseHeight,\n onCollapsedChange,\n collapsed: collapsedProp,\n } = props\n const [collapsed, setCollapsed] = useState(collapsedProp)\n const [prevCollapsedProp, setPrevCollapsedProp] = useState(collapsedProp)\n const [maxHeight, setMaxHeight] = useState('auto')\n const [collapseVisible, setCollapseVisible] = useState(true)\n const wrapper = useRef()\n\n if (prevCollapsedProp !== collapsedProp) {\n setCollapsed(collapsedProp)\n setPrevCollapsedProp(collapsedProp)\n }\n\n const calcMaxHeight = () => {\n const wrapperEl = wrapper.current\n // check if the content is smaller than the passed\n // height to collapse\n if (wrapperEl.scrollHeight > collapseHeight) {\n setMaxHeight(wrapperEl.scrollHeight + 60)\n setCollapseVisible(true)\n } else {\n setCollapseVisible(false)\n setMaxHeight('auto')\n }\n }\n\n const handleCollapsedChange = (e, newValue) => {\n setCollapsed(newValue)\n setPrevCollapsedProp(collapsedProp)\n\n if (onCollapsedChange) {\n onCollapsedChange(e, newValue)\n }\n }\n\n const debouncedCalcMaxHeight = debounce(calcMaxHeight, 500)\n useLayoutEffect(() => {\n window.addEventListener('resize', debouncedCalcMaxHeight)\n calcMaxHeight()\n return () => {\n window.removeEventListener('resize', debouncedCalcMaxHeight)\n }\n })\n\n const height = collapseVisible && collapsed ? collapseHeight : maxHeight\n const transitionTime = 600\n const fadeOutTime = 400\n\n const pointerEventsNoneClasses = classNames(\n styles.pointerEventsNone,\n { flex: collapseVisible, dn: !collapseVisible },\n 'absolute bottom-0 w-100 h-100 flex-column justify-end'\n )\n\n return (\n <Transition timeout={transitionTime} in={!collapsed}>\n {state => (\n <div\n style={{\n ...transitionStyle(transitionTime),\n height,\n overflow: 'hidden',\n display: 'block',\n }}\n onTransitionEnd={calcMaxHeight}\n className=\"relative\"\n >\n <div ref={wrapper} className=\"h-auto\">\n {children}\n </div>\n <div className={pointerEventsNoneClasses}>\n <div\n style={transitionStyle(fadeOutTime)}\n className={fadeBottomClasses(state)}\n />\n <div className={pointerEventsAutoClasses(state)}>\n <button\n onClick={e => handleCollapsedChange(e, !collapsed)}\n className=\"c-action-primary t-action pointer ma5 bn outline-0\"\n >\n {state === 'entered' || (collapsed && state !== 'exited') ? (\n <FormattedMessage id=\"store/product-description.collapse.showLess\" />\n ) : (\n <FormattedMessage id=\"store/product-description.collapse.showMore\" />\n )}\n </button>\n </div>\n </div>\n </div>\n )}\n </Transition>\n )\n}\n\nGradientCollapse.propTypes = {\n /** Maximum height collapsed */\n collapseHeight: PropTypes.number.isRequired,\n collapsed: PropTypes.bool,\n children: PropTypes.node,\n onCollapsedChange: PropTypes.func,\n}\n\nGradientCollapse.defaultProps = {\n collapsed: true,\n}\n\nexport default GradientCollapse\n\n```"
}
] |
code_store-on-localhost_086a5306
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CollectionBadges/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* CollectionBadges CSS Module\n*/\n\n.collectionContainer {}\n\n.item {}\n```"
}
] |
code_store-on-localhost_88641a33
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CollectionBadges/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport { CollectionBadgeItem } from './components/CollectionBadgeItem'\n\nimport styles from './styles.css'\n\n/**\n * Collection Badges component.\n * Encapsulates and displays a responsive list of Collection Badges.\n */\nconst CollectionBadges = ({ collectionBadgesText, children }) => (\n <div className={`${styles.collectionContainer} relative dib w-100`}>\n {children}\n <div className=\"inline-flex justify-end absolute w-100 bottom-0 left-0\">\n {collectionBadgesText.map((collectionBadgeText, index) => (\n <CollectionBadgeItem key={collectionBadgeText + index}>\n {collectionBadgeText}\n </CollectionBadgeItem>\n ))}\n </div>\n </div>\n)\n\nCollectionBadges.propTypes = {\n /** Array of collection badges text */\n collectionBadgesText: PropTypes.array.isRequired,\n /** Children component that should be render inside the collection badge item */\n children: PropTypes.node.isRequired,\n}\n\nCollectionBadges.defaultProps = {\n collectionBadgesText: [],\n}\n\nexport default CollectionBadges\n\n```"
}
] |
code_store-on-localhost_125d3d97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* ProductPrice CSS Modules\n*/\n.priceContainer {}\n.listPrice {}\n.listPriceLabel {}\n.listPriceValue {}\n\n.sellingPriceContainer {}\n.sellingPrice {} /* deprecated */\n.sellingPriceLabel {}\n.sellingPriceValue {}\n.sellingPriceValue--range {}\n\n.savingPrice {}\n.savingPriceValue {}\n\n.installmentsPrice {}\n.interestRatePrice {}\n\n.priceLoaderContainer {}\n.listPriceLoader {}\n.sellingPriceLabelLoader {}\n.sellingPriceLoader {}\n.installmentsPriceLoader {}\n.savingsPriceLoader {}\n```"
}
] |
code_store-on-localhost_cf03ed12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport { path, isEmpty, has } from 'ramda'\n\nimport ProductPrice from './index'\n\nconst styles = {\n 'vtex-price-list__container--loader': {\n x: 0,\n width: '7.219em',\n height: '0.56em',\n },\n 'vtex-price-selling__label--loader': {\n x: 0,\n y: '2em',\n width: '2.85em',\n height: '1.08em',\n },\n 'vtex-price-selling--loader': {\n x: '3.25em',\n y: '0.86em',\n width: '14.572em',\n height: '2.176em',\n },\n 'vtex-price-installments--loader': {\n x: 0,\n y: '3.75em',\n width: '12em',\n height: '0.825em',\n },\n 'vtex-price-savings--loader': {\n x: 0,\n y: '5em',\n width: '10em',\n height: '0.686em',\n },\n}\n\nconst isAvailable = commertialOffer =>\n Number.isNaN(+path(['AvailableQuantity'], commertialOffer)) ||\n path(['AvailableQuantity'], commertialOffer) > 0\n\nconst ProductPriceWrapper = ({\n labelSellingPrice,\n showListPrice,\n showInstallments,\n showLabels,\n showSavings,\n ...props\n}) => {\n const valuesFromContext = useContext(ProductContext)\n\n const {\n className,\n listPriceContainerClass,\n listPriceLabelClass,\n listPriceClass,\n sellingPriceContainerClass,\n sellingPriceLabelClass,\n sellingPriceClass,\n savingsContainerClass,\n savingsClass,\n interestRateClass,\n installmentContainerClass,\n installmentClass,\n loaderClass,\n listPrice,\n sellingPrice,\n installments,\n } = props\n\n const productPriceProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext) || (!has('query', props) && !has('params', props))) {\n return {\n ...props,\n labelSellingPrice,\n showListPrice,\n showInstallments,\n showLabels,\n showSavings,\n showProductPrice: true,\n }\n }\n\n const { selectedItem } = valuesFromContext\n const commertialOffer = path(['sellers', 0, 'commertialOffer'], selectedItem)\n\n return {\n ...props,\n styles: props.styles || styles,\n className: className || '',\n listPriceContainerClass: listPriceContainerClass || 't-small-s t-small-ns c-muted-2 mb2',\n sellingPriceLabelClass: sellingPriceLabelClass || 't-heading-6-s t-heading-5-ns dib',\n listPriceLabelClass: listPriceLabelClass || 'dib strike',\n listPriceClass: listPriceClass || 'ph2 dib strike',\n sellingPriceContainerClass: sellingPriceContainerClass || 'pv1 b c-on-base',\n sellingPriceClass: sellingPriceClass || 't-heading-2-s dib ph2',\n installmentContainerClass: installmentContainerClass || 't-mini-s t-small-ns c-on-base',\n installmentClass: installmentClass || 't-body',\n interestRateClass: interestRateClass || 'dib ph2',\n savingsContainerClass: savingsContainerClass || 'c-success mt3',\n savingsClass: savingsClass || 'dib t-small',\n loaderClass: loaderClass || 'h4-s mw6-s pt2-s',\n listPrice: listPrice || path(['ListPrice'], commertialOffer),\n sellingPrice: sellingPrice || path(['Price'], commertialOffer),\n installments: installments || path(['Installments'], commertialOffer),\n labelSellingPrice,\n showLabels,\n showInstallments,\n showListPrice,\n showSavings,\n showProductPrice: isAvailable(commertialOffer),\n }\n }\n\n const { showProductPrice, ...priceProps } = productPriceProps()\n\n if (!showProductPrice) {\n return null\n }\n\n return (\n <ProductPrice { ...priceProps } />\n )\n}\n\nProductPriceWrapper.schema = {\n title: 'admin/editor.productPrice.title',\n description: 'admin/editor.productPrice.description',\n type: 'object',\n properties: {\n labelSellingPrice: {\n type: 'string',\n title: 'admin/editor.productPrice.labelSellingPrice',\n default: ProductPrice.defaultProps.labelSellingPrice,\n isLayout: false,\n },\n labelListPrice: {\n type: 'string',\n title: 'admin/editor.productPrice.labelListPrice',\n default: ProductPrice.defaultProps.labelListPrice,\n isLayout: false,\n },\n showSellingPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSellingPriceRange',\n default: ProductPrice.defaultProps.showSellingPriceRange,\n isLayout: true,\n },\n showListPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPriceRange',\n default: ProductPrice.defaultProps.showListPriceRange,\n isLayout: true,\n },\n showListPrice: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPrice',\n default: ProductPrice.defaultProps.showListPrice,\n isLayout: true,\n },\n showLabels: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showLabels',\n default: ProductPrice.defaultProps.showLabels,\n isLayout: true,\n },\n showInstallments: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showInstallments',\n default: ProductPrice.defaultProps.showInstallments,\n isLayout: true,\n },\n showSavings: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSavings',\n default: ProductPrice.defaultProps.showSavings,\n isLayout: true,\n },\n },\n}\n\nexport default ProductPriceWrapper\n\n```"
}
] |
code_store-on-localhost_8a907dff
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport classNames from 'classnames'\n// import PropTypes from 'prop-types'\nimport { isNil, head, last, sort, equals } from 'ramda'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport IOMessage from '../../../NativeTypes/IOMessage'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport formatCurrency from '../../../FormatCurrency/formatCurrency'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nimport ProductPriceLoader from './Loader'\nimport PricePropTypes from './propTypes'\nimport Installments from './Installments'\nimport Price from './Price'\n\nimport productPrice from './styles.css'\n\nconst CSS_HANDLES = ['price_className',\n 'price_loader',\n 'price_listPriceContainer',\n 'price_listPriceLabel',\n 'price_listPrice',\n 'price_listPriceRange',\n 'price_sellingPriceRange',\n 'price_sellingPriceContainer',\n 'price_sellingPriceLabel',\n 'price_sellingPrice',\n 'price_savingsContainer',\n 'price_savings',\n 'price_savings_value',\n 'price_installment',\n 'price_interestRate',\n 'price_installmentContainer']\n\nconst isValidPriceRange = priceRange => {\n const [lowPrice, highPrice] = priceRange\n return priceRange.length === 2 && lowPrice !== highPrice\n}\n\nconst getPriceRange = prices => {\n const sortedPrices = sort((a, b) => a - b, prices)\n return [head(sortedPrices), last(sortedPrices)]\n}\n\nconst canShowListPrice = props => {\n const {\n sellingPriceList,\n sellingPrice,\n listPrice,\n listPriceList,\n showListPrice,\n showListPriceRange,\n showSellingPriceRange,\n } = props\n\n if (!showListPrice) {\n return false\n }\n\n const sellingPriceRange =\n (sellingPriceList && getPriceRange(sellingPriceList)) || []\n const listPriceRange = (listPriceList && getPriceRange(listPriceList)) || []\n\n const showingSellingPriceRange =\n showSellingPriceRange && isValidPriceRange(sellingPriceRange)\n const showingListPriceRange =\n showListPriceRange && isValidPriceRange(listPriceRange)\n\n const sellingPriceToShow = showingSellingPriceRange\n ? sellingPriceRange\n : sellingPrice\n const listPriceToShow = showingListPriceRange ? listPriceRange : listPrice\n\n return !equals(listPriceToShow, sellingPriceToShow)\n}\n\n/**\n * The Price component. Shows the prices information of the Product Summary.\n */\nconst ProductPrice = (props, context) => {\n const {\n sellingPriceList,\n sellingPrice,\n listPrice,\n listPriceList,\n showListPrice,\n showSellingPriceRange,\n showListPriceRange,\n showInstallments,\n showLabels,\n showSavings,\n labelSellingPrice,\n labelListPrice,\n // labelSavings,\n className,\n loaderClass,\n listPriceContainerClass,\n listPriceLabelClass,\n listPriceClass,\n listPriceRangeClass,\n sellingPriceRangeClass,\n sellingPriceContainerClass,\n sellingPriceLabelClass,\n sellingPriceClass,\n savingsContainerClass,\n savingsClass,\n installments,\n installmentClass,\n interestRateClass,\n installmentContainerClass,\n styles,\n intl,\n } = props\n\n const { culture } = useRuntime()\n\n const handles = useCssHandles(CSS_HANDLES)\n\n // let { classes } = props\n\n // avoiding undefined verifications\n // classes = {\n // ...PriceWithIntl.defaultProps.classes,\n // ...classes,\n // }\n\n if ((showListPrice && isNil(listPrice)) || isNil(sellingPrice)) {\n return <ProductPriceLoader loaderClass={`${loaderClass} ${handles.price_loader}`} {...styles} />\n }\n\n const mayShowListPrice = canShowListPrice(props)\n\n const sellingPriceRange = sellingPriceList && getPriceRange(sellingPriceList)\n const listPriceRange = listPriceList && getPriceRange(listPriceList)\n\n return (\n <div className={classNames(productPrice.priceContainer, className, handles.price_className)}>\n {mayShowListPrice && (\n <div\n className={classNames(\n productPrice.listPrice,\n listPriceContainerClass,\n handles.price_listPriceContainer\n )}\n >\n {showLabels && (\n <div\n className={classNames(\n productPrice.listPriceLabel,\n listPriceLabelClass,\n handles.price_listPriceLabel,\n 'dib ph2 t-small-ns t-mini'\n )}\n >\n <IOMessage id={labelListPrice} />\n </div>\n )}\n <Price\n showPriceRange={showListPriceRange}\n priceRange={listPriceRange}\n price={listPrice}\n rangeContainerClasses={classNames(\n productPrice.listPriceValue,\n listPriceRangeClass,\n handles.price_listPriceRange,\n )}\n singleContainerClasses={classNames(\n productPrice.listPriceValue,\n listPriceClass,\n handles.price_listPrice\n )}\n />\n </div>\n )}\n <div\n className={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceContainer,\n sellingPriceContainerClass,\n handles.price_sellingPriceContainer\n )}\n >\n {showLabels && mayShowListPrice && (\n <div\n className={classNames(\n productPrice.sellingPriceLabel,\n sellingPriceLabelClass,\n handles.price_sellingPriceLabel\n )}\n >\n <IOMessage id={labelSellingPrice} />\n </div>\n )}\n <Price\n showPriceRange={showSellingPriceRange}\n priceRange={sellingPriceRange}\n price={sellingPrice}\n rangeContainerClasses={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceValue,\n productPrice['sellingPriceValue--range'],\n sellingPriceRangeClass,\n handles.price_sellingPriceRange\n )}\n singleContainerClasses={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceValue,\n sellingPriceClass,\n handles.price_sellingPrice\n )}\n />\n </div>\n {showInstallments && (\n <Installments\n installments={installments}\n showLabels={showLabels}\n className={`${installmentContainerClass} ${handles.price_installmentContainer}`}\n interestRateClass={`${interestRateClass} ${handles.price_interestRate}`}\n installmentClass={`${installmentClass} ${handles.price_installment}`}\n />\n )}\n {mayShowListPrice && showSavings && (listPrice - sellingPrice > 0) && (\n <div\n className={classNames(\n productPrice.savingPrice,\n savingsContainerClass,\n handles.price_savingsContainer\n )}\n >\n <div\n className={classNames(productPrice.savingPriceValue, savingsClass, handles.price_savings)}\n >\n <FormattedMessage\n id=\"store/pricing.savings\"\n values={{\n savings: \n <span \n className={handles.price_savings_value}>\n {formatCurrency({\n intl,\n culture,\n value: listPrice - sellingPrice,\n })}\n </span>\n }}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nProductPrice.propTypes = PricePropTypes\n\nconst PriceWithIntl = injectIntl(ProductPrice)\n\nPriceWithIntl.defaultProps = {\n showSellingPriceRange: false,\n showListPriceRange: false,\n showListPrice: true,\n showLabels: true,\n showInstallments: false,\n showSavings: false,\n labelSellingPrice: null,\n labelListPrice: null,\n}\n\nPriceWithIntl.schema = {\n title: 'admin/editor.productPrice.title',\n description: 'admin/editor.productPrice.description',\n type: 'object',\n properties: {\n showSellingPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSellingPriceRange',\n default: PriceWithIntl.defaultProps.showSellingPriceRange,\n isLayout: true,\n },\n showListPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPriceRange',\n default: PriceWithIntl.defaultProps.showListPriceRange,\n isLayout: true,\n },\n showListPrice: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPrice',\n default: PriceWithIntl.defaultProps.showListPrice,\n isLayout: true,\n },\n showLabels: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showLabels',\n default: PriceWithIntl.defaultProps.showLabels,\n isLayout: true,\n },\n showInstallments: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showInstallments',\n default: PriceWithIntl.defaultProps.showInstallments,\n isLayout: true,\n },\n showSavings: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSavings',\n default: PriceWithIntl.defaultProps.showSavings,\n isLayout: true,\n },\n },\n}\n\nexport default PriceWithIntl\n\n```"
}
] |
code_store-on-localhost_02b893b7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/Installments.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport { injectIntl } from 'react-intl'\nimport classNames from 'classnames'\nimport { isEmpty } from 'ramda'\nimport { FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport formatCurrency from '../../../FormatCurrency/formatCurrency'\n\nimport PricePropTypes from './propTypes'\n\nimport productPrice from './styles.css'\n\n/** Installments component */\nconst Installments = ({\n showLabels,\n installments = [],\n className,\n installmentClass,\n interestRateClass,\n intl,\n}) => {\n const { culture } = useRuntime()\n\n if (\n !installments ||\n isEmpty(\n installments.filter(\n ({ NumberOfInstallments }) => NumberOfInstallments > 1\n )\n )\n ) {\n return null\n }\n\n const noInterestRateInstallments = installments.filter(\n installment =>\n !installment.InterestRate && installment.NumberOfInstallments > 1\n )\n\n /*\n * - The selected installment will be the one with the highest `NumberOfInstallments`;\n * - If there is no 'interest-free' installments, the normal installments will be analyzed.\n */\n const installment = (isEmpty(noInterestRateInstallments)\n ? installments\n : noInterestRateInstallments\n ).reduce((previous, current) =>\n previous.NumberOfInstallments > current.NumberOfInstallments\n ? previous\n : current\n )\n\n const formattedInstallmentPrice = formatCurrency({\n intl,\n culture,\n value: installment.Value,\n })\n\n const [installmentsElement, installmentPriceElement, timesElement] = [\n installment.NumberOfInstallments,\n formattedInstallmentPrice,\n <Fragment key=\"x\">x</Fragment>,\n ].map((element, index) => (\n <span className={installmentClass} key={index}>\n {element}\n </span>\n ))\n\n return (\n <div className={classNames(productPrice.installmentsPrice, className)}>\n {showLabels ? (\n <FormattedMessage\n id=\"store/pricing.installment-display\"\n values={{\n installments: installmentsElement,\n installmentPrice: installmentPriceElement,\n times: timesElement,\n }}\n />\n ) : (\n <Fragment>\n {installmentsElement}\n {timesElement} {installmentPriceElement}\n </Fragment>\n )}\n {!installment.InterestRate && (\n <div\n className={classNames(\n productPrice.interestRatePrice,\n interestRateClass\n )}\n >\n <FormattedMessage id=\"store/pricing.interest-free\" />\n </div>\n )}\n </div>\n )\n}\n\nInstallments.propTypes = {\n /** Classes to be applied to the root element */\n className: PropTypes.string,\n /** Classes to be applied to installment value element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Product installments to be displayed */\n installments: PricePropTypes.installments,\n /** Pages editor config to display labels */\n showLabels: PropTypes.bool.isRequired,\n}\n\nexport default injectIntl(Installments)\n\n```"
}
] |
code_store-on-localhost_4fd86f7f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/propTypes.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nexport default {\n /** Product list of selling prices */\n sellingPriceList: PropTypes.arrayOf(PropTypes.number),\n /** Product list of list prices */\n listPriceList: PropTypes.arrayOf(PropTypes.number),\n /** Product selling price */\n sellingPrice: PropTypes.number,\n /** Product list price */\n listPrice: PropTypes.number,\n /** Set visibility of selling prices range */\n showSellingPriceRange: PropTypes.bool.isRequired,\n /** Set visibility of list prices range */\n showListPriceRange: PropTypes.bool.isRequired,\n /** Set visibility of list price */\n showListPrice: PropTypes.bool.isRequired,\n /** Set visibility of labels */\n showLabels: PropTypes.bool.isRequired,\n /** Set visibility of installments */\n showInstallments: PropTypes.bool.isRequired,\n /** Set visibility of savings */\n showSavings: PropTypes.bool,\n /** Text to the selling price's label */\n labelSellingPrice: PropTypes.string,\n /** Text to the list price's label */\n labelListPrice: PropTypes.string,\n /** Available installments */\n installments: PropTypes.arrayOf(\n PropTypes.shape({\n /** Installment value */\n Value: PropTypes.number.isRequired,\n /** Interest rate (zero if interest-free) */\n InterestRate: PropTypes.number.isRequired,\n /** Calculated total value */\n TotalValuePlusInterestRate: PropTypes.number,\n /** Number of installments */\n NumberOfInstallments: PropTypes.number.isRequired,\n /** Installment offer name */\n Name: PropTypes.string,\n })\n ),\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to loader root element */\n loaderClass: PropTypes.string,\n /** Classes to be applied to container of list price */\n listPriceContainerClass: PropTypes.string,\n /** Classes to be applied to label of price */\n listPriceLabelClass: PropTypes.string,\n /** Classes to be applied to price value */\n listPriceClass: PropTypes.string,\n /** Classes to be applied to range selling prices value */\n sellingPriceRangeClass: PropTypes.string,\n /** Classes to be applied to range list prices value */\n listPriceRangeClass: PropTypes.string,\n /** Classes to be applied to selling price container */\n sellingPriceContainerClass: PropTypes.string,\n /** Classes to be applied to selling price label */\n sellingPriceLabelClass: PropTypes.string,\n /** Classes to be applied to selling price value */\n sellingPriceClass: PropTypes.string,\n /** Classes to be applied to savings container */\n savingsContainerClass: PropTypes.string,\n /** Classes to be applied to savings */\n savingsClass: PropTypes.string,\n /** Classes to be applied to installment element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to installment container */\n installmentContainerClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Component and content loader styles */\n styles: PropTypes.object,\n}\n\n```"
}
] |
code_store-on-localhost_a81a2e9b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/Price.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { injectIntl } from 'react-intl'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport formatCurrency from '../../../FormatCurrency/formatCurrency'\nimport FormattedCurrency from '../../../FormatCurrency/FormattedCurrency'\n\nconst isValidPriceRange = priceRange => {\n const [lowPrice, highPrice] = priceRange\n return priceRange.length === 2 && lowPrice !== highPrice\n}\n\nconst formatPriceRange = (intl, culture, rawPriceRange) => {\n const priceRangeFormatted = (rawPriceRange || []).map(value =>\n formatCurrency({ intl, culture, value })\n )\n\n return priceRangeFormatted.join(' - ')\n}\n\nconst Price = ({\n showPriceRange,\n priceRange,\n price,\n rangeContainerClasses,\n singleContainerClasses,\n intl,\n}) => {\n const { culture } = useRuntime()\n\n const mustShowPriceRange =\n showPriceRange && priceRange && isValidPriceRange(priceRange)\n\n if (mustShowPriceRange) {\n return (\n <span className={rangeContainerClasses}>\n {formatPriceRange(intl, culture, priceRange)}\n </span>\n )\n }\n\n return (\n <span className={singleContainerClasses}>\n <FormattedCurrency value={price} />\n </span>\n )\n}\n\nexport default injectIntl(Price)\n\n```"
}
] |
code_store-on-localhost_5fedfc52
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductPrice/Loader.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport classNames from 'classnames'\nimport ContentLoader from 'react-content-loader'\nimport productPrice from './styles.css'\n\nconst ProductPriceLoader = (loaderProps = {}) => {\n const { loaderClass, ...props } = loaderProps\n return (\n <div\n className={classNames(\n productPrice.priceContainer,\n productPrice.priceLoaderContainer,\n loaderClass\n )}\n >\n <ContentLoader\n style={{\n width: '100%',\n height: '100%',\n }}\n width={300}\n height={70}\n preserveAspectRatio=\"xMinYMin meet\"\n {...props}\n >\n <rect\n height=\"0.75em\"\n width=\"50%\"\n x=\"25%\"\n {...loaderProps[productPrice.listPriceLoader]}\n />\n <rect {...loaderProps[productPrice.sellingPriceLabelLoader]} />\n <rect\n height=\"1em\"\n width=\"70%\"\n x=\"15%\"\n y=\"1.25em\"\n {...loaderProps[productPrice.sellingPriceLoader]}\n />\n <rect\n height=\"0.75em\"\n width=\"80%\"\n x=\"10%\"\n y=\"2.75em\"\n {...loaderProps[productPrice.installmentsPriceLoader]}\n />\n <rect {...loaderProps[productPrice.savingsPriceLoader]} />\n </ContentLoader>\n </div>\n )\n}\n\nexport default ProductPriceLoader\n\n```"
}
] |
code_store-on-localhost_9ab84ddf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AvailabilitySubscriber/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* AvailabilitySubscriber CSS Module\n*/\n\n.subscriberContainer {}\n\n.title {}\n\n.subscribeLabel {}\n\n.form {}\n\n.content {}\n\n.input {}\n\n.inputName {}\n\n.inputEmail {}\n\n.submit {}\n\n.success {}\n\n.error {}\n```"
}
] |
code_store-on-localhost_e4e2452d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AvailabilitySubscriber/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport { path } from 'ramda'\n\nimport AvailabilitySubscriber from './index'\n\nconst isAvailable = commertialOffer =>\n Number.isNaN(+path(['AvailableQuantity'], commertialOffer)) ||\n path(['AvailableQuantity'], commertialOffer) > 0\n\nconst AvailabilitySubscriberWrapper = props => {\n const valuesFromContext = useContext(ProductContext)\n\n const commertialOffer = path(\n ['selectedItem', 'sellers', 0, 'commertialOffer'],\n valuesFromContext\n )\n \n const available = props.available != null ? props.available : isAvailable(commertialOffer)\n\n // Render component only if product is out of sales\n if (available) return null\n\n const skuId = props.skuId != null ? props.skuId : path(['selectedItem', 'itemId'], valuesFromContext)\n\n return <AvailabilitySubscriber skuId={skuId} />\n}\n\nexport default AvailabilitySubscriberWrapper\n\n```"
}
] |
code_store-on-localhost_1ebe4c44
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AvailabilitySubscriber/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { ApolloConsumer } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\n\nimport Button from '../../../Styleguide/Button'\nimport Input from '../../../Styleguide/Input'\nimport { loader } from 'graphql.macro'\n\nconst ADD_TO_AVAILABILITY_SUBSCRIBER_MUTATION = loader('./mutations/addToAvailabilitySubscriberMutation.gql')\n\nimport styles from './styles.css'\n\n/**\n * Represents the availability subscriber form, that's shown when\n * the product isn't available.\n */\nclass AvailabilitySubscriber extends Component {\n emailInput = React.createRef()\n nameInput = React.createRef()\n\n state = {\n name: '',\n email: '',\n emailError: '',\n hasBlurredEmail: false,\n isLoading: false,\n sendStatus: '',\n }\n\n static propTypes = {\n /** The id of the current product sku */\n skuId: PropTypes.string.isRequired,\n }\n\n validateEmail = email => {\n const { emailError } = this.state\n\n const emailRegex = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/\n\n let error = ''\n\n if (!emailRegex.test(email.toLowerCase())) {\n error = 'store/availability-subscriber.invalid-email'\n }\n\n if (error !== emailError) {\n this.setState({\n emailError: error,\n })\n }\n }\n\n handleEmailBlur = () => {\n if (this.state.hasBlurredEmail) {\n return\n }\n\n this.setState({\n hasBlurredEmail: true,\n })\n }\n\n handleInputChange = e => {\n this.setState({\n [e.target.name]: e.target.value,\n })\n\n if (e.target.name === 'email') {\n this.validateEmail(e.target.value)\n }\n }\n\n handleSubmit = (e, client) => {\n e.preventDefault()\n const variables = {\n acronym: 'AS',\n document: {\n fields: [\n {\n key: 'skuId',\n value: this.props.skuId,\n },\n {\n key: 'name',\n value: this.state.name,\n },\n {\n key: 'email',\n value: this.state.email,\n },\n {\n key: 'notificationSend',\n value: 'false',\n },\n {\n key: 'createdAt',\n value: new Date().toISOString(),\n },\n {\n key: 'sendAt',\n value: null,\n },\n ],\n },\n }\n this.setState({\n isLoading: true,\n })\n client\n .mutate({\n mutation: ADD_TO_AVAILABILITY_SUBSCRIBER_MUTATION,\n variables,\n })\n .then(\n mutationRes => {\n this.setState({\n name: '',\n email: '',\n isLoading: false,\n sendStatus: 'success',\n })\n },\n mutationErr => {\n this.setState({\n isLoading: false,\n sendStatus: 'error',\n })\n }\n )\n const event = new Event('message:success')\n event.details = {\n success: true,\n message: this.translate('store/availability-subscriber.added-message'),\n }\n document.dispatchEvent(event)\n }\n\n translate = id => this.props.intl.formatMessage({ id })\n\n componentDidMount() {\n this.setState({\n email: this.emailInput.value || '',\n name: this.nameInput.value || '',\n })\n }\n\n render() {\n const {\n name,\n email,\n emailError,\n hasBlurredEmail,\n isLoading,\n sendStatus,\n } = this.state\n\n const isFormDisabled =\n name === '' || email === '' || emailError !== '' || isLoading\n\n let emailErrorMessage = ''\n\n if (hasBlurredEmail && emailError !== '') {\n emailErrorMessage = this.translate(emailError)\n }\n\n return (\n <ApolloConsumer>\n {client => (\n <div className={styles.subscriberContainer}>\n <div className={`${styles.title} t-body mb3`}>\n {this.translate('store/availability-subscriber.title')}\n </div>\n <div className={`${styles.subscribeLabel} t-small fw3`}>\n {this.translate('store/availability-subscriber.subscribe-label')}\n </div>\n <form\n className={`${styles.form} mb4`}\n onSubmit={e => this.handleSubmit(e, client)}\n >\n <div\n className={`${styles.content} flex-ns justify-between mt4 mw6`}\n >\n <div\n className={`${styles.input} ${\n styles.inputName\n } w-100 mr5 mb4`}\n >\n <Input\n name=\"name\"\n type=\"text\"\n placeholder={this.translate(\n 'store/availability-subscriber.name-placeholder'\n )}\n value={name}\n onChange={this.handleInputChange}\n ref={e => {\n this.nameInput = e\n }}\n />\n </div>\n <div\n className={`${styles.input} ${\n styles.inputEmail\n } w-100 mr5 mb4`}\n >\n <Input\n name=\"email\"\n type=\"text\"\n placeholder={this.translate(\n 'store/availability-subscriber.email-placeholder'\n )}\n value={email}\n onChange={this.handleInputChange}\n onBlur={this.handleEmailBlur}\n error={hasBlurredEmail && !!emailError}\n errorMessage={emailErrorMessage}\n ref={e => {\n this.emailInput = e\n }}\n />\n </div>\n <div className={`${styles.submit} flex items-center mb4`}>\n <Button\n type=\"submit\"\n variation=\"primary\"\n size=\"small\"\n disabled={isFormDisabled}\n isLoading={isLoading}\n >\n {this.translate('store/availability-subscriber.send-label')}\n </Button>\n </div>\n </div>\n {sendStatus === 'success' && (\n <div className={`${styles.success} t-body c-success`}>\n {this.translate('store/availability-subscriber.added-message')}\n </div>\n )}\n {sendStatus === 'error' && (\n <div className={`${styles.error} c-danger`}>\n {this.translate('store/availability-subscriber.error-message')}\n </div>\n )}\n </form>\n </div>\n )}\n </ApolloConsumer>\n )\n }\n}\n\nexport default injectIntl(AvailabilitySubscriber)\n\n```"
}
] |
code_store-on-localhost_8d4bdc4a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductName/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport { path, isEmpty } from 'ramda'\nimport ProductContext from '../../../ProductContext/ProductContext'\n\nimport ProductName from './index'\n\nconst styles = {\n 'vtex-product-name__brand--loader': {\n x: 0,\n width: '100%',\n height: '1.631em',\n },\n 'vtex-product-name__sku--loader': {\n x: 0,\n y: '2.569em',\n width: '10.311em',\n height: '1.045em',\n },\n}\n\nconst ProductNameWrapper = props => {\n const valuesFromContext = useContext(ProductContext)\n\n const productNameProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext)) {\n return props\n }\n\n const { product, selectedItem } = valuesFromContext\n return {\n ...props,\n tag: props.tag || 'h1',\n name: props.name || path(['productName'], product),\n skuName: props.skuName || path(['name'], selectedItem),\n productReference:\n props.productReference || path(['productReference'], product),\n brandName: props.brandName || path(['brand'], product),\n styles: props.styles || styles,\n className: props.className || 't-heading-4',\n }\n }\n\n return <ProductName {...productNameProps()} />\n}\n\nProductNameWrapper.schema = {\n title: 'admin/editor.productName.title',\n description: 'admin/editor.productName.description',\n type: 'object',\n properties: {\n showBrandName: {\n type: 'boolean',\n title: 'admin/editor.productName.showBrandName.title',\n default: false,\n isLayout: true,\n },\n showSku: {\n type: 'boolean',\n title: 'admin/editor.productName.showSku.title',\n default: false,\n isLayout: true,\n },\n showProductReference: {\n type: 'boolean',\n title: 'admin/editor.productName.showProductReference.title',\n default: false,\n isLayout: true,\n },\n },\n}\n\nexport default ProductNameWrapper\n\n```"
}
] |
code_store-on-localhost_20c8c5d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductName/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React from 'react'\nimport ContentLoader from 'react-content-loader'\nimport classNames from 'classnames'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\nconst CSS_HANDLES = [\n 'productNameContainer',\n 'productBrand',\n 'productSku',\n 'productReference',\n 'productNameLoader',\n 'productNameBrandLoader',\n 'productNameSkuLoader',\n]\n\n/**\n * Name component. Show name and relevant SKU information of the Product Summary\n */\nconst ProductName = ({\n productReferenceClass,\n brandNameClass,\n skuNameClass,\n loaderClass,\n className,\n name,\n styles,\n skuName,\n showSku = false,\n brandName,\n showBrandName = false,\n productReference,\n showProductReference = false,\n tag: Wrapper = 'div',\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n const Loader = (loaderProps = {}) => (\n <div\n className={classNames(\n handles.productNameContainer,\n handles.productNameLoader,\n loaderProps.className\n )}\n >\n <ContentLoader\n style={{\n width: '100%',\n height: '100%',\n }}\n width={456}\n height={100}\n preserveAspectRatio=\"xMinYMin meet\"\n {...loaderProps}\n >\n <rect\n height=\"1.125em\"\n width=\"75%\"\n x=\"15%\"\n {...loaderProps[handles.productNameBrandLoader]}\n />\n <rect\n height=\"1.125em\"\n width=\"50%\"\n x=\"25%\"\n y=\"1.75em\"\n {...loaderProps[handles.productNameSkuLoader]}\n />\n </ContentLoader>\n </div>\n )\n\n if (!name) {\n return <Loader className={loaderClass} {...styles} />\n }\n\n return (\n <Wrapper\n className={classNames(handles.productNameContainer, 'mv0', className)}\n >\n <span className={classNames(handles.productBrand, brandNameClass)}>\n {name} {showBrandName && brandName && `- ${brandName}`}\n </span>\n {showSku && skuName && (\n <span className={classNames(handles.productBrand, skuNameClass)}>\n {skuName}\n </span>\n )}\n {showProductReference && productReference && (\n <span\n className={classNames(\n handles.productReference,\n productReferenceClass\n )}\n >\n {`REF: ${productReference}`}\n </span>\n )}\n </Wrapper>\n )\n}\n\nProductName.propTypes = {\n /** Name of the product */\n name: PropTypes.string,\n /** Selected SKU name */\n skuName: PropTypes.string,\n /** Show sku */\n showSku: PropTypes.bool,\n /** Product reference */\n productReference: PropTypes.string,\n /** Show product reference */\n showProductReference: PropTypes.bool,\n /** Brand name */\n brandName: PropTypes.string,\n /** Show brand name */\n showBrandName: PropTypes.bool,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to brandName element */\n brandNameClass: PropTypes.string,\n /** Classes to be applied to skuName element */\n skuNameClass: PropTypes.string,\n /** Classes to be applied to productReference element */\n productReferenceClass: PropTypes.string,\n /** Classes to be applied to loader root element */\n loaderClass: PropTypes.string,\n /** HTML tag to be used in the component container */\n tag: PropTypes.oneOf(['div', 'h1', 'h2', 'h3']),\n}\n\nexport default ProductName\n\n```"
}
] |
code_store-on-localhost_488458d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n useState,\n useEffect,\n useMemo,\n memo,\n useCallback,\n FC,\n} from 'react'\nimport { filter, head, isEmpty, compose, keys, length } from 'ramda'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport useResponsiveValue from '../../../ResponsiveValues/useResponsiveValue'\nimport ProductDispatchContext from '../../../ProductContext/ProductDispatchContext'\nconst { useProductDispatch } = ProductDispatchContext\n\nimport SKUSelector, { ShowValueForVariation } from './components/SKUSelector'\nimport {\n parseSku,\n isColor,\n uniqueOptionToSelect,\n findItemWithSelectedVariations,\n} from './utils'\nimport {\n Image,\n ImageMap,\n Variations,\n SelectedVariations,\n SelectorProductItem,\n InitialSelectionType,\n DisplayMode,\n} from './types'\nimport useEffectSkipMount from './components/hooks/useEffectSkipMount'\n\nconst keyCount = compose(length, keys)\nconst filterSelected = filter(Boolean)\n\nconst buildEmptySelectedVariation = (variations: Variations) => {\n const variationNames = Object.keys(variations)\n const result = {} as Record<string, null>\n for (const variationName of variationNames) {\n result[variationName] = null\n }\n return result\n}\n\n/** receives an item and the variations object, returns the selected variations for that item */\nconst selectedVariationFromItem = (\n item: SelectorProductItem,\n variations: Variations\n) => {\n const variationNames = Object.keys(variations)\n const result = {} as Record<string, string>\n for (const variationName of variationNames) {\n result[variationName] = item.variationValues[variationName]\n }\n return result\n}\n\nfunction useColorImages(items: SelectorProductItem[], imageRegexText: string) {\n const imageRegex = new RegExp(imageRegexText, 'i')\n\n return items.map(item => {\n if (!item.images) {\n return item\n }\n\n const hasVariationImage = item.images.some(\n image => image.imageLabel && imageRegex.test(image.imageLabel)\n )\n return {\n ...item,\n images: item.images.filter(image => {\n if (!image.imageLabel) {\n // if it doesn't have a variation image, it wont remove images without a label\n return !hasVariationImage\n }\n return imageRegex.test(image.imageLabel)\n }),\n }\n })\n}\n\nconst useImagesMap = (\n items: SelectorProductItem[],\n variations: Variations,\n thumbnailImage?: string\n) => {\n return useMemo(() => {\n if (thumbnailImage) {\n items = useColorImages(items, thumbnailImage)\n }\n\n const variationNames = Object.keys(variations)\n const result: ImageMap = {}\n for (const variationName of variationNames) {\n // Today, only \"Color\" variation should show image, need to find a more resilient way to tell this, waiting for backend\n if (!isColor(variationName)) {\n continue\n }\n const imageMap = {} as Record<string, Image | undefined>\n const variationValues = variations[variationName]\n for (const variationValue of variationValues) {\n const item = items.find(\n sku => sku.variationValues[variationName] === variationValue\n )\n imageMap[variationValue] = item && head(item.images)\n }\n result[variationName] = imageMap\n }\n return result\n }, [items, variations])\n}\n\nconst useAllSelectedEvent = (\n selectedVariations: SelectedVariations | null,\n variationsCount: number\n) => {\n const dispatch = useProductDispatch()\n useEffect(() => {\n if (dispatch && selectedVariations) {\n const selectedNotNull = filterSelected(selectedVariations)\n const selectedCount = keyCount(selectedNotNull)\n const allSelected = selectedCount === variationsCount\n dispatch({\n type: 'SKU_SELECTOR_SET_VARIATIONS_SELECTED',\n args: { allSelected },\n })\n }\n }, [dispatch, selectedVariations, variationsCount])\n}\n\ninterface Props {\n skuItems: ProductItem[]\n onSKUSelected?: (skuId: string) => void\n seeMoreLabel: string\n maxItems?: number\n variations: Variations\n skuSelected: ProductItem\n hideImpossibleCombinations?: boolean\n showValueForVariation?: ShowValueForVariation\n imageHeight?: number\n imageWidth?: number\n thumbnailImage?: string\n showVariationsLabels?: boolean\n variationsSpacing?: number\n showVariationsErrorMessage?: boolean\n initialSelection?: InitialSelectionType\n displayMode?: any\n sliderDisplayThreshold?: number\n sliderArrowSize?: number\n sliderItemsPerPage?: any\n}\n\nconst getNewSelectedVariations = (\n query: any,\n skuSelected: ProductItem,\n variations: Variations,\n initialSelection?: InitialSelectionType\n) => {\n const hasSkuInQuery = Boolean(query?.skuId)\n const parsedSku = parseSku(skuSelected)\n const emptyVariations = buildEmptySelectedVariation(variations)\n\n if (hasSkuInQuery || initialSelection === InitialSelectionType.complete) {\n return selectedVariationFromItem(parsedSku, variations)\n } else if (initialSelection === InitialSelectionType.image) {\n const colorVariationName = parsedSku.variations.find(isColor)\n return {\n ...emptyVariations,\n ...(colorVariationName\n ? {\n [colorVariationName]: parsedSku.variationValues[colorVariationName],\n }\n : {}),\n }\n }\n\n return emptyVariations\n}\n\n/**\n * Display a list of SKU items of a product and its specifications.\n */\nconst SKUSelectorContainer: FC<Props> = ({\n skuItems = [],\n onSKUSelected,\n seeMoreLabel,\n maxItems = 10,\n variations,\n skuSelected,\n imageWidth,\n imageHeight,\n thumbnailImage,\n variationsSpacing,\n showVariationsLabels = true,\n displayMode = DisplayMode.default,\n hideImpossibleCombinations = true,\n showVariationsErrorMessage = true,\n showValueForVariation = ShowValueForVariation.none,\n initialSelection = InitialSelectionType.complete,\n sliderDisplayThreshold = 3,\n sliderArrowSize = 12,\n sliderItemsPerPage = {\n desktop: 3,\n tablet: 2,\n phone: 1,\n },\n}) => {\n const variationsCount = keyCount(variations)\n const { query } = useRuntime()\n const responsiveDisplayMode = useResponsiveValue(displayMode)\n\n const parsedItems = useMemo(() => skuItems.map(parseSku), [skuItems])\n const { setQuery } = useRuntime()\n const redirectToSku = (skuId: string) => {\n setQuery(\n { skuId },\n {\n replace: true,\n }\n )\n }\n\n const [selectedVariations, setSelectedVariations] = useState<\n SelectedVariations\n >(() =>\n getNewSelectedVariations(query, skuSelected, variations, initialSelection)\n )\n useAllSelectedEvent(selectedVariations, variationsCount)\n\n useEffectSkipMount(() => {\n setSelectedVariations(\n getNewSelectedVariations(query, skuSelected, variations, initialSelection)\n )\n }, [variations])\n\n // No need to add skuSelected and onSKUSelected to dependency array since that would result in infinite loops\n useEffect(() => {\n if (skuSelected && onSKUSelected) {\n onSKUSelected(skuSelected.itemId)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [skuSelected.itemId])\n\n const imagesMap = useImagesMap(parsedItems, variations, thumbnailImage)\n\n const onSelectItem = useCallback(\n ({\n name: variationName,\n value: variationValue,\n skuId,\n isMainAndImpossible,\n possibleItems,\n }) => {\n const isRemoving = selectedVariations![variationName] === variationValue\n const newSelectedVariation = !isMainAndImpossible\n ? {\n ...selectedVariations,\n [variationName]: isRemoving ? null : variationValue,\n }\n : {\n ...buildEmptySelectedVariation(variations),\n [variationName]: variationValue,\n }\n // Set here for a better response to user\n setSelectedVariations(newSelectedVariation)\n const uniqueOptions = isRemoving\n ? {}\n : uniqueOptionToSelect(\n possibleItems,\n newSelectedVariation,\n isMainAndImpossible\n )\n const finalSelected = {\n ...newSelectedVariation,\n ...uniqueOptions,\n }\n if (!isEmpty(uniqueOptions)) {\n setSelectedVariations(finalSelected)\n }\n\n const selectedNotNull = filterSelected(finalSelected)\n const selectedCount = keyCount(selectedNotNull)\n const allSelected = selectedCount === variationsCount\n let skuIdToRedirect = skuId\n if (!skuIdToRedirect || !isEmpty(uniqueOptions)) {\n const newItem = findItemWithSelectedVariations(\n possibleItems,\n finalSelected\n )\n skuIdToRedirect = newItem!.itemId\n }\n\n if (isRemoving) {\n // If its just removing, no need to do anything.\n return\n }\n\n if (onSKUSelected) {\n onSKUSelected(skuIdToRedirect)\n } else {\n if (allSelected || isColor(variationName)) {\n redirectToSku(skuIdToRedirect)\n }\n }\n },\n // Adding selectedVariations, variationsCount and onSKUSelected causes an infinite loop\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [selectedVariations, variations, onSKUSelected]\n )\n\n return (\n <SKUSelector\n maxItems={maxItems}\n imagesMap={imagesMap}\n skuItems={parsedItems}\n variations={variations}\n imageWidth={imageWidth}\n displayMode={responsiveDisplayMode}\n imageHeight={imageHeight}\n seeMoreLabel={seeMoreLabel}\n onSelectItem={onSelectItem}\n variationsSpacing={variationsSpacing}\n selectedVariations={selectedVariations}\n showVariationsLabels={showVariationsLabels}\n showValueForVariation={showValueForVariation}\n hideImpossibleCombinations={hideImpossibleCombinations}\n showVariationsErrorMessage={showVariationsErrorMessage}\n sliderDisplayThreshold={sliderDisplayThreshold}\n sliderArrowSize={sliderArrowSize}\n sliderItemsPerPage={sliderItemsPerPage}\n />\n )\n}\n\nexport default memo(SKUSelectorContainer)\n\n```"
}
] |
code_store-on-localhost_f2bc3657
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* SKU Selector CSS Module\n*/\n.skuSelectorContainer {\n}\n.skuSelectorSubcontainer {\n}\n.skuSelectorName {\n}\n.skuSelectorNameContainer {\n}\n.skuSelectorNameSeparator {\n}\n.skuSelectorSelectorImageValue {\n}\n.skuSelectorTextContainer {\n}\n\n.skuSelectorSelectContainer {}\n\n.skuSelectorItem {\n font-size: 90%;\n height: 36px;\n}\n\n.skuSelectorItemImage {\n padding: 0;\n height: 40px;\n width: 40px;\n}\n\n.skuSelectorItem p {\n margin: 0;\n padding-top: 10px;\n}\n\n.skuSelectorBagde {\n font-size: 0.71429rem;\n background-color: #ff4136;\n border-radius: 50%;\n color: #fff;\n height: 18px;\n line-height: 18px;\n right: -5px;\n text-align: center;\n top: -6px;\n width: 18px;\n position: absolute;\n padding: 3px;\n}\n\n.diagonalCross {\n background-image: linear-gradient(\n to top right,\n transparent 44%,\n rgba(0, 0, 0, 0.3) 48%,\n currentColor 48%,\n currentColor 52%,\n transparent 52%\n );\n}\n\n.frameAround {\n bottom: -0.25rem;\n top: -0.25rem;\n left: -0.25rem;\n right: -0.25rem;\n}\n\n.seeMoreButton {\n}\n\n.skuSelectorOptionsList {\n}\n\n.skuSelectorItemTextValue {\n}\n\n.skuSelectorItemImageValue {\n}\n\n```"
}
] |
code_store-on-localhost_b1a99377
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/Wrapper.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, useEffect } from 'react'\nimport { pick } from 'ramda'\nimport useProduct from '../../../ProductContext/useProduct'\nimport ProductDispatchContext from '../../../ProductContext/ProductDispatchContext'\nconst { useProductDispatch } = ProductDispatchContext\nimport useResponsiveValues from '../../../ResponsiveValues/useResponsiveValues'\n\nimport SKUSelector from './index'\nimport { Variations, InitialSelectionType, DisplayMode } from './types'\nimport { ShowValueForVariation } from './components/SKUSelector'\n\nconst getVariationsFromItems = (\n skuItems: ProductItem[],\n visibleVariations?: string[]\n) => {\n const variations: Variations = {}\n const variationsSet: Record<string, Set<string>> = {}\n\n for (const skuItem of skuItems) {\n for (const currentVariation of skuItem.variations) {\n const { name, values } = currentVariation\n if (\n !visibleVariations ||\n visibleVariations.includes(name.toLowerCase().trim())\n ) {\n const value = values[0]\n const currentSet = variationsSet[name] || new Set()\n currentSet.add(value)\n variationsSet[name] = currentSet\n }\n }\n }\n const variationsNames = Object.keys(variationsSet)\n // Transform set back to array\n for (const variationName of variationsNames) {\n const set = variationsSet[variationName]\n variations[variationName] = Array.from(set)\n }\n return variations\n}\n\nconst getVariationsFromSpecifications = (\n skuSpecifications: SkuSpecification[],\n visibleVariations?: string[]\n) => {\n const variations: Variations = {}\n for (const specification of skuSpecifications) {\n if (\n !visibleVariations ||\n visibleVariations.includes(specification.field.name.toLowerCase().trim())\n ) {\n variations[specification.field.name] = specification.values.map(\n value => value.name\n )\n }\n }\n return variations\n}\n\nconst useVariations = (\n skuItems: ProductItem[],\n skuSpecifications: SkuSpecification[],\n shouldNotShow: boolean,\n visibleVariations?: string[]\n) => {\n const isSkuSpecificationsEmpty = skuSpecifications.length === 0\n /* if the skuSpecifications array has values, then it should be used to find\n * the variations, which will come ordered the same way they are in the catalog */\n const variationsSource = isSkuSpecificationsEmpty\n ? skuItems\n : skuSpecifications\n const result = useMemo(() => {\n if (\n shouldNotShow ||\n (visibleVariations && visibleVariations.length === 0)\n ) {\n return {}\n }\n let formattedVisibleVariations = visibleVariations\n if (visibleVariations) {\n formattedVisibleVariations = visibleVariations.map(variation =>\n variation.toLowerCase().trim()\n )\n }\n\n return isSkuSpecificationsEmpty\n ? getVariationsFromItems(\n variationsSource as ProductItem[],\n formattedVisibleVariations\n )\n : getVariationsFromSpecifications(\n variationsSource as SkuSpecification[],\n formattedVisibleVariations\n )\n }, [\n variationsSource,\n shouldNotShow,\n visibleVariations,\n isSkuSpecificationsEmpty,\n ])\n return result\n}\n\ninterface Props {\n skuItems: ProductItem[]\n skuSelected: ProductItem\n onSKUSelected?: (skuId: string) => void\n maxItems?: number\n visibility?: string\n seeMoreLabel: string\n hideImpossibleCombinations?: boolean\n showValueNameForImageVariation?: boolean\n showValueForVariation?: ShowValueForVariation\n imageHeight?: any\n imageWidth?: any\n thumbnailImage?: string\n visibleVariations?: string[]\n showVariationsLabels?: boolean\n variationsSpacing?: number\n showVariationsErrorMessage?: boolean\n initialSelection?: InitialSelectionType\n displayMode?: any\n sliderDisplayThreshold?: number\n sliderArrowSize?: number\n sliderItemsPerPage?: any\n}\n\nconst SKUSelectorWrapper: StorefrontFC<Props> = props => {\n const valuesFromContext = useProduct() as any\n const dispatch = useProductDispatch()\n const { imageHeight, imageWidth } = useResponsiveValues(\n pick(['imageHeight', 'imageWidth'], props)\n )\n const skuItems =\n props.skuItems != null\n ? props.skuItems\n : valuesFromContext?.product?.items ?? []\n\n const skuSelected =\n props.skuSelected != null\n ? props.skuSelected\n : valuesFromContext.selectedItem\n\n const visibility = props.visibility != null ? props.visibility : 'always'\n\n const shouldNotShow =\n skuItems.length === 0 ||\n !skuSelected?.variations ||\n skuSelected.variations.length === 0 ||\n (visibility === 'more-than-one' && skuItems.length === 1)\n\n const skuSpecifications = valuesFromContext?.product?.skuSpecifications ?? []\n const variations = useVariations(\n skuItems,\n skuSpecifications,\n shouldNotShow,\n props.visibleVariations\n )\n\n useEffect(() => {\n if (dispatch) {\n dispatch({\n type: 'SKU_SELECTOR_SET_IS_VISIBLE',\n args: { isVisible: !shouldNotShow },\n })\n }\n }, [shouldNotShow, dispatch])\n\n if (shouldNotShow || !skuSelected) {\n return null\n }\n\n let showValueForVariation = ShowValueForVariation.none\n if (props.showValueForVariation) {\n showValueForVariation = props.showValueForVariation\n } else if (props.showValueNameForImageVariation) {\n showValueForVariation = ShowValueForVariation.image\n }\n\n return (\n <SKUSelector\n skuItems={skuItems}\n variations={variations}\n imageWidth={imageWidth}\n skuSelected={skuSelected}\n maxItems={props.maxItems}\n imageHeight={imageHeight}\n displayMode={props.displayMode}\n seeMoreLabel={props.seeMoreLabel}\n onSKUSelected={props.onSKUSelected}\n thumbnailImage={props.thumbnailImage}\n initialSelection={props.initialSelection}\n variationsSpacing={props.variationsSpacing}\n showValueForVariation={showValueForVariation}\n showVariationsLabels={props.showVariationsLabels}\n hideImpossibleCombinations={props.hideImpossibleCombinations}\n showVariationsErrorMessage={props.showVariationsErrorMessage}\n sliderItemsPerPage={props.sliderItemsPerPage}\n sliderArrowSize={props.sliderArrowSize}\n sliderDisplayThreshold={props.sliderDisplayThreshold}\n />\n )\n}\n\nSKUSelectorWrapper.schema = {\n title: 'admin/editor.skuSelector.title',\n description: 'admin/editor.skuSelector.description',\n}\n\nexport default SKUSelectorWrapper\n\n```"
}
] |
code_store-on-localhost_eb4cdd5d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AutocompleteResults/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.resultsList {\n max-height: 60vh;\n}\n\n.resultsList a,\n.resultsList div {\n text-decoration: none;\n color: #727273;\n}\n\n.resultsList a:hover {\n background-color: #f2f4f5;\n}\n\n.resultsItemImage {\n width: 50px;\n}\n\n@media only screen and (max-width: 49rem) {\n .resultsList {\n margin: 0px;\n max-height: calc(100vh - 6.2rem);\n }\n}\n\n```"
}
] |
code_store-on-localhost_60377280
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AutocompleteResults/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jsx-a11y/anchor-is-valid */\nimport React, { Fragment, useMemo } from 'react'\nimport classnames from 'classnames'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage } from 'react-intl'\nimport { graphql } from 'react-apollo'\nimport Spinner from '../../../Styleguide/Spinner'\nimport { Link, useRuntime } from '../../../../../../vtex.render-runtime'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\n\n// This import should NOT be removed\n// import styles from './styles.css'\nimport { loader } from 'graphql.macro'\n\nconst autocomplete = loader('./queries/autocomplete.gql')\n\nconst MIN_RESULTS_WIDTH = 320\nconst CSS_HANDLES = [\n 'resultsItem',\n 'resultsList',\n 'searchTerm',\n 'resultsItemImage',\n 'spinnerContainer',\n 'spinnerInnerContainer',\n 'resultsItemName',\n]\n\nconst getImageUrl = image => {\n const imageUrl = (image.match(/https?:(.*?)\"/g) || [''])[0]\n return imageUrl.replace(/https?:/, '').replace(/-25-25/g, '-50-50')\n}\n\nconst getLinkProps = element => {\n let page = 'store.product'\n let params = { slug: element.slug, id: element.productId }\n let query = ''\n const terms = element.slug.split('/')\n\n if (element.criteria) {\n // This param is only useful to track terms searched\n // See: https://support.google.com/analytics/answer/1012264\n const paramForSearchTracking = '&_c=' + terms[0]\n\n page = 'store.search'\n params = { term: terms[0] }\n query = `map=c,ft&rest=${terms.slice(1).join(',')}` + paramForSearchTracking\n }\n\n return { page, params, query }\n}\n\n/** List of search results to be displayed*/\nconst AutocompleteResults = ({\n parentContainer,\n isOpen,\n data = {}, // when inputValue is '', query is skipped and value is undefined\n inputValue,\n closeMenu,\n onClearInput,\n getItemProps,\n getMenuProps,\n highlightedIndex,\n attemptPageTypeSearch,\n customSearchPageUrl,\n}) => {\n const items = data.autocomplete ? data.autocomplete.itemsReturned : []\n const {\n hints: { mobile },\n } = useRuntime()\n const handles = useCssHandles(CSS_HANDLES)\n\n const listStyle = useMemo(\n () => ({\n width: Math.max(\n MIN_RESULTS_WIDTH,\n (parentContainer.current && parentContainer.current.offsetWidth) || 0\n ),\n }),\n /* with the isOpen here this will be called \n only when you open or close the ResultList */\n [parentContainer]\n )\n\n const listClassNames = classnames(\n handles.resultsList,\n 'z-max w-100 bl-ns bb br-ns bw1 b--muted-4 bg-base c-on-base t-body left-0 list pv4 ph0 mv0 list overflow-y-auto',\n mobile ? 'fixed' : 'absolute',\n { dn: !isOpen || !inputValue }\n )\n\n const handleItemClick = () => {\n onClearInput()\n closeMenu()\n }\n\n const getListItemClassNames = ({\n itemIndex = -1,\n highlightedIndex = -2,\n hasThumb = false,\n } = {}) => {\n const highlightClass = highlightedIndex === itemIndex ? 'bg-muted-5' : ''\n return `pointer pa4 outline-0 ${handles.resultsItem} ${highlightClass} ${\n hasThumb ? 'flex justify-start' : 'db w-100'\n }`\n }\n\n const WrappedSpinner = () => (\n <div className={`w-100 flex justify-center ${handles.spinnerContainer}`}>\n <div className={`${handles.spinnerInnerContainer} w3 ma0`}>\n <Spinner />\n </div>\n </div>\n )\n\n const fullTextSearchLabel = (\n <FormattedMessage\n id=\"store/search.searchFor\"\n values={{\n term: <span className={handles.searchTerm}>{`\"${inputValue}\"`}</span>,\n }}\n />\n )\n\n const renderSearchByClick = inputValue => {\n return customSearchPageUrl ? (\n <Link\n className={getListItemClassNames({\n itemIndex: 0,\n highlightedIndex,\n })}\n to={customSearchPageUrl.replace(/\\$\\{term\\}/g, inputValue)}\n >\n {fullTextSearchLabel}\n </Link>\n ) : (\n <Link\n page=\"store.search\"\n params={{ term: inputValue }}\n query=\"map=ft\"\n className={getListItemClassNames({\n itemIndex: 0,\n highlightedIndex,\n })}\n >\n {fullTextSearchLabel}\n </Link>\n )\n }\n\n return (\n <div style={listStyle}>\n <ul className={listClassNames} {...getMenuProps()}>\n {isOpen ? (\n data.loading ? (\n <div className={getListItemClassNames({})}>\n <WrappedSpinner />\n </div>\n ) : (\n <Fragment>\n <li\n {...getItemProps({\n key: 'ft' + inputValue,\n item: { term: inputValue },\n index: 0,\n onClick: handleItemClick,\n })}\n >\n {attemptPageTypeSearch ? (\n <a\n href=\"#\"\n onClick={event => event.preventDefault()}\n className={getListItemClassNames({\n itemIndex: 0,\n highlightedIndex,\n })}\n >\n {fullTextSearchLabel}\n </a>\n ) : (\n renderSearchByClick(inputValue)\n )}\n </li>\n\n {items.map((item, index) => {\n return (\n <li\n {...getItemProps({\n key: item.name + index,\n index: index + 1,\n item,\n onClick: handleItemClick,\n })}\n >\n <Link\n {...getLinkProps(item)}\n className={getListItemClassNames({\n itemIndex: index + 1,\n highlightedIndex,\n hasThumb: !!item.thumb,\n })}\n >\n {item.thumb && (\n <img\n width={50}\n height={50}\n alt={item.name}\n className={`${handles.resultsItemImage} mr4`}\n src={getImageUrl(item.thumb)}\n />\n )}\n <div\n className={`${handles.resultsItemName} flex justify-start items-center`}\n >\n {item.name}\n </div>\n </Link>\n </li>\n )\n })}\n </Fragment>\n )\n ) : null}\n </ul>\n </div>\n )\n}\n\nconst itemProps = PropTypes.shape({\n /** Image of the product*/\n thumb: PropTypes.string,\n /** Name of the product*/\n name: PropTypes.string,\n /** Link to the product*/\n href: PropTypes.string,\n /** Slug of the product*/\n slug: PropTypes.string,\n /** Criteria of the product*/\n criteria: PropTypes.string,\n})\n\nAutocompleteResults.propTypes = {\n /** Graphql data response. */\n data: PropTypes.shape({\n autocomplete: PropTypes.shape({\n itemsReturned: PropTypes.arrayOf(itemProps),\n }),\n loading: PropTypes.bool.isRequired,\n }),\n /** Downshift specific prop*/\n highlightedIndex: PropTypes.number,\n /** Search query*/\n inputValue: PropTypes.string.isRequired,\n /** Closes the options box. */\n closeMenu: PropTypes.func,\n /** Clears the input */\n onClearInput: PropTypes.func,\n /** Downshift function */\n getItemProps: PropTypes.func,\n /** A template for a custom url. It can have a substring ${term} used as placeholder to interpolate the searched term. (e.g. `/search?query=${term}`) */\n customSearchPageUrl: PropTypes.string,\n isOpen: PropTypes.bool,\n getMenuProps: PropTypes.func,\n attemptPageTypeSearch: PropTypes.bool,\n}\n\nconst AutocompleteResultsWithData = graphql(autocomplete, {\n skip: ({ inputValue }) => !inputValue,\n options: props => ({\n variables: {\n inputValue: props.inputValue,\n },\n }),\n})(AutocompleteResults)\n\nexport default AutocompleteResultsWithData\n\n```"
}
] |
code_store-on-localhost_2838997f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Newsletter/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose } from 'ramda'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport Input from '../../../Styleguide/Input'\nimport Button from '../../../Styleguide/Button'\nimport withCssHandles from '../../../CssHandles/withCssHandles'\nimport formatIOMessage from '../../../NativeTypes/formatIOMessage'\nimport { loader } from 'graphql.macro'\n\nconst SUBSCRIBE_NEWSLETTER = loader('./mutations/subscribeNewsletter.graphql')\n\nconst EMAIL_REGEX = /^[A-z0-9+_-]+(?:\\.[A-z0-9+_-]+)*@(?:[A-z0-9](?:[A-z0-9-]*[A-z0-9])?\\.)+[A-z0-9](?:[A-z0-9-]*[A-z0-9])?$/\nconst CSS_HANDLES = [\n 'newsletter',\n 'confirmation',\n 'container',\n 'confirmationTitle',\n 'confirmationText',\n 'form',\n 'inputGroup',\n 'buttonContainer',\n 'label',\n 'error',\n]\n\nclass Newsletter extends Component {\n state = {\n email: '',\n loading: false,\n error: null,\n success: null,\n invalidEmail: false,\n }\n\n inputRef = React.createRef()\n\n componentDidMount() {\n this.mounted = true\n }\n\n componentWillUnmount() {\n this.mounted = false\n }\n\n safeSetState(...params) {\n if (this.mounted) {\n this.setState(...params)\n }\n }\n\n handleChangeEmail = e => {\n this.setState({ email: e.target.value })\n }\n\n validateEmail = () => {\n return EMAIL_REGEX.test(this.state.email)\n }\n\n handleSubmit = e => {\n e.preventDefault()\n if (!this.validateEmail()) {\n this.setState({ invalidEmail: true })\n if (this.inputRef && this.inputRef.current) {\n this.inputRef.current.focus()\n }\n return\n }\n\n this.setState({\n invalidEmail: false,\n loading: true,\n error: null,\n success: null,\n })\n\n this.props\n .subscribeNewsletter({ variables: { email: this.state.email } })\n .then(() => {\n this.safeSetState({ success: true, loading: false })\n })\n .catch(e => {\n this.safeSetState({ error: true, loading: false })\n })\n }\n\n render() {\n const { hideLabel, intl, submit, label, placeholder, cssHandles } = this.props\n const submitText = formatIOMessage({ id: submit, intl })\n const labelText = formatIOMessage({ id: label, intl })\n const placeholderText = formatIOMessage({ id: placeholder, intl })\n const confirmationTitle = formatIOMessage({\n id: 'store/newsletter.confirmationTitle',\n intl,\n })\n const confirmationText = formatIOMessage({\n id: 'store/newsletter.confirmationText',\n intl,\n })\n const invalidEmailText = formatIOMessage({\n id: 'store/newsletter.invalidEmail',\n intl,\n })\n const errorMsg = formatIOMessage({\n id: 'store/newsletter.error',\n intl,\n })\n\n return (\n <div\n className={`${cssHandles.newsletter} ${\n this.state.success ? cssHandles.confirmation : ''\n } w-100`}\n >\n <div className={`${cssHandles.container} mw9 mr-auto ml-auto pv9`}>\n {this.state.success ? (\n <Fragment>\n <div className={`${cssHandles.confirmationTitle} t-heading-3 pb4 tc`}>\n {confirmationTitle}\n </div>\n <div className={`${cssHandles.confirmationText} t-body tc`}>\n {confirmationText}\n </div>\n </Fragment>\n ) : (\n <form className={`${cssHandles.form} mw6 center tc ph5 ph0-ns`}>\n <label\n className={`${cssHandles.label} t-heading-3 tc ${\n hideLabel ? 'dn' : ''\n }`}\n htmlFor=\"newsletter-input\"\n >\n {labelText}\n </label>\n <div className={`${cssHandles.inputGroup} flex-ns pt5`}>\n <Input\n ref={this.inputRef}\n id=\"newsletter-input\"\n errorMessage={\n this.state.invalidEmail ? invalidEmailText : null\n }\n placeholder={placeholderText}\n name=\"newsletter\"\n value={this.state.email}\n onChange={this.handleChangeEmail}\n />\n <div\n className={`${\n cssHandles.buttonContainer\n } pl4-ns flex-none pt3 pt0-ns`}\n >\n <Button\n variation=\"primary\"\n type=\"submit\"\n onClick={this.handleSubmit}\n isLoading={this.state.loading}\n >\n {submitText}\n </Button>\n </div>\n </div>\n {this.state.error && (\n <div className={`${cssHandles.error} c-danger t-body pt5`}>\n {errorMsg}\n </div>\n )}\n </form>\n )}\n </div>\n </div>\n )\n }\n}\n\nNewsletter.defaultProps = {\n hideLabel: false,\n showTerms: false,\n}\n\nNewsletter.propTypes = {\n hideLabel: PropTypes.bool.isRequired,\n showTerms: PropTypes.bool.isRequired,\n label: PropTypes.string,\n placeholder: PropTypes.string,\n submit: PropTypes.string,\n subscribeNewsletter: PropTypes.func.isRequired,\n}\n\nNewsletter.getSchema = () => {\n return {\n title: 'admin/editor.newsletter.title',\n description: 'admin/editor.newsletter.description',\n type: 'object',\n properties: {\n hideLabel: {\n type: 'boolean',\n title: 'admin/editor.newsletter.hideLabel',\n default: false,\n isLayout: true,\n },\n },\n }\n}\n\nexport default compose(\n graphql(SUBSCRIBE_NEWSLETTER, { name: 'subscribeNewsletter' }),\n withCssHandles(CSS_HANDLES),\n injectIntl\n)(Newsletter)\n```"
}
] |
code_store-on-localhost_44ef47fb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductHighlights/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* ProductHighlights CSS Modules\n*/\n\n.highlightContent {}\n.itemHighlight {}\n.highlightTitle {}\n.highlightValue {}\n\n```"
}
] |
code_store-on-localhost_2f301fe1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductHighlights/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport { isEmpty, propOr } from 'ramda'\n\nimport ProductHighlights from './index'\n\nconst ProductHighlightsWrapper = (props) => {\n const { conditional } = props\n\n const valuesFromContext = useContext(ProductContext)\n\n const getHighlights = () => {\n const { product } = valuesFromContext\n\n const choose = propOr('', 'highlight', conditional)\n\n if (choose === 'admin/editor.product-details.highlights.chooseDefault') {\n const typeHighlight = propOr('', 'typeHighlight', conditional)\n const highlightName = typeHighlight.trim()\n const names = highlightName.split(',')\n const specificationGroups = propOr([], 'specificationGroups', product)\n\n return names.reduce((acc, item) => {\n const highlightSpecificationGroup = specificationGroups.filter(\n x => x.name.toLowerCase() === item.trim().toLowerCase()\n )[0]\n const highlight = propOr(\n [],\n 'specifications',\n highlightSpecificationGroup\n )\n return acc.concat(highlight)\n }, [])\n }\n\n if (choose === 'admin/editor.product-details.highlights.chooseDefaultSpecification') {\n const typeSpecifications = propOr('', 'typeSpecifications', conditional)\n const specificationNames = typeSpecifications.trim().split(',')\n const allSpecifications = propOr([], 'properties', product)\n\n return specificationNames.reduce((acc, item) => {\n const highlight = allSpecifications.filter(\n x => x.name.toLowerCase() === item.trim().toLowerCase()\n )\n return acc.concat(highlight)\n }, [])\n }\n\n if (choose === 'admin/editor.product-details.highlights.allSpecifications') {\n return propOr([], 'properties', product)\n }\n }\n\n const productHighlightsProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext)) {\n return props\n }\n\n return {\n ...props,\n highlights: props.highlights || getHighlights(),\n }\n }\n\n return (\n <ProductHighlights { ...productHighlightsProps() } />\n )\n}\n\nProductHighlightsWrapper.schema = {\n // @TODO review title and description\n title: 'admin/editor.product-details.title',\n description: 'admin/editor.product-details.description',\n type: 'object',\n definitions: {\n highlightGroupDefault: {\n title: 'highlightGroupDefault',\n type: 'object',\n properties: {\n highlight: {\n title: 'admin/editor.product-details.highlights.default',\n type: 'string',\n enum: [\n 'admin/editor.product-details.highlights.allSpecifications',\n 'admin/editor.product-details.highlights.chooseDefault',\n 'admin/editor.product-details.highlights.chooseDefaultSpecification',\n ],\n default: 'admin/editor.product-details.highlights.allSpecifications',\n },\n },\n required: ['highlight'],\n dependencies: {\n highlight: {\n oneOf: [\n {\n properties: {\n highlight: {\n enum: [\n 'admin/editor.product-details.highlights.allSpecifications',\n ],\n },\n },\n },\n {\n properties: {\n highlight: {\n enum: ['admin/editor.product-details.highlights.chooseDefault'],\n },\n typeHighlight: {\n type: 'string',\n title: 'admin/editor.product-details.highlights.title',\n },\n },\n required: [''],\n },\n {\n properties: {\n highlight: {\n enum: [\n 'admin/editor.product-details.highlights.chooseDefaultSpecification',\n ],\n },\n typeSpecifications: {\n type: 'string',\n title:\n 'admin/editor.product-details.highlights.typeSpecifications.title',\n },\n },\n required: [''],\n },\n ],\n },\n },\n },\n },\n properties: {\n showHighlight: {\n type: 'boolean',\n title: 'admin/editor.product-details.showHighlight.title',\n default: false,\n isLayout: false,\n },\n conditional: {\n title: 'Conditional',\n $ref: '#/definitions/highlightGroupDefault',\n },\n },\n}\n\nexport default ProductHighlightsWrapper\n```"
}
] |
code_store-on-localhost_524698c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductHighlights/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport HtmlParser from 'react-html-parser'\n\nimport styles from './styles.css'\n\n/**\n * Product highlights Component.\n * Render the highlights specifications of a product.\n */\nconst ProductHighlights = ({ ...props }) => {\n const { highlights } = props\n return (\n <div className={`${styles.highlightContent} pt3 pb5`}>\n {highlights.map((item, i) => (\n <div\n className={`${styles.itemHighlight} pv2`}\n data-name={item.name}\n data-value={item.values[0]}\n key={i}\n >\n <span\n className={`${styles.highlightTitle} t-body c-on-base fw7 pr3 `}\n >\n {HtmlParser(item.name)}\n {': '}\n </span>\n <span\n className={`${styles.highlightValue} t-body c-muted-1 lh-copy `}\n >\n {HtmlParser(item.values[0])}\n </span>\n </div>\n ))}\n </div>\n )\n}\n\nProductHighlights.defaultProps = {\n highlights: [],\n}\n\nProductHighlights.propTypes = {\n /** Specifications that will be displayed on the table */\n highlights: PropTypes.arrayOf(\n PropTypes.shape({\n /** Highlight name */\n name: PropTypes.string.isRequired,\n /** Highlight value */\n values: PropTypes.arrayOf(PropTypes.string).isRequired,\n })\n ),\n}\n\nexport default injectIntl(ProductHighlights)\n\n```"
}
] |
code_store-on-localhost_af28696c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/UserAddress/AddressInfo.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { ExtensionPoint, useChildBlock } from '../../../../../../vtex.render-runtime'\nimport { pathOr } from 'ramda'\nimport { injectIntl, FormattedMessage } from 'react-intl'\nimport IconLocationMarker from '../../../StoreIcons/IconLocationMarker'\n\nconst AddressInfo = ({ inverted, inline, orderForm, intl }) => {\n const { shippingData } = orderForm\n if (!shippingData || !shippingData.address) return\n\n const { street, number, complement, addressType } = shippingData.address\n\n const displayStreet = number ? `${street}, ${number}` : street\n\n const displayAddress =\n complement && complement !== ''\n ? `${displayStreet} - ${complement}`\n : `${displayStreet}`\n\n const isPickup = addressType === 'pickup'\n const friendlyName = pathOr(\n '',\n ['pickupPointCheckedIn', 'friendlyName'],\n orderForm\n )\n\n const hasModal = !!useChildBlock({ id: 'modal' })\n\n return (\n <div className={`flex ${inline ? 'items-end' : 'items-center flex-auto'}`}>\n <div className=\"flex flex-auto\">\n <div\n className={`mr3 flex items-center ${\n inverted ? 'c-on-base--inverted' : 'c-muted-2'\n }`}\n >\n <IconLocationMarker size={27} viewBox={'0 0 21 27'} />\n </div>\n <div className=\"flex flex-auto flex-column\">\n <div\n className={`t-small ${\n inverted ? 'c-on-base--inverted' : 'c-muted-2'\n }`}\n >\n {isPickup ? (\n <FormattedMessage\n id=\"store/user-address.pickup\"\n values={{ name: friendlyName }}\n />\n ) : (\n <FormattedMessage id=\"store/user-address.order\" />\n )}\n </div>\n <div className=\"truncate\">{displayAddress}</div>\n </div>\n </div>\n {hasModal && (\n <Fragment>\n <div\n className={`bl bw1 mh4 ${inline ? 'nb2' : ''} ${\n inverted ? 'b--on-base--inverted' : 'b--muted-5'\n }`}\n style={{\n height: '1.5rem',\n }}\n />\n <div className=\"flex items-center\">\n <ExtensionPoint\n id=\"modal\"\n centered\n buttonLabel={intl.formatMessage({\n id: 'store/user-address.change',\n })}\n buttonClass={\n inverted ? 'c-on-base--inverted' : 'c-action-primary'\n }\n showTopBar={false}\n />\n </div>\n </Fragment>\n )}\n </div>\n )\n}\n\nexport default injectIntl(AddressInfo)\n\n```"
}
] |
code_store-on-localhost_1250c5da
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/UserAddress/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React from 'react'\nimport { graphql } from 'react-apollo'\n\nimport Container from '../Container'\nimport AddressInfo from './AddressInfo'\nimport { loader } from 'graphql.macro'\n\nconst addressQuery = loader('../../../StoreResources/queries/address.gql')\n\nconst UserAddress = ({ variation, addressQuery }) => {\n const { orderForm } = addressQuery\n const { shippingData } = orderForm || {}\n\n if (!orderForm || !shippingData || !shippingData.address) {\n return null\n }\n\n const isInline = variation === 'inline'\n const isInverted = !isInline\n\n return isInline ? (\n <div\n className=\"ph5\"\n style={{\n maxWidth: '30rem',\n }}\n >\n {\n <AddressInfo\n inverted={isInverted}\n inline={isInline}\n orderForm={orderForm}\n />\n }\n </div>\n ) : (\n <div className=\"bg-base--inverted c-on-base--inverted flex ph5 pointer pv3\">\n <Container className=\"flex justify-center w-100 left-0\">\n <div className=\"w-100 mw9 flex\">\n <AddressInfo\n inverted={isInverted}\n inline={isInline}\n orderForm={orderForm}\n />\n </div>\n </Container>\n </div>\n )\n}\n\nUserAddress.propTypes = {\n variation: PropTypes.oneOf(['inline', 'bar']).isRequired,\n addressQuery: PropTypes.object.isRequired,\n}\n\nconst withAddressQuery = graphql(addressQuery, {\n name: 'addressQuery',\n options: () => ({ ssr: false }),\n})\n\nexport default withAddressQuery(UserAddress)\n\n```"
}
] |
code_store-on-localhost_fc923322
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CategoriesHighlights/constants.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const ITEMS_PER_ROW = 2\nexport const SQUARED = 'squared'\nexport const RECTANGULAR = 'rectangular'\n\n```"
}
] |
code_store-on-localhost_1392d2bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CategoriesHighlights/categoriesHighlights.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.squaredCategoriesHighlights:only-child,\n.rectangularCategoriesHighlights:only-child {\n display: none;\n}\n\n:global(.vtex-carousel) + .squared,\n:global(.vtex-carousel) + .rectangular {\n top: -5.625rem;\n}\n\n.squaredCard,\n.rectangularCard {\n background: rgba(61, 61, 61, 0.8);\n height: 18.75rem;\n}\n\n.squaredCard {\n width: 18.75rem;\n}\n\n.rectangularCard {\n width: 37.5rem;\n}\n\n.squaredCardImage,\n.rectangularCardImage {\n object-fit: cover;\n}\n\n.squaredCardImage {\n width: 18.75rem;\n}\n\n.rectangularCardImage {\n width: 37.5rem;\n}\n\n@media only screen and (min-width: 20em) and (max-width: 50em) {\n :global(.vtex-carousel) + .squaredCategoriesHighlights {\n top: -3.125rem;\n }\n\n :global(.vtex-carousel) + .rectangularCategoriesHighlights {\n top: 0;\n }\n\n .squaredCard,\n .squaredCardImage {\n height: 9.375rem;\n width: 9.375rem;\n }\n\n .rectangularCard,\n .rectangularCardImage {\n height: 12.5rem;\n width: 100%;\n }\n}\n\n@media only screen and (min-width: 50em) and (max-width: 64em) {\n :global(.vtex-carousel) + .squaredCategoriesHighlights,\n :global(.vtex-carousel) + .rectangularCategoriesHighlights {\n top: -4.375rem;\n }\n\n .squaredCard,\n .rectangularCard {\n margin: 0;\n height: 12.5rem;\n }\n\n .squaredCard,\n .squaredCardImage {\n width: 12.5rem;\n }\n\n .rectangularCard,\n .rectangularCardImage {\n width: 25rem;\n }\n\n .squaredCardImage,\n .rectangularCardImage {\n height: 12.5rem;\n }\n}\n```"
}
] |
code_store-on-localhost_a245f8c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CategoriesHighlights/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport categoriesHighlights from './categoriesHighlights.css'\n\nimport PropTypes from 'prop-types'\nimport { range, values } from 'ramda'\nimport React, { Component } from 'react'\n\nimport CategoryCard from './components/CategoryCard'\nimport { ITEMS_PER_ROW, RECTANGULAR, SQUARED } from './constants.js'\n\n/**\n * CategoriesHighlights is a component responsible to display the\n * Categories highlighted in a department.\n */\nclass CategoriesHighlights extends Component {\n static propTypes = {\n /** Categories highlighted in the department */\n categoriesHighlighted: PropTypes.object,\n /** Flag which indicates if the categories highlighted should be displayed or not */\n showCategoriesHighlighted: PropTypes.bool,\n /** Number of categories highlighted to be displayed (it should be 2 or 4) */\n quantityOfItems: PropTypes.number.isRequired,\n /** Shape of the card box which wraps each category (it should be 'squared' or 'rectangular') */\n cardShape: PropTypes.oneOf([SQUARED, RECTANGULAR]).isRequired,\n }\n\n static defaultProps = {\n categoriesHighlighted: {},\n showCategoriesHighlighted: false,\n quantityOfItems: ITEMS_PER_ROW,\n cardShape: SQUARED,\n }\n\n static uiSchema = {\n categoriesHighlighted: {\n items: {\n image: {\n 'ui:widget': 'image-uploader',\n },\n },\n },\n }\n\n static getSchema = ({ quantityOfItems }) => {\n let categoriesHighlightedProps = {}\n\n range(0, quantityOfItems || ITEMS_PER_ROW).forEach(index => {\n categoriesHighlightedProps[`category${index}`] = {\n type: 'object',\n title: 'admin/editor.categoriesHighlighted.category',\n properties: {\n name: {\n type: 'string',\n default: '',\n title: 'admin/editor.categoriesHighlighted.item.categoryName',\n },\n image: {\n type: 'string',\n title: 'admin/editor.categoriesHighlighted.item.categoryImage',\n default: '',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n },\n }\n })\n\n return {\n title: 'admin/editor.categoriesHighlighted.title',\n description: 'admin/editor.categoriesHighlighted.description',\n type: 'object',\n properties: {\n showCategoriesHighlighted: {\n type: 'boolean',\n title: 'admin/editor.categoriesHighlighted.showCategoriesHighlighted',\n default: false,\n isLayout: true,\n },\n quantityOfItems: {\n type: 'number',\n title: 'admin/editor.categoriesHighlighted.quantityOfItems',\n enum: [2, 4],\n default: 2,\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n isLayout: true,\n },\n cardShape: {\n type: 'string',\n title: 'admin/editor.categoriesHighlighted.cardShape',\n enum: [SQUARED, RECTANGULAR],\n enumNames: [\n 'admin/editor.categoriesHighlighted.cardShape.squared',\n 'admin/editor.categoriesHighlighted.cardShape.rectangular',\n ],\n default: SQUARED,\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n isLayout: true,\n },\n categoriesHighlighted: {\n type: 'object',\n title: 'admin/editor.categoriesHighlighted.categoriesHighlighted',\n properties: categoriesHighlightedProps,\n isLayout: false,\n },\n },\n }\n }\n\n render() {\n const {\n categoriesHighlighted,\n showCategoriesHighlighted,\n quantityOfItems,\n cardShape,\n } = this.props\n\n if (!showCategoriesHighlighted) return null\n\n let categories = values(categoriesHighlighted).map(category => category)\n range(categories.length, quantityOfItems).forEach(() => {\n categories.push({\n name: '',\n image: '',\n })\n })\n\n return (\n <div\n className={`${\n categoriesHighlights[`${cardShape}CategoriesHighlights`]\n } relative`}\n >\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {range(0, quantityOfItems / ITEMS_PER_ROW).map(indexRow => (\n <div\n key={`row${indexRow}`}\n className=\"flex flex-row flex-wrap items-center justify-center\"\n >\n {range(0, ITEMS_PER_ROW).map(indexCol => (\n <CategoryCard\n key={2 * indexRow + indexCol}\n shape={cardShape}\n {...categories[2 * indexRow + indexCol]}\n />\n ))}\n </div>\n ))}\n </div>\n </div>\n )\n }\n}\n\nexport default CategoriesHighlights\n\n```"
}
] |
code_store-on-localhost_e7e4bf04
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Share/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.shareContainer {}\n.shareLoader {}\n.shareLabel {}\n.shareButtons {}\n.shareSocialButton {}\n.shareSocialIcon {}\n```"
}
] |
code_store-on-localhost_0509bee8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Share/Wrapper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport ProductContext from '../../../ProductContext/ProductContext'\nimport { path, isEmpty } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\n\nimport Share from './index'\n\nconst ShareWrapper = props => {\n const { intl } = props\n\n const valuesFromContext = useContext(ProductContext)\n const { account } = useRuntime()\n\n const shareProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext)) {\n return props\n }\n\n const { selectedItem, product } = valuesFromContext\n\n const title = intl.formatMessage(\n { id: 'store/share.title' },\n {\n product: path(['productName'], product),\n sku: path(['name'], selectedItem),\n store: account,\n }\n )\n\n return {\n ...props,\n shareLabelClass: props.shareLabelClass || 'c-muted-2 t-small mb3',\n className: props.className || 'db',\n imageUrl: props.imageUrl || path(['items', 0, 'images', 0, 'imageUrl'], product),\n loading: props.loading != null ? props.loading : !path(['name'], selectedItem),\n title: props.title || title,\n }\n }\n\n return <Share {...shareProps()} />\n}\n\nShareWrapper.schema = Share.schema\n\nexport default injectIntl(ShareWrapper)\n\n```"
}
] |
code_store-on-localhost_f4d62938
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Share/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport { indexBy, prop } from 'ramda'\nimport React, { Component } from 'react'\nimport ContentLoader from 'react-content-loader'\nimport { FormattedMessage } from 'react-intl'\n\nimport SocialButton from './components/SocialButton'\nimport { SOCIAL_ENUM } from './constants/social'\nimport styles from './styles.css'\n\nclass Share extends Component {\n static propTypes = {\n /** Social Networks configuration */\n social: PropTypes.object,\n /** Share buttons options */\n options: PropTypes.shape({\n /** Share buttons size in pixels */\n size: PropTypes.number,\n }),\n /** Share URL title */\n title: PropTypes.string,\n /** Indcates if the component should render the Content Loader */\n loading: PropTypes.bool,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to Share label */\n shareLabelClass: PropTypes.string,\n /** Classes to be applied to social button */\n socialButtonClass: PropTypes.string,\n /** Classes to be applied to container of the buttons */\n buttonsContainerClass: PropTypes.string,\n /** Classes to be applied to icon of the button */\n socialIconClass: PropTypes.string,\n /** Classes to be applied to the Content Loader container */\n loaderContainerClass: PropTypes.string,\n /** Classes to be applied to the Content Loader */\n contentLoaderClass: PropTypes.string,\n /** Image url for share in social medias */\n imageUrl: PropTypes.string,\n }\n\n static Loader = (loaderProps = {}) => {\n const {\n 'vtex-share__button--loader': button,\n 'vtex-share__button--loader-1': button1,\n 'vtex-share__button--loader-2': button2,\n 'vtex-share__button--loader-3': button3,\n containerClass,\n contentLoaderClass,\n ...rest\n } = loaderProps\n const loaderStyles = {\n r: '1em',\n height: '2em',\n cy: '1em',\n ...button,\n }\n\n return (\n <div\n className={classNames(\n styles.shareContainer,\n styles.shareLoader,\n containerClass\n )}\n >\n <ContentLoader\n className={contentLoaderClass}\n style={{\n width: '100%',\n height: '100%',\n }}\n height=\"100\"\n width=\"100\"\n {...rest}\n >\n <circle cx=\"1em\" {...loaderStyles} {...button1} />\n <circle cx=\"3.5em\" {...loaderStyles} {...button2} />\n <circle cx=\"6em\" {...loaderStyles} {...button3} />\n </ContentLoader>\n </div>\n )\n }\n\n static defaultProps = {\n social: {\n Facebook: true,\n Twitter: true,\n WhatsApp: true,\n Pinterest: true,\n },\n options: {},\n className: 'flex flex-row flex-wrap w-100',\n shareLabelClass: 'pv2 pr3 t-small',\n buttonsContainerClass: 'flex flex-row',\n }\n\n static schema = {\n title: 'admin/editor.share.title',\n description: 'admin/editor.share.description',\n type: 'object',\n properties: {\n social: {\n title: 'admin/editor.share.social.title',\n type: 'object',\n properties: {\n ...indexBy(\n prop('title'),\n SOCIAL_ENUM.map(socialNetwork => ({\n type: 'boolean',\n title: socialNetwork,\n default: Share.defaultProps.social[socialNetwork],\n }))\n ),\n },\n },\n },\n }\n\n render() {\n const {\n social,\n title,\n loading,\n options: { size },\n className,\n shareLabelClass,\n buttonsContainerClass,\n socialButtonClass,\n socialIconClass,\n loaderContainerClass,\n contentLoaderClass,\n imageUrl,\n } = this.props\n\n if (loading) {\n return (\n <Share.Loader\n containerClass={loaderContainerClass}\n contentLoaderClass={contentLoaderClass}\n {...this.props.styles}\n />\n )\n }\n\n return (\n <div className={classNames(styles.shareContainer, className)}>\n <div className={classNames(styles.shareLabel, shareLabelClass)}>\n <FormattedMessage id=\"store/store-components.share.label\" />\n </div>\n <div className={classNames(styles.shareButtons, buttonsContainerClass)}>\n {Object.keys(social).map(\n (socialNetwork, index) =>\n social[socialNetwork] && (\n <SocialButton\n key={index}\n imageUrl={imageUrl}\n url={window.location && window.location.href}\n message={title}\n iconClass={socialIconClass}\n buttonClass={socialButtonClass}\n socialEnum={socialNetwork}\n size={size}\n />\n )\n )}\n </div>\n </div>\n )\n }\n}\n\nexport default Share\n\n```"
}
] |
code_store-on-localhost_cf0b19f8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SearchBar/components/SearchBar.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useRef, useCallback, useState, useEffect, useMemo } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport Downshift from 'downshift'\nimport debounce from 'debounce'\nimport {\n NoSSR,\n useRuntime,\n ExtensionPoint,\n useChildBlock,\n} from '../../../../../../../vtex.render-runtime'\nimport Overlay from '../../../../ReactPortal/Overlay'\nimport useCssHandles from '../../../../CssHandles/useCssHandles'\nimport { defineMessages } from 'react-intl'\nimport styles from '../styles.css'\n\nimport AutocompleteResults from '../../AutocompleteResults'\n\nimport AutocompleteInput from './AutocompleteInput'\n\nconst CSS_HANDLES = ['searchBarInnerContainer']\nconst SEARCH_DELAY_TIME = 500\nconst AUTCOMPLETE_EXTENSION_ID = 'autocomplete-result-list'\n\nconst messages = defineMessages({\n searchTermTooShort: {\n id: 'store/search.search-term-too-short',\n defaultMessage: '',\n },\n})\n\nconst SearchBar = ({\n placeholder,\n onInputChange,\n onGoToSearchPage,\n onClearInput,\n inputValue,\n compactMode,\n hasIconLeft,\n iconClasses,\n iconBlockClass,\n autoFocus,\n maxWidth,\n attemptPageTypeSearch,\n customSearchPageUrl,\n autocompleteAlignment,\n openAutocompleteOnFocus,\n blurOnSubmit,\n submitOnIconClick,\n minSearchTermLength,\n autocompleteFullWidth,\n intl,\n}) => {\n const container = useRef()\n const { navigate } = useRuntime()\n const handles = useCssHandles(CSS_HANDLES)\n const [searchTerm, setSearchTerm] = useState(inputValue)\n const [inputErrorMessage, setInputErrorMessage] = useState()\n\n const debouncedSetSearchTerm = useCallback(\n debounce(newValue => {\n setSearchTerm(newValue)\n }, SEARCH_DELAY_TIME),\n []\n )\n\n useEffect(() => {\n debouncedSetSearchTerm(inputValue)\n }, [debouncedSetSearchTerm, inputValue])\n\n const onSelect = useCallback(\n element => {\n if (!element) {\n return\n }\n\n if (element.term) {\n if (attemptPageTypeSearch) {\n window.location.href = `/${element.term}`\n return\n }\n\n if (customSearchPageUrl) {\n navigate({\n to: customSearchPageUrl.replace(/\\$\\{term\\}/g, element.term),\n })\n\n return\n }\n\n navigate({\n page: 'store.search',\n params: { term: element.term },\n query: 'map=ft',\n })\n return\n }\n\n let page = 'store.product'\n let params = {\n slug: element.slug,\n id: element.productId,\n }\n let query = ''\n const terms = element.slug.split('/')\n\n if (element.criteria) {\n // This param is only useful to track terms searched\n // See: https://support.google.com/analytics/answer/1012264\n const paramForSearchTracking = '&_c=' + terms[0]\n\n page = 'store.search'\n params = { term: terms[0] }\n query =\n `map=c,ft&rest=${terms.slice(1).join(',')}` + paramForSearchTracking\n }\n\n navigate({ page, params, query })\n },\n [navigate, attemptPageTypeSearch, customSearchPageUrl]\n )\n\n const validateInput = () => {\n if (minSearchTermLength && inputValue.length < minSearchTermLength) {\n return intl.formatMessage(messages.searchTermTooShort)\n }\n\n return null\n }\n\n const showInputErrorMessage = inputErrorMessage => {\n setInputErrorMessage(inputErrorMessage)\n }\n\n const hideInputErrorMessage = () => {\n setInputErrorMessage()\n }\n\n const fallback = (\n <AutocompleteInput\n placeholder={placeholder}\n onInputChange={onInputChange}\n inputValue={inputValue}\n hasIconLeft={hasIconLeft}\n iconClasses={iconClasses}\n iconBlockClass={iconBlockClass}\n inputErrorMessage={inputErrorMessage}\n onGoToSearchPage={onGoToSearchPage}\n />\n )\n\n const isAutocompleteDeclared = Boolean(\n useChildBlock({ id: AUTCOMPLETE_EXTENSION_ID })\n )\n\n const SelectedAutocompleteResults = useMemo(() => {\n return isAutocompleteDeclared\n ? props => <ExtensionPoint id={AUTCOMPLETE_EXTENSION_ID} {...props} />\n : props => <AutocompleteResults {...props} />\n }, [isAutocompleteDeclared])\n\n return (\n <div\n ref={container}\n className={classNames('w-100 mw7 pv4', styles.searchBarContainer)}\n style={{\n ...(maxWidth && {\n maxWidth: typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth,\n }),\n }}\n >\n <NoSSR onSSR={fallback}>\n <Downshift onSelect={onSelect}>\n {({\n getInputProps,\n getItemProps,\n getMenuProps,\n selectedItem,\n highlightedIndex,\n isOpen,\n closeMenu,\n openMenu,\n }) => (\n <div\n className={classNames(\n 'relative-m w-100',\n handles.searchBarInnerContainer\n )}\n >\n <AutocompleteInput\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={autoFocus}\n compactMode={compactMode}\n onClearInput={onClearInput}\n hasIconLeft={hasIconLeft}\n iconClasses={iconClasses}\n onGoToSearchPage={onGoToSearchPage}\n submitOnIconClick={submitOnIconClick}\n openAutocompleteOnFocus={openAutocompleteOnFocus}\n openMenu={openMenu}\n inputErrorMessage={inputErrorMessage}\n {...getInputProps({\n onKeyDown: event => {\n // Only call default search function if user doesn't\n // have any item highlighted in the menu options\n if (event.key === 'Enter' && highlightedIndex === null) {\n const errorMessage = validateInput()\n\n if (errorMessage) {\n showInputErrorMessage(errorMessage)\n return\n }\n\n if (blurOnSubmit) {\n event.currentTarget.blur()\n }\n\n onGoToSearchPage()\n closeMenu()\n } else {\n hideInputErrorMessage()\n }\n },\n placeholder,\n value: inputValue,\n onChange: onInputChange,\n onFocus: openAutocompleteOnFocus ? openMenu : undefined,\n })}\n />\n <Overlay\n alignment={autocompleteAlignment}\n fullWindow={autocompleteFullWidth}\n >\n <SelectedAutocompleteResults\n parentContainer={container}\n {...{\n attemptPageTypeSearch,\n isOpen,\n getMenuProps,\n inputValue: searchTerm,\n getItemProps,\n selectedItem,\n highlightedIndex,\n closeMenu,\n onClearInput,\n customSearchPageUrl,\n }}\n />\n </Overlay>\n </div>\n )}\n </Downshift>\n </NoSSR>\n </div>\n )\n}\n\nSearchBar.propTypes = {\n /** Placeholder to be used on the input */\n placeholder: PropTypes.string.isRequired,\n /** Current value of the input */\n inputValue: PropTypes.string.isRequired,\n /** Function to handle input changes */\n onInputChange: PropTypes.func.isRequired,\n /** Function to direct the user to the searchPage */\n onGoToSearchPage: PropTypes.func.isRequired,\n /** Function to clear the input */\n onClearInput: PropTypes.func.isRequired,\n /** Indentify when use the compact version of the component */\n compactMode: PropTypes.bool,\n /** Identify if the search icon is on left or right position */\n hasIconLeft: PropTypes.bool,\n /** Custom classes for the search icon */\n iconClasses: PropTypes.string,\n /** Block class for the search icon */\n iconBlockClass: PropTypes.string,\n /** Identify if the search input should autofocus or not */\n autoFocus: PropTypes.bool,\n /** Max width of the search bar */\n maxWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /** A template for a custom url. It can have a substring ${term} used as placeholder to interpolate the searched term. (e.g. `/search?query=${term}`) */\n customSearchPageUrl: PropTypes.string,\n /** Uses the term the user has inputed to try to navigate to the proper\n * page type (e.g. a department, a brand, a category)\n */\n attemptPageTypeSearch: PropTypes.bool,\n /* Autocomplete Horizontal alignment */\n autocompleteAlignment: PropTypes.string,\n /** Identify if autocomplete should be open on input focus or not */\n openAutocompleteOnFocus: PropTypes.bool,\n /** Identify if input should blur on submit */\n blurOnSubmit: PropTypes.bool,\n /** Identify if icon should submit on click */\n submitOnIconClick: PropTypes.bool,\n /** Minimum search term length allowed */\n minSearchTermLength: PropTypes.number,\n /** If true, the autocomplete will fill the whole window horizontally */\n autocompleteFullWidth: PropTypes.bool,\n}\n\nexport default SearchBar\n\n```"
}
] |
code_store-on-localhost_230d1852
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SearchBar/components/AutocompleteInput.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useRef, useEffect } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport Input from '../../../../Styleguide/Input'\nimport { ExtensionPoint, useChildBlock } from '../../../../../../../vtex.render-runtime'\nimport useCssHandles from '../../../../CssHandles/useCssHandles'\n\nimport IconSearch from '../../../../StoreIcons/IconSearch'\nimport IconClose from '../../../../StoreIcons/IconClose'\n\n/** Midleware component to adapt the styleguide/Input to be used by the Downshift*/\nconst CSS_HANDLES = [\n 'searchBarIcon',\n 'compactMode',\n 'autoCompleteOuterContainer',\n 'paddingInput',\n]\n\nconst CloseIcon = () => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-close' }))\n\n if (hasIconBlock) {\n return <ExtensionPoint id=\"icon-close\" size={22} type=\"line\" />\n }\n\n return <IconClose type=\"line\" size={22} />\n}\n\nconst SearchIcon = () => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-search' }))\n\n if (hasIconBlock) {\n return <ExtensionPoint id=\"icon-search\" />\n }\n\n return <IconSearch />\n}\n\nconst AutocompleteInput = ({\n onClearInput,\n compactMode,\n value,\n hasIconLeft,\n iconBlockClass,\n iconClasses,\n autoFocus,\n onGoToSearchPage,\n submitOnIconClick,\n openMenu,\n inputErrorMessage,\n ...restProps\n}) => {\n const inputRef = useRef(null)\n const handles = useCssHandles(CSS_HANDLES)\n\n useEffect(() => {\n const changeClassInput = () => {\n if (compactMode) {\n inputRef.current.placeholder = ''\n inputRef.current.classList.add(handles.paddingInput)\n }\n }\n\n changeClassInput()\n autoFocus && inputRef.current.focus()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const suffix = (\n <button\n className={`${iconClasses || ''} ${\n handles.searchBarIcon\n } flex items-center pointer bn bg-transparent outline-0`}\n onClick={\n submitOnIconClick ? onGoToSearchPage : () => value && onClearInput()\n }\n >\n {value && !submitOnIconClick ? (\n <CloseIcon />\n ) : (\n !hasIconLeft && <SearchIcon />\n )}\n </button>\n )\n\n const prefix = (\n <span className={`${iconClasses} ${handles.searchBarIcon}`}>\n <SearchIcon />\n </span>\n )\n\n const classContainer = classNames('w-100', {\n [handles.compactMode]: compactMode,\n })\n\n return (\n <div className={`${handles.autoCompleteOuterContainer} flex`}>\n <div className={classContainer}>\n <Input\n ref={inputRef}\n size=\"large\"\n value={value}\n prefix={hasIconLeft && prefix}\n suffix={suffix}\n {...restProps}\n error={Boolean(inputErrorMessage)}\n errorMessage={inputErrorMessage}\n />\n </div>\n </div>\n )\n}\n\nAutocompleteInput.propTypes = {\n /** Downshift prop to be passed to the input */\n autoComplete: PropTypes.string,\n /** Input ID */\n id: PropTypes.string,\n /** Downshift prop to be passed to the input */\n onBlur: PropTypes.func,\n /** Downshift prop to be passed to the input */\n onChange: PropTypes.func,\n /** Downshift prop to be passed to the input */\n onKeyDown: PropTypes.func,\n /** Downshift prop to be passed to the input */\n value: PropTypes.string,\n /** Downshift func to open the menu */\n openMenu: PropTypes.func,\n /** Placeholder to be used on the input */\n placeholder: PropTypes.string,\n compactMode: PropTypes.bool,\n /** Clears the input */\n onClearInput: PropTypes.func,\n /** Identify if the search icon is on left or right position */\n hasIconLeft: PropTypes.bool,\n /** Custom classes for the search icon */\n iconClasses: PropTypes.string,\n /** Block class for the search icon */\n iconBlockClass: PropTypes.string,\n /** Identify if the search input should autofocus or not */\n autoFocus: PropTypes.bool,\n /** Function to direct the user to the searchPage */\n onGoToSearchPage: PropTypes.func.isRequired,\n /** Identify if icon should submit on click */\n submitOnIconClick: PropTypes.bool,\n /** Error message showed in search input */\n inputErrorMessage: PropTypes.string,\n}\n\nexport default AutocompleteInput\n\n```"
}
] |
code_store-on-localhost_3e8effad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/mutations/setOpenMinicart.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation setMinicartOpen($isOpen: Boolean!) {\n setMinicartOpen(isOpen: $isOpen) @client\n}\n\n```"
}
] |
code_store-on-localhost_acae12a7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/mutations/addToCart.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation addToCart($items: [MinicartItem]) {\n addToCart(items: $items) @client\n}\n\n```"
}
] |
code_store-on-localhost_b09a6673
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/queries/installedApp.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery installedAppPublic($slug: String!) {\n installedAppPublic(slug: $slug) @context(provider: \"vtex.apps-graphql\") {\n version\n }\n}\n\n```"
}
] |
code_store-on-localhost_b85ecbdc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/hooks/useMarketingSessionParams.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useState } from 'react'\n\nimport { path, pathOr } from 'ramda'\n\nconst getUtmParams = (publicFields) => ({\n source: path(['utm_source', 'value'], publicFields),\n medium: path(['utm_medium', 'value'], publicFields),\n campaign: path(['utm_campaign', 'value'], publicFields),\n})\n\nconst getUtmiParams = (publicFields) => ({\n campaign: path(['utmi_cp', 'value'], publicFields),\n page: path(['utmi_p', 'value'], publicFields),\n part: path(['utmi_pc', 'value'], publicFields),\n})\n\nconst getSessionPromiseFromWindow = () =>\n !window.__RENDER_8_SESSION__ || !window.__RENDER_8_SESSION__.sessionPromise\n ? Promise.resolve(null)\n : window.__RENDER_8_SESSION__.sessionPromise\n\nconst useMarketingSessionParams = () => {\n const [utmParams, setUtmParams] = useState(undefined)\n const [utmiParams, setUtmiParams] = useState(undefined)\n\n useEffect(() => {\n getSessionPromiseFromWindow().then(data => {\n const publicFields = pathOr({}, ['response', 'namespaces', 'public'], data)\n if (Object.keys(publicFields).length === 0) {\n return\n }\n \n setUtmParams(getUtmParams(publicFields))\n setUtmiParams(getUtmiParams(publicFields))\n }).catch(() => {\n // Do nothing!\n })\n }, [])\n\n return { utmParams, utmiParams }\n}\n\nexport default useMarketingSessionParams\n\n```"
}
] |
code_store-on-localhost_fe5c4682
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Greeting/queries/orderForm.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery orderFormQuery {\n minicart @client {\n orderForm\n }\n}\n\n```"
}
] |
code_store-on-localhost_4b73e627
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/utils/ItemsPerPage.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { path } from 'ramda'\n\nfunction getItemWidth(slick, maxWidth) {\n const slidesNodeList = path(\n ['innerSlider', 'list', 'childNodes', '0', 'childNodes'],\n slick\n )\n let itemWidth = null\n if (slidesNodeList) {\n const slidesArray = Array.prototype.slice.call(slidesNodeList)\n slidesArray.map(slide => {\n const attributes = Array.prototype.slice.call(slide.attributes)\n attributes.map(attr => {\n if (attr.nodeName === 'data-index' && attr.nodeValue === '0') {\n itemWidth = path(['childNodes', '0', 'clientWidth'], slide)\n if (maxWidth && maxWidth < itemWidth) itemWidth = maxWidth\n }\n })\n })\n }\n return itemWidth || maxWidth\n}\n\n/**\n * Returns the correct number of items to be inside the slider without reduce the item width.\n */\nexport default function getItemsPerPage(\n slick,\n slideWidth,\n defaultItemWidth,\n actualItemsPerPage\n) {\n if (slideWidth) {\n const shelfItemWidth = getItemWidth(slick, defaultItemWidth)\n const maxItemsPerPage = Math.floor(slideWidth / shelfItemWidth)\n if (actualItemsPerPage >= maxItemsPerPage) {\n return maxItemsPerPage || 1\n }\n }\n return actualItemsPerPage\n}\n\n```"
}
] |
code_store-on-localhost_9964c470
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/components/Arrow.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\n/**\n * Arrow component. It's an overriden component of react-slick that controls\n * the slide transition.\n */\nexport default class Arrow extends Component {\n render() {\n const { className, style, onClick, cssClass, customClasses } = this.props\n const arrowClasses = classNames({\n [`${className}`]: className,\n [`${cssClass}`]: cssClass,\n [`${customClasses}`]: customClasses,\n })\n\n return (\n <div\n className={`${arrowClasses}`}\n style={{ ...style }}\n onClick={onClick}\n />\n )\n }\n}\n\nArrow.propTypes = {\n /** (react-slick prop) Css class of the element. */\n className: PropTypes.string,\n /** (react-slick prop) Custom style of the element. */\n style: PropTypes.object,\n /** (react-slick prop) Function to be called when the arrow is clicked. */\n onClick: PropTypes.func,\n /** Specifies wich css class the arrow will receive. */\n cssClass: PropTypes.string.isRequired,\n /** Custom classes */\n customClasses: PropTypes.string,\n}\n\n```"
}
] |
code_store-on-localhost_0cc8389b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Slider/components/Dots.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\n/**\n * Dots component. It's an overriden component of react-slick that controls\n * the slide transition;\n */\nexport default class Dots extends Component {\n render() {\n const { className, style, dots, cssClass, customClass } = this.props\n const dotsClasses = classNames([className, cssClass, customClass])\n\n return (\n <div className={dotsClasses}>\n <ul className=\"ma0 pa0\" style={{ ...style }}>\n {dots}\n </ul>\n </div>\n )\n }\n}\n\nDots.propTypes = {\n /** (react-slick prop) Css class of the element. */\n className: PropTypes.string,\n /** Dots custom classes passed by props. */\n customClass: PropTypes.string,\n /** (react-slick prop) Custom style of the element. */\n style: PropTypes.object,\n /** (react-slick prop) Dots that will be displayed */\n dots: PropTypes.node.isRequired,\n /** Specifies wich css the dots will receive. */\n cssClass: PropTypes.string.isRequired,\n}\n\n```"
}
] |
code_store-on-localhost_5c9225df
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/utils/generateUrl.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport function changeImageUrlSize(url: string, width: number | string, height: number | string): string\n```"
}
] |
code_store-on-localhost_dc1fec42
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/utils/aspectRatioUtil.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { changeImageUrlSize } from './generateUrl'\n\ntype AspectRatio = string | number\n\n/** Parses ratio values into a multiplier to set the image height.\n * For example, turns \"3:4\" into 1.333, so the image height will be \n * 1.333 times its width.\n*/\nconst parseAspectRatio = (input?: AspectRatio | null) => {\n if (!input) {\n return null\n }\n if (typeof input === 'string') {\n if (input === 'auto') { \n return null\n }\n const separator = ':'\n const data = input.split(separator)\n if (data.length !== 2) {\n return null\n }\n\n const [ width, height ] = data\n const ratio = parseFloat(height) / parseFloat(width)\n\n if (typeof ratio !== 'number' || isNaN(ratio)) {\n return null\n }\n\n return ratio\n }\n\n if (typeof input === 'number') {\n return input\n }\n\n return null\n}\n\nexport const imageUrl = (src: string, size: number, maxSize: number, aspectRatio?: AspectRatio) => {\n let width = size\n let height: number | string = 'auto'\n\n if (aspectRatio && aspectRatio !== 'auto') {\n height = size * (parseAspectRatio(aspectRatio) || 1)\n\n if (width > maxSize) {\n height = height / (width / maxSize) \n width = maxSize\n }\n\n if (height > maxSize) {\n width = width / (height / maxSize)\n height = maxSize\n }\n\n width = Math.round(width)\n height = Math.round(height)\n } else {\n width = Math.min(maxSize, width)\n }\n\n return changeImageUrlSize(src, width, height)\n}\n\n```"
}
] |
code_store-on-localhost_742cae65
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/utils/enums.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const THUMBS_POSITION_HORIZONTAL = {\n LEFT: 'left',\n RIGHT: 'right',\n}\n\nexport const THUMBS_ORIENTATION = {\n VERTICAL: 'vertical',\n HORIZONTAL: 'horizontal',\n}\n\nexport const DEFAULT_EXCLUDE_IMAGE_WITH = 'skuvariation'\n\n```"
}
] |
code_store-on-localhost_d112e02a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/utils/generateUrl.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n\nexport function cleanImageUrl(imageUrl) {\n const result = baseUrlRegex.exec(imageUrl)\n if (result.length > 0) return result[0]\n}\n\nfunction replaceLegacyFileManagerUrl(imageUrl, width, height) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n if (!isLegacyUrl) return imageUrl\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize(\n imageUrl,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT,\n) {\n if (!imageUrl) return\n typeof width === 'number' && (width = Math.min(width, MAX_WIDTH))\n typeof height === 'number' && (height = Math.min(height, MAX_HEIGHT))\n\n const normalizedImageUrl = replaceLegacyFileManagerUrl(imageUrl, width, height)\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\n```"
}
] |
code_store-on-localhost_bed84bcf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/utils/generateImageConfig.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { changeImageUrlSize } from './generateUrl'\n\nconst thumbnailSize = 160\n\nexport default function generateImageConfig (image) {\n return {\n imageUrl: image.imageUrl,\n thumbnailUrl: changeImageUrlSize(image.imageUrl, thumbnailSize),\n imageText: image.imageText,\n imageLabel: image.imageLabel,\n }\n}\n```"
}
] |
code_store-on-localhost_41772148
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/ProductImage.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo, useRef } from 'react'\nimport Zoomable, { ZoomMode } from './Zoomable'\nimport { imageUrl } from '../utils/aspectRatioUtil'\nimport useCssHandles from '../../../../CssHandles/useCssHandles'\n\nconst IMAGE_SIZES = [600, 800, 1200]\nconst DEFAULT_SIZE = 800\nconst MAX_SIZE = 2048\n\ninterface Props {\n src: string\n alt: string\n zoomMode: ZoomMode\n zoomFactor: number\n aspectRatio?: AspectRatio\n maxHeight?: number\n}\n\ntype AspectRatio = string | number\n\nconst CSS_HANDLES = [\n 'productImage',\n 'productImageTag'\n]\n\nconst ProductImage: FC<Props> = ({\n src,\n alt,\n zoomMode = ZoomMode.InPlaceClick,\n zoomFactor = 2,\n aspectRatio='auto',\n maxHeight = 600,\n}) => {\n const srcSet = useMemo(() => (\n IMAGE_SIZES\n .map(size => `${imageUrl(src, size, MAX_SIZE, aspectRatio)} ${size}w`)\n .join(',')\n ), [src, aspectRatio, IMAGE_SIZES])\n const handles = useCssHandles(CSS_HANDLES)\n\n const imageRef = useRef(null)\n\n return (\n <div className={handles.productImage}>\n <Zoomable\n mode={zoomMode}\n factor={zoomFactor}\n zoomContent={(\n <img\n src={imageUrl(src, DEFAULT_SIZE * zoomFactor, MAX_SIZE, aspectRatio)}\n className={handles.productImageTag}\n style={{\n // Resets possible resizing done via CSS\n maxWidth: 'unset',\n width: `${zoomFactor * 100}%`,\n height: `${zoomFactor * 100}%`,\n objectFit: 'contain',\n }}\n\n // See comment regarding sizes below\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n />\n )}>\n <img\n ref={imageRef}\n className={handles.productImageTag}\n style={{\n width: '100%',\n height: '100%',\n maxHeight: maxHeight || 'unset',\n objectFit: 'contain',\n }}\n src={imageUrl(src, DEFAULT_SIZE, MAX_SIZE, aspectRatio)}\n srcSet={srcSet}\n alt={alt}\n title={alt}\n loading=\"lazy\"\n\n // WIP\n // The value of the \"sizes\" attribute means: if the window has at most 64.1rem of width,\n // the image will be of a width of 100vw. Otherwise, the\n // image will be 50vw wide.\n // This size is used for picking the best available size\n // given the ones from the srcset above.\n //\n // This is WIP because it is a guess: we are assuming\n // the image will be of a certain size, but it should be\n // probably be gotten from flex-layout or something.\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n />\n </Zoomable>\n </div>\n )\n}\n\nexport default ProductImage\n```"
}
] |
code_store-on-localhost_30a67aa2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Video/Vimeo.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Vimeo extends Component {\n constructor(props) {\n super(props)\n\n this.state = { iframe: {} }\n\n const { loop, autoplay, width, height, showTitle, url } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&title=${showTitle}&width=${width}&height=${height}`\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}&${params}`\n\n this.iframeRef = React.createRef()\n\n fetch(getUrl)\n .then(response => response.json())\n .then(response => {\n const { height, width, html, title } = response\n\n const thumbUrl = Vimeo.thumbUrlFromResp(response, props.thumbWidth)\n props.setThumb && props.setThumb(thumbUrl, title)\n\n const src = html.match(/src= *\" *([^\"]*) *\"/)[1] // Get url from response\n\n this.setState({\n iframe: {\n divStyle: { padding: `${(100 * height) / width}% 0 0 0` },\n src: src,\n },\n })\n })\n }\n\n static getThumbUrl = (url) => {\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}`\n return fetch(getUrl)\n .then(response => response.json())\n .then(response => response.thumbnail_url)\n }\n\n static thumbUrlFromResp(response, thumbWidth) {\n const { height, width } = response\n const thumb = response.thumbnail_url_with_play_button\n\n thumbWidth = thumbWidth || response.thumbnail_width\n const thumbHeight = Math.ceil((thumbWidth * height) / width)\n\n return thumb.replace(\n /_[0123456789]*x[0123456789]*./,\n `_${thumbWidth}x${thumbHeight}.`\n )\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const vimeoCommand = JSON.stringify({ method: command })\n this.iframeRef.contentWindow.postMessage(\n vimeoCommand,\n 'https://player.vimeo.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id, cssHandles } = this.props\n\n this.props.playing\n ? this.executeCommand('play')()\n : this.executeCommand('pause')()\n\n return (\n <div style={iframe.divStyle} className={`relative ${className} ${cssHandles.videoContainer}`}>\n <iframe\n ref={this.iframeRef}\n title={id}\n className={`${cssHandles.video} absolute top-0 left-0 w-100 h-100`}\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nVimeo.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n showTitle: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n}\n\nVimeo.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n showTitle: false,\n className: '',\n}\n\nexport default Vimeo\n\n```"
}
] |
code_store-on-localhost_550a7b8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Video/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { match, compose, isEmpty, complement } from 'ramda'\n\nimport Vimeo from './Vimeo'\nimport YouTube from './Youtube'\n\nimport useCssHandles from '../../../../../CssHandles/useCssHandles'\n\nconst isNotEmpty = complement(isEmpty)\n\nconst isVimeo = compose(isNotEmpty, match(/vimeo/))\nconst isYoutube = compose(isNotEmpty, match(/youtube|youtu.be/)) \n\nconst CSS_HANDLES = ['productVideo', 'videoContainer', 'video']\n\nexport function getThumbUrl(url, thumbWidth) {\n if (isVimeo(url)) {\n return Vimeo.getThumbUrl(url, thumbWidth)\n }\n\n else if (isYoutube(url)) {\n return YouTube.getThumbUrl(url, thumbWidth)\n }\n}\n\nfunction Video(props) {\n const { url } = props\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <div className={handles.productVideo}>\n {isVimeo(url) && <Vimeo {...props} cssHandles={handles} />}\n {isYoutube(url) && <YouTube {...props} cssHandles={handles} />}\n </div>\n )\n}\n\nVideo.propsTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired,\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n play: PropTypes.bool,\n}\n\nexport default Video\n\n```"
}
] |
code_store-on-localhost_013a5522
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Video/Youtube.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Youtube extends Component {\n constructor(props) {\n super(props)\n\n const { loop, autoplay, title, url } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&title=${title}&enablejsapi=1&iv_load_policy=3&modestbranding=1`\n const videoId = Youtube.extractVideoID(url)\n\n this.iframeRef = React.createRef()\n this.state = {\n iframe: {\n src: `https://www.youtube.com/embed/${videoId}?${params}`,\n }\n }\n }\n\n static getThumbUrl = (url) => {\n const videoId = Youtube.extractVideoID(url)\n return Promise.resolve(`https://img.youtube.com/vi/${videoId}/default.jpg`)\n }\n\n static extractVideoID = url => {\n const regExp = /^.*((youtu.be\\/)|(v\\/)|(\\/u\\/\\w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#&?]*).*/\n const match = url.match(regExp)\n if (match && match[7].length === 11) return match[7]\n return null\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const youtubeCommand = JSON.stringify({ event: 'command', func: command })\n this.iframeRef.contentWindow.postMessage(\n youtubeCommand,\n 'https://www.youtube.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id, cssHandles } = this.props\n\n this.props.playing\n ? this.executeCommand('playVideo')()\n : this.executeCommand('pauseVideo')()\n\n return (\n <div\n className={`relative ${className} ${cssHandles.videoContainer}`}\n style={{ padding: '30%' }}\n >\n <iframe\n ref={this.iframeRef}\n title={id}\n className={`${cssHandles.video} absolute top-0 left-0 w-100 h-100`}\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nYoutube.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n showTitle: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n title: PropTypes.string,\n}\n\nYoutube.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n title: false,\n className: '',\n}\n\nexport default Youtube\n\n```"
}
] |
code_store-on-localhost_2c1b5637
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Gallery/global.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.pswp{display:none;position:absolute;width:100%;height:100%;left:0;top:0;overflow:hidden;-ms-touch-action:none;touch-action:none;z-index:1500;-webkit-text-size-adjust:100%;-webkit-backface-visibility:hidden;outline:none}.pswp *{-webkit-box-sizing:border-box;box-sizing:border-box}.pswp img{max-width:none}.pswp--animate_opacity{opacity:.001;will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--open{display:block}.pswp--zoom-allowed .pswp__img{cursor:-webkit-zoom-in;cursor:-moz-zoom-in;cursor:zoom-in}.pswp--zoomed-in .pswp__img{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.pswp--dragging .pswp__img{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.pswp__bg{background:#000;opacity:0;-webkit-transform:translateZ(0);transform:translateZ(0);-webkit-backface-visibility:hidden}.pswp__bg,.pswp__scroll-wrap{position:absolute;left:0;top:0;width:100%;height:100%}.pswp__scroll-wrap{overflow:hidden}.pswp__container,.pswp__zoom-wrap{-ms-touch-action:none;touch-action:none;position:absolute;left:0;right:0;top:0;bottom:0}.pswp__container,.pswp__img{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none}.pswp__zoom-wrap{position:absolute;width:100%;-webkit-transform-origin:left top;transform-origin:left top;-webkit-transition:-webkit-transform 333ms cubic-bezier(.4,0,.22,1);transition:-webkit-transform 333ms cubic-bezier(.4,0,.22,1);transition:transform 333ms cubic-bezier(.4,0,.22,1);transition:transform 333ms cubic-bezier(.4,0,.22,1),-webkit-transform 333ms cubic-bezier(.4,0,.22,1)}.pswp__bg{will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--animated-in .pswp__bg,.pswp--animated-in .pswp__zoom-wrap{-webkit-transition:none;transition:none}.pswp__container,.pswp__zoom-wrap{-webkit-backface-visibility:hidden}.pswp__item{right:0;bottom:0;overflow:hidden}.pswp__img,.pswp__item{position:absolute;left:0;top:0}.pswp__img{width:auto;height:auto}.pswp__img--placeholder{-webkit-backface-visibility:hidden}.pswp__img--placeholder--blank{background:#222}.pswp--ie .pswp__img{width:100%!important;height:auto!important;left:0;top:0}.pswp__error-msg{position:absolute;left:0;top:50%;width:100%;text-align:center;font-size:14px;line-height:16px;margin-top:-8px;color:#ccc}.pswp__error-msg a{color:#ccc;text-decoration:underline}.pswp__button{width:44px;height:44px;position:relative;background:none;cursor:pointer;overflow:visible;-webkit-appearance:none;display:block;border:0;padding:0;margin:0;float:right;opacity:.75;-webkit-transition:opacity .2s;transition:opacity .2s;-webkit-box-shadow:none;box-shadow:none}.pswp__button:focus,.pswp__button:hover{opacity:1}.pswp__button:active{outline:none;opacity:.9}.pswp__button::-moz-focus-inner{padding:0;border:0}.pswp__ui--over-close .pswp__button--close{opacity:1}.pswp__button,.pswp__button--arrow--left:before,.pswp__button--arrow--right:before{background:url(./default-skin.png) 0 0 no-repeat;background-size:264px 88px;width:44px;height:44px}@media (-webkit-min-device-pixel-ratio:1.1),(-webkit-min-device-pixel-ratio:1.09375),(min-resolution:1.1dppx),(min-resolution:105dpi){.pswp--svg .pswp__button,.pswp--svg .pswp__button--arrow--left:before,.pswp--svg .pswp__button--arrow--right:before{background-image:url(./default-skin.svg)}.pswp--svg .pswp__button--arrow--left,.pswp--svg .pswp__button--arrow--right{background:none}}.pswp__button--close{background-position:0 -44px}.pswp__button--share{background-position:-44px -44px}.pswp__button--fs{display:none}.pswp--supports-fs .pswp__button--fs{display:block}.pswp--fs .pswp__button--fs{background-position:-44px 0}.pswp__button--zoom{display:none;background-position:-88px 0}.pswp--zoom-allowed .pswp__button--zoom{display:block}.pswp--zoomed-in .pswp__button--zoom{background-position:-132px 0}.pswp--touch .pswp__button--arrow--left,.pswp--touch .pswp__button--arrow--right{visibility:hidden}.pswp__button--arrow--left,.pswp__button--arrow--right{background:none;top:50%;margin-top:-50px;width:70px;height:100px;position:absolute}.pswp__button--arrow--left{left:0}.pswp__button--arrow--right{right:0}.pswp__button--arrow--left:before,.pswp__button--arrow--right:before{content:\"\";top:35px;background-color:rgba(0,0,0,.3);height:30px;width:32px;position:absolute}.pswp__button--arrow--left:before{left:6px;background-position:-138px -44px}.pswp__button--arrow--right:before{right:6px;background-position:-94px -44px}.pswp__counter,.pswp__share-modal{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pswp__share-modal{display:block;background:rgba(0,0,0,.5);width:100%;height:100%;top:0;left:0;padding:10px;position:absolute;z-index:1600;opacity:0;-webkit-transition:opacity .25s ease-out;transition:opacity .25s ease-out;-webkit-backface-visibility:hidden;will-change:opacity}.pswp__share-modal--hidden{display:none}.pswp__share-tooltip{z-index:1620;position:absolute;background:#fff;top:56px;border-radius:2px;display:block;width:auto;right:44px;-webkit-box-shadow:0 2px 5px rgba(0,0,0,.25);box-shadow:0 2px 5px rgba(0,0,0,.25);-webkit-transform:translateY(6px);transform:translateY(6px);-webkit-transition:-webkit-transform .25s;transition:-webkit-transform .25s;transition:transform .25s;transition:transform .25s,-webkit-transform .25s;-webkit-backface-visibility:hidden;will-change:transform}.pswp__share-tooltip a{display:block;padding:8px 12px;font-size:14px;line-height:18px}.pswp__share-tooltip a,.pswp__share-tooltip a:hover{color:#000;text-decoration:none}.pswp__share-tooltip a:first-child{border-radius:2px 2px 0 0}.pswp__share-tooltip a:last-child{border-radius:0 0 2px 2px}.pswp__share-modal--fade-in{opacity:1}.pswp__share-modal--fade-in .pswp__share-tooltip{-webkit-transform:translateY(0);transform:translateY(0)}.pswp--touch .pswp__share-tooltip a{padding:16px 12px}a.pswp__share--facebook:before{content:\"\";display:block;width:0;height:0;position:absolute;top:-12px;right:15px;border:6px solid transparent;border-bottom-color:#fff;-webkit-pointer-events:none;-moz-pointer-events:none;pointer-events:none}a.pswp__share--facebook:hover{background:#3e5c9a;color:#fff}a.pswp__share--facebook:hover:before{border-bottom-color:#3e5c9a}a.pswp__share--twitter:hover{background:#55acee;color:#fff}a.pswp__share--pinterest:hover{background:#ccc;color:#ce272d}a.pswp__share--download:hover{background:#ddd}.pswp__counter{position:absolute;left:0;top:0;height:44px;font-size:13px;line-height:44px;color:#fff;opacity:.75;padding:0 10px}.pswp__caption{position:absolute;left:0;bottom:0;width:100%;min-height:44px}.pswp__caption small{font-size:11px;color:#bbb}.pswp__caption__center{text-align:left;max-width:420px;margin:0 auto;font-size:13px;padding:10px;line-height:20px;color:#ccc}.pswp__caption--empty{display:none}.pswp__caption--fake{visibility:hidden}.pswp__preloader{width:44px;height:44px;position:absolute;top:0;left:50%;margin-left:-22px;opacity:0;-webkit-transition:opacity .25s ease-out;transition:opacity .25s ease-out;will-change:opacity;direction:ltr}.pswp__preloader__icn{width:20px;height:20px;margin:12px}.pswp__preloader--active{opacity:1}.pswp__preloader--active .pswp__preloader__icn{background:url(./preloader.gif) 0 0 no-repeat}.pswp--css_animation .pswp__preloader--active{opacity:1}.pswp--css_animation .pswp__preloader--active .pswp__preloader__icn{-webkit-animation:clockwise .5s linear infinite;animation:clockwise .5s linear infinite}.pswp--css_animation .pswp__preloader--active .pswp__preloader__donut{-webkit-animation:donut-rotate 1s cubic-bezier(.4,0,.22,1) infinite;animation:donut-rotate 1s cubic-bezier(.4,0,.22,1) infinite}.pswp--css_animation .pswp__preloader__icn{background:none;opacity:.75;width:14px;height:14px;position:absolute;left:15px;top:15px;margin:0}.pswp--css_animation .pswp__preloader__cut{position:relative;width:7px;height:14px;overflow:hidden}.pswp--css_animation .pswp__preloader__donut{-webkit-box-sizing:border-box;box-sizing:border-box;width:14px;height:14px;border:2px solid #fff;border-radius:50%;border-left-color:transparent;border-bottom-color:transparent;position:absolute;top:0;left:0;background:none;margin:0}@media screen and (max-width:1024px){.pswp__preloader{position:relative;left:auto;top:auto;margin:0;float:right}}@-webkit-keyframes clockwise{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes clockwise{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes donut-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}50%{-webkit-transform:rotate(-140deg);transform:rotate(-140deg)}to{-webkit-transform:rotate(0);transform:rotate(0)}}@keyframes donut-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}50%{-webkit-transform:rotate(-140deg);transform:rotate(-140deg)}to{-webkit-transform:rotate(0);transform:rotate(0)}}.pswp__ui{-webkit-font-smoothing:auto;visibility:visible;opacity:1;z-index:1550}.pswp__top-bar{position:absolute;left:0;top:0;height:44px;width:100%}.pswp--has_mouse .pswp__button--arrow--left,.pswp--has_mouse .pswp__button--arrow--right,.pswp__caption,.pswp__top-bar{-webkit-backface-visibility:hidden;will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--has_mouse .pswp__button--arrow--left,.pswp--has_mouse .pswp__button--arrow--right{visibility:visible}.pswp__caption,.pswp__top-bar{background-color:rgba(0,0,0,.5)}.pswp__ui--fit .pswp__caption,.pswp__ui--fit .pswp__top-bar{background-color:rgba(0,0,0,.3)}.pswp__ui--idle .pswp__button--arrow--left,.pswp__ui--idle .pswp__button--arrow--right,.pswp__ui--idle .pswp__top-bar{opacity:0}.pswp__ui--hidden .pswp__button--arrow--left,.pswp__ui--hidden .pswp__button--arrow--right,.pswp__ui--hidden .pswp__caption,.pswp__ui--hidden .pswp__top-bar{opacity:.001}.pswp__ui--one-slide .pswp__button--arrow--left,.pswp__ui--one-slide .pswp__button--arrow--right,.pswp__ui--one-slide .pswp__counter{display:none}.pswp__element--disabled{display:none!important}.pswp--minimal--dark .pswp__top-bar{background:none}\n```"
}
] |
code_store-on-localhost_298e2851
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Gallery/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport Gallery from \"./Gallery\";\nexport default Gallery\n```"
}
] |
code_store-on-localhost_3fde7b2f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Gallery/Gallery.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo } from 'react'\nimport { PhotoSwipe } from 'react-photoswipe'\n\nimport './global.css'\n\nconst Gallery = ({ items, isOpen, index, handleClose, bgOpacity}) => {\n const toPswItem = item => ({\n src: item.urls[item.bestUrlIndex],\n w: 1280,\n h: 1280,\n title: item.alt,\n thumbnail: item.thumbUrl,\n })\n\n return (\n <PhotoSwipe\n isOpen={isOpen}\n items={useMemo(() => items.map(toPswItem), [items])}\n onClose={handleClose}\n options={{index, bgOpacity, history: false}}\n />\n )\n}\n\nexport default Gallery\n```"
}
] |
code_store-on-localhost_d2933a2c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Zoomable/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, ReactElement } from 'react'\nimport useDevice from '../../../../../DeviceDetector/useDevice'\nimport ZoomInPlace from './ZoomInPlace'\n\nexport enum ZoomMode {\n InPlaceClick = 'in-place-click',\n InPlaceHover = 'in-place-hover',\n Disabled = 'disabled'\n}\n\ninterface Props {\n mode?: ZoomMode\n zoomContent?: ReactElement\n factor?: number\n}\n\n\nconst Zoomable: FC<Props> = ({ children, factor = 2, zoomContent, mode = ZoomMode.InPlaceClick }) => {\n const { isMobile } = useDevice()\n\n if (isMobile && mode !== ZoomMode.Disabled) {\n // TODO: Good enough for now, but needs to be a gallery in the future.\n // Preferably photoswipe.com\n return (\n <ZoomInPlace type=\"click\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n }\n\n switch (mode) {\n case ZoomMode.InPlaceHover:\n return (\n <ZoomInPlace type=\"hover\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n case ZoomMode.InPlaceClick:\n return (\n <ZoomInPlace type=\"click\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n case ZoomMode.Disabled:\n default:\n return <>{children}</>\n }\n}\n\nexport default Zoomable\n```"
}
] |
code_store-on-localhost_1f6e995a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Zoomable/ZoomInPlace.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useRef, useState, useEffect, ReactElement } from 'react'\nimport { clamp } from 'ramda'\n\ninterface ContainerBounds {\n x: number,\n y: number,\n width: number,\n height: number,\n}\n\ntype ZoomType = 'click' | 'hover'\n\ninterface Props {\n type: ZoomType \n zoomContent?: ReactElement\n factor: number\n}\n\ntype ReactMouseEvent = MouseEvent | React.MouseEvent<HTMLElement, MouseEvent>\n\nconst getBounds = (element?: Element | null): ContainerBounds | null => {\n if (!element) return null\n\n const bounds = element.getBoundingClientRect()\n return {\n x: bounds.left,\n y: bounds.top,\n width: bounds.width,\n height: bounds.height,\n }\n}\n\nconst getMousePositionFromEvent = (event: ReactMouseEvent, bounds?: ContainerBounds | null): {x: number, y: number, isOutOfBounds?: boolean} => {\n if (!bounds) {\n return { x: 0, y: 0 }\n }\n\n const [ x, y ] = [ event.clientX - bounds.x, event.clientY - bounds.y ]\n\n const threshold = 20\n /* Uses out-of-bounds detection instead of simply a \"mouse-out\" event\n * to prevent from zooming out when the mouse hovers a button or suchlike */\n const isOutOfBounds = x < -threshold || y < -threshold || x > bounds.width + threshold || y > bounds.height + threshold\n\n // Values larger than 0 increase mouse movement sensivity\n const boost = 0.1\n return {\n x: clamp(0, bounds.width, (-bounds.width * boost) + (x * (1 + boost * 2))),\n y: clamp(0, bounds.height, (-bounds.height * boost) + (y * (1 + boost * 2))),\n isOutOfBounds,\n }\n}\n\nconst ZoomInPlace: FC<Props> = ({ children, zoomContent, type, factor }) => {\n const [isZoomedIn, setZoom] = useState(false)\n\n const containerRef = useRef<HTMLDivElement>(null)\n const contentRef = useRef<HTMLDivElement>(null)\n\n const containerBounds = useRef<ContainerBounds | null>(null)\n\n const setPositionAndScale = (x: number, y: number, scale: number) => {\n const contentElement = contentRef.current\n if (!contentElement) {\n return\n }\n\n contentElement.style.transform = `scale(${scale}, ${scale}) translate3d(${-x/scale}px, ${-y/scale}px, 0)`\n }\n\n const getContainerBounds = () => containerBounds.current || getBounds(containerRef.current)\n\n const handleMouseOver = () => {\n setZoom(true)\n }\n\n const handleClick = (event: ReactMouseEvent) => {\n setZoom(!isZoomedIn)\n\n if (!isZoomedIn) {\n const mousePosition = getMousePositionFromEvent(event, getContainerBounds())\n setPositionAndScale(mousePosition.x, mousePosition.y, factor)\n }\n }\n\n // Resets position when the image is zoomed out\n useEffect(() => {\n if (!isZoomedIn) {\n setPositionAndScale(0, 0, 1)\n containerBounds.current = null\n }\n }, [isZoomedIn])\n\n /* Adds mouse event handlers to the entire document, so that\n * mouse movement is not restricted to just the content element */\n const handleClickOutside = () => {\n if (isZoomedIn) {\n setZoom(false)\n }\n }\n\n const handleMouseMove = (event: ReactMouseEvent) => {\n if (!isZoomedIn) {\n return\n }\n\n const mousePosition = getMousePositionFromEvent(event, getContainerBounds())\n\n /* Uses out-of-bounds detection instead of simply a \"mouse-out\" event\n * to prevent from zooming out when the mouse hovers a button or suchlike */\n if (type === 'hover' && mousePosition.isOutOfBounds) {\n setZoom(false)\n } else {\n setPositionAndScale(mousePosition.x, mousePosition.y, factor)\n }\n }\n\n useEffect(() => {\n if (document) {\n document.addEventListener('mousemove', handleMouseMove)\n if (type === 'click') {\n document.addEventListener('click', handleClickOutside)\n }\n }\n return () => {\n if (document) {\n document.removeEventListener('mousemove', handleMouseMove)\n if (type === 'click') {\n document.removeEventListener('click', handleClickOutside)\n }\n }\n }\n })\n\n return (\n <div\n ref={containerRef}\n onMouseOver={type === 'hover' ? handleMouseOver : undefined}\n onClick={type === 'click' ? handleClick : undefined}\n className=\"relative\">\n <div ref={contentRef} style={{\n transformOrigin: '0 0',\n fontSize: 0, /** Prevents accidental whitespaces on the content from stretching\n * the container, and consequently the zoomed image */\n }}>\n {children}\n {zoomContent && isZoomedIn && (\n <div\n className=\"absolute top-0 left-0 right-0 bottom-0\"\n style={{\n transformOrigin: '0 0',\n transform: `scale(${1/factor})`,\n fontSize: 0\n }}>\n {zoomContent}\n </div>\n )}\n </div>\n </div>\n )\n}\n\nexport default ZoomInPlace\n```"
}
] |
code_store-on-localhost_490f3b8c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Carousel/ThumbnailSwiper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { THUMB_SIZE } from '../../../module/images'\nimport classNames from 'classnames'\n\nimport { THUMBS_POSITION_HORIZONTAL } from '../../utils/enums'\nimport { imageUrl } from '../../utils/aspectRatioUtil'\nimport useCssHandles from '../../../../../CssHandles/useCssHandles'\n\nconst THUMB_MAX_SIZE = 256\n\n/** Swiper and its modules are imported using require to avoid breaking SSR */\nconst Swiper = window.navigator\n ? require('react-id-swiper/lib/ReactIdSwiper').default\n : null\n\nconst CSS_HANDLES = [\n 'figure',\n 'thumbImg',\n 'productImagesThumb',\n 'carouselThumbBorder',\n 'carouselGaleryThumbs',\n 'productImagesThumbActive',\n]\n\nconst Thumbnail = ({\n alt,\n index,\n onThumbClick,\n height,\n thumbUrl,\n handles,\n maxHeight = 150,\n aspectRatio = 'auto',\n itemContainerClasses,\n}) => {\n return (\n <div\n className={itemContainerClasses}\n style={{ height, maxHeight: maxHeight || 'unset' }}\n onClick={() => onThumbClick(index)}\n >\n <figure\n className={handles.figure}\n itemProp=\"associatedMedia\"\n itemScope\n itemType=\"http://schema.org/ImageObject\"\n >\n <img\n className={`${handles.thumbImg} w-100 h-auto db`}\n itemProp=\"thumbnail\"\n alt={alt}\n src={imageUrl(thumbUrl, THUMB_SIZE, THUMB_MAX_SIZE, aspectRatio)}\n />\n </figure>\n <div\n className={`absolute absolute--fill b--solid b--muted-2 bw0 ${handles.carouselThumbBorder}`}\n />\n </div>\n )\n}\n\nconst ThumbnailSwiper = ({\n isThumbsVertical,\n slides,\n swiperParams,\n thumbUrls,\n position,\n onThumbClick,\n activeIndex,\n thumbnailAspectRatio,\n thumbnailMaxHeight,\n}) => {\n const hasThumbs = slides.length > 1\n const handles = useCssHandles(CSS_HANDLES)\n\n const thumbClasses = classNames(`${handles.carouselGaleryThumbs} dn h-auto`, {\n 'db-ns': hasThumbs,\n mt3: !isThumbsVertical,\n 'w-20 bottom-0 top-0 absolute': isThumbsVertical,\n 'left-0':\n isThumbsVertical && position === THUMBS_POSITION_HORIZONTAL.LEFT,\n 'right-0':\n isThumbsVertical && position === THUMBS_POSITION_HORIZONTAL.RIGHT,\n })\n\n return (\n <div className={thumbClasses} data-testid=\"thumbnail-swiper\">\n <Swiper {...swiperParams} shouldSwiperUpdate>\n {slides.map((slide, i) => {\n const itemContainerClasses = classNames('swiper-slide mb5 pointer',\n handles.productImagesThumb,\n {\n 'w-20': !isThumbsVertical,\n 'w-100': isThumbsVertical,\n 'swiper-slide-active': activeIndex === i,\n [handles.productImagesThumbActive]: activeIndex === i,\n }\n )\n\n return (\n <Thumbnail\n key={`${i}-${slide.alt}`}\n itemContainerClasses={itemContainerClasses}\n index={i}\n handles={handles}\n height={isThumbsVertical ? 'auto' : '115px'}\n onThumbClick={onThumbClick}\n alt={slide.alt}\n thumbUrl={slide.thumbUrl || thumbUrls[i]}\n aspectRatio={thumbnailAspectRatio}\n maxHeight={thumbnailMaxHeight}\n />\n )\n })}\n </Swiper>\n </div>\n )\n}\n\nexport default ThumbnailSwiper\n\n```"
}
] |
code_store-on-localhost_5781ae3c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Carousel/ImagePlaceholder.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport style from '../../styles.css'\n\nexport default function ImagePlaceholder() {\n return (\n <div className=\"relative\">\n <div\n className={`${\n style.carouselImagePlaceholder\n } absolute w-100 h-100 contain bg-center`}\n />\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox=\"0 0 512 512\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <rect width=\"512\" height=\"512\" fill=\"#F2F2F2\" />\n <rect\n x=\"183.857\"\n y=\"180.2\"\n width=\"144.286\"\n height=\"150.474\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n />\n <path d=\"M183.78 303.688H328.214\" stroke=\"#CACBCC\" strokeWidth=\"2\" />\n <path\n d=\"M205.082 279.563L223.599 240.507L242.116 260.035L269.892 220.979L306.926 279.563H205.082Z\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M252.225 213.939C252.225 219.822 247.66 224.52 242.114 224.52C236.569 224.52 232.004 219.822 232.004 213.939C232.004 208.057 236.569 203.359 242.114 203.359C247.66 203.359 252.225 208.057 252.225 213.939Z\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n />\n </svg>\n </div>\n )\n}\n\n```"
}
] |
code_store-on-localhost_0961ac46
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Carousel/global.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n * Swiper 4.4.1\n * Most modern mobile touch slider and framework with hardware accelerated transitions\n * http://www.idangero.us/swiper/\n *\n * Copyright 2014-2018 Vladimir Kharlampidi\n *\n * Released under the MIT License\n *\n * Released on: September 14, 2018\n */\n\n/** \n * This is a quick-and-dirty fix to avoid `w-20` token from being\n * overwritten by `width: 100%;` set by `swiper-slide`.\n*/\n.w-20.w-20.w-20 {\n width: 20%;\n}\n\n.swiper-container {\n margin: 0 auto;\n position: relative;\n overflow: hidden;\n list-style: none;\n padding: 0;\n /* Fix of Webkit flickering */\n z-index: 1;\n}\n.swiper-container-no-flexbox .swiper-slide {\n float: left;\n}\n.swiper-container-vertical > .swiper-wrapper {\n -webkit-box-orient: vertical;\n -webkit-box-direction: normal;\n -webkit-flex-direction: column;\n -ms-flex-direction: column;\n flex-direction: column;\n}\n.swiper-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n z-index: 1;\n display: -webkit-box;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-transition-property: -webkit-transform;\n transition-property: -webkit-transform;\n -o-transition-property: transform;\n transition-property: transform;\n transition-property: transform, -webkit-transform;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n align-items: center;\n}\n.swiper-container-android .swiper-slide,\n.swiper-wrapper {\n -webkit-transform: translate3d(0px, 0, 0);\n transform: translate3d(0px, 0, 0);\n}\n.swiper-container-multirow > .swiper-wrapper {\n -webkit-flex-wrap: wrap;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n}\n.swiper-container-free-mode > .swiper-wrapper {\n -webkit-transition-timing-function: ease-out;\n -o-transition-timing-function: ease-out;\n transition-timing-function: ease-out;\n margin: 0 auto;\n}\n.swiper-slide {\n -webkit-flex-shrink: 0;\n -ms-flex-negative: 0;\n flex-shrink: 0;\n width: 100%;\n height: 100%;\n position: relative;\n -webkit-transition-property: -webkit-transform;\n transition-property: -webkit-transform;\n -o-transition-property: transform;\n transition-property: transform;\n transition-property: transform, -webkit-transform;\n}\n.swiper-slide-invisible-blank {\n visibility: hidden;\n}\n/* Auto Height */\n.swiper-container-autoheight,\n.swiper-container-autoheight .swiper-slide {\n height: auto;\n}\n.swiper-container-autoheight .swiper-wrapper {\n -webkit-box-align: start;\n -webkit-align-items: flex-start;\n -ms-flex-align: start;\n align-items: flex-start;\n -webkit-transition-property: height, -webkit-transform;\n transition-property: height, -webkit-transform;\n -o-transition-property: transform, height;\n transition-property: transform, height;\n transition-property: transform, height, -webkit-transform;\n}\n/* 3D Effects */\n.swiper-container-3d {\n -webkit-perspective: 1200px;\n perspective: 1200px;\n}\n.swiper-container-3d .swiper-wrapper,\n.swiper-container-3d .swiper-slide,\n.swiper-container-3d .swiper-slide-shadow-left,\n.swiper-container-3d .swiper-slide-shadow-right,\n.swiper-container-3d .swiper-slide-shadow-top,\n.swiper-container-3d .swiper-slide-shadow-bottom,\n.swiper-container-3d .swiper-cube-shadow {\n -webkit-transform-style: preserve-3d;\n transform-style: preserve-3d;\n}\n.swiper-container-3d .swiper-slide-shadow-left,\n.swiper-container-3d .swiper-slide-shadow-right,\n.swiper-container-3d .swiper-slide-shadow-top,\n.swiper-container-3d .swiper-slide-shadow-bottom {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 10;\n}\n.swiper-container-3d .swiper-slide-shadow-left {\n background-image: -webkit-gradient(\n linear,\n right top,\n left top,\n from(rgba(0, 0, 0, 0.5)),\n to(rgba(0, 0, 0, 0))\n );\n background-image: -webkit-linear-gradient(\n right,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: -o-linear-gradient(\n right,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: linear-gradient(\n to left,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n}\n.swiper-container-3d .swiper-slide-shadow-right {\n background-image: -webkit-gradient(\n linear,\n left top,\n right top,\n from(rgba(0, 0, 0, 0.5)),\n to(rgba(0, 0, 0, 0))\n );\n background-image: -webkit-linear-gradient(\n left,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: -o-linear-gradient(\n left,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: linear-gradient(\n to right,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n}\n.swiper-container-3d .swiper-slide-shadow-top {\n background-image: -webkit-gradient(\n linear,\n left bottom,\n left top,\n from(rgba(0, 0, 0, 0.5)),\n to(rgba(0, 0, 0, 0))\n );\n background-image: -webkit-linear-gradient(\n bottom,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: -o-linear-gradient(\n bottom,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: linear-gradient(\n to top,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n}\n.swiper-container-3d .swiper-slide-shadow-bottom {\n background-image: -webkit-gradient(\n linear,\n left top,\n left bottom,\n from(rgba(0, 0, 0, 0.5)),\n to(rgba(0, 0, 0, 0))\n );\n background-image: -webkit-linear-gradient(\n top,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: -o-linear-gradient(\n top,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n background-image: linear-gradient(\n to bottom,\n rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0)\n );\n}\n/* IE10 Windows Phone 8 Fixes */\n.swiper-container-wp8-horizontal,\n.swiper-container-wp8-horizontal > .swiper-wrapper {\n -ms-touch-action: pan-y;\n touch-action: pan-y;\n}\n.swiper-container-wp8-vertical,\n.swiper-container-wp8-vertical > .swiper-wrapper {\n -ms-touch-action: pan-x;\n touch-action: pan-x;\n}\n.swiper-button-prev,\n.swiper-button-next {\n position: absolute;\n top: 50%;\n width: 27px;\n height: 44px;\n margin-top: -22px;\n z-index: 10;\n cursor: pointer;\n background-size: 27px 44px;\n background-position: center;\n background-repeat: no-repeat;\n}\n.swiper-button-prev.swiper-button-disabled,\n.swiper-button-next.swiper-button-disabled {\n opacity: 0.35;\n cursor: auto;\n pointer-events: none;\n}\n.swiper-button-prev,\n.swiper-container-rtl .swiper-button-next {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23007aff'%2F%3E%3C%2Fsvg%3E\");\n left: 10px;\n right: auto;\n}\n.swiper-button-next,\n.swiper-container-rtl .swiper-button-prev {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23007aff'%2F%3E%3C%2Fsvg%3E\");\n right: 10px;\n left: auto;\n}\n.swiper-button-prev.swiper-button-white,\n.swiper-container-rtl .swiper-button-next.swiper-button-white {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23ffffff'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-next.swiper-button-white,\n.swiper-container-rtl .swiper-button-prev.swiper-button-white {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23ffffff'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-prev.swiper-button-black,\n.swiper-container-rtl .swiper-button-next.swiper-button-black {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M0%2C22L22%2C0l2.1%2C2.1L4.2%2C22l19.9%2C19.9L22%2C44L0%2C22L0%2C22L0%2C22z'%20fill%3D'%23000000'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-next.swiper-button-black,\n.swiper-container-rtl .swiper-button-prev.swiper-button-black {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2027%2044'%3E%3Cpath%20d%3D'M27%2C22L27%2C22L5%2C44l-2.1-2.1L22.8%2C22L2.9%2C2.1L5%2C0L27%2C22L27%2C22z'%20fill%3D'%23000000'%2F%3E%3C%2Fsvg%3E\");\n}\n.swiper-button-lock {\n display: none;\n}\n.swiper-pagination {\n position: absolute;\n text-align: center;\n -webkit-transition: 300ms opacity;\n -o-transition: 300ms opacity;\n transition: 300ms opacity;\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n z-index: 10;\n}\n.swiper-pagination.swiper-pagination-hidden {\n opacity: 0;\n}\n/* Common Styles */\n.swiper-pagination-fraction,\n.swiper-pagination-custom,\n.swiper-container-horizontal > .swiper-pagination-bullets {\n bottom: 0;\n padding-bottom: 10px;\n left: 0;\n width: 100%;\n}\n/* Bullets */\n.swiper-pagination-bullets-dynamic {\n overflow: hidden;\n font-size: 0;\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n position: relative;\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active {\n -webkit-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-main {\n -webkit-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev {\n -webkit-transform: scale(0.66);\n -ms-transform: scale(0.66);\n transform: scale(0.66);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev-prev {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next {\n -webkit-transform: scale(0.66);\n -ms-transform: scale(0.66);\n transform: scale(0.66);\n}\n.swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next-next {\n -webkit-transform: scale(0.33);\n -ms-transform: scale(0.33);\n transform: scale(0.33);\n}\n.swiper-pagination-bullet {\n width: 8px;\n height: 8px;\n display: inline-block;\n border-radius: 100%;\n background: #000;\n opacity: 0.2;\n}\nbutton.swiper-pagination-bullet {\n border: none;\n margin: 0;\n padding: 0;\n -webkit-box-shadow: none;\n box-shadow: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n.swiper-pagination-clickable .swiper-pagination-bullet {\n cursor: pointer;\n}\n.swiper-pagination-bullet-active {\n opacity: 1;\n background: currentColor;\n}\n.swiper-container-vertical > .swiper-pagination-bullets {\n right: 10px;\n top: 50%;\n -webkit-transform: translate3d(0px, -50%, 0);\n transform: translate3d(0px, -50%, 0);\n}\n.swiper-container-vertical\n > .swiper-pagination-bullets\n .swiper-pagination-bullet {\n margin: 6px 0;\n display: block;\n}\n.swiper-container-vertical\n > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic {\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n width: 8px;\n}\n.swiper-container-vertical\n > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic\n .swiper-pagination-bullet {\n display: inline-block;\n -webkit-transition: 200ms top, 200ms -webkit-transform;\n transition: 200ms top, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms top;\n transition: 200ms transform, 200ms top;\n transition: 200ms transform, 200ms top, 200ms -webkit-transform;\n}\n.swiper-container-horizontal\n > .swiper-pagination-bullets\n .swiper-pagination-bullet {\n margin: 0 4px;\n}\n.swiper-container-horizontal\n > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic {\n left: 50%;\n -webkit-transform: translateX(-50%);\n -ms-transform: translateX(-50%);\n transform: translateX(-50%);\n white-space: nowrap;\n}\n.swiper-container-horizontal\n > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic\n .swiper-pagination-bullet {\n -webkit-transition: 200ms left, 200ms -webkit-transform;\n transition: 200ms left, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms left;\n transition: 200ms transform, 200ms left;\n transition: 200ms transform, 200ms left, 200ms -webkit-transform;\n}\n.swiper-container-horizontal.swiper-container-rtl\n > .swiper-pagination-bullets-dynamic\n .swiper-pagination-bullet {\n -webkit-transition: 200ms right, 200ms -webkit-transform;\n transition: 200ms right, 200ms -webkit-transform;\n -o-transition: 200ms transform, 200ms right;\n transition: 200ms transform, 200ms right;\n transition: 200ms transform, 200ms right, 200ms -webkit-transform;\n}\n/* Progress */\n.swiper-pagination-progressbar {\n background: rgba(0, 0, 0, 0.25);\n position: absolute;\n}\n.swiper-pagination-progressbar .swiper-pagination-progressbar-fill {\n background: currentColor;\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n -webkit-transform: scale(0);\n -ms-transform: scale(0);\n transform: scale(0);\n -webkit-transform-origin: left top;\n -ms-transform-origin: left top;\n transform-origin: left top;\n}\n.swiper-container-rtl\n .swiper-pagination-progressbar\n .swiper-pagination-progressbar-fill {\n -webkit-transform-origin: right top;\n -ms-transform-origin: right top;\n transform-origin: right top;\n}\n.swiper-container-horizontal > .swiper-pagination-progressbar,\n.swiper-container-vertical\n > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite {\n width: 100%;\n height: 4px;\n left: 0;\n top: 0;\n}\n.swiper-container-vertical > .swiper-pagination-progressbar,\n.swiper-container-horizontal\n > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite {\n width: 4px;\n height: 100%;\n left: 0;\n top: 0;\n}\n.swiper-pagination-white .swiper-pagination-bullet-active {\n background: #ffffff;\n}\n.swiper-pagination-progressbar.swiper-pagination-white {\n background: rgba(255, 255, 255, 0.25);\n}\n.swiper-pagination-progressbar.swiper-pagination-white\n .swiper-pagination-progressbar-fill {\n background: #ffffff;\n}\n.swiper-pagination-black .swiper-pagination-bullet-active {\n background: #000000;\n}\n.swiper-pagination-progressbar.swiper-pagination-black {\n background: rgba(0, 0, 0, 0.25);\n}\n.swiper-pagination-progressbar.swiper-pagination-black\n .swiper-pagination-progressbar-fill {\n background: #000000;\n}\n.swiper-pagination-lock {\n display: none;\n}\n/* Scrollbar */\n.swiper-scrollbar {\n border-radius: 10px;\n position: relative;\n -ms-touch-action: none;\n background: rgba(0, 0, 0, 0.1);\n}\n.swiper-container-horizontal > .swiper-scrollbar {\n position: absolute;\n left: 1%;\n bottom: 3px;\n z-index: 50;\n height: 5px;\n width: 98%;\n}\n.swiper-container-vertical > .swiper-scrollbar {\n position: absolute;\n right: 3px;\n top: 1%;\n z-index: 50;\n width: 5px;\n height: 98%;\n}\n.swiper-scrollbar-drag {\n height: 100%;\n width: 100%;\n position: relative;\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n left: 0;\n top: 0;\n}\n.swiper-scrollbar-cursor-drag {\n cursor: move;\n}\n.swiper-scrollbar-lock {\n display: none;\n}\n.swiper-zoom-container {\n width: 100%;\n height: 100%;\n display: -webkit-box;\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n -webkit-box-align: center;\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n text-align: center;\n}\n.swiper-zoom-container > img,\n.swiper-zoom-container > svg,\n.swiper-zoom-container > canvas {\n max-width: 100%;\n max-height: 100%;\n -o-object-fit: contain;\n object-fit: contain;\n}\n.swiper-slide-zoomed {\n cursor: move;\n}\n/* Preloader */\n.swiper-lazy-preloader {\n width: 42px;\n height: 42px;\n position: absolute;\n left: 50%;\n top: 50%;\n margin-left: -21px;\n margin-top: -21px;\n z-index: 10;\n -webkit-transform-origin: 50%;\n -ms-transform-origin: 50%;\n transform-origin: 50%;\n -webkit-animation: swiper-preloader-spin 1s steps(12, end) infinite;\n animation: swiper-preloader-spin 1s steps(12, end) infinite;\n}\n.swiper-lazy-preloader:after {\n display: block;\n content: '';\n width: 100%;\n height: 100%;\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D'0%200%20120%20120'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3Cline%20id%3D'l'%20x1%3D'60'%20x2%3D'60'%20y1%3D'7'%20y2%3D'27'%20stroke%3D'%236c6c6c'%20stroke-width%3D'11'%20stroke-linecap%3D'round'%2F%3E%3C%2Fdefs%3E%3Cg%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(30%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(60%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(90%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(120%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(150%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.37'%20transform%3D'rotate(180%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.46'%20transform%3D'rotate(210%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.56'%20transform%3D'rotate(240%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.66'%20transform%3D'rotate(270%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.75'%20transform%3D'rotate(300%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.85'%20transform%3D'rotate(330%2060%2C60)'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E\");\n background-position: 50%;\n background-size: 100%;\n background-repeat: no-repeat;\n}\n.swiper-lazy-preloader-white:after {\n background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20viewBox%3D'0%200%20120%20120'%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3Cline%20id%3D'l'%20x1%3D'60'%20x2%3D'60'%20y1%3D'7'%20y2%3D'27'%20stroke%3D'%23fff'%20stroke-width%3D'11'%20stroke-linecap%3D'round'%2F%3E%3C%2Fdefs%3E%3Cg%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(30%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(60%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(90%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(120%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.27'%20transform%3D'rotate(150%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.37'%20transform%3D'rotate(180%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.46'%20transform%3D'rotate(210%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.56'%20transform%3D'rotate(240%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.66'%20transform%3D'rotate(270%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.75'%20transform%3D'rotate(300%2060%2C60)'%2F%3E%3Cuse%20xlink%3Ahref%3D'%23l'%20opacity%3D'.85'%20transform%3D'rotate(330%2060%2C60)'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E\");\n}\n@-webkit-keyframes swiper-preloader-spin {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes swiper-preloader-spin {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n/* a11y */\n.swiper-container .swiper-notification {\n position: absolute;\n left: 0;\n top: 0;\n pointer-events: none;\n opacity: 0;\n z-index: -1000;\n}\n.swiper-container-fade.swiper-container-free-mode .swiper-slide {\n -webkit-transition-timing-function: ease-out;\n -o-transition-timing-function: ease-out;\n transition-timing-function: ease-out;\n}\n.swiper-container-fade .swiper-slide {\n pointer-events: none;\n -webkit-transition-property: opacity;\n -o-transition-property: opacity;\n transition-property: opacity;\n}\n.swiper-container-fade .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-fade .swiper-slide-active,\n.swiper-container-fade .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-cube {\n overflow: visible;\n}\n.swiper-container-cube .swiper-slide {\n pointer-events: none;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n z-index: 1;\n visibility: hidden;\n -webkit-transform-origin: 0 0;\n -ms-transform-origin: 0 0;\n transform-origin: 0 0;\n width: 100%;\n height: 100%;\n}\n.swiper-container-cube .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-cube.swiper-container-rtl .swiper-slide {\n -webkit-transform-origin: 100% 0;\n -ms-transform-origin: 100% 0;\n transform-origin: 100% 0;\n}\n.swiper-container-cube .swiper-slide-active,\n.swiper-container-cube .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-cube .swiper-slide-active,\n.swiper-container-cube .swiper-slide-next,\n.swiper-container-cube .swiper-slide-prev,\n.swiper-container-cube .swiper-slide-next + .swiper-slide {\n pointer-events: auto;\n visibility: visible;\n}\n.swiper-container-cube .swiper-slide-shadow-top,\n.swiper-container-cube .swiper-slide-shadow-bottom,\n.swiper-container-cube .swiper-slide-shadow-left,\n.swiper-container-cube .swiper-slide-shadow-right {\n z-index: 0;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n}\n.swiper-container-cube .swiper-cube-shadow {\n position: absolute;\n left: 0;\n bottom: 0px;\n width: 100%;\n height: 100%;\n background: #000;\n opacity: 0.6;\n -webkit-filter: blur(50px);\n filter: blur(50px);\n z-index: 0;\n}\n.swiper-container-flip {\n overflow: visible;\n}\n.swiper-container-flip .swiper-slide {\n pointer-events: none;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n z-index: 1;\n}\n.swiper-container-flip .swiper-slide .swiper-slide {\n pointer-events: none;\n}\n.swiper-container-flip .swiper-slide-active,\n.swiper-container-flip .swiper-slide-active .swiper-slide-active {\n pointer-events: auto;\n}\n.swiper-container-flip .swiper-slide-shadow-top,\n.swiper-container-flip .swiper-slide-shadow-bottom,\n.swiper-container-flip .swiper-slide-shadow-left,\n.swiper-container-flip .swiper-slide-shadow-right {\n z-index: 0;\n -webkit-backface-visibility: hidden;\n backface-visibility: hidden;\n}\n.swiper-container-coverflow .swiper-wrapper {\n /* Windows 8 IE 10 fix */\n -ms-perspective: 1200px;\n}\n\n/*------------------ vtex -----------------------*/\n@media screen and (min-width: 40em) {\n .ml-20-ns {\n margin-left: 20%;\n }\n}\n\n.center-all {\n margin: auto;\n}\n\n.border-box {\n box-sizing: border-box;\n}\n\n.top-50 {\n top: 50%;\n}\n\n.translate--50y {\n transform: translate(0, -50%);\n}\n\n.pointer-events-none {\n pointer-events: none;\n}\n\n```"
}
] |
code_store-on-localhost_b63cfd7b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/ProductImages/components/Carousel/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport debounce from 'debounce'\nimport classNames from 'classnames'\nimport { path, equals } from 'ramda'\nimport ReactResizeDetector from 'react-resize-detector'\n\nimport IconCaret from '../../../../../StoreIcons/IconCaret'\nimport withCssHandles from '../../../../../CssHandles/withCssHandles'\n\nimport Video, { getThumbUrl } from '../Video'\nimport ProductImage from '../ProductImage'\n\nimport styles from '../../styles.css'\nimport './global.css'\n\n/**\n * ReactIdSwiper cannot be SSRendered, so this is a fake swiper that copies some of its classes and HTML layout and render only the first image of the children array.\n */\nconst FakeSwiper = ({ children, containerClass, direction = THUMBS_ORIENTATION.HORIZONTAL }) => {\n const swiperContainerDirection = direction === THUMBS_ORIENTATION.HORIZONTAL ? 'swiper-container-horizontal' : direction === THUMBS_ORIENTATION.VERTICAL ? 'swiper-container-vertical' : ''\n const childrenArray = React.Children.toArray(children)\n if (childrenArray.length === 0) {\n return null\n }\n const child = childrenArray[0]\n const childClass = path(['props', 'className'], child)\n const newChildClass = childClass ? `${childClass} swiper-slide-active` : childClass\n return (\n <div className={`${containerClass} swiper-container-initialized ${swiperContainerDirection}`}>\n <div className=\"swiper-wrapper\">\n {React.cloneElement(child, {\n className: newChildClass,\n })}\n </div>\n </div>\n )\n}\n\n/** Swiper and its modules are imported using require to avoid breaking SSR */\nconst Swiper = window.navigator\n ? require('react-id-swiper/lib/ReactIdSwiper').default\n : FakeSwiper\n\nconst SwiperModules = window.navigator ? require('swiper/dist/js/swiper') : {}\n\nimport ThumbnailSwiper from './ThumbnailSwiper'\nimport {\n THUMBS_ORIENTATION,\n THUMBS_POSITION_HORIZONTAL,\n} from '../../utils/enums'\n\nconst CSS_HANDLES = [\n 'carouselContainer',\n 'productImagesThumbsSwiperContainer',\n 'productImagesGallerySwiperContainer',\n 'productImagesGallerySlide',\n 'swiperCaret',\n 'swiperCaretNext',\n 'swiperCaretPrev',\n 'productImagesThumbCaret',\n]\n\nconst initialState = {\n loaded: [],\n thumbUrl: [],\n alt: [],\n thumbsLoaded: false,\n activeIndex: 0,\n}\n\nclass Carousel extends Component {\n thumbSwiper = null\n gallerySwiper = null\n state = initialState\n\n async setInitialVariablesState() {\n const slides = this.props.slides || []\n\n this.isVideo = []\n this.thumbLoadCount = 0\n\n slides.forEach(async (slide, i) => {\n if (slide.type === 'video') {\n const thumbUrl = await getThumbUrl(slide.src, slide.thumbWidth)\n this.isVideo[i] = true\n this.setVideoThumb(i)(thumbUrl)\n this.thumbLoadFinish()\n } else {\n this.getThumb(slide.thumbUrl)\n }\n })\n }\n\n updateSwiperSize = debounce(() => {\n if (this.thumbSwiper) {\n this.thumbSwiper.update()\n }\n\n if (this.gallerySwiper) {\n this.gallerySwiper.update()\n }\n }, 500)\n\n thumbLoadFinish = () => {\n this.thumbLoadCount++\n if (!this.props.slides || this.thumbLoadCount === this.props.slides.length) {\n this.setState({ thumbsLoaded: true })\n }\n }\n\n getThumb = thumbUrl => {\n if (!window.navigator) return // Image object doesn't exist when it's being rendered in the server side\n const image = new Image()\n image.onload = () => {\n this.thumbLoadFinish()\n }\n image.onerror = () => {\n this.thumbLoadFinish()\n }\n image.src = thumbUrl\n }\n\n handleResize = () => {\n this.updateSwiperSize()\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.handleResize)\n this.setInitialVariablesState()\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.handleResize)\n\n this.updateSwiperSize.clear()\n }\n\n componentDidUpdate(prevProps) {\n const { loaded, activeIndex } = this.state\n const isVideo = this.isVideo\n\n if (!equals(prevProps.slides, this.props.slides)) {\n this.setInitialVariablesState()\n this.setState(initialState)\n if (this.props.slides && this.props.slides.length > 1) {\n this.gallerySwiper && this.gallerySwiper.slideTo(0)\n this.thumbSwiper && this.thumbSwiper.slideTo(0)\n }\n return\n }\n\n const paginationElement = path(['pagination', 'el'], this.gallerySwiper)\n if (paginationElement) paginationElement.hidden = isVideo[activeIndex]\n\n const gallerySwiperZoom = path(['zoom'], this.gallerySwiper)\n\n if (gallerySwiperZoom) {\n loaded[activeIndex]\n ? gallerySwiperZoom.enable()\n : gallerySwiperZoom.disable()\n }\n }\n\n onSlideChange = () => {\n const activeIndex = path(['activeIndex'], this.gallerySwiper)\n this.setState({ activeIndex, sliderChanged: true })\n }\n\n setVideoThumb = i => (url, title) => {\n const thumbUrl = { ...this.state.thumbUrl }\n const alt = { ...this.state.alt }\n\n thumbUrl[i] = url\n alt[i] = title\n\n this.setState({ thumbUrl, alt })\n }\n\n renderSlide = (slide, i) => {\n const { aspectRatio, maxHeight, zoomMode, zoomFactor, zoomProps: legacyZoomProps } = this.props\n\n // Backwards compatibility\n const { zoomType: legacyZoomType } = legacyZoomProps || {}\n const isZoomDisabled = legacyZoomType === 'no-zoom' || zoomMode === 'disabled'\n\n switch (slide.type) {\n case 'image':\n return (\n <ProductImage\n src={slide.url}\n alt={slide.alt}\n aspectRatio={aspectRatio}\n maxHeight={maxHeight}\n zoomFactor={zoomFactor}\n zoomMode={isZoomDisabled ? 'disabled' : zoomMode}\n />\n )\n case 'video':\n return (\n <Video\n url={slide.src}\n setThumb={this.setVideoThumb(i)}\n playing={i === this.state.activeIndex}\n id={i}\n />\n )\n default:\n return null\n }\n }\n\n get galleryParams() {\n const {\n cssHandles,\n slides = [],\n showPaginationDots = true,\n showNavigationArrows = true,\n } = this.props\n\n const iconSize = 24\n const caretClassName =\n 'pv8 absolute top-50 translate--50y z-2 pointer c-action-primary'\n\n return {\n modules: [SwiperModules.Pagination, SwiperModules.Navigation],\n containerClass: `swiper-container ${cssHandles.productImagesGallerySwiperContainer}`,\n ...(slides.length > 1 && showPaginationDots && {\n pagination: {\n el: '.swiper-pagination',\n clickable: true,\n bulletActiveClass: 'c-action-primary swiper-pagination-bullet-active',\n },\n }),\n ...(slides.length > 1 && {\n navigation: {\n prevEl: '.swiper-caret-prev',\n nextEl: '.swiper-caret-next',\n disabledClass: `c-disabled ${styles.carouselCursorDefault}`,\n },\n }),\n thumbs: {\n swiper: this.thumbSwiper,\n },\n threshold: 10,\n resistanceRatio: slides.length > 1 ? 0.85 : 0,\n ...(showNavigationArrows && {\n renderNextButton: () => (\n <span className={`swiper-caret-next pl7 pr2 right-0 ${caretClassName} ${cssHandles.swiperCaret} ${cssHandles.swiperCaretNext}`}>\n <IconCaret\n orientation=\"right\"\n size={iconSize}\n className={styles.carouselIconCaretRight}\n />\n </span>\n ),\n renderPrevButton: () => (\n <span className={`swiper-caret-prev pr7 pl2 left-0 ${caretClassName} ${cssHandles.swiperCaret} ${cssHandles.swiperCaretPrev}`}>\n <IconCaret\n orientation=\"left\"\n size={iconSize}\n className={styles.carouselIconCaretLeft}\n />\n </span>\n ),\n }),\n on: {\n slideChange: this.onSlideChange,\n },\n getSwiper: swiper => {\n if (this.gallerySwiper !== swiper) {\n this.gallerySwiper = swiper\n }\n }\n }\n }\n\n get thumbnailsParams() {\n const { displayThumbnailsArrows, thumbnailsOrientation, cssHandles } = this.props\n\n const isThumbsVertical =\n thumbnailsOrientation === THUMBS_ORIENTATION.VERTICAL\n const caretSize = 24\n const caretClassName = `${cssHandles.productImagesThumbCaret} absolute z-2 pointer c-action-primary flex pv2`\n const caretStyle = { transition: 'opacity 200ms' }\n\n return {\n modules: [SwiperModules.Navigation],\n ...(displayThumbnailsArrows && {\n navigation: {\n prevEl: '.swiper-thumbnails-caret-prev',\n nextEl: '.swiper-thumbnails-caret-next',\n disabledClass: `c-disabled o-0 pointer-events-none ${styles.carouselCursorDefault}`,\n hiddenClass: 'dn',\n },\n renderNextButton: () => {\n const classes = classNames(\n 'swiper-thumbnails-caret-next',\n caretClassName,\n {\n [`bottom-0 pt7 left-0 justify-center w-100 ${styles.gradientBaseBottom}`]: isThumbsVertical,\n [`right-0 top-0 items-center h-100 pl6 ${styles.gradientBaseRight}`]: !isThumbsVertical,\n }\n )\n return (\n <span className={classes} style={caretStyle}>\n <IconCaret\n orientation={isThumbsVertical ? 'down' : 'right'}\n size={caretSize}\n />\n </span>\n )\n },\n renderPrevButton: () => {\n const classes = classNames(\n 'swiper-thumbnails-caret-prev top-0 left-0',\n caretClassName,\n {\n [`pb7 justify-center w-100 ${styles.gradientBaseTop}`]: isThumbsVertical,\n [`items-center h-100 pr6 ${styles.gradientBaseLeft}`]: !isThumbsVertical,\n }\n )\n return (\n <span className={classes} style={caretStyle}>\n <IconCaret\n orientation={isThumbsVertical ? 'up' : 'left'}\n size={caretSize}\n />\n </span>\n )\n },\n }),\n observer: true,\n containerClass: `swiper-container h-100 ${cssHandles.productImagesThumbsSwiperContainer}`,\n watchSlidesVisibility: true,\n watchSlidesProgress: true,\n freeMode: false,\n // It seems crazy but this is just\n // an workaround to make it work the thumbnails with the carousel\n slideActiveClass: 'undefined',\n slideNextClass: 'undefined',\n slidePrevClass: 'undefined',\n direction: thumbnailsOrientation,\n slidesPerView: 'auto',\n touchRatio: 1,\n mousewheel: false,\n preloadImages: true,\n shouldSwiperUpdate: true,\n zoom: false,\n threshold: 8,\n /* Slides are grouped when thumbnails arrows are enabled\n * so that clicking on next/prev will scroll more than\n * one thumbnail */\n slidesPerGroup: displayThumbnailsArrows ? 4 : 1,\n getSwiper: swiper => {\n if (this.thumbSwiper !== swiper) {\n this.thumbSwiper = swiper\n }\n }\n }\n }\n\n render() {\n const { thumbsLoaded, activeIndex } = this.state\n\n const {\n position,\n cssHandles,\n slides = [],\n thumbnailMaxHeight,\n thumbnailAspectRatio,\n thumbnailsOrientation,\n zoomProps: { zoomType },\n } = this.props\n\n const isThumbsVertical =\n thumbnailsOrientation === THUMBS_ORIENTATION.VERTICAL\n const hasThumbs = slides && slides.length > 1\n\n const galleryCursor = {\n 'in-page': styles.carouselGaleryCursor,\n 'no-zoom': '',\n }\n\n const imageClasses = classNames(\n 'w-100 border-box',\n galleryCursor[zoomType],\n {\n 'ml-20-ns w-80-ns pl5':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.LEFT &&\n hasThumbs,\n 'mr-20-ns w-80-ns pr5':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.RIGHT &&\n hasThumbs,\n }\n )\n\n const thumbnailSwiper = thumbsLoaded && hasThumbs && (\n <ThumbnailSwiper\n isThumbsVertical={isThumbsVertical}\n slides={slides}\n activeIndex={activeIndex}\n swiperParams={this.thumbnailsParams}\n thumbUrls={this.state.thumbUrl}\n position={position}\n onThumbClick={index => this.gallerySwiper && this.gallerySwiper.slideTo(index)}\n thumbnailAspectRatio={thumbnailAspectRatio}\n thumbnailMaxHeight={thumbnailMaxHeight}\n />\n )\n\n const containerClasses = classNames(cssHandles.carouselContainer, 'relative overflow-hidden w-100', {\n 'flex-ns justify-end-ns': isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.LEFT &&\n hasThumbs,\n 'flex-ns justify-start-ns': isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.RIGHT &&\n hasThumbs,\n })\n\n const SliderComponent = slides.length === 1 ? FakeSwiper : Swiper\n\n return (\n <div className={containerClasses} aria-hidden=\"true\">\n {isThumbsVertical && thumbnailSwiper}\n <div className={imageClasses}>\n <ReactResizeDetector handleHeight onResize={this.updateSwiperSize}>\n <SliderComponent {...this.galleryParams} shouldSwiperUpdate>\n {slides.map((slide, i) => (\n <div key={i} className={`${cssHandles.productImagesGallerySlide} swiper-slide center-all`}>\n {this.renderSlide(slide, i)}\n </div>\n ))}\n </SliderComponent>\n </ReactResizeDetector>\n {!isThumbsVertical && thumbnailSwiper}\n </div>\n </div>\n )\n }\n}\n\nCarousel.propTypes = {\n slides: PropTypes.arrayOf(\n PropTypes.shape({\n type: PropTypes.string,\n url: PropTypes.string,\n alt: PropTypes.string,\n thumbUrl: PropTypes.string,\n bestUrlIndex: PropTypes.number,\n })\n ),\n displayThumbnailsArrows: PropTypes.bool,\n}\n\nexport default withCssHandles(CSS_HANDLES)(Carousel)\n\n```"
}
] |
code_store-on-localhost_d7a4d968
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CollectionBadges/components/CollectionBadgeItem.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nimport styles from '../styles.css'\n\n/**\n * Collection Badge Item.\n * Displays a collection badge item.\n */\nexport class CollectionBadgeItem extends PureComponent {\n render() {\n return (\n <div className={`${styles.item} mh1 pa2 bg-blue white tc`}>\n {this.props.children}\n </div>\n )\n }\n}\n\nCollectionBadgeItem.propTypes = {\n /** Children component that should be render inside the collection badge item */\n children: PropTypes.node.isRequired,\n}\n\nCollectionBadgeItem.defaultProps = {\n children: {},\n}\n\n```"
}
] |
code_store-on-localhost_e49d4882
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AvailabilitySubscriber/mutations/addToAvailabilitySubscriberMutation.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation availabilitySubscribe($acronym: String!, $document: DocumentInput) {\n createDocument(acronym: $acronym, document: $document) {\n cacheId\n id\n href\n documentId\n }\n}\n\n```"
}
] |
code_store-on-localhost_4c3ac99a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/types/index.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport enum InitialSelectionType {\n complete = 'complete',\n image = 'image',\n empty = 'empty',\n}\n\nexport enum DisplayMode {\n select = 'select',\n default = 'default',\n slider = 'slider',\n}\n\nexport interface SelectorProductItem extends Omit<ProductItem, 'variations'> {\n variations: string[]\n variationValues: Record<string, string>\n}\n\nexport type SelectedVariations = Record<string, string | null>\n\nexport interface CallbackItem {\n name: string\n value: string\n skuId: string | null\n isMainAndImpossible: boolean\n possibleItems: SelectorProductItem[]\n}\n\nexport interface Image {\n imageId: string\n imageLabel: string | null\n imageTag: string\n imageUrl: string\n imageText: string\n}\n\nexport type ImageMap = Record<string, Record<string, Image | undefined>>\n\nexport interface DisplayOption {\n label: string\n onSelectItem: () => void\n image: Image | undefined\n available: boolean\n impossible: boolean\n}\n\nexport interface DisplayVariation {\n name: string\n options: DisplayOption[]\n}\n\nexport type Variations = Record<string, string[]>\n\n```"
}
] |
code_store-on-localhost_ccf1519a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/utils/proptypes.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport PropTypes from 'prop-types'\n\nexport const skuShape = PropTypes.shape({\n /** Name of the SKU Item */\n name: PropTypes.string.isRequired,\n /** Images of the SKU item */\n images: PropTypes.arrayOf(\n PropTypes.shape({\n /** URL of source Image */\n imageUrl: PropTypes.string.isRequired,\n /** Brief description of the image */\n imageLabel: PropTypes.string,\n })\n ).isRequired,\n /** SkuID */\n itemId: PropTypes.string.isRequired,\n /** List of products specifications names */\n variations: PropTypes.arrayOf(\n PropTypes.shape({\n /** Variation Name */\n name: PropTypes.string,\n /** Variation Values */\n values: PropTypes.arrayOf(PropTypes.string),\n })\n ),\n})\n\nexport const parsedSkuShape = PropTypes.shape({\n ...skuShape,\n /** List of products specifications names */\n variations: PropTypes.arrayOf(PropTypes.string),\n})\n\nexport const variationShape = PropTypes.shape({\n /** Variation Name */\n name: PropTypes.string,\n /** Options Array */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n image: PropTypes.shape({\n imageLabel: PropTypes.string,\n imageUrl: PropTypes.string,\n }),\n available: PropTypes.bool,\n label: PropTypes.string,\n onSelectItem: PropTypes.func,\n impossible: PropTypes.bool,\n })\n ),\n})\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.