id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-components_f0c94a97
|
[
{
"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-components/react/components/ProductImages/utils/enums.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const THUMBS_POSITION_HORIZONTAL = {\n LEFT: 'left',\n RIGHT: 'right',\n}\n\nexport const THUMBS_ORIENTATION = {\n VERTICAL: 'vertical',\n HORIZONTAL: 'horizontal',\n}\n\nexport const DISPLAY_MODE = {\n CAROUSEL: 'carousel',\n LIST: 'list',\n FIRST_IMAGE: 'first-image',\n}\n\nexport const THUMBS_VISIBILITY = {\n VISIBLE: 'visible',\n HIDDEN: 'hidden',\n}\n\nexport const DEFAULT_EXCLUDE_IMAGE_WITH = 'skuvariation'\n\n```"
}
] |
code_store-components_770386de
|
[
{
"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-components/react/components/ProductImages/utils/generateUrl.js from the store-components 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\nfunction getParamFromUrl(url, name) {\n return (url?.split(`${name}=`)[1] || '')?.split('&')[0]\n}\n\nexport function cleanImageUrl(imageUrl) {\n const cleanUrlResult = baseUrlRegex.exec(imageUrl)\n const vParam = getParamFromUrl(imageUrl, 'v')\n\n if (cleanUrlResult && cleanUrlResult.length > 0) {\n return {\n cleanUrl: cleanUrlResult[0],\n vParam,\n }\n }\n\n return { cleanUrl: imageUrl }\n}\n\nfunction replaceLegacyFileManagerUrl(imageUrl, width, height) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n\n if (!isLegacyUrl) return imageUrl\n\n const { vParam, cleanUrl } = cleanImageUrl(imageUrl)\n\n return vParam\n ? `${cleanUrl}-${width}-${height}?v=${vParam}`\n : `${cleanUrl}-${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\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\n```"
}
] |
code_store-components_ef6b8c89
|
[
{
"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-components/react/components/ProductImages/utils/generateImageConfig.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { changeImageUrlSize } from './generateUrl'\n\nconst thumbnailSize = 160\n\nexport default function generateImageConfig(image) {\n return {\n imageUrl: image.imageUrl,\n thumbnailUrl: changeImageUrlSize(image.imageUrl, thumbnailSize),\n imageText: image.imageText,\n imageLabel: image.imageLabel,\n }\n}\n\n```"
}
] |
code_store-components_abc2082f
|
[
{
"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-components/react/components/ProductImages/components/ProductImageContext.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createContext } from 'react'\n\nexport interface State {\n src: string\n alt: string\n}\n\nconst ProductImageContext = createContext<State | Record<string, any>>({})\n\nexport default ProductImageContext\n\n```"
}
] |
code_store-components_6ec07e44
|
[
{
"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-components/react/components/ProductImages/components/ProductImage.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo, useRef } from 'react'\nimport { Modal } from 'vtex.modal-layout'\nimport { useCssHandles, applyModifiers } from 'vtex.css-handles'\n\nimport Zoomable, { ZoomMode } from './Zoomable'\nimport { imageUrl } from '../utils/aspectRatioUtil'\nimport ProductImageContext, {\n State as ProductImageState,\n} from './ProductImageContext'\n\nconst IMAGE_SIZES = [600, 800, 1200]\nconst DEFAULT_SIZE = 800\nconst MAX_SIZE = 2048\n\ninterface Props {\n index: number\n src: string\n alt: string\n imageLabel?: string\n zoomMode: ZoomMode\n zoomFactor: number\n aspectRatio?: AspectRatio\n maxHeight?: number | string\n ModalZoomElement?: typeof Modal\n}\n\ntype AspectRatio = string | number\n\nconst CSS_HANDLES = ['productImage', 'productImageTag', 'productImageLabel']\n\nconst ProductImage: FC<Props> = ({\n index,\n src,\n alt,\n imageLabel,\n zoomFactor = 2,\n maxHeight = 600,\n ModalZoomElement,\n aspectRatio = 'auto',\n zoomMode = 'in-place-click',\n}) => {\n const srcSet = useMemo(\n () =>\n IMAGE_SIZES.map(\n size => `${imageUrl(src, size, MAX_SIZE, aspectRatio)} ${size}w`\n ).join(','),\n [src, aspectRatio]\n )\n\n const { handles } = useCssHandles(CSS_HANDLES)\n const imageRef = useRef(null)\n\n const imageContext: ProductImageState = useMemo(\n () => ({\n src,\n alt,\n }),\n [alt, src]\n )\n\n return (\n <ProductImageContext.Provider value={imageContext}>\n <div className={handles.productImage}>\n {imageLabel && (\n <div className={`tc ${handles.productImageLabel}`}>{imageLabel}</div>\n )}\n <Zoomable\n mode={zoomMode}\n factor={zoomFactor}\n ModalZoomElement={ModalZoomElement}\n zoomContent={\n // eslint-disable-next-line jsx-a11y/alt-text\n <img\n // This img element is just for zoom\n role=\"presentation\"\n src={imageUrl(\n src,\n DEFAULT_SIZE * zoomFactor,\n MAX_SIZE,\n aspectRatio\n )}\n className={`${applyModifiers(handles.productImageTag, 'zoom')}`}\n style={{\n // Resets possible resizing done via CSS\n maxWidth: 'unset',\n width: `${zoomFactor * 100}%`,\n height: `${zoomFactor * 100}%`,\n objectFit: 'contain',\n }}\n // See comment regarding sizes below\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n />\n }\n >\n <img\n ref={imageRef}\n className={`${applyModifiers(handles.productImageTag, 'main')}`}\n style={{\n width: '100%',\n height: '100%',\n maxHeight: maxHeight || 'unset',\n objectFit: 'contain',\n }}\n src={imageUrl(src, DEFAULT_SIZE, MAX_SIZE, aspectRatio)}\n srcSet={srcSet}\n alt={alt}\n title={alt}\n loading={index === 0 ? 'eager' : 'lazy'}\n {...(index === 0 && { fetchPriority: 'high' })}\n // WIP\n // The value of the \"sizes\" attribute means: if the window has at most 64.1rem of width,\n // the image will be of a width of 100vw. Otherwise, the\n // image will be 50vw wide.\n // This size is used for picking the best available size\n // given the ones from the srcset above.\n //\n // This is WIP because it is a guess: we are assuming\n // the image will be of a certain size, but it should be\n // probably be gotten from flex-layout or something.\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n />\n </Zoomable>\n </div>\n </ProductImageContext.Provider>\n )\n}\n\nexport default ProductImage\n\n```"
}
] |
code_store-components_c5b4b5a6
|
[
{
"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-components/react/components/ProductImages/components/HighQualityProductImage.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useContext } from 'react'\nimport classnames from 'classnames'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport styles from '../styles.css'\nimport { imageUrl } from '../utils/aspectRatioUtil'\nimport ProductImageContext from './ProductImageContext'\nimport Zoomable, { ZoomMode as ZoomModeComplete } from './Zoomable'\n\ntype AspectRatio = string | number\ntype ZoomMode = Exclude<ZoomModeComplete, 'open-modal'>\n\ninterface Props {\n zoomMode?: ZoomMode\n zoomFactor?: number\n aspectRatio?: AspectRatio\n imageSizes?: number[]\n defaultSize?: number\n maxSize?: number\n}\n\nfunction validateZoomMode(zoomMode: ZoomModeComplete): ZoomMode {\n if (\n zoomMode !== 'disabled' &&\n zoomMode !== 'in-place-click' &&\n zoomMode !== 'in-place-hover'\n ) {\n console.warn(\n `You passed a wrong value to prop zoomMode \\`${zoomMode}\\` using 'disabled' instead`\n )\n\n return 'disabled'\n }\n\n return zoomMode\n}\n\nconst CSS_HANDLES = [\n 'imgZoom',\n 'productImageTag',\n 'highQualityContainer',\n] as const\n\nfunction HighQualityProductImage(props: Props) {\n const {\n imageSizes,\n maxSize = 4096,\n zoomFactor = 2,\n defaultSize = 1200,\n aspectRatio = 'auto',\n zoomMode = 'disabled',\n } = props\n\n const { handles } = useCssHandles(CSS_HANDLES)\n const context = useContext(ProductImageContext)\n\n if (!context) {\n console.warn(\n \"You're using a HighQualityProductImage out of a ProductImageContext\"\n )\n\n return null\n }\n\n if (!('src' in context)) {\n return null\n }\n\n const { alt, src } = context\n const srcSet = imageSizes\n ?.map(size => `${imageUrl(src, size, maxSize, aspectRatio)} ${size}w`)\n .join(',')\n\n const containerClasses = classnames(\n handles.highQualityContainer,\n 'w-100 h-100 overflow-hidden'\n )\n\n const imgClasses = classnames(\n handles.productImageTag,\n styles.highQualityProductImageImgElement,\n 'w-100 h-100'\n )\n\n return (\n <div className={containerClasses}>\n <Zoomable\n mode={validateZoomMode(zoomMode)}\n factor={zoomFactor}\n zoomContent={\n // eslint-disable-next-line jsx-a11y/alt-text\n <img\n // This img element is just for zoom\n role=\"presentation\"\n className={handles.imgZoom}\n style={{\n // Resets possible resizing done via CSS\n maxWidth: 'unset',\n width: `${zoomFactor * 100}%`,\n height: `${zoomFactor * 100}%`,\n objectFit: 'contain',\n }}\n // See comment regarding sizes below\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n src={\n imageSizes\n ? imageUrl(src, defaultSize * zoomFactor, maxSize, aspectRatio)\n : src\n }\n />\n }\n >\n <img\n alt={alt}\n title={alt}\n loading=\"lazy\"\n srcSet={srcSet}\n className={imgClasses}\n // See comment regarding sizes below\n sizes=\"(max-width: 64.1rem) 100vw, 50vw\"\n src={\n imageSizes\n ? imageUrl(src, defaultSize * zoomFactor, maxSize, aspectRatio)\n : src\n }\n />\n </Zoomable>\n </div>\n )\n}\n\nexport default HighQualityProductImage\n\n```"
}
] |
code_store-components_56276e2a
|
[
{
"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-components/react/components/ProductImages/components/Video/Vimeo.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Vimeo extends Component {\n constructor(props) {\n super(props)\n\n this.state = { iframe: {} }\n\n const { loop, autoplay, width, height, showTitle, url } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&title=${showTitle}&width=${width}&height=${height}`\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}&${params}`\n\n this.iframeRef = React.createRef()\n\n fetch(getUrl)\n .then(response => response.json())\n .then(response => {\n const { height: heightDiv, width: widthDiv, html, title } = response\n\n const thumbUrl = Vimeo.thumbUrlFromResp(response, props.thumbWidth)\n\n props.setThumb && props.setThumb(thumbUrl, title)\n\n const [, src] = html.match(/src= *\" *([^\"]*) *\"/) // Get url from response\n\n this.setState({\n iframe: {\n divStyle: { padding: `${(100 * heightDiv) / widthDiv}% 0 0 0` },\n src,\n },\n })\n })\n }\n\n static getThumbUrl = url => {\n const getUrl = `https://vimeo.com/api/oembed.json?url=${url}`\n\n return fetch(getUrl)\n .then(response => response.json())\n .then(response => response.thumbnail_url)\n }\n\n static thumbUrlFromResp(response, thumbWidth) {\n const { height, width } = response\n const thumb = response.thumbnail_url_with_play_button\n\n thumbWidth = thumbWidth || response.thumbnail_width\n const thumbHeight = Math.ceil((thumbWidth * height) / width)\n\n return thumb.replace(\n /_[0123456789]*x[0123456789]*./,\n `_${thumbWidth}x${thumbHeight}.`\n )\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const vimeoCommand = JSON.stringify({ method: command })\n\n this.iframeRef.contentWindow.postMessage(\n vimeoCommand,\n 'https://player.vimeo.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id, cssHandles } = this.props\n\n this.props.playing\n ? this.executeCommand('play')()\n : this.executeCommand('pause')()\n\n return (\n <div\n style={iframe.divStyle}\n className={`relative ${className} ${cssHandles.videoContainer}`}\n >\n <iframe\n ref={this.iframeRef}\n title={id}\n className={`${cssHandles.video} absolute top-0 left-0 w-100 h-100`}\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nVimeo.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n showTitle: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n cssHandles: PropTypes.shape({\n video: PropTypes.string.isRequired,\n videoContainer: PropTypes.string.isRequired,\n }).isRequired,\n}\n\nVimeo.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n showTitle: false,\n className: '',\n}\n\nexport default Vimeo\n\n```"
}
] |
code_store-components_1eb79dc7
|
[
{
"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-components/react/components/ProductImages/components/Video/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { match, compose, isEmpty, complement } from 'ramda'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { NoSSR } from 'vtex.render-runtime'\n\nimport Vimeo from './Vimeo'\nimport YouTube from './Youtube'\n\nconst isNotEmpty = complement(isEmpty)\n\nconst isVimeo = compose(isNotEmpty, match(/vimeo/))\nconst isYoutube = compose(isNotEmpty, match(/youtube|youtu.be/))\n\nconst CSS_HANDLES = ['productVideo', 'videoContainer', 'video']\n\nexport function getThumbUrl(url, thumbWidth) {\n if (isVimeo(url)) {\n return Vimeo.getThumbUrl(url, thumbWidth)\n }\n\n if (isYoutube(url)) {\n return YouTube.getThumbUrl(url, thumbWidth)\n }\n}\n\nfunction Video(props) {\n const { url } = props\n const { handles } = useCssHandles(CSS_HANDLES)\n\n return (\n <div className={handles.productVideo}>\n {isVimeo(url) && (\n <NoSSR>\n <Vimeo key={url} {...props} cssHandles={handles} />\n </NoSSR>\n )}\n {isYoutube(url) && <YouTube key={url} {...props} cssHandles={handles} />}\n </div>\n )\n}\n\nVideo.propsTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired,\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n play: PropTypes.bool,\n}\n\nexport default Video\n\n```"
}
] |
code_store-components_ad6858f5
|
[
{
"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-components/react/components/ProductImages/components/Video/Youtube.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Youtube extends Component {\n constructor(props) {\n super(props)\n\n const { loop, autoplay, title, url } = this.props\n const params = `autoplay=${autoplay}&loop=${loop}&title=${title}&enablejsapi=1&iv_load_policy=3&modestbranding=1`\n const videoId = Youtube.extractVideoID(url)\n\n this.iframeRef = React.createRef()\n this.state = {\n iframe: {\n src: `https://www.youtube.com/embed/${videoId}?${params}`,\n },\n }\n }\n\n static getThumbUrl = url => {\n const videoId = Youtube.extractVideoID(url)\n\n return Promise.resolve(`https://img.youtube.com/vi/${videoId}/default.jpg`)\n }\n\n static extractVideoID = url => {\n const regExp =\n /^.*((youtu.be\\/)|(v\\/)|(\\/u\\/\\w\\/)|(embed\\/)|(watch\\?)|(shorts\\/))\\??v?=?([^#&?]*).*/\n\n const match = url.match(regExp)\n\n if (match && match[8].length === 11) return match[8]\n\n return null\n }\n\n executeCommand = command => () => {\n if (!this.frameReady) return\n\n const youtubeCommand = JSON.stringify({ event: 'command', func: command })\n\n this.iframeRef.contentWindow.postMessage(\n youtubeCommand,\n 'https://www.youtube.com'\n )\n }\n\n render() {\n const { iframe } = this.state\n const { className, id, cssHandles } = this.props\n\n this.props.playing\n ? this.executeCommand('playVideo')()\n : this.executeCommand('pauseVideo')()\n\n return (\n <div\n className={`relative ${className} ${cssHandles.videoContainer}`}\n style={{ padding: '30%' }}\n >\n <iframe\n ref={this.iframeRef}\n title={id}\n className={`${cssHandles.video} absolute top-0 left-0 w-100 h-100`}\n src={iframe.src}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n }\n}\n\nYoutube.propTypes = {\n url: PropTypes.string.isRequired,\n id: PropTypes.number.isRequired, // Unique ID for iframe title\n setThumb: PropTypes.func,\n thumbWidth: PropTypes.number,\n className: PropTypes.string,\n loop: PropTypes.bool,\n autoplay: PropTypes.bool,\n showTitle: PropTypes.bool,\n width: PropTypes.number,\n height: PropTypes.number,\n playing: PropTypes.bool,\n title: PropTypes.string,\n cssHandles: PropTypes.shape({\n video: PropTypes.string.isRequired,\n videoContainer: PropTypes.string.isRequired,\n }).isRequired,\n}\n\nYoutube.defaultProps = {\n loop: true,\n autoplay: false,\n width: null,\n height: null,\n title: false,\n className: '',\n}\n\nexport default Youtube\n\n```"
}
] |
code_store-components_17f7cdff
|
[
{
"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-components/react/components/ProductImages/components/Gallery/global.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.pswp{display:none;position:absolute;width:100%;height:100%;left:0;top:0;overflow:hidden;-ms-touch-action:none;touch-action:none;z-index:1500;-webkit-text-size-adjust:100%;-webkit-backface-visibility:hidden;outline:none}.pswp *{-webkit-box-sizing:border-box;box-sizing:border-box}.pswp img{max-width:none}.pswp--animate_opacity{opacity:.001;will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--open{display:block}.pswp--zoom-allowed .pswp__img{cursor:-webkit-zoom-in;cursor:-moz-zoom-in;cursor:zoom-in}.pswp--zoomed-in .pswp__img{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.pswp--dragging .pswp__img{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.pswp__bg{background:#000;opacity:0;-webkit-transform:translateZ(0);transform:translateZ(0);-webkit-backface-visibility:hidden}.pswp__bg,.pswp__scroll-wrap{position:absolute;left:0;top:0;width:100%;height:100%}.pswp__scroll-wrap{overflow:hidden}.pswp__container,.pswp__zoom-wrap{-ms-touch-action:none;touch-action:none;position:absolute;left:0;right:0;top:0;bottom:0}.pswp__container,.pswp__img{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none}.pswp__zoom-wrap{position:absolute;width:100%;-webkit-transform-origin:left top;transform-origin:left top;-webkit-transition:-webkit-transform 333ms cubic-bezier(.4,0,.22,1);transition:-webkit-transform 333ms cubic-bezier(.4,0,.22,1);transition:transform 333ms cubic-bezier(.4,0,.22,1);transition:transform 333ms cubic-bezier(.4,0,.22,1),-webkit-transform 333ms cubic-bezier(.4,0,.22,1)}.pswp__bg{will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--animated-in .pswp__bg,.pswp--animated-in .pswp__zoom-wrap{-webkit-transition:none;transition:none}.pswp__container,.pswp__zoom-wrap{-webkit-backface-visibility:hidden}.pswp__item{right:0;bottom:0;overflow:hidden}.pswp__img,.pswp__item{position:absolute;left:0;top:0}.pswp__img{width:auto;height:auto}.pswp__img--placeholder{-webkit-backface-visibility:hidden}.pswp__img--placeholder--blank{background:#222}.pswp--ie .pswp__img{width:100%!important;height:auto!important;left:0;top:0}.pswp__error-msg{position:absolute;left:0;top:50%;width:100%;text-align:center;font-size:14px;line-height:16px;margin-top:-8px;color:#ccc}.pswp__error-msg a{color:#ccc;text-decoration:underline}.pswp__button{width:44px;height:44px;position:relative;background:none;cursor:pointer;overflow:visible;-webkit-appearance:none;display:block;border:0;padding:0;margin:0;float:right;opacity:.75;-webkit-transition:opacity .2s;transition:opacity .2s;-webkit-box-shadow:none;box-shadow:none}.pswp__button:focus,.pswp__button:hover{opacity:1}.pswp__button:active{outline:none;opacity:.9}.pswp__button::-moz-focus-inner{padding:0;border:0}.pswp__ui--over-close .pswp__button--close{opacity:1}.pswp__button,.pswp__button--arrow--left:before,.pswp__button--arrow--right:before{background:url(./default-skin.png) 0 0 no-repeat;background-size:264px 88px;width:44px;height:44px}@media (-webkit-min-device-pixel-ratio:1.1),(-webkit-min-device-pixel-ratio:1.09375),(min-resolution:1.1dppx),(min-resolution:105dpi){.pswp--svg .pswp__button,.pswp--svg .pswp__button--arrow--left:before,.pswp--svg .pswp__button--arrow--right:before{background-image:url(./default-skin.svg)}.pswp--svg .pswp__button--arrow--left,.pswp--svg .pswp__button--arrow--right{background:none}}.pswp__button--close{background-position:0 -44px}.pswp__button--share{background-position:-44px -44px}.pswp__button--fs{display:none}.pswp--supports-fs .pswp__button--fs{display:block}.pswp--fs .pswp__button--fs{background-position:-44px 0}.pswp__button--zoom{display:none;background-position:-88px 0}.pswp--zoom-allowed .pswp__button--zoom{display:block}.pswp--zoomed-in .pswp__button--zoom{background-position:-132px 0}.pswp--touch .pswp__button--arrow--left,.pswp--touch .pswp__button--arrow--right{visibility:hidden}.pswp__button--arrow--left,.pswp__button--arrow--right{background:none;top:50%;margin-top:-50px;width:70px;height:100px;position:absolute}.pswp__button--arrow--left{left:0}.pswp__button--arrow--right{right:0}.pswp__button--arrow--left:before,.pswp__button--arrow--right:before{content:\"\";top:35px;background-color:rgba(0,0,0,.3);height:30px;width:32px;position:absolute}.pswp__button--arrow--left:before{left:6px;background-position:-138px -44px}.pswp__button--arrow--right:before{right:6px;background-position:-94px -44px}.pswp__counter,.pswp__share-modal{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pswp__share-modal{display:block;background:rgba(0,0,0,.5);width:100%;height:100%;top:0;left:0;padding:10px;position:absolute;z-index:1600;opacity:0;-webkit-transition:opacity .25s ease-out;transition:opacity .25s ease-out;-webkit-backface-visibility:hidden;will-change:opacity}.pswp__share-modal--hidden{display:none}.pswp__share-tooltip{z-index:1620;position:absolute;background:#fff;top:56px;border-radius:2px;display:block;width:auto;right:44px;-webkit-box-shadow:0 2px 5px rgba(0,0,0,.25);box-shadow:0 2px 5px rgba(0,0,0,.25);-webkit-transform:translateY(6px);transform:translateY(6px);-webkit-transition:-webkit-transform .25s;transition:-webkit-transform .25s;transition:transform .25s;transition:transform .25s,-webkit-transform .25s;-webkit-backface-visibility:hidden;will-change:transform}.pswp__share-tooltip a{display:block;padding:8px 12px;font-size:14px;line-height:18px}.pswp__share-tooltip a,.pswp__share-tooltip a:hover{color:#000;text-decoration:none}.pswp__share-tooltip a:first-child{border-radius:2px 2px 0 0}.pswp__share-tooltip a:last-child{border-radius:0 0 2px 2px}.pswp__share-modal--fade-in{opacity:1}.pswp__share-modal--fade-in .pswp__share-tooltip{-webkit-transform:translateY(0);transform:translateY(0)}.pswp--touch .pswp__share-tooltip a{padding:16px 12px}a.pswp__share--facebook:before{content:\"\";display:block;width:0;height:0;position:absolute;top:-12px;right:15px;border:6px solid transparent;border-bottom-color:#fff;-webkit-pointer-events:none;-moz-pointer-events:none;pointer-events:none}a.pswp__share--facebook:hover{background:#3e5c9a;color:#fff}a.pswp__share--facebook:hover:before{border-bottom-color:#3e5c9a}a.pswp__share--twitter:hover{background:#55acee;color:#fff}a.pswp__share--pinterest:hover{background:#ccc;color:#ce272d}a.pswp__share--download:hover{background:#ddd}.pswp__counter{position:absolute;left:0;top:0;height:44px;font-size:13px;line-height:44px;color:#fff;opacity:.75;padding:0 10px}.pswp__caption{position:absolute;left:0;bottom:0;width:100%;min-height:44px}.pswp__caption small{font-size:11px;color:#bbb}.pswp__caption__center{text-align:left;max-width:420px;margin:0 auto;font-size:13px;padding:10px;line-height:20px;color:#ccc}.pswp__caption--empty{display:none}.pswp__caption--fake{visibility:hidden}.pswp__preloader{width:44px;height:44px;position:absolute;top:0;left:50%;margin-left:-22px;opacity:0;-webkit-transition:opacity .25s ease-out;transition:opacity .25s ease-out;will-change:opacity;direction:ltr}.pswp__preloader__icn{width:20px;height:20px;margin:12px}.pswp__preloader--active{opacity:1}.pswp__preloader--active .pswp__preloader__icn{background:url(./preloader.gif) 0 0 no-repeat}.pswp--css_animation .pswp__preloader--active{opacity:1}.pswp--css_animation .pswp__preloader--active .pswp__preloader__icn{-webkit-animation:clockwise .5s linear infinite;animation:clockwise .5s linear infinite}.pswp--css_animation .pswp__preloader--active .pswp__preloader__donut{-webkit-animation:donut-rotate 1s cubic-bezier(.4,0,.22,1) infinite;animation:donut-rotate 1s cubic-bezier(.4,0,.22,1) infinite}.pswp--css_animation .pswp__preloader__icn{background:none;opacity:.75;width:14px;height:14px;position:absolute;left:15px;top:15px;margin:0}.pswp--css_animation .pswp__preloader__cut{position:relative;width:7px;height:14px;overflow:hidden}.pswp--css_animation .pswp__preloader__donut{-webkit-box-sizing:border-box;box-sizing:border-box;width:14px;height:14px;border:2px solid #fff;border-radius:50%;border-left-color:transparent;border-bottom-color:transparent;position:absolute;top:0;left:0;background:none;margin:0}@media screen and (max-width:1024px){.pswp__preloader{position:relative;left:auto;top:auto;margin:0;float:right}}@-webkit-keyframes clockwise{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes clockwise{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes donut-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}50%{-webkit-transform:rotate(-140deg);transform:rotate(-140deg)}to{-webkit-transform:rotate(0);transform:rotate(0)}}@keyframes donut-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}50%{-webkit-transform:rotate(-140deg);transform:rotate(-140deg)}to{-webkit-transform:rotate(0);transform:rotate(0)}}.pswp__ui{-webkit-font-smoothing:auto;visibility:visible;opacity:1;z-index:1550}.pswp__top-bar{position:absolute;left:0;top:0;height:44px;width:100%}.pswp--has_mouse .pswp__button--arrow--left,.pswp--has_mouse .pswp__button--arrow--right,.pswp__caption,.pswp__top-bar{-webkit-backface-visibility:hidden;will-change:opacity;-webkit-transition:opacity 333ms cubic-bezier(.4,0,.22,1);transition:opacity 333ms cubic-bezier(.4,0,.22,1)}.pswp--has_mouse .pswp__button--arrow--left,.pswp--has_mouse .pswp__button--arrow--right{visibility:visible}.pswp__caption,.pswp__top-bar{background-color:rgba(0,0,0,.5)}.pswp__ui--fit .pswp__caption,.pswp__ui--fit .pswp__top-bar{background-color:rgba(0,0,0,.3)}.pswp__ui--idle .pswp__button--arrow--left,.pswp__ui--idle .pswp__button--arrow--right,.pswp__ui--idle .pswp__top-bar{opacity:0}.pswp__ui--hidden .pswp__button--arrow--left,.pswp__ui--hidden .pswp__button--arrow--right,.pswp__ui--hidden .pswp__caption,.pswp__ui--hidden .pswp__top-bar{opacity:.001}.pswp__ui--one-slide .pswp__button--arrow--left,.pswp__ui--one-slide .pswp__button--arrow--right,.pswp__ui--one-slide .pswp__counter{display:none}.pswp__element--disabled{display:none!important}.pswp--minimal--dark .pswp__top-bar{background:none}\n```"
}
] |
code_store-components_4cdbef70
|
[
{
"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-components/react/components/ProductImages/components/Gallery/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport Gallery from './Gallery'\n\nexport default Gallery\n\n```"
}
] |
code_store-components_6efaa167
|
[
{
"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-components/react/components/ProductImages/components/Gallery/Gallery.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo } from 'react'\nimport { PhotoSwipe } from 'react-photoswipe'\n\nimport './global.css'\n\nconst Gallery = ({ items, isOpen, index, handleClose, bgOpacity }) => {\n const toPswItem = item => ({\n src: item.urls[item.bestUrlIndex],\n w: 1280,\n h: 1280,\n title: item.alt,\n thumbnail: item.thumbUrl,\n })\n\n return (\n <PhotoSwipe\n isOpen={isOpen}\n items={useMemo(() => items.map(toPswItem), [items])}\n onClose={handleClose}\n options={{ index, bgOpacity, history: false }}\n />\n )\n}\n\nexport default Gallery\n\n```"
}
] |
code_store-components_f1f7118a
|
[
{
"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-components/react/components/ProductImages/components/Zoomable/index.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, ReactElement } from 'react'\nimport { Modal } from 'vtex.modal-layout'\nimport { useDevice } from 'vtex.device-detector'\n\nimport ZoomInPlace from './ZoomInPlace'\nimport ModalZoom from './ModalZoom'\n\nexport type ZoomMode =\n | 'in-place-click'\n | 'in-place-hover'\n | 'disabled'\n | 'open-modal'\n\ninterface Props {\n mode?: ZoomMode\n zoomContent?: ReactElement\n factor?: number\n ModalZoomElement?: typeof Modal\n}\n\nconst Zoomable: FC<Props> = ({\n children,\n factor = 2,\n zoomContent,\n ModalZoomElement,\n mode = 'in-place-click',\n}) => {\n const { isMobile } = useDevice()\n\n if (isMobile && mode !== 'disabled' && mode !== 'open-modal') {\n // TODO: Good enough for now, but needs to be a gallery in the future.\n // Preferably photoswipe.com\n return (\n <ZoomInPlace type=\"click\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n }\n\n switch (mode) {\n case 'in-place-hover':\n return (\n <ZoomInPlace type=\"hover\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n\n case 'in-place-click':\n return (\n <ZoomInPlace type=\"click\" factor={factor} zoomContent={zoomContent}>\n {children}\n </ZoomInPlace>\n )\n\n case 'open-modal': {\n if (ModalZoomElement) {\n return (\n <ModalZoom ModalZoomElement={ModalZoomElement}>{children}</ModalZoom>\n )\n }\n }\n // falls through\n\n case 'disabled':\n // falls through\n\n default:\n return <>{children}</>\n }\n}\n\nexport default Zoomable\n\n```"
}
] |
code_store-components_37bbaf22
|
[
{
"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-components/react/components/ProductImages/components/Zoomable/ModalZoom.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ModalTrigger, Modal } from 'vtex.modal-layout'\n\ninterface Props {\n children: React.ReactNode\n ModalZoomElement: typeof Modal\n}\n\nfunction ModalZoom(props: Props) {\n const { children, ModalZoomElement } = props\n\n return (\n <ModalTrigger>\n {children}\n <ModalZoomElement />\n </ModalTrigger>\n )\n}\n\nexport default ModalZoom\n\n```"
}
] |
code_store-components_bb855e2c
|
[
{
"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-components/react/components/ProductImages/components/Zoomable/ZoomInPlace.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useRef, useState, useEffect, ReactElement } from 'react'\nimport { clamp } from 'ramda'\n\ninterface ContainerBounds {\n x: number\n y: number\n width: number\n height: number\n}\n\ntype ZoomType = 'click' | 'hover'\n\ninterface Props {\n type: ZoomType\n zoomContent?: ReactElement\n factor: number\n}\n\ntype ReactMouseEvent = MouseEvent | React.MouseEvent<HTMLElement, MouseEvent>\n\nconst getBounds = (element?: Element | null): ContainerBounds | null => {\n if (!element) return null\n\n const bounds = element.getBoundingClientRect()\n\n return {\n x: bounds.left,\n y: bounds.top,\n width: bounds.width,\n height: bounds.height,\n }\n}\n\nconst getMousePositionFromEvent = (\n event: ReactMouseEvent,\n bounds?: ContainerBounds | null\n): { x: number; y: number; isOutOfBounds?: boolean } => {\n if (!bounds) {\n return { x: 0, y: 0 }\n }\n\n const [x, y] = [event.clientX - bounds.x, event.clientY - bounds.y]\n\n const threshold = 20\n /* Uses out-of-bounds detection instead of simply a \"mouse-out\" event\n * to prevent from zooming out when the mouse hovers a button or suchlike */\n const isOutOfBounds =\n x < -threshold ||\n y < -threshold ||\n x > bounds.width + threshold ||\n y > bounds.height + threshold\n\n // Values larger than 0 increase mouse movement sensivity\n const boost = 0.1\n\n return {\n x: clamp(0, bounds.width, -bounds.width * boost + x * (1 + boost * 2)),\n y: clamp(0, bounds.height, -bounds.height * boost + y * (1 + boost * 2)),\n isOutOfBounds,\n }\n}\n\nconst ZoomInPlace: FC<Props> = ({ children, zoomContent, type, factor }) => {\n const [isZoomedIn, setZoom] = useState(false)\n\n const containerRef = useRef<HTMLDivElement>(null)\n const contentRef = useRef<HTMLDivElement>(null)\n\n const containerBounds = useRef<ContainerBounds | null>(null)\n\n const setPositionAndScale = (x: number, y: number, scale: number) => {\n const contentElement = contentRef.current\n\n if (!contentElement) {\n return\n }\n\n contentElement.style.transform = `scale(${scale}, ${scale}) translate3d(${\n -x / scale\n }px, ${-y / scale}px, 0)`\n }\n\n const getContainerBounds = () =>\n containerBounds.current ?? getBounds(containerRef.current)\n\n const handleMouseOver = () => {\n setZoom(true)\n }\n\n const handleClick = (event: ReactMouseEvent) => {\n setZoom(!isZoomedIn)\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (!isZoomedIn) {\n const mousePosition = getMousePositionFromEvent(\n event,\n getContainerBounds()\n )\n\n setPositionAndScale(mousePosition.x, mousePosition.y, factor)\n }\n }\n\n // Resets position when the image is zoomed out\n useEffect(() => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (!isZoomedIn) {\n setPositionAndScale(0, 0, 1)\n containerBounds.current = null\n }\n }, [isZoomedIn])\n\n /* Adds mouse event handlers to the entire document, so that\n * mouse movement is not restricted to just the content element */\n const handleClickOutside = (event: MouseEvent) => {\n if (!isZoomedIn) {\n return\n }\n\n const isDescendant =\n containerRef.current &&\n event.target &&\n containerRef.current.contains?.(event.target as Node)\n\n if (isDescendant) {\n return\n }\n\n setZoom(false)\n }\n\n const handleMouseMove = (event: ReactMouseEvent) => {\n if (!isZoomedIn) {\n return\n }\n\n const mousePosition = getMousePositionFromEvent(event, getContainerBounds())\n\n /* Uses out-of-bounds detection instead of simply a \"mouse-out\" event\n * to prevent from zooming out when the mouse hovers a button or suchlike */\n if (type === 'hover' && mousePosition.isOutOfBounds) {\n setZoom(false)\n } else {\n setPositionAndScale(mousePosition.x, mousePosition.y, factor)\n }\n }\n\n useEffect(() => {\n if (document) {\n document.addEventListener('mousemove', handleMouseMove)\n if (type === 'click') {\n document.addEventListener('click', handleClickOutside)\n }\n }\n\n return () => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (document) {\n document.removeEventListener('mousemove', handleMouseMove)\n if (type === 'click') {\n document.removeEventListener('click', handleClickOutside)\n }\n }\n }\n })\n\n return (\n // eslint-disable-next-line jsx-a11y/click-events-have-key-events\n <div\n ref={containerRef}\n onMouseOver={type === 'hover' ? handleMouseOver : undefined}\n onClick={type === 'click' ? handleClick : undefined}\n className=\"relative\"\n >\n <div\n ref={contentRef}\n style={{\n transformOrigin: '0 0',\n fontSize: 0,\n /** Prevents accidental whitespaces on the content from stretching\n * the container, and consequently the zoomed image */\n }}\n >\n {children}\n {zoomContent && isZoomedIn && (\n <div\n className=\"absolute top-0 left-0 right-0 bottom-0\"\n style={{\n transformOrigin: '0 0',\n transform: `scale(${1 / factor})`,\n fontSize: 0,\n }}\n >\n {zoomContent}\n </div>\n )}\n </div>\n </div>\n )\n}\n\nexport default ZoomInPlace\n\n```"
}
] |
code_store-components_28159bef
|
[
{
"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-components/react/components/ProductImages/components/Carousel/ThumbnailSwiper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useMemo } from 'react'\nimport classNames from 'classnames'\nimport { useCssHandles, applyModifiers } from 'vtex.css-handles'\nimport { Swiper, SwiperSlide } from 'swiper/react'\nimport { IconCaret } from 'vtex.store-icons'\n\nimport { THUMB_SIZE } from '../../../module/images'\nimport { THUMBS_POSITION_HORIZONTAL } from '../../utils/enums'\nimport { imageUrl } from '../../utils/aspectRatioUtil'\nimport styles from '../../styles.css'\n\nconst THUMB_MAX_SIZE = 256\n\nconst CSS_HANDLES = [\n 'figure',\n 'thumbImg',\n 'thumbVid',\n 'productImagesThumb',\n 'carouselThumbBorder',\n 'carouselGaleryThumbs',\n 'productImagesThumbCaret',\n]\n\nconst Thumbnail = props => {\n const { alt, isVideo, thumbUrl, handles, aspectRatio = 'auto' } = props\n\n return (\n <>\n <figure\n className={`${applyModifiers(handles.figure, isVideo ? 'video' : '')}`}\n itemProp=\"associatedMedia\"\n itemScope\n itemType=\"http://schema.org/ImageObject\"\n >\n <img\n className={`${applyModifiers(\n handles.thumbImg,\n isVideo ? 'video' : ''\n )} w-100 h-auto db`}\n itemProp=\"thumbnail\"\n alt={alt}\n src={imageUrl(thumbUrl, THUMB_SIZE, THUMB_MAX_SIZE, aspectRatio)}\n />\n </figure>\n <div\n className={`absolute absolute--fill b--solid b--muted-2 bw0 ${handles.carouselThumbBorder}`}\n />\n </>\n )\n}\n\nconst navigationConfig = {\n prevEl: '.swiper-thumbnails-caret-prev',\n nextEl: '.swiper-thumbnails-caret-next',\n disabledClass: `c-disabled o-0 pointer-events-none ${styles.carouselCursorDefault}`,\n hiddenClass: 'dn',\n}\n\nconst ThumbnailSwiper = props => {\n const { handles } = useCssHandles(CSS_HANDLES)\n\n const {\n isThumbsVertical,\n slides,\n thumbUrls,\n position,\n thumbnailAspectRatio,\n thumbnailMaxHeight,\n displayThumbnailsArrows,\n ...swiperProps\n } = props\n\n const hasThumbs = slides.length > 1\n\n const thumbClassName = classNames(\n `${handles.carouselGaleryThumbs} dn h-auto`,\n {\n 'db-ns': hasThumbs,\n mt3: !isThumbsVertical,\n 'w-20 bottom-0 top-0 absolute': isThumbsVertical,\n 'left-0':\n isThumbsVertical && position === THUMBS_POSITION_HORIZONTAL.LEFT,\n 'right-0':\n isThumbsVertical && position === THUMBS_POSITION_HORIZONTAL.RIGHT,\n }\n )\n\n const itemContainerClassName = classNames(\n handles.productImagesThumb,\n 'mb5 pointer',\n {\n 'w-20': !isThumbsVertical,\n 'w-100': isThumbsVertical,\n }\n )\n\n const arrows = useMemo(() => {\n if (!displayThumbnailsArrows) {\n return null\n }\n\n const thumbCaretSize = 24\n const thumbCaretClassName = `${handles.productImagesThumbCaret} absolute z-2 pointer c-action-primary flex pv2`\n const thumbCaretStyle = { transition: 'opacity 0.2s' }\n\n const nextBtnClassName = classNames(\n 'swiper-thumbnails-caret-next',\n thumbCaretClassName,\n {\n [`bottom-0 pt7 left-0 justify-center w-100 ${styles.gradientBaseBottom}`]:\n isThumbsVertical,\n [`right-0 top-0 items-center h-100 pl6 ${styles.gradientBaseRight}`]:\n !isThumbsVertical,\n }\n )\n\n const prevBtnClassName = classNames(\n 'swiper-thumbnails-caret-prev top-0 left-0',\n thumbCaretClassName,\n isThumbsVertical && `pb7 justify-center w-100 ${styles.gradientBaseTop}`,\n !isThumbsVertical && `items-center h-100 pr6 ${styles.gradientBaseLeft}`\n )\n\n return (\n <Fragment key=\"navigation-arrows\">\n <span className={nextBtnClassName} style={thumbCaretStyle}>\n <IconCaret\n orientation={isThumbsVertical ? 'down' : 'right'}\n size={thumbCaretSize}\n />\n </span>\n <span className={prevBtnClassName} style={thumbCaretStyle}>\n <IconCaret\n orientation={isThumbsVertical ? 'up' : 'left'}\n size={thumbCaretSize}\n />\n </span>\n </Fragment>\n )\n }, [\n displayThumbnailsArrows,\n handles.productImagesThumbCaret,\n isThumbsVertical,\n ])\n\n return (\n <div className={thumbClassName} data-testid=\"thumbnail-swiper\">\n <Swiper\n className={`h-100 ${handles.productImagesThumbsSwiperContainer}`}\n slidesPerView=\"auto\"\n touchRatio={1}\n threshold={8}\n navigation={navigationConfig}\n /* Slides are grouped when thumbnails arrows are enabled\n * so that clicking on next/prev will scroll more than\n * one thumbnail */\n slidesPerGroup={displayThumbnailsArrows ? 4 : 1}\n freeMode={false}\n mousewheel={false}\n zoom={false}\n watchSlidesVisibility\n watchSlidesProgress\n preloadImages\n updateOnWindowResize\n direction={isThumbsVertical ? 'vertical' : 'horizontal'}\n {...swiperProps}\n >\n {slides.map((slide, i) => {\n return (\n <SwiperSlide\n key={`${i}-${slide.alt}`}\n className={itemContainerClassName}\n style={{\n height: isThumbsVertical ? 'auto' : '115px',\n maxHeight: thumbnailMaxHeight || 'unset',\n position: 'relative',\n }}\n >\n <Thumbnail\n isVideo={slide.type === 'video'}\n index={i}\n handles={handles}\n alt={slide.alt}\n thumbUrl={slide.thumbUrl || thumbUrls[i]}\n aspectRatio={thumbnailAspectRatio}\n />\n </SwiperSlide>\n )\n })}\n {arrows}\n </Swiper>\n </div>\n )\n}\n\nexport default ThumbnailSwiper\n\n```"
}
] |
code_store-components_b1620476
|
[
{
"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-components/react/components/ProductImages/components/Carousel/swiper.scoped.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.carouselGaleryCursor {\n cursor: url(./cursor.svg) 8 8, default;\n}\n\n.carouselGaleryThumbs :global(.swiper-slide) {\n height: auto;\n}\n\n.carouselIconCaretRight,\n.carouselIconCaretLeft {\n stroke: white;\n stroke-width: 0.5px;\n -webkit-filter: drop-shadow(0px 1px 1px #cacbcc);\n filter: drop-shadow(0px 1px 1px #cacbcc);\n}\n\n.carouselCursorDefault:hover {\n cursor: default;\n}\n\n.carouselImagePlaceholder {\n}\n\n/* pagination */\n.swiper-pagination {\n position: absolute;\n text-align: center;\n transition: 300ms opacity;\n transform: translate3d(0, 0, 0);\n z-index: 10;\n}\n\n.swiper-pagination:global(.swiper-pagination-hidden) {\n opacity: 0;\n}\n\n/* Bullets */\n.swiperBullet {\n width: 8px;\n height: 8px;\n display: inline-block;\n border-radius: 100%;\n background: #000;\n opacity: 0.2;\n}\n\nbutton.swiperBullet {\n border: none;\n margin: 0;\n padding: 0;\n box-shadow: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n\n.swiperPaginationClickable .swiperBullet {\n cursor: pointer;\n}\n\n.swiperBullet--active {\n opacity: 1;\n background-color: currentColor;\n}\n\n:global(.swiper-container-vertical > .swiper-pagination-bullets) {\n right: 10px;\n top: 50%;\n transform: translate3d(0px, -50%, 0);\n}\n\n:global(.swiper-container-vertical > .swiper-pagination-bullets) .swiperBullet {\n margin: 6px 0;\n display: block;\n}\n\n:global(.swiper-container-horizontal > .swiper-pagination-bullets)\n .swiperBullet {\n margin: 0 4px;\n}\n\n```"
}
] |
code_store-components_73ae66a1
|
[
{
"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-components/react/components/ProductImages/components/Carousel/ImagePlaceholder.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\n\nimport style from '../../styles.css'\n\nconst ImagePlaceholder: FC = () => {\n return (\n <div className=\"relative\" data-testid=\"default-image-placeholder\">\n <div\n className={`${style.carouselImagePlaceholder} absolute w-100 contain bg-center`}\n />\n <svg\n width=\"100%\"\n viewBox=\"0 0 512 512\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <rect width=\"512\" height=\"512\" fill=\"#F2F2F2\" />\n <rect\n x=\"183.857\"\n y=\"180.2\"\n width=\"144.286\"\n height=\"150.474\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n />\n <path d=\"M183.78 303.688H328.214\" stroke=\"#CACBCC\" strokeWidth=\"2\" />\n <path\n d=\"M205.082 279.563L223.599 240.507L242.116 260.035L269.892 220.979L306.926 279.563H205.082Z\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M252.225 213.939C252.225 219.822 247.66 224.52 242.114 224.52C236.569 224.52 232.004 219.822 232.004 213.939C232.004 208.057 236.569 203.359 242.114 203.359C247.66 203.359 252.225 208.057 252.225 213.939Z\"\n stroke=\"#CACBCC\"\n strokeWidth=\"2\"\n />\n </svg>\n </div>\n )\n}\n\nexport default ImagePlaceholder\n\n```"
}
] |
code_store-components_343db828
|
[
{
"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-components/react/components/ProductImages/components/Carousel/overrides.global.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/** \n * This is a quick-and-dirty fix to avoid `w-20` token from being\n * overwritten by `width: 100%;` set by `swiper-slide`.\n*/\n.w-20.w-20.w-20 {\n width: 20%;\n}\n\n@media screen and (min-width: 40em) {\n .ml-20-ns {\n margin-left: 20%;\n }\n}\n\n.center-all {\n margin: auto;\n}\n\n.border-box {\n box-sizing: border-box;\n}\n\n.top-50 {\n top: 50%;\n}\n\n.translate--50y {\n transform: translate(0, -50%);\n}\n\n.pointer-events-none {\n pointer-events: none;\n}\n\n```"
}
] |
code_store-components_6d57c499
|
[
{
"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-components/react/components/ProductImages/components/Carousel/swiper.global.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n * Swiper 6.1.1\n * Most modern mobile touch slider and framework with hardware accelerated transitions\n * http://swiperjs.com\n *\n * Copyright 2014-2020 Vladimir Kharlampidi\n *\n * Released under the MIT License\n *\n * Released on: July 31, 2020\n */\n\n.swiper-container {\n margin-left: auto;\n margin-right: auto;\n position: relative;\n overflow: hidden;\n list-style: none;\n padding: 0;\n /* Fix of Webkit flickering */\n z-index: 1;\n}\n\n.swiper-container-vertical > .swiper-wrapper {\n flex-direction: column;\n align-items: center;\n}\n\n.swiper-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n z-index: 1;\n display: flex;\n transition-property: transform;\n box-sizing: content-box;\n}\n\n.swiper-container-android .swiper-slide,\n.swiper-wrapper {\n transform: translate3d(0px, 0, 0);\n}\n\n.swiper-container-multirow > .swiper-wrapper {\n flex-wrap: wrap;\n}\n\n.swiper-container-multirow-column > .swiper-wrapper {\n flex-wrap: wrap;\n flex-direction: column;\n}\n\n.swiper-container-free-mode > .swiper-wrapper {\n transition-timing-function: ease-out;\n margin: 0 auto;\n}\n\n.swiper-slide {\n flex-shrink: 0;\n width: 100%;\n height: 100%;\n position: relative;\n transition-property: transform;\n}\n\n.swiper-slide-invisible-blank {\n visibility: hidden;\n}\n\n/* Auto Height */\n.swiper-container-autoheight,\n.swiper-container-autoheight .swiper-slide {\n height: auto;\n}\n\n.swiper-container-autoheight .swiper-wrapper {\n align-items: flex-start;\n transition-property: transform, height;\n}\n\n.swiper-button-prev,\n.swiper-button-next {\n position: absolute;\n top: 50%;\n width: 27px;\n height: 44px;\n margin-top: -22px;\n z-index: 10;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #0f3e99;\n}\n\n.swiper-button-prev.swiper-button-disabled,\n.swiper-button-next.swiper-button-disabled {\n opacity: 0.35;\n cursor: auto;\n pointer-events: none;\n}\n\n.swiper-button-prev,\n.swiper-container-rtl .swiper-button-next {\n left: 10px;\n right: auto;\n}\n\n.swiper-button-next,\n.swiper-container-rtl .swiper-button-prev {\n right: 10px;\n left: auto;\n}\n\n.swiper-button-lock {\n display: none;\n}\n\n.swiper-container-horizontal > .swiper-pagination-bullets {\n bottom: 10px;\n left: 0;\n width: 100%;\n}\n\n/* Preloader */\n.swiper-lazy-preloader {\n width: 42px;\n height: 42px;\n position: absolute;\n left: 50%;\n top: 50%;\n margin-left: -21px;\n margin-top: -21px;\n z-index: 10;\n transform-origin: 50%;\n animation: swiper-preloader-spin 1s infinite linear;\n box-sizing: border-box;\n border: 4px solid #0f3e99;\n border-radius: 50%;\n border-top-color: transparent;\n}\n\n@keyframes swiper-preloader-spin {\n 100% {\n transform: rotate(360deg);\n }\n}\n\n```"
}
] |
code_store-components_da6d3bff
|
[
{
"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-components/react/components/ProductImages/components/Carousel/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable react/prop-types */\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport { path, equals } from 'ramda'\nimport { IconCaret } from 'vtex.store-icons'\nimport { withCssHandles } from 'vtex.css-handles'\nimport SwiperCore, { Thumbs, Navigation, Pagination } from 'swiper'\nimport { Swiper, SwiperSlide } from 'swiper/react'\n\nimport Video, { getThumbUrl } from '../Video'\nimport ProductImage from '../ProductImage'\nimport ThumbnailSwiper from './ThumbnailSwiper'\nimport ImagePlaceholder from './ImagePlaceholder'\nimport {\n THUMBS_ORIENTATION,\n THUMBS_POSITION_HORIZONTAL,\n THUMBS_VISIBILITY,\n} from '../../utils/enums'\nimport styles from './swiper.scoped.css'\n\nimport './swiper.global.css'\nimport './overrides.global.css'\n\nconst CARET_ICON_SIZE = 24\nconst CARET_CLASSNAME =\n 'pv8 absolute top-50 translate--50y z-2 pointer c-action-primary'\n\n// install Swiper's Thumbs component\nSwiperCore.use([Thumbs, Navigation, Pagination])\n\nconst CSS_HANDLES = [\n 'carouselContainer',\n 'productImagesThumbsSwiperContainer',\n 'productImagesThumbActive',\n 'productImagesGallerySwiperContainer',\n 'productImagesGallerySlide',\n 'swiperCaret',\n 'swiperCaretNext',\n 'swiperCaretPrev',\n]\n\nconst initialState = {\n thumbUrl: [],\n alt: [],\n activeIndex: 0,\n}\n\nclass Carousel extends Component {\n state = {\n ...initialState,\n thumbSwiper: null,\n gallerySwiper: null,\n }\n\n isVideo = []\n\n get hasGallerySwiper() {\n return Boolean(this.state.gallerySwiper)\n }\n\n get hasThumbSwiper() {\n return Boolean(this.state.thumbSwiper)\n }\n\n setInitialVariablesState() {\n const slides = this.props.slides || []\n\n this.isVideo = []\n\n slides.forEach(async (slide, i) => {\n if (slide.type === 'video') {\n const thumbUrl = await getThumbUrl(slide.src, slide.thumbWidth)\n\n this.isVideo[i] = true\n this.setVideoThumb(i)(thumbUrl)\n } else {\n // Image object doesn't exist when it's being rendered in the server side\n if (!window.navigator) {\n return\n }\n\n const image = new Image()\n\n image.src = slide.thumbUrl\n }\n })\n }\n\n componentDidMount() {\n this.setInitialVariablesState()\n }\n\n componentDidUpdate(prevProps) {\n const { activeIndex } = this.state\n const { isVideo } = this\n\n if (!equals(prevProps.slides, this.props.slides)) {\n this.setInitialVariablesState()\n\n if (\n !this.props.slides ||\n this.state.gallerySwiper?.destroyed ||\n this.state.thumbSwiper?.destroyed\n ) {\n return\n }\n\n this.state.gallerySwiper?.slideTo(initialState.activeIndex)\n this.state.thumbSwiper?.slideTo(initialState.activeIndex)\n\n this.setState({\n ...initialState,\n })\n\n return\n }\n\n const paginationElement = path(\n ['swiper', 'pagination', 'el'],\n this.state.gallerySwiper\n )\n\n if (paginationElement) {\n paginationElement.hidden = isVideo[activeIndex]\n }\n }\n\n handleSlideChange = () => {\n this.setState(prevState => {\n if (!this.hasGallerySwiper) {\n return\n }\n\n const { activeIndex } = prevState.gallerySwiper\n\n return { activeIndex, sliderChanged: true }\n })\n }\n\n setVideoThumb = i => (url, title) => {\n this.setState(prevState => {\n const thumbUrl = { ...prevState.thumbUrl }\n const alt = { ...prevState.alt }\n\n thumbUrl[i] = url\n alt[i] = title\n\n return { thumbUrl, alt }\n })\n }\n\n renderSlide = (slide, i) => {\n const {\n aspectRatio,\n maxHeight,\n zoomMode,\n zoomFactor,\n ModalZoomElement,\n zoomProps: legacyZoomProps,\n } = this.props\n\n // Backwards compatibility\n const { zoomType: legacyZoomType } = legacyZoomProps || {}\n const isZoomDisabled =\n legacyZoomType === 'no-zoom' || zoomMode === 'disabled'\n\n switch (slide.type) {\n case 'image':\n return (\n <ProductImage\n index={i}\n src={slide.url}\n alt={slide.alt}\n imageLabel={slide.imageLabel}\n maxHeight={maxHeight}\n zoomFactor={zoomFactor}\n aspectRatio={aspectRatio}\n ModalZoomElement={ModalZoomElement}\n zoomMode={isZoomDisabled ? 'disabled' : zoomMode}\n />\n )\n\n case 'video':\n return i === this.state.activeIndex ? (\n <Video\n url={slide.src}\n setThumb={this.setVideoThumb(i)}\n playing={i === this.state.activeIndex}\n id={i}\n />\n ) : (\n <div />\n )\n\n default:\n return null\n }\n }\n\n get galleryParams() {\n const { handles, slides = [], showPaginationDots = true } = this.props\n\n const params = {}\n\n if (slides.length > 1 && showPaginationDots) {\n params.pagination = {\n el: `.${styles['swiper-pagination']}`,\n clickable: true,\n clickableClass: styles.swiperPaginationClickable,\n bulletClass: styles.swiperBullet,\n bulletActiveClass: styles['swiperBullet--active'],\n renderBullet(_index, className) {\n return `<span class=\"${className} c-action-primary\"></span>`\n },\n }\n }\n\n if (slides.length > 1) {\n params.navigation = {\n prevEl: '.swiper-caret-prev',\n nextEl: '.swiper-caret-next',\n disabledClass: `c-disabled ${styles.carouselCursorDefault}`,\n }\n }\n\n params.thumbs = {\n swiper: this.state.thumbSwiper,\n multipleActiveThumbs: false,\n slideThumbActiveClass: handles.productImagesThumbActive,\n }\n\n return params\n }\n\n render() {\n const {\n aspectRatio,\n maxHeight,\n placeholder,\n position,\n handles,\n slides = [],\n thumbnailMaxHeight,\n thumbnailAspectRatio,\n thumbnailsOrientation,\n zoomProps: { zoomType },\n showPaginationDots = true,\n showNavigationArrows = true,\n thumbnailVisibility,\n displayThumbnailsArrows = false,\n } = this.props\n\n const hasSlides = slides && slides.length > 0\n\n const isThumbsVertical =\n thumbnailsOrientation === THUMBS_ORIENTATION.VERTICAL\n\n const hasThumbs = slides && slides.length > 1\n\n const galleryCursor = {\n 'in-page': styles.carouselGaleryCursor,\n 'no-zoom': '',\n }\n\n const imageClasses = classNames(\n 'w-100 border-box',\n galleryCursor[hasSlides ? zoomType : 'no-zoom'],\n {\n 'ml-20-ns w-80-ns pl5-ns':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.LEFT &&\n ((hasThumbs && thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE) ||\n !hasSlides),\n 'mr-20-ns w-80-ns pr5-ns':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.RIGHT &&\n ((hasThumbs && thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE) ||\n !hasSlides),\n }\n )\n\n if (!hasSlides) {\n return (\n <div className={imageClasses}>\n {placeholder ? (\n <ProductImage\n src={placeholder}\n alt=\"Product image placeholder\"\n maxHeight={maxHeight}\n aspectRatio={aspectRatio}\n zoomMode=\"disabled\"\n />\n ) : (\n <ImagePlaceholder />\n )}\n </div>\n )\n }\n\n const containerClasses = classNames(\n handles.carouselContainer,\n 'relative overflow-hidden w-100',\n {\n 'flex-ns justify-end-ns':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.LEFT &&\n hasThumbs &&\n thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE,\n 'flex-ns justify-start-ns':\n isThumbsVertical &&\n position === THUMBS_POSITION_HORIZONTAL.RIGHT &&\n hasThumbs &&\n thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE,\n }\n )\n\n const thumbnailSwiper = (\n <ThumbnailSwiper\n onSwiper={instance => this.setState({ thumbSwiper: instance })}\n isThumbsVertical={isThumbsVertical}\n thumbnailAspectRatio={thumbnailAspectRatio}\n thumbnailMaxHeight={thumbnailMaxHeight}\n thumbUrls={this.state.thumbUrl}\n displayThumbnailsArrows={displayThumbnailsArrows}\n slides={slides}\n position={position}\n />\n )\n\n return (\n <div className={containerClasses} aria-hidden=\"true\">\n {isThumbsVertical &&\n thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE &&\n thumbnailSwiper}\n <div className={imageClasses}>\n {!this.state.thumbSwiper?.destroyed && (\n <Swiper\n onSwiper={instance => this.setState({ gallerySwiper: instance })}\n className={handles.productImagesGallerySwiperContainer}\n threshold={10}\n resistanceRatio={slides.length > 1 ? 0.85 : 0}\n onSlideChange={this.handleSlideChange}\n updateOnWindowResize\n {...this.galleryParams}\n >\n {slides.map((slide, i) => (\n <SwiperSlide\n key={`slider-${i}`}\n className={`${handles.productImagesGallerySlide} swiper-slide center-all`}\n >\n {this.renderSlide(slide, i)}\n </SwiperSlide>\n ))}\n\n <div\n key=\"pagination\"\n className={classNames(styles['swiper-pagination'], {\n dn: slides.length === 1 || !showPaginationDots,\n })}\n />\n\n <div\n className={classNames({\n dn: slides.length === 1 || !showNavigationArrows,\n })}\n >\n <span\n key=\"caret-next\"\n className={`swiper-caret-next pl7 pr2 right-0 ${CARET_CLASSNAME} ${handles.swiperCaret} ${handles.swiperCaretNext}`}\n >\n <IconCaret\n orientation=\"right\"\n size={CARET_ICON_SIZE}\n className={styles.carouselIconCaretRight}\n />\n </span>\n <span\n key=\"caret-prev\"\n className={`swiper-caret-prev pr7 pl2 left-0 ${CARET_CLASSNAME} ${handles.swiperCaret} ${handles.swiperCaretPrev}`}\n >\n <IconCaret\n orientation=\"left\"\n size={CARET_ICON_SIZE}\n className={styles.carouselIconCaretLeft}\n />\n </span>\n </div>\n </Swiper>\n )}\n\n {!isThumbsVertical &&\n thumbnailVisibility === THUMBS_VISIBILITY.VISIBLE &&\n thumbnailSwiper}\n </div>\n </div>\n )\n }\n}\n\nCarousel.propTypes = {\n slides: PropTypes.arrayOf(\n PropTypes.shape({\n type: PropTypes.string,\n url: PropTypes.string,\n alt: PropTypes.string,\n thumbUrl: PropTypes.string,\n bestUrlIndex: PropTypes.number,\n })\n ),\n ModalZoomElement: PropTypes.any,\n displayThumbnailsArrows: PropTypes.bool,\n thumbnailVisibility: PropTypes.oneOf([\n THUMBS_VISIBILITY.VISIBLE,\n THUMBS_VISIBILITY.HIDDEN,\n ]),\n}\n\nexport default withCssHandles(CSS_HANDLES)(Carousel)\n\n```"
}
] |
code_store-components_96880686
|
[
{
"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-components/react/components/SKUSelector/types/index.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport type InitialSelectionType = 'complete' | 'image' | 'empty'\n\nexport type DisplayMode = 'select' | 'default' | 'slider'\n\nexport interface SelectorProductItem extends Omit<ProductItem, 'variations'> {\n variations: string[]\n variationValues: Record<string, string>\n}\n\nexport type SelectedVariations = Record<string, string | null>\n\nexport interface CallbackItem {\n name: string\n value: string\n skuId: string | null\n isMainAndImpossible: boolean\n possibleItems: SelectorProductItem[]\n}\n\nexport interface Image {\n imageId: string\n imageLabel: string | null\n imageTag: string\n imageUrl: string\n imageText: string\n}\n\nexport type ImageMap = Record<string, Record<string, Image | undefined>>\n\nexport interface DisplayOption {\n label: string\n originalName: string\n onSelectItem: () => void\n image: Image | undefined\n available: boolean\n impossible: boolean\n disabled: boolean\n}\n\nexport interface DisplayVariation {\n name: string\n originalName: string\n options: DisplayOption[]\n}\n\nexport type Variations = Record<\n string,\n {\n originalName: string\n values: Array<{\n name: string\n originalName: string\n }>\n }\n>\n\n```"
}
] |
code_store-components_aca54739
|
[
{
"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-components/react/components/SKUSelector/utils/proptypes.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport PropTypes from 'prop-types'\n\nexport const skuShape = PropTypes.shape({\n /** Name of the SKU Item */\n name: PropTypes.string.isRequired,\n /** Images of the SKU item */\n images: PropTypes.arrayOf(\n PropTypes.shape({\n /** URL of source Image */\n imageUrl: PropTypes.string.isRequired,\n /** Brief description of the image */\n imageLabel: PropTypes.string,\n })\n ).isRequired,\n /** SkuID */\n itemId: PropTypes.string.isRequired,\n /** List of products specifications names */\n variations: PropTypes.arrayOf(\n PropTypes.shape({\n /** Variation Name */\n name: PropTypes.string,\n /** Variation Values */\n values: PropTypes.arrayOf(PropTypes.string),\n })\n ),\n})\n\nexport const parsedSkuShape = PropTypes.shape({\n ...skuShape,\n /** List of products specifications names */\n variations: PropTypes.arrayOf(PropTypes.string),\n})\n\nexport const variationShape = PropTypes.shape({\n /** Variation Name */\n name: PropTypes.string,\n /** Options Array */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n image: PropTypes.shape({\n imageLabel: PropTypes.string,\n imageUrl: PropTypes.string,\n }),\n available: PropTypes.bool,\n label: PropTypes.string,\n onSelectItem: PropTypes.func,\n impossible: PropTypes.bool,\n })\n ),\n})\n\n```"
}
] |
code_store-components_bcd78a6e
|
[
{
"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-components/react/components/SKUSelector/utils/index.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { clone, filter, prop, reject } from 'ramda'\nimport slugify from 'slugify'\n\nimport { getDefaultSeller } from '../../../utils/sellers'\nimport { SelectedVariations, SelectorProductItem } from '../types'\n\n/**\n * Return the maximum sku price\n * @param {array of sku's} items\n */\nexport const getMaxSkuPrice = (items: SelectorProductItem[]) => {\n if (!items) return 0\n\n return items.reduce((max, sku) => {\n const seller = getDefaultSeller(sku.sellers)\n const price = seller?.commertialOffer.Price ?? 0\n\n return Math.max(max, price)\n }, 0)\n}\n\n/**\n * Remove the 'https' from the given url\n * @param {string} url\n */\nexport const stripUrl = (url: string) => url.replace(/^https?:/, '')\n\n/**\n * Parse the variations field in the sku object\n * @param {sku} sku\n */\nexport const parseSku = (sku: ProductItem) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = clone(sku) as any\n const variationValues = {} as Record<string, string>\n\n for (const variation of sku.variations) {\n variationValues[variation.name] = variation.values[0]\n }\n\n const variations = sku.variations.map(prop('name'))\n\n result.variationValues = variationValues\n result.variations = variations\n\n return result as SelectorProductItem\n}\n\n/**\n * Verifies if the variation is color\n * @param {string} variation\n */\nexport const isColor = (variation: string) => {\n if (!variation) return false\n\n const possibleValues = [\n 'cor',\n 'color',\n 'colour',\n 'colore',\n 'farbe',\n 'couleur',\n 'kleuren',\n 'culoare',\n 'värit',\n 'kolory',\n 'farve',\n 'färger',\n 'farby',\n 'boje',\n 'colori',\n 'tsvyat',\n 'Цвят',\n ]\n\n return possibleValues.includes(variation.toLowerCase())\n}\n\n/**\n * Choose wich variation will be the main one.\n * @param {Array[string]} variations\n */\nexport const getMainVariationName = (variations: string[]) => {\n for (let i = 0; i < variations.length; i++) {\n if (isColor(variations[i])) return variations[i]\n }\n\n return variations[0]\n}\n\n/**\n * Given a selectedVariations, find the first item that has those variations selected\n * selectedVariations format: { \"color\": \"black\", size: \"small\", fabric: null }\n * items: skuItems parsed with variations fields\n * Output: item or null, if not present\n */\nexport const findItemWithSelectedVariations = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations\n) => {\n const selectedNotNull = filter(\n Boolean,\n selectedVariations\n ) as SelectedVariationsNotNull\n\n const selectedCount = Object.keys(selectedNotNull).length\n\n if (selectedCount === 0) {\n // may return any item, return first element\n return items[0]\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return items.find(isSkuSelected(selectedNotNull))\n}\n\n/**\n * Given a selectedVariations, find items that have those variations selected\n * selectedVariations format: { \"color\": \"black\", size: \"small\", fabric: null }\n * items: skuItems parsed with variations fields\n * Output: list of items with those variations\n */\nexport const findListItemsWithSelectedVariations = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations\n) => {\n const selectedNotNull = filter(\n Boolean,\n selectedVariations\n ) as SelectedVariationsNotNull\n\n const selectedCount = Object.keys(selectedNotNull).length\n\n if (selectedCount === 0) {\n // return all\n return items\n }\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return items.filter(isSkuSelected(selectedNotNull))\n}\n\nexport const uniqueOptionToSelect = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations,\n isMainAndImpossible: boolean\n) => {\n const possibleItems = !isMainAndImpossible\n ? items\n : findListItemsWithSelectedVariations(items, selectedVariations)\n\n const unselected = reject(Boolean, selectedVariations)\n const unselectedNames = Object.keys(unselected)\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const availableOptions = buildAvailableVariations(\n possibleItems,\n unselectedNames\n )\n\n const variationsWithOne = filter(\n setValues => setValues.size === 1,\n availableOptions\n )\n\n const variationsNames = Object.keys(variationsWithOne)\n const finalUniqueVariations = {} as Record<string, string>\n\n // Transform set to plain value\n for (const variationName of variationsNames) {\n const { value } = variationsWithOne[variationName].values().next()\n\n finalUniqueVariations[variationName] = value\n }\n\n return finalUniqueVariations\n}\n\nexport function slug(str: string) {\n // eslint-disable-next-line no-useless-escape\n const replaced = str?.replace(/[*+~.()'`’\"!:@&\\[\\]]/g, '') || ''\n const slugified = slugify(replaced, { lower: true }) || ''\n\n return slugified\n}\n\ntype SelectedVariationsNotNull = Record<string, string>\n\n/** Private functions */\nconst isSkuSelected =\n (selectedNotNull: SelectedVariationsNotNull) =>\n (sku: SelectorProductItem) => {\n const hasAll = Object.keys(selectedNotNull).every(variationName => {\n const selectedValue = selectedNotNull[variationName]\n\n return sku.variationValues[variationName] === selectedValue\n })\n\n return hasAll\n }\n\nconst buildAvailableVariations = (\n items: SelectorProductItem[],\n variationNames: string[]\n) => {\n const result = {} as Record<string, Set<string>>\n\n for (const variationName of variationNames) {\n result[variationName] = new Set()\n }\n\n for (const item of items) {\n for (const variationName of variationNames) {\n const variationValue = item.variationValues[variationName]\n const currentSet = result[variationName]\n\n if (variationValue) {\n currentSet.add(variationValue)\n }\n }\n }\n\n return result\n}\n\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n\nexport function cleanImageUrl(imageUrl: string) {\n const result = baseUrlRegex.exec(imageUrl) ?? []\n\n return result.length > 0 ? result[0] : null\n}\n\nfunction replaceLegacyFileManagerUrl(\n imageUrl: string,\n width: number | string,\n height: number | string\n) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n\n if (!isLegacyUrl) return imageUrl\n\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize(\n imageUrl: string,\n width: string | number = DEFAULT_WIDTH,\n height: string | number = 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\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\nexport const DEFAULT_BOTTOM_MARGIN = 7\nconst MAX_POSSIBLE_MARGIN = 11\nconst MIN_POSSIBLE_MARGIN = 0\n\nexport function getValidMarginBottom(variationsSpacing?: number) {\n if (typeof variationsSpacing === 'undefined') {\n return DEFAULT_BOTTOM_MARGIN\n }\n\n return Math.max(\n Math.min(MAX_POSSIBLE_MARGIN, variationsSpacing),\n MIN_POSSIBLE_MARGIN\n )\n}\n\nexport const NO_BOTTOM_MARGIN = 'none'\n\n```"
}
] |
code_store-components_43cd866b
|
[
{
"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-components/react/components/SKUSelector/components/ErrorMessage.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\nimport { useSKUSelectorCssHandles } from '../SKUSelectorCssHandles'\n\nexport const CSS_HANDLES = ['errorMessage'] as const\n\nfunction ErrorMessage() {\n const { handles } = useSKUSelectorCssHandles()\n const className = `${handles.errorMessage} c-danger`\n\n return (\n <FormattedMessage id=\"store/sku-selector.variation.select-an-option\">\n {message => (\n <>\n {' '}\n {/* this space is necessary */}\n <span className={className}>{message}</span>\n </>\n )}\n </FormattedMessage>\n )\n}\n\nexport default ErrorMessage\n\n```"
}
] |
code_store-components_e1f030bf
|
[
{
"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-components/react/components/SKUSelector/components/SKUSelector.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useCallback, memo, useState, useMemo } from 'react'\nimport { filter, clone } from 'ramda'\nimport { ResponsiveValuesTypes } from 'vtex.responsive-values'\n\nimport styles from '../styles.css'\nimport {\n isColor,\n getValidMarginBottom,\n findItemWithSelectedVariations,\n findListItemsWithSelectedVariations,\n} from '../utils'\nimport {\n SelectorProductItem,\n CallbackItem,\n SelectedVariations,\n ImageMap,\n DisplayOption,\n DisplayVariation,\n Variations,\n DisplayMode,\n} from '../types'\nimport Variation from './Variation'\nimport useEffectSkipMount from './hooks/useEffectSkipMount'\nimport { useSKUSelectorCssHandles } from '../SKUSelectorCssHandles'\nimport { getDefaultSeller } from '../../../utils/sellers'\n\nexport type ShowValueForVariation = 'none' | 'image' | 'all'\n\n// The boolean type was kept because for backward compatibility\nexport type ShowVariationsLabels =\n | boolean\n | 'none'\n | 'variation'\n | 'itemValue'\n | 'variationAndItemValue'\n\nfunction getShowValueForVariation(\n showValueForVariation: ShowValueForVariation,\n variationName: string\n) {\n const isImage = isColor(variationName)\n\n return (\n showValueForVariation === 'all' ||\n (showValueForVariation === 'image' && isImage)\n )\n}\n\ninterface Props {\n seeMoreLabel: string\n maxItems: number\n variations: Variations\n skuItems: SelectorProductItem[]\n onSelectItem: (callbackItem: CallbackItem) => void\n imagesMap: ImageMap\n selectedVariations: Record<string, string | null>\n hideImpossibleCombinations: boolean\n disableUnavailableSelectOptions: boolean\n showValueForVariation: ShowValueForVariation\n showBorders?: boolean\n imageHeight?: number\n imageWidth?: number\n showVariationsLabels: ShowVariationsLabels\n variationsSpacing?: number\n showVariationsErrorMessage: boolean\n displayMode: DisplayMode\n sliderDisplayThreshold: number\n sliderArrowSize: number\n sliderItemsPerPage: ResponsiveValuesTypes.ResponsiveValue<number>\n sortVariationsByLabel?: boolean\n}\n\nfunction isSkuAvailable(item?: SelectorProductItem) {\n if (!item) {\n return false\n }\n\n const seller = getDefaultSeller(item.sellers)\n\n if (!seller) {\n return false\n }\n\n return seller.commertialOffer?.AvailableQuantity > 0\n}\n\nfunction sortOptionsNumerically(options: DisplayOption[]) {\n return options.sort((a, b) => parseFloat(a.label) - parseFloat(b.label))\n}\n\nfunction sortOptionsAlphabetically(options: DisplayOption[]) {\n return options.sort((a, b) => {\n if (a.label < b.label) return -1\n if (a.label > b.label) return 1\n\n return 0\n })\n}\n\nconst showItemAsAvailable = ({\n possibleItems,\n selectedVariations,\n variationCount,\n isSelected,\n}: {\n possibleItems: SelectorProductItem[]\n selectedVariations: SelectedVariations\n variationCount: number\n isSelected: boolean\n}) => {\n const selectedNotNull = filter(Boolean, selectedVariations)\n const selectedCount = Object.keys(selectedNotNull).length\n\n if (selectedCount === variationCount && isSelected) {\n const item = findItemWithSelectedVariations(\n possibleItems,\n selectedVariations\n )\n\n return isSkuAvailable(item)\n }\n\n return possibleItems.some(isSkuAvailable)\n}\n\ninterface AvailableVariationParams {\n variations: Variations\n selectedVariations: SelectedVariations\n imagesMap: ImageMap\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n skuItems: SelectorProductItem[]\n hideImpossibleCombinations: boolean\n disableUnavailableSelectOptions: boolean\n sortVariationsByLabel: boolean\n}\n\nexport const orderItemsByAvailability = (\n item1: SelectorProductItem,\n item2: SelectorProductItem\n) => {\n const isAvailableItem1 = isSkuAvailable(item1)\n const isAvailableItem2 = isSkuAvailable(item2)\n\n if (isAvailableItem1 && !isAvailableItem2) {\n return -1\n }\n\n if (!isAvailableItem1 && isAvailableItem2) {\n return 1\n }\n\n const defaultSellerItem1 = getDefaultSeller(item1.sellers)\n const defaultSellerItem2 = getDefaultSeller(item2.sellers)\n\n const availabilityItem1 = defaultSellerItem1\n ? defaultSellerItem1.commertialOffer.AvailableQuantity\n : 0\n\n const availabilityItem2 = defaultSellerItem2\n ? defaultSellerItem2.commertialOffer.AvailableQuantity\n : 0\n\n return availabilityItem2 - availabilityItem1\n}\n\nconst parseOptionNameToDisplayOption =\n ({\n selectedVariations,\n variationName,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n }: {\n selectedVariations: SelectedVariations\n variationName: string\n skuItems: SelectorProductItem[]\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n imagesMap: ImageMap\n variationCount: number\n hideImpossibleCombinations: boolean\n disableUnavailableSelectOptions: boolean\n }) =>\n (variationValue: {\n name: string\n originalName: string\n }): DisplayOption | null => {\n const isSelected = selectedVariations[variationName] === variationValue.name\n const image = imagesMap?.[variationName]?.[variationValue.name]\n\n const newSelectedVariation = clone(selectedVariations)\n\n newSelectedVariation[variationName] = isSelected\n ? null\n : variationValue.name\n\n const possibleItems = findListItemsWithSelectedVariations(\n skuItems,\n newSelectedVariation\n )\n\n if (possibleItems.length > 0) {\n // This is a valid combination option\n\n const possibleItemsOrderedByAvailability =\n possibleItems.length > 1\n ? possibleItems.sort(orderItemsByAvailability)\n : possibleItems\n\n const [item] = possibleItemsOrderedByAvailability\n\n const callbackFn = onSelectItemMemo({\n name: variationName,\n value: variationValue.name,\n skuId: item.itemId,\n isMainAndImpossible: false,\n possibleItems: possibleItemsOrderedByAvailability,\n })\n\n return {\n label: variationValue.name,\n originalName: variationValue.originalName,\n onSelectItem: callbackFn,\n image,\n available: showItemAsAvailable({\n possibleItems: possibleItemsOrderedByAvailability,\n selectedVariations,\n variationCount,\n isSelected,\n }),\n impossible: false,\n disabled: disableUnavailableSelectOptions,\n }\n }\n\n if (!hideImpossibleCombinations) {\n // This is a impossible combination and will only appear if the prop allows.\n return {\n label: variationValue.name,\n originalName: variationValue.originalName,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onSelectItem: () => {},\n image,\n available: true,\n impossible: true,\n disabled: disableUnavailableSelectOptions,\n }\n }\n\n // This is a impossible combination and will be hidden.\n return null\n }\n\nconst variationNameToDisplayVariation =\n ({\n variations,\n selectedVariations,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n sortVariationsByLabel,\n }: {\n variations: Variations\n selectedVariations: SelectedVariations\n skuItems: SelectorProductItem[]\n imagesMap: ImageMap\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n variationCount: number\n hideImpossibleCombinations: boolean\n disableUnavailableSelectOptions: boolean\n sortVariationsByLabel: boolean\n }) =>\n (variationName: string): DisplayVariation => {\n const name = variationName\n const { values, originalName } = variations[variationName]\n let options = values\n .map(\n parseOptionNameToDisplayOption({\n selectedVariations,\n variationName,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n })\n )\n .filter(Boolean) as DisplayOption[]\n\n if (sortVariationsByLabel) {\n const areAllNumbers = options.every(\n (option: DisplayOption) => !Number.isNaN(Number(option.label))\n )\n\n const sortedOptions = areAllNumbers\n ? sortOptionsNumerically([...options])\n : sortOptionsAlphabetically([...options])\n\n options = [...sortedOptions]\n }\n\n return { name, originalName, options }\n }\n\n// Parameters are explained on PropTypes\nconst getAvailableVariations = ({\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n sortVariationsByLabel,\n}: AvailableVariationParams): DisplayVariation[] => {\n const variationCount = Object.keys(variations).length\n\n return Object.keys(variations).map(\n variationNameToDisplayVariation({\n variations,\n selectedVariations,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n sortVariationsByLabel,\n })\n )\n}\n\nconst getAvailableVariationsPromise = (\n params: AvailableVariationParams\n): Promise<DisplayVariation[]> => {\n return new Promise(resolve => {\n const result = getAvailableVariations(params)\n\n resolve(result)\n })\n}\n\nexport const CSS_HANDLES = ['skuSelectorContainer'] as const\n\n/** Renders the main and the secondary variation, if it exists. */\nfunction SKUSelector({\n seeMoreLabel,\n maxItems,\n variations,\n skuItems,\n onSelectItem,\n imagesMap,\n imageHeight,\n imageWidth,\n showBorders,\n displayMode,\n selectedVariations,\n showVariationsLabels,\n showValueForVariation,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n showVariationsErrorMessage,\n variationsSpacing: marginBottomProp,\n sliderDisplayThreshold,\n sliderArrowSize,\n sliderItemsPerPage,\n sortVariationsByLabel = false,\n}: Props) {\n const { handles } = useSKUSelectorCssHandles()\n const variationsSpacing = getValidMarginBottom(marginBottomProp)\n const onSelectItemMemo = useCallback(\n ({\n name,\n value,\n skuId,\n isMainAndImpossible,\n possibleItems,\n }: CallbackItem) =>\n () =>\n onSelectItem({\n name,\n value,\n skuId,\n isMainAndImpossible,\n possibleItems,\n }),\n [onSelectItem]\n )\n\n const availableVariationsPayload = useMemo(\n () => ({\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n sortVariationsByLabel,\n }),\n [\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n disableUnavailableSelectOptions,\n sortVariationsByLabel,\n ]\n )\n\n const [displayVariations, setDisplayVariations] = useState<\n DisplayVariation[]\n >(() => getAvailableVariations(availableVariationsPayload))\n\n useEffectSkipMount(() => {\n let isCurrent = true\n const promise = getAvailableVariationsPromise(availableVariationsPayload)\n\n promise.then(availableVariations => {\n if (isCurrent) {\n setDisplayVariations(availableVariations)\n }\n })\n\n return () => {\n isCurrent = false\n }\n }, [availableVariationsPayload])\n\n const variationClasses = `mb${variationsSpacing}`\n\n return (\n <div\n className={`${styles.skuSelectorContainer} ${handles.skuSelectorContainer}`}\n >\n {displayVariations.map((variationOption, index) => {\n const selectedItem = selectedVariations[variationOption.name]\n\n return (\n <Variation\n mode={displayMode}\n maxItems={maxItems}\n imageWidth={imageWidth}\n imageHeight={imageHeight}\n showBorders={showBorders}\n variation={variationOption}\n selectedItem={selectedItem}\n seeMoreLabel={seeMoreLabel}\n showLabel={showVariationsLabels}\n containerClasses={variationClasses}\n key={`${variationOption.name}-${index}`}\n showErrorMessage={showVariationsErrorMessage}\n showValueForVariation={getShowValueForVariation(\n showValueForVariation,\n variationOption.name\n )}\n sliderDisplayThreshold={sliderDisplayThreshold}\n sliderArrowSize={sliderArrowSize}\n sliderItemsPerPage={sliderItemsPerPage}\n />\n )\n })}\n </div>\n )\n}\n\nexport default memo(SKUSelector)\n\n```"
}
] |
code_store-components_af75652d
|
[
{
"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-components/react/components/SKUSelector/components/Variation.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, memo, useState, Fragment, useCallback } from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { IOMessage } from 'vtex.native-types'\nimport { SliderLayout } from 'vtex.slider-layout'\nimport { findIndex, propEq } from 'ramda'\nimport classnames from 'classnames'\nimport { useProduct } from 'vtex.product-context'\nimport { ResponsiveValuesTypes } from 'vtex.responsive-values'\n\nimport { stripUrl, isColor, slug } from '../utils'\nimport styles from '../styles.css'\nimport { DisplayVariation } from '../types'\nimport { imageUrlForSize, VARIATION_IMG_SIZE } from '../../module/images'\nimport ErrorMessage from './ErrorMessage'\nimport SelectModeVariation from './SelectVariationMode'\nimport SelectorItem from './SelectorItem'\nimport { ShowVariationsLabels } from './SKUSelector'\n\ninterface Props {\n variation: DisplayVariation\n maxSkuPrice?: number | null\n seeMoreLabel: string\n maxItems: number\n selectedItem: string | null\n showValueForVariation: boolean\n imageHeight?: number\n imageWidth?: number\n showBorders?: boolean\n showLabel: ShowVariationsLabels\n containerClasses?: string\n showErrorMessage: boolean\n mode?: string\n sliderDisplayThreshold: number\n sliderArrowSize: number\n sliderItemsPerPage: ResponsiveValuesTypes.ResponsiveValue<number>\n}\n\nconst ITEMS_VISIBLE_THRESHOLD = 2\n\nconst findSelectedOption = (selectedItem: string | null) =>\n findIndex(propEq('label', selectedItem))\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst noop = () => {}\n\nconst Variation: FC<Props> = ({\n mode = 'default',\n maxItems,\n showLabel,\n variation,\n imageWidth,\n imageHeight,\n showBorders,\n maxSkuPrice,\n seeMoreLabel,\n selectedItem,\n showErrorMessage,\n showValueForVariation,\n containerClasses: containerClassesProp,\n sliderArrowSize,\n sliderDisplayThreshold,\n sliderItemsPerPage,\n}) => {\n const { originalName, name, options } = variation\n\n const visibleItemsWhenCollapsed = maxItems - ITEMS_VISIBLE_THRESHOLD\n\n const [showAll, setShowAll] = useState(() => {\n const selectedOptionPosition = findSelectedOption(selectedItem)(options)\n\n return selectedOptionPosition >= visibleItemsWhenCollapsed\n })\n\n const {\n buyButton = {\n clicked: false,\n },\n } = useProduct()\n\n const displayImage = isColor(originalName)\n\n const shouldCollapse = !showAll && options.length > maxItems\n\n const overflowQuantity = options.length - visibleItemsWhenCollapsed\n const displayOptions = options.slice(\n 0,\n shouldCollapse ? visibleItemsWhenCollapsed : options.length\n )\n\n const showAllAction = useCallback(() => setShowAll(true), [setShowAll])\n const containerClasses = classnames(\n 'flex flex-column',\n containerClassesProp,\n styles.skuSelectorSubcontainer,\n `${styles.skuSelectorSubcontainer}--${slug(originalName)}`\n )\n\n const shouldUseSlider =\n displayOptions.length > sliderDisplayThreshold && mode === 'slider'\n\n const sliderConfigurationProps = {\n itemsPerPage: sliderItemsPerPage,\n infinite: true,\n showNavigationArrows: 'always',\n showPaginationDots: 'never',\n arrowSize: sliderArrowSize,\n fullWidth: false,\n }\n\n // The following code is here to maintain backwards compatibility\n let variationLabel = ''\n\n if (typeof showLabel === 'boolean') {\n variationLabel = showLabel ? 'variation' : 'none'\n } else {\n variationLabel = showLabel\n }\n\n const showVariationLabelName =\n variationLabel === 'variation' || variationLabel === 'variationAndItemValue'\n\n const selectorItemsArray = displayOptions.map(option => {\n return (\n <SelectorItem\n isSelected={option.label === selectedItem}\n key={`\u001c${option.label}-${name}`}\n isAvailable={option.available}\n maxPrice={maxSkuPrice}\n onClick={option.impossible ? noop : option.onSelectItem}\n isImage={displayImage}\n variationValue={option.label}\n variationValueOriginalName={option.originalName}\n imageHeight={imageHeight}\n imageWidth={imageWidth}\n showBorders={showBorders}\n imageUrl={\n option.image &&\n imageUrlForSize(stripUrl(option.image.imageUrl), VARIATION_IMG_SIZE)\n }\n imageLabel={option.image?.imageLabel}\n isImpossible={option.impossible}\n variationLabel={variationLabel}\n label={name}\n />\n )\n })\n\n return (\n <div className={containerClasses}>\n <div className={`${styles.skuSelectorNameContainer} ma1`}>\n <div className={`${styles.skuSelectorTextContainer} db mb3`}>\n {showVariationLabelName && (\n <span\n className={`${styles.skuSelectorName} c-muted-1 t-small overflow-hidden`}\n >\n {name}\n {showErrorMessage && buyButton.clicked && !selectedItem && (\n <ErrorMessage />\n )}\n </span>\n )}\n {selectedItem && showValueForVariation && (\n <Fragment>\n <span\n className={`${styles.skuSelectorNameSeparator} c-muted-1 t-small`}\n >\n :{' '}\n </span>\n <span\n className={`${styles.skuSelectorSelectorImageValue} c-muted-1 t-small`}\n >\n {selectedItem}\n </span>\n </Fragment>\n )}\n </div>\n <div\n className={`${styles.skuSelectorOptionsList} w-100 inline-flex flex-wrap ml2 items-center`}\n >\n {mode === 'select' && !displayImage ? (\n <SelectModeVariation\n selectedItem={selectedItem}\n displayOptions={displayOptions}\n />\n ) : shouldUseSlider ? (\n <SliderLayout {...sliderConfigurationProps}>\n {selectorItemsArray}\n </SliderLayout>\n ) : (\n selectorItemsArray\n )}\n {!showAll && shouldCollapse && (\n <div className={styles.seeMoreButton}>\n <Button\n variation=\"tertiary\"\n onClick={showAllAction}\n size=\"small\"\n collapseLeft\n >\n <IOMessage\n id={seeMoreLabel}\n values={{ quantity: overflowQuantity }}\n data-testid=\"seeMoreLabel\"\n />\n </Button>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n\nexport default memo(Variation)\n\n```"
}
] |
code_store-components_b06fe932
|
[
{
"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-components/react/components/SKUSelector/components/SelectVariationMode.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Dropdown } from 'vtex.styleguide'\nimport type { IntlShape } from 'react-intl'\nimport { injectIntl, defineMessages } from 'react-intl'\n\nimport styles from '../styles.css'\nimport type { DisplayOption } from '../types'\n\ninterface VariationSelectModeProps {\n intl: IntlShape\n selectedItem: string | null\n displayOptions: DisplayOption[]\n}\n\ninterface IsDisableParams {\n disabled: boolean\n impossible: boolean\n available: boolean\n}\n\nconst messages = defineMessages({\n selectPlaceholder: {\n id: 'store/sku-selector.select.placeholder',\n defaultMessage: '',\n },\n})\n\nfunction isDisabled({ disabled, impossible, available }: IsDisableParams) {\n if (disabled) {\n if (impossible) return true\n if (!impossible && !available) return true\n }\n\n return false\n}\n\nfunction SelectVariationMode(props: VariationSelectModeProps) {\n const { intl, selectedItem, displayOptions } = props\n\n const options = displayOptions.map(op => ({\n label: op.label,\n value: op.label,\n disabled: isDisabled({\n disabled: op.disabled,\n impossible: op.impossible,\n available: op.available,\n }),\n }))\n\n const handleClick = (_: React.MouseEvent, value: string) => {\n const reducedOptions = displayOptions.reduce<Record<string, DisplayOption>>(\n (acc, cur) => {\n acc[cur.label] = cur\n\n return acc\n },\n {}\n )\n\n return reducedOptions[value].onSelectItem()\n }\n\n return (\n <div className={styles.skuSelectorSelectContainer}>\n {/* Warning: don't change the name property. Its value is being checked in the Slider component to avoid a preventDefault call on the event triggered by the dropdown. */}\n <Dropdown\n name=\"product-summary-sku-selector\"\n options={options}\n value={selectedItem}\n onChange={handleClick}\n placeholder={intl.formatMessage(messages.selectPlaceholder)}\n />\n </div>\n )\n}\n\nexport default injectIntl(SelectVariationMode)\n\n```"
}
] |
code_store-components_1342d9a5
|
[
{
"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-components/react/components/SKUSelector/components/SelectorItem.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { memo, SyntheticEvent, useMemo } from 'react'\nimport classNames from 'classnames'\nimport { FormattedNumber } from 'react-intl'\n\nimport { useSKUSelectorCssHandles } from '../SKUSelectorCssHandles'\nimport { slug, changeImageUrlSize } from '../utils'\n\ninterface Props {\n isAvailable: boolean\n isSelected: boolean\n maxPrice?: number | null\n price?: number | null\n onClick: (e: SyntheticEvent<HTMLDivElement>) => void\n isImage: boolean\n variationValue: string\n variationValueOriginalName: string\n imageUrl?: string\n imageLabel?: string | null\n isImpossible: boolean\n imageHeight?: number | string\n imageWidth?: number | string\n showBorders?: boolean\n variationLabel: string\n label: string\n}\n\nconst getDiscount = (maxPrice?: number | null, price?: number | null) => {\n let discount = 0\n\n if (maxPrice && price) {\n discount = 1 - price / maxPrice\n }\n\n return discount\n}\n\nexport const CSS_HANDLES = [\n 'frameAround',\n 'valueWrapper',\n 'diagonalCross',\n 'unavailable',\n 'skuSelectorItem',\n 'skuSelectorBadge',\n 'skuSelectorItemImage',\n 'skuSelectorInternalBox',\n 'skuSelectorItemTextValue',\n 'skuSelectorItemImageValue',\n] as const\n\n/**\n * Inherits the components that should be displayed inside the Selector component.\n */\nfunction SelectorItem({\n isAvailable = true,\n isSelected = false,\n maxPrice,\n price,\n onClick,\n isImage,\n variationValue,\n variationValueOriginalName,\n imageUrl,\n imageLabel,\n isImpossible,\n imageHeight,\n imageWidth,\n showBorders = true,\n variationLabel,\n label,\n}: Props) {\n const discount = getDiscount(maxPrice, price)\n const { handles, withModifiers } = useSKUSelectorCssHandles()\n\n const containerClasses = useMemo(\n () =>\n classNames(\n withModifiers('skuSelectorItem', [\n slug(variationValueOriginalName),\n isSelected ? 'selected' : '',\n ]),\n 'relative di pointer flex items-center outline-0 ma2',\n {\n [`${handles.skuSelectorItemImage}`]: isImage,\n 'o-20': isImpossible,\n },\n 'valueWrapper',\n !isAvailable ? `${handles.unavailable}` : ''\n ),\n [\n isImage,\n isAvailable,\n isSelected,\n isImpossible,\n variationValueOriginalName,\n withModifiers,\n handles.skuSelectorItemImage,\n handles.unavailable,\n ]\n )\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const passedAnyDimension = Boolean(imageHeight || imageWidth)\n let containerStyles = {}\n\n if (isImage && passedAnyDimension && imageUrl) {\n containerStyles = {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n height: imageHeight || 'auto',\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n width: imageWidth || 'auto',\n padding: 0,\n }\n imageUrl = changeImageUrlSize(imageUrl, imageWidth, imageHeight)\n }\n\n let itemTextValue = variationValue\n\n if (\n variationLabel === 'itemValue' ||\n variationLabel === 'variationAndItemValue'\n ) {\n itemTextValue = `${label} ${variationValue}`\n }\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n onClick={onClick}\n style={containerStyles}\n className={containerClasses}\n onKeyDown={e => e.key === 'Enter' && onClick(e)}\n >\n <div\n className={classNames(\n handles.frameAround,\n 'absolute b--action-primary br3 bw1',\n {\n ba: isSelected,\n }\n )}\n />\n <div\n className={classNames(\n handles.skuSelectorInternalBox,\n 'w-100 h-100 b--muted-4 br2 b z-1 c-muted-5 flex items-center overflow-hidden',\n {\n 'hover-b--muted-2': !isSelected && !isImpossible,\n ba: showBorders,\n }\n )}\n >\n <div\n className={classNames('absolute absolute--fill', {\n [handles.diagonalCross]: !isAvailable,\n })}\n />\n <div\n className={classNames(\n withModifiers('valueWrapper', !isAvailable ? 'unavailable' : ''),\n {\n [`${handles.skuSelectorItemTextValue} c-on-base center pl5 pr5 z-1 t-body`]:\n !isImage,\n 'h-100': isImage,\n }\n )}\n >\n {isImage && imageUrl ? (\n <img\n className={handles.skuSelectorItemImageValue}\n src={imageUrl}\n alt={imageLabel as string | undefined}\n />\n ) : (\n itemTextValue\n )}\n </div>\n </div>\n {discount > 0 && (\n <span className={`${handles.skuSelectorBadge} b`}>\n <FormattedNumber value={discount} style=\"percent\" />\n </span>\n )}\n </div>\n )\n}\n\nexport default memo(SelectorItem)\n\n```"
}
] |
code_store-components_fb3f8a3a
|
[
{
"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-components/react/components/SKUSelector/components/hooks/useEffectSkipMount.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useEffect, useRef, EffectCallback } from 'react'\n\nconst useEffectSkipMount = (func: EffectCallback, deps: unknown[]) => {\n const isFirstRender = useRef(true)\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false\n\n return\n }\n\n return func()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n}\n\nexport default useEffectSkipMount\n\n```"
}
] |
code_store-components_cccb397a
|
[
{
"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-components/react/components/Newsletter/mutations/subscribeNewsletter.graphql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation subscribeNewsletter($email: String) {\n subscribeNewsletter(email: $email)\n}\n```"
}
] |
code_store-components_2d2580d0
|
[
{
"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-components/react/components/CategoriesHighlights/components/CategoryCard.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport { Link } from 'vtex.render-runtime'\n\nimport { RECTANGULAR, SQUARED } from '../constants'\nimport rectangularPlaceholder from '../images/rectangular-placeholder.svg'\nimport squaredPlaceholder from '../images/squared-placeholder.svg'\nimport categoriesHighlights from '../categoriesHighlights.css'\n\n/**\n * CategoryCard is a component responsible to display an image of a category\n * and provides the link to the category specified by its name.\n */\n// eslint-disable-next-line react/prefer-stateless-function\nclass CategoryCard extends Component {\n static propTypes = {\n /** Name of the category */\n name: PropTypes.string.isRequired,\n /** Image of the category */\n image: PropTypes.string,\n /** Shape of the category card */\n shape: PropTypes.oneOf([RECTANGULAR, SQUARED]),\n }\n\n render() {\n const { name, image, shape } = this.props\n\n return (\n <div className={`${categoriesHighlights[`${shape}Card`]} shadow-1 ma1`}>\n {/* TODO: Redirect to the page of the category specified by its name */}\n\n {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}\n <Link>\n {image ? (\n <img\n src={image}\n alt={name}\n className={`${categoriesHighlights[`${shape}CardImage`]}`}\n />\n ) : (\n <img\n src={\n shape === SQUARED ? squaredPlaceholder : rectangularPlaceholder\n }\n alt=\"\"\n className={`${categoriesHighlights[`${shape}CardImage`]}`}\n />\n )}\n </Link>\n </div>\n )\n }\n}\n\nexport default CategoryCard\n\n```"
}
] |
code_store-components_64105c7b
|
[
{
"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-components/react/components/Share/constants/social.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport * as Social from 'react-share'\n\nexport const SOCIAL_NAME_MAP = {\n facebook: 'Facebook',\n whatsapp: 'WhatsApp',\n twitter: 'Twitter',\n telegram: 'Telegram',\n email: 'E-mail',\n pinterest: 'Pinterest',\n}\n\nexport const SOCIAL_LIST = Object.values(SOCIAL_NAME_MAP)\n\nexport const SOCIAL_COMPONENT_MAP = {\n [SOCIAL_NAME_MAP.facebook]: {\n SocialNetworkName: SOCIAL_NAME_MAP.facebook,\n SocialComponent: Social.FacebookShareButton,\n SocialIcon: Social.FacebookIcon,\n },\n [SOCIAL_NAME_MAP.whatsapp]: {\n SocialNetworkName: SOCIAL_NAME_MAP.whatsapp,\n SocialComponent: Social.WhatsappShareButton,\n SocialIcon: Social.WhatsappIcon,\n },\n [SOCIAL_NAME_MAP.twitter]: {\n SocialNetworkName: SOCIAL_NAME_MAP.twitter,\n SocialComponent: Social.TwitterShareButton,\n SocialIcon: Social.TwitterIcon,\n },\n [SOCIAL_NAME_MAP.telegram]: {\n SocialNetworkName: SOCIAL_NAME_MAP.telegram,\n SocialComponent: Social.TelegramShareButton,\n SocialIcon: Social.TelegramIcon,\n },\n [SOCIAL_NAME_MAP.email]: {\n SocialNetworkName: SOCIAL_NAME_MAP.email,\n SocialComponent: Social.EmailShareButton,\n SocialIcon: Social.EmailIcon,\n },\n [SOCIAL_NAME_MAP.pinterest]: {\n SocialNetworkName: SOCIAL_NAME_MAP.pinterest,\n SocialComponent: Social.PinterestShareButton,\n SocialIcon: Social.PinterestIcon,\n },\n}\n\n```"
}
] |
code_store-components_4b6b1756
|
[
{
"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-components/react/components/Share/components/SocialButton.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nimport { SOCIAL_NAME_MAP, SOCIAL_COMPONENT_MAP } from '../constants/social'\nimport styles from '../styles.css'\nimport { slug } from '../../SKUSelector/utils'\n\nconst SOCIAL_WITH_TITLE = new Set([\n SOCIAL_NAME_MAP.whatsapp,\n SOCIAL_NAME_MAP.twitter,\n SOCIAL_NAME_MAP.telegram,\n SOCIAL_NAME_MAP.pinterest,\n])\n\nfunction getExtraSocialProps({ message, socialEnum }) {\n if (!message) return {}\n\n if (SOCIAL_WITH_TITLE.has(socialEnum)) {\n return { title: message }\n }\n\n if (socialEnum === SOCIAL_NAME_MAP.facebook) {\n return { quote: message }\n }\n\n return { body: message }\n}\n\nexport default class SocialButton extends Component {\n static propTypes = {\n /** Share URL */\n url: PropTypes.string.isRequired,\n /** Message to be shared */\n message: PropTypes.string,\n /** Social Network Enum */\n socialEnum: PropTypes.string.isRequired,\n /** Button size in pixels */\n size: PropTypes.number,\n /** Classes to be applied to social button */\n buttonClass: PropTypes.string,\n /** Classes to be applied to icon of the button */\n iconClass: PropTypes.string,\n /** Image url to share in social medias */\n imageUrl: PropTypes.string,\n /** Function that sends share event to analytics */\n sendShareEvent: PropTypes.func,\n }\n\n static defaultProps = {\n size: 32,\n buttonClass: 'mh1 pointer outline-0 dim',\n }\n\n render() {\n const { url, message, size, socialEnum, buttonClass, iconClass, imageUrl } =\n this.props\n\n const { SocialNetworkName, SocialComponent, SocialIcon } =\n SOCIAL_COMPONENT_MAP[socialEnum]\n\n const additionalProps = getExtraSocialProps({ message, socialEnum })\n\n const icon = (\n <SocialIcon\n round\n size={size}\n className={classNames(\n styles.shareSocialIcon,\n `${styles.shareSocialIcon}--${slug(SocialNetworkName)}`,\n iconClass\n )}\n />\n )\n\n /* Pinterest requires imageUrl for the \"media\" prop, but\n * it might not be loaded yet */\n if (SocialNetworkName === SOCIAL_NAME_MAP.pinterest && !imageUrl) {\n return icon\n }\n\n return (\n <SocialComponent\n url={url}\n className={classNames(\n styles.shareSocialButton,\n `${styles.shareSocialButton}--${slug(SocialNetworkName)}`,\n buttonClass\n )}\n media={imageUrl}\n onClick={() => this.props.sendShareEvent(socialEnum)}\n openShareDialogOnClick\n {...additionalProps}\n >\n {icon}\n </SocialComponent>\n )\n }\n}\n\n```"
}
] |
code_store-components_b109eaeb
|
[
{
"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-components/react/__tests__/components/SKUSelector.test.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render, fireEvent, wait } from '@vtex/test-tools/react'\nimport { useProduct, ProductContext } from 'vtex.product-context'\nimport { getSKU } from 'sku-helper'\n\nimport SKUSelector from '../../components/SKUSelector/Wrapper'\nimport { orderItemsByAvailability } from '../../components/SKUSelector/components/SKUSelector'\n\ndescribe('<SKUSelector />', () => {\n const renderComponent = (customProps = {}) => {\n const props: any = {\n skuSelected: getSKU(),\n skuItems: [getSKU('Black'), getSKU('Blue'), getSKU('Yellow')],\n ...customProps,\n }\n\n return render(<SKUSelector {...props} />)\n }\n\n const mockedUseProduct = useProduct as jest.Mock<ProductContext>\n\n it('should call onSKUSelected', async () => {\n const onSKUSelected = jest.fn()\n const { container } = renderComponent({ onSKUSelected })\n\n await wait()\n const selector = container.querySelector('.skuSelectorItem')\n\n await wait(() => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n fireEvent.click(selector!)\n })\n expect(onSKUSelected).toBeCalledTimes(2)\n })\n\n it('should render the options an select one', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Blue', 'Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const [skuSelected] = skuItems\n const onSKUSelected = jest.fn()\n const { getByText } = render(\n <SKUSelector\n skuItems={skuItems}\n displayMode=\"select\"\n skuSelected={skuSelected}\n initialSelection=\"empty\"\n onSKUSelected={onSKUSelected}\n />\n )\n\n await wait()\n\n await wait(() => {\n getByText('Gray').click()\n })\n\n expect(getByText('42')).toBeDefined()\n\n await wait(() => {\n getByText('42').click()\n })\n\n expect(onSKUSelected).toBeCalledTimes(2)\n expect(getByText('41')).toBeDefined()\n })\n\n it('should be able to order by availability', async () => {\n const defaultSeller1 = {\n sellerDefault: true,\n commertialOffer: { Price: 15, AvailableQuantity: 0, ListPrice: 200 },\n }\n\n const defaultSeller2 = {\n sellerDefault: true,\n commertialOffer: { Price: 15, AvailableQuantity: 1, ListPrice: 200 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: ['Size', 'Color'],\n variationValues: { Size: '41', Color: 'Gray' },\n sellers: [defaultSeller1],\n images: [],\n },\n {\n itemId: '2',\n name: 'Gray Shoe',\n variations: ['Size', 'Color'],\n variationValues: { Size: '41', Color: 'Gray' },\n sellers: [defaultSeller2],\n images: [],\n },\n ]\n\n const possibleItemsOrderedByAvailability = skuItems.sort(\n orderItemsByAvailability\n )\n\n expect(possibleItemsOrderedByAvailability[0].itemId).toEqual('2')\n })\n\n it('should render only three main variations', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Blue'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const [skuSelected] = skuItems\n\n const { getByText, getAllByText } = render(\n <SKUSelector skuSelected={skuSelected} skuItems={skuItems} />\n )\n\n await wait()\n\n expect(getAllByText(/gray/i)).toHaveLength(1)\n expect(getAllByText(/blue/i)).toHaveLength(1)\n expect(getAllByText(/black/i)).toHaveLength(1)\n\n expect(getByText(/color/i)).toBeInTheDocument()\n expect(getByText(/size/i)).toBeInTheDocument()\n })\n\n it('should render show 8 items for variation and see more button', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Blue'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '5',\n name: 'xxxx',\n variations: [\n {\n name: 'Size',\n values: ['43'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '6',\n name: 'xxxxxx',\n variations: [\n {\n name: 'Size',\n values: ['44'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '7',\n name: 'xxxxaaaxx',\n variations: [\n {\n name: 'Size',\n values: ['45'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '8',\n name: 'aaaa',\n variations: [\n {\n name: 'Size',\n values: ['46'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '9',\n name: 'bb',\n variations: [\n {\n name: 'Size',\n values: ['47'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '10',\n name: 'ppp',\n variations: [\n {\n name: 'Size',\n values: ['41'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '11',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['38'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '12',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['39'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '13',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['10'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '14',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['11'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '15',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['12'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '16',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['13'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '17',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['14'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const [skuSelected] = skuItems\n\n const { getByText, queryByText } = render(\n <SKUSelector skuSelected={skuSelected} skuItems={skuItems} />\n )\n\n await wait()\n // await Promise.resolve()\n expect(getByText('seeMoreLabel')).toBeDefined()\n expect(getByText('38')).toBeDefined()\n expect(queryByText('39')).toBeNull()\n })\n\n it('should respect given maxItems prop set and show see more button', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Blue'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['2'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '5',\n name: 'xxxx',\n variations: [\n {\n name: 'Size',\n values: ['3'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '6',\n name: 'xxxxxx',\n variations: [\n {\n name: 'Size',\n values: ['4'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '7',\n name: 'xxxxaaaxx',\n variations: [\n {\n name: 'Size',\n values: ['5'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '8',\n name: 'aaaa',\n variations: [\n {\n name: 'Size',\n values: ['6'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '9',\n name: 'bb',\n variations: [\n {\n name: 'Size',\n values: ['7'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '10',\n name: 'ppp',\n variations: [\n {\n name: 'Size',\n values: ['1'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '11',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['8'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '12',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['9'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '13',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['10'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '14',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['11'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '15',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['12'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '16',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['13'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '17',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['14'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const [skuSelected] = skuItems\n\n const { getByText, queryByText } = render(\n <SKUSelector skuSelected={skuSelected} skuItems={skuItems} maxItems={6} />\n )\n\n await wait()\n\n // eslint-disable-next-line jest/valid-expect\n expect(getByText('seeMoreLabel'))\n expect(getByText('4')).toBeDefined()\n expect(queryByText('5')).toBeNull()\n })\n\n it('should show all variations when count is inside threshold', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Blue'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['2'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '5',\n name: 'xxxx',\n variations: [\n {\n name: 'Size',\n values: ['3'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '6',\n name: 'xxxxxx',\n variations: [\n {\n name: 'Size',\n values: ['4'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '7',\n name: 'xxxxaaaxx',\n variations: [\n {\n name: 'Size',\n values: ['5'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '8',\n name: 'aaaa',\n variations: [\n {\n name: 'Size',\n values: ['6'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '9',\n name: 'bb',\n variations: [\n {\n name: 'Size',\n values: ['7'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '10',\n name: 'ppp',\n variations: [\n {\n name: 'Size',\n values: ['1'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '11',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['8'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '12',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['9'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '13',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['10'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const [skuSelected] = skuItems\n\n const { getByText, queryByText } = render(\n <SKUSelector skuSelected={skuSelected} skuItems={skuItems} />\n )\n\n await wait()\n expect(queryByText('seeMoreLabel')).toBeNull()\n expect(getByText('10')).toBeDefined()\n })\n\n it('should show all options if a sku selected variations appears later on the array than in the cut', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['1'] },\n { name: 'Color', values: ['Blue'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['2'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '5',\n name: 'xxxx',\n variations: [\n {\n name: 'Size',\n values: ['3'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '6',\n name: 'xxxxxx',\n variations: [\n {\n name: 'Size',\n values: ['4'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '7',\n name: 'xxxxaaaxx',\n variations: [\n {\n name: 'Size',\n values: ['5'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '8',\n name: 'aaaa',\n variations: [\n {\n name: 'Size',\n values: ['6'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '9',\n name: 'bb',\n variations: [\n {\n name: 'Size',\n values: ['7'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '10',\n name: 'ppp',\n variations: [\n {\n name: 'Size',\n values: ['1'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '11',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['8'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '12',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['9'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '13',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['10'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '14',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['11'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '15',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['12'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '16',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['13'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '17',\n name: 'c',\n variations: [\n {\n name: 'Size',\n values: ['14'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const skuSelected = skuItems.find(({ itemId }) => itemId === '15')\n\n const { getByText } = render(\n <SKUSelector skuSelected={skuSelected} skuItems={skuItems} maxItems={6} />\n )\n\n await wait()\n\n expect(getByText('4')).toBeDefined()\n expect(getByText('12')).toBeDefined()\n })\n\n it('remove accent from names on slugify methods', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['[Square Brackets]'] },\n { name: 'Color', values: ['Jácó'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['[Square Brackets]'] },\n { name: 'Color', values: ['@@Testing&&'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['[Square Brackets]'] },\n { name: 'Color', values: [\"John's\"] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['[Square Brackets]'] },\n { name: 'Color', values: ['Feijão'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const { queryByText } = render(\n <SKUSelector skuSelected={skuItems[0]} skuItems={skuItems} maxItems={6} />\n )\n\n await wait()\n expect(queryByText('skuSelectorItem--feijao')).toBeDefined()\n expect(queryByText('skuSelectorItem--square-brackets')).toBeDefined()\n expect(queryByText('skuSelectorItem--johns')).toBeDefined()\n expect(queryByText('skuSelectorItem--testing')).toBeDefined()\n expect(queryByText('skuSelectorItem--jaco')).toBeDefined()\n })\n\n it('should show the selected variation name', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const { container } = render(\n <SKUSelector\n skuSelected={skuItems[0]}\n skuItems={skuItems}\n maxItems={6}\n showValueNameForImageVariation\n />\n )\n\n await wait()\n\n const separator = container.querySelector('.skuSelectorNameSeparator')\n const variationValue = container.querySelector(\n '.skuSelectorSelectorImageValue'\n )\n\n expect(separator).toHaveTextContent(':')\n expect(variationValue).toHaveTextContent('Gray')\n })\n\n /* Order of the color variations should be: Black, Gray, Blue.\n * Order of the Size variations should be: 42, 41\n * The snapshot should validate if the values are coming correctly */\n it('should consider order from skuSpecifications', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, ListPrice: 20, AvailableQuantity: 10 },\n }\n\n const firstSku = {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n }\n\n mockedUseProduct.mockImplementation(\n function getProductContext(): ProductContext {\n return {\n product: {\n buyButton: {\n clicked: false,\n },\n skuSelector: {\n isVisible: true,\n areAllVariationsSelected: true,\n },\n selectedItem: firstSku,\n selectedQuantity: 1,\n assemblyOptions: {\n items: {},\n areGroupsValid: {},\n inputValues: {},\n },\n skuSpecifications: [\n {\n field: {\n name: 'Color',\n originalName: 'Color',\n },\n values: [\n {\n name: 'Black',\n originalName: 'Black',\n },\n {\n name: 'Gray',\n originalName: 'Gray',\n },\n {\n name: 'Blue',\n originalName: 'Blue',\n },\n ],\n },\n {\n field: {\n name: 'Size',\n originalName: 'Size',\n },\n values: [\n {\n name: '43',\n originalName: '43',\n },\n {\n name: '42',\n originalName: '42',\n },\n {\n name: '41',\n originalName: '41',\n },\n ],\n },\n ],\n },\n }\n }\n )\n const skuItems = [\n firstSku,\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Blue', 'Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const { asFragment } = render(\n <SKUSelector skuSelected={skuItems[0]} skuItems={skuItems} maxItems={6} />\n )\n\n // check comment above the 'it' description\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should not show the Yellow variation since there is no items with the Yellow variation', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, ListPrice: 20, AvailableQuantity: 10 },\n }\n\n const firstSku = {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['41'] },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n }\n\n mockedUseProduct.mockImplementation(\n function getProductContext(): ProductContext {\n return {\n product: {\n buyButton: {\n clicked: false,\n },\n skuSelector: {\n isVisible: true,\n areAllVariationsSelected: true,\n },\n selectedItem: firstSku,\n selectedQuantity: 1,\n assemblyOptions: {\n items: {},\n areGroupsValid: {},\n inputValues: {},\n },\n skuSpecifications: [\n {\n field: {\n name: 'Color',\n originalName: 'Color',\n },\n values: [\n {\n name: 'Yellow',\n originalName: 'Yellow',\n },\n {\n name: 'Black',\n originalName: 'Black',\n },\n {\n name: 'Gray',\n originalName: 'Gray',\n },\n {\n name: 'Blue',\n originalName: 'Blue',\n },\n ],\n },\n {\n field: {\n name: 'Size',\n originalName: 'Size',\n },\n values: [\n {\n name: '43',\n originalName: '43',\n },\n {\n name: '42',\n originalName: '42',\n },\n {\n name: '41',\n originalName: '41',\n },\n ],\n },\n ],\n },\n }\n }\n )\n\n const skuItems = [\n firstSku,\n {\n itemId: '2',\n name: 'Black Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '3',\n name: 'Blue Shoe',\n variations: [\n { name: 'Size', values: ['41', '42', '43'] },\n { name: 'Color', values: ['Blue', 'Black'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n sellers: [defaultSeller],\n images: [],\n },\n ]\n\n const { queryByText } = render(\n <SKUSelector skuSelected={skuItems[0]} skuItems={skuItems} maxItems={6} />\n )\n\n expect(queryByText('Yellow')).toBeFalsy()\n })\n\n it('must order sku specification to be sorted in alphabetical order', async () => {\n const defaultSeller = {\n commertialOffer: { Price: 15, AvailableQuantity: 1 },\n }\n\n const skuItems = [\n {\n itemId: '1',\n name: 'Gray Shoe',\n variations: [\n { name: 'Size', values: ['43'] },\n { name: 'Color', values: ['Gray'] },\n ],\n images: [],\n sellers: [defaultSeller],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['42'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n images: [],\n sellers: [defaultSeller],\n },\n {\n itemId: '4',\n name: 'Gray Shoe',\n variations: [\n {\n name: 'Size',\n values: ['41'],\n },\n { name: 'Color', values: ['Gray'] },\n ],\n images: [],\n sellers: [defaultSeller],\n },\n ]\n\n const { container } = renderComponent({\n sortVariationsByLabel: true,\n skuSelected: skuItems[0],\n skuItems,\n })\n\n const options = container.querySelectorAll('.skuSelectorItemTextValue')\n\n expect(options[0]).toHaveTextContent('41')\n expect(options[1]).toHaveTextContent('42')\n expect(options[2]).toHaveTextContent('43')\n })\n})\n\n```"
}
] |
code_store-components_c79e5cc2
|
[
{
"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-components/react/__tests__/components/ProductImages.test.jsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React from 'react'\nimport { render, fireEvent } from '@vtex/test-tools/react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { Modal } from 'vtex.modal-layout'\n\nimport ProductImages from '../../ProductImages'\n// eslint-disable-next-line jest/no-mocks-import\nimport { createItem } from '../../__mocks__/productMock'\nimport HighQualityProductImage from '../../HighQualityProductImage'\n\nconst mockUseProduct = useProduct\n\n// This works just like a slot passed to product-iamges\nfunction ModalLayout() {\n return (\n <Modal>\n <HighQualityProductImage />\n </Modal>\n )\n}\n\njest.mock('swiper/react', () => {\n return {\n Swiper({ children }) {\n return <div>{children}</div>\n },\n SwiperSlide({ children }) {\n return <div>{children}</div>\n },\n }\n})\n\n// This Image mock only call set onload function after user sets the src property in object\nclass FakeImage {\n onload = null\n set src(newSrc) {\n this.onload && this.onload()\n }\n}\n\nbeforeEach(() => {\n window.Image = FakeImage\n})\n\ndescribe('<ProductImages />', () => {\n const renderComponent = customProps => {\n return render(<ProductImages {...customProps} />)\n }\n\n it('should render two images (thumb and main image) for each product image', () => {\n const props = {\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n imageLabel: 'imageLabel',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n imageLabel: 'imageLabel2',\n },\n ],\n }\n\n const { getAllByAltText } = renderComponent(props)\n\n expect(getAllByAltText('imageLabel')).toHaveLength(2)\n expect(getAllByAltText('imageLabel2')).toHaveLength(2)\n })\n it('should show thumbs when there is more than one image', () => {\n const props = {\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n imageLabel: 'imageLabel',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n imageLabel: 'imageLabel2',\n },\n ],\n }\n\n const { queryByTestId, getAllByAltText } = renderComponent(props)\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('db-ns')).toBeTruthy()\n getAllByAltText('imageLabel')\n getAllByAltText('imageLabel2')\n })\n it('should show default placeholder when there is NO image', () => {\n const props = {\n images: [],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const defaultPlaceholder = queryByTestId('default-image-placeholder')\n\n expect(defaultPlaceholder).toBeVisible()\n })\n\n it('should show custom placeholder when provided and there is NO image', () => {\n const props = {\n images: [],\n placeholder: 'url',\n }\n\n const { queryByAltText } = renderComponent(props)\n\n const defaultPlaceholder = queryByAltText('Product image placeholder')\n\n expect(defaultPlaceholder).toBeVisible()\n })\n\n it('should NOT show thumbs when there is one image', () => {\n const props = {\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper).toHaveClass('dn')\n })\n\n describe('test logic to thumbnail orientation', () => {\n it('should render with correct classes when vertical', () => {\n const props = {\n thumbnailsOrientation: 'vertical',\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('absolute')).toBeTruthy()\n expect(swiper.className.includes('w-20')).toBeTruthy()\n })\n it('default orientation should be vertical', () => {\n const props = {\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('absolute')).toBeTruthy()\n expect(swiper.className.includes('w-20')).toBeTruthy()\n })\n it('should render with correct classes when horizontal', () => {\n const props = {\n thumbnailsOrientation: 'horizontal',\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('absolute')).toBeFalsy()\n expect(swiper.className.includes('w-20')).toBeFalsy()\n })\n it('should render with correct classes when vertical and position left', () => {\n const props = {\n thumbnailsOrientation: 'vertical',\n position: 'left',\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('absolute')).toBeTruthy()\n expect(swiper.className.includes('w-20')).toBeTruthy()\n expect(swiper.className.includes('left')).toBeTruthy()\n expect(swiper.className.includes('right')).toBeFalsy()\n })\n it('should render with correct classes when vertical and position right', () => {\n const props = {\n thumbnailsOrientation: 'vertical',\n position: 'right',\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n },\n ],\n }\n\n const { queryByTestId } = renderComponent(props)\n\n const swiper = queryByTestId('thumbnail-swiper')\n\n expect(swiper.className.includes('absolute')).toBeTruthy()\n expect(swiper.className.includes('w-20')).toBeTruthy()\n expect(swiper.className.includes('left')).toBeFalsy()\n expect(swiper.className.includes('right')).toBeTruthy()\n })\n })\n\n describe('test with product context', () => {\n it('render properly with product in context', () => {\n mockUseProduct.mockImplementation(() => ({\n selectedItem: createItem({ id: 'potato' }),\n }))\n const { queryAllByAltText } = renderComponent({})\n\n expect(queryAllByAltText('potato-Color')).toHaveLength(6)\n })\n\n it('gives priority to selected image variation sku', () => {\n mockUseProduct.mockImplementation(() => ({\n product: {\n items: [createItem({ id: '123' }), createItem({ id: '456' })],\n },\n skuSelector: {\n selectedImageVariationSKU: '456',\n },\n }))\n const { queryAllByAltText } = renderComponent({})\n\n expect(queryAllByAltText('456-Color')).toHaveLength(6)\n })\n\n it('give priority to prop items if product in context', () => {\n mockUseProduct.mockImplementation(() => ({\n selectedItem: createItem({}),\n }))\n const props = {\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'propImageText',\n imageLabel: 'propImageLabel',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'propImageText2',\n imageLabel: 'propImageLabel2',\n },\n ],\n }\n\n const { queryAllByAltText } = renderComponent(props)\n\n expect(queryAllByAltText('propImageLabel')).toHaveLength(2)\n expect(queryAllByAltText('propImageLabel2')).toHaveLength(2)\n })\n })\n\n describe('<HighQualityProductImage />', () => {\n it('should render if the modal-trigger is clicked', () => {\n const props = {\n zoomMode: 'open-modal',\n ModalZoom: ModalLayout,\n images: [\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n imageLabel: 'imageLabel2',\n },\n ],\n }\n\n const { getAllByAltText, getByTestId } = render(\n <ProductImages {...props} />\n )\n\n const images = getAllByAltText('imageLabel2')\n\n // 2 for thumb + main image\n expect(images).toHaveLength(2)\n fireEvent.click(getByTestId('modal-trigger'), {\n bubbles: true,\n cancelable: true,\n })\n\n // 3 for thumb + main image + modal image\n expect(getAllByAltText('imageLabel2')).toHaveLength(3)\n })\n\n it('should render 2 img[alt=\"imageLabel2\"] if img2 trigger is clicked', () => {\n const props = {\n zoomMode: 'open-modal',\n ModalZoom: ModalLayout,\n images: [\n {\n imageUrls: ['url'],\n thresholds: [1],\n thumbnailUrl: 'url',\n imageText: 'imageText',\n imageLabel: 'imageLabel',\n },\n {\n imageUrls: ['url2'],\n thresholds: [1],\n thumbnailUrl: 'url2',\n imageText: 'imageText2',\n imageLabel: 'imageLabel2',\n },\n ],\n }\n\n const { getAllByAltText, getAllByTestId } = render(\n <ProductImages {...props} />\n )\n\n const images = getAllByAltText('imageLabel2')\n\n expect(images).toHaveLength(2)\n fireEvent.click(getAllByTestId('modal-trigger')[1], {\n bubbles: true,\n cancelable: true,\n })\n\n // 3 images with the alt because is one image of the trigger,\n // one image of the thumbs and the image of HighQualityProductImage\n expect(getAllByAltText('imageLabel2')).toHaveLength(3)\n })\n })\n})\n\n```"
}
] |
code_store-components_f1d934aa
|
[
{
"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-components/react/__tests__/components/CategoriesHighlights.test.js from the store-components 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 CategoriesHighlights from '../../CategoriesHighlights'\n\ndescribe('<CategoriesHighlights />', () => {\n const renderComponent = customProps => {\n const props = {\n cardShape: 'squared',\n showCategoriesHighlighted: true,\n ...customProps,\n }\n\n return render(<CategoriesHighlights {...props} />)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot Squared', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot Rectangular', () => {\n const { asFragment } = renderComponent({ cardShape: 'rectangular' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_12bd5f1b
|
[
{
"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-components/react/__tests__/components/Share.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, fireEvent, screen } from '@vtex/test-tools/react'\n\nimport Share from '../../Share'\n\nconst mockedUsePixelPush = jest.fn()\n\njest.mock('vtex.pixel-manager', () => ({\n usePixel: () => ({ push: mockedUsePixelPush }),\n}))\n\ndescribe('<Share />', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n const renderComponent = props => {\n return render(<Share imageUrl=\"\" {...props} />)\n }\n\n it('should be mounted', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n })\n\n it('should match the snapshot with Facebook', () => {\n const { asFragment } = renderComponent({\n social: {\n Facebook: true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Twitter', () => {\n const { asFragment } = renderComponent({\n social: {\n Twitter: true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with WhatsApp', () => {\n const { asFragment } = renderComponent({\n social: {\n WhatsApp: true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Telegram', () => {\n const { asFragment } = renderComponent({\n social: {\n Telegram: true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with E-mail', () => {\n const { asFragment } = renderComponent({\n social: {\n 'E-mail': true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with multiples Socials', () => {\n const { asFragment } = renderComponent({\n social: {\n 'E-mail': true,\n Twitter: true,\n Telegram: true,\n },\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot Loader', () => {\n const { asFragment } = renderComponent({ loading: true })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should send vtex:share with Facebook method when is clicked', async () => {\n await renderComponent({\n social: {\n Facebook: true,\n },\n loading: false,\n })\n\n const btn = screen.getByLabelText('facebook')\n\n fireEvent.click(btn)\n\n const expectedPixelEvent = {\n event: 'share',\n method: 'Facebook',\n contentType: 'product',\n itemId: '23087',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should send vtex:share with WhatsApp method when is clicked', async () => {\n await renderComponent({\n social: {\n WhatsApp: true,\n },\n loading: false,\n })\n\n const btn = screen.getByLabelText('whatsapp')\n\n fireEvent.click(btn)\n\n const expectedPixelEvent = {\n event: 'share',\n method: 'WhatsApp',\n contentType: 'product',\n itemId: '23087',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should send vtex:share with Twitter method when is clicked', async () => {\n await renderComponent({\n social: {\n Twitter: true,\n },\n loading: false,\n })\n\n const btn = screen.getByLabelText('twitter')\n\n fireEvent.click(btn)\n\n const expectedPixelEvent = {\n event: 'share',\n method: 'Twitter',\n contentType: 'product',\n itemId: '23087',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should send vtex:share with Telegram method when is clicked', async () => {\n await renderComponent({\n social: {\n Telegram: true,\n },\n loading: false,\n })\n\n const btn = screen.getByLabelText('telegram')\n\n fireEvent.click(btn)\n\n const expectedPixelEvent = {\n event: 'share',\n method: 'Telegram',\n contentType: 'product',\n itemId: '23087',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should send vtex:share with E-mail method when is clicked', async () => {\n await renderComponent({\n social: {\n 'E-mail': true,\n },\n loading: false,\n })\n\n const btn = screen.getByLabelText('email')\n\n fireEvent.click(btn)\n\n const expectedPixelEvent = {\n event: 'share',\n method: 'E-mail',\n contentType: 'product',\n itemId: '23087',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n})\n\n```"
}
] |
code_store-components_fef36925
|
[
{
"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-components/react/__tests__/components/SearchBar.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, fireEvent, screen } from '@vtex/test-tools/react'\n\nimport SearchBar from '../../SearchBar'\nimport autocomplete from '../../graphql/autocomplete.gql'\n\nconst mockedUsePixelPush = jest.fn()\n\njest.mock('vtex.pixel-manager', () => ({\n usePixel: () => ({ push: mockedUsePixelPush }),\n}))\n\ndescribe('<SearchBar />', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n const mockedResult = {\n request: {\n query: autocomplete,\n },\n result: {\n data: {\n loading: false,\n autocomplete: {\n itemsReturned: [{ thumb: 'thumb', name: 'name', href: 'href' }],\n },\n },\n },\n }\n\n const renderComponent = (customProps = {}) => {\n return render(<SearchBar {...customProps} />, {\n graphql: { mocks: [mockedResult] },\n })\n }\n\n it('should be able to mount and not break', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should have CSS handle searchBarIcon', () => {\n const { container } = renderComponent()\n const element = container.querySelector('.searchBarIcon')\n\n expect(element).toBeTruthy()\n })\n\n it('should display internal search icon button', () => {\n const { container } = renderComponent({\n displayMode: 'search-button',\n })\n\n expect(container.querySelector('.searchBarIcon--search')).toBeTruthy()\n })\n\n it('should display internal clear icon button when a value is typed', () => {\n const { container } = renderComponent({\n displayMode: 'search-button',\n value: 'foo',\n })\n\n expect(container.querySelector('.searchBarIcon--search')).toBeTruthy()\n })\n\n it('should display external search icon button', () => {\n const { container } = renderComponent({\n displayMode: 'search-and-clear-buttons',\n })\n\n expect(\n container.querySelector('.searchBarIcon--external-search')\n ).toBeTruthy()\n })\n\n it('should display interal clear icon button when a value is typed', () => {\n const { container } = renderComponent({\n displayMode: 'search-and-clear-buttons',\n value: 'foo',\n })\n\n expect(container.querySelector('.searchBarIcon--clear')).toBeTruthy()\n })\n\n it('should trigger vtex:search when a value is typed', async () => {\n const { container } = renderComponent({\n displayMode: 'search-and-clear-buttons',\n submitOnIconClick: true,\n })\n\n const [searchButton] = container.getElementsByClassName('searchBarIcon')\n const inputNode = screen.getByPlaceholderText('Search')\n\n fireEvent.change(inputNode, { target: { value: 'foo' } })\n\n fireEvent.click(searchButton)\n\n const expectedPixelEvent = {\n event: 'search',\n term: 'foo',\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n})\n\n```"
}
] |
code_store-components_4203431c
|
[
{
"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-components/react/__tests__/components/ProductDescription.test.tsx from the store-components 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 ProductDescription from '../../ProductDescription'\n\ndescribe('<ProductDescription />', () => {\n const renderComponent = (customProps?: any) => {\n const props = {\n description: 'Test description',\n ...customProps,\n }\n\n return render(<ProductDescription {...props} />)\n }\n\n it('should be mounted', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n })\n\n it('should match the snapshot with description', () => {\n const { asFragment, queryByText } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n expect(queryByText('Show more')).toBeInTheDocument()\n })\n\n it('should not show show more button', () => {\n const { queryByText } = renderComponent({ collapseContent: false })\n\n expect(queryByText('Show more')).toBeNull()\n })\n})\n\n```"
}
] |
code_store-components_0bff5d98
|
[
{
"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-components/react/__tests__/components/ProductPrice.test.js from the store-components 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 ProductPrice from '../../ProductPrice'\n\ndescribe('<ProductPrice />', () => {\n const defaultProps = {\n loaderClass: '',\n showListPrice: false,\n sellingPrice: 40,\n }\n\n const renderComponent = customProps => {\n const props = {\n ...defaultProps,\n ...customProps,\n }\n\n return render(<ProductPrice {...props} />)\n }\n\n it('should be mount', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot Loader', () => {\n const { asFragment } = renderComponent({ showListPrice: true })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should show selling price and list price (with labels)', () => {\n const customProps = {\n listPrice: 50,\n showLabels: true,\n showListPrice: true,\n labelSellingPrice: 'To',\n labelListPrice: 'From',\n }\n\n const { getByText } = renderComponent(customProps)\n\n expect(getByText('From')).toBeDefined()\n expect(getByText('To')).toBeDefined()\n expect(getByText('$40.00')).toBeDefined()\n expect(getByText('$50.00')).toBeDefined()\n })\n\n it('should show selling price and list price but with NO labels', () => {\n const customProps = {\n listPrice: 50,\n showLabels: false,\n showListPrice: true,\n labelSellingPrice: 'To',\n labelListPrice: 'From',\n }\n\n const { getByText, queryByText } = renderComponent(customProps)\n\n expect(queryByText('From')).toBeNull()\n expect(queryByText('To')).toBeNull()\n expect(getByText('$40.00')).toBeDefined()\n expect(getByText('$50.00')).toBeDefined()\n })\n\n // eslint-disable-next-line jest/no-identical-title\n it('should show selling price and list price but with NO labels', () => {\n const customProps = {\n listPrice: 50,\n showLabels: false,\n showListPrice: true,\n }\n\n const { getByText, queryByText } = renderComponent(customProps)\n\n expect(queryByText('From')).toBeNull()\n expect(queryByText('To')).toBeNull()\n expect(getByText('$40.00')).toBeDefined()\n expect(getByText('$50.00')).toBeDefined()\n })\n\n it('should show selling price and list price but with custom labels', () => {\n const customProps = {\n listPrice: 50,\n showLabels: true,\n showListPrice: true,\n labelSellingPrice: 'Now',\n labelListPrice: 'Was',\n }\n\n const { getByText } = renderComponent(customProps)\n\n expect(getByText('Was')).toBeDefined()\n expect(getByText('Now')).toBeDefined()\n expect(getByText('$40.00')).toBeDefined()\n expect(getByText('$50.00')).toBeDefined()\n })\n\n it('should show range selling price (not list price)', () => {\n const customProps = {\n listPrice: 50,\n showLabels: true,\n showListPrice: false,\n labelSellingPrice: 'Now',\n labelListPrice: 'Was',\n sellingPriceList: [30, 50, 20, 55],\n showSellingPriceRange: true,\n }\n\n const { getByText, queryByText } = renderComponent(customProps)\n\n // dont show labels\n expect(queryByText('Now')).toBeNull()\n expect(queryByText('Was')).toBeNull()\n // dont show selling price\n expect(queryByText('$40.00')).toBeNull()\n\n expect(getByText('$20.00 - $55.00')).toBeDefined()\n })\n\n it('show list price range and selling price range (no labels)', () => {\n const customProps = {\n listPrice: 50,\n showLabels: false,\n showListPrice: true,\n showListPriceRange: true,\n labelSellingPrice: 'Now',\n labelListPrice: 'Was',\n sellingPriceList: [30, 50, 20, 55],\n listPriceList: [100, 200, 300, 400],\n showSellingPriceRange: true,\n }\n\n const { getByText, queryByText } = renderComponent(customProps)\n\n // dont show labels\n expect(queryByText('Now')).toBeNull()\n expect(queryByText('Was')).toBeNull()\n // dont show selling price\n expect(queryByText('$40.00')).toBeNull()\n expect(queryByText('$50.00')).toBeNull()\n\n expect(getByText('$20.00 - $55.00')).toBeDefined()\n expect(getByText('$100.00 - $400.00')).toBeDefined()\n })\n\n it('show list price range and selling price range (with labels)', () => {\n const customProps = {\n listPrice: 50,\n showLabels: true,\n showListPrice: true,\n showListPriceRange: true,\n labelSellingPrice: 'Now',\n labelListPrice: 'Was',\n sellingPriceList: [30, 50, 20, 55],\n listPriceList: [100, 200, 300, 400],\n showSellingPriceRange: true,\n }\n\n const { getByText, queryByText } = renderComponent(customProps)\n\n // show labels\n expect(getByText('Now')).toBeDefined()\n expect(getByText('Was')).toBeDefined()\n // dont show selling price\n expect(queryByText('$40.00')).toBeNull()\n expect(queryByText('$50.00')).toBeNull()\n\n expect(getByText('$20.00 - $55.00')).toBeDefined()\n expect(getByText('$100.00 - $400.00')).toBeDefined()\n })\n})\n\n```"
}
] |
code_store-components_43110607
|
[
{
"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-components/react/__tests__/components/GradientCollapse.test.js from the store-components 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 GradientCollapse from '../../GradientCollapse'\n\ndescribe('<GradientCollapse /> component', () => {\n function renderComponent(customProps = {}) {\n const props = {\n collapseHeight: 50,\n ...customProps,\n }\n\n const component = <GradientCollapse {...props}>Test</GradientCollapse>\n\n return render(component)\n }\n\n it('should be able to mount and not break', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_0575b6e2
|
[
{
"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-components/react/__tests__/components/Container.test.js from the store-components 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 Container from '../../Container'\n\ndescribe('<Container /> component', () => {\n const renderComponent = customProps => {\n const comp = <Container {...customProps}> Test </Container>\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_9d1c2a61
|
[
{
"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-components/react/__tests__/components/ProductBrand.test.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render, wait } from '@vtex/test-tools/react'\n\nimport ProductBrand from '../../ProductBrand'\nimport type { ProductBrandProps } from '../../ProductBrand'\nimport brandLogoQuery from '../../graphql/productBrand.gql'\n\nconst mocks = [\n {\n request: {\n query: brandLogoQuery,\n variables: {\n id: 2000850,\n },\n },\n result: {\n data: {\n brand: {\n slug: 'billabong',\n imageUrl: '/220310/billabong.jpg',\n },\n },\n },\n },\n]\n\nconst mocksWithoutImage = [\n {\n request: {\n query: brandLogoQuery,\n variables: {\n id: 2000850,\n },\n },\n result: {\n data: {\n brand: {\n slug: 'billabong',\n },\n },\n },\n },\n]\n\ndescribe('<ProductBrand /> component', () => {\n const renderComponent = (props: ProductBrandProps) => {\n const comp = <ProductBrand {...props} loadingPlaceholder=\"logo\" />\n\n return render(comp, { graphql: { mocks } })\n }\n\n const renderComponentWithoutImage = (props: ProductBrandProps) => {\n const comp = <ProductBrand {...props} loadingPlaceholder=\"logo\" />\n\n return render(comp, { graphql: { mocks: mocksWithoutImage } })\n }\n\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n it('brand image should not have a link', async () => {\n const { queryByTestId } = renderComponent({})\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeNull()\n })\n\n it('brand image should be backwards compatible and have a link', async () => {\n const { queryByTestId } = renderComponent({\n logoWithLink: true,\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeDefined()\n expect(queryByTestId('name-redirect')).toBeNull()\n })\n\n it('brand text should have a link', async () => {\n const { queryByTestId } = renderComponent({\n withLink: 'text',\n displayMode: 'text',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeDefined()\n })\n\n it('brand text should have a link when withLink equals logoAndText', async () => {\n const { queryByTestId } = renderComponent({\n withLink: 'logoAndText',\n displayMode: 'text',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeDefined()\n })\n\n it('brand image should have a link when withLink equals logoAndText', async () => {\n const { queryByTestId } = renderComponent({\n withLink: 'logoAndText',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeDefined()\n expect(queryByTestId('name-redirect')).toBeNull()\n })\n\n it('brand should fallback to text and not have a link when withLinks equals logo', async () => {\n const { queryByTestId } = renderComponentWithoutImage({\n withLink: 'logo',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeNull()\n })\n\n it('brand should fallback to text and have a link when withLinks equals text', async () => {\n const { queryByTestId } = renderComponentWithoutImage({\n withLink: 'text',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeDefined()\n })\n\n it('brand should fallback to text and have a text link when withLink equals logoAndText', async () => {\n const { queryByTestId } = renderComponentWithoutImage({\n withLink: 'logoAndText',\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('logo-redirect')).toBeNull()\n expect(queryByTestId('name-redirect')).toBeDefined()\n })\n})\n\n```"
}
] |
code_store-components_a0846504
|
[
{
"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-components/react/__tests__/components/Newsletter.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { fireEvent, render } from '@vtex/test-tools/react'\n\nimport Newsletter from '../../components/Newsletter'\nimport subscribeNewsletter from '../../components/Newsletter/mutations/subscribeNewsletter.graphql'\n\nconst placeholderTextId = 'store/newsletter.placeholder'\nconst labelTextId = 'store/newsletter.label'\nconst submitTextId = 'store/newsletter.submit'\nconst thanksTextId = 'store/newsletter.confirmationTitle'\nconst errorTextId = 'store/newsletter.error'\n\ntest('should have label, input and submit', () => {\n const { getByLabelText, getByText } = render(\n <Newsletter\n placeholder={placeholderTextId}\n label={labelTextId}\n submit={submitTextId}\n />\n )\n\n const input = getByLabelText(labelTextId)\n const submit = getByText(submitTextId)\n\n expect(input).toBeTruthy()\n expect(submit).toBeTruthy()\n})\n\ntest('should add error message when user types wrong email', () => {\n const { getByLabelText, getByText } = render(\n <Newsletter\n placeholder={placeholderTextId}\n label={labelTextId}\n submit={submitTextId}\n />\n )\n\n const mockedInput = getByLabelText(labelTextId)\n const submit = getByText(submitTextId)\n\n const wrongEmail = 'foobar'\n\n fireEvent.change(mockedInput, { target: { value: wrongEmail } })\n fireEvent.click(submit)\n\n expect(mockedInput).toHaveAttribute('data-errormessage')\n})\n\ntest('should call mutation', async () => {\n const email = 'breno@mailinator.com'\n const mocks = [\n {\n request: {\n query: subscribeNewsletter,\n variables: { email },\n },\n result: {\n data: {\n subscribeNewsletter: {},\n },\n },\n },\n ]\n\n const { getByLabelText, getByText, findByText } = render(\n <Newsletter\n placeholder={placeholderTextId}\n label={labelTextId}\n submit={submitTextId}\n />,\n {\n graphql: { mocks, addTypename: false },\n }\n )\n\n const input = getByLabelText(labelTextId)\n const submit = getByText(submitTextId)\n\n fireEvent.change(input, { target: { value: email } })\n fireEvent.click(submit)\n\n const thanks = await findByText(thanksTextId)\n\n expect(thanks).toBeTruthy()\n})\n\ntest('should handle mutation error', async () => {\n const email = 'breno@mailinator.com'\n const mocks = [\n {\n request: {\n query: subscribeNewsletter,\n variables: { email },\n },\n error: new Error('ops'),\n },\n ]\n\n const { getByLabelText, getByText, findByText } = render(\n <Newsletter\n placeholder={placeholderTextId}\n label={labelTextId}\n submit={submitTextId}\n />,\n {\n graphql: { mocks, addTypename: false },\n }\n )\n\n const input = getByLabelText(labelTextId)\n const submit = getByText(submitTextId)\n\n fireEvent.change(input, { target: { value: email } })\n fireEvent.click(submit)\n\n const error = await findByText(errorTextId)\n\n expect(error).toBeTruthy()\n})\n\n```"
}
] |
code_store-components_384f1738
|
[
{
"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-components/react/__tests__/components/Greeting.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, waitFor } from '@vtex/test-tools/react'\n\nimport orderFormQuery from '../../components/Greeting/queries/orderForm.gql'\nimport Greeting from '../../Greeting'\n\nconst mocks = [\n {\n request: {\n query: orderFormQuery,\n },\n result: {\n data: {\n minicart: {\n orderForm: '{ \"clientProfileData\": { \"firstName\": \"Adam\" } }',\n },\n },\n },\n },\n]\n\ndescribe('<Greeting /> component', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n const renderComponent = customProps => {\n const props = {\n ...customProps,\n }\n\n return render(<Greeting {...props} />, { graphql: { mocks } })\n }\n\n it('should render name in orderForm', async () => {\n const { queryByText } = renderComponent()\n\n await waitFor(() => {\n jest.runAllTimers()\n })\n\n expect(queryByText('Adam')).not.toBeFalsy()\n })\n\n // eslint-disable-next-line jest/no-identical-title\n it('should render name in orderForm', async () => {\n const { queryByTestId } = renderComponent({ loading: true })\n\n await waitFor(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('greeting-loader')).not.toBeFalsy()\n })\n})\n\n```"
}
] |
code_store-components_8218202a
|
[
{
"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-components/react/__tests__/components/ProductSpecifications.test.js from the store-components 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 ProductSpecifications from '../../ProductSpecifications'\n\ndescribe('<ProductSpecifications /> component', () => {\n const renderComponent = customProps => {\n const props = {\n ...customProps,\n }\n\n const comp = <ProductSpecifications {...props} />\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot with table view and no specifications', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with table view and with specification', () => {\n const { asFragment } = renderComponent({\n specifications: [{ name: 'test', values: ['value'] }],\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with tabs view', () => {\n const { asFragment } = renderComponent({\n specifications: [{ name: 'test', values: ['value'] }],\n tabsMode: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_c83c7c98
|
[
{
"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-components/react/__tests__/components/DiscountBadge.test.js from the store-components 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 DiscountBadge from '../../DiscountBadge'\n\ndescribe('<DiscountBadge /> component', () => {\n function renderComponent(customProps = {}) {\n const props = {\n listPrice: 100,\n sellingPrice: 90,\n ...customProps,\n }\n\n const component = <DiscountBadge {...props}>Test</DiscountBadge>\n\n return render(component)\n }\n\n it('should be able to mount and not break', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot without label', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with label', () => {\n const { asFragment } = renderComponent({ label: 'LABEL' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_7d8be0c1
|
[
{
"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-components/react/__tests__/components/ShippingSimulator.test.js from the store-components 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 ShippingSimulator from '../../ShippingSimulator'\n\ndescribe('<ShippingSimulator /> component', () => {\n const renderComponent = (customProps = {}) => {\n const props = {\n country: 'brazil',\n ...customProps,\n }\n\n return render(<ShippingSimulator {...props} />)\n }\n\n it('should be able to mount and not break', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot without skuId and seller', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with skuId and seller', () => {\n const props = {\n skuId: 'skuId',\n seller: '1',\n }\n\n const { asFragment } = renderComponent(props)\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_97ae06e8
|
[
{
"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-components/react/__tests__/components/InfoCard.test.js from the store-components 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 InfoCard from '../../InfoCard'\n\ndescribe('<InfoCard />', () => {\n const renderComponent = props => {\n const defaultProps = {\n isFullModeStyle: false,\n headline: 'MY HEADLINE',\n subhead: 'MY SUBHEAD',\n imageUrl: 'my-image.com/image.png',\n callToActionText: 'CLICK HERE',\n callToActionUrl: 'classic-shoes/p',\n }\n\n return render(<InfoCard {...defaultProps} {...props} />)\n }\n\n it('should render with full mode style', () => {\n const { asFragment, getByTestId } = renderComponent({\n isFullModeStyle: true,\n })\n\n expect(asFragment()).toBeDefined()\n const container = getByTestId('container')\n\n expect(container.style['background-image']).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should render with image and text side by side', () => {\n const { asFragment, getByTestId } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n const halfImage = getByTestId('half-image')\n\n expect(halfImage).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should render without a call to action', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should wrap half image in a link with imageActionUrl', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: false,\n callToActionMode: 'none',\n imageActionUrl: 'classic-shoes/p',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should wrap whole container in a link with imageActionUrl', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n imageActionUrl: 'classic-shoes/p',\n textAlignment: 'right',\n textPosition: 'center',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should insert span with class on headline', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n textAlignment: 'right',\n textPosition: 'center',\n headline:\n 'HEADLINE <span class=\"my-custom-class\">THIS IS BOOOLD AND BLUE</span> HEADLINE STILL',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should not render subhead', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n textAlignment: 'right',\n textPosition: 'center',\n headline:\n 'HEADLINE <span class=\"my-custom-class\">THIS IS BOOOLD AND BLUE</span> HEADLINE STILL',\n subhead: '',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it(\"should render subhead and headline using the RichText component when textMode is set to 'rich-text'\", () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n textAlignment: 'right',\n textPosition: 'center',\n textMode: 'rich-text',\n headline: 'This is a headline, and should be inside a rich-text.',\n subhead: 'This is a subhead, and should be inside a rich-text.',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it('should not render bodyText', () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n textAlignment: 'right',\n textPosition: 'center',\n headline:\n 'HEADLINE <span class=\"my-custom-class\">THIS IS BOOOLD AND BLUE</span> HEADLINE STILL',\n subhead: '',\n bodyText: '',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n it(\"should render bodyText, subhead and headline using the RichText component when textMode is set to 'rich-text'\", () => {\n const { asFragment } = renderComponent({\n isFullModeStyle: true,\n callToActionMode: 'none',\n textAlignment: 'right',\n textPosition: 'center',\n textMode: 'rich-text',\n headline: 'This is a headline, and should be inside a rich-text.',\n subhead: 'This is a subhead, and should be inside a rich-text.',\n bodyText: 'This is a bodyText, and should be inside a rich-text.',\n })\n\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_24079865
|
[
{
"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-components/react/__tests__/components/Logo.test.js from the store-components 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 Logo from '../../Logo'\n\ndescribe('<Logo /> component', () => {\n const renderComponent = customProps => {\n const props = {\n title: 'title',\n ...customProps,\n }\n\n const comp = <Logo {...props} />\n\n return render(comp)\n }\n\n it('should match snapshot with link', () => {\n const { asFragment } = renderComponent({ href: 'http://logotest.test' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot without link', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with url', () => {\n const { asFragment } = renderComponent({ url: 'http://logourl.test' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_0572dfaf
|
[
{
"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-components/react/__tests__/components/BuyButton.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { fireEvent, waitFor, render } from '@vtex/test-tools/react'\n\nimport BuyButton from '../../BuyButton'\nimport addToCartMutation from '../../components/BuyButton/mutations/addToCart.gql'\n\nconst mocks = [\n {\n request: {\n query: addToCartMutation,\n variables: { items: [] },\n },\n result: {\n data: {\n addToCart: {},\n },\n },\n },\n]\n\ndescribe('<BuyButton />', () => {\n const renderComponent = (customProps, text = 'Test') => {\n const props = {\n available: true,\n ...customProps,\n }\n\n return render(<BuyButton {...props}>{text}</BuyButton>, {\n graphql: { mocks },\n })\n }\n\n it('should be rendered', async () => {\n const { asFragment } = renderComponent()\n\n await waitFor(() => {})\n expect(asFragment()).toBeDefined()\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot normal', async () => {\n const { asFragment } = renderComponent({ available: true, skuItems: [] })\n\n await waitFor(() => {})\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot unavailable', async () => {\n const { asFragment } = renderComponent({ available: false, skuItems: [] })\n\n await waitFor(() => {})\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot loading', async () => {\n const { asFragment } = renderComponent({ available: false })\n\n await waitFor(() => {})\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should call onAddStart and onAddFinish', async () => {\n const onAddStart = jest.fn()\n const onAddFinish = jest.fn()\n\n const buttonText = 'Add to cart'\n\n const { getByText } = renderComponent(\n {\n available: true,\n skuItems: [],\n onAddStart,\n onAddFinish,\n },\n buttonText\n )\n\n await waitFor(() => {\n fireEvent.click(getByText(buttonText))\n })\n\n const assertions = () => {\n expect(onAddStart).toBeCalledTimes(1)\n expect(onAddFinish).toBeCalledTimes(1)\n }\n\n expect.assertions(assertions)\n })\n\n // eslint-disable-next-line jest/expect-expect\n it('should show items prices', async () => {\n const skuItems = [\n {\n skuId: '1',\n quantity: 2,\n seller: '1',\n name: 'Item',\n brand: 'fo',\n price: 100,\n options: [\n { assemblyId: '1', id: '2', quantity: 2, seller: '1' },\n { assemblyId: '1', id: '3', quantity: 1, seller: '1' },\n ],\n assemblyOptions: {\n added: [\n {\n normalizedQuantity: 2,\n extraQuantity: 2,\n choiceType: 'MULTIPLE',\n item: {\n name: 'Assembly One',\n sellingPrice: 5,\n quantity: 2,\n id: '1',\n sellingPriceWithAssemblies: 6,\n assemblyOptions: {\n added: [\n {\n item: {\n sellingPrice: 1,\n id: '3',\n quantity: 1,\n name: 'Recursive',\n sellingPriceWithAssemblies: 1,\n },\n },\n ],\n },\n },\n },\n {\n normalizedQuantity: 1,\n extraQuantity: 1,\n choiceType: 'MULTIPLE',\n item: {\n name: 'Assembly Two',\n sellingPrice: 3,\n quantity: 1,\n id: '2',\n sellingPriceWithAssemblies: 3,\n },\n },\n ],\n removed: [],\n parentPrice: 100,\n },\n sellingPriceWithAssemblies: 115,\n },\n ]\n\n const { getByText } = renderComponent(\n {\n available: true,\n skuItems,\n showItemsPrice: true,\n },\n null\n )\n\n const priceRegex = /230.00/\n\n await waitFor(() => {})\n getByText(priceRegex)\n })\n})\n\n```"
}
] |
code_store-components_77c0d304
|
[
{
"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-components/react/__tests__/components/Animation.test.js from the store-components 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 Animation from '../../Animation'\n\ndescribe('<Animation /> component', () => {\n const renderComponent = customProps => {\n const comp = <Animation {...customProps}> Test </Animation>\n\n return render(comp)\n }\n\n it('should be rendered', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot animation left', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot animation right', () => {\n const { asFragment } = renderComponent({ type: 'drawerRight' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot animation top', () => {\n const { asFragment } = renderComponent({ type: 'drawerTop' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot animation bottom', () => {\n const { asFragment } = renderComponent({ type: 'drawerBottom' })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_9d510453
|
[
{
"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-components/react/__tests__/components/ProductName.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport PropTypes from 'prop-types'\n\nimport ProductName from '../../ProductName'\n\ndescribe('<ProductName />', () => {\n const defaultProps = {\n loaderClass: '',\n name: 'ProductTest',\n }\n\n const context = { culture: { currency: 'USD' } }\n\n const renderComponent = customProps => {\n const props = {\n ...defaultProps,\n ...customProps,\n }\n\n return render(<ProductName {...props} />, {\n context,\n childContextTypes: {\n culture: PropTypes.object,\n },\n })\n }\n\n it('should be mounted', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeDefined()\n })\n\n it('should match the snapshot with only Name', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Name and SkuName', () => {\n const { asFragment } = renderComponent({\n skuName: 'ProductSkuName',\n showSku: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Name and Brand', () => {\n const { asFragment } = renderComponent({\n brandName: 'ProductBrandName',\n showBrandName: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Name and Product Reference', () => {\n const { asFragment } = renderComponent({\n productReference: 'productReferenceTest',\n showProductReference: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with Name and Sponsored Badge', () => {\n const { asFragment } = renderComponent({\n sponsoredBadgeLabel: 'sponsoredBadgeTest',\n showSponsoredBadge: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot with all options', () => {\n const { asFragment } = renderComponent({\n skuName: 'ProductSkuName',\n showSku: true,\n brandName: 'ProductBrandName',\n showBrandName: true,\n productReference: 'productReferenceTest',\n showProductReference: true,\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot Loader', () => {\n const { asFragment } = renderComponent({ name: undefined })\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_e1f777aa
|
[
{
"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-components/react/__tests__/components/AvailabilitySubscriber.test.js from the store-components 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 AvailabilitySubscriber from '../../AvailabilitySubscriber'\n\ndescribe('<AvailabilitySubscriber />', () => {\n function renderComponent(customProps = {}) {\n const props = {\n skuId: '111111',\n available: false,\n ...customProps,\n }\n\n return render(<AvailabilitySubscriber {...props} />)\n }\n\n it('should be able to mount and not break', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toBeTruthy()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderComponent()\n\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-components_7f7fc379
|
[
{
"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-components/react/__tests__/hooks/useMarketingSessionParams.test.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { renderHook, act } from '@testing-library/react-hooks'\n\nimport useMarketingSessionParams from '../../components/BuyButton/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\ntest('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 =>\n resolve(fakeSessionWithData)\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n // eslint-disable-next-line no-return-await\n await act(async () => await Promise.resolve())\n\n const { utmParams, utmiParams } = result.current\n\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\ntest('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 =>\n resolve(fakeSessionNoData)\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n // eslint-disable-next-line no-return-await\n await act(async () => await Promise.resolve())\n\n const { utmParams, utmiParams } = result.current\n\n expect(utmParams).toBeUndefined()\n expect(utmiParams).toBeUndefined()\n})\n\ntest('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) =>\n reject()\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n // eslint-disable-next-line no-return-await\n await act(async () => await Promise.resolve())\n\n const { utmParams, utmiParams } = result.current\n\n expect(utmParams).toBeUndefined()\n expect(utmiParams).toBeUndefined()\n})\n\n```"
}
] |
code_store-components_5242ce5e
|
[
{
"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-components/react/__tests__/hooks/useEffectkSkipMount.test.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { renderHook } from '@vtex/test-tools/react'\n\nimport useEffectSkipMount from '../../components/SKUSelector/components/hooks/useEffectSkipMount'\n\ntest('ensure that function wont be called on first render', () => {\n const fakeFn = jest.fn()\n const deps = ['a']\n const { rerender } = renderHook(() => useEffectSkipMount(fakeFn, deps))\n\n expect(fakeFn).toBeCalledTimes(0)\n rerender()\n expect(fakeFn).toBeCalledTimes(0)\n})\n\ntest('ensure that after prop changes, provided function is called', () => {\n const fakeFn = jest.fn()\n const { rerender } = renderHook(\n ({ deps }) => useEffectSkipMount(fakeFn, deps),\n {\n initialProps: {\n deps: ['a'],\n },\n }\n )\n\n expect(fakeFn).toBeCalledTimes(0)\n rerender({ deps: ['b'] })\n expect(fakeFn).toBeCalledTimes(1)\n})\n\n```"
}
] |
code_store-components_578b841b
|
[
{
"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-components/react/__tests__/hooks/useCommercialOffer.test.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { renderHook } from '@vtex/test-tools/react'\nimport { ProductContextState } from 'vtex.product-context/react/ProductTypes'\n\nimport { useCommercialOffer } from '../../utils/useCommercialOffer'\n\nlet mockEnableDefaultSeller = true\n\njest.mock('vtex.render-runtime', () => {\n return {\n useRuntime: jest.fn(() => ({\n getSettings() {\n return {\n enableDefaultSeller: mockEnableDefaultSeller,\n }\n },\n })),\n }\n})\n\nconst ctx = {\n selectedItem: {\n sellers: [\n {\n sellerDefault: false,\n commertialOffer: 1000,\n },\n {\n sellerDefault: true,\n commertialOffer: 2000,\n },\n ],\n },\n} as unknown as Partial<ProductContextState>\n\ntest('Should return the commercial offer from the defaultSeller', () => {\n const { result } = renderHook(() => useCommercialOffer(ctx))\n\n expect(result.current).toBe(2000)\n})\n\ntest('Should return the commercial offer from the first seller', () => {\n mockEnableDefaultSeller = false\n const { result } = renderHook(() => useCommercialOffer(ctx))\n\n expect(result.current).toBe(1000)\n})\n\n```"
}
] |
code_store-components_22f18a37
|
[
{
"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-components/react/__tests__/modules/sanitizedHTML.test.tsx from the store-components 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 { SanitizedHTML } from '../../components/SanitizedHTML'\n\ntest('renders a simple string', () => {\n const { container } = render(<SanitizedHTML content=\"Potato\" />)\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n Potato\n </div>\n `)\n})\n\ntest('filters out script tags', () => {\n const { container } = render(\n <SanitizedHTML content=\"<script>console.log('potato')</script><h1>Hey</h1>\" />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <h1>\n Hey\n </h1>\n </div>\n `)\n})\n\ntest('filters out attributes', () => {\n const { container } = render(\n <SanitizedHTML\n allowedAttributes={{ h1: ['potato'] }}\n content={`<h1 potato=\"🥔\" fruit=\"🍎\">Hey</h1>`}\n />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <h1\n potato=\"🥔\"\n >\n Hey\n </h1>\n </div>\n `)\n})\n\ntest('filters out classes', () => {\n const { container } = render(\n <SanitizedHTML\n allowedClasses={{ h1: ['🥔', '🍇'] }}\n content={`<h1 class=\"🥔 🍎 🍇\">Hey</h1>`}\n />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <h1\n class=\"🥔 🍎 🍇\"\n >\n Hey\n </h1>\n </div>\n `)\n})\n\ntest('filters out tags', () => {\n const { container } = render(\n <SanitizedHTML\n allowedTags={['h1', 'h3']}\n content={`<h1>Hey</h1><h2>Ho</h2><h3>Let's go</h3>`}\n />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <h1>\n Hey\n </h1>\n <h3>\n Let's go\n </h3>\n </div>\n `)\n})\n\ntest('renders iframes', () => {\n const { container } = render(\n <SanitizedHTML\n content={`<iframe src=\"https://player.vimeo.com/video/402279141\" frameborder=\"0\" \n allow=\"autoplay; fullscreen\" allowfullscreen=\"\" style=\"position: relative; height: 200px; width: 100%;\"></iframe>`}\n />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <iframe\n allow=\"autoplay; fullscreen\"\n allowfullscreen=\"\"\n frameborder=\"0\"\n src=\"https://player.vimeo.com/video/402279141\"\n style=\"position: relative; height: 200px; width: 100%;\"\n />\n </div>\n `)\n})\n\ntest('renders divs and spans with classes, styles and ids', () => {\n const { container } = render(\n <SanitizedHTML\n content={`<div id=\"the-potato\" class=\"🥔\">potato</div><span style=\"font-size: 22px;\">big 🥔</span>`}\n />\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n style=\"display: contents;\"\n >\n <div\n class=\"🥔\"\n id=\"the-potato\"\n >\n potato\n </div>\n <span\n style=\"font-size: 22px;\"\n >\n big 🥔\n </span>\n </div>\n `)\n})\n\n```"
}
] |
code_checkout-old_65859f4f
|
[
{
"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 checkout-old/messages/pt.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"editor.base-store-component.title\": \"IO Base App\",\n \"editor.base-store-component.description\": \"Um componente de demonstração para apps do VTEX IO\",\n \"editor.base-store-component.title.title\": \"Título\",\n \"editor.base-store-component.title.description\": \"Especifique um título personalizado\",\n \"base.title\": \"Olá, Mundo!!\",\n \"base.change-value\": \"Troque seu valor: {value}\"\n}\n```"
}
] |
code_checkout-old_1a7b70aa
|
[
{
"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 checkout-old/messages/en.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"editor.base-store-component.title\": \"IO Base App\",\n \"editor.base-store-component.description\": \"A demo component for IO apps\",\n \"editor.base-store-component.title.title\": \"Title\",\n \"editor.base-store-component.title.description\": \"Specify a custom title\",\n \"base.title\": \"Hello, World!!\",\n \"base.change-value\": \"Change your value: {value}\"\n}\n```"
}
] |
code_checkout-old_7cede988
|
[
{
"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 checkout-old/messages/context.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"editor.base-store-component.title\": \"Title of IO Base App component\",\n \"editor.base-store-component.description\": \"Description of IO Base App component\",\n \"editor.base-store-component.title.title\": \"Title of title property\",\n \"editor.base-store-component.title.description\": \"Description of title property\",\n \"base.title\": \"Base title message to be shown when title is not provided via CMS\",\n \"base.change-value\": \"Text to be shown beside input component typed value\"\n}\n```"
}
] |
code_checkout-old_6c62aeae
|
[
{
"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 checkout-old/messages/es.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"editor.base-store-component.title\": \"IO Base App\",\n \"editor.base-store-component.description\": \"Un componente de demostración para aplicaciones IO.\",\n \"editor.base-store-component.title.title\": \"Título\",\n \"editor.base-store-component.title.description\": \"Especifique un título personalizado\",\n \"base.title\": \"¡Hola Mundo!\",\n \"base.change-value\": \"Cambia tu valor: {value}\"\n}\n```"
}
] |
code_checkout-old_d0628021
|
[
{
"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 checkout-old/react/HomeWrapper.js from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useMemo } from 'react'\nimport PropTypes from 'prop-types'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport useDataPixel from './hooks/useDataPixel'\n\nconst HomeWrapper = ({ children }) => {\n const { account } = useRuntime()\n\n const pixelEvents = useMemo(\n () =>\n typeof document !== 'undefined' && {\n event: 'pageInfo',\n eventType: 'homeView',\n accountName: account,\n pageTitle: document.title,\n pageUrl: location.href,\n pageCategory: 'Home',\n },\n [account]\n )\n\n useDataPixel(pixelEvents)\n\n return children\n}\n\nHomeWrapper.propTypes = {\n children: PropTypes.element,\n}\n\nexport default HomeWrapper\n```"
}
] |
code_checkout-old_d0b1bf59
|
[
{
"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 checkout-old/react/package.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"@vtex/css-handles\": \"^1.0.0\",\n \"classnames\": \"^2.2.6\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.3\",\n \"react-dom\": \"^16.8.3\",\n \"react-intl\": \"^2.7.2\"\n },\n \"devDependencies\": {\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^0.2.0\",\n \"apollo-client\": \"^2.5.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"prettier\": \"^1.18.2\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.5.2\"\n }\n}\n\n```"
}
] |
code_checkout-old_4db00069
|
[
{
"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 checkout-old/store/blocks.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.checkout.cart\": {\n \"blocks\": [\"checkout-cart\"]\n }\n}\n```"
}
] |
code_checkout-old_4dabef08
|
[
{
"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 checkout-old/store/interfaces.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.checkout\": {\n \"allowConditions\": true,\n \"component\": \"*\",\n \"before\": [\"header.full\"],\n \"after\": [\"footer\", \"pixels\"],\n \"preview\": {\n \"type\": \"transparent\",\n \"height\": 600\n }\n },\n \"store.checkout.cart\": {\n \"around\": [\"homeWrapper\"],\n \"allowed\": [\"checkout-cart\"],\n \"preview\": {\n \"type\": \"box\",\n \"height\": 1400\n }\n }\n}\n```"
}
] |
code_checkout-old_89b11946
|
[
{
"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 checkout-old/store/routes.json from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.checkout.cart\": {\n \"path\": \"/cart/\"\n }\n}\n\n```"
}
] |
code_checkout-old_635202bb
|
[
{
"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 checkout-old/react/typings/storefront.d.ts from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```"
}
] |
code_checkout-old_55111be4
|
[
{
"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 checkout-old/react/typings/vtex.render-runtime.d.ts from the checkout-old 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, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = function({ id: string }): object {}\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n}\n\n```"
}
] |
code_checkout-old_3aad9b94
|
[
{
"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 checkout-old/react/typings/css.d.ts from the checkout-old 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_checkout-old_d9133798
|
[
{
"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 checkout-old/react/typings/graphql.d.ts from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_checkout-old_f842b1cc
|
[
{
"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 checkout-old/react/typings/vtex.styleguide.d.ts from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```"
}
] |
code_checkout-old_19f8c5f7
|
[
{
"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 checkout-old/react/components/TranslatedTitle.tsx from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { FormattedMessage } from 'react-intl'\n\n// The b-s token makes the `b` class be applied only on mobile devices.\nconst TranslatedTile: FunctionComponent<TranslatedTileProps> = ({ title }) => {\n const titleText = title || <FormattedMessage id=\"base.title\" />\n return (\n <div className=\"flex flex-grow-1 justify-center b-s\">\n <span className=\"t-heading-4\">{titleText}</span>\n </div>\n )\n}\n\ninterface TranslatedTileProps {\n title?: string\n}\n\nexport default TranslatedTile\n\n```"
}
] |
code_checkout-old_0e291496
|
[
{
"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 checkout-old/react/hooks/useDataPixel.js from the checkout-old VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useRef } from 'react'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\n\nconst useDataPixel = (data, isLoading = false) => {\n const { push } = usePixel()\n const prevLoadingRef = useRef(true)\n\n useEffect(() => {\n if (prevLoadingRef.current && !isLoading) {\n if (!data) {\n return\n }\n\n if (Array.isArray(data)) {\n data.forEach(event => push(event))\n } else {\n push(data)\n }\n }\n\n prevLoadingRef.current = isLoading\n }, [data, isLoading, push])\n}\n\nexport default useDataPixel\n\n```"
}
] |
code_stack-layout_dab45bf4
|
[
{
"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 stack-layout/messages/pt.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.stack-layout.title\": \"Pilha\",\n \"admin/editor.stack-layout.description\": \"Componente usado para colocar blocos um sobre os outros\",\n \"store/stack-layout.aria-label\": \"Seção flutuante\"\n}\n\n```"
}
] |
code_stack-layout_6b429b67
|
[
{
"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 stack-layout/messages/en.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.stack-layout.title\": \"Stack Layout\",\n \"admin/editor.stack-layout.description\": \"Component used to put blocks over each other\",\n \"store/stack-layout.aria-label\": \"Floating section\"\n}\n\n```"
}
] |
code_stack-layout_1ac2048f
|
[
{
"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 stack-layout/messages/context.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.stack-layout.title\": \"Title of Stack Layout\",\n \"admin/editor.stack-layout.description\": \"Description of the Stack Layout component\",\n \"store/stack-layout.aria-label\": \"Floating section\"\n}\n\n```"
}
] |
code_stack-layout_e07ddba7
|
[
{
"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 stack-layout/messages/es.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.stack-layout.title\": \"Pila\",\n \"admin/editor.stack-layout.description\": \"Componente utilizado para colocar bloques uno encima del otro\",\n \"store/stack-layout.aria-label\": \"Sección flotante\"\n}\n\n```"
}
] |
code_stack-layout_b1c43ca2
|
[
{
"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 stack-layout/docs/README.md from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Stack Layout\n\nUse this layout component to show blocks on top of other blocks.\n\n\n\nEach child passed to `stack-layout` will receive an increasingly higher value of `zIndex`.\n\nThis means `flex-layout.row#viewone` will appear on the bottom, `flex-layout.row#viewtwo` will appear over it with `zIndex` of value 2, and `flex-layout.row#viewthree` will appear over them both with `zIndex` of value 3. Another thing to notice is that if you pass the `blockClass` prop to any children of the `stack-layout`, it will apply the `blockClass` to the element that wraps the child element.\n\n## Configuration\n\n1. Import the Stack Layout app to your theme's dependencies to the `manifest.json`:\n\n```json\n \"dependencies\": {\n \"vtex.stack-layout\": \"0.x\"\n }\n```\n\n2. Add the `stack-layout` block to the desired template. For example:\n\n```json\n\"stack-layout\": {\n \"children\": [\"flex-layout.row#viewone\", \"flex-layout.row#viewtwo\", \"flex-layout.row#viewthree]\n}\n```\n\n| Prop name | Type | Description | Default value |\n| -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `blockClass` | `string` | Allows to pass a custom name to be added to component CSS classes. | `null` |\n| `zIndexOffset` | `number` | An offset to be passed to the zIndex of the children of the stack layout. If you pass `3`, the first children will have `zIndex` of 3, and the next layer will have `zIndex` of 4, and so on. | `0` |\n| `arialabel` | `string` | A value to customize the aria-label property | `null` |\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization). \n\n| CSS Handles |\n| ------------------|\n| `stackContainer` |\n| `stackItem` |\n| `stackItem--first`|\n\n```"
}
] |
code_stack-layout_bb24cff6
|
[
{
"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 stack-layout/react/index.tsx from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { useCssHandles, applyModifiers } from 'vtex.css-handles'\nconst CSS_HANDLES = ['stackContainer', 'stackItem'] as const\n\ninterface Props {\n zIndexOffset?: number,\n arialabel?: string\n}\n\nconst StackLayout: StorefrontFunctionComponent<Props> = ({\n children,\n zIndexOffset = 0,\n arialabel\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const intl = useIntl()\n return (\n <div className={`${handles.stackContainer} relative`} aria-label={arialabel ? arialabel : intl.formatMessage(\n { id: 'store/stack-layout.aria-label' })}>\n {React.Children.toArray(children).map((child, idx) => {\n\n // This allows the user customize the stackItem via CSS, via the blockClass of each child\n const childBlockClass = (child as any)?.props?.blockProps?.blockClass || ''\n let stackItemBlockClass = ''\n if (childBlockClass) {\n stackItemBlockClass = applyModifiers(handles.stackItem, childBlockClass)\n }\n\n if (idx === 0) {\n return (\n <div\n key={idx}\n className={`${applyModifiers(handles.stackItem, 'first')} ${stackItemBlockClass}`}\n style={{ zIndex: zIndexOffset + 1 }}\n >\n {child}\n </div>\n )\n }\n\n return (\n <div\n key={idx}\n className={`${handles.stackItem} absolute top-0 left-0 w-auto h-auto ${stackItemBlockClass}`}\n style={{ zIndex: zIndexOffset + idx + 1 }}\n >\n {child}\n </div>\n )\n })}\n </div>\n )\n}\n\nconst messages = defineMessages({\n title: {\n defaultMessage: '',\n id: 'admin/editor.stack-layout.title',\n },\n description: {\n defaultMessage: '',\n id: 'admin/editor.stack-layout.description',\n },\n})\n\nStackLayout.schema = {\n title: messages.title.id,\n description: messages.description.id,\n}\n\nexport default StackLayout\n\n```"
}
] |
code_stack-layout_fc2bfb88
|
[
{
"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 stack-layout/react/package.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.6\",\n \"react-intl\": \"^3.12.1\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.2\",\n \"@types/ramda\": \"^0.26.8\",\n \"@types/react\": \"^16.8.13\",\n \"@types/react-intl\": \"^2.3.17\"\n },\n \"version\": \"0.1.3\"\n}\n\n```"
}
] |
code_stack-layout_da343a2f
|
[
{
"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 stack-layout/store/interfaces.json from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"stack-layout\": {\n \"component\": \"index\",\n \"composition\": \"children\",\n \"allowed\": \"*\"\n }\n}\n\n```"
}
] |
code_stack-layout_00e585a6
|
[
{
"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 stack-layout/react/typings/vtex.css-handles.d.ts from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n type CssHandlesInput = readonly string[]\n type ValueOf<T extends readonly any[]> = T[number]\n type CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\n interface CssHandlesOptions {\n migrationFrom?: string | string[]\n }\n\n export const useCssHandles: <T extends CssHandlesInput>(\n handles: T,\n options: CssHandlesOptions = {}\n ) => CssHandles<T>\n export const applyModifiers: (\n handles: string,\n modifier: string | string[]\n ) => string\n}\n\n```"
}
] |
code_stack-layout_8b875db6
|
[
{
"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 stack-layout/react/typings/global.d.ts from the stack-layout VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\nimport { TachyonsScaleInput } from '../hooks/tachyons'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n schema?: object\n getSchema?(props?: P): object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n schema?: object\n getSchema?(props: P): object\n }\n\n interface StorefrontElement extends ReactElement {\n schema?: object\n getSchema?(props: P): object\n }\n}\n\n```"
}
] |
code_order-form-courier_6214acd2
|
[
{
"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 order-form-courier/docs/README.md from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Order Form Courier\n\nThis app listens to orderForm events `orderFormUpdated.vtex` and sends those events to courier.\n```"
}
] |
code_order-form-courier_50416cd2
|
[
{
"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 order-form-courier/node/service.json from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 120,\n \"timeout\": 10,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"notify\": {\n \"path\": \"/_v/order-form-courier/notify\",\n \"public\": true\n }\n },\n \"events\": {\n \"orderFormEmailUpdated\": {\n \"sender\": \"order-form-courier\",\n \"keys\": [\"order-form-email-updated\"]\n }\n }\n}\n\n```"
}
] |
code_order-form-courier_a6e7a1ed
|
[
{
"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 order-form-courier/node/package.json from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/clients\": \"^2.11.0\",\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^26.0.24\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.6\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"jest\": \"^27.0.6\",\n \"ts-jest\": \"^27.0.4\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\",\n \"test\": \"jest --collectCoverage\"\n },\n \"jest\": {\n \"testMatch\": [\n \"**/__tests__/**/+(spec|test).+(ts|tsx|js)\",\n \"**/?(*.)+(spec|test).+(ts|tsx|js)\"\n ],\n \"transform\": {\n \"^.+\\\\.(ts|tsx)$\": \"ts-jest\"\n }\n },\n \"version\": \"0.7.0\"\n}\n\n```"
}
] |
code_order-form-courier_0207e3b9
|
[
{
"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 order-form-courier/node/index.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext, RecorderState } from '@vtex/api'\nimport { method, LRUCache, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { notify } from './middlewares/notify'\n\nconst TIMEOUT_MS = 800\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, never>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n type State = RecorderState\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n notify: method({\n POST: [notify],\n }),\n },\n})\n\n```"
}
] |
code_order-form-courier_e772a58f
|
[
{
"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 order-form-courier/pages/pages.json from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"extensions\": {\n \"checkout/universal/orderFormEvents\": {\n \"component\": \"index\"\n }\n }\n }\n```"
}
] |
code_order-form-courier_1b4c3e53
|
[
{
"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 order-form-courier/react/index.tsx from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport OrderFormUpdateHandler from './OrderFormUpdateHandler'\n\nconst EventListenerTest: React.FC = () => {\n return <OrderFormUpdateHandler />\n}\n\nexport default EventListenerTest\n\n```"
}
] |
code_order-form-courier_e6d75273
|
[
{
"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 order-form-courier/react/package.json from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"order-form-poc\",\n \"version\": \"0.0.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"axios\": \"^0.24.0\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/jquery\": \"^3.5.9\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/clients\": \"^2.17.0\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\"\n }\n}\n\n```"
}
] |
code_order-form-courier_bc214f9b
|
[
{
"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 order-form-courier/react/OrderFormUpdateHandler.tsx from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect } from 'react'\nimport type { OrderForm } from '@vtex/clients'\n\nimport { notificationClient } from './clients/notificationClient'\nimport { useOrderFormMonitor } from './hooks/useOrderFormMonitor'\nimport { onEmailChanged } from './eventHandlers/onEmailChanged'\n\nconst OrderFormUpdateHandler: React.FC = () => {\n const client = notificationClient()\n const eventHandler = useOrderFormMonitor([onEmailChanged])\n\n const handleOrderFormUpdated = async (_: unknown, orderForm: OrderForm) => {\n const events = eventHandler(orderForm)\n\n await client.notify(events)\n }\n\n useEffect(() => {\n $(window).on('orderFormUpdated.vtex', handleOrderFormUpdated)\n\n return () => {\n $(window).off('orderFormUpdated.vtex', handleOrderFormUpdated)\n }\n }, [eventHandler])\n\n return <></>\n}\n\nexport default OrderFormUpdateHandler\n\n```"
}
] |
code_order-form-courier_ef6e2baf
|
[
{
"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 order-form-courier/node/clients/index.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {}\n\n```"
}
] |
code_order-form-courier_e4e88e9c
|
[
{
"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 order-form-courier/node/typings/orderFormEvent.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface OrderFormEvent {\n eventName: string\n eventObject: unknown\n triggered: boolean\n}\n\n```"
}
] |
code_order-form-courier_6a408047
|
[
{
"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 order-form-courier/node/middlewares/notify.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport type { OrderFormEvent } from '../typings/orderFormEvent'\n\nexport async function notify(ctx: Context, next: () => Promise<unknown>) {\n const {\n clients: { events },\n } = ctx\n\n const orderFormEvents = (await json(ctx.req)).events as OrderFormEvent[]\n\n const eventsPromise = orderFormEvents\n .filter((e) => e.triggered)\n .map((e) => events.sendEvent('', e.eventName, e.eventObject))\n\n await Promise.all(eventsPromise)\n\n ctx.status = 200\n await next()\n}\n\n```"
}
] |
code_order-form-courier_d15c3893
|
[
{
"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 order-form-courier/react/clients/notificationClient.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport axios from 'axios'\n\nimport type { OrderFormEvent } from '../typings/orderFormEvent'\n\nexport const notificationClient = () => {\n return {\n notify: (events: Array<OrderFormEvent<{ orderFormId: string }>>) => {\n return axios.post('/_v/order-form-courier/notify', {\n events,\n })\n },\n }\n}\n\n```"
}
] |
code_order-form-courier_b4e4493c
|
[
{
"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 order-form-courier/react/eventHandlers/onEmailChanged.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { OrderForm } from '@vtex/clients'\n\nimport type { OrderFormEvent } from '../typings/orderFormEvent'\n\nexport const onEmailChanged = (old: OrderForm, updated: OrderForm) => {\n const oldEmail = old?.clientProfileData?.email\n const newEmail = updated?.clientProfileData?.email\n\n return {\n eventName: 'order-form-email-updated',\n eventObject: { email: newEmail, orderFormId: updated.orderFormId },\n triggered: oldEmail !== newEmail,\n } as OrderFormEvent<{ email: string; orderFormId: string }>\n}\n\n```"
}
] |
code_order-form-courier_c5670ad1
|
[
{
"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 order-form-courier/react/typings/gql.d.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import type { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```"
}
] |
code_order-form-courier_dfeee040
|
[
{
"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 order-form-courier/react/typings/orderFormEvent.d.ts from the order-form-courier VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { OrderForm } from '@vtex/clients'\n\nexport interface OrderFormEvent<T extends { orderFormId: string }> {\n eventName: string\n eventObject: T\n triggered: boolean\n}\n\nexport type OrderFormEventHandler = (\n orderForm: OrderForm,\n newOrderForm: OrderForm\n) => OrderFormEvent<{ orderFormId: string }>\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.