id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-on-localhost_874ccafa
|
[
{
"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/ProductSummary/components/ProductSummarySKUSelector/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { head } from 'ramda'\nimport SKUSelector from '../../../StoreComponents/SKUSelector'\nimport useCssHandles from '../../../CssHandles/useCssHandles'\nimport ProductSummaryContextApp from '../../../ProductSummaryContext/ProductSummaryContext'\nconst { useProductSummaryDispatch, useProductSummary } = ProductSummaryContextApp\n\nconst CSS_HANDLES = ['SKUSelectorContainer']\n\nfunction ProductSummarySKUSelector(props) {\n const stopBubblingUp = e => {\n e.preventDefault()\n e.stopPropagation()\n }\n const dispatch = useProductSummaryDispatch()\n const { product } = useProductSummary()\n\n const handleSKUSelected = skuId => {\n const selectedItem =\n product.items && product.items.find(item => item.itemId === skuId)\n\n const sku = {\n ...selectedItem,\n image: head(selectedItem.images),\n seller: head(selectedItem.sellers),\n }\n\n const newProduct = {\n ...product,\n selectedItem,\n sku,\n }\n\n dispatch({\n type: 'SET_PRODUCT',\n args: { product: newProduct },\n })\n\n dispatch({\n type: 'SET_PRODUCT_QUERY',\n args: { query: `skuId=${skuId}` },\n })\n }\n\n const handles = useCssHandles(CSS_HANDLES)\n return (\n // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions\n <div\n onClick={stopBubblingUp}\n className={handles.SKUSelectorContainer}\n >\n <SKUSelector onSKUSelected={handleSKUSelected} {...props} />\n </div>\n )\n}\n\nexport default ProductSummarySKUSelector\n\n```"
}
] |
code_store-on-localhost_c36b044e
|
[
{
"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/Minicart/typings/OrderForm.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface OrderFormContext {\n orderForm: OrderForm\n loading: boolean\n}\n\ninterface OrderFormItem {\n additionalInfo: ItemAdditionalInfo\n availability: string\n detailUrl: string\n id: string\n imageUrl: string\n listPrice: number\n measurementUnit: string\n name: string\n price: number\n productId: string\n quantity: number\n sellingPrice: number\n skuName: string\n skuSpecifications: SKUSpecification[]\n uniqueId: string\n productCategories: Record<string, string>\n productCategoryIds: string\n productRefId: string\n}\n\ninterface ItemAdditionalInfo {\n brandName: string\n}\n\ninterface SKUSpecification {\n fieldName: string\n fieldValues: string[]\n}\n\ninterface OrderForm {\n id: string\n items: OrderFormItem[]\n marketingData: MarketingData\n totalizers: Totalizer[]\n value: number\n messages: OrderFormMessages\n}\n\ninterface MarketingData {\n coupon: string\n}\n\ninterface Totalizer {\n id: string\n name: string\n value: number\n}\n\ninterface OrderFormMessages {\n couponMessages: Message[]\n generalMessages: Message[]\n}\n\ninterface Message {\n code: string\n status: string\n text: string\n}\n\n```"
}
] |
code_store-on-localhost_da6b1967
|
[
{
"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/Minicart/typings/vtex.order-items.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.order-items'\ndeclare module 'vtex.order-items/*'\n\n```"
}
] |
code_store-on-localhost_ea99cbc8
|
[
{
"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/Minicart/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface MinicartProps {\n variation: MinicartVariationType\n openOnHover: boolean\n linkVariationUrl: string\n maxDrawerWidth: number | string\n drawerSlideDirection: SlideDirectionType\n}\n\ntype SlideDirectionType =\n | 'horizontal'\n | 'vertical'\n | 'rightToLeft'\n | 'leftToRight'\ntype MinicartVariationType = 'popup' | 'drawer' | 'link'\n\n```"
}
] |
code_store-on-localhost_ce1517fa
|
[
{
"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/Minicart/typings/css.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: Record<string, string>\n export default css\n}\n\n```"
}
] |
code_store-on-localhost_a2144c41
|
[
{
"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/Minicart/typings/vtex.pixel-manager.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.pixel-manager'\ndeclare module 'vtex.pixel-manager/*'\n\n```"
}
] |
code_store-on-localhost_312c5c52
|
[
{
"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/Minicart/legacy/minicart.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container {\n}\n.label {\n}\n.itemImage {\n}\n.item {\n}\n.itemContainer {\n}\n.itemDeleteIcon {\n}\n.itemDeleteIcon {\n}\n.itemDeleteIconLoader {\n}\n.content {\n}\n.contentDiscount {\n}\n.contentPrice {\n}\n.itemName {\n}\n.itemNameLarge {\n}\n.itemFooter {\n}\n.imgContainer {\n}\n.itemRemoveBtn {\n}\n.sidebarScrim {\n}\n.sidebarHeader {\n}\n\n.contentSmall {\n max-height: 383px;\n}\n\n.contentLarge {\n max-height: stretch;\n}\n\n.badge {\n top: -0.7rem;\n right: -0.8rem;\n}\n\n.arrowUp {\n right: 7px;\n}\n\n.box {\n width: 364px;\n top: 100%;\n}\n\n.itemImageLoader {\n width: 100%;\n height: 100%;\n}\n\n.contentFooter {\n}\n\n.footerSpacer {\n}\n\n.footerShippingPriceContainer {\n}\n\n.footerShippingPriceLabelContainer {\n}\n\n.popupContentContainer {\n}\n\n.popupChildrenContainer {\n}\n\n.sidebarRightCaretContainer {\n}\n\n.sidebarItemQuantityContainer {\n}\n\n.labelDiscountText{\n}\n\n@media only screen and (max-width: 40rem) {\n body.sidebarOpen {\n overflow: hidden;\n }\n}\n\n@media only screen and (min-width: 40em) {\n .sidebar {\n width: 340px;\n }\n}\n\n```"
}
] |
code_store-on-localhost_38d05157
|
[
{
"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/Minicart/components/DrawerMode.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport useCssHandles from '../../CssHandles/useCssHandles'\nimport Drawer from '../../Drawer/Drawer'\n\nimport MinicartIconButton from './MinicartIconButton'\n\nconst DRAWER_CLOSE_ICON_HEIGHT = 58\nconst CSS_HANLDES = ['minicartSideBarContentWrapper']\n\ninterface Props {\n maxDrawerWidth: number | string\n drawerSlideDirection: SlideDirectionType\n}\n\nconst DrawerMode: FC<Props> = ({\n maxDrawerWidth,\n drawerSlideDirection,\n children,\n}) => {\n const handles = useCssHandles(CSS_HANLDES)\n\n return (\n <Drawer\n maxWidth={maxDrawerWidth}\n slideDirection={drawerSlideDirection}\n customIcon={<MinicartIconButton />}\n >\n <div\n className={`${handles.minicartSideBarContentWrapper} w-100 h-100`}\n style={{\n height: window.innerHeight - DRAWER_CLOSE_ICON_HEIGHT,\n }}\n >\n {children}\n </div>\n </Drawer>\n )\n}\n\nexport default DrawerMode\n\n```"
}
] |
code_store-on-localhost_f07e0885
|
[
{
"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/Minicart/components/Popup.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable jsx-a11y/no-static-element-interactions */\n/* eslint-disable jsx-a11y/click-events-have-key-events */\nimport React, { FC } from 'react'\nimport Overlay from '../../ReactPortal/Overlay'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport { useMinicartState, useMinicartDispatch } from '../MinicartContext'\nimport MinicartIconButton from './MinicartIconButton'\nimport styles from '../styles.css'\n\nconst CSS_HANDLES = [\n 'popupWrapper',\n 'popupContentContainer',\n 'arrowUp',\n 'popupChildrenContainer',\n]\n\nconst PopupMode: FC = ({ children }) => {\n const {\n open,\n hasBeenOpened,\n openBehavior,\n openOnHoverProp,\n } = useMinicartState()\n const dispatch = useMinicartDispatch()\n const handles = useCssHandles(CSS_HANDLES)\n\n const handleClick = () => {\n if (openOnHoverProp) {\n dispatch({ type: 'SET_OPEN_BEHAVIOR', value: 'hover' })\n }\n dispatch({ type: 'CLOSE_MINICART' })\n }\n const handleMouseLeave = () => {\n dispatch({ type: 'CLOSE_MINICART' })\n }\n\n return (\n <div onMouseLeave={openBehavior === 'hover' ? handleMouseLeave : undefined}>\n <MinicartIconButton />\n {open && (\n <Overlay>\n {openBehavior === 'click' && (\n <div\n className=\"fixed top-0 left-0 w-100 h-100\"\n onClick={handleClick}\n />\n )}\n <div\n className={`${handles.popupWrapper} ${styles.popupBoxPosition} absolute z-max flex flex-column`}\n >\n <div\n className={`${handles.popupContentContainer} w-100 shadow-3 bg-base`}\n >\n <div\n className={`${handles.arrowUp} ${styles.popupArrowUp} absolute top-0 bg-base h1 w1 pa4 rotate-45`}\n />\n <div\n className={`${handles.popupChildrenContainer} mt3 bg-base relative flex flex-column ph5 pv3`}\n >\n {hasBeenOpened && children}\n </div>\n </div>\n </div>\n </Overlay>\n )}\n </div>\n )\n}\n\nexport default PopupMode\n\n```"
}
] |
code_store-on-localhost_abbed357
|
[
{
"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/Minicart/components/MinicartIconButton.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport ButtonWithIcon from '../../Styleguide/ButtonWithIcon'\nimport IconCart from '../../StoreIcons/IconCart'\nimport useCssHandles from '../../CssHandles/useCssHandles'\nimport OrderFormOrder from '../../OrderManager/OrderForm'\n\nimport { useMinicartDispatch, useMinicartState } from '../MinicartContext'\nimport styles from '../styles.css'\n\nconst { useOrderForm } = OrderFormOrder\n\nconst CSS_HANDLES = ['minicartIconContainer', 'minicartQuantityBadge'] as const\n\nconst MinicartIconButton = () => {\n const { orderForm, loading }: OrderFormContext = useOrderForm()\n const handles = useCssHandles(CSS_HANDLES)\n const { open, openBehavior, openOnHoverProp } = useMinicartState()\n const dispatch = useMinicartDispatch()\n const itemQuantity = loading ? 0 : orderForm.items.length\n\n const handleClick = () => {\n if (openOnHoverProp) {\n if (openBehavior === 'hover') {\n dispatch({\n type: 'SET_OPEN_BEHAVIOR',\n value: 'click',\n })\n return\n }\n dispatch({ type: 'CLOSE_MINICART' })\n dispatch({\n type: 'SET_OPEN_BEHAVIOR',\n value: 'hover',\n })\n return\n }\n dispatch({ type: open ? 'CLOSE_MINICART' : 'OPEN_MINICART' })\n }\n\n return (\n <ButtonWithIcon\n icon={\n <span className={`${handles.minicartIconContainer} gray relative`}>\n <IconCart />\n {itemQuantity > 0 && (\n <span\n style={{ userSelect: 'none' }}\n className={`${handles.minicartQuantityBadge} ${styles.minicartQuantityBadgeDefault} c-on-emphasis absolute t-mini bg-emphasis br4 w1 h1 pa1 flex justify-center items-center lh-solid`}\n >\n {itemQuantity}\n </span>\n )}\n </span>\n }\n variation=\"tertiary\"\n onMouseEnter={\n openBehavior === 'hover'\n ? () => dispatch({ type: 'OPEN_MINICART' })\n : undefined\n }\n onClick={handleClick}\n />\n )\n}\n\nexport default MinicartIconButton\n\n```"
}
] |
code_store-on-localhost_d2409e15
|
[
{
"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/Minicart/modules/useCartIdPixel.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useEffect } from 'react'\nimport { usePixel } from '../../PixelContext/PixelContext'\n\nconst useCartIdPixel = (orderFormId?: string) => {\n const { push } = usePixel()\n\n useEffect(() => {\n if (!orderFormId) {\n return\n }\n\n push({\n event: 'cartId',\n cartId: orderFormId,\n } as any)\n }, [push, orderFormId])\n}\n\nexport default useCartIdPixel\n\n```"
}
] |
code_store-on-localhost_c1f5c5f9
|
[
{
"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/Minicart/modules/pixelHelper.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport function mapCartItemToPixel(item: CartItem | any): PixelCartItem {\n return {\n skuId: item.id,\n variant: item.skuName,\n price: item.sellingPrice,\n name: getNameWithoutVariant(item),\n quantity: item.quantity,\n productRefId: item.productRefId,\n brand: item.additionalInfo ? item.additionalInfo.brandName : '',\n category: productCategory(item),\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrls\n ? fixUrlProtocol(item.imageUrls.at3x)\n : item.imageUrl ?? '',\n }\n}\n\nexport function mapBuyButtonItemToPixel(item: BuyButtonItem): PixelCartItem {\n // Change this `/Apparel & Accessories/Clothing/Tops/`\n // to this `Apparel & Accessories/Clothing/Tops`\n const category = item.category ? item.category.slice(1, -1) : ''\n\n return {\n skuId: item.id,\n variant: item.skuName,\n price: item.sellingPrice,\n name: item.name,\n quantity: item.quantity,\n productRefId: item.productRefId,\n brand: item.brand,\n category,\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrl,\n }\n}\n\n/**\n * URL comes like \"//storecomponents.vteximg.com.br/arquivos/ids/155491\"\n * this function guarantees it comes with protocol in it.\n */\nfunction fixUrlProtocol(url: string) {\n if (!url || url.indexOf('http') === 0) {\n return url\n }\n\n return `https:${url}`\n}\n\n/**\n * Remove the variant from the end of the name.\n * Ex: from \"Classic Shoes Pink\" to \"Classic Shoes\"\n */\nfunction getNameWithoutVariant(item: CartItem) {\n if (!item.name.includes(item.skuName)) {\n return item.name\n }\n\n const leadingSpace = 1\n const variantLength = leadingSpace + item.skuName.length\n\n return item.name.slice(0, item.name.length - variantLength)\n}\n\nfunction productCategory(item: CartItem) {\n try {\n const categoryIds = item.productCategoryIds.split('/').filter(c => c.length)\n const category = categoryIds.map(id => item.productCategories[id]).join('/')\n\n return category\n } catch {\n return ''\n }\n}\n\ninterface PixelCartItem {\n skuId: string\n variant: string\n price: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n}\n\ninterface BuyButtonItem {\n id: string\n skuName: string\n sellingPrice: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n}\n\ninterface CartItem {\n id: string\n skuName: string\n sellingPrice: number\n name: string\n quantity: number\n productRefId: string\n additionalInfo: {\n brandName: string\n }\n productCategoryIds: string\n productCategories: Record<string, string>\n detailUrl: string\n // Field from the usual orderForm API\n imageUrl?: string\n // Field from the order-manager orderForm API\n imageUrls?: {\n at1x: string\n at2x: string\n at3x: string\n }\n}\n\n```"
}
] |
code_store-on-localhost_84cde31e
|
[
{
"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/Minicart/modules/debouncedPixelHook.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useRef } from 'react'\nimport { usePixel } from '../../PixelContext/PixelContext'\nimport debounce from 'debounce'\n\nexport default function useDebouncedPush() {\n const { push } = usePixel()\n const debouncedPush = useRef<(param: object) => void>(debounce(push, 600))\n\n return debouncedPush.current\n}\n\n```"
}
] |
code_store-on-localhost_93522398
|
[
{
"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/Minicart/modules/checkoutHook.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport CheckoutUtils from '../../CheckoutResources/Utils'\nconst { useCheckoutURL } = CheckoutUtils\nimport { useRuntime } from '../../../../../vtex.render-runtime'\n\nexport default function useCheckout() {\n const { url: checkoutUrl, major } = useCheckoutURL()\n const { navigate } = useRuntime()\n\n const goToCheckout = (url: string) => {\n if (major > 0 && url === checkoutUrl) {\n navigate({ to: url })\n } else {\n window.location.href = url\n }\n }\n\n return goToCheckout\n}\n\n```"
}
] |
code_store-on-localhost_73c10a06
|
[
{
"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/Minicart/legacy/utils/itemsHelper.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst isParentItem = ({ parentItemIndex, parentAssemblyBinding }) =>\n parentItemIndex == null && parentAssemblyBinding == null\n\nexport const shouldShowItem = item => !!item.quantity && isParentItem(item)\n\n```"
}
] |
code_store-on-localhost_15a553bf
|
[
{
"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/Minicart/legacy/utils/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 const MiniCartPropTypes = {\n /* Set the minicart type */\n type: PropTypes.oneOf(['popup', 'sidebar']),\n /* Set the content visibility */\n hideContent: PropTypes.bool,\n /* Label that will appear when the minicart is empty */\n labelMiniCartEmpty: PropTypes.string,\n /* Finish shopping button label */\n labelButtonFinishShopping: PropTypes.string,\n linkButtonFinishShopping: PropTypes.string,\n /* Icon's classnames */\n iconClasses: PropTypes.string,\n /* Icon's size */\n iconSize: PropTypes.number,\n /* Icon's label */\n iconLabel: PropTypes.object,\n /* Label's classnames */\n labelClasses: PropTypes.string,\n /* Set the discount visibility */\n showDiscount: PropTypes.bool,\n /* Set the shipping fee visibility */\n showShippingCost: PropTypes.bool,\n}\n\n```"
}
] |
code_store-on-localhost_fb0cad17
|
[
{
"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/Minicart/legacy/utils/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 if (!url) return ''\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_629cdd7a
|
[
{
"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/Minicart/legacy/localState/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { head, mergeDeepRight, values } from 'ramda'\nimport { loader } from 'graphql.macro'\n\nconst updateOrderFormShipping = loader('../../../StoreResources/mutations/updateOrderFormShipping.gql')\nconst updateOrderFormCheckin = loader('../../../StoreResources/mutations/updateOrderFormCheckin.gql')\nconst fullMinicartQuery = loader('./graphql/fullMinicartQuery.gql')\n\nexport const ITEMS_STATUS = {\n NONE: 'NONE',\n MODIFIED: 'MODIFIED',\n LOCAL_ITEM: 'LOCAL_ITEM',\n}\n\nexport default function(client) {\n const replayOrderFormServerMutation = mutation => async (\n _,\n variables,\n { cache }\n ) => {\n const response = await client.mutate({\n variables,\n mutation,\n })\n\n const updatedOrderForm = head(values(response.data))\n\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const orderForm = JSON.stringify(\n mergeDeepRight(JSON.parse(data.minicart.orderForm), updatedOrderForm)\n )\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n orderForm,\n },\n },\n })\n return orderForm\n }\n\n const resolvers = {\n Mutation: {\n addToCart: (_, { items }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const cartItems = JSON.parse(data.minicart.items)\n const newItems = items.filter(\n item =>\n !cartItems.find(\n cartItem =>\n cartItem.id === item.id && cartItem.seller === item.seller\n )\n )\n\n const writeItems = cartItems.concat(\n newItems.map(item => ({\n ...item,\n localStatus: navigator.onLine\n ? ITEMS_STATUS.MODIFIED\n : ITEMS_STATUS.LOCAL_ITEM,\n }))\n )\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(writeItems),\n },\n },\n })\n\n return writeItems\n },\n updateItems: (_, { items: newItems }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const cartItems = JSON.parse(data.minicart.items)\n\n // Items provided to this function MUST have a valid index property\n const cleanNewItems = newItems.filter(({ index }) => index != null)\n const items = [...cartItems]\n\n for (const newItem of cleanNewItems) {\n const { index } = newItem\n const prevItem = cartItems[index]\n items[index] = mergeDeepRight(prevItem, {\n ...newItem,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n }\n\n const newCartItems = items.filter(Boolean)\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(newCartItems),\n },\n },\n })\n return newCartItems\n },\n updateLocalItems: (_, { items }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const itemsToRemove = items.filter(({ quantity }) => quantity === 0)\n const itemsToUpdate = items.filter(({ quantity }) => quantity > 0)\n\n const updatedItems = JSON.parse(data.minicart.items)\n .map((item, index) => {\n const updateItem = itemsToUpdate.find(\n updateItem => updateItem.index === index\n )\n\n if (updateItem) {\n return {\n ...item,\n ...updateItem,\n }\n }\n\n return item\n })\n .filter(\n (_, index) =>\n itemsToRemove.findIndex(\n removedItem => removedItem.index === index\n ) === -1\n )\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return updatedItems\n },\n updateOrderForm: (\n _,\n { orderForm, forceUpdateItems = false },\n { cache }\n ) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const prevItems = JSON.parse(data.minicart.items)\n const orderFormItems = (orderForm.items || []).map(item => ({\n ...item,\n localStatus: ITEMS_STATUS.NONE,\n }))\n\n const currentItems = forceUpdateItems\n ? prevItems.map(item => ({\n ...item,\n localStatus:\n item.localStatus === ITEMS_STATUS.MODIFIED\n ? ITEMS_STATUS.NONE\n : item.localStatus,\n }))\n : prevItems\n\n const updatedItems = [\n ...orderFormItems,\n ...currentItems.filter(\n ({ localStatus }) => localStatus !== ITEMS_STATUS.NONE\n ),\n ]\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n orderForm: JSON.stringify(orderForm),\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return orderForm\n },\n updateLocalItemStatus: (_, __, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n const prevItems = JSON.parse(data.minicart.items)\n\n const updatedItems = prevItems.map(item => ({\n ...item,\n localStatus:\n item.localStatus === ITEMS_STATUS.LOCAL_ITEM\n ? ITEMS_STATUS.MODIFIED\n : item.localStatus,\n }))\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return true\n },\n updateOrderFormShipping: replayOrderFormServerMutation(\n updateOrderFormShipping\n ),\n updateOrderFormCheckin: replayOrderFormServerMutation(\n updateOrderFormCheckin\n ),\n setMinicartOpen: (_, { isOpen }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n isOpen,\n },\n },\n })\n return true\n },\n },\n }\n\n const initialState = {\n minicart: {\n __typename: 'Minicart',\n items: '[]',\n orderForm: null,\n isOpen: false,\n },\n }\n\n return { resolvers, initialState }\n}\n\n```"
}
] |
code_store-on-localhost_8e368c31
|
[
{
"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/Minicart/legacy/components/Popup.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 Overlay from '../../../ReactPortal/Overlay'\n\nimport minicart from '../minicart.css'\n\nconst boxPositionStyle = {\n right: -40,\n}\n\n/**\n * Pop-up component.\n */\nconst Popup = ({ children, onOutsideClick }) => {\n return (\n <Overlay>\n <div\n className=\"fixed top-0 left-0 w-100 h-100\"\n onClick={onOutsideClick}\n />\n <div\n className={`${minicart.box} dn db-ns absolute z-max flex flex-colunm`}\n style={boxPositionStyle}\n >\n <div className={`${minicart.popupContentContainer} shadow-3`}>\n <div\n className={`${minicart.arrowUp} absolute top-0 shadow-3 bg-base h1 w1 pa4 rotate-45`}\n />\n <div\n className={`${minicart.popupChildrenContainer} mt3 bg-base relative flex flex-column`}\n >\n {children}\n </div>\n </div>\n </div>\n </Overlay>\n )\n}\n\nPopup.propTypes = {\n /* The pop-up's content */\n children: PropTypes.object,\n /* Offset width to set the arrow position */\n buttonOffsetWidth: PropTypes.number,\n /* Function to be called when click occurs outside the popup */\n onOutsideClick: PropTypes.func,\n}\n\nexport default Popup\n\n```"
}
] |
code_store-on-localhost_387a1331
|
[
{
"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/Minicart/legacy/components/MiniCartFooter.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, memo } from 'react'\nimport classNames from 'classnames'\nimport ProductPrice from '../../../StoreComponents/ProductPrice'\nimport Button from '../../../Styleguide/Button'\nimport Spinner from '../../../Styleguide/Spinner'\nimport { FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport { useRuntime, ExtensionPoint } from '../../../../../../vtex.render-runtime'\n\nimport { MiniCartPropTypes } from '../utils/propTypes'\nimport minicart from '../minicart.css'\n\nconst MiniCartFooter = ({\n shippingCost,\n isSizeLarge,\n isUpdating,\n totalValue,\n buttonLabel,\n buttonLink,\n showDiscount,\n discount,\n labelDiscount,\n showShippingCost,\n}) => {\n const { rootPath = '' } = useRuntime()\n const handleClickButton = () => window.location.assign(rootPath + buttonLink)\n\n const priceAndDiscountClasses = classNames(\n `${minicart.contentDiscount} w-100 flex justify-end items-center mb3`,\n {\n pv3: isSizeLarge,\n }\n )\n\n const checkoutButtonClasses = classNames({\n 'bb bw4 bw2-m b--transparent': isSizeLarge,\n })\n\n const shouldShowShippingCost = showShippingCost && shippingCost > 0\n\n const footerClasses = classNames(\n `${minicart.contentFooter} w-100 bg-base pa4 pv5 flex flex-column items-end`,\n {\n 'bt b--muted-3': shouldShowShippingCost || isSizeLarge,\n }\n )\n\n return (\n <Fragment>\n {shouldShowShippingCost && (\n <div\n className={`${minicart.footerShippingPriceContainer} flex items-center justify-between ma5`}\n >\n <div\n className={`${minicart.footerShippingPriceLabelContainer} t-body c-muted-1`}\n >\n <FormattedMessage id=\"store/minicart.shipping-cost\" />\n </div>\n <ProductPrice\n sellingPriceClass=\"t-heading-5-ns b c-on-base ph2 dib\"\n sellingPrice={shippingCost}\n showLabels={false}\n showListPrice={false}\n />\n </div>\n )}\n <div\n className={minicart.footerSpacer}\n style={{\n marginTop: 'auto',\n }}\n />\n <ExtensionPoint id=\"sandbox\" />\n <div className={footerClasses}>\n {!isUpdating && showDiscount && discount > 0 && (\n <div className={priceAndDiscountClasses}>\n <span\n className={`${minicart.labelDiscountText} ttl c-action-primary`}\n >\n {labelDiscount}\n </span>\n <ProductPrice\n sellingPriceClass=\"c-action-primary t-body ph2 dib\"\n sellingPrice={discount}\n listPrice={discount}\n showLabels={false}\n showListPrice={false}\n />\n </div>\n )}\n <div className={`${minicart.contentPrice} mb3`}>\n {isUpdating ? (\n <Spinner size={18} />\n ) : (\n <ProductPrice\n sellingPriceClass=\"t-heading-5-ns c-on-base b ph2 dib\"\n sellingPrice={totalValue}\n listPrice={totalValue}\n showLabels={false}\n showListPrice={false}\n />\n )}\n </div>\n <div className={checkoutButtonClasses}>\n <Button variation=\"primary\" size=\"small\" onClick={handleClickButton}>\n {buttonLabel}\n </Button>\n </div>\n </div>\n </Fragment>\n )\n}\n\nMiniCartFooter.propTypes = {\n shippingCost: PropTypes.number,\n isSizeLarge: PropTypes.bool,\n isUpdating: PropTypes.bool,\n totalValue: PropTypes.number.isRequired,\n buttonLink: PropTypes.string,\n buttonLabel: PropTypes.string.isRequired,\n showDiscount: MiniCartPropTypes.showDiscount,\n discount: PropTypes.number,\n labelDiscount: PropTypes.string,\n showShippingCost: MiniCartPropTypes.showShippingCost,\n}\n\nexport default memo(MiniCartFooter)\n\n```"
}
] |
code_store-on-localhost_5b80c4e6
|
[
{
"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/Minicart/legacy/components/Sidebar.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 IconCaret from '../../../StoreIcons/IconCaret'\nimport IconCart from '../../../StoreIcons/IconCart'\nimport { injectIntl } from 'react-intl'\nimport OutsideClickHandler from 'react-outside-click-handler'\nimport Animation from '../../../StoreComponents/Animation'\nimport classNames from 'classnames'\nimport Overlay from '../../../ReactPortal/Overlay'\n\nimport minicart from '../minicart.css'\n\nconst OPEN_SIDEBAR_CLASS = minicart.sidebarOpen\n\n/* SideBar component */\nclass Sidebar extends Component {\n updateComponent() {\n if (this.props.isOpen) {\n document.body.classList.add(OPEN_SIDEBAR_CLASS)\n } else {\n document.body.classList.remove(OPEN_SIDEBAR_CLASS)\n }\n }\n\n componentDidMount() {\n this.updateComponent()\n }\n\n componentDidUpdate() {\n this.updateComponent()\n }\n\n componentWillUnmount() {\n document.body.classList.remove(OPEN_SIDEBAR_CLASS)\n }\n\n render() {\n const {\n isOpen,\n onOutsideClick,\n intl,\n iconSize,\n quantity,\n iconsProps,\n } = this.props\n\n if (typeof document === 'undefined') {\n return null\n }\n\n const scrimClasses = classNames(\n `${minicart.sidebarScrim} fixed dim bg-base--inverted top-0 left-0 z-9999 w-100 vh-100 o-40`,\n {\n dn: !isOpen,\n }\n )\n\n return (\n <Overlay fullWidth>\n <OutsideClickHandler onOutsideClick={onOutsideClick}>\n <div\n style={{ willChange: 'opacity' }}\n className={scrimClasses}\n onClick={onOutsideClick}\n />\n\n <Animation\n className={`${minicart.sidebar} w-80 w-auto-ns h-100 fixed top-0 right-0 z-9999 bg-base shadow-2 flex flex-column`}\n isActive={isOpen}\n type=\"drawerLeft\"\n >\n <div\n className={`${minicart.sidebarHeader} pointer flex flex-row items-center pa5 h3 bg-base w-100 z-max bb b--muted-3 bw1`}\n >\n <div\n className={`${minicart.sidebarRightCaretContainer} c-muted-1 pa4 flex items-center`}\n onClick={onOutsideClick}\n >\n <IconCaret orientation=\"right\" size={17} {...iconsProps} />\n </div>\n <div\n className={`${minicart.sidebarItemQuantityContainer} relative c-muted-1`}\n >\n <IconCart size={iconSize} {...iconsProps} />\n {quantity > 0 && (\n <span\n className={`${minicart.badge} c-on-emphasis absolute t-mini bg-emphasis br4 w1 h1 pa1 flex justify-center items-center lh-solid`}\n >\n {quantity}\n </span>\n )}\n </div>\n <span\n className={`${minicart.label} dn-m db-l t-action--small pl${\n quantity > 0 ? '6' : '4'\n } c-muted-1`}\n >\n {intl.formatMessage({ id: 'store/sidebar-title' })}\n </span>\n </div>\n {this.props.children}\n </Animation>\n </OutsideClickHandler>\n </Overlay>\n )\n }\n}\n\nSidebar.propTypes = {\n /* Set the sideBar visibility */\n isOpen: PropTypes.bool,\n /* Sidebar content */\n children: PropTypes.object.isRequired,\n /* Function to be called when click in the close sidebar button or outside the sidebar */\n onOutsideClick: PropTypes.func,\n /* Items quantity */\n quantity: PropTypes.number.isRequired,\n /* Cart icon size */\n iconSize: PropTypes.number,\n /** Props to passed to icons from store-icons */\n iconsProps: PropTypes.shape({\n viewBox: PropTypes.string,\n size: PropTypes.number,\n }),\n}\n\nexport default injectIntl(Sidebar)\n\n```"
}
] |
code_store-on-localhost_c6192281
|
[
{
"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/Minicart/legacy/components/MiniCartContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport { reduceBy, values, clone, find, propEq, compose } from 'ramda'\nimport React, { Component, Fragment } from 'react'\nimport { graphql } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\nimport classNames from 'classnames'\n\nimport { withPixel } from '../../../PixelContext/PixelContext'\n\nimport ButtonWithIcon from '../../../Styleguide/ButtonWithIcon'\nimport Spinner from '../../../Styleguide/Spinner'\nimport IconDelete from '../../../StoreIcons/IconDelete'\n\nimport { MiniCartPropTypes } from '../utils/propTypes'\nimport { toHttps, changeImageUrlSize } from '../utils/urlHelpers'\nimport { mapCartItemToPixel } from '../../modules/pixelHelper'\n\nimport { ITEMS_STATUS } from '../localState/index'\nimport styles from '../minicart.css'\nimport MiniCartFooter from './MiniCartFooter'\n\nimport ProductSummary from '../../../ProductSummary/ProductSummaryLegacy'\nimport { loader } from 'graphql.macro'\n\nconst updateItemsMutation = loader('../localState/graphql/updateItemsMutation.gql')\nconst updateLocalItemsMutation = loader('../localState/graphql/updateLocalItemsMutation.gql')\n\n/**\n * Minicart content component\n */\n\nclass MiniCartContent extends Component {\n static propTypes = {\n /* Set the mini cart content size */\n isSizeLarge: PropTypes.bool,\n /** Define a function that is executed when the item is clicked */\n onClickAction: PropTypes.func,\n /* Update Items mutation */\n updateItems: PropTypes.func.isRequired,\n updateLocalItems: PropTypes.func.isRequired,\n /* Determines if the orderform is updating */\n updatingOrderForm: PropTypes.bool,\n /* Reused props */\n orderForm: PropTypes.object,\n loading: PropTypes.bool,\n labelMiniCartEmpty: MiniCartPropTypes.labelMiniCartEmpty,\n linkButton: MiniCartPropTypes.linkButtonFinishShopping,\n labelButton: MiniCartPropTypes.labelButtonFinishShopping,\n showDiscount: MiniCartPropTypes.showDiscount,\n showShippingCost: MiniCartPropTypes.showShippingCost,\n itemsToShow: PropTypes.arrayOf(PropTypes.object),\n /* Pixel push */\n push: PropTypes.func.isRequired,\n /** Props to passed to icons from store-icons */\n iconsProps: PropTypes.shape({\n viewBox: PropTypes.string,\n size: PropTypes.number,\n }),\n }\n\n state = { isUpdating: [] }\n\n sumItemsPrice = items =>\n items.reduce(\n (sum, { sellingPrice, quantity }) => sum + sellingPrice * quantity,\n 0\n )\n\n getGroupedItems = () =>\n values(\n reduceBy(\n (acc, item) =>\n acc ? { ...acc, quantity: acc.quantity + item.quantity } : item,\n undefined,\n item => item.id,\n this.props.orderForm.items\n )\n )\n\n getShippingCost = orderForm => {\n const totalizer = find(propEq('id', 'Shipping'))(orderForm.totalizers || [])\n return (totalizer && totalizer.value / 100) || 0\n }\n\n calculateDiscount = items =>\n items.reduce(\n (sum, { listPrice, sellingPrice, quantity }) =>\n sum + (listPrice - sellingPrice) * quantity,\n 0\n )\n\n handleItemRemoval = async (item, index) => {\n const { updateItems, updateLocalItems } = this.props\n const updatedItems = [\n {\n id: item.id,\n index: item.cartIndex != null ? item.cartIndex : index,\n quantity: 0,\n },\n ]\n\n try {\n if (item.cartIndex != null) {\n await updateItems(updatedItems)\n } else {\n await updateLocalItems(updatedItems)\n }\n\n this.props.push({\n event: 'removeFromCart',\n items: [mapCartItemToPixel(item)],\n })\n } catch (error) {\n // TODO: Toast error message\n console.error(error)\n }\n }\n\n updateItemLoad = (itemId, newStatus) => {\n const isUpdating = clone(this.state.isUpdating)\n isUpdating[itemId] = newStatus\n this.setState({ isUpdating })\n }\n\n calculateTotalValue = orderForm =>\n this.getShippingCost(orderForm)\n ? orderForm.value\n : this.sumItemsPrice(orderForm.items)\n\n getItemCategory = item => {\n if (!item.productCategoryIds || !item.productCategories) {\n return ''\n }\n\n return item.productCategoryIds\n .split('/')\n .reduce((acc, id) => acc.concat(item.productCategories[id]), [])\n .join('/')\n .slice(1, -1)\n }\n\n createProductShapeFromItem = item => {\n return {\n productName: item.name,\n brand: item.additionalInfo ? item.additionalInfo.brandName : undefined,\n category: this.getItemCategory(item),\n productRefId: item.productRefId,\n linkText: item.detailUrl.replace(/^\\//, '').replace(/\\/p$/, ''),\n sku: {\n seller: {\n commertialOffer: {\n Price: item.sellingPriceWithAssemblies * item.quantity,\n ListPrice: item.listPrice,\n },\n sellerId: item.seller,\n },\n name: item.skuName,\n itemId: item.id,\n image: {\n imageUrl: changeImageUrlSize(toHttps(item ? item.imageUrl : ''), 240),\n },\n },\n assemblyOptions: item.assemblyOptions,\n quantity: item.quantity,\n cartIndex: item.cartIndex,\n }\n }\n\n get isUpdating() {\n const { isUpdating } = this.state\n const {\n orderForm: { items },\n updatingOrderForm,\n } = this.props\n return (\n updatingOrderForm ||\n items.some(item => item.quantity === 0) ||\n isUpdating.some(status => status)\n )\n }\n\n renderWithoutItems = label => (\n <div\n className={`${styles.item} pa9 flex items-center justify-center relative bg-base`}\n >\n <span className=\"t-body\">{label}</span>\n </div>\n )\n\n renderMiniCartWithItems = (\n orderForm,\n itemsToShow,\n label,\n labelDiscount,\n showDiscount,\n onClickAction,\n isUpdating,\n isSizeLarge,\n showShippingCost,\n iconsProps,\n productSummaryProps\n ) => {\n const MIN_ITEMS_TO_SCROLL = 2\n\n const classes = classNames(`${styles.content} overflow-x-hidden pa1`, {\n [`${styles.contentSmall} bg-base`]: !isSizeLarge,\n [`${styles.contentLarge}`]: isSizeLarge,\n 'overflow-y-scroll':\n itemsToShow.length > MIN_ITEMS_TO_SCROLL && !isSizeLarge,\n })\n\n return (\n <Fragment>\n <div className={classes}>\n {itemsToShow.map((item, index) => (\n <Fragment key={item.id}>\n <section className={`${styles.itemContainer} relative flex`}>\n <div\n className={`${styles.itemDeleteIcon} fr absolute top-0 right-0`}\n >\n {isUpdating[item.id] ? (\n <div className={`${styles.itemDeleteIconLoader} ma4`}>\n <Spinner size={18} />\n </div>\n ) : (\n <ButtonWithIcon\n icon={\n <IconDelete\n size={15}\n activeClassName=\"c-muted-2\"\n {...iconsProps}\n />\n }\n variation=\"tertiary\"\n onClick={() => this.handleItemRemoval(item, index)}\n />\n )}\n </div>\n <ProductSummary \n showBorders\n product={this.createProductShapeFromItem(item)}\n name={item.name}\n displayMode=\"inlinePrice\"\n showListPrice={false}\n showBadge={false}\n showInstallments={false}\n showLabels={false}\n actionOnClick={onClickAction}\n muted={item.localStatus !== ITEMS_STATUS.NONE}\n index={index}\n {...(productSummaryProps? productSummaryProps : {})}\n />\n {/* <ExtensionPoint\n id=\"product-summary\"\n showBorders\n product={this.createProductShapeFromItem(item)}\n name={item.name}\n displayMode=\"inlinePrice\"\n showListPrice={false}\n showBadge={false}\n showInstallments={false}\n showLabels={false}\n actionOnClick={onClickAction}\n muted={item.localStatus !== ITEMS_STATUS.NONE}\n index={index}\n /> */}\n </section>\n </Fragment>\n ))}\n </div>\n <MiniCartFooter\n shippingCost={this.getShippingCost(orderForm)}\n isUpdating={this.isUpdating}\n totalValue={this.calculateTotalValue(orderForm)}\n discount={this.calculateDiscount(orderForm.items)}\n buttonLink={this.props.linkButton}\n buttonLabel={label}\n isSizeLarge={isSizeLarge}\n labelDiscount={labelDiscount}\n showDiscount={showDiscount}\n showShippingCost={showShippingCost}\n />\n </Fragment>\n )\n }\n\n renderLoading = () => (\n <div\n className={`${styles.item} pa4 flex items-center justify-center relative bg-base`}\n >\n <Spinner />\n </div>\n )\n\n render() {\n const {\n itemsToShow,\n labelMiniCartEmpty,\n labelButton,\n intl,\n showDiscount,\n onClickAction,\n isSizeLarge,\n showShippingCost,\n orderForm,\n loading,\n iconsProps,\n productSummaryProps,\n } = this.props\n const { isUpdating } = this.state\n\n if (loading) {\n return this.renderLoading()\n }\n\n if (!orderForm || !itemsToShow.length) {\n const label =\n labelMiniCartEmpty || intl.formatMessage({ id: 'store/minicart-empty' })\n return this.renderWithoutItems(label)\n }\n\n const label =\n labelButton ||\n intl.formatMessage({ id: 'store/finish-shopping-button-label' })\n const labelDiscount = intl.formatMessage({\n id: 'store/minicart-content-footer-discount',\n })\n\n return this.renderMiniCartWithItems(\n orderForm,\n itemsToShow,\n label,\n labelDiscount,\n showDiscount,\n onClickAction,\n isUpdating,\n isSizeLarge,\n showShippingCost,\n iconsProps,\n productSummaryProps\n )\n }\n}\n\nconst withUpdateItemsMutation = graphql(updateItemsMutation, {\n name: 'updateItems',\n props: ({ updateItems }) => ({\n updateItems: items => updateItems({ variables: { items } }),\n }),\n})\n\nconst withUpdateLocalItemsMutation = graphql(updateLocalItemsMutation, {\n name: 'updateLocalItems',\n props: ({ updateLocalItems }) => ({\n updateLocalItems: items => updateLocalItems({ variables: { items } }),\n }),\n})\n\nexport default compose(\n injectIntl,\n withUpdateItemsMutation,\n withUpdateLocalItemsMutation,\n withPixel\n)(MiniCartContent)\n\n```"
}
] |
code_store-on-localhost_031bed0e
|
[
{
"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/Minicart/legacy/__tests__/MiniCart.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, fireEvent, wait } from '@vtex/test-tools/react'\nimport { orderForm as orderFormQuery } from 'vtex.store-resources/Queries'\n\nimport orderForm from '../__mocks__/orderForm'\nimport emptyOrderForm from '../__mocks__/emptyOrderForm'\nimport MiniCart from '../../index'\n\nconst mocks = [\n {\n request: {\n query: orderFormQuery,\n },\n result: {\n data: {\n orderForm,\n },\n },\n },\n]\n\nconst emptyMock = [\n {\n request: {\n query: orderFormQuery,\n },\n result: {\n data: {\n orderForm: emptyOrderForm,\n },\n },\n },\n]\n\ndescribe('<MiniCart />', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n it('should render popup onClick', async () => {\n const { getByText, baseElement } = render(\n <MiniCart type=\"popup\" hideContent={false} />\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n let box = baseElement.querySelector('.box')\n let sidebar = baseElement.querySelector('.sidebar')\n\n // Expect box be null before click\n expect(box).toBeNull()\n // Sidebar should not exist before and after click\n expect(sidebar).toBeNull()\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i))\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n box = baseElement.querySelector('.box')\n sidebar = baseElement.querySelector('.sidebar')\n\n // Expect Minicart Popup redered\n expect(box).toBeDefined()\n expect(box).not.toBeNull()\n // Expect sidebar still not rendered\n expect(sidebar).toBeNull()\n })\n\n it('should display sidebar onClick', async () => {\n const { getByText, baseElement } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n let box = baseElement.querySelector('.box')\n let sidebar = baseElement.querySelector('.sidebarScrim.dn')\n\n // Expect box be null before and after click\n expect(box).toBeNull()\n // Sidebar should have diplay none class before click\n expect(sidebar).toBeDefined()\n expect(sidebar).not.toBeNull()\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i))\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n box = baseElement.querySelector('.box')\n sidebar = baseElement.querySelector('.sidebarScrim.dn')\n\n // Expect sidebar dont have display none after click\n expect(sidebar).toBeNull()\n expect(box).toBeNull()\n })\n\n it('should match the snapshot in popup mode', async () => {\n const leftClick = { button: 0 }\n\n const { getByText, asFragment } = render(\n <MiniCart type=\"popup\" hideContent={false} />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i), leftClick)\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot in sidebar mode', async () => {\n const { baseElement } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />,\n { graphql: { mocks } }\n )\n\n await wait(async () => {\n jest.runAllTimers()\n })\n \n expect(baseElement).toMatchSnapshot()\n })\n\n it('should be editable in Site Editor', () => {\n const schema = MiniCart.schema || MiniCart.getSchema({})\n expect(schema).toEqual(\n expect.objectContaining({ title: expect.any(String) })\n )\n })\n\n it('should not show item quantity if there are no items in cart', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty={false} />,\n { graphql: { mocks: emptyMock } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('item-qty')).toBeNull()\n })\n\n it('should show the quantity of different items in cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty={false} />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(getByTestId('item-qty').textContent).toBe('1')\n })\n\n it('should show the total quantity of items in cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(getByTestId('item-qty').textContent).toBe('2')\n })\n\n it('should not show price if showPrice is false', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice={false} />,\n { graphql: { mocks } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n expect(queryByTestId('total-price')).toBeNull()\n })\n\n it('should not show price if there are no items in the cart', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice />,\n { graphql: { mocks: emptyMock } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('total-price')).toBeNull()\n })\n\n it('should show price if there are items in the cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice />,\n { graphql: { mocks } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n expect(getByTestId('total-price')).toBeInTheDocument()\n })\n\n it('should not show price if showPrice is false', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice={false} />,\n { graphql: { mocks } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n expect(queryByTestId('total-price')).toBeNull()\n })\n\n it('should show price if there are items in the cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n \n expect(getByTestId('total-price')).toBeInTheDocument()\n })\n})\n\n```"
}
] |
code_store-on-localhost_f16c2499
|
[
{
"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/Minicart/legacy/__tests__/localState.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport gql from 'graphql-tag'\nimport { loader } from 'graphql.macro'\n\nimport createLocalState from '../localState/index'\nimport { ITEMS_STATUS } from '../localState'\nconst addToCartMutation = loader('../localState/graphql/addToCartMutation.gql')\nconst updateItemsMutation = loader('../localState/graphql/updateItemsMutation.gql')\n\ndescribe('Local State', () => {\n let cache, client\n\n beforeEach(() => {\n cache = new InMemoryCache()\n client = new ApolloClient({\n link: ApolloLink.empty(),\n cache,\n })\n\n const { resolvers, initialState } = createLocalState(client)\n\n client.addResolvers(resolvers)\n cache.writeData({ data: initialState })\n })\n\n it('should append new items to end of cart', async () => {\n const items = [\n {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n {\n id: '101',\n name: 'Chiclete de menta',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete-de-menta/p',\n skuName: 'chiclete de menta',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n ]\n\n await client.mutate({ mutation: addToCartMutation, variables: { items } })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n // assert that the cache items contains all items of the mutation\n expect(cacheItems).toEqual(\n expect.arrayContaining(items.map(expect.objectContaining))\n )\n\n cacheItems.forEach(item => {\n expect(item).toHaveProperty('localStatus', ITEMS_STATUS.MODIFIED)\n })\n })\n\n it('should update quantity of item in cart', async () => {\n const item = {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n }\n\n cache.writeData({\n data: {\n minicart: {\n __typename: 'Minicart',\n items: JSON.stringify([item]),\n },\n },\n })\n\n const updateItemsPayload = [{ index: 0, quantity: 2, id: item.id }]\n\n await client.mutate({\n mutation: updateItemsMutation,\n variables: { items: updateItemsPayload },\n })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({\n id: item.id,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n )\n )\n )\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({ id: item.id, quantity: item.quantity })\n )\n )\n )\n })\n\n it('should update quantity of more than one item in cart', async () => {\n const items = [\n {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n {\n id: '101',\n name: 'Chiclete de menta',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete-de-menta/p',\n skuName: 'chiclete de menta',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n ]\n\n cache.writeData({\n data: {\n minicart: {\n __typename: 'Minicart',\n items: JSON.stringify(items),\n },\n },\n })\n\n const updateItemsPayload = [\n { index: 0, quantity: 2, id: items[0].id },\n { index: 1, quantity: 9, id: items[1].id },\n ]\n\n await client.mutate({\n mutation: updateItemsMutation,\n variables: { items: updateItemsPayload },\n })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({\n id: item.id,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n )\n )\n )\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({ id: item.id, quantity: item.quantity })\n )\n )\n )\n })\n})\n\n```"
}
] |
code_store-on-localhost_9ef026b0
|
[
{
"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/Minicart/legacy/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_2b512cea
|
[
{
"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/Minicart/legacy/localState/graphql/updateLocalItemStatusMutation.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateLocalItemStatus {\n updateLocalItemStatus @client\n}\n\n```"
}
] |
code_store-on-localhost_1693ffc2
|
[
{
"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/Minicart/legacy/localState/graphql/addToCartMutation.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_7f0a61de
|
[
{
"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/Minicart/legacy/localState/graphql/updateLocalItemsMutation.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation UpdateLocalItems($items: [MinicartItem]) {\n updateLocalItems(items: $items) @client\n}\n\n```"
}
] |
code_store-on-localhost_c7627639
|
[
{
"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/Minicart/legacy/localState/graphql/fullMinicartQuery.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery {\n minicart @client {\n items\n orderForm\n isOpen\n }\n}\n\n```"
}
] |
code_store-on-localhost_0e3e6569
|
[
{
"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/Minicart/legacy/localState/graphql/minicartOrderFormQuery.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery orderFormLocal {\n minicart @client {\n orderForm\n }\n}\n\n```"
}
] |
code_store-on-localhost_ccb9cd91
|
[
{
"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/Minicart/legacy/localState/graphql/updateOrderFormMutation.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateOrderForm(\n $orderForm: [OrderForm]\n $forceUpdateItems: Boolean = false\n) {\n updateOrderForm(orderForm: $orderForm, forceUpdateItems: $forceUpdateItems)\n @client\n}\n\n```"
}
] |
code_store-on-localhost_b9324889
|
[
{
"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/Minicart/legacy/localState/graphql/updateItemsMutation.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateItemsLocal($items: [MinicartItem]) {\n updateItems(items: $items) @client\n}\n\n```"
}
] |
code_store-on-localhost_f2197d0f
|
[
{
"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/Minicart/legacy/localState/graphql/setMinicartOpenMutation.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_a2bfc877
|
[
{
"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/Minicart/legacy/__tests__/hooks/useMarketingSessionParams.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { renderHook, wait } from '@vtex/test-tools/react'\nimport useMarketingSessionParams from '../../hooks/useMarketingSessionParams'\n\nconst fakeSessionWithData = {\n response: {\n namespaces: {\n public: {\n ['utm_source']: {\n value: 'utmSource'\n },\n ['utm_medium']: {\n value: 'utmMedium'\n },\n ['utm_campaign']: {\n value: 'utmCampaign'\n },\n ['utmi_cp']: {\n value: 'utmiCampaign'\n },\n ['utmi_p']: {\n value: 'utmiPage'\n },\n ['utmi_pc']: {\n value: 'utmiPart'\n },\n }\n }\n }\n}\n\nconst fakeSessionNoData = {\n response: {\n namespaces: {\n public: {}\n }\n }\n}\n\nit('if session has correct data, get and format input correctly', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise(resolve => resolve(fakeSessionWithData))\n const { result } = renderHook(() => useMarketingSessionParams())\n \n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toMatchObject({\n source: 'utmSource',\n medium: 'utmMedium',\n campaign: 'utmCampaign',\n })\n expect(utmiParams).toMatchObject({\n campaign: 'utmiCampaign',\n page: 'utmiPage',\n part: 'utmiPart',\n })\n})\n\nit('if session does not have data, leave object as undefined', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise(resolve => resolve(fakeSessionNoData))\n const { result } = renderHook(() => useMarketingSessionParams())\n\n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toBe(undefined)\n expect(utmiParams).toBe(undefined)\n})\n\nit('if session promise rejects, everything still works, response is undefined', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise((_, reject) => reject())\n const { result } = renderHook(() => useMarketingSessionParams())\n\n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toBe(undefined)\n expect(utmiParams).toBe(undefined)\n})\n\n```"
}
] |
code_store-on-localhost_c6e95302
|
[
{
"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/StoreIcons/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface IconProps {\n readonly id: string\n readonly handle?: string\n readonly isActive?: boolean\n readonly size?: number\n readonly viewBox?: string\n readonly activeClassName?: string\n readonly mutedClassName?: string\n}\n\ninterface EnhancedIconProps extends IconProps {\n readonly orientation?: string\n readonly state?: string\n readonly shape?: string\n readonly type?: string\n}\n\ninterface CaretProps extends EnhancedIconProps {\n readonly thin?: boolean\n}\n\ninterface Enhancement {\n id: string\n modifier: string\n}\n\n```"
}
] |
code_store-on-localhost_f8c43307
|
[
{
"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/StoreIcons/utils/helpers.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { contains, find, propEq } from 'ramda'\nimport { ORIENTATIONS, SHAPES, STATES, TYPES } from './enhancements'\n\n/**\n * Get the modifer from any collection matching the rule collection{id, modifier}\n * @param {*} id\n * @param {*} collection\n */\nexport const getModifier = (collection: Enhancement[], id?: string) => {\n const foundItem = find(propEq('id', id), collection) as any\n return !!foundItem ? foundItem.modifier : id\n}\n\n/**\n * Get a subset of the collections with given ids (passed with commas)\n * @param {*} tokens\n * @param {*} collection\n */\nexport const getSubset = (tokens: string, collection: Enhancement[]) => {\n const ids = tokens.split(',').join('')\n return collection.filter((item: any) => contains(item.id, ids))\n}\n\n/**\n * Get enhancement modifier\n * @param enhancementList list of enhancements\n * @param enhancement desired enhancement\n * @param supported all supported enhancement list\n */\nexport const getEnhancement = (\n enhancementList: Enhancement[],\n enhancement?: string,\n supported?: string\n) => {\n const supportedEnhancements = !!supported\n ? getSubset(supported, enhancementList)\n : enhancementList\n const modifier = getModifier(supportedEnhancements, enhancement)\n return modifier\n}\n\n/**\n * Get orientation modifier\n * @param orientation desired orientation\n * @param supported suported orientations\n */\nexport const getOrientation = (orientation?: string, supported?: string) =>\n getEnhancement(ORIENTATIONS, orientation, supported)\n\n/**\n * Get type modifier\n * @param type desired type\n * @param supported suported types\n */\nexport const getType = (type?: string, supported?: string) =>\n getEnhancement(TYPES, type, supported)\n\n/**\n * Get state modifier\n * @param state desirend state\n * @param supported suported states\n */\nexport const getState = (state?: string, supported?: string) =>\n getEnhancement(STATES, state, supported)\n\n/**\n * Get shape modifier\n * @param size icon size\n * @param background background color\n * @param shape desired shape\n * @param supported suported shapes\n */\nexport const getShape = (\n size: number,\n background: string,\n shape?: string,\n supported?: string\n) => {\n const REDUCTION_PERCENTAGE = 0.4\n const getReduction = (size: number) => size * REDUCTION_PERCENTAGE\n const modifiers = getEnhancement(SHAPES, shape, supported)\n const reduction = getReduction(size)\n const padding = reduction / 2\n const reducedIconSize = size - reduction\n\n const wrapperProps = [\n { className: `${modifiers} flex` },\n { style: { padding, backgroundColor: background } },\n ]\n\n return { wrapperProps, reducedIconSize }\n}\n\n```"
}
] |
code_store-on-localhost_9b11c389
|
[
{
"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/StoreIcons/utils/enhancements.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const SHAPES = [\n {\n id: 'square',\n modifier: 'br1',\n },\n {\n id: 'rounded',\n modifier: 'br3',\n },\n {\n id: 'circle',\n modifier: 'br-100',\n },\n]\n\nexport const ORIENTATIONS = [\n {\n id: 'up',\n modifier: '--up',\n },\n {\n id: 'down',\n modifier: '--down',\n },\n {\n id: 'right',\n modifier: '--right',\n },\n {\n id: 'left',\n modifier: '--left',\n },\n]\n\nexport const STATES = [\n {\n id: 'on',\n modifier: '--on',\n },\n {\n id: 'off',\n modifier: '--off',\n },\n]\n\nexport const TYPES = [\n {\n id: 'filled',\n modifier: '--filled',\n },\n {\n id: 'outline',\n modifier: '--outline',\n },\n {\n id: 'line',\n modifier: '--line',\n },\n]\n\n```"
}
] |
code_store-on-localhost_848ca839
|
[
{
"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/StoreIcons/components/Icon.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport Use from './Use'\nimport Svg from './Svg'\n\nimport './icon.global.css'\n\nconst CSS_HANDLES = [\n 'arrowBackIcon',\n 'assistantSalesIcon',\n 'caretIcon',\n 'cartIcon',\n 'checkIcon',\n 'closeIcon',\n 'deleteIcon',\n 'equalsIcon',\n 'eyeSightIcon',\n 'filterIcon',\n 'globeIcon',\n 'gridIcon',\n 'heartIcon',\n 'homeIcon',\n 'inlineGridIcon',\n 'locationInputIcon',\n 'locationMarkerIcon',\n 'menuIcon',\n 'minusIcon',\n 'plusIcon',\n 'profileIcon',\n 'removeIcon',\n 'searchIcon',\n 'singleGridIcon',\n 'socialIcon',\n 'starIcon',\n 'swapIcon',\n] as const\n\nconst Icon = ({\n id,\n handle,\n isActive,\n size,\n viewBox,\n activeClassName,\n mutedClassName,\n}: IconProps) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <Svg\n fill=\"none\"\n width={size}\n height={size}\n viewBox={viewBox}\n className={`${\n isActive ? activeClassName || '' : mutedClassName || ''\n } ${handles[handle] || ''}`}\n >\n <Use id={id} />\n </Svg>\n )\n}\n\nIcon.defaultProps = {\n isActive: true,\n size: 16,\n viewBox: '0 0 16 16',\n}\n\nexport default Icon\n\n```"
}
] |
code_store-on-localhost_a538a3a6
|
[
{
"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/StoreIcons/components/Use.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n id: string\n}\n\nconst Use = ({ id }: Props) => <use href={`#${id}`} xlinkHref={`#${id}`} />\n\nexport default Use\n\n```"
}
] |
code_store-on-localhost_d385f891
|
[
{
"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/StoreIcons/components/Svg.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { ReactNode } from 'react'\n\ninterface Props {\n readonly fill?: string\n readonly width?: number\n readonly height?: number\n readonly viewBox?: string\n readonly className?: string\n readonly xmlns?: string\n readonly xmlnsXlink?: string\n readonly children?: ReactNode\n}\n\nconst Svg = ({ children, ...props }: Props) => <svg {...props}>{children}</svg>\n\nSvg.defaultProps = {\n xmlns: 'http://www.w3.org/2000/svg',\n xmlnsXlink: 'http://www.w3.org/1999/xlink',\n}\n\nexport default Svg\n\n```"
}
] |
code_store-on-localhost_96227677
|
[
{
"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/StoreIcons/components/icon.global.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@keyframes sti-loading-rotate {\n 0% {\n transform: rotate(0);\n }\n 100% {\n transform: rotate(360deg);\n }\n}\n\n.sti-loading-rotate {\n transform-origin: 50px 50px;\n animation: sti-loading-rotate 0.7s infinite linear;\n}\n\n```"
}
] |
code_store-on-localhost_05469eb1
|
[
{
"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/StoreIcons/__tests__/Svg.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport Svg from '../components/Svg'\n\ndescribe('Svg', () => {\n it('should match snapshot', () => {\n const component = render(\n <Svg fill=\"black\">\n <path />\n </Svg>\n ).asFragment()\n expect(component).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_71498019
|
[
{
"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/StoreIcons/__tests__/Icon.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport Icon from '../components/Icon'\n\ndescribe('Icon', () => {\n it('should match snapshot', () => {\n const component = render(<Icon id=\"tst-snapshot\" size={20} />).asFragment()\n expect(component).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_4387e955
|
[
{
"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/StoreIcons/__tests__/Use.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport Use from '../components/Use'\n\ndescribe('Use', () => {\n it('should match snapshot', () => {\n const component = render(\n <svg>\n <Use id=\"tst-snapshot\" />\n </svg>\n ).asFragment()\n expect(component).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_7bef8d8f
|
[
{
"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/StoreIcons/__tests__/Enhancements.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport {\n getSubset,\n getShape,\n getOrientation,\n getState,\n getType,\n} from '../utils/helpers'\nimport { SHAPES, ORIENTATIONS } from '../utils/enhancements'\n\ndescribe('Enhancements', () => {\n it('should allow supported enhancements', () => {\n const shapes = getSubset('square', SHAPES)\n const orientations = getSubset('down, right', ORIENTATIONS)\n\n expect(shapes).toEqual([\n {\n id: 'square',\n modifier: 'br1',\n },\n ])\n\n expect(orientations).toEqual([\n {\n id: 'down',\n modifier: '--down',\n },\n {\n id: 'right',\n modifier: '--right',\n },\n ])\n })\n\n it('should get the correct shape', () => {\n const square = getShape(16, 'red', 'square')\n const rounded = getShape(20, 'green', 'rounded')\n const circle = getShape(24, 'blue', 'circle')\n\n expect(square.reducedIconSize).toBeLessThan(16)\n expect(rounded.reducedIconSize).toBeLessThan(20)\n expect(circle.reducedIconSize).toBeLessThan(24)\n\n expect(square.wrapperProps).toHaveLength(2)\n expect(rounded.wrapperProps).toHaveLength(2)\n expect(circle.wrapperProps).toHaveLength(2)\n\n expect(square.wrapperProps[0].className).toContain('br1')\n expect(rounded.wrapperProps[0].className).toContain('br3')\n expect(circle.wrapperProps[0].className).toContain('br-100')\n\n expect(square.wrapperProps[1].style!.backgroundColor).toEqual('red')\n expect(rounded.wrapperProps[1].style!.backgroundColor).toEqual('green')\n expect(circle.wrapperProps[1].style!.backgroundColor).toEqual('blue')\n })\n\n it('should get the correct orientation', () => {\n const up = getOrientation('up')\n const down = getOrientation('down')\n const left = getOrientation('left')\n const right = getOrientation('right')\n\n expect(up).toEqual('--up')\n expect(down).toEqual('--down')\n expect(left).toEqual('--left')\n expect(right).toEqual('--right')\n })\n\n it('should get the correct state', () => {\n const on = getState('on')\n const off = getState('off')\n\n expect(on).toEqual('--on')\n expect(off).toEqual('--off')\n })\n\n it('should get the correct type', () => {\n const filled = getType('filled')\n const outline = getType('outline')\n const line = getType('line')\n\n expect(filled).toEqual('--filled')\n expect(outline).toEqual('--outline')\n expect(line).toEqual('--line')\n })\n})\n\n```"
}
] |
code_store-on-localhost_b1d265fe
|
[
{
"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/StoreIcons/testUtils/setupTests.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n// react-testing-library renders your components to document.body,\n// this will ensure they're removed after each test.\nimport 'react-testing-library/cleanup-after-each'\n\n// this adds jest-dom's custom assertions\nimport 'jest-dom/extend-expect'\n\n```"
}
] |
code_store-on-localhost_9bb45460
|
[
{
"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/Slider/utils/resolveSlidesNumber.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/**\n * This function returns the number of slides to show depending on the size of the window.\n * If you pass a number it just returns that number.\n * If you pass an object it will return the number of slides of the closest breakpoint to the size of the window.\n * If you pass for example\n * perPage = {\n * 400: 2,\n * 1000: 3\n * }\n *\n * If the size of the window is something between 400px and 999px if will return 2,\n * if it is 1000px or bigger, it will return 3, and if it is smaller than 400px it\n * will return the default value; that is, 1.\n * @param {number|object} perPage\n * @param {number|undefined} minPerPage\n */\nfunction resolveSlidesNumber(minPerPage, perPage, isMobile) {\n let result = minPerPage || 1\n if (typeof perPage === 'number') {\n result = perPage\n } else if (typeof perPage === 'object') {\n const innerWidth = window && window.innerWidth\n\n /** If it's on SSR, use placeholder screen sizes to get an approximate\n * guess of how many items are displayed per page */\n const windowSize = innerWidth || (isMobile ? 320 : 1024)\n\n for (const viewport in perPage) {\n if (windowSize >= viewport) {\n result = perPage[viewport]\n }\n }\n }\n return result < minPerPage ? minPerPage : result\n}\n\nexport default resolveSlidesNumber\n\n```"
}
] |
code_store-on-localhost_371f187d
|
[
{
"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/Slider/utils/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport function setStyle(target, styles) {\n Object.keys(styles).forEach(attr => {\n target.style[attr] = styles[attr]\n })\n}\n\nfunction getZeroOrString(num = 0) {\n return num === 0 ? num : `${num}%`\n}\n\nexport function getTranslateProperty(x = 0, y = 0, z = 0) {\n return {\n transform: `translate3d(${getZeroOrString(x)}, ${getZeroOrString(\n y\n )}, ${getZeroOrString(z)})`,\n WebkitTransform: `translate3d(${getZeroOrString(x)}, ${getZeroOrString(\n y\n )}, ${getZeroOrString(z)})`,\n }\n}\n\nexport function getStylingTransition(easing, duration = 0) {\n return {\n WebkitTransition: `all ${duration}ms ${easing}`,\n transition: `all ${duration}ms ${easing}`,\n }\n}\n\nexport const constants = {\n defaultResizeDebounce: 250,\n defaultTransitionDuration: 250,\n NAVIGATION_PAGE: 'page',\n}\n\n```"
}
] |
code_store-on-localhost_af0baa8c
|
[
{
"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/Slider/components/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.slideImg {\n margin-right: -50%;\n transform: translate(-50%, -50%);\n left: 50%;\n top: 50%;\n}\n\n.dotsContainer {\n margin-right: -50%;\n transform: translate(-50%, 0);\n left: 50%;\n}\n\n.arrowContainer {\n top: 50%;\n transform: translate(0, -50%);\n}\n\n.sliderFrame {\n will-change: transform;\n}\n\n```"
}
] |
code_store-on-localhost_9b802f64
|
[
{
"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/Slider/components/Dots.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'\nimport classnames from 'classnames'\nimport debounce from 'debounce'\nimport EventListener from 'react-event-listener'\nimport { constants } from '../utils'\nimport resolveSlidesNumber from '../utils/resolveSlidesNumber'\nimport styles from './styles.css'\n\nclass Dots extends PureComponent {\n static propTypes = {\n /** Classes to style the elements fo the component */\n classes: PropTypes.shape({\n root: PropTypes.string,\n dot: PropTypes.string,\n activeDot: PropTypes.string,\n notActiveDot: PropTypes.string,\n }),\n /** Current slide on the screen, if you have perPage > 1, then the current slide is the most left slide on the screen */\n currentSlide: PropTypes.number,\n /** Extra props to be applied to the dot element */\n dotProps: PropTypes.object,\n /** The size of the dots, can be a number (in this case it will use px unit), or a string (you have to pass the number with the unit e.g '3rem') */\n dotSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /** Tag to be rendered in the dot element */\n dotTag: PropTypes.string,\n /** If the slides should be looping */\n loop: PropTypes.bool,\n /** Function to change the currentSlide */\n onChangeSlide: PropTypes.func.isRequired,\n /** This prop works the same way the minPerPage of Slider and this component should receive the same value of Slider */\n minPerPage: PropTypes.number,\n /** This prop works the same way the perPage of Slider and this component should receive the same value of Slider */\n perPage: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),\n /** Debounce time in milliseconds. */\n resizeDebounce: PropTypes.number,\n /** Tag of root element of the component to be rendered */\n rootTag: PropTypes.string,\n /** Total value of sliders that will be rendered */\n totalSlides: PropTypes.number.isRequired,\n /** If this flag is true, then every dot represent a page of slides (e.g. if perPage = 2 and you have 4 elements,\n * then you have 2 dots), if false, then it will render a dot to every slide */\n showDotsPerPage: PropTypes.bool,\n }\n\n static defaultProps = {\n classes: {\n root: '',\n dot: '',\n activeDot: '',\n notActiveDot: '',\n },\n dotTag: 'li',\n loop: false,\n perPage: 1,\n rootTag: 'ul',\n showDotsPerPage: false,\n resizeDebounce: constants.defaultResizeDebounce,\n }\n\n constructor(props) {\n super(props)\n\n this.handleResize = debounce(this._setPerPageOnResize, props.resizeDebounce)\n }\n\n get slideIndeces() {\n const { showDotsPerPage, totalSlides } = this.props\n return this.perPage\n ? [\n ...Array(\n showDotsPerPage\n ? Math.ceil(totalSlides / this.perPage)\n : totalSlides\n ).keys(),\n ]\n : []\n }\n\n get selectedDot() {\n const { showDotsPerPage, currentSlide, loop } = this.props\n const realCurrentSlide = loop ? currentSlide - this.perPage : currentSlide\n return showDotsPerPage\n ? Math.floor(realCurrentSlide / this.perPage)\n : realCurrentSlide\n }\n\n handleDotClick = index => {\n const { showDotsPerPage, onChangeSlide, loop } = this.props\n const slideToGo = showDotsPerPage ? index * this.perPage : index\n onChangeSlide(loop ? slideToGo + this.perPage : slideToGo)\n }\n\n componentWillUnmount() {\n this.handleResize.clear()\n }\n\n _setPerPageOnResize = () => {\n const { minPerPage, perPage } = this.props\n this.perPage = resolveSlidesNumber(minPerPage, perPage)\n this.forceUpdate()\n }\n\n render() {\n const {\n rootTag: RootTag,\n dotTag: DotTag,\n classes: classesProp,\n dotProps,\n minPerPage,\n perPage,\n totalSlides,\n dotSize,\n } = this.props\n\n const classes = {\n ...Dots.defaultProps.classes,\n ...classesProp,\n }\n\n if (totalSlides < 2) {\n return null\n }\n\n if (!this.perPage) {\n this.perPage = resolveSlidesNumber(minPerPage, perPage)\n }\n\n return (\n <RootTag\n className={classnames(\n styles.dotsContainer,\n classes.root,\n 'absolute ma0 pa0 dib list'\n )}\n >\n <EventListener target=\"window\" onResize={this.handleResize} />\n {this.slideIndeces.map(i => {\n const dotClasses = classnames(classes.dot, 'dib', {\n [classes.activeDot]: i === this.selectedDot,\n [classes.notActiveDot]: i !== this.selectedDot,\n })\n\n return (\n <DotTag\n className={dotClasses}\n key={i}\n onClick={() => this.handleDotClick(i)}\n {...{ style: { height: dotSize, width: dotSize } }}\n {...dotProps}\n />\n )\n })}\n </RootTag>\n )\n }\n}\n\nexport default Dots\n\n```"
}
] |
code_store-on-localhost_a4d7cdd6
|
[
{
"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/Slider/components/Slide.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport EventListener from 'react-event-listener'\nimport classnames from 'classnames'\nimport PropTypes from 'prop-types'\nimport debounce from 'debounce'\nimport styles from './styles.css'\nimport { constants } from '../utils'\n\nclass SlideComponent extends PureComponent {\n constructor(props) {\n super(props)\n this.imgRef = React.createRef()\n this.handleResize = debounce(() => {\n setTimeout(() => {\n this.fit()\n }, props.sliderTransitionDuration)\n }, props.resizeDebounce)\n\n this.state = {\n firstRender: true\n }\n }\n\n componentDidMount() {\n this.ensureImageCover()\n this.setState({ firstRender: false })\n }\n\n componentDidUpdate() {\n this.ensureImageCover()\n }\n\n componentWillUnmount() {\n this.handleResize.clear()\n }\n\n fit = () => {\n const { current: imgElement } = this.imgRef\n\n if (!imgElement || !imgElement.complete) {\n return\n }\n\n const imgAspectRatio = imgElement.width / imgElement.height\n const parentAspectRatio = imgElement.parentNode.offsetWidth / imgElement.parentNode.offsetHeight\n\n if (imgAspectRatio > parentAspectRatio) {\n imgElement.classList.remove('w-100')\n imgElement.classList.add('h-100')\n } else {\n imgElement.classList.remove('h-100')\n imgElement.classList.add('w-100')\n }\n imgElement.removeEventListener('load', this.fit)\n }\n\n ensureImageCover = () => {\n const { current: imgElement } = this.imgRef\n if (!imgElement || !this.props.fitImg) {\n return\n }\n\n if (imgElement.complete) {\n this.fit()\n } else {\n imgElement.addEventListener('load', this.fit)\n }\n }\n\n render() {\n const {\n children,\n className,\n tag: RootComponent,\n fitImg,\n innerRef,\n resizeDebounce,\n defaultWidth,\n style,\n sliderTransitionDuration,\n ...rootProps\n } = this.props\n\n return (\n <RootComponent\n ref={innerRef}\n className={classnames(className, 'inline-flex h-100 relative overflow-hidden')}\n style={{ ...style }}\n {...rootProps}\n >\n <EventListener target=\"window\" onResize={this.handleResize} />\n {React.Children.map(children, child => {\n if (!React.isValidElement(child)) {\n return null\n }\n if (fitImg && child.type === 'img') {\n return React.cloneElement(child, {\n ref: this.imgRef,\n className: classnames(styles.slideImg, child.props.className, 'absolute')\n })\n }\n\n return child\n })}\n </RootComponent>\n )\n }\n}\n\nconst renderForwardRef = (props, ref) => <SlideComponent innerRef={ref} {...props} />\n\nrenderForwardRef.displayName = 'Slide'\n\nconst Slide = React.forwardRef(renderForwardRef)\n\nSlide.propTypes = {\n /** Node to render */\n children: PropTypes.node.isRequired,\n /** Classes to pass to root of slider */\n className: PropTypes.string,\n /** Default width of root in px */\n defaultWidth: PropTypes.number,\n /** Tag to be rendered in root element */\n tag: PropTypes.string,\n /** If the slide component should try to fit the img (only works if children is an img element) */\n fitImg: PropTypes.bool,\n /** Time of debounce of resize event listener */\n resizeDebounce: PropTypes.number,\n /** Duration of transition passed to Slider (must be the same), if nothing is passed to any of the components\n * it will apply the same default value\n */\n sliderTransitionDuration: PropTypes.number\n}\n\nSlide.defaultProps = {\n tag: 'li',\n fitImg: true,\n resizeDebounce: constants.defaultResizeDebounce,\n sliderTransitionDuration: constants.defaultTransitionDuration\n}\n\nexport default Slide\n\n```"
}
] |
code_store-on-localhost_7c8c1295
|
[
{
"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/Slider/components/SliderContainer.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport classnames from 'classnames'\nimport PropTypes from 'prop-types'\n\nclass SliderContainerComponent extends PureComponent {\n intervalRef = null\n\n setNewInterval = () => {\n const { autoplay, autoplayInterval, onNextSlide } = this.props\n\n if (\n !autoplay ||\n typeof autoplayInterval !== 'number' ||\n autoplayInterval === 0\n ) {\n return\n }\n\n if (this.intervalRef) {\n clearInterval(this.intervalRef)\n }\n\n this.intervalRef = setInterval(() => {\n onNextSlide && onNextSlide()\n }, autoplayInterval)\n }\n\n componentDidMount() {\n if (this.props.autoplay && this.props.autoplayInterval > 0) {\n this.setNewInterval()\n }\n }\n\n componentWillUnmount() {\n clearInterval(this.intervalRef)\n }\n\n eventProcedure = (e, eventCallback, clearOnPause = true) => {\n const { pauseOnHover } = this.props\n if (pauseOnHover) {\n clearOnPause ? clearInterval(this.intervalRef) : this.setNewInterval()\n }\n if (eventCallback) {\n eventCallback(e)\n }\n }\n\n onTouchStart = e => {\n this.eventProcedure(e, this.props.onTouchStart)\n }\n\n onTouchEnd = e => {\n this.eventProcedure(e, this.props.onTouchEnd, false)\n }\n\n onMouseEnter = e => {\n this.eventProcedure(e, this.props.onMouseEnter)\n }\n\n onMouseLeave = e => {\n this.eventProcedure(e, this.props.onMouseLeave, false)\n }\n\n render() {\n const {\n className,\n children,\n tag: RootTag,\n innerRef,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n onTouchEnd,\n onNextSlide,\n pauseOnHover,\n autoplay,\n autoplayInterval,\n ...otherProps\n } = this.props\n\n return (\n <RootTag\n ref={innerRef}\n className={classnames(className, 'relative')}\n onMouseEnter={this.onMouseEnter}\n onMouseLeave={this.onMouseLeave}\n onTouchStart={this.onTouchStart}\n onTouchEnd={this.onTouchEnd}\n {...otherProps}\n >\n {children}\n </RootTag>\n )\n }\n}\n\nconst renderForwardRef = (props, ref) => (\n <SliderContainerComponent innerRef={ref} {...props} />\n)\nrenderForwardRef.displayName = 'SliderContainer'\nconst SliderContainer = React.forwardRef(renderForwardRef)\n\nSliderContainer.propsTypes = {\n /** If the slider should be passing automatically */\n autoplay: PropTypes.boolean,\n /** Time in milliseconds of the interval to pass from a slider to the next one */\n autoplayInterval: PropTypes.number,\n /** Children of the component to render */\n children: PropTypes.node.isRequired,\n /** Classes to be applied to the root element */\n className: PropTypes.string,\n /** Function to go to the next slide */\n onNextSlide: PropTypes.func,\n /** If the interval should not be executed if the mouse is on the component */\n pauseOnHover: PropTypes.boolean,\n /** Tag to render the component */\n tag: PropTypes.string,\n}\n\nSliderContainer.defaultProps = {\n autoplay: false,\n autoplayInterval: 5000,\n pauseOnHover: true,\n tag: 'div',\n}\n\nexport default SliderContainer\n\n```"
}
] |
code_store-on-localhost_2284ba34
|
[
{
"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/Slider/components/Slider.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent, Fragment } from 'react'\nimport debounce from 'debounce'\nimport classnames from 'classnames'\nimport PropTypes from 'prop-types'\nimport EventListener from 'react-event-listener'\nimport styles from './styles.css'\nimport resolveSlidesNumber from '../utils/resolveSlidesNumber'\nimport withDevice from '../../DeviceDetector/withDevice'\n\nimport {\n getStylingTransition,\n getTranslateProperty,\n setStyle,\n constants,\n} from '../utils'\n\nclass Slider extends PureComponent {\n static propTypes = {\n /** A render function that will receive as props an orientation prop\n * and a onClick callback */\n arrowRender: PropTypes.func,\n /** The component used to contain both arrows.\n * Either a string to use a DOM element or a component.\n */\n arrowsContainerComponent: PropTypes.oneOfType([\n PropTypes.func,\n PropTypes.string,\n ]),\n /** The slides to render */\n children: PropTypes.oneOfType([\n PropTypes.element,\n PropTypes.arrayOf(PropTypes.element),\n ]),\n /** Classes to apply to the Slider elements */\n classes: PropTypes.shape({\n root: PropTypes.string,\n sliderFrame: PropTypes.string,\n }),\n /** Current slide on the screen (if you have perPage > 1, then the current slide is the most left slide on the screen) */\n currentSlide: PropTypes.number,\n /** Css value of cursor when mouse is hovering the slider frame */\n cursor: PropTypes.string,\n /** Css value of cursos when mouse is down */\n cursorOnMouseDown: PropTypes.string,\n // TODO draggable: PropTypes.bool,\n /** Duration of transitions */\n duration: PropTypes.number,\n /** Transition function */\n easing: PropTypes.string,\n /** If the slides should be looping */\n loop: PropTypes.bool,\n /** Function to change the value of currentSlide */\n onChangeSlide: PropTypes.func.isRequired,\n /** Minimum amount of slides to be on the screen */\n minPerPage: PropTypes.number,\n /** Amount of slides to be on the screen, if a number is passed, then thats the slides that will be shown,\n * if an object with breakpoints is passed, then the component will check the size of the screen to see how\n * many elements will be on the screen\n */\n perPage: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),\n /** Resize debounce timer in milliseconds */\n resizeDebounce: PropTypes.number,\n /** Tag to be rendered in the root element of the page */\n rootTag: PropTypes.string,\n /** Tag to be rendered in the slider frame */\n sliderFrameTag: PropTypes.string,\n /** Threshold of pixels to drag to the slider let it go to the next/prev slide */\n threshold: PropTypes.number,\n /** If should scroll by page or one item at a time */\n scrollByPage: PropTypes.bool,\n /** Check if on mobile using vtex.device-detector */\n isMobile: PropTypes.bool,\n draggable: PropTypes.bool,\n navigationStep: PropTypes.oneOfType([\n PropTypes.oneOf([constants.NAVIGATION_PAGE]),\n PropTypes.number,\n ]),\n }\n\n static defaultProps = {\n classes: {\n root: '',\n sliderFrame: '',\n },\n currentSlide: 0,\n cursor: 'default',\n cursorOnMouseDown: 'default',\n draggable: false,\n duration: 250,\n easing: 'ease-out',\n loop: false,\n perPage: 1,\n resizeDebounce: constants.defaultResizeDebounce,\n rootTag: 'div',\n showArrows: false,\n sliderFrameTag: 'ul',\n threshold: 50,\n scrollByPage: false,\n navigationStep: 'page',\n }\n\n static events = [\n 'onTouchStart',\n 'onTouchEnd',\n 'onTouchMove',\n 'onMouseUp',\n 'onMouseDown',\n 'onMouseLeave',\n 'onMouseMove',\n ]\n\n static getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.currentSlide !== prevState.currentSlide) {\n const { currentSlide, children } = nextProps\n const perPage = resolveSlidesNumber(\n nextProps.minPerPage,\n nextProps.perPage,\n nextProps.isMobile\n )\n const currentSlideIsClone =\n currentSlide < perPage ||\n currentSlide >= React.Children.count(children) + perPage\n return {\n currentSlide: currentSlideIsClone\n ? prevState.currentSlide\n : currentSlide,\n enableTransition: !currentSlideIsClone,\n }\n }\n\n return null\n }\n\n constructor(props) {\n super(props)\n\n this.drag = {\n startX: 0,\n endX: 0,\n startY: 0,\n letItGo: null,\n }\n\n this._selector = React.createRef()\n this._sliderFrame = React.createRef()\n this._sliderFrameWidth = 0\n this.handleResize = debounce(this.fit, props.resizeDebounce)\n this.perPage = resolveSlidesNumber(\n props.minPerPage,\n props.perPage,\n props.isMobile\n )\n\n this.state = {\n firstRender: true,\n currentSlide: props.currentSlide,\n enableTransition: false,\n dragDistance: 0,\n }\n }\n\n componentDidMount() {\n const { onChangeSlide, currentSlide, loop } = this.props\n let stateCurrentSlide = currentSlide\n if (loop) {\n if (this.isNegativeClone(currentSlide)) {\n onChangeSlide(currentSlide + this.perPage)\n stateCurrentSlide += this.perPage\n } else if (this.isPositiveClone(currentSlide)) {\n const mirrorIndex =\n this.childrenLength + this.perPage - currentSlide - 1\n onChangeSlide(mirrorIndex)\n }\n }\n this.setState({\n firstRender: false,\n currentSlide: stateCurrentSlide,\n })\n }\n\n componentWillUnmount() {\n this.handleResize.clear()\n }\n\n componentDidUpdate() {\n const newState = {\n currentSlide: this.state.currentSlide,\n dragDistance: 0,\n enableTransition: true,\n }\n\n if (this.props.currentSlide !== this.state.currentSlide) {\n const { currentSlide } = this.state\n const { onChangeSlide } = this.props\n if (this.isNegativeClone(currentSlide)) {\n newState.currentSlide = currentSlide + this.perPage\n onChangeSlide(newState.currentSlide)\n } else if (this.isPositiveClone(currentSlide)) {\n newState.currentSlide = this.totalSlides - currentSlide\n onChangeSlide(newState.currentSlide)\n } else {\n onChangeSlide(currentSlide)\n }\n this.setState(newState)\n } else if (this.state.dragDistance) {\n this.setState(newState)\n }\n\n this.setSelectorWidth()\n this.setInnerElements()\n this.perPage = resolveSlidesNumber(\n this.props.minPerPage,\n this.props.perPage,\n this.props.isMobile\n )\n this._sliderFrameWidth = this._sliderFrame.current.getBoundingClientRect().width\n }\n\n isNegativeClone = index => {\n return index < this.perPage\n }\n\n isPositiveClone = index => {\n return index >= this.childrenLength + this.perPage\n }\n\n getNegativeClone = index => {\n return index - this.childrenLength\n }\n\n getPositiveClone = index => {\n return index + this.childrenLength\n }\n\n fit = () => {\n const { minPerPage, perPage, currentSlide, onChangeSlide } = this.props\n this.perPage = resolveSlidesNumber(minPerPage, perPage, this.props.isMobile)\n const newCurrentSlide =\n Math.floor(currentSlide / this.perPage) * this.perPage\n\n this.setSelectorWidth()\n this._sliderFrameWidth = this._sliderFrame.current.getBoundingClientRect().width\n\n if (currentSlide !== newCurrentSlide) {\n this.setState({\n currentSlide: newCurrentSlide,\n enableTransition: false,\n })\n onChangeSlide(newCurrentSlide)\n }\n this.forceUpdate()\n }\n\n setSelectorWidth = () => {\n this.selectorWidth = this._selector.current.getBoundingClientRect().width\n }\n\n setInnerElements = () => {\n this.innerElements = Array.prototype.slice.call(\n this._sliderFrame.current.children\n )\n }\n\n get totalSlides() {\n const { children } = this.props\n\n if (children) {\n const totalChildren = React.Children.count(children)\n return totalChildren + (this.shouldAddClones ? 2 * this.perPage : 0)\n }\n\n return 0\n }\n\n get childrenLength() {\n return this.props.children ? React.Children.count(this.props.children) : 0\n }\n\n prev = (howManySlides = 1, dragDistance = 0) => {\n const howManyInt = Number.parseInt(howManySlides)\n const { onChangeSlide, currentSlide, loop } = this.props\n let newCurrentSlide = Number.parseInt(currentSlide)\n let stateCurrentSlide\n let enableTransition = true\n\n if (this.totalSlides <= this.perPage) {\n return\n }\n\n if (loop) {\n if (this.isNegativeClone(currentSlide - howManyInt)) {\n newCurrentSlide = this.getPositiveClone(currentSlide)\n enableTransition = false\n stateCurrentSlide = newCurrentSlide - howManyInt\n } else {\n newCurrentSlide = currentSlide - howManyInt\n stateCurrentSlide = newCurrentSlide\n }\n } else {\n newCurrentSlide = Math.max(currentSlide - howManyInt, 0)\n stateCurrentSlide = newCurrentSlide\n }\n\n if (newCurrentSlide !== currentSlide) {\n this.setState({\n enableTransition,\n currentSlide: stateCurrentSlide,\n dragDistance,\n })\n onChangeSlide(newCurrentSlide)\n }\n }\n\n next = (howManySlides = 1, dragDistance = 0) => {\n const howManyInt = Number.parseInt(howManySlides)\n const { onChangeSlide, currentSlide, loop } = this.props\n let newCurrentSlide = Number.parseInt(currentSlide)\n let stateCurrentSlide\n let enableTransition = true\n\n if (this.totalSlides <= this.perPage) {\n return\n }\n\n if (loop) {\n if (this.isPositiveClone(currentSlide + howManyInt)) {\n newCurrentSlide = this.getNegativeClone(currentSlide)\n enableTransition = false\n stateCurrentSlide = newCurrentSlide + howManyInt\n } else {\n newCurrentSlide = currentSlide + howManyInt\n stateCurrentSlide = newCurrentSlide\n }\n } else {\n newCurrentSlide = Math.min(\n currentSlide + howManyInt,\n this.totalSlides - this.perPage\n )\n stateCurrentSlide = newCurrentSlide\n }\n\n if (newCurrentSlide !== currentSlide) {\n this.setState({\n enableTransition,\n currentSlide: stateCurrentSlide,\n dragDistance,\n })\n onChangeSlide(newCurrentSlide)\n }\n }\n\n prevPage = () => {\n this.prev(this.perPage)\n }\n\n nextPage = () => {\n this.next(this.perPage)\n }\n\n updateAfterDrag = () => {\n const { threshold } = this.props\n const movement = this.drag.endX - this.drag.startX\n const movementDistance = Math.abs(movement)\n const howManySlidesToSlide = Math.ceil(\n movementDistance / (this.selectorWidth / this.perPage)\n )\n const dragDistance = (movement / this._sliderFrameWidth) * 100\n if (\n movement > 0 &&\n movementDistance > threshold &&\n this.totalSlides > this.perPage\n ) {\n this.prev(howManySlidesToSlide, dragDistance)\n } else if (\n movement < 0 &&\n movementDistance > threshold &&\n this.totalSlides > this.perPage\n ) {\n this.next(howManySlidesToSlide, dragDistance)\n } else {\n const { easing, duration, currentSlide } = this.props\n\n this.setState({ enableTransition: true, dragDistance: 0 })\n setStyle(this._sliderFrame.current, {\n ...getStylingTransition(easing, duration),\n ...getTranslateProperty((currentSlide / this.totalSlides) * -100),\n })\n }\n }\n\n _clearDrag = () => {\n this.drag = {\n startX: 0,\n endX: 0,\n startY: 0,\n letItGo: null,\n }\n }\n\n onTouchStart = e => {\n this.pointerDown = true\n this.drag.startX = e.touches[0].pageX\n this.drag.startY = e.touches[0].pageY\n this.setState({ enableTransition: false })\n }\n\n onTouchEnd = () => {\n this.pointerDown = false\n if (this.drag.endX) {\n this.updateAfterDrag()\n }\n this._clearDrag()\n }\n\n onTouchMove = e => {\n if (this.drag.letItGo === null) {\n this.drag.letItGo =\n Math.abs(this.drag.startY - e.touches[0].pageY) <\n Math.abs(this.drag.startX - e.touches[0].pageX)\n }\n\n if (this.pointerDown && this.drag.letItGo) {\n const { currentSlide } = this.props\n\n this.drag.endX = e.touches[0].pageX\n\n const currentOffset = currentSlide * (this.selectorWidth / this.perPage)\n const dragOffset = this.drag.endX - this.drag.startX\n const offset =\n ((currentOffset - dragOffset) / this._sliderFrameWidth) * -100\n\n setStyle(this._sliderFrame.current, {\n ...getTranslateProperty(offset),\n })\n }\n }\n\n onMouseDown = e => {\n const { cursorOnMouseDown } = this.props\n e.preventDefault()\n this.pointerDown = true\n this.drag.startX = e.pageX\n\n setStyle(this._sliderFrame.current, {\n cursor: cursorOnMouseDown,\n })\n\n this.setState({ enableTransition: false })\n }\n\n onMouseUp = () => {\n const { cursor } = this.props\n\n this.pointerDown = false\n setStyle(this._sliderFrame.current, { cursor })\n if (this.drag.endX) {\n this.updateAfterDrag()\n }\n\n this._clearDrag()\n }\n\n onMouseMove = e => {\n const { currentSlide, draggable, cursorOnMouseDown } = this.props\n e.preventDefault()\n if (this.pointerDown && draggable) {\n // TODO prevent link clicks\n this.drag.endX = e.pageX\n\n const currentOffset = currentSlide * (this.selectorWidth / this.perPage)\n const dragOffset = this.drag.endX - this.drag.startX\n const offset =\n ((currentOffset - dragOffset) / this._sliderFrameWidth) * -100\n setStyle(this._sliderFrame.current, {\n cursor: cursorOnMouseDown,\n ...getTranslateProperty(offset),\n })\n }\n }\n\n onMouseLeave = e => {\n if (this.pointerDown) {\n const { cursor, draggable } = this.props\n this.pointerDown = false\n this.drag.endX = e.pageX\n\n if (draggable) {\n setStyle(this._sliderFrame.current, { cursor })\n }\n this.updateAfterDrag()\n this._clearDrag()\n }\n }\n\n getSlidesToSlide = () => {\n const { navigationStep, scrollByPage } = this.props\n\n if (typeof navigationStep === 'number') {\n return navigationStep\n }\n\n if (navigationStep === constants.NAVIGATION_PAGE || scrollByPage) {\n return this.perPage\n }\n\n return 1\n }\n\n renderArrows = () => {\n const {\n arrowsContainerComponent: ArrowsContainerComponent,\n arrowRender,\n } = this.props\n\n if (!arrowRender) {\n return null\n }\n\n const slidesToSlide = this.getSlidesToSlide()\n\n const arrows = (\n <Fragment>\n {arrowRender({\n orientation: 'left',\n onClick: () => this.prev(slidesToSlide),\n })}\n {arrowRender({\n orientation: 'right',\n onClick: () => this.next(slidesToSlide),\n })}\n </Fragment>\n )\n return ArrowsContainerComponent ? (\n <ArrowsContainerComponent>{arrows}</ArrowsContainerComponent>\n ) : (\n arrows\n )\n }\n\n renderChild = child => {\n return React.cloneElement(child, {\n style: {\n ...(child.props.style ? child.props.style : {}),\n width: this.isMultiPage\n ? `${100 / this.totalSlides}%`\n : `${100 / this.perPage}%`,\n },\n })\n }\n\n get isMultiPage() {\n return this.childrenLength > this.perPage\n }\n\n get shouldAddClones() {\n const { loop } = this.props\n const { firstRender } = this.state\n return !firstRender && loop && this.isMultiPage\n }\n\n render() {\n const {\n children,\n sliderFrameTag: SliderFrameTag,\n rootTag: RootTag,\n classes: classesProp,\n currentSlide,\n easing,\n duration,\n cursor,\n isMobile,\n minPerPage,\n } = this.props\n const { enableTransition, dragDistance, firstRender } = this.state\n const shouldCenterSlideOnMobile =\n minPerPage && !Number.isInteger(minPerPage)\n const CURRENT_SLIDE_CENTER_SHIFT =\n isMobile && shouldCenterSlideOnMobile ? 0.75 : 0\n\n const classes = {\n ...Slider.defaultProps.classes,\n ...classesProp,\n }\n\n const arrayChildren = React.Children.toArray(children)\n const sliderFrameWidth =\n this.perPage < this.childrenLength || firstRender\n ? (100 * this.totalSlides) / this.perPage\n : 100\n const sliderFrameStyle = {\n width: `${sliderFrameWidth}%`,\n ...(this.isMultiPage &&\n getTranslateProperty(\n ((currentSlide + CURRENT_SLIDE_CENTER_SHIFT) / this.totalSlides) *\n -100 +\n dragDistance\n )),\n ...getStylingTransition(easing, enableTransition ? duration : 0),\n ...(this.isMultiPage && { cursor }),\n }\n\n return (\n <Fragment>\n <div className={this.isMultiPage && !firstRender ? 'db' : 'dn'}>\n {this.renderArrows()}\n </div>\n <RootTag\n className={classnames(classes.root, 'overflow-hidden h-100')}\n ref={this._selector}\n {...(this.isMultiPage &&\n Slider.events.reduce(\n (props, event) => ({ ...props, [event]: this[event] }),\n {}\n ))}\n >\n <EventListener target=\"window\" onResize={this.handleResize} />\n <SliderFrameTag\n className={classnames(\n classes.sliderFrame,\n styles.sliderFrame,\n { 'justify-center': !this.isMultiPage },\n 'list pa0 h-100 ma0 flex'\n )}\n style={sliderFrameStyle}\n ref={this._sliderFrame}\n >\n {this.shouldAddClones &&\n React.Children.map(\n arrayChildren.slice(\n children.length - this.perPage,\n children.length\n ),\n this.renderChild\n )}\n {React.Children.map(arrayChildren, this.renderChild)}\n {this.shouldAddClones &&\n React.Children.map(\n arrayChildren.slice(0, this.perPage),\n this.renderChild\n )}\n </SliderFrameTag>\n </RootTag>\n </Fragment>\n )\n }\n}\n\nexport default withDevice(Slider)\n\n```"
}
] |
code_store-on-localhost_edc2d915
|
[
{
"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/Slider/__tests__/Slider.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport Slider from '../components/Slider.js'\nimport Slide from '../components/Slide.js'\n\ndescribe('<Slider /> component', () => {\n const renderComponent = customProps => {\n const props = {\n loop: true,\n arrowRender: ({ orientation }) => {\n return <div>arrow {orientation}</div>\n },\n onChangeSlide: () => {},\n ...customProps,\n }\n\n const comp = (\n <Slider {...props}>\n <Slide>\n <div>\n <p>Slide 1</p>\n </div>\n </Slide>\n <Slide>\n <div>\n <p>Slide 2</p>\n </div>\n </Slide>\n </Slider>\n )\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_5c7f2e50
|
[
{
"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/Slider/__tests__/SliderContainer.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport Slider from '../components/Slider.js'\nimport Slide from '../components/Slide.js'\nimport SliderContainer from '../components/SliderContainer.js'\n\ndescribe('<SliderContainer /> component', () => {\n const renderComponent = customProps => {\n const props = {\n ...customProps,\n }\n\n const comp = (\n <SliderContainer {...props}>\n <Slider onChangeSlide={() => {}}>\n <Slide>\n <div>\n <p>Slide 1</p>\n </div>\n </Slide>\n <Slide>\n <div>\n <p>Slide 2</p>\n </div>\n </Slide>\n </Slider>\n </SliderContainer>\n )\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with another tag', () => {\n const { asFragment } = renderComponent({ tag: 'span' })\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should generate with tag', () => {\n const { container } = renderComponent({ tag: 'span' })\n expect(container.querySelector('span')).toBeTruthy()\n })\n})\n\n```"
}
] |
code_store-on-localhost_817fe268
|
[
{
"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/Slider/__tests__/Dots.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, fireEvent } from '@vtex/test-tools/react'\n\nimport Dots from '../components/Dots.js'\n\ndescribe('<Dots /> component', () => {\n const renderComponent = customProps => {\n const props = {\n totalSlides: 10,\n onChangeSlide: () => {},\n ...customProps,\n }\n\n const comp = <Dots {...props} />\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should be active when clicked', () => {\n const { container } = renderComponent({\n classes: { dot: 'dot', activeDot: 'active', notActiveDot: 'inactive' },\n })\n\n const dot = container.querySelector('.dot')\n fireEvent.click(dot)\n\n expect(container.querySelector('.inactive')).toBeTruthy()\n })\n})\n\n```"
}
] |
code_store-on-localhost_e69bdc3f
|
[
{
"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/Slider/__tests__/Utils.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { JSDOM } from 'jsdom'\n\nimport resolveSlidesNumber from '../utils/resolveSlidesNumber'\nimport { setStyle, getTranslateProperty, getStylingTransition } from '../utils'\n\ndescribe('Util functions', () => {\n beforeEach(() => {\n const dom = new JSDOM(\n '<!DOCTYPE html><html><head></head><body></body></html>'\n )\n\n global.window = dom.window\n global.document = dom.window.document\n\n const resizeEvent = document.createEvent('Event')\n resizeEvent.initEvent('resize', true, true)\n\n global.window.resizeTo = (width, height) => {\n global.window.innerWidth = width || global.window.innerWidth\n global.window.innerHeight = height || global.window.innerHeight\n global.window.dispatchEvent(resizeEvent)\n }\n })\n\n it('should resolve slides number correctly', () => {\n expect(resolveSlidesNumber(5)).toEqual(5)\n\n window.resizeTo(400, 1000)\n expect(resolveSlidesNumber(1, { 400: 2, 1000: 3 })).toEqual(2)\n\n window.resizeTo(1000, 1000)\n expect(resolveSlidesNumber(1, { 400: 2, 1000: 3 })).toEqual(3)\n\n // Testing for minimum values\n window.resizeTo(320, 1000)\n expect(resolveSlidesNumber(2, { 320: 1, 500: 2, 750: 3 })).toEqual(2)\n })\n\n it('should set style correctly', () => {\n const target = {\n style: {},\n }\n const styles = {\n backgroundColor: 'pink',\n color: 'black',\n }\n setStyle(target, styles)\n expect(target.style).toEqual(styles)\n })\n\n it('should get translate property correctly', () => {\n expect(getTranslateProperty(0, 5, -70)).toEqual({\n transform: 'translate3d(0, 5%, -70%)',\n WebkitTransform: 'translate3d(0, 5%, -70%)',\n })\n })\n\n it('should get styling transition correctly', () => {\n expect(\n getStylingTransition('cubic-bezier(0.215, 0.61, 0.355, 1)', 500)\n ).toEqual({\n WebkitTransition: 'all 500ms cubic-bezier(0.215, 0.61, 0.355, 1)',\n transition: 'all 500ms cubic-bezier(0.215, 0.61, 0.355, 1)',\n })\n })\n})\n\n```"
}
] |
code_store-on-localhost_38235187
|
[
{
"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/Slider/__tests__/Slide.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport Slide from '../components/Slide.js'\n\ndescribe('<Slide /> component', () => {\n const renderComponent = customProps => {\n const props = {\n ...customProps,\n }\n\n const comp = (\n <Slide {...props}>\n <div>\n <p>Testing</p>\n </div>\n </Slide>\n )\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should generate with the correct tag', () => {\n const { container, rerender } = renderComponent({ tag: 'span' })\n expect(container.querySelector('span')).toBeTruthy()\n\n rerender(<Slide tag=\"main\" />)\n expect(container.querySelector('main')).toBeTruthy()\n\n rerender(<Slide tag=\"section\" />)\n expect(container.querySelector('section')).toBeTruthy()\n })\n\n it('should math snapshot with tag', () => {\n const { asFragment } = renderComponent({ tag: 'span' })\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_8ce083db
|
[
{
"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/Carousel/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n export const useCssHandles: any\n}\n\n```"
}
] |
code_store-on-localhost_5c1568d0
|
[
{
"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/Carousel/typings/vtex.store-components.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-components' {\n export const Container\n export const Slider\n}\n```"
}
] |
code_store-on-localhost_679401ab
|
[
{
"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/Carousel/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ReactElement } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RuntimeProps {\n navigate: (options: NavigationOptions) => void\n hints: {\n mobile: boolean,\n desktop: boolean\n }\n }\n\n export interface RenderContextProps {\n runtime: RuntimeProps\n }\n\n export interface LinkProps {\n onClick?: (event: any) => void\n params?: object | null\n page?: string\n className?: string\n to?: string\n }\n\n export const ExtensionPoint: ReactElement\n export const Helmet: ReactElement\n export const Link: React.FunctionComponent<LinkProps>\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const useRuntime: () => RuntimeProps\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n \n export const withSession: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n \n export const buildCacheLocator = (app: string, type: string, cacheId: string) => string\n\n interface RenderComponent<P = {}, S = {}> extends Component<P, S> {\n getCustomMessages?: (locale: string) => any\n schema: ComponentSchema\n getSchema?: (a: any, b: any?) => ComponentSchema\n uiSchema: UISchema\n }\n\n export interface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n }\n\n export interface Window extends Window {\n __RENDER_7_COMPONENTS__: ComponentsRegistry\n }\n\n let global: Window\n}\n\n```"
}
] |
code_store-on-localhost_097c1ba7
|
[
{
"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/Carousel/typings/vtex.store-icons.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-icons' {\n export const IconCaret: ReactElement\n}\n\n```"
}
] |
code_store-on-localhost_60e6fc96
|
[
{
"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/Carousel/typings/styles.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```"
}
] |
code_store-on-localhost_c26a27d2
|
[
{
"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/Carousel/typings/vtex.slider.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.slider' {\n export const Slider: ReactElement\n export const Slide: ReactElement\n export const SliderContainer: ReactElement\n export const Dots: ReactElement\n}\n\n```"
}
] |
code_store-on-localhost_effb4bf0
|
[
{
"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/Carousel/__tests__/Carousel.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-env jest */\nimport React from 'react'\nimport { range, map, forEach, pluck } from 'ramda'\nimport { render } from '@vtex/test-tools/react'\n\nimport Carousel from '../Carousel'\n\ndescribe('Carousel component', () => {\n const renderComponent = customProps => {\n const props = {\n height: 440,\n mobileHeight: 339,\n showArrows: true,\n showDots: true,\n autoplay: true,\n autoplaySpeed: 4,\n numberOfBanners: 3,\n banners: [\n {\n image:\n 'https://raw.githubusercontent.com/vtex-apps/carousel/master/images/banners-01.png',\n externalRoute: true,\n description: 'banner1',\n url: 'banner1-url',\n },\n {\n image:\n 'https://raw.githubusercontent.com/vtex-apps/carousel/master/images/banners-02.png',\n externalRoute: true,\n description: 'banner2',\n url: 'banner2-url',\n },\n {\n image:\n 'https://raw.githubusercontent.com/vtex-apps/carousel/master/images/banners-03.png',\n externalRoute: true,\n description: 'banner3',\n url: 'banner3-url',\n },\n ],\n ...customProps,\n }\n\n return render(<Carousel {...props} />)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toBeDefined()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render items', () => {\n const banner = id => ({\n image: `image${id}`,\n externalRoute: true,\n description: `description${id}`,\n url: `url${id}`,\n })\n const banners = map(banner, range(0, 10))\n\n const { container, getByAltText } = renderComponent({\n numberOfBanners: banners.length,\n banners,\n })\n\n const itensContainer = container.querySelectorAll('.slider-container-mock')\n expect(itensContainer.length).toBe(1)\n\n const items = container.querySelectorAll('.slide-mock')\n expect(items.length).toBe(banners.length)\n\n // The URLs rendered should be the ones in the banners\n const urls = [...container.querySelectorAll('a')].map(a =>\n a.getAttribute('href')\n )\n expect(urls).toEqual(pluck('url', banners))\n\n // The Images URLs rendered should be the ones in the banners\n const images = [...container.querySelectorAll('img')].map(img =>\n img.getAttribute('src')\n )\n expect(images).toEqual(pluck('image', banners))\n\n // The alts rendered should be the ones in the banners\n const descriptions = pluck('description', banners)\n forEach(description => {\n getByAltText(description)\n }, descriptions)\n })\n})\n\n```"
}
] |
code_store-on-localhost_941b4f85
|
[
{
"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/VtexId/service-components/SetPasswordAfterLogin.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 Context from '../context'\nimport { Services, Validations, Constants } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\n\nexport default class SetPasswordAfterLogin extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n disableSetPreference: PropTypes.bool,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n disableSetPreference: false,\n }\n\n state = {\n loading: false,\n error: null,\n }\n\n setPassword = ({\n account,\n scope,\n password,\n setGlobalLoading,\n parentAppId,\n }) => {\n const { onSuccess, onFailure, disableSetPreference } = this.props\n return Services.setPasswordAfterLogin({\n accountName: account,\n scope,\n password,\n setPreference: !disableSetPreference,\n parentAppId,\n })\n .then(({ authStatus } = { authStatus: 'UnexpectedError' }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n this.setState({ loading: false, error }, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { email, password, scope, account },\n handlers: { setGlobalLoading },\n parentAppId,\n }) =>\n this.props.children({\n state: { email, password },\n loading: this.state.loading,\n action: () => {\n this.setState({ loading: true })\n setGlobalLoading(true)\n return this.setPassword({\n account,\n scope,\n password,\n setGlobalLoading,\n parentAppId,\n })\n },\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_02ef788f
|
[
{
"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/VtexId/service-components/OAuthPopup.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useState, useContext, useCallback } from 'react'\nimport PropTypes from 'prop-types'\nimport { Services } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\n\nfunction openWindow(url, title) {\n const newWindow = window.open(\n url,\n title,\n 'toolbar=no, location=no, directories=no, status=no, copyhistory=no, menubar=no,width=800,height=600,scrollbars=yes'\n )\n if (window.focus) newWindow.focus()\n return newWindow\n}\n\nconst OAuthPopup = ({\n children,\n provider,\n onSuccess = () => {},\n onFailure = () => {},\n autorun = false,\n useNewSession = false,\n}) => {\n const [loading, setLoading] = useState(false)\n const {\n state: { account, returnUrl, scope, email, fingerprint },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const onDone = useCallback(() => {\n setLoading(false)\n setGlobalLoading(false)\n }, [setGlobalLoading])\n\n const openPopup = useCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n\n const getOAuthRedirectUrl = useNewSession\n ? Services.withSession({\n accountName: account,\n returnUrl,\n scope,\n user: email,\n fingerprint,\n parentAppId,\n useOAuthPopup: true,\n })(() => Services.getOAuthRedirectUrl({ provider }))\n : Services.getOAuthRedirectUrl({ provider })\n\n const popup = openWindow('', provider)\n popup.opener = null\n getOAuthRedirectUrl\n .then(({ url }) => {\n popup.location.assign(url)\n\n const id = setInterval(() => {\n if (!popup || popup.closed) {\n onFailure(getError({ message: 'OAuth popup window closed' }))\n onDone()\n clearInterval(id)\n return\n }\n try {\n if (popup.location.href.indexOf(window.location.host) !== -1) {\n const qs = new URLSearchParams(popup.location.search)\n const authStatus = qs.get('authStatus')\n if (authStatus === 'Success') {\n popup.close()\n onDone()\n onSuccess()\n }\n clearInterval(id)\n }\n // eslint-disable-next-line\n } catch {}\n }, 500)\n })\n .catch(error => {\n popup.close()\n onFailure(getError(error))\n onDone()\n })\n }, [\n account,\n email,\n fingerprint,\n onDone,\n onFailure,\n onSuccess,\n parentAppId,\n provider,\n returnUrl,\n scope,\n setGlobalLoading,\n useNewSession,\n ])\n\n useEffect(() => {\n autorun && openPopup()\n }, [autorun, openPopup])\n\n return children({\n loading,\n action: openPopup,\n })\n}\n\nOAuthPopup.proptypes = {\n children: PropTypes.func.isRequired,\n provider: PropTypes.string.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n autorun: PropTypes.bool,\n useNewSession: PropTypes.bool,\n}\n\nexport default OAuthPopup\n\n```"
}
] |
code_store-on-localhost_0cef7c45
|
[
{
"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/VtexId/service-components/RegisterMfaPhone.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 { Services, Validations, Constants } from '../utils'\nimport Context from '../context'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\n\nexport default class RegisterMfaPhone extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n useNewSession: PropTypes.bool,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n useNewSession: false,\n }\n\n state = {\n loading: false,\n error: null,\n }\n\n registerMfaPhoneNumber = ({\n phoneNumber,\n recaptcha,\n setGlobalLoading,\n parentAppId,\n }) => {\n const { useNewSession, onSuccess, onFailure } = this.props\n return (useNewSession\n ? Services.withMfaSession(\n () =>\n Services.registerMfaPhoneNumber({\n phoneNumber,\n recaptcha,\n parentAppId,\n }),\n { parentAppId }\n )\n : Services.registerMfaPhoneNumber({\n phoneNumber,\n recaptcha,\n parentAppId,\n })\n )\n .then(({ authStatus }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Pending) {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n console.log(error)\n this.setState({ loading: false, error }, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { phoneNumber },\n handlers: { setGlobalLoading },\n parentAppId,\n }) =>\n this.props.children({\n state: { phoneNumber },\n loading: this.state.loading,\n action: () => {\n this.setState({ loading: true }, () =>\n setGlobalLoading(true, () =>\n this.registerMfaPhoneNumber({\n phoneNumber,\n recaptcha: null,\n setGlobalLoading,\n parentAppId,\n })\n )\n )\n },\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_e8c0e357
|
[
{
"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/VtexId/service-components/LoginWithPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, createRef } from 'react'\nimport PropTypes from 'prop-types'\n\nimport { Services, Validations, Constants, NOOP } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\n\nclass LoginWithPassword extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n onRequiresSmsMfa: PropTypes.func,\n onRequiresAppMfa: PropTypes.func,\n onRequiresPasswordUpdate: PropTypes.func,\n onRequiresMfaRegistration: PropTypes.func,\n useNewSession: PropTypes.bool,\n saveUserAccount: PropTypes.bool,\n state: PropTypes.object.isRequired,\n handlers: PropTypes.object.isRequired,\n parentAppId: PropTypes.string,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n onRequiresSmsMfa: () => {},\n onRequiresAppMfa: () => {},\n onRequiresPasswordUpdate: () => {},\n onRequiresMfaRegistration: () => {},\n useNewSession: false,\n }\n\n state = {\n loading: false,\n }\n\n actionRef = createRef(NOOP)\n\n validatePassword = ({\n email,\n password,\n userAccounts,\n recaptcha,\n fingerprint,\n handlers: {\n setGlobalLoading,\n setMfaPhone,\n withSession,\n handleUserAccountsChange,\n handleCurrentPasswordChange,\n handlePasswordChange,\n },\n }) => {\n const {\n useNewSession,\n onSuccess,\n onRequiresSmsMfa,\n onRequiresAppMfa,\n onRequiresMfaRegistration,\n onRequiresPasswordUpdate,\n onFailure,\n saveUserAccount,\n parentAppId,\n } = this.props\n this.setState({ loading: true })\n setGlobalLoading(true)\n return (useNewSession\n ? withSession(() =>\n Services.validatePassword({\n login: email,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n })\n )\n : Services.validatePassword({\n login: email,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n })\n )\n .then(({ authStatus, phoneNumber }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n if (saveUserAccount && !userAccounts.includes(email)) {\n handleUserAccountsChange([...userAccounts, email])\n }\n return setGlobalLoading(false, onSuccess)\n } else if (authStatus === API_AUTH_STATUS.RequiresMFAAuthenticator) {\n return setGlobalLoading(false, onRequiresAppMfa)\n } else if (authStatus === API_AUTH_STATUS.RequiresPhoneRegistration) {\n return setGlobalLoading(false, onRequiresMfaRegistration)\n } else if (authStatus === API_AUTH_STATUS.RequiresMFA) {\n return setMfaPhone(phoneNumber, onRequiresSmsMfa)\n } else if (authStatus === API_AUTH_STATUS.ExpiredPassword) {\n return setGlobalLoading(false, () => {\n handleCurrentPasswordChange(password)\n handlePasswordChange('')\n onRequiresPasswordUpdate()\n })\n }\n\n return setGlobalLoading(false, () =>\n onFailure(getError({ authStatus }))\n )\n })\n })\n .catch(({ response }) => {\n const error = response && response.data\n\n this.setState({ loading: false }, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n }\n\n componentDidUpdate() {\n const {\n email,\n password,\n userAccounts,\n recaptcha,\n fingerprint,\n } = this.props.state\n this.actionRef.current = () => {\n this.props.handlers.handleRecaptchaChange('')\n return this.validatePassword({\n email,\n password,\n userAccounts,\n recaptcha,\n fingerprint,\n handlers: this.props.handlers,\n })\n }\n }\n\n render() {\n const { email, password } = this.props.state\n return this.props.children({\n state: { email, password },\n loading: this.state.loading,\n action: () => this.actionRef.current(),\n validation: Validations,\n })\n }\n}\n\nconst Wrapper = props => (\n <Context.Consumer>\n {({ state, handlers, parentAppId }) => (\n <LoginWithPassword\n {...props}\n state={state}\n handlers={handlers}\n parentAppId={parentAppId}\n />\n )}\n </Context.Consumer>\n)\n\nexport default Wrapper\n\n```"
}
] |
code_store-on-localhost_10ed3e99
|
[
{
"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/VtexId/service-components/OAuthRedirect.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 { useEffect, useState, useContext, useCallback } from 'react'\nimport PropTypes from 'prop-types'\nimport { Services } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\n\nconst OAuthRedirect = ({\n children,\n provider,\n onSuccess = () => {},\n onFailure = () => {},\n autorun = false,\n useNewSession = false,\n}) => {\n const [loading, setLoading] = useState(false)\n const {\n handlers: { setGlobalLoading, withSession },\n } = useContext(Context)\n\n const startSessionAndRedirect = useCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n\n const onDone = () => {\n setLoading(false)\n setGlobalLoading(false)\n }\n\n const start = useNewSession\n ? withSession(() => Services.redirectOAuth({ provider }))\n : Services.redirectOAuth({ provider })\n\n start\n .then(() => {\n onSuccess()\n onDone()\n })\n .catch(error => {\n onFailure(getError(error))\n onDone()\n })\n })\n\n useEffect(() => {\n autorun && startSessionAndRedirect()\n }, [autorun])\n\n return children({\n loading,\n action: startSessionAndRedirect,\n })\n}\n\nOAuthRedirect.proptypes = {\n children: PropTypes.func.isRequired,\n provider: PropTypes.string.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n autorun: PropTypes.bool,\n useNewSession: PropTypes.bool,\n}\n\nexport default OAuthRedirect\n\n```"
}
] |
code_store-on-localhost_f7523629
|
[
{
"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/VtexId/service-components/Logout.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 { Services } from '../utils'\nimport Context from '../context'\n\nexport default class Logout extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n }\n\n static defaultProps = {\n redirect: false,\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n state = {\n loading: false,\n }\n\n logout = ({ setGlobalLoading, parentAppId }) => {\n const { onSuccess, onFailure } = this.props\n return Services.logout({ parentAppId })\n .then(() => {\n this.setState({ loading: false }, () => {\n return setGlobalLoading(false, onSuccess)\n })\n })\n .catch(error => {\n this.setState({ loading: false }, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({ handlers: { setGlobalLoading }, parentAppId }) =>\n this.props.children({\n loading: this.state.loading,\n action: () =>\n this.setState({ loading: true }, () =>\n setGlobalLoading(true, () =>\n this.logout({ setGlobalLoading, parentAppId })\n )\n ),\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_c0899fa6
|
[
{
"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/VtexId/service-components/StartLoginSession.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 { Services, Validations } from '../utils'\nimport Context from '../context'\n\nexport default class StartLoginSession extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n state = {\n loading: false,\n }\n\n startSession = ({\n accountName,\n returnUrl,\n scope,\n user,\n setGlobalLoading,\n parentAppId,\n }) => {\n const { onSuccess, onFailure } = this.props\n return Services.startSession({\n accountName,\n returnUrl,\n scope,\n user,\n parentAppId,\n })\n .then(() => {\n this.setState({ loading: false }, () => {\n return setGlobalLoading(false, onSuccess)\n })\n })\n .catch(error => {\n console.log(error)\n this.setState({ loading: false, error }, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { account, returnUrl, scope, email },\n handlers: { setGlobalLoading },\n parentAppId,\n }) =>\n this.props.children({\n state: { email },\n loading: this.state.loading,\n action: () =>\n this.setState({ loading: true }, () =>\n setGlobalLoading(true, () =>\n this.startSession({\n accountName: account,\n returnUrl,\n scope,\n user: email,\n setGlobalLoading,\n parentAppId,\n })\n )\n ),\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_2e27c893
|
[
{
"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/VtexId/service-components/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport { default as GetIdentityProviders } from './GetIdentityProviders'\nexport { default as GetLoginPreference } from './GetLoginPreference'\nexport { default as LoginWithAccessKey } from './LoginWithAccessKey'\nexport { default as LoginWithPassword } from './LoginWithPassword'\nexport { default as Logout } from './Logout'\nexport { default as OAuthPopup } from './OAuthPopup'\nexport { default as OAuthRedirect } from './OAuthRedirect'\nexport { default as RedirectAfterLogin } from './RedirectAfterLogin'\nexport { default as RedirectLogout } from './RedirectLogout'\nexport { default as RegisterMfaAuthenticator } from './RegisterMfaAuthenticator'\nexport { default as RegisterMfaPhone } from './RegisterMfaPhone'\nexport { default as ResendMfaToken } from './ResendMfaToken'\nexport { default as SendAccessKey } from './SendAccessKey'\nexport { default as SetPassword } from './SetPassword'\nexport { default as SetPasswordAfterLogin } from './SetPasswordAfterLogin'\nexport { default as StartLoginSession } from './StartLoginSession'\nexport { default as ValidateMfa } from './ValidateMfa'\n\n```"
}
] |
code_store-on-localhost_60d8bc7d
|
[
{
"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/VtexId/service-components/SendAccessKey.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 { Services, Validations } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\n// import ReCAPTCHA from './ReCAPTCHA'\n\nexport default class SendAccessKey extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n useNewSession: PropTypes.bool,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n useNewSession: false,\n }\n\n state = {\n loading: false,\n }\n\n sendToken = async ({\n user,\n locale,\n recaptcha,\n setGlobalLoading,\n withSession,\n parentAppId,\n }) => {\n const { useNewSession, onSuccess, onFailure } = this.props\n this.setState({ loading: true })\n setGlobalLoading(true)\n return (useNewSession\n ? withSession(() =>\n Services.sendVerificationCode({\n email: user.email,\n locale,\n recaptcha,\n parentAppId,\n })\n )\n : Services.sendVerificationCode({\n email: user.email,\n locale,\n recaptcha,\n parentAppId,\n })\n )\n .then(() => {\n this.setState({ loading: false }, () => {\n return setGlobalLoading(false, () => onSuccess(user))\n })\n })\n .catch(error => {\n this.setState({ loading: false }, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: globalState,\n handlers: { setGlobalLoading, withSession },\n parentAppId,\n }) =>\n this.props.children({\n state: {\n email: globalState.email,\n token: globalState.token,\n recaptcha: globalState.recaptcha,\n },\n loading: this.state.loading,\n action: ({ email, preference, recaptcha } = {}) =>\n this.sendToken({\n user: {\n email: email || globalState.email,\n ...(preference && { preference }),\n },\n locale: globalState.locale,\n recaptcha: recaptcha || globalState.recaptcha,\n setGlobalLoading,\n withSession,\n parentAppId,\n }),\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_df5dbd4d
|
[
{
"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/VtexId/service-components/LoginWithAccessKey.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 Context from '../context'\nimport { Services, Validations, Constants } from '../utils'\nimport getError from '../utils/getError'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\n// import ReCAPTCHA from './ReCAPTCHA'\n\nexport default class LoginWithAccessKey extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n saveUserAccount: PropTypes.bool,\n disableSetPreference: PropTypes.bool,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n disableSetPreference: false,\n }\n\n state = {\n loading: false,\n }\n\n verifyToken = ({\n email,\n token,\n userAccounts,\n recaptcha,\n handlers: { setGlobalLoading, handleUserAccountsChange },\n parentAppId,\n }) => {\n const {\n onSuccess,\n onFailure,\n saveUserAccount,\n disableSetPreference,\n } = this.props\n return Services.validateToken({\n login: email,\n accesskey: token,\n recaptcha,\n setPreference: !disableSetPreference,\n parentAppId,\n })\n .then(({ authStatus }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n if (saveUserAccount && !userAccounts.includes(email)) {\n handleUserAccountsChange([...userAccounts, email])\n }\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () =>\n onFailure(getError({ authStatus }))\n )\n })\n })\n .catch(errorCode => {\n this.setState({ loading: false }, () => {\n setGlobalLoading(false, () => onFailure(getError(errorCode)))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { email, token, userAccounts, recaptcha },\n handlers,\n parentAppId,\n }) =>\n this.props.children({\n state: { email, token },\n loading: this.state.loading,\n action: () =>\n this.setState({ loading: true }, () =>\n handlers.setGlobalLoading(true, () => {\n return this.verifyToken({\n email,\n token,\n userAccounts,\n recaptcha,\n handlers,\n parentAppId,\n })\n })\n ),\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_1b62f5b7
|
[
{
"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/VtexId/service-components/SetPassword.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 { Services, Validations, Constants } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\n\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nexport default class SetPassword extends Component {\n static propTypes = {\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n children: PropTypes.func.isRequired,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n state = {\n loading: false,\n error: null,\n }\n\n setPassword = ({\n email,\n password,\n currentPassword,\n token,\n recaptcha,\n setGlobalLoading,\n parentAppId,\n }) => {\n const { onSuccess, onFailure } = this.props\n return Services.setPassword({\n login: email,\n newPassword: password,\n currentPassword,\n accesskey: token,\n recaptcha,\n parentAppId,\n })\n .then(({ authStatus } = { authStatus: 'UnexpectedError' }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n this.setState({ loading: false, error }, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { email, password, currentPassword, token },\n handlers: { setGlobalLoading },\n parentAppId,\n }) =>\n this.props.children({\n state: { email, password, currentPassword, token },\n loading: this.state.loading,\n action: () => {\n this.setState({ loading: true })\n setGlobalLoading(true)\n return this.setPassword({\n email,\n password,\n currentPassword,\n token,\n recaptcha: null,\n setGlobalLoading,\n parentAppId,\n })\n },\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_d5130d59
|
[
{
"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/VtexId/service-components/ValidateMfa.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 { Services, Validations, Constants } from '../utils'\nimport getError from '../utils/getError'\nimport Context from '../context'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\n\nclass ValidateMfa extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n setGlobalLoading: PropTypes.func.isRequired,\n handleTokenChange: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n token: PropTypes.string,\n parentAppId: PropTypes.string,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n state = {\n loading: false,\n error: null,\n }\n\n componentWillUnmount() {\n this.props.handleTokenChange('')\n }\n\n validateMfa = () => {\n const {\n token,\n onSuccess,\n onFailure,\n setGlobalLoading,\n parentAppId,\n } = this.props\n return Services.validateMfa({ mfaToken: token, parentAppId })\n .then(({ authStatus }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure(getError({ authStatus })))\n })\n })\n .catch(errorCode => {\n this.setState({ loading: false }, () => {\n setGlobalLoading(false, () => onFailure(getError(errorCode)))\n })\n })\n }\n\n render() {\n const { token, children, setGlobalLoading } = this.props\n return children({\n state: { token },\n loading: this.state.loading,\n validation: Validations,\n action: () =>\n this.setState({ loading: true }, () =>\n setGlobalLoading(true, () => this.validateMfa())\n ),\n })\n }\n}\n\nconst Wrapper = props => (\n <Context.Consumer>\n {({\n state: { token },\n handlers: { setGlobalLoading, handleTokenChange },\n parentAppId,\n }) => (\n <ValidateMfa\n {...props}\n token={token}\n setGlobalLoading={setGlobalLoading}\n handleTokenChange={handleTokenChange}\n parentAppId={parentAppId}\n />\n )}\n </Context.Consumer>\n)\n\nexport default Wrapper\n\n```"
}
] |
code_store-on-localhost_90066745
|
[
{
"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/VtexId/service-components/ResendMfaToken.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 { Services, Validations } from '../utils'\nimport Context from '../context'\n\nexport default class ResendMfaToken extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n }\n\n static defaultProps = {\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n state = {\n loading: false,\n error: null,\n }\n\n resendMfaToken = ({ recaptcha, setGlobalLoading, parentAppId }) => {\n const { onSuccess, onFailure } = this.props\n return Services.resendMfa({ recaptcha, parentAppId })\n .then(({ authStatus }) => {\n this.setState({ loading: false }, () => {\n if (authStatus === 'Pending') {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n console.log(error)\n this.setState({ loading: false, error }, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }\n\n render() {\n return (\n <Context.Consumer>\n {({\n state: { phoneNumber },\n handlers: { setGlobalLoading },\n parentAppId,\n }) =>\n this.props.children({\n state: { phoneNumber },\n ...this.state,\n action: () =>\n this.setState({ loading: true }, () =>\n setGlobalLoading(true, () =>\n this.resendMfaToken({\n recaptcha: null,\n setGlobalLoading,\n parentAppId,\n })\n )\n ),\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_0dac1c5e
|
[
{
"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/VtexId/service-components/RedirectLogout.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport { Services } from '../utils'\n\nconst RedirectLogout = ({ children, returnUrl }) =>\n children({ action: () => Services.redirectLogout({ returnUrl }) })\n\nRedirectLogout.propTypes = {\n children: PropTypes.func.isRequired,\n returnUrl: PropTypes.string,\n}\n\nexport default RedirectLogout\n\n```"
}
] |
code_store-on-localhost_53564b6f
|
[
{
"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/VtexId/service-components/RegisterMfaAuthenticator.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\nimport { Services, Validations, Constants } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\n\nclass RegisterMfaAuthenticator extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n setGlobalLoading: PropTypes.func.isRequired,\n skip: PropTypes.bool,\n useNewSession: PropTypes.bool,\n parentAppId: PropTypes.string,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n }\n\n static defaultProps = {\n skip: false,\n useNewSession: false,\n onSuccess: () => {},\n onFailure: () => {},\n }\n\n static defaultState = {\n loading: false,\n error: null,\n data: null,\n }\n\n state = RegisterMfaAuthenticator.defaultState\n\n startAuthenticatorRegistration = () => {\n const {\n useNewSession,\n setGlobalLoading,\n onSuccess,\n onFailure,\n parentAppId,\n } = this.props\n this.setState({ loading: true })\n setGlobalLoading(true)\n\n const onDone = () => {\n setGlobalLoading(false)\n this.setState({ loading: false })\n }\n\n return (useNewSession\n ? Services.withMfaSession(\n () => Services.registerMfaAuthenticator({ parentAppId }),\n {\n parentAppId,\n }\n )\n : Services.registerMfaAuthenticator({ parentAppId })\n )\n .then(data => {\n const { authStatus } = data\n\n if (authStatus !== Constants.ApiAuthStatus.Pending) {\n this.setState({ error: getError(authStatus) })\n onDone()\n return\n }\n\n this.setState({\n ...RegisterMfaAuthenticator.defaultState,\n data,\n error: null,\n })\n\n onSuccess(data)\n onDone()\n })\n .catch(error => {\n this.setState({ ...RegisterMfaAuthenticator.defaultState, error })\n onFailure(getError(error))\n onDone()\n })\n }\n\n componentDidMount() {\n if (!this.props.skip) {\n this.startAuthenticatorRegistration()\n }\n }\n\n render() {\n const { loading, error, data } = this.state\n const { children } = this.props\n return children({\n value: data,\n loading,\n error,\n validation: Validations,\n action: this.startAuthenticatorRegistration,\n })\n }\n}\n\nconst Wrapper = props => (\n <Context.Consumer>\n {({ handlers: { setGlobalLoading }, parentAppId }) => (\n <RegisterMfaAuthenticator\n {...props}\n setGlobalLoading={setGlobalLoading}\n parentAppId={parentAppId}\n />\n )}\n </Context.Consumer>\n)\n\nexport default Wrapper\n\n```"
}
] |
code_store-on-localhost_98789c1e
|
[
{
"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/VtexId/service-components/GetLoginPreference.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 { useState, useEffect, useContext } from 'react'\nimport PropTypes from 'prop-types'\nimport { useRuntime } from '../../../../../vtex.render-runtime'\n\nimport Context from '../context'\nimport { Services } from '../utils'\nimport getError from '../utils/getError'\n\nconst noop = () => {}\n\nconst preferenceByKey = {\n NoPreference: 'NO_PREFERENCE',\n Password: 'PASSWORD',\n AccessKey: 'TOKEN',\n}\n\nconst GetLoginPreference = ({\n children,\n onSuccess = noop,\n onFailure = noop,\n}) => {\n const [loading, setLoading] = useState(true)\n const [loginPreference, setLoginPreference] = useState()\n const [error, setError] = useState()\n const { account } = useRuntime()\n const {\n state: { email, scope },\n parentAppId,\n } = useContext(Context)\n\n const fetchLoginPreference = (givenEmail = email) => {\n Services.getLoginPreference({\n accountName: account,\n scopeName: scope,\n email: givenEmail,\n parentAppId,\n })\n .then(data => {\n setLoginPreference(preferenceByKey[data])\n })\n .then(setLoginPreference, error => {\n setError(error)\n onFailure(getError(error))\n })\n }\n\n useEffect(() => {\n if (loginPreference) {\n setLoading(false)\n onSuccess(loginPreference)\n }\n }, [loginPreference])\n\n return children({\n loading,\n error,\n value: loginPreference,\n action: fetchLoginPreference,\n })\n}\n\nGetLoginPreference.propTypes = {\n children: PropTypes.func.isRequired,\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n}\n\nexport default GetLoginPreference\n\n```"
}
] |
code_store-on-localhost_0407e951
|
[
{
"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/VtexId/service-components/GetIdentityProviders.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 { useState, useEffect, useContext } from 'react'\nimport PropTypes from 'prop-types'\nimport { useRuntime } from '../../../../../vtex.render-runtime'\n\nimport { Services } from '../utils'\nimport getError from '../utils/getError'\nimport Context from '../context'\n\nconst noop = () => {}\n\nconst GetIdentityProviders = ({\n children,\n scope = 'STORE',\n onSuccess = noop,\n onFailure = noop,\n skip = false,\n}) => {\n const [loading, setLoading] = useState(!skip)\n const [providers, setProviders] = useState()\n const [error, setError] = useState()\n const { account } = useRuntime()\n const { parentAppId } = useContext(Context)\n\n const fetchIdentityProviders = () => {\n Services.getIdentityProviders({\n accountName: account,\n scopeName: scope,\n parentAppId,\n }).then(\n ({\n oAuthProviders,\n samlProviders,\n passwordAuthentication: password,\n accessKeyAuthentication: accessKey,\n }) => {\n setProviders({\n oAuthProviders,\n samlProviders,\n password,\n accessKey,\n })\n },\n error => {\n setError(error)\n onFailure(getError(error))\n }\n )\n }\n\n useEffect(() => {\n !skip && fetchIdentityProviders()\n }, [skip])\n\n useEffect(() => {\n if (providers) {\n setLoading(false)\n onSuccess()\n }\n }, [providers])\n\n return children({\n loading,\n error,\n value: providers,\n action: fetchIdentityProviders,\n })\n}\n\nGetIdentityProviders.propTypes = {\n children: PropTypes.func.isRequired,\n scope: PropTypes.oneOf(['ADMIN', 'STORE']),\n onSuccess: PropTypes.func,\n onFailure: PropTypes.func,\n skip: PropTypes.bool,\n}\n\nexport default GetIdentityProviders\n\n```"
}
] |
code_store-on-localhost_f778a950
|
[
{
"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/VtexId/service-components/RedirectAfterLogin.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 { useEffect, useContext, useCallback } from 'react'\nimport PropTypes from 'prop-types'\nimport { Services } from '../utils'\nimport Context from '../context'\n\nconst RedirectAfterLogin = ({ children, autorun }) => {\n const {\n state: { returnUrl },\n } = useContext(Context)\n\n const redirect = useCallback(() => Services.redirect({ returnUrl }))\n\n useEffect(() => {\n autorun && redirect()\n }, [autorun])\n\n return children ? children({ action: redirect }) : null\n}\n\nRedirectAfterLogin.propTypes = {\n children: PropTypes.func,\n autorun: PropTypes.bool,\n}\n\nexport default RedirectAfterLogin\n\n```"
}
] |
code_store-on-localhost_9fd1be1f
|
[
{
"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/VtexId/service-components/ReCAPTCHA.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 GoogleRecaptcha from 'react-google-recaptcha'\nimport { Constants } from '../utils'\n\nexport default class ReCAPTCHA extends Component {\n static propTypes = {\n onSuccess: PropTypes.func.isRequired,\n children: PropTypes.func.isRequired,\n }\n\n state = {\n recaptchaRef: React.createRef(),\n }\n\n verifyRecaptcha = () => {\n this.state.recaptchaRef.current.execute()\n }\n\n render() {\n return (\n <React.Fragment>\n {this.props.children(this.verifyRecaptcha)}\n <div className=\"dn\">\n <GoogleRecaptcha\n ref={this.state.recaptchaRef}\n sitekey={Constants.ReCAPTCHA.SiteKey}\n size={Constants.ReCAPTCHA.Size}\n badge=\"inline\"\n onChange={value => {\n this.props.onSuccess(value)\n }}\n />\n </div>\n </React.Fragment>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_8f3f15f4
|
[
{
"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/VtexId/utils/constants.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst TEN_MINUTES = 600000\n\nconst constants = {\n OAuthCallbackUrl: '/api/vtexid/oauth/finish?popup=false',\n OAuthPopupCallbackUrl:\n '/api/vtexid/pub/authentication/finish?sessionRedirect=false',\n ReCAPTCHA: {\n SiteKey: '6LejYzMUAAAAADEaWZnPjOBiyqxE7cvnKpC8kz5F',\n Size: 'invisible',\n },\n SessionDuration: TEN_MINUTES,\n Scopes: {\n ADMIN: 'ADMIN',\n STORE: 'STORE',\n },\n ApiAuthStatus: {\n Success: 'Success',\n WrongCredentials: 'WrongCredentials',\n InativeUser: 'InativeUser',\n BlockedUser: 'BlockedUser',\n MultipleAccount: 'MultipleAccount',\n Pending: 'Pending',\n CanceledKey: 'CanceledKey',\n InvalidToken: 'InvalidToken',\n Error: 'Error',\n CanceledByUser: 'CanceledByUser',\n WeakPassword: 'WeakPassword',\n RequiresMFA: 'RequiresMFA',\n RequiresPhoneRegistration: 'RequiresPhoneRegistration',\n InvalidMFAToken: 'InvalidMFAToken',\n MissingPhoneNumber: 'MissingPhoneNumber',\n InvalidMFAState: 'InvalidMFAState',\n CanRegisterPhoneNumber: 'CanRegisterPhoneNumber',\n InvalidPhoneNumber: 'InvalidPhoneNumber',\n RequiresMFAAuthenticator: 'RequiresMFAAuthenticator',\n PasswordAlreadyUsed: 'PasswordAlreadyUsed',\n ExpiredPassword: 'ExpiredPassword',\n InvalidEmail: 'InvalidEmail',\n InvalidRecaptcha: 'InvalidRecaptcha',\n },\n}\n\nexport default constants\n\n```"
}
] |
code_store-on-localhost_62ae7230
|
[
{
"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/VtexId/utils/fingerprint.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport Fingerprint from 'fingerprintjs2'\nimport promiseDelay from './promise-delay'\n\nconst defaultOptions = {\n preprocessor: null,\n fonts: {\n swfContainerId: 'fingerprintjs2',\n swfPath: 'flash/compiled/FontList.swf',\n userDefinedFonts: [],\n extendedJsFonts: false,\n },\n screen: {\n detectScreenOrientation: true,\n },\n plugins: {\n sortPluginsFor: [/palemoon/i],\n excludeIE: true,\n },\n extraComponents: [],\n excludes: {\n enumerateDevices: true,\n pixelRatio: true,\n doNotTrack: true,\n fonts: true,\n fontsFlash: true,\n audio: true,\n canvas: true,\n webgl: true,\n webglVendorAndRenderer: true,\n webdriver: true,\n cpuClass: true,\n availableScreenResolution: true,\n timezoneOffset: true,\n timezone: true,\n },\n NOT_AVAILABLE: 'not available',\n ERROR: 'error',\n EXCLUDED: 'excluded',\n}\n\nfunction hexString(buffer) {\n const byteArray = new Uint8Array(buffer)\n\n const hexCodes = [...byteArray].map(value => {\n const hexCode = value.toString(16)\n const paddedHexCode = hexCode.padStart(2, '0')\n return paddedHexCode\n })\n\n return hexCodes.join('')\n}\n\nfunction canUseNativeHash() {\n return window.crypto && window.crypto.subtle && window.crypto.subtle.digest\n}\n\nasync function nativeHash(message) {\n if (!canUseNativeHash()) return null\n try {\n const encoder = new TextEncoder()\n const data = await window.crypto.subtle.digest(\n 'SHA-256',\n encoder.encode(message)\n )\n return hexString(data)\n } catch (error) {\n console.error(error)\n return null\n }\n}\n\nasync function getFingerprint(options = null) {\n let attemps = 3\n const opt = options ? { ...defaultOptions, ...options } : defaultOptions\n while (attemps > 0) {\n attemps--\n const components = await Fingerprint.getPromise(opt)\n if (components) {\n const serializedComponents = components\n .map(c => `${c.key}:${c.value.toString()}`)\n .join(';')\n if (canUseNativeHash()) {\n const hash = await nativeHash(serializedComponents)\n return hash\n }\n const hash = Fingerprint.x64hash128(serializedComponents, 31)\n return hash\n }\n }\n return null\n}\n\nexport async function get(options) {\n await promiseDelay(150)\n return Promise.race([promiseDelay(50), getFingerprint(options)])\n}\n\n```"
}
] |
code_store-on-localhost_d984d655
|
[
{
"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/VtexId/utils/getError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport errorTypeByCode from './errorTypeByCode'\nimport UnexpectedError from '../errors/UnexpectedError'\n\nexport default function(error) {\n // The VTEXID token api will return a status 401 and an specific text body\n // message whenever the user is blocked because of too many attempts.\n const legacyBlockedUserResponse = 'Seu login está bloqueado temporariamente.'\n\n const wasBlockedByToken =\n error && error.response && error.response.data === legacyBlockedUserResponse\n\n let errorCode = error && error.code\n errorCode = errorCode || (wasBlockedByToken && 'BlockedUser')\n errorCode = errorCode || (error && error.authStatus)\n errorCode =\n errorCode ||\n (error &&\n error.response &&\n error.response.data &&\n error.response.data.authStatus)\n errorCode = errorCode || ((error && error.message) || '').replace(/\\s+/g, '')\n const errorDetails = error && error.details\n\n if (errorCode) {\n const ErrorType = errorTypeByCode[errorCode]\n return ErrorType\n ? new ErrorType(errorDetails)\n : new UnexpectedError(errorDetails)\n }\n return new UnexpectedError(errorDetails)\n}\n\n```"
}
] |
code_store-on-localhost_6a79d3c8
|
[
{
"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/VtexId/utils/errorTypeByCode.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport {\n NetworkError,\n WrongCredentialsError,\n BlockedUserError,\n InvalidRecaptchaError,\n} from '../errors/index'\n\nconst errorTypeByCode = {\n NetworkError,\n BlockedUser: BlockedUserError,\n WrongCredentials: WrongCredentialsError,\n InvalidMFAToken: WrongCredentialsError,\n InvalidRecaptcha: InvalidRecaptchaError,\n}\n\nexport default errorTypeByCode\n\n```"
}
] |
code_store-on-localhost_f1bab567
|
[
{
"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/VtexId/utils/user-accounts.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport * as jscookies from 'js-cookie'\n\nconst COOKIE_NAME = '_vua'\nconst COOKIE_EXPIRES = 365\n\nconst Cookies = jscookies.withConverter({\n read: (value, name) => {\n if (name === COOKIE_NAME) return window.atob(value)\n },\n write: (value, name) => {\n if (name === COOKIE_NAME) return window.btoa(value)\n },\n})\n\nexport const get = () => {\n if (window && window.document && window.document.cookie) {\n try {\n const usersJson = Cookies.get(COOKIE_NAME)\n const users = JSON.parse(usersJson)\n if (!Array.isArray(users)) {\n Cookies.remove(COOKIE_NAME, { path: window.location.pathname })\n return []\n }\n return users\n } catch {\n Cookies.remove(COOKIE_NAME, { path: window.location.pathname })\n return []\n }\n }\n return []\n}\n\nexport const set = userAccounts => {\n if (window && window.document && window.location) {\n Cookies.set(COOKIE_NAME, userAccounts, {\n expires: COOKIE_EXPIRES,\n path: window.location.pathname,\n })\n }\n}\n\n```"
}
] |
code_store-on-localhost_4dcbc80a
|
[
{
"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/VtexId/utils/services.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport http from 'axios'\nimport Paths from './paths'\nimport Constants from './constants'\nimport { get as getDeviceFingerprint } from './fingerprint'\nimport { UnexpectedError } from '../errors'\n\nconst getReqConfig = parentAppId => {\n const uiPrefix = parentAppId ? `${parentAppId}/` : ''\n const selfAppId = process.env.VTEX_APP_ID || process.env.VTEX_APP_NAME || ''\n return {\n headers: {\n 'vtex-id-ui-version': `${uiPrefix}${selfAppId}`,\n },\n }\n}\n\nconst buildFormData = valueObject => {\n var form = new FormData()\n Object.keys(valueObject).forEach(key =>\n form.append(key, valueObject[key] || '')\n )\n return form\n}\n\nexport const startSession = ({\n accountName,\n returnUrl,\n scope,\n user,\n fingerprint,\n useOAuthPopup,\n parentAppId,\n}) => {\n const { href } = window.location\n const absoluteReturnUrl = new URL(decodeURIComponent(returnUrl || '/'), href)\n const absoluteCallbackUrl = new URL(\n useOAuthPopup\n ? Constants.OAuthPopupCallbackUrl\n : Constants.OAuthCallbackUrl,\n href\n )\n const body = buildFormData({\n accountName,\n scope: scope === Constants.Scopes.ADMIN ? '' : accountName,\n returnUrl: absoluteReturnUrl.href,\n callbackUrl: absoluteCallbackUrl.href,\n user,\n fingerprint,\n })\n return http\n .post(Paths.startLogin(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const getIdentityProviders = ({\n accountName,\n scopeName,\n parentAppId,\n}) => {\n const scope = scopeName === Constants.Scopes.ADMIN ? '' : accountName\n\n return http\n .get(\n Paths.getIdentityProviders(accountName, scope),\n getReqConfig(parentAppId)\n )\n .then(response => {\n const { status, data } = response\n if (status !== 200) {\n throw new UnexpectedError()\n }\n return Promise.resolve(data)\n })\n}\n\nexport const getLoginPreference = ({\n accountName,\n scopeName,\n email,\n parentAppId,\n}) => {\n const scope = scopeName === Constants.Scopes.ADMIN ? '' : accountName\n\n return http\n .get(Paths.getLoginPreference(scope, email), getReqConfig(parentAppId))\n .then(response => {\n const { status, data } = response\n if (status !== 200) {\n throw new UnexpectedError()\n }\n return Promise.resolve(data)\n })\n}\n\nexport const withSession = ({\n accountName,\n returnUrl,\n scope,\n user,\n fingerprint,\n useOAuthPopup,\n parentAppId,\n}) => callback =>\n startSession({\n accountName,\n returnUrl,\n scope,\n user,\n fingerprint,\n useOAuthPopup,\n parentAppId,\n }).then(() => (callback ? callback() : null))\n\nexport const sendVerificationCode = ({\n email,\n locale,\n recaptcha,\n parentAppId,\n}) => {\n const body = buildFormData({\n email,\n locale,\n recaptcha,\n })\n return http\n .post(Paths.sendEmailVerification(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const validateToken = ({\n login,\n accesskey,\n recaptcha,\n setPreference,\n parentAppId,\n}) => {\n const body = buildFormData({\n login,\n accesskey,\n recaptcha,\n })\n return http\n .post(Paths.validateToken(setPreference), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const redirect = ({ returnUrl }) => {\n const absoluteReturnUrl = new URL(\n decodeURIComponent(returnUrl || '/'),\n window.location.href\n )\n window.location.href = Paths.redirect(absoluteReturnUrl.href)\n}\n\nexport const redirectOAuth = ({ provider }) =>\n provider && (window.location.href = Paths.getOAuthRedirectUrl(provider))\n\nexport const getOAuthRedirectUrl = ({ provider }) =>\n Promise.resolve({ url: Paths.getOAuthRedirectUrl(provider) })\n\nexport const setPassword = ({\n login,\n newPassword,\n currentPassword,\n accesskey,\n recaptcha,\n parentAppId,\n}) => {\n const body = buildFormData({\n login,\n newPassword,\n currentPassword,\n accesskey,\n recaptcha,\n })\n return http\n .post(Paths.setPassword(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const setPasswordAfterLogin = ({\n accountName,\n scope,\n password,\n setPreference,\n parentAppId,\n}) => {\n const body = {\n password,\n }\n const account = scope === Constants.Scopes.ADMIN ? '' : accountName\n return http\n .post(\n Paths.setPasswordAfterLogin(account, setPreference),\n body,\n getReqConfig(parentAppId)\n )\n .then(({ data }) => data)\n}\n\nexport const validatePassword = ({\n login,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n}) => {\n const body = buildFormData({\n login,\n password,\n recaptcha,\n fingerprint,\n })\n return http\n .post(Paths.validatePassword(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const startMfaSetup = ({ parentAppId }) =>\n http\n .post(Paths.startMfaSetup(), null, getReqConfig(parentAppId))\n .then(({ data }) => data)\n\nexport const withMfaSession = (callback, { parentAppId }) =>\n startMfaSetup({ parentAppId }).then(() => (callback ? callback() : null))\n\nexport const validateMfa = ({ mfaToken, recaptcha, parentAppId }) => {\n const body = buildFormData({\n mfaToken,\n recaptcha,\n })\n return http\n .post(Paths.validateMfa(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const registerMfaPhoneNumber = ({\n phoneNumber,\n recaptcha,\n parentAppId,\n}) => {\n const body = buildFormData({\n phoneNumber,\n recaptcha,\n })\n return http\n .post(Paths.registerMfaPhoneNumber(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const resendMfa = ({ recaptcha, parentAppId }) => {\n const body = buildFormData({\n recaptcha,\n })\n return http\n .post(Paths.resendMfa(), body, getReqConfig(parentAppId))\n .then(({ data }) => data)\n}\n\nexport const registerMfaAuthenticator = ({ parentAppId }) => {\n return http\n .post(Paths.registerMfaAuthenticator(), null, getReqConfig(parentAppId))\n .then(({ data }) => data)\n .then(data => {\n if (!data || !data.qRCodeUrl) return data\n return {\n ...data,\n qRCodeUrl: data.qRCodeUrl.replace('chs=150x150', 'chs=200x200'),\n }\n })\n}\n\nexport const redirectLogout = ({ returnUrl }) => {\n const absoluteReturnUrl = new URL(\n decodeURIComponent(returnUrl || '/'),\n window.location.href\n )\n window.location.href = Paths.logout(\n encodeURIComponent(window.location.host),\n absoluteReturnUrl.href\n )\n}\n\nexport const logout = ({ parentAppId }) =>\n http.get(\n Paths.logout(encodeURIComponent(window.location.host)),\n getReqConfig(parentAppId)\n )\n\nconst reauthenticateUser = ({\n accountName,\n scopeName,\n parentAppId,\n fingerprint,\n}) => {\n const scope = scopeName === Constants.Scopes.ADMIN ? '' : accountName\n\n return http\n .post(\n Paths.reauthenticateUser(scope),\n { fingerprint },\n getReqConfig(parentAppId)\n )\n .then(response => {\n const { status, data } = response\n if (status !== 200) {\n return Promise.resolve(null)\n }\n return Promise.resolve(data)\n })\n .catch(() => Promise.resolve(null))\n}\n\nexport const getUserInfo = ({ accountName, scopeName, parentAppId }) => {\n const scope = scopeName === Constants.Scopes.ADMIN ? '' : accountName\n\n return http\n .get(Paths.getUserInfo(scope), getReqConfig(parentAppId))\n .then(response => {\n const { status, data } = response\n if (status !== 200) {\n return Promise.resolve(null)\n }\n return Promise.resolve(data)\n })\n .catch(() => Promise.resolve(null))\n}\n\nconst reauthenticateAndGetUserInfo = async ({\n fingerprintPromise,\n accountName,\n scopeName,\n parentAppId,\n isAdmin,\n}) => {\n if (isAdmin) {\n const fingerprint = await fingerprintPromise\n await reauthenticateUser({\n accountName,\n scopeName,\n parentAppId,\n fingerprint,\n })\n }\n return await getUserInfo({ accountName, scopeName, parentAppId })\n}\n\nexport const getInitialData = ({ accountName, scopeName, parentAppId }) => {\n const isAdmin = scopeName === Constants.Scopes.ADMIN\n\n const fingerprintPromise = getDeviceFingerprint()\n\n return Promise.all([\n getIdentityProviders({ accountName, scopeName, parentAppId }),\n reauthenticateAndGetUserInfo({\n fingerprintPromise,\n accountName,\n scopeName,\n parentAppId,\n isAdmin,\n }),\n isAdmin ? fingerprintPromise : Promise.resolve(null),\n ]).then(([identityProviders, userInfo, fingerprint]) =>\n Promise.resolve({ identityProviders, userInfo, fingerprint })\n )\n}\n\n```"
}
] |
code_store-on-localhost_12002e2f
|
[
{
"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/VtexId/utils/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport * as Fingerprint from './fingerprint'\nimport * as Services from './services'\nimport * as UserAccounts from './user-accounts'\nimport * as Validations from './validations'\n\nexport { default as Constants } from './constants'\nexport { default as NOOP } from './noop'\nexport { Fingerprint, Services, Validations, UserAccounts }\n\n```"
}
] |
code_store-on-localhost_9cf030b4
|
[
{
"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/VtexId/utils/paths.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst composeQuerystring = valueObject => {\n return Object.keys(valueObject)\n .map(key => `${key}=${encodeURIComponent(valueObject[key] || '')}`)\n .join('&')\n}\n\n/*global __RUNTIME__*/\nconst rootPath = `${\n __RUNTIME__ && __RUNTIME__.rootPath ? __RUNTIME__.rootPath : ''\n}/api/vtexid`\n\nconst paths = {\n startLogin: () => `${rootPath}/pub/authentication/startlogin`,\n getIdentityProviders: (account, scope) =>\n `${rootPath}/pub/authentication/providers?scope=${scope}&accountName=${account}`,\n getLoginPreference: (scope, email) => {\n const qs = composeQuerystring({ scope, email })\n return `${rootPath}/pub/authentication/userpreference?${qs}`\n },\n redirect: returnUrl => {\n const qs = returnUrl ? composeQuerystring({ returnUrl }) : ''\n return `${rootPath}/pub/authentication/redirect?${qs}`\n },\n getOAuthRedirectUrl: providerName =>\n `${rootPath}/pub/authentication/oauth/redirect?${composeQuerystring({\n providerName,\n })}`,\n getUserInfo: scope => `${rootPath}/user/info?scope=${scope}`,\n reauthenticateUser: scope => `${rootPath}/refreshtoken?scope=${scope}`,\n setPassword: () => `${rootPath}/pub/authentication/classic/setpassword`,\n sendEmailVerification: () => `${rootPath}/pub/authentication/accesskey/send`,\n validateToken: setPreference =>\n `${rootPath}/pub/authentication/accesskey/validate?setPreference=${!!setPreference}`,\n validatePassword: () => `${rootPath}/pub/authentication/classic/validate`,\n startMfaSetup: () => `${rootPath}/pvt/mfa/start`,\n validateMfa: () => `${rootPath}/pub/mfa/validate`,\n registerMfaPhoneNumber: () => `${rootPath}/pub/mfa/registerphone`,\n registerMfaAuthenticator: () => `${rootPath}/pub/mfa/registerAuthenticator`,\n resendMfa: () => `${rootPath}/pub/mfa/resend`,\n setPasswordAfterLogin: (scope, setPreference) => {\n return `${rootPath}/user/password/quickset?scope=${scope}&setPreference=${!!setPreference}`\n },\n logout: (scope, returnUrl) => {\n const qs = composeQuerystring({\n scope,\n returnUrl,\n })\n return `${rootPath}/pub/logout?${qs}`\n },\n}\nexport default paths\n\n```"
}
] |
code_store-on-localhost_846f7539
|
[
{
"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/VtexId/utils/useStateWithCallback.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useRef, useCallback, useEffect } from 'react'\n\nconst useStateWithCallback = initialState => {\n const [state, setState] = useState(initialState)\n const callbackAfterSetState = useRef(null)\n const [refUpdaterCounter, setRefUpdaterCounter] = useState(0)\n\n const setStateWithCallback = useCallback(\n (stateUpdater, callback = null) => {\n setState(stateUpdater)\n callbackAfterSetState.current = callback\n setRefUpdaterCounter(counter => counter + 1)\n },\n [setState, callbackAfterSetState, setRefUpdaterCounter]\n )\n\n useEffect(() => {\n if (callbackAfterSetState.current) {\n const callback = callbackAfterSetState.current\n callbackAfterSetState.current = null\n callback(state)\n }\n }, [refUpdaterCounter, callbackAfterSetState, state])\n\n return [state, setStateWithCallback]\n}\n\nexport default useStateWithCallback\n\n```"
}
] |
code_store-on-localhost_ba715e75
|
[
{
"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/VtexId/utils/useRefCallback.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useRef, useEffect } from 'react'\n\n/// Returns a wrapper function that persists through the lifetime of the component (like a ref)\n/// and that internally calls the input callback\nconst useRefCallback = (callback, depsLst) => {\n const ref = useRef(callback)\n\n useEffect(() => {\n ref.current = callback\n }, [callback, ...depsLst])\n\n return (...args) => ref.current(...args)\n}\n\nexport default useRefCallback\n\n```"
}
] |
code_store-on-localhost_9b61c914
|
[
{
"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/VtexId/utils/validations.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable no-useless-escape */\nconst patterns = {\n hasNumber: /\\d/,\n hasNotANumber: /[^\\d]/,\n lowerCaseLetter: /[a-z]/,\n upperCaseLetter: /[A-Z]/,\n email: /^(([^<>()\\[\\]\\\\.,;:\\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}\nexport const validateEmail = email => {\n if (!email) return false\n return patterns.email.test(String(email).toLowerCase())\n}\n\nexport const hasChar = value =>\n patterns.lowerCaseLetter.test(String(value || '').toLowerCase())\n\nexport const hasOnlyNumbers = value =>\n patterns.hasNumber.test(String(value || ''))\n\nexport const validatePassword = pass => {\n if (!pass) {\n return {\n passwordIsValid: false,\n hasNumber: false,\n hasMinLength: false,\n hasLowerCaseLetter: false,\n hasUpperCaseLetter: false,\n }\n }\n const hasMinLength = !!(pass && pass.length >= 8)\n const hasNumber = patterns.hasNumber.test(pass)\n const hasLowerCaseLetter = patterns.lowerCaseLetter.test(pass)\n const hasUpperCaseLetter = patterns.upperCaseLetter.test(pass)\n\n return {\n passwordIsValid:\n hasNumber && hasMinLength && hasLowerCaseLetter && hasUpperCaseLetter,\n hasNumber,\n hasMinLength,\n hasLowerCaseLetter,\n hasUpperCaseLetter,\n }\n}\n\nexport const validatePhone = () => true\n\n```"
}
] |
code_store-on-localhost_9595596a
|
[
{
"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/VtexId/utils/promise-delay.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n\nconst delay = (ms) => new Promise(resolve => { setTimeout(resolve, ms) })\n\nexport default delay\n\n```"
}
] |
code_store-on-localhost_b788fedb
|
[
{
"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/VtexId/state-components/CurrentPassword.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 { Validations } from '../utils'\nimport Context from '../context'\n\nconst CurrentPassword = ({ children }) => {\n return (\n <Context.Consumer>\n {({ state: { currentPassword }, handlers: { handleCurrentPasswordChange } }) =>\n children({\n value: currentPassword,\n setValue: handleCurrentPasswordChange,\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n}\nCurrentPassword.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default CurrentPassword\n\n```"
}
] |
code_store-on-localhost_1042ffeb
|
[
{
"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/VtexId/state-components/Token.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 { Validations } from '../utils'\nimport Context from '../context'\n\nclass Token extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n handleTokenChange: PropTypes.func.isRequired,\n token: PropTypes.string,\n }\n\n componentWillUnmount = () => this.props.handleTokenChange('')\n\n render() {\n const { children, token, handleTokenChange } = this.props\n return children({\n value: token,\n setValue: handleTokenChange,\n validation: Validations,\n })\n }\n}\n\nconst TokenWrapper = props => (\n <Context.Consumer>\n {({ state: { token }, handlers: { handleTokenChange } }) => (\n <Token {...props} token={token} handleTokenChange={handleTokenChange} />\n )}\n </Context.Consumer>\n)\n\nexport default TokenWrapper\n\n```"
}
] |
code_store-on-localhost_80e414e6
|
[
{
"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/VtexId/state-components/Password.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 { Validations } from '../utils'\nimport Context from '../context'\n\nconst Password = ({ children }) => {\n return (\n <Context.Consumer>\n {({ state: { password }, handlers: { handlePasswordChange } }) =>\n children({\n value: password,\n setValue: handlePasswordChange,\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n}\nPassword.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default Password\n\n```"
}
] |
code_store-on-localhost_c711ec45
|
[
{
"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/VtexId/state-components/Login.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 { Validations } from '../utils'\nimport Context from '../context'\n\nexport default class VtexIdConsumer extends Component {\n static propTypes = {\n children: PropTypes.func.isRequired,\n }\n\n render() {\n return (\n <Context.Consumer>\n {({ state, handlers }) =>\n this.props.children(state, handlers, Validations)\n }\n </Context.Consumer>\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.