id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-components_b5a8e5d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/storefront.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ntype GenericObject = Record<string, any>\n\ndeclare global {\n interface StorefrontFC<P = GenericObject> extends FunctionComponent<P> {\n getSchema?(props: P): GenericObject\n schema?: GenericObject\n }\n\n interface StorefrontComponent<P = GenericObject, S = GenericObject>\n extends Component<P, S> {\n getSchema?(props: P): GenericObject\n schema: GenericObject\n }\n}\n\n```"
}
] |
code_store-components_33f5f029
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/jsx.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport 'react'\n\ndeclare module 'react' {\n interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {\n loading?: 'lazy' | 'eager' | 'auto'\n fetchPriority?: 'high' | 'low' | 'auto'\n }\n}\n\n```"
}
] |
code_store-components_82c2a207
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/vtex.product-context.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\ninterface ProductItem {\n itemId: string\n name: string\n images: Image[]\n variations: Array<{\n name: string\n values: string[]\n }>\n sellers: Array<{\n sellerDefault: boolean\n commertialOffer: {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n }\n }>\n}\n\ninterface Product {\n brand: string\n brandId: string\n itemMetadata: ItemMetadata\n items: ProductItem[]\n linkText: string\n productId: string\n skuSpecifications: SkuSpecification[]\n productName: string\n productReference: string\n brand: string\n description: string\n}\n\ninterface SkuSpecification {\n field: SkuSpecificationField\n values: SkuSpecificationValues[]\n}\n\ninterface SkuSpecificationField {\n name: string\n originalName: string\n}\n\ninterface SkuSpecificationValues {\n name: string\n originalName: string\n}\n\ndeclare module 'vtex.product-context/ProductDispatchContext' {\n type DispatchFunction = (payload: { type: string; args?: any }) => void\n export const useProductDispatch: () => DispatchFunction\n}\n\ndeclare module 'vtex.product-context' {\n export interface Seller {\n sellerDefault: boolean\n commertialOffer: {\n Price: number\n AvailableQuantity: number\n }\n }\n\n type GroupId = string\n\n interface AssemblyOptionItem {\n id: string\n quantity: number\n seller: string\n initialQuantity: number\n choiceType: string\n name: string\n price: number\n children: Record<string, AssemblyOptionItem[]> | null\n }\n\n type InputValues = Record<string, string>\n\n export interface ProductContext {\n product?: Product\n selectedItem: ProductItem | null\n selectedQuantity: number\n skuSelector: {\n isVisible: boolean\n areAllVariationsSelected: boolean\n selectedImageVariationSKU: string\n }\n buyButton: {\n clicked: boolean\n }\n assemblyOptions: {\n items: Record<GroupId, AssemblyOptionItem[]>\n inputValues: Record<GroupId, InputValues>\n areGroupsValid: Record<GroupId, boolean>\n }\n }\n\n export const useProduct: () => ProductContext\n type DispatchFunction = (payload: { type: string; args?: any }) => void\n export const useProductDispatch: () => DispatchFunction\n export const ProductContext\n}\n\n```"
}
] |
code_store-components_b439628c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/vtex.device-detector.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.device-detector' {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const useDevice: any\n}\n\n```"
}
] |
code_store-components_15c15bb7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/css.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const css: any\n export default css\n}\n\n```"
}
] |
code_store-components_d077e448
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/json.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.json' {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value: any\n export default value\n}\n\n```"
}
] |
code_store-components_1200ed90
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/product.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface Product {\n linkText: string\n productName: string\n brand: string\n categoryId: string\n categoryTree: Category[]\n productId: string\n titleTag: string\n metaTagDescription: string\n items: SKU[]\n skuSpecifications: SkuSpecification[]\n}\n\nexport interface Category {\n id: string\n name: string\n}\n\nexport interface SKU {\n itemId: string\n ean: string\n referenceId: [{ Value: string }]\n sellers: Seller[]\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n}\n\ninterface CommertialOffer {\n ListPrice: number\n Price: number\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n}\n\ninterface CommertialOffer {\n AvailableQuantity: number\n}\n\ninterface SkuSpecification {\n field: SkuSpecificationField\n values: SkuSpecificationValues[]\n}\n\ninterface SkuSpecificationField {\n name: string\n}\n\ninterface SkuSpecificationValues {\n name: string\n}\n\n```"
}
] |
code_store-components_58c613f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/graphql.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const graphql: any\n export default graphql\n}\n\n```"
}
] |
code_store-components_19890f1d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/vtex.store-resources.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-resources/OrderFormContext' {\n export const orderFormConsumer\n}\n\ndeclare module 'vtex.store-resources/QueryAddress'\n\n```"
}
] |
code_store-components_8fe794cd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/typings/vtex.styleguide.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* eslint-disable @typescript-eslint/no-explicit-any */\ndeclare module 'vtex.styleguide' {\n export const Checkbox: any\n export const Radio: any\n export const NumericStepper: any\n export const Button: any\n export const Modal: any\n export const withToast: any\n export const Tooltip: any\n // eslint-disable-next-line @typescript-eslint/naming-convention\n export const EXPERIMENTAL_Select: any\n export const Dropdown: any\n export const Input: any\n export const Spinner: any\n export const InputSearch: any\n}\n\n```"
}
] |
code_store-components_d10b11f4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/utils/sellers.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { Seller } from 'vtex.product-context'\n\nexport function getDefaultSeller(sellers?: Seller[]) {\n if (!sellers || sellers.length === 0) {\n return\n }\n\n const defaultSeller = sellers.find(seller => seller.sellerDefault)\n\n if (defaultSeller) {\n return defaultSeller\n }\n\n return sellers[0]\n}\n\n```"
}
] |
code_store-components_3b883f02
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/utils/imgUrlHelpers.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n\nconst httpRegex = new RegExp(/http:\\/\\//)\n\nexport function toHttps(url: string) {\n return url.replace(httpRegex, 'https://')\n}\n\nexport function cleanImageUrl(imageUrl: string) {\n const result = baseUrlRegex.exec(imageUrl)\n\n if (result && result.length > 0) {\n return result[0]\n }\n\n return 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) {\n return imageUrl\n }\n\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize({\n imageUrl,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT,\n}: {\n imageUrl: string\n width?: string | number\n height?: string | number\n}) {\n let adjustedWidth = width\n let adjustedHeight = height\n\n if (typeof width === 'number') {\n adjustedWidth = Math.min(width, MAX_WIDTH)\n }\n\n if (typeof height === 'number') {\n adjustedHeight = Math.min(height, MAX_HEIGHT)\n }\n\n const normalizedImageUrl = replaceLegacyFileManagerUrl(\n imageUrl,\n adjustedWidth,\n adjustedHeight\n )\n\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${adjustedWidth}&height=${adjustedHeight}&aspect=true`\n}\n\n```"
}
] |
code_store-components_6910bb72
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/utils/useCommercialOffer.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useRuntime } from 'vtex.render-runtime'\nimport { path } from 'ramda'\nimport { ProductContextState } from 'vtex.product-context/react/ProductTypes'\n\nimport { getDefaultSeller } from './sellers'\n\nexport const useCommercialOffer = (\n valuesFromContext: Partial<ProductContextState>\n) => {\n const renderRuntime = useRuntime()\n\n const { selectedItem } = valuesFromContext\n\n const settings = renderRuntime?.getSettings?.('vtex.store')\n\n if (settings?.enableDefaultSeller) {\n return getDefaultSeller(selectedItem?.sellers)?.commertialOffer\n }\n\n console.warn(\n 'In feature releases the enableDefaultSeller setting will be removed, and the commercialOffer will be calculated only by defaultSeller'\n )\n\n return path(['sellers', 0, 'commertialOffer'], selectedItem)\n}\n\n```"
}
] |
code_store-components_07859693
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SanitizedHTML.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, FC } from 'react'\nimport insane from '@vtex/insane'\n\ntype SanitizeOpts = {\n allowedAttributes?: Record<string, string[]>\n allowedClasses?: Record<string, string[]>\n allowedTags?: string[]\n}\n\ntype SanitizedHTMLProps = SanitizeOpts & {\n content: string\n}\n\nexport const DEFAULTS = {\n allowedAttributes: {\n '*': [\n 'id',\n 'title',\n 'accesskey',\n 'class',\n 'style',\n 'aria-label',\n 'width',\n 'height',\n 'hidden',\n ],\n a: ['href', 'name', 'target'],\n iframe: ['allow', 'allowfullscreen', 'frameborder', 'src'],\n img: ['src', 'alt'],\n link: ['rel', 'type', 'href'],\n td: ['colspan', 'rowspan', 'headers'],\n },\n allowedClasses: {},\n allowedSchemes: ['http', 'https', 'mailto', 'tel'],\n allowedTags: [\n 'a',\n 'abbr',\n 'article',\n 'b',\n 'blockquote',\n 'br',\n 'caption',\n 'code',\n 'del',\n 'details',\n 'div',\n 'em',\n 'figure',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'hr',\n 'header',\n 'footer',\n 'i',\n 'img',\n 'ins',\n 'iframe',\n 'kbd',\n 'li',\n 'main',\n 'mark',\n 'ol',\n 'p',\n 'picture',\n 'pre',\n 'section',\n 'source',\n 'span',\n 'strike',\n 'strong',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'th',\n 'thead',\n 'tr',\n 'u',\n 'ul',\n ],\n}\n\nfunction sanitizeHTML(\n html: string,\n { allowedAttributes, allowedClasses, allowedTags }: SanitizeOpts = {}\n) {\n const opts: Record<string, any> = { ...DEFAULTS }\n\n if (allowedTags) opts.allowedTags = allowedTags\n if (allowedClasses) opts.allowedClasses = allowedClasses\n if (allowedAttributes) opts.allowedAttributes = allowedAttributes\n\n return insane(html, opts)\n}\n\nfunction getDangerousSanitizedHTML(html: string, opts: SanitizeOpts = {}) {\n return { __html: sanitizeHTML(html, opts) }\n}\n\nfunction useSanitizedHTML(\n html: string,\n { allowedAttributes, allowedClasses, allowedTags }: SanitizeOpts = {}\n) {\n const sanitizedHTML = useMemo(() => {\n return getDangerousSanitizedHTML(html, {\n allowedAttributes,\n allowedClasses,\n allowedTags,\n })\n }, [allowedAttributes, allowedClasses, allowedTags, html])\n\n return sanitizedHTML\n}\n\nexport const SanitizedHTML: FC<SanitizedHTMLProps> = ({\n content,\n allowedAttributes,\n allowedClasses,\n allowedTags,\n}) => {\n const sanitizedContent = useSanitizedHTML(content, {\n allowedAttributes,\n allowedClasses,\n allowedTags,\n })\n\n if (!content) {\n return null\n }\n\n return (\n <div\n // Display 'contents' is used so this div doesn't affect the layout\n style={{ display: 'contents' }}\n dangerouslySetInnerHTML={sanitizedContent}\n />\n )\n}\n\n```"
}
] |
code_store-components_5e0ed865
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/CollectionBadges.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 CollectionBadges from './CollectionBadges'\n\ndescribe('<CollectionBadges /> component', () => {\n it('should match snapshot without badges', () => {\n const { container } = render(<CollectionBadges>Test</CollectionBadges>)\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n class=\"collectionContainer relative dib w-100\"\n >\n Test\n <div\n class=\"inline-flex justify-end absolute w-100 bottom-0 left-0\"\n />\n </div>\n `)\n })\n\n it('should match snapshot with badges', () => {\n const { container } = render(\n <CollectionBadges collectionBadgesText={['badge1', 'badge2']}>\n Test\n </CollectionBadges>\n )\n\n expect(container.firstChild).toMatchInlineSnapshot(`\n <div\n class=\"collectionContainer relative dib w-100\"\n >\n Test\n <div\n class=\"inline-flex justify-end absolute w-100 bottom-0 left-0\"\n >\n <div\n class=\"item mh1 pa2 bg-blue white tc\"\n >\n badge1\n </div>\n <div\n class=\"item mh1 pa2 bg-blue white tc\"\n >\n badge2\n </div>\n </div>\n </div>\n `)\n })\n})\n\n```"
}
] |
code_store-components_e7a79991
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/CollectionBadges.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { FC } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nexport type Props = {\n collectionBadgesText?: string[]\n}\n\nconst HANDLES = ['collectionContainer', 'item'] as const\n\n/**\n * @deprecated This component is deprecated. Please use [vtex.product-highlights](https://github.com/vtex-apps/product-highlights) instead.\n */\nconst CollectionBadges: FC<Props> = ({\n collectionBadgesText = [],\n children,\n}) => {\n const { handles } = useCssHandles(HANDLES)\n\n return (\n <div className={`${handles.collectionContainer} relative dib w-100`}>\n {children}\n <div className=\"inline-flex justify-end absolute w-100 bottom-0 left-0\">\n {collectionBadgesText.map((collectionBadgeText, index) => (\n <div\n key={`${collectionBadgeText}-${index}`}\n className={`${handles.item} mh1 pa2 bg-blue white tc`}\n >\n {collectionBadgeText}\n </div>\n ))}\n </div>\n </div>\n )\n}\n\nexport default CollectionBadges\n\n```"
}
] |
code_store-components_c21c1f21
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/graphql/addToAvailabilitySubscriberMutation.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation availabilitySubscribe($acronym: String!, $document: DocumentInput) {\n createDocument(acronym: $acronym, document: $document)\n @context(provider: \"vtex.store-graphql\") {\n cacheId\n id\n href\n documentId\n }\n}\n\n```"
}
] |
code_store-components_fd75edb3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/graphql/productBrand.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Brand($id: Int) {\n brand(id: $id) @context(provider: \"vtex.store-graphql\") {\n slug\n imageUrl\n }\n}\n\n```"
}
] |
code_store-components_10c675b7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/graphql/autocomplete.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Autocomplete($maxRows: Int, $inputValue: String) {\n autocomplete(maxRows: $maxRows, searchTerm: $inputValue)\n @context(provider: \"vtex.search-graphql\") {\n itemsReturned {\n thumb\n name\n href\n productId\n criteria\n slug\n }\n }\n}\n\n```"
}
] |
code_store-components_ea55cae8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SearchBar/SearchBar.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.searchBarContainer :global(.vtex-input-prefix__group) {\n height: 38px;\n}\n\n.searchBarContainer input {\n color: #727273;\n border-radius: 1px;\n}\n\n.compactMode input {\n border-top-style: none !important;\n border-left-style: none !important;\n border-right-style: none !important;\n border-bottom: 2px solid !important;\n}\n\n.paddingInput input {\n -webkit-appearance: none;\n padding-left: 40px !important;\n}\n\n.searchMobile .vtex-button {\n padding: 0.9rem;\n font-weight: 400;\n font-size: 0.875rem;\n}\n\n.searchMobile input {\n border: none;\n}\n\n@media only screen and (max-width: 49rem) {\n .searchBarContainer input {\n box-shadow: none;\n }\n}\n\n.visuallyHidden {\n border: 0;\n clip: rect(0 0 0 0);\n clip-path: inset(50%);\n height: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n white-space: nowrap;\n width: 1px;\n}\n\n```"
}
] |
code_store-components_73f99959
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SearchBar/AutocompleteInput.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useRef, useEffect } from 'react'\nimport classNames from 'classnames'\nimport { Input, InputSearch } from 'vtex.styleguide'\nimport { ExtensionPoint, useChildBlock } from 'vtex.render-runtime'\nimport { IconSearch, IconClose } from 'vtex.store-icons'\nimport type { DownshiftProps } from 'downshift'\nimport { useIntl } from 'react-intl'\n\nimport { useSearchBarCssHandles } from './SearchBarCssHandles'\n\nconst DISPLAY_MODES = [\n 'clear-button',\n 'search-and-clear-buttons',\n 'search-button',\n]\n\n/** Midleware component to adapt the styleguide/Input to be used by the Downshift */\nexport const CSS_HANDLES = [\n 'autoCompleteOuterContainer',\n 'compactMode',\n 'externalSearchButtonWrapper',\n 'paddingInput',\n 'searchBarClearIcon',\n 'searchBarIcon',\n 'searchBarSearchIcon',\n 'suffixWrapper',\n] as const\n\nconst CloseIcon = () => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-close' }))\n\n if (hasIconBlock) {\n return <ExtensionPoint id=\"icon-close\" size={16} type=\"line\" />\n }\n\n return <IconClose type=\"line\" size={16} />\n}\n\nconst SearchIcon = () => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-search' }))\n\n if (hasIconBlock) {\n return <ExtensionPoint id=\"icon-search\" />\n }\n\n return <IconSearch />\n}\n\ninterface Props {\n /** Downshift prop to be passed to the input */\n autoComplete?: string\n /** Input ID */\n id?: string\n /** Downshift prop to be passed to the input */\n onBlur?: () => void\n /** Downshift prop to be passed to the input */\n onChange?: DownshiftProps<any>['onChange']\n /** Downshift prop to be passed to the input */\n onKeyDown?: (event: any) => void\n /** Downshift prop to be passed to the input */\n value?: string\n /** Downshift func to open the menu */\n openMenu?: () => void\n /** Placeholder to be used on the input */\n placeholder?: string\n compactMode?: boolean\n /** Clears the input */\n onClearInput: () => void\n /** Identify if the search icon is on left or right position */\n hasIconLeft?: boolean\n /** Custom classes for the search icon */\n iconClasses?: string\n /** Block class for the search icon */\n iconBlockClass?: string\n /** Identify if the search input should autofocus or not */\n autoFocus?: boolean\n /** Function to direct the user to the searchPage */\n onGoToSearchPage: () => void\n /**\n * @deprecated Use `displayMode`\n * Identify if icon should submit on click\n * */\n submitOnIconClick?: boolean\n /* Define the input display mode */\n displayMode?: 'clear-button' | 'search-and-clear-buttons' | 'search-button'\n /** Error message showed in search input */\n inputErrorMessage?: string\n /** The type of the search input */\n inputType?: 'text' | 'search'\n openAutocompleteOnFocus?: boolean\n onInputChange: DownshiftProps<any>['onChange']\n inputValue: string\n}\n\nfunction AutocompleteInput({\n onClearInput,\n compactMode,\n value,\n hasIconLeft,\n iconBlockClass,\n iconClasses,\n autoFocus,\n onGoToSearchPage,\n submitOnIconClick,\n displayMode = 'clear-button',\n openMenu,\n inputErrorMessage,\n inputType = 'text',\n openAutocompleteOnFocus,\n ...restProps\n}: Props) {\n const { handles, withModifiers } = useSearchBarCssHandles()\n const inputRef = useRef<HTMLInputElement>(null)\n\n const intl = useIntl()\n\n let dMode = displayMode\n\n if (DISPLAY_MODES.indexOf(dMode) < 0) {\n console.error(\n `[store-components/search-bar] Invalid displayMode '${displayMode}'. The valid options are: ${DISPLAY_MODES.join(\n ', '\n )}`\n )\n }\n\n // for backward compatibility\n if (submitOnIconClick === true) {\n dMode = 'search-button'\n } else if (submitOnIconClick === false) {\n dMode = 'clear-button'\n }\n\n useEffect(() => {\n const changeClassInput = () => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (compactMode && inputRef.current) {\n inputRef.current.placeholder = ''\n inputRef.current.classList.add(handles.paddingInput)\n }\n }\n\n changeClassInput()\n if (autoFocus) inputRef.current?.focus()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const hasValue = value != null && value.length > 0\n\n const showClearButton =\n (dMode === 'clear-button' && hasValue) ||\n dMode === 'search-and-clear-buttons'\n\n const showInternalSearchButton =\n (dMode === 'clear-button' && !hasValue) || dMode === 'search-button'\n\n const showExternalSearchButton = dMode === 'search-and-clear-buttons'\n\n const clearButton = showClearButton && (\n <button\n className={`${iconClasses ?? ''} ${withModifiers(\n 'searchBarIcon',\n 'clear'\n )} flex items-center pointer bn bg-transparent outline-0 pv0 pl0 pr3`}\n style={{\n visibility: hasValue ? 'visible' : 'hidden',\n }}\n aria-label={intl.formatMessage({\n id: 'store/search.clear-input',\n })}\n onClick={() => onClearInput()}\n >\n <CloseIcon />\n </button>\n )\n\n const internalSearchButton = showInternalSearchButton && (\n <button\n className={`${iconClasses ?? ''} ${withModifiers(\n 'searchBarIcon',\n 'search'\n )} flex items-center pointer bn bg-transparent outline-0 pv0 pl0 pr3`}\n onClick={() => hasValue && onGoToSearchPage()}\n aria-label={intl.formatMessage({\n id: 'store/search.submit-search',\n })}\n >\n <SearchIcon />\n </button>\n )\n\n const externalSearchButton = showExternalSearchButton && (\n <div\n className={`${handles.externalSearchButtonWrapper} bw1 bl b--muted-4 flex items-center `}\n >\n <button\n className={`${iconClasses ?? ''} ${withModifiers(\n 'searchBarIcon',\n 'external-search'\n )} flex items-center h-100 pointer pv0 nr5 ph5 bn c-link`}\n onClick={onGoToSearchPage}\n aria-label={intl.formatMessage({\n id: 'store/search.submit-search',\n })}\n >\n <SearchIcon />\n </button>\n </div>\n )\n\n const suffix = (\n <div className={`${handles.suffixWrapper} flex h-100`}>\n {clearButton}\n {internalSearchButton}\n {externalSearchButton}\n </div>\n )\n\n const prefix = (\n <span\n className={`${iconClasses} ${withModifiers('searchBarIcon', 'prefix')} `}\n >\n <SearchIcon />\n </span>\n )\n\n const classContainer = classNames('w-100 flex', {\n [handles.compactMode]: compactMode,\n })\n\n if (inputType === 'search') {\n // <form> tag is needed for iOS:\n // https://stackoverflow.com/a/26287843\n return (\n <form\n action=\"#\"\n onSubmit={e => {\n e.preventDefault()\n e.stopPropagation()\n e.nativeEvent.stopImmediatePropagation()\n }}\n className={handles.autoCompleteOuterContainer}\n >\n <div className={classContainer}>\n <InputSearch\n ref={inputRef}\n size=\"large\"\n value={value}\n {...restProps}\n error={Boolean(inputErrorMessage)}\n errorMessage={inputErrorMessage}\n onSubmit={onGoToSearchPage}\n aria-label={intl.formatMessage({\n id: 'store/search.autocompleteInput.aria-label',\n })}\n />\n </div>\n </form>\n )\n }\n\n return (\n <div className={handles.autoCompleteOuterContainer}>\n <div className={classContainer}>\n <Input\n ref={inputRef}\n size=\"large\"\n value={value}\n prefix={hasIconLeft && prefix}\n suffix={suffix}\n {...restProps}\n error={Boolean(inputErrorMessage)}\n errorMessage={inputErrorMessage}\n aria-label={intl.formatMessage({\n id: 'store/search.autocompleteInput.aria-label',\n })}\n />\n </div>\n </div>\n )\n}\n\nexport default AutocompleteInput\n\n```"
}
] |
code_store-components_3f95294c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SearchBar/SearchBar.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useRef, useCallback, useState, useEffect, useMemo } from 'react'\nimport classNames from 'classnames'\nimport Downshift, {\n DownshiftProps,\n DownshiftState,\n StateChangeOptions,\n} from 'downshift'\nimport debounce from 'debounce'\nimport {\n NoSSR,\n useRuntime,\n ExtensionPoint,\n useChildBlock,\n} from 'vtex.render-runtime'\nimport { Overlay } from 'vtex.react-portal'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\n\nimport styles from './SearchBar.css'\nimport AutocompleteResults from '../../AutocompleteResults'\nimport type { Props as AutocompleteResultsProps } from '../../AutocompleteResults'\nimport AutocompleteInput from './AutocompleteInput'\nimport { useSearchBarCssHandles } from './SearchBarCssHandles'\n\nexport const CSS_HANDLES = ['searchBarInnerContainer'] as const\n\nconst SEARCH_DELAY_TIME = 1000\nconst AUTOCOMPLETE_EXTENSION_ID = 'autocomplete-result-list'\n\nconst messages = defineMessages({\n searchTermTooShort: {\n id: 'store/search.search-term-too-short',\n defaultMessage: '',\n },\n})\n\ninterface Props {\n /** Placeholder to be used on the input */\n placeholder: string\n /** Current value of the input */\n inputValue: string\n /** Function to handle input changes */\n onInputChange: DownshiftProps<any>['onChange']\n /** Function to direct the user to the searchPage */\n onGoToSearchPage: () => void\n /** Function to clear the input */\n onClearInput: () => void\n /** Indentify when use the compact version of the component */\n compactMode?: boolean\n /** Identify if the search icon is on left or right position */\n hasIconLeft?: boolean\n /** Custom classes for the search icon */\n iconClasses?: string\n /** Block class for the search icon */\n iconBlockClass?: string\n /** Identify if the search input should autofocus or not */\n autoFocus?: boolean\n /** Max width of the search bar */\n maxWidth?: string | number\n /** A template for a custom url. It can have a substring ${term} used as placeholder to interpolate the searched term. (e.g. `/search?query=${term}`) */\n customSearchPageUrl?: string\n /** Uses the term the user has inputed to try to navigate to the proper\n * page type (e.g. a department, a brand, a category)\n */\n attemptPageTypeSearch?: boolean\n /* Autocomplete Horizontal alignment */\n autocompleteAlignment?: 'right' | 'left' | 'center'\n /** Identify if autocomplete should be open on input focus or not */\n openAutocompleteOnFocus?: boolean\n /** Identify if input should blur on submit */\n blurOnSubmit?: boolean\n /** Identify if icon should submit on click */\n submitOnIconClick?: boolean\n /** Minimum search term length allowed */\n minSearchTermLength?: number\n /** If true, the autocomplete will fill the whole window horizontally */\n autocompleteFullWidth?: boolean\n /** The type of the search input */\n inputType?: 'text' | 'search'\n /** Define the component display mode,such as which buttons should be visible */\n displayMode?: 'clear-button' | 'search-and-clear-buttons' | 'search-button'\n /** Define how the autocomplete component should be displayed. Possible values are: `overlay` (suggestions overlapping other components) and `container` (displays the suggestion within a container). */\n containerMode: 'overlay' | 'container'\n /** The autocomplete can have touchable/clickable components. Interacting with those components may trigger blur and touch events that will close the autcomplete. When set to true, this prop will disable those handlers */\n disableBlurAndTouchEndHandler?: boolean\n}\n\nfunction SearchBar({\n placeholder,\n onInputChange,\n onGoToSearchPage,\n onClearInput,\n inputValue,\n compactMode,\n hasIconLeft,\n iconClasses,\n iconBlockClass,\n autoFocus,\n maxWidth,\n attemptPageTypeSearch,\n customSearchPageUrl,\n autocompleteAlignment,\n openAutocompleteOnFocus,\n blurOnSubmit,\n submitOnIconClick,\n displayMode,\n minSearchTermLength,\n autocompleteFullWidth,\n inputType,\n containerMode = 'overlay',\n disableBlurAndTouchEndHandler,\n}: Props) {\n const { withModifiers } = useSearchBarCssHandles()\n const intl = useIntl()\n const container = useRef<HTMLDivElement>(null)\n const { navigate } = useRuntime()\n const [searchTerm, setSearchTerm] = useState(inputValue)\n const [inputErrorMessage, setInputErrorMessage] = useState<\n string | undefined\n >()\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const debouncedSetSearchTerm = useCallback(\n debounce((newValue: string) => {\n setSearchTerm(newValue)\n }, SEARCH_DELAY_TIME),\n []\n )\n\n useEffect(() => {\n debouncedSetSearchTerm(inputValue)\n }, [debouncedSetSearchTerm, inputValue])\n\n const onSelect = useCallback(\n element => {\n if (!element) {\n return\n }\n\n if (element.term) {\n if (attemptPageTypeSearch) {\n window.location.href = `/${element.term}`\n\n return\n }\n\n if (customSearchPageUrl) {\n navigate({\n to: customSearchPageUrl.replace(/\\$\\{term\\}/g, element.term),\n })\n\n return\n }\n\n navigate({\n page: 'store.search',\n params: { term: element.term },\n query: 'map=ft',\n })\n\n return\n }\n\n let page = 'store.product'\n let params: Record<string, string> = {\n slug: element.slug,\n id: element.productId,\n }\n\n let query = ''\n const terms = element.slug.split('/')\n\n if (element.criteria) {\n // This param is only useful to track terms searched\n // See: https://support.google.com/analytics/answer/1012264\n const paramForSearchTracking = `&_c=${terms[0]}`\n\n page = 'store.search'\n params = { term: terms.join('/') }\n query = `map=c,ft${paramForSearchTracking}`\n }\n\n navigate({ page, params, query })\n },\n [navigate, attemptPageTypeSearch, customSearchPageUrl]\n )\n\n const validateInput = () => {\n if (minSearchTermLength && inputValue.length < minSearchTermLength) {\n return intl.formatMessage(messages.searchTermTooShort)\n }\n\n return null\n }\n\n const showInputErrorMessage = (newInputErrorMessage: string) => {\n setInputErrorMessage(newInputErrorMessage)\n }\n\n const hideInputErrorMessage = () => {\n setInputErrorMessage(undefined)\n }\n\n const fallback = (\n <AutocompleteInput\n placeholder={formatIOMessage({ id: placeholder, intl }) as string}\n onInputChange={onInputChange}\n inputValue={inputValue}\n hasIconLeft={hasIconLeft}\n iconClasses={iconClasses}\n iconBlockClass={iconBlockClass}\n inputErrorMessage={inputErrorMessage}\n onGoToSearchPage={onGoToSearchPage}\n onClearInput={onClearInput}\n />\n )\n\n const isAutocompleteDeclared = Boolean(\n useChildBlock({ id: AUTOCOMPLETE_EXTENSION_ID })\n )\n\n const SelectedAutocompleteResults = useMemo(() => {\n if (isAutocompleteDeclared) {\n const AutoCompleteResultsWrapper = (props: AutocompleteResultsProps) => (\n <ExtensionPoint id={AUTOCOMPLETE_EXTENSION_ID} {...props} />\n )\n\n return AutoCompleteResultsWrapper\n }\n\n const AutoCompleteResultsWrapper = (props: AutocompleteResultsProps) => (\n <AutocompleteResults {...props} />\n )\n\n return AutoCompleteResultsWrapper\n }, [isAutocompleteDeclared])\n\n const autocompleteContainerRef = useRef<HTMLDivElement>(null)\n\n const stateReducer = (\n state: DownshiftState<unknown>,\n changes: StateChangeOptions<unknown>\n ): StateChangeOptions<unknown> => {\n const { type } = changes\n\n if (\n (type === Downshift.stateChangeTypes.blurInput ||\n type === Downshift.stateChangeTypes.touchEnd) &&\n disableBlurAndTouchEndHandler\n ) {\n return {\n ...changes,\n isOpen: state.isOpen,\n }\n }\n\n return changes\n }\n\n return (\n <div\n ref={container}\n className={classNames('w-100 mw7 pv4', styles.searchBarContainer)}\n style={{\n ...(maxWidth && {\n maxWidth: typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth,\n }),\n }}\n >\n <NoSSR onSSR={fallback}>\n <Downshift onSelect={onSelect} stateReducer={stateReducer}>\n {({\n getInputProps,\n getItemProps,\n getMenuProps,\n getLabelProps,\n selectedItem,\n highlightedIndex,\n isOpen,\n closeMenu,\n openMenu,\n }) => (\n <div\n className={`relative-m w-100 ${withModifiers(\n 'searchBarInnerContainer',\n [isOpen ? 'opened' : '', inputValue ? 'filled' : '']\n )}`}\n >\n <label {...getLabelProps()} className={styles.visuallyHidden}>\n {formatIOMessage({ id: placeholder, intl }) as string}\n </label>\n <AutocompleteInput\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={autoFocus}\n compactMode={compactMode}\n hasIconLeft={hasIconLeft}\n iconClasses={iconClasses}\n openAutocompleteOnFocus={openAutocompleteOnFocus}\n submitOnIconClick={submitOnIconClick}\n displayMode={displayMode}\n inputType={inputType}\n openMenu={openMenu}\n inputErrorMessage={inputErrorMessage}\n {...getInputProps({\n onKeyDown: event => {\n // Only call default search function if user doesn't\n // have any item highlighted in the menu options\n if (event.key === 'Enter' && highlightedIndex === null) {\n const errorMessage = validateInput()\n\n if (errorMessage) {\n showInputErrorMessage(errorMessage)\n\n return\n }\n\n if (blurOnSubmit) {\n event.currentTarget.blur()\n }\n\n onGoToSearchPage()\n closeMenu()\n } else {\n hideInputErrorMessage()\n }\n },\n placeholder: formatIOMessage({\n id: placeholder,\n intl,\n }) as string,\n value: inputValue,\n onChange: onInputChange,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error this exists\n onFocus: openAutocompleteOnFocus ? openMenu : undefined,\n })}\n onClearInput={onClearInput}\n onGoToSearchPage={onGoToSearchPage}\n />\n <div ref={autocompleteContainerRef} />\n\n {containerMode === 'container' ? (\n <SelectedAutocompleteResults\n parentContainer={container ?? undefined}\n {...{\n attemptPageTypeSearch,\n isOpen,\n getMenuProps,\n inputValue: searchTerm,\n getItemProps,\n selectedItem,\n highlightedIndex,\n closeMenu,\n onClearInput,\n customSearchPageUrl,\n }}\n />\n ) : (\n <Overlay\n fullWindow={autocompleteFullWidth}\n alignment={autocompleteAlignment}\n target={autocompleteContainerRef.current ?? undefined}\n >\n <SelectedAutocompleteResults\n parentContainer={container}\n {...{\n attemptPageTypeSearch,\n isOpen,\n getMenuProps,\n inputValue: searchTerm,\n getItemProps,\n selectedItem,\n highlightedIndex,\n closeMenu,\n onClearInput,\n customSearchPageUrl,\n }}\n />\n </Overlay>\n )}\n </div>\n )}\n </Downshift>\n </NoSSR>\n </div>\n )\n}\n\nexport default SearchBar\n\n```"
}
] |
code_store-components_4cd9c006
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SearchBar/SearchBarCssHandles.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { SEARCH_BAR_CSS_HANDLES } from '../../SearchBar'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n SEARCH_BAR_CSS_HANDLES\n)\n\nexport {\n CssHandlesProvider as SearchBarCssHandlesProvider,\n useContextCssHandles as useSearchBarCssHandles,\n}\n\n```"
}
] |
code_store-components_33511dd6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, {\n useContext,\n useState,\n useEffect,\n useCallback,\n useRef,\n} from 'react'\nimport { ProductContext } from 'vtex.product-context'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useApolloClient } from 'react-apollo'\nimport { addValidation, removeValidation } from 'vtex.address-form/helpers'\nimport {\n useOrderShipping,\n OrderShippingProvider,\n} from 'vtex.order-shipping/OrderShipping'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\n\nimport { getNewAddress } from './utils'\nimport ShippingSimulator from './index'\nimport getShippingEstimates from './queries/getShippingEstimates.gql'\nimport ShippingSimulatorLoader from './Loader'\nimport { getDefaultSeller } from '../../utils/sellers'\n\nconst useAddressState = (country, postalCode) => {\n const [address, setAddress] = useState(() =>\n addValidation(getNewAddress(country, postalCode))\n )\n\n const [isValid, setIsValid] = useState(!!postalCode)\n\n const updateAddress = newAddress => {\n const updatedAddress = {\n ...address,\n ...newAddress,\n }\n\n setAddress(updatedAddress)\n setIsValid(updatedAddress.postalCode.valid)\n }\n\n return { address, updateAddress, isValid }\n}\n\nconst BaseShippingSimulatorWrapper = ({\n country,\n seller,\n skuId,\n loaderStyles,\n onShippingAddressUpdate = _ => {},\n initialPostalCode = undefined,\n shouldUpdateOrderForm,\n pricingMode,\n selectedQuantity,\n}) => {\n const [shipping, setShipping] = useState(null)\n const [loading, setLoading] = useState(false)\n\n const { address, updateAddress, isValid } = useAddressState(\n country,\n initialPostalCode\n )\n\n const client = useApolloClient()\n\n const handleCalculateShipping = useCallback(\n e => {\n e && e.preventDefault()\n setLoading(true)\n const rawAddress = removeValidation(address)\n\n client\n .query({\n query: getShippingEstimates,\n variables: {\n country,\n postalCode: rawAddress.postalCode,\n items: [\n {\n quantity: selectedQuantity,\n id: skuId,\n seller,\n },\n ],\n },\n })\n .then(result => {\n setShipping(result.data.shipping)\n })\n .then(() => {\n if (!shouldUpdateOrderForm) return\n\n return onShippingAddressUpdate?.(rawAddress)\n })\n .catch(error => {\n console.error(error)\n })\n .finally(() => {\n setLoading(false)\n })\n },\n [\n address,\n client,\n country,\n seller,\n skuId,\n selectedQuantity,\n onShippingAddressUpdate,\n shouldUpdateOrderForm,\n ]\n )\n\n const isMountedRef = useRef(false)\n\n useEffect(() => {\n if (isMountedRef.current) {\n isMountedRef.current = false\n }\n }, [seller])\n\n useEffect(() => {\n if (isMountedRef.current) {\n return\n }\n\n isMountedRef.current = true\n\n if (!address || !isValid) {\n return\n }\n\n handleCalculateShipping()\n }, [handleCalculateShipping, address, isValid])\n\n return (\n <ShippingSimulator\n skuId={skuId}\n seller={seller}\n country={country}\n loaderStyles={loaderStyles}\n loading={loading}\n address={address}\n isValid={isValid}\n shipping={shipping}\n pricingMode={pricingMode}\n selectedQuantity={selectedQuantity}\n onAddressChange={updateAddress}\n onCalculateShipping={handleCalculateShipping}\n />\n )\n}\n\nconst ShippingSimulatorWithOrderForm = ({\n country,\n skuId,\n seller,\n loaderStyles,\n shouldUpdateOrderForm,\n pricingMode,\n selectedQuantity,\n}) => {\n const { updateSelectedAddress } = useOrderShipping()\n const { orderForm } = useOrderForm()\n\n const selectedAddress = orderForm?.shipping?.selectedAddress\n\n return (\n <BaseShippingSimulatorWrapper\n skuId={skuId}\n seller={seller}\n country={country}\n loaderStyles={loaderStyles}\n initialPostalCode={\n orderForm?.canEditData || selectedAddress?.isDisposable\n ? selectedAddress?.postalCode\n : undefined\n }\n onShippingAddressUpdate={updateSelectedAddress}\n shouldUpdateOrderForm={shouldUpdateOrderForm}\n pricingMode={pricingMode}\n selectedQuantity={selectedQuantity}\n />\n )\n}\n\nconst OrderFormLoader = props => {\n const { loading } = useOrderForm()\n\n if (loading) {\n return <ShippingSimulatorLoader {...props.loaderStyles} />\n }\n\n return props.children\n}\n\nconst ShippingSimulatorWrapper = props => {\n const { culture } = useRuntime()\n const productContext = useContext(ProductContext)\n\n const country = props.country || culture.country\n const skuId = props.skuId || productContext?.selectedItem?.itemId\n const selectedQuantity = productContext?.selectedQuantity?.toString()\n\n const { pricingMode } = props\n\n let sellerId = props.seller\n\n if (!sellerId) {\n const defaultSeller = getDefaultSeller(\n productContext?.selectedItem?.sellers\n )\n\n if (defaultSeller) {\n sellerId = defaultSeller.sellerId\n }\n }\n\n const { shouldUpdateOrderForm = true } = props\n\n if (\n window.__RUNTIME__?.settings?.['vtex.store']\n ?.enableOrderFormOptimization !== true\n ) {\n return (\n <BaseShippingSimulatorWrapper\n country={country}\n skuId={skuId}\n seller={sellerId}\n pricingMode={pricingMode}\n selectedQuantity={selectedQuantity}\n loaderStyles={props.loaderStyles}\n />\n )\n }\n\n return (\n <OrderShippingProvider>\n <OrderFormLoader>\n <ShippingSimulatorWithOrderForm\n country={country}\n seller={sellerId}\n skuId={skuId}\n loaderStyles={props.loaderStyles}\n pricingMode={pricingMode}\n selectedQuantity={selectedQuantity}\n shouldUpdateOrderForm={shouldUpdateOrderForm}\n />\n </OrderFormLoader>\n </OrderShippingProvider>\n )\n}\n\nexport default ShippingSimulatorWrapper\n\n```"
}
] |
code_store-components_269b7810
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/global.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.vtex-store-components-3-x-shippingContainer .vtex-input {\n height: 100%;\n}\n\n.vtex-store-components-3-x-shippingContainer .vtex-input input {\n padding: 10px 5px;\n color: #4f4f4f;\n border: 1px solid #e3e4e6;\n border-radius: 2px;\n height: 100%;\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n\n.vtex-store-components-3-x-shippingContainer .vtex-button {\n border-radius: 2px;\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n\n```"
}
] |
code_store-components_072a087d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { useIntl } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport { Button } from 'vtex.styleguide'\nimport {\n AddressRules,\n AddressContainer,\n PostalCodeGetter,\n} from 'vtex.address-form'\nimport { StyleguideInput } from 'vtex.address-form/inputs'\n\nimport ShippingTable from './components/ShippingTable'\nimport ShippingSimulatorLoader from './Loader'\nimport styles from './shippingSimulator.css'\n\nconst ShippingSimulator = ({\n /* eslint-disable react/prop-types */\n skuId,\n seller,\n country,\n loading,\n loaderStyles,\n onAddressChange,\n address,\n isValid,\n onCalculateShipping,\n shipping,\n pricingMode,\n /* eslint-enable react/prop-types */\n}) => {\n const intl = useIntl()\n\n if (!seller || !skuId) {\n return <ShippingSimulatorLoader {...loaderStyles} />\n }\n\n return (\n <Fragment>\n <div className={`${styles.shippingContainer} t-small c-on-base`}>\n <AddressRules country={country} shouldUseIOFetching>\n <AddressContainer\n Input={StyleguideInput}\n address={address}\n onChangeAddress={onAddressChange}\n autoCompletePostalCode\n disabled={loading}\n >\n <PostalCodeGetter onSubmit={onCalculateShipping} />\n </AddressContainer>\n </AddressRules>\n <Button\n onClick={onCalculateShipping}\n className={styles.shippingCTA}\n disabled={!isValid}\n size=\"small\"\n type=\"submit\"\n block\n isLoading={loading}\n >\n {intl.formatMessage({ id: 'store/shipping.label' })}\n </Button>\n </div>\n <ShippingTable shipping={shipping} pricingMode={pricingMode} />\n </Fragment>\n )\n}\n\nShippingSimulator.propTypes = {\n skuId: PropTypes.string,\n seller: PropTypes.string,\n pricingMode: PropTypes.enum,\n country: PropTypes.string.isRequired,\n /** Component and content loader styles */\n styles: PropTypes.object,\n}\n\nShippingSimulator.defaultProps = {\n pricingMode: 'individualItems',\n}\n\nexport default ShippingSimulator\n\n```"
}
] |
code_store-components_945b9233
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/shippingSimulator.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.shippingContainer {}\n.shippingContainerLoader {}\n.shippingCTA {}\n.shippingInputLoader {}\n.shippingNoMessage {}\n.shippingTable {}\n.shippingTableBody {}\n.shippingTableCell {}\n.shippingTableCellDeliveryEstimate {}\n.shippingTableCellDeliveryName {}\n.shippingTableCellDeliveryPrice {}\n.shippingTableHead\n.shippingTableHead {\n /* Use the following CSS rule to display correctly */\n /* display: table-header-group */\n}\n.shippingTableHeadDeliveryEstimate {}\n.shippingTableHeadDeliveryName {}\n.shippingTableHeadDeliveryPrice {}\n.shippingTableLabel {}\n.shippingTableRadioBtn {}\n.shippingTableRow {}\n.shippingZipcodeLabel {}\n.shippingZipcodeLabelLoader {}\n```"
}
] |
code_store-components_14e1857c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/Loader.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport ContentLoader from 'react-content-loader'\n\nimport styles from './shippingSimulator.css'\n\nconst ShippingSimulatorLoader = (loaderProps = {}) => (\n <div className={styles.shippingContainer}>\n <ContentLoader\n className={styles.shippingContainerLoader}\n style={{\n width: '100%',\n height: '100%',\n }}\n width={500}\n height={40}\n preserveAspectRatio=\"xMinYMin meet\"\n {...loaderProps}\n >\n <rect\n height=\"100%\"\n width=\"7em\"\n {...loaderProps[styles.shippingZipcodeLabelLoader]}\n />\n <rect\n height=\"100%\"\n width=\"15em\"\n x=\"8em\"\n {...loaderProps[styles.shippingInputLoader]}\n />\n </ContentLoader>\n </div>\n)\n\nexport default ShippingSimulatorLoader\n\n```"
}
] |
code_store-components_b35e9e60
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/assemblyUtils.test.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n transformAssemblyOptions,\n ItemOption,\n InputValuesOption,\n} from './assemblyUtils'\n// eslint-disable-next-line jest/no-mocks-import\nimport { customBell, comboPizza, starColor } from './__mocks__/assemblyOptions'\n\ntest('should transform assemblyOptions', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultBell = transformAssemblyOptions(\n customBell.items,\n {},\n parentPrice,\n parentQuantity\n )\n\n expect(resultBell.options).toHaveLength(5)\n const addonOption = resultBell.options[0] as ItemOption\n\n expect(addonOption.assemblyId).toBe('add-on_Add-on')\n expect(addonOption.id).toBe('2000588')\n expect(addonOption.quantity).toBe(1)\n expect(addonOption.seller).toBe('1')\n\n const resultPizza = transformAssemblyOptions(\n comboPizza.items,\n {},\n parentPrice,\n parentQuantity\n )\n\n expect(resultPizza.options).toHaveLength(2)\n const pizzaOption = resultPizza.options[0] as ItemOption\n\n expect(pizzaOption.assemblyId).toBe('pizza_composition_Pizza flavor')\n expect(pizzaOption.id).toBe('5101')\n expect(pizzaOption.quantity).toBe(1)\n expect(pizzaOption.seller).toBe('1')\n expect(pizzaOption.options).toHaveLength(3)\n\n const drinksOptions = resultPizza.options[1] as ItemOption\n\n expect(drinksOptions.options).toBeUndefined()\n})\n\ntest('input values', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultStar = transformAssemblyOptions(\n starColor.items,\n starColor.inputValues,\n parentPrice,\n parentQuantity\n )\n\n expect(resultStar.options).toHaveLength(1)\n const customization = resultStar.options[0] as InputValuesOption\n\n expect(customization.assemblyId).toBe('Customization')\n expect(customization.inputValues).toMatchObject({\n Font: 'Sans serif',\n 'Front text': 'Frente',\n 'Back text': 'Verso',\n 'Glossy print': true,\n })\n expect(resultStar).toMatchInlineSnapshot(`\n Object {\n \"assemblyOptions\": Object {\n \"added\": Array [],\n \"parentPrice\": 450,\n \"removed\": Array [],\n },\n \"options\": Array [\n Object {\n \"assemblyId\": \"Customization\",\n \"inputValues\": Object {\n \"Back text\": \"Verso\",\n \"Font\": \"Sans serif\",\n \"Front text\": \"Frente\",\n \"Glossy print\": true,\n },\n },\n ],\n }\n `)\n})\n\ntest('recursive input values', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultBell = transformAssemblyOptions(\n customBell.items,\n customBell.inputValues,\n parentPrice,\n parentQuantity\n )\n\n expect(resultBell.options).toHaveLength(5)\n\n const engraving = resultBell.options[4] as ItemOption\n\n expect(engraving.options).toHaveLength(1)\n\n const recursiveInputValue = engraving.options![0] as InputValuesOption\n\n expect(recursiveInputValue.assemblyId).toBe('1-3-lines')\n expect(recursiveInputValue.inputValues).toBe(\n customBell.inputValues['1-3-lines']\n )\n expect(resultBell).toMatchInlineSnapshot(`\n Object {\n \"assemblyOptions\": Object {\n \"added\": Array [\n Object {\n \"choiceType\": \"TOGGLE\",\n \"extraQuantity\": 1,\n \"item\": Object {\n \"id\": \"2000588\",\n \"name\": \"Bells add-ons Logo small\",\n \"quantity\": 1,\n \"sellingPrice\": 75,\n \"sellingPriceWithAssemblies\": 75,\n },\n \"normalizedQuantity\": 1,\n },\n Object {\n \"choiceType\": \"TOGGLE\",\n \"extraQuantity\": 1,\n \"item\": Object {\n \"id\": \"2000589\",\n \"name\": \"Bells add-ons Logo big\",\n \"quantity\": 1,\n \"sellingPrice\": 90,\n \"sellingPriceWithAssemblies\": 90,\n },\n \"normalizedQuantity\": 1,\n },\n Object {\n \"choiceType\": \"SINGLE\",\n \"extraQuantity\": 1,\n \"item\": Object {\n \"id\": \"2000592\",\n \"name\": \"Bells add-ons Script\",\n \"quantity\": 1,\n \"sellingPrice\": 15,\n \"sellingPriceWithAssemblies\": 15,\n },\n \"normalizedQuantity\": 1,\n },\n Object {\n \"choiceType\": \"SINGLE\",\n \"extraQuantity\": 1,\n \"item\": Object {\n \"assemblyOptions\": Object {\n \"added\": Array [],\n \"parentPrice\": 26,\n \"removed\": Array [],\n },\n \"id\": \"2000586\",\n \"name\": \"Bells add-ons 1-3 lines\",\n \"quantity\": 1,\n \"sellingPrice\": 26,\n \"sellingPriceWithAssemblies\": 26,\n },\n \"normalizedQuantity\": 1,\n },\n ],\n \"parentPrice\": 450,\n \"removed\": Array [],\n },\n \"options\": Array [\n Object {\n \"assemblyId\": \"add-on_Add-on\",\n \"id\": \"2000588\",\n \"quantity\": 1,\n \"seller\": \"1\",\n },\n Object {\n \"assemblyId\": \"add-on_Add-on\",\n \"id\": \"2000589\",\n \"quantity\": 1,\n \"seller\": \"1\",\n },\n Object {\n \"assemblyId\": \"text_style_Text Style\",\n \"id\": \"2000591\",\n \"quantity\": 0,\n \"seller\": \"1\",\n },\n Object {\n \"assemblyId\": \"text_style_Text Style\",\n \"id\": \"2000592\",\n \"quantity\": 1,\n \"seller\": \"1\",\n },\n Object {\n \"assemblyId\": \"engraving_Engraving\",\n \"id\": \"2000586\",\n \"options\": Array [\n Object {\n \"assemblyId\": \"1-3-lines\",\n \"inputValues\": Object {\n \"Line 1\": \"First line\",\n \"Line 2\": \"Second line\",\n \"Line 3\": \"Third line\",\n },\n },\n ],\n \"quantity\": 1,\n \"seller\": \"1\",\n },\n ],\n }\n `)\n})\n\ntest('empty input values should result in empty options', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultStar = transformAssemblyOptions(\n starColor.items,\n {\n Customization: {},\n },\n parentPrice,\n parentQuantity\n )\n\n expect(resultStar.options).toHaveLength(0)\n})\n\n```"
}
] |
code_store-components_58a5a94e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/assemblyUtils.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype GroupId = string\ntype GroupTypes = 'SINGLE' | 'TOGGLE' | 'MULTIPLE'\n\nexport const sumAssembliesPrice = (\n assemblyOptions: Record<GroupId, AssemblyOptionItem[]>\n) => {\n const cleanAssemblies = assemblyOptions || {}\n const assembliesGroupItems = Object.values(cleanAssemblies)\n\n return assembliesGroupItems.reduce<number>(\n (sum: number, groupItems: AssemblyOptionItem[]) => {\n const groupPrice = groupItems.reduce<number>((groupSum, item) => {\n const childrenPrice: number = item.children\n ? sumAssembliesPrice(item.children)\n : 0\n\n const itemCost = item.price * item.quantity\n\n return groupSum + itemCost + childrenPrice * item.quantity\n }, 0)\n\n return groupPrice + sum\n },\n 0\n )\n}\n\ninterface AssemblyOptionItem {\n price: number\n choiceType: GroupTypes\n children: Record<GroupId, AssemblyOptionItem[]> | null\n name: string\n id: string\n initialQuantity: number\n quantity: number\n seller: string\n}\n\ntype InputValue = Record<string, string | boolean>\n\nexport interface AssemblyOptions {\n items: Record<GroupId, AssemblyOptionItem[]>\n inputValues: Record<GroupId, InputValue>\n areGroupsValid: Record<string, boolean>\n}\n\ntype Option = ItemOption | InputValuesOption\n\nexport interface ItemOption {\n assemblyId: string\n id: string\n quantity: number\n seller: string\n options?: Option[]\n}\n\nexport interface InputValuesOption {\n assemblyId: string\n inputValues: InputValue\n}\n\ninterface AddedItem {\n id: string\n name: string\n quantity: number\n sellingPrice: number\n sellingPriceWithAssemblies: number\n assemblyOptions?: ParsedAssemblyOptionsMeta\n}\n\ninterface CartAddedOption {\n normalizedQuantity: number\n extraQuantity: number\n choiceType: GroupTypes\n item: AddedItem\n}\n\ninterface CartRemovedOption {\n name: string\n initialQuantity: number\n removedQuantity: number\n}\n\ninterface ParsedAssemblyOptionsMeta {\n added: CartAddedOption[]\n removed: CartRemovedOption[]\n parentPrice: number\n}\n\ninterface ParsedAssemblyOptions {\n options: Option[]\n assemblyOptions: ParsedAssemblyOptionsMeta\n}\n\nexport const transformAssemblyOptions = (\n // eslint-disable-next-line @typescript-eslint/default-param-last\n assemblyOptionsItems: Record<GroupId, AssemblyOptionItem[]> = {},\n // eslint-disable-next-line @typescript-eslint/default-param-last\n inputValues: Record<GroupId, InputValue> = {},\n parentPrice: number,\n parentQuantity: number\n // eslint-disable-next-line max-params\n): ParsedAssemblyOptions => {\n // contains options sent as arguments to graphql mutation\n const options: Option[] = []\n\n // array with added assemblies data to show in minicart optimistic preview\n const added: CartAddedOption[] = []\n\n // array with removed assemblies data to show in minicart optimistic preview\n const removed: CartRemovedOption[] = []\n\n // Start the list of all the input values that we should handle\n let assemblyInputValuesKeys: GroupId[] = Object.keys(inputValues)\n\n const assemblyItemsKeys: GroupId[] = Object.keys(assemblyOptionsItems)\n\n for (const groupId of assemblyItemsKeys) {\n const items = assemblyOptionsItems[groupId]\n\n for (const item of items) {\n let childrenAddedData = null\n\n if (item.children) {\n const childInputValues: Record<GroupId, InputValue> = {}\n\n // Get every input value of the item and add it as a child\n for (const key in item.children) {\n childInputValues[key] = inputValues[key]\n }\n\n // Get all the input values this item is handling\n const handledInputValues = Object.keys(childInputValues)\n\n // and remove the handled input values from the list\n assemblyInputValuesKeys = assemblyInputValuesKeys.filter(\n inputValueKey => {\n return handledInputValues.includes(inputValueKey)\n }\n )\n\n childrenAddedData = transformAssemblyOptions(\n item.children,\n childInputValues,\n item.price,\n item.quantity * parentQuantity\n )\n }\n\n const {\n options: childrenOptions,\n assemblyOptions: childrenAssemblyOptions,\n } = childrenAddedData ?? {\n options: undefined,\n assemblyOptions: undefined,\n }\n\n const { quantity, initialQuantity } = item\n\n if (quantity >= initialQuantity && quantity > 0) {\n added.push({\n normalizedQuantity: quantity,\n extraQuantity: quantity - initialQuantity,\n choiceType: item.choiceType,\n item: {\n name: item.name,\n sellingPrice: item.price,\n quantity,\n sellingPriceWithAssemblies:\n item.price + sumAssembliesPrice(item.children ?? {}),\n id: item.id,\n ...(childrenAssemblyOptions\n ? { assemblyOptions: childrenAssemblyOptions }\n : {}),\n },\n })\n }\n\n if (quantity < initialQuantity && item.choiceType === 'TOGGLE') {\n removed.push({\n name: item.name,\n initialQuantity,\n removedQuantity: initialQuantity - quantity,\n })\n }\n\n const addedChildrenCount = childrenAddedData\n ? childrenAddedData.options.length\n : 0\n\n if (quantity !== initialQuantity || addedChildrenCount > 0) {\n options.push({\n assemblyId: groupId,\n id: item.id,\n quantity: quantity * parentQuantity,\n seller: item.seller,\n ...(childrenOptions && childrenOptions.length > 0\n ? { options: childrenOptions }\n : {}),\n })\n }\n }\n }\n\n for (const groupId of assemblyInputValuesKeys) {\n const inputValuesObject = inputValues[groupId] || {}\n\n if (Object.keys(inputValuesObject).length > 0) {\n options.push({\n assemblyId: groupId,\n inputValues: inputValues[groupId],\n })\n }\n }\n\n return {\n options,\n assemblyOptions: {\n added,\n removed,\n parentPrice,\n },\n }\n}\n\n```"
}
] |
code_store-components_a3b4c006
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { path, isEmpty, compose } from 'ramda'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport { withToast } from 'vtex.styleguide'\nimport { useOrderForm } from 'vtex.store-resources/OrderFormContext'\nimport { graphql } from 'react-apollo'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport ProductPrice from '../ProductPrice'\nimport { BuyButton } from './index'\nimport { transformAssemblyOptions, sumAssembliesPrice } from './assemblyUtils'\nimport addToCartMutation from './mutations/addToCart.gql'\nimport setOpenMinicartMutation from './mutations/setOpenMinicart.gql'\nimport installedApp from './queries/installedApp.gql'\n\nconst MESSAGE_CSS_HANDLES = [\n 'buyButtonText',\n 'buttonDataContainer',\n 'buttonItemsPrice',\n]\n\nconst CHECKOUT_URL = {\n V0: '/checkout/#/cart',\n V1: '/cart',\n}\n\nconst BuyButtonMessage = ({ showItemsPrice, skuItems }) => {\n const { handles } = useCssHandles(MESSAGE_CSS_HANDLES)\n\n if (!showItemsPrice) {\n return (\n <FormattedMessage id=\"store/buy-button.add-to-cart\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n )\n }\n\n const totalPrice = skuItems.reduce((acc, item) => {\n const itemPrice =\n item.sellingPriceWithAssemblies != null\n ? item.sellingPriceWithAssemblies\n : item.price\n\n const itemCost = itemPrice * item.quantity\n\n return acc + itemCost\n }, 0)\n\n return (\n <div\n className={`${handles.buttonDataContainer} flex w-100 justify-between items-center`}\n >\n <FormattedMessage id=\"store/buy-button.add-to-cart\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n <ProductPrice\n showLabels={false}\n showListPrice={false}\n sellingPrice={totalPrice}\n className={handles.buttonItemsPrice}\n />\n </div>\n )\n}\n\nconst BuyButtonWrapper = ({\n intl,\n addToCart,\n showToast,\n onAddStart,\n onAddFinish,\n children,\n isOneClickBuy,\n shouldOpenMinicart,\n setMinicartOpen,\n showItemsPrice,\n available: propAvailable,\n skuItems: propSkuItems,\n large: propLarge,\n disabled: propDisabled,\n shouldAddToCart,\n customToastURL,\n showTooltipOnSkuNotSelected,\n checkoutVersion,\n selectedSeller,\n}) => {\n const orderFormContext = useOrderForm()\n const valuesFromContext = useProduct()\n\n const isEmptyContext = !valuesFromContext || isEmpty(valuesFromContext)\n\n const product = valuesFromContext && valuesFromContext.product\n const selectedItem = valuesFromContext && valuesFromContext.selectedItem\n const assemblyOptions = valuesFromContext && valuesFromContext.assemblyOptions\n\n selectedSeller =\n selectedSeller || path(['selectedItem', 'sellers', 0], valuesFromContext)\n const selectedQuantity =\n valuesFromContext && valuesFromContext.selectedQuantity != null\n ? valuesFromContext.selectedQuantity\n : 1\n\n const skuItems =\n isEmptyContext || propSkuItems != null\n ? propSkuItems\n : // eslint-disable-next-line @typescript-eslint/no-use-before-define\n EnhancedBuyButton.mapCatalogItemToCart({\n product,\n selectedItem,\n selectedQuantity,\n selectedSeller,\n assemblyOptions,\n })\n\n const large = isEmptyContext || propLarge != null ? propLarge : true\n\n const available =\n isEmptyContext || propAvailable != null\n ? propAvailable\n : selectedSeller &&\n selectedSeller.commertialOffer &&\n selectedSeller.commertialOffer.AvailableQuantity > 0\n\n const groupsValidArray =\n (assemblyOptions &&\n assemblyOptions.areGroupsValid &&\n Object.values(assemblyOptions.areGroupsValid)) ||\n []\n\n const areAssemblyGroupsValid = groupsValidArray.every(Boolean)\n const disabled =\n isEmptyContext || propDisabled != null\n ? propDisabled\n : !areAssemblyGroupsValid\n\n const version =\n checkoutVersion &&\n checkoutVersion.installedAppPublic &&\n checkoutVersion.installedAppPublic.version\n\n const checkoutUrl =\n // eslint-disable-next-line radix\n version && parseInt(version.split('.')[0]) > 0\n ? CHECKOUT_URL.V1\n : CHECKOUT_URL.V0\n\n return (\n <BuyButton\n intl={intl}\n addToCart={addToCart}\n onAddStart={onAddStart}\n onAddFinish={onAddFinish}\n showToast={showToast}\n orderFormContext={orderFormContext}\n skuItems={skuItems}\n large={large}\n available={available}\n isOneClickBuy={isOneClickBuy}\n shouldOpenMinicart={shouldOpenMinicart}\n setMinicartOpen={setMinicartOpen}\n disabled={disabled}\n customToastURL={customToastURL}\n shouldAddToCart={shouldAddToCart}\n showTooltipOnSkuNotSelected={showTooltipOnSkuNotSelected}\n checkoutUrl={checkoutUrl}\n >\n {children && children.length > 0 ? (\n children\n ) : (\n <BuyButtonMessage showItemsPrice={showItemsPrice} skuItems={skuItems} />\n )}\n </BuyButton>\n )\n}\n\nconst withAddToCart = graphql(addToCartMutation, {\n name: 'addToCart',\n props: ({ addToCart }) => ({\n addToCart: items => addToCart({ variables: { items } }),\n }),\n})\n\nconst withOpenMinicart = graphql(setOpenMinicartMutation, {\n name: 'setMinicartOpen',\n props: ({ setMinicartOpen }) => ({\n setMinicartOpen: isOpen => setMinicartOpen({ variables: { isOpen } }),\n }),\n})\n\nconst withCheckoutVersion = graphql(installedApp, {\n name: 'checkoutVersion',\n options: {\n ssr: false,\n variables: {\n slug: 'vtex.checkout',\n },\n },\n})\n\n/**\n * @deprecated This component is deprecated. Please use [vtex.add-to-cart-button](https://github.com/vtex-apps/add-to-cart-button) instead.\n */\nconst EnhancedBuyButton = compose(\n withAddToCart,\n withOpenMinicart,\n withCheckoutVersion,\n withToast,\n injectIntl\n)(BuyButtonWrapper)\n\n// This function is public available to be used only by vtex.product-summary.\n// We do not garantee this API will not change and might happen breaking change anytime.\nEnhancedBuyButton.mapCatalogItemToCart = function mapCatalogItemToCart({\n product,\n selectedItem,\n selectedQuantity,\n selectedSeller,\n assemblyOptions,\n}) {\n return (\n product &&\n selectedItem &&\n selectedSeller &&\n selectedSeller.commertialOffer && [\n {\n index: 0,\n quantity: selectedQuantity,\n detailUrl: `/${product.linkText}/p`,\n name: product.productName,\n brand: product.brand,\n category:\n product.categories && product.categories.length > 0\n ? product.categories[0]\n : '',\n productRefId: product.productReference,\n seller: selectedSeller.sellerId,\n price: selectedSeller.commertialOffer.Price,\n listPrice: selectedSeller.commertialOffer.ListPrice,\n variant: selectedItem.name,\n skuId: selectedItem.itemId,\n imageUrl: path(['images', '0', 'imageUrl'], selectedItem),\n ...transformAssemblyOptions(\n path(['items'], assemblyOptions),\n path(['inputValues'], assemblyOptions),\n selectedSeller.commertialOffer.Price,\n selectedQuantity\n ),\n sellingPriceWithAssemblies:\n selectedSeller.commertialOffer.Price +\n sumAssembliesPrice(path(['items'], assemblyOptions) || {}),\n },\n ]\n )\n}\n\nexport default EnhancedBuyButton\n\n```"
}
] |
code_store-components_8af4116f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { useContext, useCallback, useState, useEffect } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { path } from 'ramda'\nimport ContentLoader from 'react-content-loader'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { usePWA } from 'vtex.store-resources/PWAContext'\nimport { useCssHandles } from 'vtex.css-handles'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { useProductDispatch } from 'vtex.product-context/ProductDispatchContext'\nimport { Button, ToastContext, Tooltip } from 'vtex.styleguide'\n\nimport useMarketingSessionParams from './hooks/useMarketingSessionParams'\n\nconst CONSTANTS = {\n SUCCESS_MESSAGE_ID: 'store/buybutton.buy-success',\n SELECT_SKU_ERROR_ID: 'store/buybutton.select-sku-variations',\n OFFLINE_BUY_MESSAGE_ID: 'store/buybutton.buy-offline-success',\n DUPLICATE_CART_ITEM_ID: 'store/buybutton.buy-success-duplicate',\n ERROR_MESSAGE_ID: 'store/buybutton.add-failure',\n SEE_CART_ID: 'store/buybutton.see-cart',\n TOAST_TIMEOUT: 3000,\n}\n\nconst CSS_HANDLES = ['buyButtonContainer', 'buyButtonText']\n\nconst isTooltipNeeded = ({ showTooltipOnSkuNotSelected, skuSelector }) => {\n if (showTooltipOnSkuNotSelected && !skuSelector.areAllVariationsSelected) {\n return {\n showTooltip: true,\n labelId: CONSTANTS.SELECT_SKU_ERROR_ID,\n }\n }\n\n return {\n showTooltip: false,\n }\n}\n\nconst skuItemToMinicartItem = item => {\n return {\n // Important for the mutation\n id: item.skuId ?? item.id,\n seller: item.seller,\n options: item.options,\n quantity: item.quantity,\n\n // Fields for optmistic cart\n sellingPrice: item.price,\n skuName: item.variant,\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrl,\n name: item.name,\n listPrice: item.listPrice,\n assemblyOptions: item.assemblyOptions,\n sellingPriceWithAssemblies: item.sellingPriceWithAssemblies,\n\n // Fields for Analytics\n brand: item.brand,\n category: item.category,\n productRefId: item.productRefId,\n }\n}\n\nconst useCallCartFinishIfPending = (\n orderFormContext,\n isAddingToCart,\n addToCartAndFinish\n) => {\n const orderFormLoading = orderFormContext && orderFormContext.loading\n\n useEffect(() => {\n if (!orderFormLoading && isAddingToCart) {\n addToCartAndFinish()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderFormLoading])\n}\n\n/**\n * BuyButton Component.\n * Adds a list of sku items to the cart.\n * @deprecated This component is deprecated. Please use [vtex.add-to-cart-button](https://github.com/vtex-apps/add-to-cart-button) instead.\n */\nexport const BuyButton = ({\n intl,\n large,\n addToCart,\n skuItems,\n onAddStart,\n onAddFinish,\n setMinicartOpen,\n available = true,\n orderFormContext,\n isOneClickBuy = false,\n children,\n disabled: disabledProp,\n shouldAddToCart = true,\n shouldOpenMinicart = false,\n showTooltipOnSkuNotSelected = true,\n checkoutUrl,\n customToastURL = checkoutUrl,\n}) => {\n const { handles } = useCssHandles(CSS_HANDLES)\n const [isAddingToCart, setAddingToCart] = useState(false)\n const { showToast } = useContext(ToastContext)\n const {\n skuSelector = {\n areAllVariationsSelected: true,\n },\n } = useProduct()\n\n const dispatch = useProductDispatch()\n const { settings = {}, showInstallPrompt } = usePWA() || {}\n const { rootPath = '' } = useRuntime()\n const { promptOnCustomEvent } = settings\n const translateMessage = useCallback(id => intl.formatMessage({ id }), [intl])\n const orderFormItems = path(['orderForm', 'items'], orderFormContext)\n const { utmParams, utmiParams } = useMarketingSessionParams()\n\n const resolveToastMessage = (success, isNewItem) => {\n if (!success) return translateMessage(CONSTANTS.ERROR_MESSAGE_ID)\n if (!isNewItem) return translateMessage(CONSTANTS.DUPLICATE_CART_ITEM_ID)\n\n const isOffline = window && window.navigator && !window.navigator.onLine\n const checkForOffline = !isOffline\n ? translateMessage(CONSTANTS.SUCCESS_MESSAGE_ID)\n : translateMessage(CONSTANTS.OFFLINE_BUY_MESSAGE_ID)\n\n return checkForOffline\n }\n\n const toastMessage = ({ success, isNewItem }) => {\n const message = resolveToastMessage(success, isNewItem)\n\n const action = success\n ? {\n label: translateMessage(CONSTANTS.SEE_CART_ID),\n href: rootPath + customToastURL,\n }\n : undefined\n\n showToast({ message, action })\n }\n\n const fullCheckoutUrl = rootPath + checkoutUrl\n\n const beforeAddToCart = event => {\n event.stopPropagation()\n event.preventDefault()\n\n setAddingToCart(true)\n onAddStart && onAddStart()\n }\n\n const addToCartAndFinish = async () => {\n let showToastMessage\n\n try {\n const minicartItems = skuItems.map(skuItemToMinicartItem)\n const localStateMutationResult = !isOneClickBuy\n ? await addToCart(minicartItems)\n : null\n\n const linkStateItems =\n localStateMutationResult && localStateMutationResult.data.addToCart\n\n const callOrderFormDirectly = !linkStateItems\n\n let success = null\n\n if (callOrderFormDirectly) {\n const variables = {\n orderFormId: orderFormContext.orderForm.orderFormId,\n items: skuItems.map(item => ({\n id: item.skuId ?? item.id,\n seller: item.seller,\n options: item.options,\n quantity: item.quantity,\n })),\n ...(utmParams ? { utmParams } : {}),\n ...(utmiParams ? { utmiParams } : {}),\n }\n\n const mutationRes = await orderFormContext.addItem({ variables })\n const { items } = mutationRes.data.addItem\n\n success = skuItems.filter(\n skuItem =>\n !!items.find(\n ({ id, seller }) =>\n (id === skuItem.skuId || id === skuItem.id) &&\n seller === skuItem.seller\n )\n )\n await orderFormContext.refetch().catch(() => null)\n }\n\n const addedItem =\n (linkStateItems &&\n skuItems.filter(\n skuItem =>\n !!linkStateItems.find(\n ({ id, seller }) =>\n (id === skuItem.skuId || id === skuItem.id) &&\n seller === skuItem.seller\n )\n )) ||\n success\n\n const foundItem =\n addedItem.length &&\n orderFormItems &&\n orderFormItems.filter(\n item =>\n item.id === addedItem[0].skuId &&\n item.seller === addedItem[0].seller &&\n !item.canHaveAttachment\n ).length > 0\n\n success = addedItem\n\n showToastMessage = () =>\n toastMessage({\n success: success && success.length >= 1,\n isNewItem: !foundItem,\n })\n\n /* PWA */\n if (promptOnCustomEvent === 'addToCart' && showInstallPrompt) {\n showInstallPrompt()\n }\n\n shouldOpenMinicart && !isOneClickBuy && setMinicartOpen(true)\n } catch (err) {\n console.error(err)\n showToastMessage = () => toastMessage(false)\n }\n\n setTimeout(() => {\n setAddingToCart(false)\n showToastMessage()\n if (isOneClickBuy) {\n // eslint-disable-next-line no-restricted-globals\n location.assign(fullCheckoutUrl)\n }\n\n onAddFinish && onAddFinish()\n }, 500)\n }\n\n const handleAddToCart = async event => {\n beforeAddToCart(event)\n await addToCartAndFinish()\n }\n\n useCallCartFinishIfPending(\n orderFormContext,\n isAddingToCart,\n addToCartAndFinish\n )\n\n const handleClick = e => {\n if (dispatch) {\n dispatch({ type: 'SET_BUY_BUTTON_CLICKED', args: { clicked: true } })\n }\n\n if (skuSelector.areAllVariationsSelected && shouldAddToCart) {\n if (orderFormContext && orderFormContext.loading) {\n // Just call the before add to cart function and the useEffect hook will call the finish part when apropriate\n beforeAddToCart(e)\n } else {\n handleAddToCart(e)\n }\n }\n }\n\n if (!skuItems) {\n return <ContentLoader />\n }\n\n const disabled = disabledProp || !available\n const unavailableLabel = (\n <FormattedMessage id=\"store/buyButton-label-unavailable\">\n {message => <span className={handles.buyButtonText}>{message}</span>}\n </FormattedMessage>\n )\n\n const ButtonWithLabel = (\n <Button\n block={large}\n disabled={disabled}\n onClick={handleClick}\n isLoading={isAddingToCart}\n >\n {available ? children : unavailableLabel}\n </Button>\n )\n\n const { showTooltip, labelId } = isTooltipNeeded({\n showTooltipOnSkuNotSelected,\n skuSelector,\n })\n\n const tooltipLabel = showTooltip && (\n <span className={handles.errorMessage}>\n <FormattedMessage id={labelId} />\n </span>\n )\n\n return !showTooltip ? (\n ButtonWithLabel\n ) : (\n <Tooltip trigger=\"click\" label={tooltipLabel}>\n {ButtonWithLabel}\n </Tooltip>\n )\n}\n\nBuyButton.propTypes = {\n /** SKU Items to be added to the cart */\n skuItems: PropTypes.arrayOf(\n PropTypes.shape({\n /** Specification of which product will be added to the cart */\n skuId: PropTypes.string.isRequired,\n /** Quantity of the product sku to be added to the cart */\n quantity: PropTypes.number.isRequired,\n /** Which seller is being referenced by the button */\n seller: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /* Sku name */\n name: PropTypes.string.isRequired,\n /* Sku price */\n price: PropTypes.number.isRequired,\n /* Sku variant */\n variant: PropTypes.string,\n /* Sku brand */\n brand: PropTypes.string.isRequired,\n /* Sku options. In delivery, for examples, are the pizza options */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n /* Option id */\n id: PropTypes.string.isRequired,\n /* Option quantity */\n quantity: PropTypes.number.isRequired,\n /* Option assembly id */\n assemblyId: PropTypes.string.isRequired,\n /* Option seller */\n seller: PropTypes.string,\n })\n ),\n })\n ),\n /** Component children that will be displayed inside of the button */\n children: PropTypes.node.isRequired,\n /** Should redirect to checkout after adding to cart */\n isOneClickBuy: PropTypes.bool,\n /** Should open the Minicart after click */\n shouldOpenMinicart: PropTypes.bool,\n /** If it should add to cart when clicked */\n shouldAddToCart: PropTypes.bool,\n /** Set style to large */\n large: PropTypes.bool,\n /** Internationalization */\n intl: PropTypes.object.isRequired,\n /** If the product is available or not */\n available: PropTypes.bool,\n /** If it should a tooltip when you click the button but there's no SKU selected */\n showTooltipOnSkuNotSelected: PropTypes.bool,\n /** Function used to show toasts (messages) to user */\n showToast: PropTypes.func,\n /** Function to be called on the start of add to cart click event */\n onAddStart: PropTypes.func,\n /** Function to be called on the end of add to cart event */\n onAddFinish: PropTypes.func,\n /** Add to cart mutation */\n addToCart: PropTypes.func.isRequired,\n /** Open Minicart mutation */\n setMinicartOpen: PropTypes.func.isRequired,\n /** The orderFormContext object */\n orderFormContext: PropTypes.object,\n /** If the button is disabled or not */\n disabled: PropTypes.bool,\n /** A custom URL for the `VIEW CART` button inside the toast */\n customToastURL: PropTypes.string,\n /** The URL to the cart */\n checkoutUrl: PropTypes.string,\n}\n\nexport default BuyButton\n\n```"
}
] |
code_store-components_d809ade9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/DiscountBadge/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* DiscountBadge CSS Module.\n*/\n\n.discountContainer {\n}\n.discountInsideContainer {\n}\n\n```"
}
] |
code_store-components_f639ff85
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/DiscountBadge/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { FormattedNumber } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport { IOMessage } from 'vtex.native-types'\n\nimport styles from './styles.css'\n\nconst calculateDiscountTax = (listPrice, sellingPrice) => {\n return (listPrice - sellingPrice) / listPrice\n}\n\n/**\n * The discount badge component. It receives the product's list and selling prices\n * and calculates the discount percent to show it in the product's sumary.\n *\n * @deprecated This component is deprecated. Please use [vtex.product-price](https://github.com/vtex-apps/product-price) instead.\n */\nfunction DiscountBadge({ listPrice, sellingPrice, label = '', children }) {\n const percent = calculateDiscountTax(listPrice, sellingPrice)\n const shouldShowPercentage = percent && percent >= 0.01\n\n return (\n <div className={`${styles.discountContainer} relative dib`}>\n {shouldShowPercentage ? (\n <div\n className={`${styles.discountInsideContainer} t-mini white absolute right-0 pv2 ph3 bg-emphasis z-1`}\n >\n <IOMessage id={label}>\n {labelValue => (\n <>\n {!labelValue && '-'}\n <FormattedNumber value={percent} style=\"percent\" />{' '}\n {labelValue && ' '}\n {labelValue && <span>{labelValue}</span>}\n </>\n )}\n </IOMessage>\n </div>\n ) : null}\n {children}\n </div>\n )\n}\n\nDiscountBadge.propTypes = {\n /** The product's default price */\n listPrice: PropTypes.number.isRequired,\n /** The product's price with discount */\n sellingPrice: PropTypes.number.isRequired,\n /** Label to track the discount percent */\n label: PropTypes.string,\n /** Image element */\n children: PropTypes.node.isRequired,\n}\n\nexport default DiscountBadge\n\n```"
}
] |
code_store-components_6a6cad78
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Greeting/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* Greeting CSS Module\n*/\n.greetingContainer {\n}\n.message {\n}\n.firstName {\n}\n\n```"
}
] |
code_store-components_9b16208b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Greeting/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Fragment } from 'react'\nimport { compose, branch, renderComponent } from 'recompose'\nimport { FormattedMessage } from 'react-intl'\nimport { path } from 'ramda'\nimport { graphql } from 'react-apollo'\n\nimport orderFormQuery from './queries/orderForm.gql'\nimport Loader from './Loader'\nimport styles from './styles.css'\n\nfunction Wrapper({ children }) {\n return (\n <div\n className={`${styles.greetingContainer} mh4 pv4 t-heading-4 c-on-base nowrap`}\n >\n {children}\n </div>\n )\n}\n\n// eslint-disable-next-line react/display-name\nconst withWrapper = Component => props =>\n (\n <Wrapper>\n <Component {...props} />\n </Wrapper>\n )\n\n/**\n * @deprecated This component is deprecated.\n */\nfunction Greeting({ orderForm }) {\n const firstName = path(['clientProfileData', 'firstName'], orderForm) || null\n\n return (\n firstName && (\n <Wrapper>\n <Fragment>\n <span className={styles.message}>\n <FormattedMessage id=\"store/greeting\" />,\n </span>\n <span className={`${styles.firstName} pl2 b`}>{firstName}</span>\n </Fragment>\n </Wrapper>\n )\n )\n}\n\nGreeting.propTypes = {\n orderForm: PropTypes.shape({\n clientProfileData: PropTypes.shape({\n firstName: PropTypes.string,\n }),\n }),\n}\n\nconst withLinkStateOrderForm = graphql(orderFormQuery, {\n props: ({ data: { minicart } }) => ({\n orderForm: minicart && minicart.orderForm && JSON.parse(minicart.orderForm),\n }),\n})\n\nexport default compose(\n withLinkStateOrderForm,\n branch(({ loading }) => loading, renderComponent(withWrapper(Loader)))\n)(Greeting)\n\n```"
}
] |
code_store-components_0fb31f50
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Greeting/Loader.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport ContentLoader from 'react-content-loader'\n\nconst GreetingLoading = props => (\n <ContentLoader\n height={32}\n width={300}\n speed={2}\n primaryColor=\"#f3f3f3\"\n secondaryColor=\"#ecebeb\"\n className=\"v-mid\"\n data-testid=\"greeting-loader\"\n {...props}\n >\n <rect rx=\"1\" ry=\"1\" width=\"300\" height=\"32\" />\n </ContentLoader>\n)\n\nexport default GreetingLoading\n\n```"
}
] |
code_store-components_87e562d3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/module/images.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { head } from 'ramda'\n\nexport const imageUrlForSize = (imageUrl: string, size: number) => {\n if (!imageUrl) {\n return ''\n }\n\n const urlSplitted = imageUrl.split('/')\n const idsStringIdx = urlSplitted.findIndex(content => content === 'ids')\n\n if (idsStringIdx < 0 || idsStringIdx === urlSplitted.length - 1)\n return imageUrl\n const sizeStringIdx = idsStringIdx + 1\n const sizeString = urlSplitted[sizeStringIdx]\n const imageId = head(sizeString.split('-'))\n const newSizeString = `${imageId}-${size * 2}-auto`\n\n return [\n ...urlSplitted.slice(0, sizeStringIdx),\n newSizeString,\n ...urlSplitted.slice(sizeStringIdx + 1),\n ].join('/')\n}\n\nexport const VARIATION_IMG_SIZE = 40\nexport const IMAGE_DEFAULT_SIZE = 900\nexport const THUMB_SIZE = 150\n\n```"
}
] |
code_store-components_2e27cabc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Animation/index.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\nimport { ANIMATIONS } from './animation'\n\nconst ANIMATION_TRANSFER = 110\nconst ANIMATION_TRANSFER_ENTER = 0\nconst ANIMATION_TIME = 0.4\n\n/**\n * Animation component\n *\n * @deprecated This component is deprecated.\n */\nexport default class Animation extends Component {\n static propTypes = {\n /* Object to be animated */\n children: PropTypes.node.isRequired,\n /* Active the animation */\n isActive: PropTypes.bool,\n /* Classname to the animation */\n className: PropTypes.string,\n /* Type of animation */\n type: PropTypes.oneOf([\n 'drawerLeft',\n 'drawerRight',\n 'drawerTop',\n 'drawerBottom',\n ]),\n /* The animation's duration in seconds */\n duration: PropTypes.number,\n /* The active animation deslocation in percentage */\n transfer: PropTypes.number,\n /* The not active animation deslocation in percentage */\n transferEnter: PropTypes.number,\n }\n\n static defaultProps = {\n className: '',\n type: 'drawerLeft',\n duration: ANIMATION_TIME,\n transfer: ANIMATION_TRANSFER,\n transferEnter: ANIMATION_TRANSFER_ENTER,\n }\n\n get animation() {\n const { isActive, type, duration, transfer, transferEnter } = this.props\n let animation = ANIMATIONS[type]\n\n if (isActive) {\n animation = animation.from(duration, transferEnter)\n } else {\n animation = animation.leave(duration, transfer)\n }\n\n return animation\n }\n\n render() {\n const { className, children } = this.props\n\n return (\n <div className={className} style={this.animation}>\n {children}\n </div>\n )\n }\n}\n\n```"
}
] |
code_store-components_4c8bfee4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Animation/animation.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst DRAWER_HORIZONTAL = 'drawerHorizontal'\nconst DRAWER_VERTICAL = 'drawerVertical'\n\nexport const DRAWER_ANIMATION = {\n [DRAWER_HORIZONTAL]: (duration, transfer) => ({\n transform: `translateX(${transfer}%)`,\n transition: `transform ${duration}s ease-in-out`,\n }),\n [DRAWER_VERTICAL]: (duration, transfer) => ({\n transform: `translateY(${transfer}%)`,\n transition: `transform ${duration}s ease-in-out`,\n }),\n}\n\nexport const ANIMATIONS = {\n drawerLeft: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, -transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, transfer),\n },\n drawerRight: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_HORIZONTAL](duration, -transfer),\n },\n drawerTop: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, -transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, transfer),\n },\n drawerBottom: {\n from: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, transfer),\n leave: (duration, transfer) =>\n DRAWER_ANIMATION[DRAWER_VERTICAL](duration, -transfer),\n },\n}\n\n```"
}
] |
code_store-components_231e26fd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/slider.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.arrowRight:before {\n display: inline-block;\n width: 48px;\n height: 48px;\n background: url(./images/stre-right.svg); \n content: '';\n}\n.arrowLeft:before {\n display: inline-block;\n width: 48px;\n height: 48px;\n background: url(./images/stre-left.svg); \n content: '';\n}\n\n.dots {}\n```"
}
] |
code_store-components_d4c6e134
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/global.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@import url('~slick-carousel/slick/slick.css');\n@import url('~slick-carousel/slick/slick-theme.css');\n@import url('./slider.css');\n\n/* Fixes uneven arrows distance */\n.slick-prev, .slick-next {\n width: inherit !important;\n height: inherit !important;\n}\n\n/* Clearfix for left arrow */\n.slick-prev {\n left: 0 !important;\n}\n\n/* Clearfix for right arrow */\n.slick-next {\n right: 0 !important;\n}\n\n.slick-dots {\n position: inherit !important;\n}\n\n\n```"
}
] |
code_store-components_fa555628
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/index.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 Slider from 'react-slick'\nimport ReactResizeDetector from 'react-resize-detector'\nimport { NoSSR } from 'vtex.render-runtime'\n\nimport Dots from './components/Dots'\nimport Arrow from './components/Arrow'\nimport getItemsPerPage from './utils/ItemsPerPage'\nimport './global.css'\nimport slider from './slider.css'\n\nconst VTEXClasses = {\n ARROW_RIGHT_CLASS: `${slider.arrowRight}`,\n ARROW_LEFT_CLASS: `${slider.arrowLeft}`,\n DOTS_CLASS: `${slider.dots}`,\n}\n\n/**\n * Slick Slider Component.\n *\n * @deprecated This component is deprecated. Please use [vtex.slider-layout](https://github.com/vtex-apps/slider-layout) instead.\n */\nexport default class SlickSlider extends Component {\n static propTypes = {\n /** Array of items to be rendered inside the slider. */\n children: PropTypes.array.isRequired,\n /** Slider settings. */\n sliderSettings: PropTypes.object,\n /** Makes the items per page to adapt by the slider width. */\n adaptToScreen: PropTypes.bool,\n /** Default item width, it's necessary when the adaptToScreen is true. */\n defaultItemWidth: PropTypes.number,\n /** If the scroll of items is by page or not. */\n scrollByPage: PropTypes.bool,\n /** SSR fallback. */\n ssrFallback: PropTypes.element,\n /** Left arrow custom classes */\n leftArrowClasses: PropTypes.string,\n /** Right arrow custom classes */\n rightArrowClasses: PropTypes.string,\n /** Dots custom classes */\n dotsClasses: PropTypes.string,\n }\n\n getSettings(slideWidth) {\n const {\n sliderSettings,\n adaptToScreen,\n scrollByPage,\n defaultItemWidth,\n children,\n leftArrowClasses,\n rightArrowClasses,\n dotsClasses,\n } = this.props\n\n const itemsPerPage = getItemsPerPage(\n this._slick,\n slideWidth,\n defaultItemWidth,\n sliderSettings.slidesToShow\n )\n\n const settings = { ...sliderSettings }\n const numItems = children.length\n\n settings.nextArrow = settings.nextArrow || (\n <Arrow\n customClasses={rightArrowClasses}\n cssClass={VTEXClasses.ARROW_RIGHT_CLASS}\n />\n )\n settings.prevArrow = settings.prevArrow || (\n <Arrow\n customClasses={leftArrowClasses}\n cssClass={VTEXClasses.ARROW_LEFT_CLASS}\n />\n )\n settings.appendDots = dots => (\n <Dots\n dots={dots}\n customClass={dotsClasses}\n cssClass={VTEXClasses.DOTS_CLASS}\n />\n )\n\n if (adaptToScreen) {\n settings.slidesToShow = itemsPerPage\n }\n\n if (scrollByPage) {\n settings.slidesToScroll = settings.slidesToShow\n }\n\n if (settings.infinite === undefined) {\n settings.infinite = settings.slidesToScroll < numItems\n }\n\n return settings\n }\n\n render() {\n const component = (\n <ReactResizeDetector handleWidth>\n {width => (\n <Slider\n {...this.getSettings(width)}\n ref={c => {\n this._slick = c\n }}\n >\n {this.props.children}\n </Slider>\n )}\n </ReactResizeDetector>\n )\n\n if (this.props.ssrFallback) {\n // eslint-disable-next-line react/jsx-handler-names\n return <NoSSR onSSR={this.props.ssrFallback}>{component}</NoSSR>\n }\n\n return component\n }\n}\n\n```"
}
] |
code_store-components_027290fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BackToTopButton/index.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect } from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { Icon } from 'vtex.store-icons'\nimport classNames from 'classnames'\n\nimport styles from './styles.css'\n\ninterface Props {\n displayThreshold?: number\n display?: Display\n}\n\ntype Display = 'button' | 'caret-icon'\n\nconst handleBackTop = () => {\n window.scroll({ top: 0, left: 0, behavior: 'smooth' })\n}\n\nconst BackToTopButton: StorefrontFC<Props> = ({\n displayThreshold = 600,\n display = 'button',\n}) => {\n const [isShowed, setIsShowed] = useState(false)\n const [scrollY, setScrollY] = useState(0)\n const backToTopButtonClasses = classNames(\n `${styles.backToTopButtonContainer} z-999 fixed bottom-2 right-2`,\n {\n [`${styles.backToTopButtonHidden}`]: !isShowed,\n [`${styles.backToTopButtonActive}`]: isShowed,\n }\n )\n\n function scrollValue() {\n setScrollY(window.pageYOffset)\n }\n\n useEffect(() => {\n window.addEventListener('scroll', scrollValue)\n\n return () => {\n window.removeEventListener('scroll', scrollValue)\n }\n }, [])\n\n useEffect(() => {\n if (scrollY > displayThreshold) {\n setIsShowed(true)\n } else {\n setIsShowed(false)\n }\n }, [scrollY, displayThreshold])\n\n if (!isShowed) {\n return null\n }\n\n return display === 'button' ? (\n <div className={backToTopButtonClasses}>\n <Button onClick={handleBackTop} size=\"regular\">\n <FormattedMessage id=\"store/back-to-top.label\" />\n </Button>\n </div>\n ) : (\n <div className={backToTopButtonClasses}>\n <Button onClick={handleBackTop} size=\"regular\">\n <Icon id=\"nav-caret--up\" size=\"16\" />\n </Button>\n </div>\n )\n}\n\nexport default BackToTopButton\n\n```"
}
] |
code_store-components_f7c9a871
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BackToTopButton/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.backToTopButtonContainer {\n border-bottom: 3.125rem;\n transition: all 0.3s ease-in-out;\n}\n\n.backToTopButtonHidden {\n overflow: hidden;\n height: 0;\n opacity: 0;\n}\n\n.backToTopButtonActive {\n height: auto;\n opacity: 1;\n}\n\n```"
}
] |
code_store-components_b3ea3c10
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BackToTopButton/BackToTopButton.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 BackToTopButton from './index'\n\ndescribe('<BackToTopButton /> component', () => {\n it('should be rendered', () => {\n const { asFragment } = render(<BackToTopButton />)\n\n expect(asFragment()).toBeTruthy()\n })\n})\n\n```"
}
] |
code_store-components_483af6ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductBrand/ProductBrandCssHandles.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { PRODUCT_BRAND_CSS_HANDLES } from '../../ProductBrand'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n PRODUCT_BRAND_CSS_HANDLES\n)\n\nexport {\n CssHandlesProvider as ProductBrandCssHandlesProvider,\n useContextCssHandles as useProductBrandCssHandles,\n}\n\n```"
}
] |
code_store-components_1dbf4d0e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductBrand/ProductBrandName.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { useProductBrandCssHandles } from './ProductBrandCssHandles'\n\ninterface Props {\n brandName: string\n withLink: boolean\n slug?: string\n}\n\nexport const CSS_HANDLES = ['productBrandNameLink', 'productBrandName'] as const\n\nfunction ProductBrandName({ brandName, withLink, slug }: Props) {\n const { handles } = useProductBrandCssHandles()\n\n if (withLink && slug) {\n const nameLink = `/${slug}`\n\n return (\n <a\n href={nameLink}\n className={`${handles.productBrandNameLink}`}\n data-testid=\"name-redirect\"\n >\n <span className={`${handles.productBrandName}`}>{brandName}</span>\n </a>\n )\n }\n\n return <span className={`${handles.productBrandName}`}>{brandName}</span>\n}\n\nexport default ProductBrandName\n\n```"
}
] |
code_store-components_aa0e6858
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/InfoCard/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport classNames from 'classnames'\nimport PropTypes, { bool, string, oneOf } from 'prop-types'\nimport React, { memo } from 'react'\nimport { values } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport {\n useRuntime,\n useExperimentalLazyImagesContext,\n} from 'vtex.render-runtime'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { useCssHandles } from 'vtex.css-handles'\nimport RichText from 'vtex.rich-text/index'\n\nimport CallToAction from './CallToAction'\nimport LinkWrapper from './LinkWrapper'\nimport {\n textPositionTypes,\n textAlignmentTypes,\n callToActionModeTypes,\n textPostionValues,\n textAlignmentValues,\n textModeTypes,\n} from './SchemaTypes'\nimport { SanitizedHTML } from '../SanitizedHTML'\n\nconst ALLOWED_TAGS = ['p', 'span', 'a', 'div', 'br']\nconst ALLOWED_ATTRS = {\n a: ['class', 'href', 'title', 'target'],\n span: ['class'],\n p: ['class'],\n div: ['class'],\n}\n\nconst justifyTokens = {\n [textPostionValues.LEFT]: 'justify-start',\n [textPostionValues.CENTER]: 'justify-center',\n [textPostionValues.RIGHT]: 'justify-end',\n}\n\nconst alignTokens = {\n [textAlignmentValues.LEFT]: 'tl',\n [textAlignmentValues.CENTER]: 'tc',\n [textAlignmentValues.RIGHT]: 'tr',\n}\n\nconst itemsTokens = {\n [textAlignmentValues.LEFT]: 'items-start',\n [textAlignmentValues.CENTER]: 'items-center',\n [textAlignmentValues.RIGHT]: 'items-end',\n}\n\nconst flexOrderTokens = {\n [textPostionValues.LEFT]: 'flex-row',\n [textPostionValues.RIGHT]: 'flex-row-reverse',\n}\n\nconst defaultValues = {\n textPosition: textPositionTypes.TEXT_POSITION_LEFT.value,\n textAlignment: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n}\n\nconst getEnumValues = enumObject => values(enumObject).map(({ value }) => value)\nconst getEnumNames = enumObject => values(enumObject).map(({ name }) => name)\n\nconst safelyGetToken = (tokenMap, valueWanted, propName) =>\n tokenMap[valueWanted] || defaultValues[propName]\n\nconst getImageUrl = (isMobile, imageUrl, mobileImageUrl) =>\n !!mobileImageUrl && isMobile ? mobileImageUrl : imageUrl\n\nconst CSS_HANDLES = [\n 'infoCardImageLinkWrapper',\n 'infoCardContainer',\n 'infoCardTextContainer',\n 'infoCardHeadline',\n 'infoCardSubhead',\n 'infoCardBodyText',\n 'infoCardImageContainer',\n 'infoCardImage',\n]\n\nconst InfoCard = ({\n isFullModeStyle,\n headline,\n subhead,\n bodyText,\n callToActionMode,\n callToActionText,\n callToActionUrl,\n callToActionLinkTarget,\n textPosition,\n textAlignment,\n imageUrl,\n mobileImageUrl,\n imageActionUrl,\n intl,\n htmlId,\n textMode,\n linkTarget,\n fetchpriority,\n preload,\n imageAltText,\n}) => {\n const {\n hints: { mobile },\n } = useRuntime()\n\n const { lazyLoad } = useExperimentalLazyImagesContext()\n\n const { handles } = useCssHandles(CSS_HANDLES)\n const paddingClass =\n textPosition === textPostionValues.LEFT ? 'pr4-ns' : 'pl4-ns'\n\n // We ignore textAlignment tokens when full image mode\n const alignToken = isFullModeStyle\n ? safelyGetToken(alignTokens, textPosition, 'textPosition')\n : safelyGetToken(alignTokens, textAlignment, 'textAlignment')\n\n const itemsToken = isFullModeStyle\n ? safelyGetToken(itemsTokens, textPosition, 'textPosition')\n : safelyGetToken(itemsTokens, textAlignment, 'textAlignment')\n\n const justifyToken = safelyGetToken(\n justifyTokens,\n textPosition,\n 'textPosition'\n )\n\n const flexOrderToken = safelyGetToken(\n flexOrderTokens,\n textPosition,\n 'textPosition'\n )\n\n const finalImageUrl = getImageUrl(\n mobile,\n formatIOMessage({ id: imageUrl, intl }),\n formatIOMessage({ id: mobileImageUrl, intl })\n )\n\n const containerStyle = isFullModeStyle\n ? {\n /* If lazyloaded, the background image comes from the `data-bg` attribute\n * below. Otherwise, sets it here as background-image */\n ...(!lazyLoad && { backgroundImage: `url(${finalImageUrl})` }),\n backgroundSize: 'cover',\n }\n : {}\n\n const containerAttributes =\n isFullModeStyle && lazyLoad ? { 'data-bg': finalImageUrl } : {}\n\n const containerClasses = classNames(\n `${handles.infoCardContainer} items-center`,\n {\n [`flex-ns ${flexOrderToken} bg-base ph2-ns pb2 justify-between`]:\n !isFullModeStyle,\n [`bg-center bb b--muted-4 flex ${justifyToken}`]: isFullModeStyle,\n lazyload: lazyLoad,\n }\n )\n\n const linkWrapperClasses = `${handles.infoCardImageLinkWrapper} no-underline`\n\n const textContainerClasses = classNames(\n `${handles.infoCardTextContainer} flex flex-column mw-100`,\n {\n [`w-50-ns ph3-s ${itemsToken} ${paddingClass}`]: !isFullModeStyle,\n [`mh8-ns mh4-s w-40-ns ${itemsToken}`]: isFullModeStyle,\n }\n )\n\n const headlineClasses = `${handles.infoCardHeadline} t-heading-2 mt6 ${alignToken} c-on-base mw-100`\n\n const subheadClasses = `${handles.infoCardSubhead} t-body mt6 c-on-base ${alignToken} mw-100`\n\n const bodyTextClasses = `${handles.infoCardBodyText} t-body mt6 c-on-base ${alignToken} mw-100`\n\n return (\n <LinkWrapper\n imageActionUrl={formatIOMessage({ id: imageActionUrl, intl })}\n extraCondition={!isFullModeStyle}\n linkProps={{ className: linkWrapperClasses, target: linkTarget }}\n >\n <div\n className={containerClasses}\n style={containerStyle}\n data-testid=\"container\"\n id={htmlId}\n {...containerAttributes}\n >\n <div className={textContainerClasses}>\n {headline &&\n (textMode === 'html' ? (\n <div className={headlineClasses}>\n <SanitizedHTML\n content={formatIOMessage({ id: headline, intl })}\n allowedTags={ALLOWED_TAGS}\n allowedAttributes={ALLOWED_ATTRS}\n />\n </div>\n ) : (\n <RichText className={headlineClasses} text={headline} />\n ))}\n {subhead &&\n (textMode === 'html' ? (\n <div className={subheadClasses}>\n <SanitizedHTML\n content={formatIOMessage({ id: subhead, intl })}\n allowedTags={ALLOWED_TAGS}\n allowedAttributes={ALLOWED_ATTRS}\n />\n </div>\n ) : (\n <RichText className={subheadClasses} text={subhead} />\n ))}\n {bodyText &&\n (textMode === 'html' ? (\n <div className={bodyTextClasses}>\n <SanitizedHTML\n content={formatIOMessage({ id: bodyText, intl })}\n allowedTags={ALLOWED_TAGS}\n allowedAttributes={ALLOWED_ATTRS}\n />\n </div>\n ) : (\n <RichText className={bodyTextClasses} text={bodyText} />\n ))}\n <CallToAction\n mode={callToActionMode}\n text={formatIOMessage({ id: callToActionText, intl })}\n url={formatIOMessage({ id: callToActionUrl, intl })}\n linkTarget={callToActionLinkTarget}\n />\n </div>\n {!isFullModeStyle && (\n <div className={`${handles.infoCardImageContainer} w-50-ns`}>\n <LinkWrapper\n imageActionUrl={formatIOMessage({ id: imageActionUrl, intl })}\n linkProps={{ target: linkTarget }}\n >\n <img\n className={handles.infoCardImage}\n src={finalImageUrl}\n style={{ objectFit: 'cover' }}\n alt={\n imageAltText ||\n formatIOMessage({ id: callToActionText, intl })\n }\n data-testid=\"half-image\"\n fetchPriority={fetchpriority}\n {...(preload\n ? {\n 'data-vtex-preload': 'true',\n }\n : {})}\n />\n </LinkWrapper>\n </div>\n )}\n </div>\n </LinkWrapper>\n )\n}\n\nconst MemoizedInfoCard = memo(injectIntl(InfoCard))\n\nMemoizedInfoCard.propTypes = {\n blockClass: string,\n isFullModeStyle: bool,\n textPosition: oneOf(getEnumValues(textPositionTypes)),\n headline: string,\n subhead: string,\n bodyText: string,\n callToActionMode: oneOf(getEnumValues(callToActionModeTypes)),\n callToActionText: string,\n callToActionUrl: string,\n imageUrl: string,\n mobileImageUrl: string,\n textAlignment: oneOf(getEnumValues(textAlignmentTypes)),\n imageActionUrl: string,\n imageAltText: string,\n intl: PropTypes.object,\n htmlId: string,\n textMode: oneOf(getEnumValues(textModeTypes)),\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a\n linkTarget: oneOf(['_self', '_blank', '_parent', '_top']),\n callToActionLinkTarget: oneOf(['_self', '_blank', '_parent', '_top']),\n}\n\nMemoizedInfoCard.defaultProps = {\n isFullModeStyle: false,\n textPosition: textPositionTypes.TEXT_POSITION_LEFT.value,\n headline: '',\n subhead: '',\n bodyText: '',\n callToActionMode: callToActionModeTypes.CALL_ACTION_BUTTON.value,\n callToActionText: '',\n callToActionUrl: '',\n imageUrl: '',\n imageAltText: '',\n mobileImageUrl: '',\n textAlignment: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n textMode: textModeTypes.TEXT_MODE_HTML.value,\n linkTarget: '_self',\n callToActionLinkTarget: '_self',\n fetchpriority: 'auto',\n preload: false,\n}\n\nMemoizedInfoCard.schema = {\n title: 'admin/editor.info-card.title',\n description: 'admin/editor.info-card.description',\n type: 'object',\n properties: {\n isFullModeStyle: {\n title: 'admin/editor.info-card.isFullModeStyle.title',\n description: 'admin/editor.info-card.isFullModeStyle.description',\n type: 'boolean',\n default: false,\n isLayout: true,\n },\n textPosition: {\n title: 'admin/editor.info-card.textPosition.title',\n description: 'admin/editor.info-card.textPosition.description',\n type: 'string',\n enum: getEnumValues(textPositionTypes),\n enumNames: getEnumNames(textPositionTypes),\n default: textPositionTypes.TEXT_POSITION_LEFT.value,\n isLayout: true,\n },\n callToActionMode: {\n title: 'admin/editor.info-card.callToActionMode.title',\n description: 'admin/editor.info-card.callToActionMode.description',\n type: 'string',\n enum: getEnumValues(callToActionModeTypes),\n enumNames: getEnumNames(callToActionModeTypes),\n default: callToActionModeTypes.CALL_ACTION_BUTTON.value,\n isLayout: true,\n },\n imageAltText: {\n title: 'admin/editor.info-card.imageAltText.title',\n description: 'admin/editor.info-card.imageAltText.description',\n type: 'string',\n default: '',\n },\n textAlignment: {\n title: 'admin/editor.info-card.textAlignment.title',\n description: 'admin/editor.info-card.textAlignment.description',\n type: 'string',\n default: textAlignmentTypes.TEXT_ALIGNMENT_LEFT.value,\n enum: getEnumValues(textAlignmentTypes),\n enumNames: getEnumNames(textAlignmentTypes),\n isLayout: true,\n },\n textMode: {\n title: 'admin/editor.info-card.textMode.title',\n description: 'admin/editor.info-card.textMode.description',\n type: 'string',\n default: textModeTypes.TEXT_MODE_HTML.value,\n enum: getEnumValues(textModeTypes),\n enumNames: getEnumNames(textModeTypes),\n isLayout: true,\n },\n blockClass: {\n title: 'admin/editor.blockClass.title',\n description: 'admin/editor.blockClass.description',\n type: 'string',\n isLayout: true,\n },\n },\n}\n\nexport default MemoizedInfoCard\n\n```"
}
] |
code_store-components_1cabadbf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/InfoCard/CallToAction.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { Link } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { callActionValues } from './SchemaTypes'\n\nconst CSS_HANDLES = ['infoCardCallActionContainer', 'infoCardCallActionText']\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst noop = () => {}\n\nconst CallToAction = ({ mode, text, url, linkTarget }) => {\n const { handles } = useCssHandles(CSS_HANDLES)\n\n if (mode === callActionValues.NONE) {\n return null\n }\n\n // eslint-disable-next-line no-shadow\n const ActionWrapper = ({ text, mode }) => {\n if (mode === callActionValues.BUTTON) {\n return <Button onClick={noop}>{text}</Button>\n }\n\n // Mode is link\n return (\n <p\n className={`${handles.infoCardCallActionText} link t-body b underline c-action-primary`}\n >\n {text}\n </p>\n )\n }\n\n return (\n <Link\n className={`${handles.infoCardCallActionContainer} mt6 mb6`}\n target={linkTarget}\n to={url}\n alt={text}\n >\n <ActionWrapper text={text} mode={mode} />\n </Link>\n )\n}\n\nexport default CallToAction\n\n```"
}
] |
code_store-components_68aac24d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/InfoCard/SchemaTypes.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const textModeValues = {\n HTML: 'html',\n RICHTEXT: 'rich-text',\n}\n\nexport const textPostionValues = {\n LEFT: 'left',\n CENTER: 'center',\n RIGHT: 'right',\n}\n\nexport const textAlignmentValues = {\n LEFT: 'left',\n CENTER: 'center',\n RIGHT: 'right',\n}\n\nexport const callActionValues = {\n NONE: 'none',\n BUTTON: 'button',\n LINK: 'link',\n}\n\nexport const textModeTypes = {\n TEXT_MODE_HTML: {\n name: 'admin/editor.info-card.textMode.html',\n value: textModeValues.HTML,\n },\n TEXT_MODE_RICHTEXT: {\n name: 'admin/editor.info-card.textMode.rich-text',\n value: textModeValues.RICHTEXT,\n },\n}\n\nexport const textPositionTypes = {\n TEXT_POSITION_LEFT: {\n name: 'admin/editor.info-card.textPosition.left',\n value: textPostionValues.LEFT,\n },\n TEXT_POSITION_CENTER: {\n name: 'admin/editor.info-card.textPosition.center',\n value: textPostionValues.CENTER,\n },\n TEXT_POSITION_RIGHT: {\n name: 'admin/editor.info-card.textPosition.right',\n value: textPostionValues.RIGHT,\n },\n}\n\nexport const textAlignmentTypes = {\n TEXT_ALIGNMENT_LEFT: {\n name: 'admin/editor.info-card.textAlignment.left',\n value: textAlignmentValues.LEFT,\n },\n TEXT_ALIGNMENT_CENTER: {\n name: 'admin/editor.info-card.textAlignment.center',\n value: textAlignmentValues.CENTER,\n },\n TEXT_ALIGNMENT_RIGHT: {\n name: 'admin/editor.info-card.textAlignment.right',\n value: textAlignmentValues.RIGHT,\n },\n}\n\nexport const callToActionModeTypes = {\n CALL_ACTION_NONE: {\n name: 'admin/editor.info-card.callAction.none',\n value: callActionValues.NONE,\n },\n CALL_ACTION_BUTTON: {\n name: 'admin/editor.info-card.callAction.button',\n value: callActionValues.BUTTON,\n },\n CALL_ACTION_LINK: {\n name: 'admin/editor.info-card.callAction.link',\n value: callActionValues.LINK,\n },\n}\n\n```"
}
] |
code_store-components_e02c4856
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/InfoCard/LinkWrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { bool, string, object, node } from 'prop-types'\nimport { Link } from 'vtex.render-runtime'\n\nconst LinkWrapper = ({\n imageActionUrl,\n children,\n extraCondition,\n linkProps = {},\n}) => {\n if (!imageActionUrl || imageActionUrl.length === 0 || extraCondition) {\n return <Fragment>{children}</Fragment>\n }\n\n return (\n <Link {...linkProps} to={imageActionUrl}>\n {children}\n </Link>\n )\n}\n\nLinkWrapper.propTypes = {\n imageActionUrl: string,\n children: node,\n extraCondition: bool,\n linkProps: object,\n}\n\nexport default LinkWrapper\n\n```"
}
] |
code_store-components_54681efa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductSpecifications/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { isEmpty, propOr } from 'ramda'\n\nimport ProductSpecifications from './index'\n\nconst getSpecifications = productContext => {\n if (!productContext || isEmpty(productContext)) {\n return []\n }\n\n const { product } = productContext\n const specificationGroups = propOr([], 'specificationGroups', product)\n const groupWithAll = specificationGroups.find(\n specificationGroup =>\n specificationGroup.originalName === 'allSpecifications' ||\n specificationGroup.name === 'allSpecifications'\n )\n\n const allSpecifications = groupWithAll ? groupWithAll.specifications : []\n\n return allSpecifications\n}\n\n/**\n * @deprecated This component is deprecated. Please use [vtex.product-specifications](https://github.com/vtex-apps/product-specifications) instead.\n */\nfunction ProductSpecificationsWrapper({\n hiddenSpecifications,\n visibleSpecifications,\n specifications: propsSpecifications,\n tabsMode, // This is a legacy prop passed by product-details\n showSpecificationsTab = false,\n collapsible = 'always',\n}) {\n const productContext = useProduct()\n const specifications =\n propsSpecifications || getSpecifications(productContext)\n\n return (\n <ProductSpecifications\n hiddenSpecifications={hiddenSpecifications}\n visibleSpecifications={visibleSpecifications}\n tabsMode={tabsMode != null ? tabsMode : showSpecificationsTab}\n specifications={specifications}\n collapsible={collapsible}\n />\n )\n}\n\nProductSpecificationsWrapper.schema = {\n title: 'admin/editor.product-specifications.title',\n description: '',\n type: 'object',\n properties: {\n hiddenSpecifications: {\n items: {\n default: '',\n type: 'string',\n title: 'admin/editor.product-specifications.items.title',\n },\n description:\n 'admin/editor.product-specifications.hidden-specifications.description',\n title: 'admin/editor.product-specifications.hidden-specifications.title',\n type: 'array',\n },\n visibleSpecifications: {\n items: {\n default: '',\n type: 'string',\n title: 'admin/editor.product-specifications.items.title',\n },\n description:\n 'admin/editor.product-specifications.visible-specifications.description',\n title: 'admin/editor.product-specifications.visible-specifications.title',\n type: 'array',\n },\n },\n}\n\nexport default ProductSpecificationsWrapper\n\n```"
}
] |
code_store-components_55598280
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductSpecifications/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useState } from 'react'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { Tabs, Tab } from 'vtex.styleguide'\nimport { useDevice } from 'vtex.device-detector'\n\nimport { SanitizedHTML } from '../SanitizedHTML'\nimport GradientCollapse from '../GradientCollapse/index'\n\nconst CSS_HANDLES = [\n 'specificationsTableContainer',\n 'specificationsTabsContainer',\n 'specificationsTitle',\n 'specificationsTable',\n 'specificationsTableRow',\n 'specificationsTableHead',\n 'specificationsTableBody',\n 'specificationsTab',\n 'specificationsTablePropertyHeading',\n 'specificationsTableSpecificationHeading',\n 'specificationItemProperty',\n 'specificationItemSpecifications',\n]\n\n/**\n * Product Specification Component.\n * Render the technical specifications of a product. Can be displayed in two views: Table view or Tabs view.\n */\nconst ProductSpecifications = ({\n tabsMode,\n specifications,\n collapsible = 'always',\n hiddenSpecifications,\n visibleSpecifications,\n shouldCollapseInTabChange,\n}) => {\n const [currentTab, setCurrentTab] = useState(0)\n const [collapsed, setCollapsed] = useState(true)\n const { handles } = useCssHandles(CSS_HANDLES)\n const { isMobile } = useDevice()\n\n const shouldBeCollapsible = Boolean(\n collapsible === 'always' ||\n (collapsible === 'mobileOnly' && isMobile) ||\n (collapsible === 'desktopOnly' && !isMobile)\n )\n\n const handleTabChange = tabIndex => {\n setCurrentTab(tabIndex)\n if (shouldCollapseInTabChange) {\n setCollapsed(true)\n }\n }\n\n const getSpecificationItems = () => {\n const mappedSpecifications = specifications.map(specification => {\n return {\n property: specification.name,\n specifications: specification.values.join(', '),\n }\n })\n\n if (\n visibleSpecifications &&\n visibleSpecifications.length > 0 &&\n hiddenSpecifications &&\n hiddenSpecifications.length > 0\n ) {\n console.warn(\n 'A product-specification block is using both visibleSpecifications and hiddenSpecifications props at the same time. Please choose only one of them.'\n )\n\n return mappedSpecifications\n }\n\n if (visibleSpecifications && visibleSpecifications.length > 0) {\n return mappedSpecifications.filter(specification =>\n visibleSpecifications.find(\n filter =>\n specification.property.toLowerCase() === filter.toLowerCase()\n )\n )\n }\n\n if (hiddenSpecifications && hiddenSpecifications.length > 0) {\n return mappedSpecifications.filter(\n specification =>\n !hiddenSpecifications.find(\n filter =>\n specification.property.toLowerCase() === filter.toLowerCase()\n )\n )\n }\n\n return mappedSpecifications\n }\n\n const specificationItems = getSpecificationItems()\n\n const specificationTitle = (\n <FormattedMessage id=\"store/technicalspecifications.title\">\n {txt => (\n <h2 className={`${handles.specificationsTitle} t-heading-5 mb5 mt0`}>\n <SanitizedHTML content={txt} />\n </h2>\n )}\n </FormattedMessage>\n )\n\n const specificationsTable = (\n <table\n className={`${handles.specificationsTable} w-100 bg-base border-collapse`}\n >\n <thead className={handles.specificationsTableHead}>\n <tr className={handles.specificationsTableRow}>\n <th\n className={`${handles.specificationsTablePropertyHeading} w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5`}\n >\n <FormattedMessage id=\"store/product-description.property\" />\n </th>\n <th\n className={`${handles.specificationsTableSpecificationHeading} w-50 b--muted-4 bb bt c-muted-2 t-body tl pa5`}\n >\n <FormattedMessage id=\"store/product-description.specification\" />\n </th>\n </tr>\n </thead>\n <tbody className={handles.specificationsTableBody}>\n {specificationItems.map((specification, i) => (\n <tr className={handles.specificationsTableRow} key={i}>\n <td\n data-specification={specification.property}\n className={`${handles.specificationItemProperty} w-50 b--muted-4 bb pa5`}\n >\n <SanitizedHTML content={specification.property} />\n </td>\n <td\n data-specification={specification.specifications}\n className={`${handles.specificationItemSpecifications} w-50 b--muted-4 bb pa5`}\n >\n <SanitizedHTML content={specification.specifications} />\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )\n\n const tableView = (\n <Fragment>\n {specifications.length > 0 && (\n <div\n className={`${handles.specificationsTableContainer} mt9 mt0-l pl8-l`}\n >\n {specificationTitle}\n {shouldBeCollapsible ? (\n <GradientCollapse\n collapseHeight={220}\n collapsed={collapsed}\n onCollapsedChange={(_, newValue) => setCollapsed(newValue)}\n >\n {specificationsTable}\n </GradientCollapse>\n ) : (\n specificationsTable\n )}\n </div>\n )}\n </Fragment>\n )\n\n const tabsView = (\n <div className={`${handles.specificationsTabsContainer} pt8`}>\n {specificationTitle}\n <Tabs fullWidth>\n {specificationItems.map((specification, i) => (\n <Tab\n key={i}\n label={<SanitizedHTML content={specification.property} />}\n active={currentTab === i}\n onClick={() => handleTabChange(i)}\n >\n <div className={`${handles.specificationsTab} pb8 c-muted-1 pv6`}>\n {shouldBeCollapsible ? (\n <GradientCollapse\n collapseHeight={220}\n collapsed={collapsed}\n onCollapsedChange={(_, newValue) => setCollapsed(newValue)}\n >\n <SanitizedHTML content={specification.specifications} />\n </GradientCollapse>\n ) : (\n <SanitizedHTML content={specification.specifications} />\n )}\n </div>\n </Tab>\n ))}\n </Tabs>\n </div>\n )\n\n return tabsMode ? tabsView : tableView\n}\n\nProductSpecifications.defaultProps = {\n specifications: [],\n tabsMode: false,\n shouldCollapseInTabChange: false,\n}\n\nProductSpecifications.propTypes = {\n /** Specifications that will be displayed on the table */\n specifications: PropTypes.arrayOf(\n PropTypes.shape({\n /** Specification name */\n name: PropTypes.string.isRequired,\n /** Specifications value */\n values: PropTypes.arrayOf(PropTypes.string).isRequired,\n })\n ),\n /** If should collapse when a tab is changed */\n shouldCollapseInTabChange: PropTypes.bool,\n /** Tabs mode view */\n tabsMode: PropTypes.bool,\n /** Specifications which will be shown exclusively (optional) */\n visibleSpecifications: PropTypes.array,\n /** Specifications which will be hidden (optional) */\n hiddenSpecifications: PropTypes.array,\n collapsible: PropTypes.oneOf([\n 'always',\n 'never',\n 'desktopOnly',\n 'mobileOnly',\n ]),\n}\n\nexport default ProductSpecifications\n\n```"
}
] |
code_store-components_2b987420
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* Product Image CSS Module\n*/\n\n.productVideo {\n}\n\n.productImage {\n}\n\n.highQualityProductImageImgElement {\n max-height: unset;\n object-fit: contain;\n}\n\n/** Overrides figure css declaration from vtex-tachyons, which\n * for some reason adds margin to all figure elements */\n.figure {\n margin: 0;\n}\n\n.gradientBaseBottom {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(transparent, white);\n}\n\n.gradientBaseTop {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(white, transparent);\n}\n\n.gradientBaseRight {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(90deg, transparent, white);\n}\n\n.gradientBaseLeft {\n /** TODO: use the actual bg-base token instead of a hardcoded color */\n background: linear-gradient(90deg, white, transparent);\n}\n\n```"
}
] |
code_store-components_e1e12af2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo } from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { useResponsiveValues } from 'vtex.responsive-values'\nimport { path, pick } from 'ramda'\n\nimport ProductImages from './index'\nimport generateImageConfig from './utils/generateImageConfig'\nimport { THUMBS_ORIENTATION, THUMBS_POSITION_HORIZONTAL } from './utils/enums'\n\nconst ProductImagesWrapper = props => {\n const valuesFromContext = useProduct() || {}\n const {\n aspectRatio,\n maxHeight,\n showNavigationArrows,\n showPaginationDots,\n contentOrder,\n placeholder,\n } = useResponsiveValues(\n pick(\n [\n 'aspectRatio',\n 'maxHeight',\n 'showNavigationArrows',\n 'showPaginationDots',\n 'contentOrder',\n 'placeholder',\n ],\n props\n )\n )\n\n const { selectedItem, skuSelector, product } = valuesFromContext\n\n const images = useMemo(() => {\n if (props.images != null) {\n return props.images\n }\n\n let imagePaths\n\n // if there's a image sku defined\n if (\n product &&\n product.items &&\n skuSelector &&\n skuSelector.selectedImageVariationSKU\n ) {\n const skuItem = product.items.find(\n sku => sku.itemId === skuSelector.selectedImageVariationSKU\n )\n\n if (skuItem) {\n imagePaths = skuItem.images\n }\n }\n\n if (!imagePaths && selectedItem) {\n imagePaths = selectedItem.images\n }\n\n return (imagePaths || []).map(generateImageConfig)\n }, [props.images, product, skuSelector, selectedItem])\n\n const videos = useMemo(\n () =>\n props.videos != null\n ? props.videos\n : path(['videos'], selectedItem) || [],\n [props.videos, selectedItem]\n )\n\n return (\n <ProductImages\n images={images}\n videos={videos}\n hiddenImages={props.hiddenImages}\n placeholder={placeholder}\n // thumbnailPosition is a legacy prop from product-details\n position={props.position || props.thumbnailPosition}\n displayThumbnailsArrows={props.displayThumbnailsArrows}\n thumbnailsOrientation={props.thumbnailsOrientation}\n zoomMode={props.zoomMode}\n zoomFactor={props.zoomFactor}\n aspectRatio={aspectRatio}\n maxHeight={maxHeight}\n thumbnailAspectRatio={props.thumbnailAspectRatio}\n thumbnailMaxHeight={props.thumbnailMaxHeight}\n showNavigationArrows={showNavigationArrows}\n showPaginationDots={showPaginationDots}\n thumbnailVisibility={props.thumbnailVisibility}\n contentOrder={contentOrder}\n ModalZoomElement={props.ModalZoom}\n contentType={props.contentType}\n showImageLabel={props.showImageLabel}\n // Deprecated\n zoomProps={props.zoomProps}\n displayMode={props.displayMode}\n />\n )\n}\n\nProductImagesWrapper.getSchema = ({ zoomProps: { zoomType } = {} }) => ({\n title: 'admin/editor.product-images.title',\n description: 'admin/editor.product-images.description',\n type: 'object',\n properties: {\n zoomProps: {\n title: 'admin/editor.product-images.zoomOptions.title',\n type: 'object',\n properties: {\n zoomType: {\n title: 'admin/editor.product-images.zoomType.title',\n type: 'string',\n enum: ['gallery', 'in-page', 'no-zoom'],\n enumNames: [\n 'admin/editor.product-images.gallery',\n 'admin/editor.product-images.in-page',\n 'admin/editor.product-images.no-zoom',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: 'no-zoom',\n },\n ...(zoomType === 'gallery' && {\n bgOpacity: {\n title: 'admin/editor.product-images.bgopacity.title',\n type: 'number',\n minimum: 0.0,\n maximum: 1.0,\n multipleOf: 0.01,\n default: 0.8,\n },\n }),\n },\n },\n thumbnailsOrientation: {\n title: 'admin/editor.product-images.thumbnailsOrientation.title',\n type: 'string',\n enum: [THUMBS_ORIENTATION.VERTICAL, THUMBS_ORIENTATION.HORIZONTAL],\n enumNames: [\n 'admin/editor.product-images.vertical',\n 'admin/editor.product-images.horizontal',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: THUMBS_ORIENTATION.VERTICAL,\n isLayout: true,\n },\n position: {\n title: 'admin/editor.product-images.position.title',\n description: 'admin/editor.product-images.position.description',\n type: 'string',\n enum: [THUMBS_POSITION_HORIZONTAL.LEFT, THUMBS_POSITION_HORIZONTAL.RIGHT],\n enumNames: [\n 'admin/editor.product-images.left',\n 'admin/editor.product-images.right',\n ],\n widget: {\n 'ui:options': {\n inline: false,\n },\n 'ui:widget': 'radio',\n },\n default: THUMBS_POSITION_HORIZONTAL.LEFT,\n isLayout: true,\n },\n displayThumbnailsArrows: {\n title: 'admin/editor.product-images.displayThumbnailsArrows.title',\n type: 'boolean',\n default: false,\n isLayout: true,\n },\n },\n})\n\nexport default ProductImagesWrapper\n\n```"
}
] |
code_store-components_980e34d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo } from 'react'\nimport PropTypes from 'prop-types'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport Carousel from './components/Carousel'\nimport ProductImage from './components/ProductImage'\nimport {\n THUMBS_ORIENTATION,\n THUMBS_POSITION_HORIZONTAL,\n THUMBS_VISIBILITY,\n DEFAULT_EXCLUDE_IMAGE_WITH,\n DISPLAY_MODE,\n} from './utils/enums'\n\nconst CSS_HANDLES = ['content', 'productImagesContainer']\n\nconst ProductImages = ({\n position,\n displayThumbnailsArrows,\n hiddenImages,\n placeholder,\n images: allImages,\n videos: allVideos,\n thumbnailsOrientation,\n aspectRatio,\n maxHeight,\n thumbnailAspectRatio,\n thumbnailMaxHeight,\n showNavigationArrows,\n showPaginationDots,\n showImageLabel = false,\n thumbnailVisibility,\n contentOrder = 'images-first',\n zoomMode,\n zoomFactor,\n ModalZoomElement,\n contentType = 'all',\n // Deprecated\n zoomProps,\n displayMode,\n}) => {\n if (hiddenImages && !Array.isArray(hiddenImages)) {\n hiddenImages = [hiddenImages]\n }\n\n const excludeImageRegexes =\n hiddenImages && hiddenImages.map(text => new RegExp(text, 'i'))\n\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES)\n const productImagesContainerClass = withModifiers(\n 'productImagesContainer',\n displayMode\n )\n\n const images = useMemo(() => {\n const shouldIncludeImages = contentType !== 'videos'\n\n return shouldIncludeImages\n ? allImages\n .filter(\n image =>\n !image.imageLabel ||\n !excludeImageRegexes.some(regex => regex.test(image.imageLabel))\n )\n .map(image => ({\n type: 'image',\n url: image.imageUrls ? image.imageUrls[0] : image.imageUrl,\n alt: image.imageLabel,\n thumbUrl: image.thumbnailUrl || image.imageUrl,\n ...(showImageLabel && { imageLabel: image.imageLabel }),\n }))\n : []\n }, [allImages, contentType, excludeImageRegexes, showImageLabel])\n\n const videos = useMemo(() => {\n const shouldIncludeVideos = contentType !== 'images'\n\n return shouldIncludeVideos\n ? allVideos.map(video => ({\n type: 'video',\n src: video.videoUrl,\n thumbWidth: 300,\n }))\n : []\n }, [allVideos, contentType])\n\n const showVideosFirst = contentOrder === 'videos-first'\n\n const slides = useMemo(() => {\n return showVideosFirst ? [...videos, ...images] : [...images, ...videos]\n }, [showVideosFirst, videos, images])\n\n const { zoomType: legacyZoomType } = zoomProps || {}\n const isZoomDisabled = legacyZoomType === 'no-zoom' || zoomMode === 'disabled'\n\n const containerClass = `${productImagesContainerClass} ${handles.content} w-100`\n\n if (displayMode === DISPLAY_MODE.LIST) {\n return (\n <div className={containerClass}>\n {images.map(({ url, alt, imageLabel }, index) => (\n <ProductImage\n key={index}\n src={url}\n alt={alt}\n imageLabel={imageLabel}\n maxHeight={maxHeight}\n zoomFactor={zoomFactor}\n aspectRatio={aspectRatio}\n ModalZoomElement={ModalZoomElement}\n zoomMode={isZoomDisabled ? 'disabled' : zoomMode}\n />\n ))}\n </div>\n )\n }\n\n if (displayMode === DISPLAY_MODE.FIRST_IMAGE && images?.length) {\n const { url, alt, imageLabel } = images?.[0] ?? {}\n\n return (\n <div className={containerClass}>\n <ProductImage\n src={url}\n alt={alt}\n imageLabel={imageLabel}\n maxHeight={maxHeight}\n zoomFactor={zoomFactor}\n aspectRatio={aspectRatio}\n ModalZoomElement={ModalZoomElement}\n zoomMode={isZoomDisabled ? 'disabled' : zoomMode}\n />\n </div>\n )\n }\n\n return (\n <div className={containerClass}>\n <Carousel\n slides={slides}\n placeholder={placeholder}\n position={position}\n zoomMode={zoomMode}\n maxHeight={maxHeight}\n zoomFactor={zoomFactor}\n aspectRatio={aspectRatio}\n ModalZoomElement={ModalZoomElement}\n thumbnailMaxHeight={thumbnailMaxHeight}\n showPaginationDots={showPaginationDots}\n thumbnailAspectRatio={thumbnailAspectRatio}\n showNavigationArrows={showNavigationArrows}\n thumbnailsOrientation={thumbnailsOrientation}\n displayThumbnailsArrows={displayThumbnailsArrows}\n thumbnailVisibility={thumbnailVisibility}\n // Deprecated\n zoomProps={zoomProps}\n />\n </div>\n )\n}\n\nProductImages.propTypes = {\n /** The position of the thumbs */\n position: PropTypes.oneOf([\n THUMBS_POSITION_HORIZONTAL.LEFT,\n THUMBS_POSITION_HORIZONTAL.RIGHT,\n ]),\n ModalZoomElement: PropTypes.any,\n thumbnailsOrientation: PropTypes.oneOf([\n THUMBS_ORIENTATION.VERTICAL,\n THUMBS_ORIENTATION.HORIZONTAL,\n ]),\n /** This is a necessary prop if you're using SKUSelector to display color images\n * (like a image with only green to represent an SKU of something green) and you\n * want to not display this image in the ProductImages component, to do this you\n * just have to upload the image in the catalog with the value of this prop inside the imageText property */\n hiddenImages: PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.arrayOf(PropTypes.string),\n ]),\n placeholder: PropTypes.string,\n /** Array of images to be passed for the Thumbnail Slider component as a props */\n images: PropTypes.arrayOf(\n PropTypes.shape({\n /** URL of the image */\n imageUrls: PropTypes.arrayOf(PropTypes.string.isRequired),\n /** Size thresholds used to choose each image */\n thresholds: PropTypes.arrayOf(PropTypes.number),\n /** URL of the image thumbnail */\n thumbnailUrl: PropTypes.string,\n /** Text that describes the image */\n imageText: PropTypes.string,\n })\n ),\n videos: PropTypes.arrayOf(\n PropTypes.shape({\n videoUrl: PropTypes.string,\n })\n ),\n zoomProps: PropTypes.shape({\n zoomType: PropTypes.string,\n }),\n displayThumbnailsArrows: PropTypes.bool,\n aspectRatio: PropTypes.string,\n maxHeight: PropTypes.number,\n thumbnailAspectRatio: PropTypes.string,\n thumbnailMaxHeight: PropTypes.number,\n showNavigationArrows: PropTypes.bool,\n showPaginationDots: PropTypes.bool,\n showImageLabel: PropTypes.bool,\n thumbnailVisibility: PropTypes.oneOf([\n THUMBS_VISIBILITY.VISIBLE,\n THUMBS_VISIBILITY.HIDDEN,\n ]),\n contentOrder: PropTypes.oneOf(['images-first', 'videos-first']),\n zoomMode: PropTypes.oneOf([\n 'disabled',\n 'open-modal',\n 'in-place-click',\n 'in-place-hover',\n ]),\n zoomFactor: PropTypes.number,\n contentType: PropTypes.oneOf(['all', 'images', 'videos']),\n displayMode: PropTypes.oneOf([\n DISPLAY_MODE.CAROUSEL,\n DISPLAY_MODE.LIST,\n DISPLAY_MODE.FIRST_IMAGE,\n ]),\n}\n\nProductImages.defaultProps = {\n images: [],\n position: THUMBS_POSITION_HORIZONTAL.LEFT,\n zoomProps: { zoomType: 'in-page' },\n thumbnailsOrientation: THUMBS_ORIENTATION.VERTICAL,\n displayThumbnailsArrows: false,\n thumbnailVisibility: THUMBS_VISIBILITY.VISIBLE,\n hiddenImages: DEFAULT_EXCLUDE_IMAGE_WITH,\n displayMode: DISPLAY_MODE.CAROUSEL,\n}\n\nexport default ProductImages\n\n```"
}
] |
code_store-components_b16fa176
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Logo/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.sizeDesktop {\n max-width: 150px;\n max-height: 75px;\n min-width: 120px;\n}\n\n.sizeMobile {\n max-width: 90px;\n max-height: 40px;\n min-width: 72px;\n}\n\n```"
}
] |
code_store-components_aac6db93
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Logo/LogoPlaceholder.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { memo } from 'react'\n\ninterface Props {\n width?: string | number\n height?: string | number\n title: string\n}\n\nfunction LogoPlaceholder({ width, height, title }: Props) {\n return (\n <svg\n width={width}\n height={height}\n viewBox=\"0 0 142 80\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <title>{title}</title>\n <rect width=\"142\" height=\"80\" fill=\"#F2F4F5\" stroke=\"#E3E4E6\" />\n <path\n d=\"M84.8156 47.5402L77.8157 33.9407C77.5479 33.4222 77.0282 33.0703 76.4349 33.0108C75.8434 32.9445 75.2572 33.1876 74.8844 33.6381L68.8854 40.9206L64.9707 38.386C64.5717 38.1293 64.08 38.0392 63.6162 38.1412C63.149 38.2432 62.7447 38.5271 62.4997 38.9249L57.2497 47.4246C56.9242 47.9499 56.9172 48.6026 57.227 49.1381C57.5367 49.6719 58.1195 50 58.7495 50H83.2494C83.8567 50 84.4184 49.694 84.7386 49.1925C85.0589 48.691 85.0851 48.0655 84.8156 47.5402Z\"\n fill=\"#CACBCC\"\n />\n <path\n d=\"M67.5 33C69.433 33 71 31.433 71 29.5C71 27.567 69.433 26 67.5 26C65.567 26 64 27.567 64 29.5C64 31.433 65.567 33 67.5 33Z\"\n fill=\"#CACBCC\"\n />\n <defs>\n <clipPath id=\"clip0\">\n <rect width=\"127\" height=\"65\" fill=\"white\" />\n </clipPath>\n </defs>\n </svg>\n )\n}\n\nexport default memo(LogoPlaceholder)\n\n```"
}
] |
code_store-components_6247fdb7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/GradientCollapse/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* GradientCollapse CSS Modules\n*/\n\n.fadeBottom {\n background-image: linear-gradient(transparent, white);\n}\n\n.pointerEventsNone {\n pointer-events: none;\n}\n\n.pointerEventsAuto {\n pointer-events: auto;\n}\n```"
}
] |
code_store-components_b298f530
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/GradientCollapse/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useState, useRef, useLayoutEffect } from 'react'\nimport PropTypes from 'prop-types'\nimport { Transition } from 'react-transition-group'\nimport debounce from 'debounce'\nimport { FormattedMessage } from 'react-intl'\nimport classNames from 'classnames'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport styles from './styles.css'\n\nconst CSS_HANDLES = ['container', 'content', 'showMoreButton']\n\nconst transitionStyle = transitionTime => ({\n transition: `${transitionTime}ms ease-in-out`,\n})\n\nconst fadeBottomClasses = state =>\n classNames(styles.fadeBottom, { 'o-0': state === 'entered' }, 'w-100 h-50')\n\nconst pointerEventsAutoClasses = state =>\n classNames(\n styles.pointerEventsAuto,\n {\n 'bg-transparent': state === 'entered',\n 'bg-base': state !== 'entered',\n },\n 'tc w-100'\n )\n\n/**\n * @deprecated This component is deprecated.\n */\nfunction GradientCollapse(props) {\n const {\n children,\n collapseHeight,\n onCollapsedChange,\n collapsed: collapsedProp,\n } = props\n\n const { handles } = useCssHandles(CSS_HANDLES)\n const [collapsed, setCollapsed] = useState(collapsedProp)\n const [prevCollapsedProp, setPrevCollapsedProp] = useState(collapsedProp)\n const [maxHeight, setMaxHeight] = useState('auto')\n const [collapseVisible, setCollapseVisible] = useState(true)\n const wrapper = useRef()\n\n if (prevCollapsedProp !== collapsedProp) {\n setCollapsed(collapsedProp)\n setPrevCollapsedProp(collapsedProp)\n }\n\n const calcMaxHeight = () => {\n const wrapperEl = wrapper.current\n\n // check if the content is smaller than the passed\n // height to collapse\n if (wrapperEl.scrollHeight > collapseHeight) {\n setMaxHeight(wrapperEl.scrollHeight + 60)\n setCollapseVisible(true)\n } else {\n setCollapseVisible(false)\n setMaxHeight('auto')\n }\n }\n\n const handleCollapsedChange = (e, newValue) => {\n setCollapsed(newValue)\n setPrevCollapsedProp(collapsedProp)\n\n if (onCollapsedChange) {\n onCollapsedChange(e, newValue)\n }\n }\n\n const debouncedCalcMaxHeight = debounce(calcMaxHeight, 500)\n\n useLayoutEffect(() => {\n window.addEventListener('resize', debouncedCalcMaxHeight)\n calcMaxHeight()\n\n return () => {\n window.removeEventListener('resize', debouncedCalcMaxHeight)\n }\n })\n\n const height = collapseVisible && collapsed ? collapseHeight : maxHeight\n const transitionTime = 600\n const fadeOutTime = 400\n\n const pointerEventsNoneClasses = classNames(\n styles.pointerEventsNone,\n { flex: collapseVisible, dn: !collapseVisible },\n 'absolute bottom-0 w-100 h-100 flex-column justify-end'\n )\n\n return (\n <Transition timeout={transitionTime} in={!collapsed}>\n {state => (\n <div\n style={{\n ...transitionStyle(transitionTime),\n height,\n overflow: 'hidden',\n display: 'block',\n }}\n onTransitionEnd={calcMaxHeight}\n className={`${handles.container} relative`}\n >\n <div ref={wrapper} className={`${handles.content} h-auto`}>\n {children}\n </div>\n <div className={pointerEventsNoneClasses}>\n <div\n style={transitionStyle(fadeOutTime)}\n className={fadeBottomClasses(state)}\n />\n <div className={pointerEventsAutoClasses(state)}>\n <button\n onClick={e => handleCollapsedChange(e, !collapsed)}\n className={`${handles.showMoreButton} c-action-primary t-action pointer ma5 bn outline-0`}\n >\n {state === 'entered' || (collapsed && state !== 'exited') ? (\n <FormattedMessage id=\"store/product-description.collapse.showLess\" />\n ) : (\n <FormattedMessage id=\"store/product-description.collapse.showMore\" />\n )}\n </button>\n </div>\n </div>\n </div>\n )}\n </Transition>\n )\n}\n\nGradientCollapse.propTypes = {\n /** Maximum height collapsed */\n collapseHeight: PropTypes.number.isRequired,\n collapsed: PropTypes.bool,\n children: PropTypes.node,\n onCollapsedChange: PropTypes.func,\n}\n\nGradientCollapse.defaultProps = {\n collapsed: true,\n}\n\nexport default GradientCollapse\n\n```"
}
] |
code_store-components_02663328
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/GradientCollapse/index.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FC } from 'react'\n\nconst GradientCollapse: FC<any>\n\nexport default GradientCollapse\n\n```"
}
] |
code_store-components_f56e6111
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* ProductPrice CSS Modules\n*/\n.priceContainer {}\n.listPrice {}\n.listPriceLabel {}\n.listPriceValue {}\n\n.sellingPriceContainer {}\n.sellingPrice {} /* deprecated */\n.sellingPriceLabel {}\n.sellingPriceValue {}\n.sellingPriceValue--range {}\n\n.savingPrice {}\n.savingPriceValue {}\n\n.installmentsPrice {}\n.interestRatePrice {}\n\n.priceLoaderContainer {}\n.listPriceLoader {}\n.sellingPriceLabelLoader {}\n.sellingPriceLoader {}\n.installmentsPriceLoader {}\n.savingsPriceLoader {}\n```"
}
] |
code_store-components_824ba411
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport { ProductContext } from 'vtex.product-context'\nimport { path, isEmpty, has } from 'ramda'\n\nimport { useCommercialOffer } from '../../utils/useCommercialOffer'\nimport ProductPrice from './index'\n\nconst styles = {\n 'vtex-price-list__container--loader': {\n x: 0,\n width: '7.219em',\n height: '0.56em',\n },\n 'vtex-price-selling__label--loader': {\n x: 0,\n y: '2em',\n width: '2.85em',\n height: '1.08em',\n },\n 'vtex-price-selling--loader': {\n x: '3.25em',\n y: '0.86em',\n width: '14.572em',\n height: '2.176em',\n },\n 'vtex-price-installments--loader': {\n x: 0,\n y: '3.75em',\n width: '12em',\n height: '0.825em',\n },\n 'vtex-price-savings--loader': {\n x: 0,\n y: '5em',\n width: '10em',\n height: '0.686em',\n },\n}\n\nconst isAvailable = commercialOffer =>\n Number.isNaN(+path(['AvailableQuantity'], commercialOffer)) ||\n path(['AvailableQuantity'], commercialOffer) > 0\n\nconst ProductPriceWrapper = ({\n labelSellingPrice,\n showListPrice,\n showInstallments,\n showLabels,\n showSavings,\n ...props\n}) => {\n const valuesFromContext = useContext(ProductContext)\n\n const commercialOffer = useCommercialOffer(valuesFromContext)\n\n const {\n className,\n listPriceContainerClass,\n listPriceLabelClass,\n listPriceClass,\n sellingPriceContainerClass,\n sellingPriceLabelClass,\n sellingPriceClass,\n savingsContainerClass,\n savingsClass,\n interestRateClass,\n installmentContainerClass,\n installmentClass,\n loaderClass,\n listPrice,\n sellingPrice,\n installments,\n } = props\n\n const productPriceProps = () => {\n if (\n !valuesFromContext ||\n isEmpty(valuesFromContext) ||\n (!has('query', props) && !has('params', props))\n ) {\n return {\n ...props,\n labelSellingPrice,\n showListPrice,\n showInstallments,\n showLabels,\n showSavings,\n showProductPrice: true,\n }\n }\n\n return {\n ...props,\n styles: props.styles || styles,\n className: className || '',\n listPriceContainerClass:\n listPriceContainerClass || 't-small-s t-small-ns c-muted-2 mb2',\n sellingPriceLabelClass:\n sellingPriceLabelClass || 't-heading-6-s t-heading-5-ns dib',\n listPriceLabelClass: listPriceLabelClass || 'dib strike',\n listPriceClass: listPriceClass || 'ph2 dib strike',\n sellingPriceContainerClass:\n sellingPriceContainerClass || 'pv1 b c-on-base',\n sellingPriceClass: sellingPriceClass || 't-heading-2-s dib ph2',\n installmentContainerClass:\n installmentContainerClass || 't-mini-s t-small-ns c-on-base',\n installmentClass: installmentClass || 't-body',\n interestRateClass: interestRateClass || 'dib ph2',\n savingsContainerClass: savingsContainerClass || 'c-success mt3',\n savingsClass: savingsClass || 'dib t-small',\n loaderClass: loaderClass || 'h4-s mw6-s pt2-s',\n listPrice: listPrice || path(['ListPrice'], commercialOffer),\n sellingPrice: sellingPrice || path(['Price'], commercialOffer),\n installments: installments || path(['Installments'], commercialOffer),\n labelSellingPrice,\n showLabels,\n showInstallments,\n showListPrice,\n showSavings,\n showProductPrice: isAvailable(commercialOffer),\n }\n }\n\n const { showProductPrice, ...priceProps } = productPriceProps()\n\n if (!showProductPrice) {\n return null\n }\n\n return <ProductPrice {...priceProps} />\n}\n\nProductPriceWrapper.schema = {\n title: 'admin/editor.productPrice.title',\n description: 'admin/editor.productPrice.description',\n type: 'object',\n properties: {\n labelSellingPrice: {\n type: 'string',\n title: 'admin/editor.productPrice.labelSellingPrice',\n default: ProductPrice.defaultProps.labelSellingPrice,\n isLayout: false,\n },\n labelListPrice: {\n type: 'string',\n title: 'admin/editor.productPrice.labelListPrice',\n default: ProductPrice.defaultProps.labelListPrice,\n isLayout: false,\n },\n showSellingPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSellingPriceRange',\n default: ProductPrice.defaultProps.showSellingPriceRange,\n isLayout: true,\n },\n showListPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPriceRange',\n default: ProductPrice.defaultProps.showListPriceRange,\n isLayout: true,\n },\n showListPrice: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPrice',\n default: ProductPrice.defaultProps.showListPrice,\n isLayout: true,\n },\n showLabels: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showLabels',\n default: ProductPrice.defaultProps.showLabels,\n isLayout: true,\n },\n showInstallments: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showInstallments',\n default: ProductPrice.defaultProps.showInstallments,\n isLayout: true,\n },\n showSavings: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSavings',\n default: ProductPrice.defaultProps.showSavings,\n isLayout: true,\n },\n },\n}\n\nexport default ProductPriceWrapper\n\n```"
}
] |
code_store-components_a3510fea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport classNames from 'classnames'\nimport { isNil, head, last, sort, equals } from 'ramda'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport { IOMessage } from 'vtex.native-types'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { formatCurrency } from 'vtex.format-currency'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport ProductPriceLoader from './Loader'\nimport PricePropTypes from './propTypes'\nimport Installments from './Installments'\nimport Price from './Price'\nimport productPrice from './styles.css'\n\nconst CSS_HANDLES = [\n 'price_className',\n 'price_loader',\n 'price_listPriceContainer',\n 'price_listPriceLabel',\n 'price_listPrice',\n 'price_listPriceRange',\n 'price_sellingPriceRange',\n 'price_sellingPriceContainer',\n 'price_sellingPriceLabel',\n 'price_sellingPrice',\n 'price_savingsContainer',\n 'price_savings',\n 'price_savings_value',\n 'price_installment',\n 'price_interestRate',\n 'price_installmentContainer',\n]\n\nconst isValidPriceRange = priceRange => {\n const [lowPrice, highPrice] = priceRange\n\n return priceRange.length === 2 && lowPrice !== highPrice\n}\n\nconst getPriceRange = prices => {\n const sortedPrices = sort((a, b) => a - b, prices)\n\n return [head(sortedPrices), last(sortedPrices)]\n}\n\nconst canShowListPrice = props => {\n const {\n sellingPriceList,\n sellingPrice,\n listPrice,\n listPriceList,\n showListPrice,\n showListPriceRange,\n showSellingPriceRange,\n } = props\n\n if (!showListPrice) {\n return false\n }\n\n const sellingPriceRange =\n (sellingPriceList && getPriceRange(sellingPriceList)) || []\n\n const listPriceRange = (listPriceList && getPriceRange(listPriceList)) || []\n\n const showingSellingPriceRange =\n showSellingPriceRange && isValidPriceRange(sellingPriceRange)\n\n const showingListPriceRange =\n showListPriceRange && isValidPriceRange(listPriceRange)\n\n const sellingPriceToShow = showingSellingPriceRange\n ? sellingPriceRange\n : sellingPrice\n\n const listPriceToShow = showingListPriceRange ? listPriceRange : listPrice\n\n return !equals(listPriceToShow, sellingPriceToShow)\n}\n\n/**\n * The Price component. Shows the prices information of the Product Summary.\n */\nconst ProductPrice = props => {\n const {\n sellingPriceList,\n sellingPrice,\n listPrice,\n listPriceList,\n showListPrice,\n showSellingPriceRange,\n showListPriceRange,\n showInstallments,\n showLabels,\n showSavings,\n labelSellingPrice,\n labelListPrice,\n className,\n loaderClass,\n listPriceContainerClass,\n listPriceLabelClass,\n listPriceClass,\n listPriceRangeClass,\n sellingPriceRangeClass,\n sellingPriceContainerClass,\n sellingPriceLabelClass,\n sellingPriceClass,\n savingsContainerClass,\n savingsClass,\n installments,\n installmentClass,\n interestRateClass,\n installmentContainerClass,\n styles,\n intl,\n } = props\n\n const { culture } = useRuntime()\n\n const { handles } = useCssHandles(CSS_HANDLES)\n\n if ((showListPrice && isNil(listPrice)) || isNil(sellingPrice)) {\n return (\n <ProductPriceLoader\n loaderClass={`${loaderClass} ${handles.price_loader}`}\n {...styles}\n />\n )\n }\n\n const mayShowListPrice = canShowListPrice(props)\n\n const sellingPriceRange = sellingPriceList && getPriceRange(sellingPriceList)\n const listPriceRange = listPriceList && getPriceRange(listPriceList)\n\n return (\n <div\n className={classNames(\n productPrice.priceContainer,\n className,\n handles.price_className\n )}\n >\n {mayShowListPrice && (\n <div\n className={classNames(\n productPrice.listPrice,\n listPriceContainerClass,\n handles.price_listPriceContainer\n )}\n >\n {showLabels && (\n <div\n className={classNames(\n productPrice.listPriceLabel,\n listPriceLabelClass,\n handles.price_listPriceLabel,\n 'dib ph2 t-small-ns t-mini'\n )}\n >\n <IOMessage id={labelListPrice} />\n </div>\n )}\n <Price\n showPriceRange={showListPriceRange}\n priceRange={listPriceRange}\n price={listPrice}\n rangeContainerClasses={classNames(\n productPrice.listPriceValue,\n listPriceRangeClass,\n handles.price_listPriceRange\n )}\n singleContainerClasses={classNames(\n productPrice.listPriceValue,\n listPriceClass,\n handles.price_listPrice\n )}\n />\n </div>\n )}\n <div\n className={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceContainer,\n sellingPriceContainerClass,\n handles.price_sellingPriceContainer\n )}\n >\n {showLabels && mayShowListPrice && (\n <div\n className={classNames(\n productPrice.sellingPriceLabel,\n sellingPriceLabelClass,\n handles.price_sellingPriceLabel\n )}\n >\n <IOMessage id={labelSellingPrice} />\n </div>\n )}\n <Price\n showPriceRange={showSellingPriceRange}\n priceRange={sellingPriceRange}\n price={sellingPrice}\n rangeContainerClasses={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceValue,\n productPrice['sellingPriceValue--range'],\n sellingPriceRangeClass,\n handles.price_sellingPriceRange\n )}\n singleContainerClasses={classNames(\n productPrice.sellingPrice,\n productPrice.sellingPriceValue,\n sellingPriceClass,\n handles.price_sellingPrice\n )}\n />\n </div>\n {showInstallments && (\n <Installments\n installments={installments}\n showLabels={showLabels}\n className={`${installmentContainerClass} ${handles.price_installmentContainer}`}\n interestRateClass={`${interestRateClass} ${handles.price_interestRate}`}\n installmentClass={`${installmentClass} ${handles.price_installment}`}\n />\n )}\n {mayShowListPrice && showSavings && listPrice - sellingPrice > 0 && (\n <div\n className={classNames(\n productPrice.savingPrice,\n savingsContainerClass,\n handles.price_savingsContainer\n )}\n >\n <div\n className={classNames(\n productPrice.savingPriceValue,\n savingsClass,\n handles.price_savings\n )}\n >\n <FormattedMessage\n id=\"store/pricing.savings\"\n values={{\n savings: (\n <span className={handles.price_savings_value}>\n {formatCurrency({\n intl,\n culture,\n value: listPrice - sellingPrice,\n })}\n </span>\n ),\n }}\n />\n </div>\n </div>\n )}\n </div>\n )\n}\n\nProductPrice.propTypes = PricePropTypes\n\nconst PriceWithIntl = injectIntl(ProductPrice)\n\nPriceWithIntl.defaultProps = {\n showSellingPriceRange: false,\n showListPriceRange: false,\n showListPrice: true,\n showLabels: true,\n showInstallments: false,\n showSavings: false,\n labelSellingPrice: null,\n labelListPrice: null,\n}\n\nPriceWithIntl.schema = {\n title: 'admin/editor.productPrice.title',\n description: 'admin/editor.productPrice.description',\n type: 'object',\n properties: {\n showSellingPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSellingPriceRange',\n default: PriceWithIntl.defaultProps.showSellingPriceRange,\n isLayout: true,\n },\n showListPriceRange: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPriceRange',\n default: PriceWithIntl.defaultProps.showListPriceRange,\n isLayout: true,\n },\n showListPrice: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showListPrice',\n default: PriceWithIntl.defaultProps.showListPrice,\n isLayout: true,\n },\n showLabels: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showLabels',\n default: PriceWithIntl.defaultProps.showLabels,\n isLayout: true,\n },\n showInstallments: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showInstallments',\n default: PriceWithIntl.defaultProps.showInstallments,\n isLayout: true,\n },\n showSavings: {\n type: 'boolean',\n title: 'admin/editor.productPrice.showSavings',\n default: PriceWithIntl.defaultProps.showSavings,\n isLayout: true,\n },\n },\n}\n\nexport default PriceWithIntl\n\n```"
}
] |
code_store-components_cb49d950
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/Installments.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { injectIntl, FormattedMessage } from 'react-intl'\nimport classNames from 'classnames'\nimport { isEmpty } from 'ramda'\nimport PropTypes from 'prop-types'\nimport { formatCurrency } from 'vtex.format-currency'\n\nimport PricePropTypes from './propTypes'\nimport productPrice from './styles.css'\n\n/** Installments component */\nconst Installments = ({\n showLabels,\n installments = [],\n className,\n installmentClass,\n interestRateClass,\n intl,\n}) => {\n const { culture } = useRuntime()\n\n if (\n !installments ||\n isEmpty(\n installments.filter(\n ({ NumberOfInstallments }) => NumberOfInstallments > 1\n )\n )\n ) {\n return null\n }\n\n const noInterestRateInstallments = installments.filter(\n installment =>\n !installment.InterestRate && installment.NumberOfInstallments > 1\n )\n\n /*\n * - The selected installment will be the one with the highest `NumberOfInstallments`;\n * - If there is no 'interest-free' installments, the normal installments will be analyzed.\n */\n const installment = (\n isEmpty(noInterestRateInstallments)\n ? installments\n : noInterestRateInstallments\n ).reduce((previous, current) =>\n previous.NumberOfInstallments > current.NumberOfInstallments\n ? previous\n : current\n )\n\n const formattedInstallmentPrice = formatCurrency({\n intl,\n culture,\n value: installment.Value,\n })\n\n const [installmentsElement, installmentPriceElement, timesElement] = [\n installment.NumberOfInstallments,\n formattedInstallmentPrice,\n <Fragment key=\"x\">x</Fragment>,\n ].map((element, index) => (\n <span className={installmentClass} key={index}>\n {element}\n </span>\n ))\n\n return (\n <div className={classNames(productPrice.installmentsPrice, className)}>\n {showLabels ? (\n <FormattedMessage\n id=\"store/pricing.installment-display\"\n values={{\n installments: installmentsElement,\n installmentPrice: installmentPriceElement,\n times: timesElement,\n }}\n />\n ) : (\n <Fragment>\n {installmentsElement}\n {timesElement} {installmentPriceElement}\n </Fragment>\n )}\n {!installment.InterestRate && (\n <div\n className={classNames(\n productPrice.interestRatePrice,\n interestRateClass\n )}\n >\n <FormattedMessage id=\"store/pricing.interest-free\" />\n </div>\n )}\n </div>\n )\n}\n\nInstallments.propTypes = {\n /** Classes to be applied to the root element */\n className: PropTypes.string,\n /** Classes to be applied to installment value element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Product installments to be displayed */\n installments: PricePropTypes.installments,\n /** Pages editor config to display labels */\n showLabels: PropTypes.bool.isRequired,\n intl: PropTypes.object.isRequired,\n}\n\nexport default injectIntl(Installments)\n\n```"
}
] |
code_store-components_a15baa37
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/propTypes.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nexport default {\n /** Product list of selling prices */\n sellingPriceList: PropTypes.arrayOf(PropTypes.number),\n /** Product list of list prices */\n listPriceList: PropTypes.arrayOf(PropTypes.number),\n /** Product selling price */\n sellingPrice: PropTypes.number,\n /** Product list price */\n listPrice: PropTypes.number,\n /** Set visibility of selling prices range */\n showSellingPriceRange: PropTypes.bool.isRequired,\n /** Set visibility of list prices range */\n showListPriceRange: PropTypes.bool.isRequired,\n /** Set visibility of list price */\n showListPrice: PropTypes.bool.isRequired,\n /** Set visibility of labels */\n showLabels: PropTypes.bool.isRequired,\n /** Set visibility of installments */\n showInstallments: PropTypes.bool.isRequired,\n /** Set visibility of savings */\n showSavings: PropTypes.bool,\n /** Text to the selling price's label */\n labelSellingPrice: PropTypes.string,\n /** Text to the list price's label */\n labelListPrice: PropTypes.string,\n /** Available installments */\n installments: PropTypes.arrayOf(\n PropTypes.shape({\n /** Installment value */\n Value: PropTypes.number.isRequired,\n /** Interest rate (zero if interest-free) */\n InterestRate: PropTypes.number.isRequired,\n /** Calculated total value */\n TotalValuePlusInterestRate: PropTypes.number,\n /** Number of installments */\n NumberOfInstallments: PropTypes.number.isRequired,\n /** Installment offer name */\n Name: PropTypes.string,\n })\n ),\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to loader root element */\n loaderClass: PropTypes.string,\n /** Classes to be applied to container of list price */\n listPriceContainerClass: PropTypes.string,\n /** Classes to be applied to label of price */\n listPriceLabelClass: PropTypes.string,\n /** Classes to be applied to price value */\n listPriceClass: PropTypes.string,\n /** Classes to be applied to range selling prices value */\n sellingPriceRangeClass: PropTypes.string,\n /** Classes to be applied to range list prices value */\n listPriceRangeClass: PropTypes.string,\n /** Classes to be applied to selling price container */\n sellingPriceContainerClass: PropTypes.string,\n /** Classes to be applied to selling price label */\n sellingPriceLabelClass: PropTypes.string,\n /** Classes to be applied to selling price value */\n sellingPriceClass: PropTypes.string,\n /** Classes to be applied to savings container */\n savingsContainerClass: PropTypes.string,\n /** Classes to be applied to savings */\n savingsClass: PropTypes.string,\n /** Classes to be applied to installment element */\n installmentClass: PropTypes.string,\n /** Classes to be applied to installment container */\n installmentContainerClass: PropTypes.string,\n /** Classes to be applied to interest rate element */\n interestRateClass: PropTypes.string,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** intl property to format data */\n intl: PropTypes.object.isRequired,\n}\n\n```"
}
] |
code_store-components_e73f85e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/Price.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { injectIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { FormattedCurrency, formatCurrency } from 'vtex.format-currency'\n\nconst isValidPriceRange = priceRange => {\n const [lowPrice, highPrice] = priceRange\n\n return priceRange.length === 2 && lowPrice !== highPrice\n}\n\nconst formatPriceRange = (intl, culture, rawPriceRange) => {\n const priceRangeFormatted = (rawPriceRange || []).map(value =>\n formatCurrency({ intl, culture, value })\n )\n\n return priceRangeFormatted.join(' - ')\n}\n\nconst Price = ({\n showPriceRange,\n priceRange,\n price,\n rangeContainerClasses,\n singleContainerClasses,\n intl,\n}) => {\n const { culture } = useRuntime()\n\n const mustShowPriceRange =\n showPriceRange && priceRange && isValidPriceRange(priceRange)\n\n if (mustShowPriceRange) {\n return (\n <span className={rangeContainerClasses}>\n {formatPriceRange(intl, culture, priceRange)}\n </span>\n )\n }\n\n return (\n <span className={singleContainerClasses}>\n <FormattedCurrency value={price} />\n </span>\n )\n}\n\nexport default injectIntl(Price)\n\n```"
}
] |
code_store-components_8aaeab89
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductPrice/Loader.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport classNames from 'classnames'\nimport ContentLoader from 'react-content-loader'\n\nimport productPrice from './styles.css'\n\nconst ProductPriceLoader = (loaderProps = {}) => {\n const { loaderClass, ...props } = loaderProps\n\n return (\n <div\n className={classNames(\n productPrice.priceContainer,\n productPrice.priceLoaderContainer,\n loaderClass\n )}\n >\n <ContentLoader\n style={{\n width: '100%',\n height: '100%',\n }}\n width={300}\n height={70}\n preserveAspectRatio=\"xMinYMin meet\"\n {...props}\n >\n <rect\n height=\"0.75em\"\n width=\"50%\"\n x=\"25%\"\n {...loaderProps[productPrice.listPriceLoader]}\n />\n <rect {...loaderProps[productPrice.sellingPriceLabelLoader]} />\n <rect\n height=\"1em\"\n width=\"70%\"\n x=\"15%\"\n y=\"1.25em\"\n {...loaderProps[productPrice.sellingPriceLoader]}\n />\n <rect\n height=\"0.75em\"\n width=\"80%\"\n x=\"10%\"\n y=\"2.75em\"\n {...loaderProps[productPrice.installmentsPriceLoader]}\n />\n <rect {...loaderProps[productPrice.savingsPriceLoader]} />\n </ContentLoader>\n </div>\n )\n}\n\nexport default ProductPriceLoader\n\n```"
}
] |
code_store-components_839a1586
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/index.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n useState,\n useEffect,\n useMemo,\n memo,\n useCallback,\n FC,\n} from 'react'\nimport { filter, head, isEmpty, compose, keys, length } from 'ramda'\nimport { useRuntime } from 'vtex.render-runtime'\nimport {\n useResponsiveValue,\n ResponsiveValuesTypes,\n} from 'vtex.responsive-values'\nimport { useProduct, useProductDispatch } from 'vtex.product-context'\n\nimport SKUSelector, {\n ShowValueForVariation,\n ShowVariationsLabels,\n} from './components/SKUSelector'\nimport {\n parseSku,\n isColor,\n uniqueOptionToSelect,\n findItemWithSelectedVariations,\n} from './utils'\nimport {\n Image,\n ImageMap,\n Variations,\n SelectedVariations,\n SelectorProductItem,\n InitialSelectionType,\n DisplayMode,\n} from './types'\nimport useEffectSkipMount from './components/hooks/useEffectSkipMount'\n\nconst keyCount = compose(length, keys)\nconst filterSelected = filter(Boolean)\n\nconst areAllVariationsSelected = (\n selected: SelectedVariations,\n numberOfVariations: number\n) => {\n const selectedCount = keyCount(filterSelected(selected))\n\n return selectedCount === numberOfVariations\n}\n\nconst buildEmptySelectedVariation = (variations: Variations) => {\n const variationNames = Object.keys(variations)\n const result = {} as Record<string, null>\n\n for (const variationName of variationNames) {\n result[variationName] = null\n }\n\n return result\n}\n\n/** receives an item and the variations object, returns the selected variations for that item */\nconst selectedVariationFromItem = (\n item: SelectorProductItem,\n variations: Variations\n) => {\n const variationNames = Object.keys(variations)\n const result = {} as Record<string, string>\n\n for (const variationName of variationNames) {\n result[variationName] = item.variationValues[variationName]\n }\n\n return result\n}\n\nfunction filterColorImages(\n items: SelectorProductItem[],\n imageRegexText: string\n) {\n const imageRegex = new RegExp(imageRegexText, 'i')\n\n return items.map(item => {\n if (!item.images) {\n return item\n }\n\n const hasVariationImage = item.images.some(\n image => image.imageLabel && imageRegex.test(image.imageLabel)\n )\n\n return {\n ...item,\n // if it doesn't have a variation image, it wont remove images without a label\n images: hasVariationImage\n ? item.images.filter(image => {\n if (!image.imageLabel) {\n return false\n }\n\n return imageRegex.test(image.imageLabel)\n })\n : item.images,\n }\n })\n}\n\nconst useImagesMap = (\n items: SelectorProductItem[],\n variations: Variations,\n thumbnailImage?: string\n) => {\n return useMemo(() => {\n let filteredItems = items\n\n if (thumbnailImage) {\n filteredItems = filterColorImages(items, thumbnailImage)\n }\n\n const variationNames = Object.keys(variations)\n\n const result: ImageMap = {}\n\n for (const variationName of variationNames) {\n // Today, only \"Color\" variation should show image, need to find a more resilient way to tell this, waiting for backend\n if (!isColor(variations[variationName].originalName)) {\n continue\n }\n\n const imageMap = {} as Record<string, Image | undefined>\n const variationValues = variations[variationName].values\n\n for (const variationValue of variationValues) {\n const item = filteredItems.find(\n sku => sku.variationValues[variationName] === variationValue.name\n )\n\n imageMap[variationValue.name] = item && head(item.images)\n }\n\n result[variationName] = imageMap\n }\n\n return result\n }, [items, variations, thumbnailImage])\n}\n\nconst useAllSelectedEvent = (\n selectedVariations: SelectedVariations | null,\n variationsCount: number\n) => {\n const dispatch = useProductDispatch()\n\n useEffect(() => {\n if (dispatch && selectedVariations) {\n dispatch({\n type: 'SKU_SELECTOR_SET_VARIATIONS_SELECTED',\n args: {\n allSelected: areAllVariationsSelected(\n selectedVariations,\n variationsCount\n ),\n },\n })\n }\n }, [dispatch, selectedVariations, variationsCount])\n}\n\ninterface Props {\n skuItems: ProductItem[]\n onSKUSelected?: (skuId: string) => void\n seeMoreLabel: string\n maxItems?: number\n variations: Variations\n skuSelected: ProductItem | null\n hideImpossibleCombinations?: boolean\n disableUnavailableSelectOptions?: boolean\n showValueForVariation?: ShowValueForVariation\n imageHeight?: number\n imageWidth?: number\n thumbnailImage?: string\n showVariationsLabels?: ShowVariationsLabels\n variationsSpacing?: number\n showVariationsErrorMessage?: boolean\n initialSelection?: InitialSelectionType\n displayMode?: ResponsiveValuesTypes.ResponsiveValue<DisplayMode>\n sliderDisplayThreshold?: number\n sliderArrowSize?: number\n sliderItemsPerPage?: ResponsiveValuesTypes.ResponsiveValue<number>\n sortVariationsByLabel?: boolean\n}\n\nconst getNewSelectedVariations = (\n query: Record<string, string> | undefined,\n skuSelected: Props['skuSelected'],\n variations: Props['variations'],\n initialSelection?: Props['initialSelection']\n // eslint-disable-next-line max-params\n) => {\n const emptyVariations = buildEmptySelectedVariation(variations)\n\n if (skuSelected == null) {\n return emptyVariations\n }\n\n const hasSkuInQuery = Boolean(query?.skuId)\n const parsedSku = parseSku(skuSelected)\n\n if (hasSkuInQuery || initialSelection === 'complete') {\n return selectedVariationFromItem(parsedSku, variations)\n }\n\n if (initialSelection === 'image') {\n const colorVariationName = parsedSku.variations.find(isColor)\n\n return {\n ...emptyVariations,\n ...(colorVariationName\n ? {\n [colorVariationName]: parsedSku.variationValues[colorVariationName],\n }\n : {}),\n }\n }\n\n return emptyVariations\n}\n\n/**\n * Display a list of SKU items of a product and its specifications.\n */\nconst SKUSelectorContainer: FC<Props> = ({\n skuItems = [],\n onSKUSelected,\n seeMoreLabel,\n maxItems = 10,\n variations,\n skuSelected,\n imageWidth,\n imageHeight,\n thumbnailImage,\n variationsSpacing,\n showVariationsLabels = 'variation',\n displayMode = 'default',\n hideImpossibleCombinations = true,\n disableUnavailableSelectOptions = false,\n showVariationsErrorMessage = true,\n showValueForVariation = 'none',\n initialSelection = 'complete',\n sliderDisplayThreshold = 3,\n sliderArrowSize = 12,\n sortVariationsByLabel = false,\n sliderItemsPerPage = {\n desktop: 3,\n tablet: 2,\n phone: 1,\n },\n}) => {\n const productContext = useProduct()\n const selectedItem = productContext?.selectedItem\n\n const variationsCount = keyCount(variations)\n const { query } = useRuntime()\n const responsiveDisplayMode = useResponsiveValue(displayMode)\n\n const parsedItems = useMemo(() => skuItems.map(parseSku), [skuItems])\n const { setQuery } = useRuntime()\n const redirectToSku = (skuId: string) => {\n setQuery({ skuId }, { replace: true })\n }\n\n const [selectedVariations, setSelectedVariations] =\n useState<SelectedVariations>(() =>\n getNewSelectedVariations(query, skuSelected, variations, initialSelection)\n )\n\n useAllSelectedEvent(selectedVariations, variationsCount)\n\n useEffectSkipMount(() => {\n setSelectedVariations(\n getNewSelectedVariations(query, skuSelected, variations, initialSelection)\n )\n }, [variations, skuSelected])\n\n // This is used to selected an SKU when initialSelection is not 'empty'.\n // Runs only on the first render.\n useEffect(() => {\n if (skuSelected && onSKUSelected) {\n onSKUSelected(skuSelected.itemId)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const imagesMap = useImagesMap(parsedItems, variations, thumbnailImage)\n\n const dispatch = useProductDispatch()\n\n const onSelectItem = useCallback(\n ({\n name: variationName,\n value: variationValue,\n skuId,\n isMainAndImpossible,\n possibleItems,\n }) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const isRemoving = selectedVariations![variationName] === variationValue\n\n const newSelectedVariation = !isMainAndImpossible\n ? {\n ...selectedVariations,\n [variationName]: isRemoving ? null : variationValue,\n }\n : {\n ...buildEmptySelectedVariation(variations),\n [variationName]: variationValue,\n }\n\n // Set here for a better response to user\n setSelectedVariations(newSelectedVariation)\n\n if (selectedItem && selectedItem.itemId !== skuId && !isRemoving) {\n dispatch({\n type: 'SET_LOADING_ITEM',\n args: { loadingItem: true },\n })\n } else if (selectedItem?.itemId === skuId) {\n dispatch({\n type: 'SET_LOADING_ITEM',\n args: { loadingItem: false },\n })\n }\n\n const uniqueOptions = isRemoving\n ? {}\n : uniqueOptionToSelect(\n possibleItems,\n newSelectedVariation,\n isMainAndImpossible\n )\n\n const finalSelected = {\n ...newSelectedVariation,\n ...uniqueOptions,\n }\n\n if (!isEmpty(uniqueOptions)) {\n setSelectedVariations(finalSelected)\n }\n\n const allSelected = areAllVariationsSelected(\n finalSelected,\n variationsCount\n )\n\n let skuIdToRedirect = skuId\n\n if (!skuIdToRedirect || !isEmpty(uniqueOptions)) {\n const newItem = findItemWithSelectedVariations(\n possibleItems,\n finalSelected\n )\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n skuIdToRedirect = newItem!.itemId\n }\n\n // if (un)selecting a color variation, dispatch to the product context\n // so we can show/hide the mainImageLabel if defined\n if (isColor(variationName)) {\n const variationSKU = isRemoving ? null : skuIdToRedirect\n\n dispatch({\n type: 'SELECT_IMAGE_VARIATION',\n args: {\n selectedImageVariationSKU: variationSKU,\n },\n })\n }\n\n // only redirect to a specific sku id if every variation was defined\n if (allSelected === false) {\n skuIdToRedirect = null\n\n dispatch({\n type: 'SET_LOADING_ITEM',\n args: { loadingItem: false },\n })\n }\n\n if (onSKUSelected) {\n onSKUSelected(skuIdToRedirect)\n\n return\n }\n\n // If its just removing, no need to redirect\n if (!isRemoving && (allSelected || isColor(variationName))) {\n redirectToSku(skuIdToRedirect)\n }\n },\n // Adding selectedVariations, variationsCount and onSKUSelected causes an infinite loop\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [selectedVariations, variations, onSKUSelected, skuSelected?.itemId]\n )\n\n return (\n <SKUSelector\n maxItems={maxItems}\n imagesMap={imagesMap}\n skuItems={parsedItems}\n variations={variations}\n imageWidth={imageWidth}\n displayMode={responsiveDisplayMode}\n imageHeight={imageHeight}\n seeMoreLabel={seeMoreLabel}\n onSelectItem={onSelectItem}\n variationsSpacing={variationsSpacing}\n selectedVariations={selectedVariations}\n showVariationsLabels={showVariationsLabels}\n showValueForVariation={showValueForVariation}\n hideImpossibleCombinations={hideImpossibleCombinations}\n disableUnavailableSelectOptions={disableUnavailableSelectOptions}\n showVariationsErrorMessage={showVariationsErrorMessage}\n sliderDisplayThreshold={sliderDisplayThreshold}\n sliderArrowSize={sliderArrowSize}\n sliderItemsPerPage={sliderItemsPerPage}\n sortVariationsByLabel={sortVariationsByLabel}\n />\n )\n}\n\nexport default memo(SKUSelectorContainer)\n\n```"
}
] |
code_store-components_3f81a81c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* SKU Selector CSS Module\n*/\n.skuSelectorContainer {\n}\n.skuSelectorSubcontainer {\n}\n.skuSelectorName {\n}\n.skuSelectorNameContainer {\n}\n.skuSelectorNameSeparator {\n}\n.skuSelectorSelectorImageValue {\n}\n.skuSelectorTextContainer {\n}\n\n.skuSelectorSelectContainer {}\n\n.skuSelectorItem {\n font-size: 90%;\n height: 36px;\n}\n\n.skuSelectorItemImage {\n padding: 0;\n height: 40px;\n width: 40px;\n}\n\n.skuSelectorItem p {\n margin: 0;\n padding-top: 10px;\n}\n\n.skuSelectorBagde {\n font-size: 0.71429rem;\n background-color: #ff4136;\n border-radius: 50%;\n color: #fff;\n height: 18px;\n line-height: 18px;\n right: -5px;\n text-align: center;\n top: -6px;\n width: 18px;\n position: absolute;\n padding: 3px;\n}\n\n.diagonalCross {\n background-image: linear-gradient(\n to top right,\n transparent 44%,\n rgba(0, 0, 0, 0.3) 48%,\n currentColor 48%,\n currentColor 52%,\n transparent 52%\n );\n}\n\n.frameAround {\n bottom: -0.25rem;\n top: -0.25rem;\n left: -0.25rem;\n right: -0.25rem;\n}\n\n.seeMoreButton {\n}\n\n.skuSelectorOptionsList {\n}\n\n```"
}
] |
code_store-components_7e8aa474
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/SKUSelectorCssHandles.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { SKU_SELECTOR_CSS_HANDLES } from './Wrapper'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n SKU_SELECTOR_CSS_HANDLES\n)\n\nexport {\n CssHandlesProvider as SKUSelectorCssHandlesProvider,\n useContextCssHandles as useSKUSelectorCssHandles,\n}\n\n```"
}
] |
code_store-components_82533220
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Wrapper.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, useEffect } from 'react'\nimport { useProduct, useProductDispatch } from 'vtex.product-context'\nimport { pick } from 'ramda'\nimport {\n useResponsiveValues,\n ResponsiveValuesTypes,\n} from 'vtex.responsive-values'\nimport { useCssHandles } from 'vtex.css-handles'\nimport type { CssHandlesTypes } from 'vtex.css-handles'\n\nimport SKUSelector from './index'\nimport { CSS_HANDLES as SelectorItemCssHandles } from './components/SelectorItem'\nimport { CSS_HANDLES as ErrorMessageCssHandles } from './components/ErrorMessage'\nimport { Variations, InitialSelectionType, DisplayMode } from './types'\nimport {\n ShowValueForVariation,\n ShowVariationsLabels,\n CSS_HANDLES as SKUSelectorCssHandles,\n} from './components/SKUSelector'\nimport { SKUSelectorCssHandlesProvider } from './SKUSelectorCssHandles'\n\nexport const SKU_SELECTOR_CSS_HANDLES = [\n ...ErrorMessageCssHandles,\n ...SelectorItemCssHandles,\n ...SKUSelectorCssHandles,\n] as const\n\nconst getVariationsFromItems = (\n skuItems: ProductItem[],\n visibleVariations?: string[]\n) => {\n const variations: Variations = {}\n const variationsSet: Record<string, Set<string>> = {}\n\n for (const skuItem of skuItems) {\n for (const currentVariation of skuItem.variations) {\n const { name, values } = currentVariation\n\n if (\n !visibleVariations ||\n visibleVariations.includes(name.toLowerCase().trim())\n ) {\n const [value] = values\n const currentSet = variationsSet[name] || new Set()\n\n currentSet.add(value)\n variationsSet[name] = currentSet\n }\n }\n }\n\n const variationsNames = Object.keys(variationsSet)\n\n // Transform set back to array\n for (const variationName of variationsNames) {\n const set = variationsSet[variationName]\n\n variations[variationName] = {\n originalName: variationName,\n values: Array.from(set).map(value => ({\n name: value,\n originalName: value,\n })),\n }\n }\n\n return variations\n}\n\nconst getVariationsFromSpecifications = (\n skuSpecifications: SkuSpecification[],\n visibleVariations?: string[]\n) => {\n const variations: Variations = {}\n\n for (const specification of skuSpecifications) {\n if (\n !visibleVariations ||\n visibleVariations.includes(\n specification.field.originalName.toLowerCase().trim()\n )\n ) {\n variations[specification.field.name] = {\n originalName: specification.field.originalName,\n values: specification.values.map(value => ({\n name: value.name,\n originalName: value.originalName,\n })),\n }\n }\n }\n\n return variations\n}\n\nconst useVariations = ({\n skuItems,\n skuSpecifications,\n shouldNotShow,\n visibleVariations,\n}: {\n skuItems: ProductItem[]\n skuSpecifications: SkuSpecification[]\n shouldNotShow: boolean\n visibleVariations?: string[]\n}) => {\n const isSkuSpecificationsEmpty = skuSpecifications.length === 0\n /* if the skuSpecifications array has values, then it should be used to find\n * the variations, which will come ordered the same way they are in the catalog */\n const variationsSource = isSkuSpecificationsEmpty\n ? skuItems\n : skuSpecifications\n\n const result = useMemo(() => {\n if (\n shouldNotShow ||\n (visibleVariations && visibleVariations.length === 0)\n ) {\n return {}\n }\n\n let formattedVisibleVariations = visibleVariations\n\n if (visibleVariations) {\n formattedVisibleVariations = visibleVariations.map(variation =>\n variation.toLowerCase().trim()\n )\n }\n\n return isSkuSpecificationsEmpty\n ? getVariationsFromItems(\n variationsSource as ProductItem[],\n formattedVisibleVariations\n )\n : getVariationsFromSpecifications(\n variationsSource as SkuSpecification[],\n formattedVisibleVariations\n )\n }, [\n variationsSource,\n shouldNotShow,\n visibleVariations,\n isSkuSpecificationsEmpty,\n ])\n\n return result\n}\n\ninterface Props {\n skuItems: ProductItem[]\n skuSelected: ProductItem | null\n onSKUSelected?: (skuId: string) => void\n maxItems?: number\n visibility?: string\n seeMoreLabel: string\n hideImpossibleCombinations?: boolean\n disableUnavailableSelectOptions?: boolean\n showValueNameForImageVariation?: boolean\n showValueForVariation?: ShowValueForVariation\n imageHeight?: ResponsiveValuesTypes.ResponsiveValue<number>\n imageWidth?: ResponsiveValuesTypes.ResponsiveValue<number>\n thumbnailImage?: string\n visibleVariations?: string[]\n showVariationsLabels?: ShowVariationsLabels\n variationsSpacing?: number\n showVariationsErrorMessage?: boolean\n initialSelection?: InitialSelectionType\n displayMode?: ResponsiveValuesTypes.ResponsiveValue<DisplayMode>\n sliderDisplayThreshold?: number\n sliderArrowSize?: number\n sliderItemsPerPage?: ResponsiveValuesTypes.ResponsiveValue<number>\n sortVariationsByLabel?: boolean\n /** Used to override default CSS handles */\n classes?: CssHandlesTypes.CustomClasses<typeof SKU_SELECTOR_CSS_HANDLES>\n}\n\nfunction SKUSelectorWrapper(props: Props) {\n const { handles, withModifiers } = useCssHandles(SKU_SELECTOR_CSS_HANDLES, {\n classes: props.classes,\n })\n\n const valuesFromContext = useProduct()\n const dispatch = useProductDispatch()\n const { imageHeight, imageWidth } = useResponsiveValues(\n pick(['imageHeight', 'imageWidth'], props)\n )\n\n const shouldSelectInitialSKU = props.initialSelection !== 'empty'\n\n const skuItems =\n props.skuItems != null\n ? props.skuItems\n : valuesFromContext?.product?.items ?? []\n\n let skuSelected = props.skuSelected ?? null\n\n if (shouldSelectInitialSKU && skuSelected == null) {\n skuSelected = valuesFromContext.selectedItem\n }\n\n const visibility = props.visibility != null ? props.visibility : 'always'\n\n const shouldNotShow =\n (shouldSelectInitialSKU && skuSelected == null) ||\n skuItems.length === 0 ||\n skuSelected?.variations.length === 0 ||\n (visibility === 'more-than-one' && skuItems.length === 1)\n\n const skuSpecifications = valuesFromContext?.product?.skuSpecifications ?? []\n const variations = useVariations({\n skuItems,\n skuSpecifications,\n shouldNotShow,\n visibleVariations: props.visibleVariations,\n })\n\n useEffect(() => {\n if (dispatch) {\n dispatch({\n type: 'SKU_SELECTOR_SET_IS_VISIBLE',\n args: { isVisible: !shouldNotShow },\n })\n }\n }, [shouldNotShow, dispatch])\n\n if (shouldNotShow) {\n return null\n }\n\n let showValueForVariation: ShowValueForVariation = 'none'\n\n if (props.showValueForVariation) {\n showValueForVariation = props.showValueForVariation\n } else if (props.showValueNameForImageVariation) {\n showValueForVariation = 'image'\n }\n\n return (\n <SKUSelectorCssHandlesProvider\n handles={handles}\n withModifiers={withModifiers}\n >\n <SKUSelector\n skuItems={skuItems}\n variations={variations}\n imageWidth={imageWidth}\n skuSelected={skuSelected}\n maxItems={props.maxItems}\n imageHeight={imageHeight}\n displayMode={props.displayMode}\n seeMoreLabel={props.seeMoreLabel}\n onSKUSelected={props.onSKUSelected}\n thumbnailImage={props.thumbnailImage}\n initialSelection={props.initialSelection}\n variationsSpacing={props.variationsSpacing}\n showValueForVariation={showValueForVariation}\n showVariationsLabels={props.showVariationsLabels}\n hideImpossibleCombinations={props.hideImpossibleCombinations}\n disableUnavailableSelectOptions={props.disableUnavailableSelectOptions}\n showVariationsErrorMessage={props.showVariationsErrorMessage}\n sliderItemsPerPage={props.sliderItemsPerPage}\n sliderArrowSize={props.sliderArrowSize}\n sliderDisplayThreshold={props.sliderDisplayThreshold}\n sortVariationsByLabel={props.sortVariationsByLabel}\n />\n </SKUSelectorCssHandlesProvider>\n )\n}\n\nSKUSelectorWrapper.schema = {\n title: 'admin/editor.skuSelector.title',\n description: 'admin/editor.skuSelector.description',\n}\n\nexport default SKUSelectorWrapper\n\n```"
}
] |
code_store-components_055be135
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose } from 'ramda'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport { Input, Button } from 'vtex.styleguide'\nimport { withCssHandles } from 'vtex.css-handles'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { PixelContext } from 'vtex.pixel-manager'\n\nimport SUBSCRIBE_NEWSLETTER from './mutations/subscribeNewsletter.graphql'\n\nconst EMAIL_REGEX =\n /^[A-z0-9+_-]+(?:\\.[A-z0-9+_-]+)*@(?:[A-z0-9](?:[A-z0-9-]*[A-z0-9])?\\.)+[A-z0-9](?:[A-z0-9-]*[A-z0-9])?$/\n\nconst CSS_HANDLES = [\n 'newsletter',\n 'confirmation',\n 'container',\n 'confirmationTitle',\n 'confirmationText',\n 'form',\n 'inputGroup',\n 'buttonContainer',\n 'label',\n 'error',\n]\n\nclass Newsletter extends Component {\n state = {\n email: '',\n loading: false,\n error: null,\n success: null,\n invalidEmail: false,\n }\n\n inputRef = React.createRef()\n\n componentDidMount() {\n this.mounted = true\n this.props.push({ event: 'newsletterInput' })\n }\n\n componentWillUnmount() {\n this.mounted = false\n }\n\n safeSetState(...params) {\n if (this.mounted) {\n this.setState(...params)\n }\n }\n\n handleChangeEmail = e => {\n this.setState({ email: e.target.value.trim() })\n }\n\n validateEmail = () => {\n return EMAIL_REGEX.test(this.state.email)\n }\n\n handleSubmit = e => {\n e.preventDefault()\n if (!this.validateEmail()) {\n this.setState({ invalidEmail: true })\n if (this.inputRef && this.inputRef.current) {\n this.inputRef.current.focus()\n }\n\n return\n }\n\n this.setState({\n invalidEmail: false,\n loading: true,\n error: null,\n success: null,\n })\n\n this.props\n .subscribeNewsletter({ variables: { email: this.state.email } })\n .then(() => {\n this.safeSetState({ success: true, loading: false })\n })\n .catch(() => {\n this.safeSetState({ error: true, loading: false })\n })\n }\n\n render() {\n const { hideLabel, intl, submit, label, placeholder, handles } = this.props\n\n const submitText = formatIOMessage({ id: submit, intl })\n const labelText = formatIOMessage({ id: label, intl })\n const placeholderText = formatIOMessage({ id: placeholder, intl })\n const confirmationTitle = formatIOMessage({\n id: 'store/newsletter.confirmationTitle',\n intl,\n })\n\n const confirmationText = formatIOMessage({\n id: 'store/newsletter.confirmationText',\n intl,\n })\n\n const invalidEmailText = formatIOMessage({\n id: 'store/newsletter.invalidEmail',\n intl,\n })\n\n const errorMsg = formatIOMessage({\n id: 'store/newsletter.error',\n intl,\n })\n\n return (\n <div\n className={`${handles.newsletter} ${\n this.state.success ? handles.confirmation : ''\n } w-100`}\n >\n <div className={`${handles.container} mw9 mr-auto ml-auto pv9`}>\n {this.state.success ? (\n <Fragment>\n <div\n className={`${handles.confirmationTitle} t-heading-3 pb4 tc`}\n >\n {confirmationTitle}\n </div>\n <div className={`${handles.confirmationText} t-body tc`}>\n {confirmationText}\n </div>\n </Fragment>\n ) : (\n <form className={`${handles.form} mw6 center tc ph5 ph0-ns`}>\n <label\n className={`${handles.label} t-heading-3 tc ${\n hideLabel ? 'dn' : ''\n }`}\n htmlFor=\"newsletter-input\"\n >\n {labelText}\n </label>\n <div className={`${handles.inputGroup} flex-ns pt5`}>\n <Input\n ref={this.inputRef}\n id=\"newsletter-input\"\n errorMessage={\n this.state.invalidEmail ? invalidEmailText : null\n }\n placeholder={placeholderText}\n name=\"newsletter\"\n value={this.state.email}\n onChange={this.handleChangeEmail}\n />\n <div\n className={`${handles.buttonContainer} pl4-ns flex-none pt3 pt0-ns`}\n >\n <Button\n variation=\"primary\"\n type=\"submit\"\n onClick={this.handleSubmit}\n isLoading={this.state.loading}\n >\n {submitText}\n </Button>\n </div>\n </div>\n {this.state.error && (\n <div className={`${handles.error} c-danger t-body pt5`}>\n {errorMsg}\n </div>\n )}\n </form>\n )}\n </div>\n </div>\n )\n }\n}\n\nconst NewsletterWrapper = compose(\n graphql(SUBSCRIBE_NEWSLETTER, { name: 'subscribeNewsletter' }),\n withCssHandles(CSS_HANDLES),\n injectIntl,\n PixelContext.withPixel\n)(Newsletter)\n\nNewsletter.defaultProps = {\n hideLabel: false,\n showTerms: false,\n}\n\nNewsletter.propTypes = {\n hideLabel: PropTypes.bool.isRequired,\n showTerms: PropTypes.bool.isRequired,\n label: PropTypes.string,\n placeholder: PropTypes.string,\n submit: PropTypes.string,\n subscribeNewsletter: PropTypes.func.isRequired,\n intl: PropTypes.object,\n handles: PropTypes.any,\n push: PropTypes.func,\n}\n\nNewsletterWrapper.getSchema = () => {\n return {\n title: 'admin/editor.newsletter.title',\n description: 'admin/editor.newsletter.description',\n type: 'object',\n properties: {\n hideLabel: {\n type: 'boolean',\n title: 'admin/editor.newsletter.hideLabel',\n default: false,\n isLayout: true,\n },\n },\n }\n}\n\nexport default NewsletterWrapper\n\n```"
}
] |
code_store-components_8de33e59
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductHighlights/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n/**\n* ProductHighlights CSS Modules\n*/\n\n.highlightContent {}\n.itemHighlight {}\n.highlightTitle {}\n.highlightValue {}\n\n```"
}
] |
code_store-components_4eb46f43
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductHighlights/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport { ProductContext } from 'vtex.product-context'\nimport { isEmpty, propOr } from 'ramda'\n\nimport ProductHighlights from './index'\n\nconst ProductHighlightsWrapper = props => {\n const { conditional } = props\n\n const valuesFromContext = useContext(ProductContext)\n\n const getHighlights = () => {\n const { product } = valuesFromContext\n\n const choose = propOr('', 'highlight', conditional)\n\n if (choose === 'admin/editor.product-details.highlights.chooseDefault') {\n const typeHighlight = propOr('', 'typeHighlight', conditional)\n const highlightName = typeHighlight.trim()\n const names = highlightName.split(',')\n const specificationGroups = propOr([], 'specificationGroups', product)\n\n return names.reduce((acc, item) => {\n const [highlightSpecificationGroup] = specificationGroups.filter(\n x => x.name.toLowerCase() === item.trim().toLowerCase()\n )\n\n const highlight = propOr(\n [],\n 'specifications',\n highlightSpecificationGroup\n )\n\n return acc.concat(highlight)\n }, [])\n }\n\n if (\n choose ===\n 'admin/editor.product-details.highlights.chooseDefaultSpecification'\n ) {\n const typeSpecifications = propOr('', 'typeSpecifications', conditional)\n const specificationNames = typeSpecifications.trim().split(',')\n const allSpecifications = propOr([], 'properties', product)\n\n return specificationNames.reduce((acc, item) => {\n const highlight = allSpecifications.filter(\n x => x.name.toLowerCase() === item.trim().toLowerCase()\n )\n\n return acc.concat(highlight)\n }, [])\n }\n\n if (\n choose === 'admin/editor.product-details.highlights.allSpecifications'\n ) {\n return propOr([], 'properties', product)\n }\n }\n\n const productHighlightsProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext)) {\n return props\n }\n\n return {\n ...props,\n highlights: props.highlights || getHighlights(),\n }\n }\n\n return <ProductHighlights {...productHighlightsProps()} />\n}\n\nProductHighlightsWrapper.schema = {\n // @TODO review title and description\n title: 'admin/editor.product-details.title',\n description: 'admin/editor.product-details.description',\n type: 'object',\n definitions: {\n highlightGroupDefault: {\n title: 'highlightGroupDefault',\n type: 'object',\n properties: {\n highlight: {\n title: 'admin/editor.product-details.highlights.default',\n type: 'string',\n enum: [\n 'admin/editor.product-details.highlights.allSpecifications',\n 'admin/editor.product-details.highlights.chooseDefault',\n 'admin/editor.product-details.highlights.chooseDefaultSpecification',\n ],\n default: 'admin/editor.product-details.highlights.allSpecifications',\n },\n },\n required: ['highlight'],\n dependencies: {\n highlight: {\n oneOf: [\n {\n properties: {\n highlight: {\n enum: [\n 'admin/editor.product-details.highlights.allSpecifications',\n ],\n },\n },\n },\n {\n properties: {\n highlight: {\n enum: [\n 'admin/editor.product-details.highlights.chooseDefault',\n ],\n },\n typeHighlight: {\n type: 'string',\n title: 'admin/editor.product-details.highlights.title',\n },\n },\n required: [''],\n },\n {\n properties: {\n highlight: {\n enum: [\n 'admin/editor.product-details.highlights.chooseDefaultSpecification',\n ],\n },\n typeSpecifications: {\n type: 'string',\n title:\n 'admin/editor.product-details.highlights.typeSpecifications.title',\n },\n },\n required: [''],\n },\n ],\n },\n },\n },\n },\n properties: {\n showHighlight: {\n type: 'boolean',\n title: 'admin/editor.product-details.showHighlight.title',\n default: false,\n isLayout: false,\n },\n conditional: {\n title: 'Conditional',\n $ref: '#/definitions/highlightGroupDefault',\n },\n },\n}\n\nexport default ProductHighlightsWrapper\n\n```"
}
] |
code_store-components_dbb18914
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ProductHighlights/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 { injectIntl } from 'react-intl'\n\nimport { SanitizedHTML } from '../SanitizedHTML'\nimport styles from './styles.css'\n\n/**\n * Product highlights Component.\n * Render the highlights specifications of a product.\n */\nconst ProductHighlights = ({ ...props }) => {\n const { highlights } = props\n\n return (\n <div className={`${styles.highlightContent} pt3 pb5`}>\n {highlights.map((item, i) => (\n <div\n className={`${styles.itemHighlight} pv2`}\n data-name={item.name}\n data-value={item.values[0]}\n key={i}\n >\n <span\n className={`${styles.highlightTitle} t-body c-on-base fw7 pr3 `}\n >\n <SanitizedHTML content={item.name} />\n {': '}\n </span>\n <span\n className={`${styles.highlightValue} t-body c-muted-1 lh-copy `}\n >\n <SanitizedHTML content={item.values[0]} />\n </span>\n </div>\n ))}\n </div>\n )\n}\n\nProductHighlights.defaultProps = {\n highlights: [],\n}\n\nProductHighlights.propTypes = {\n /** Intl object to provides internationalization */\n intl: PropTypes.object.isRequired,\n /** Specifications that will be displayed on the table */\n highlights: PropTypes.arrayOf(\n PropTypes.shape({\n /** Highlight name */\n name: PropTypes.string.isRequired,\n /** Highlight value */\n values: PropTypes.arrayOf(PropTypes.string).isRequired,\n })\n ),\n}\n\nexport default injectIntl(ProductHighlights)\n\n```"
}
] |
code_store-components_38c03ec4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/UserAddress/UserAddressCssHandles.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { USER_ADDRESS_CSS_HANDLES } from '../../UserAddress'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n USER_ADDRESS_CSS_HANDLES\n)\n\nexport {\n CssHandlesProvider as UserAddressCssHandlesProvider,\n useContextCssHandles as useUserAddressCssHandles,\n}\n\n```"
}
] |
code_store-components_a3071597
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/UserAddress/AddressInfo.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { ExtensionPoint, useChildBlock } from 'vtex.render-runtime'\nimport { useIntl, FormattedMessage } from 'react-intl'\nimport { IconLocationMarker } from 'vtex.store-icons'\n\nimport { useUserAddressCssHandles } from './UserAddressCssHandles'\n\ntype Props = {\n // todo: fix orderform typings\n orderForm: any\n inverted: boolean\n inline: boolean\n showStreet: boolean\n showCityAndState: boolean\n showPostalCode: boolean\n showIfMasked: boolean\n showPrefix: boolean\n showIfEmpty: boolean\n}\n\nexport const CSS_HANDLES = [\n 'addressInfoIconContainer',\n 'addressInfoTextContainer',\n 'addressInfoPrefixContainer',\n 'addressInfoAddressContainer',\n 'addressInfoDivider',\n 'addressInfoModalContainer',\n] as const\n\nconst AddressInfo = ({\n inverted,\n inline,\n orderForm,\n showStreet,\n showCityAndState,\n showPostalCode,\n showIfMasked,\n showPrefix,\n showIfEmpty,\n}: Props) => {\n const { shippingData } = orderForm\n const hasModal = !!useChildBlock({ id: 'modal' })\n const { handles } = useUserAddressCssHandles()\n const intl = useIntl()\n\n if (\n !shippingData ||\n !shippingData.address ||\n (!showIfMasked && shippingData.address.postalCode.includes('*'))\n ) {\n if (!showIfEmpty) {\n return null\n }\n\n return (\n <div\n className={`flex ${inline ? 'items-end' : 'items-center flex-auto'}`}\n >\n <div\n className={`${\n handles.addressInfoIconContainer\n } mr3 flex items-center ${\n inverted ? 'c-on-base--inverted' : 'c-muted-2'\n }`}\n >\n <IconLocationMarker size={27} viewBox=\"0 0 21 27\" />\n </div>\n {hasModal ? (\n <div\n className={`${handles.addressInfoModalContainer} flex items-center`}\n >\n <ExtensionPoint\n id=\"modal\"\n centered\n buttonLabel={intl.formatMessage({\n id: 'store/user-address.add',\n })}\n buttonClass={\n inverted ? 'c-on-base--inverted' : 'c-action-primary'\n }\n showTopBar={false}\n />\n </div>\n ) : (\n <div className={`${handles.addressInfoAddressContainer} truncate`}>\n <FormattedMessage id=\"store/user-address.add\" />\n </div>\n )}\n </div>\n )\n }\n\n const { street, number, complement, addressType, city, state, postalCode } =\n shippingData.address\n\n let displayStreet = number ? `${street}, ${number}` : street\n\n if (complement) displayStreet = `${displayStreet} - ${complement}`\n\n const displayCityAndState = !!city && !!state ? `${city}, ${state}` : ''\n\n const displayAddress = `${showStreet ? displayStreet || '' : ''}${\n showStreet && (showCityAndState || showPostalCode) ? ', ' : ''\n }${showCityAndState ? displayCityAndState : ''}${\n showCityAndState && showPostalCode && !postalCode.includes('*')\n ? `${displayCityAndState ? ', ' : ''}`\n : ''\n }${showPostalCode && !postalCode.includes('*') ? postalCode : ''}`\n\n const isPickup = addressType === 'pickup'\n const friendlyName = orderForm?.pickupPointCheckedIn?.friendlyName ?? ''\n\n return (\n <div className={`flex ${inline ? 'items-end' : 'items-center flex-auto'}`}>\n <div className=\"flex flex-auto items-center\">\n <div\n className={`${\n handles.addressInfoIconContainer\n } mr3 flex items-center ${\n inverted ? 'c-on-base--inverted' : 'c-muted-2'\n }`}\n >\n <IconLocationMarker size={27} viewBox=\"0 0 21 27\" />\n </div>\n\n <div\n className={`${handles.addressInfoTextContainer} flex flex-auto flex-column`}\n >\n {showPrefix && (\n <div\n className={`${handles.addressInfoPrefixContainer} t-small ${\n inverted ? 'c-on-base--inverted' : 'c-muted-2'\n }`}\n >\n {isPickup ? (\n <FormattedMessage\n id=\"store/user-address.pickup\"\n values={{ name: friendlyName }}\n />\n ) : (\n <FormattedMessage id=\"store/user-address.order\" />\n )}\n </div>\n )}\n\n <div className={`${handles.addressInfoAddressContainer} truncate`}>\n {displayAddress}\n </div>\n </div>\n </div>\n {hasModal && (\n <Fragment>\n <div\n className={`${handles.addressInfoDivider} bl bw1 mh4 ${\n inline ? 'nb2' : ''\n } ${inverted ? 'b--on-base--inverted' : 'b--muted-5'}`}\n style={{\n height: '1.5rem',\n }}\n />\n\n <div\n className={`${handles.addressInfoModalContainer} flex items-center`}\n >\n <ExtensionPoint\n id=\"modal\"\n centered\n buttonLabel={intl.formatMessage({\n id: 'store/user-address.change',\n })}\n buttonClass={\n inverted ? 'c-on-base--inverted' : 'c-action-primary'\n }\n showTopBar={false}\n />\n </div>\n </Fragment>\n )}\n </div>\n )\n}\n\nexport default AddressInfo\n\n```"
}
] |
code_store-components_d4926c2d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/constants.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const ITEMS_PER_ROW = 2\nexport const SQUARED = 'squared'\nexport const RECTANGULAR = 'rectangular'\n\n```"
}
] |
code_store-components_3e1d9216
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/categoriesHighlights.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.squaredCategoriesHighlights:only-child,\n.rectangularCategoriesHighlights:only-child {\n display: none;\n}\n\n:global(.vtex-carousel) + .squared,\n:global(.vtex-carousel) + .rectangular {\n top: -5.625rem;\n}\n\n.squaredCard,\n.rectangularCard {\n background: rgba(61, 61, 61, 0.8);\n height: 18.75rem;\n}\n\n.squaredCard {\n width: 18.75rem;\n}\n\n.rectangularCard {\n width: 37.5rem;\n}\n\n.squaredCardImage,\n.rectangularCardImage {\n object-fit: cover;\n}\n\n.squaredCardImage {\n width: 18.75rem;\n}\n\n.rectangularCardImage {\n width: 37.5rem;\n}\n\n@media only screen and (min-width: 20em) and (max-width: 50em) {\n :global(.vtex-carousel) + .squaredCategoriesHighlights {\n top: -3.125rem;\n }\n\n :global(.vtex-carousel) + .rectangularCategoriesHighlights {\n top: 0;\n }\n\n .squaredCard,\n .squaredCardImage {\n height: 9.375rem;\n width: 9.375rem;\n }\n\n .rectangularCard,\n .rectangularCardImage {\n height: 12.5rem;\n width: 100%;\n }\n}\n\n@media only screen and (min-width: 50em) and (max-width: 64em) {\n :global(.vtex-carousel) + .squaredCategoriesHighlights,\n :global(.vtex-carousel) + .rectangularCategoriesHighlights {\n top: -4.375rem;\n }\n\n .squaredCard,\n .rectangularCard {\n margin: 0;\n height: 12.5rem;\n }\n\n .squaredCard,\n .squaredCardImage {\n width: 12.5rem;\n }\n\n .rectangularCard,\n .rectangularCardImage {\n width: 25rem;\n }\n\n .squaredCardImage,\n .rectangularCardImage {\n height: 12.5rem;\n }\n}\n```"
}
] |
code_store-components_115b6721
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport { range, values } from 'ramda'\nimport React, { Component } from 'react'\n\nimport categoriesHighlights from './categoriesHighlights.css'\nimport CategoryCard from './components/CategoryCard'\nimport { ITEMS_PER_ROW, RECTANGULAR, SQUARED } from './constants.js'\n\n/**\n * CategoriesHighlights is a component responsible to display the\n * Categories highlighted in a department.\n *\n * @deprecated This component is deprecated.\n */\nclass CategoriesHighlights extends Component {\n static propTypes = {\n /** Categories highlighted in the department */\n categoriesHighlighted: PropTypes.object,\n /** Flag which indicates if the categories highlighted should be displayed or not */\n showCategoriesHighlighted: PropTypes.bool,\n /** Number of categories highlighted to be displayed (it should be 2 or 4) */\n quantityOfItems: PropTypes.number.isRequired,\n /** Shape of the card box which wraps each category (it should be 'squared' or 'rectangular') */\n cardShape: PropTypes.oneOf([SQUARED, RECTANGULAR]).isRequired,\n }\n\n static defaultProps = {\n categoriesHighlighted: {},\n showCategoriesHighlighted: false,\n quantityOfItems: ITEMS_PER_ROW,\n cardShape: SQUARED,\n }\n\n static uiSchema = {\n categoriesHighlighted: {\n items: {\n image: {\n 'ui:widget': 'image-uploader',\n },\n },\n },\n }\n\n static getSchema = ({ quantityOfItems }) => {\n const categoriesHighlightedProps = {}\n\n range(0, quantityOfItems || ITEMS_PER_ROW).forEach(index => {\n categoriesHighlightedProps[`category${index}`] = {\n type: 'object',\n title: 'admin/editor.categoriesHighlighted.category',\n properties: {\n name: {\n type: 'string',\n default: '',\n title: 'admin/editor.categoriesHighlighted.item.categoryName',\n },\n image: {\n type: 'string',\n title: 'admin/editor.categoriesHighlighted.item.categoryImage',\n default: '',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n },\n }\n })\n\n return {\n title: 'admin/editor.categoriesHighlighted.title',\n description: 'admin/editor.categoriesHighlighted.description',\n type: 'object',\n properties: {\n showCategoriesHighlighted: {\n type: 'boolean',\n title: 'admin/editor.categoriesHighlighted.showCategoriesHighlighted',\n default: false,\n isLayout: true,\n },\n quantityOfItems: {\n type: 'number',\n title: 'admin/editor.categoriesHighlighted.quantityOfItems',\n enum: [2, 4],\n default: 2,\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n isLayout: true,\n },\n cardShape: {\n type: 'string',\n title: 'admin/editor.categoriesHighlighted.cardShape',\n enum: [SQUARED, RECTANGULAR],\n enumNames: [\n 'admin/editor.categoriesHighlighted.cardShape.squared',\n 'admin/editor.categoriesHighlighted.cardShape.rectangular',\n ],\n default: SQUARED,\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n isLayout: true,\n },\n categoriesHighlighted: {\n type: 'object',\n title: 'admin/editor.categoriesHighlighted.categoriesHighlighted',\n properties: categoriesHighlightedProps,\n isLayout: false,\n },\n },\n }\n }\n\n render() {\n const {\n categoriesHighlighted,\n showCategoriesHighlighted,\n quantityOfItems,\n cardShape,\n } = this.props\n\n if (!showCategoriesHighlighted) return null\n\n const categories = values(categoriesHighlighted).map(category => category)\n\n range(categories.length, quantityOfItems).forEach(() => {\n categories.push({\n name: '',\n image: '',\n })\n })\n\n return (\n <div\n className={`${\n categoriesHighlights[`${cardShape}CategoriesHighlights`]\n } relative`}\n >\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {range(0, quantityOfItems / ITEMS_PER_ROW).map(indexRow => (\n <div\n key={`row${indexRow}`}\n className=\"flex flex-row flex-wrap items-center justify-center\"\n >\n {range(0, ITEMS_PER_ROW).map(indexCol => (\n <CategoryCard\n key={2 * indexRow + indexCol}\n shape={cardShape}\n {...categories[2 * indexRow + indexCol]}\n />\n ))}\n </div>\n ))}\n </div>\n </div>\n )\n }\n}\n\nexport default CategoriesHighlights\n\n```"
}
] |
code_store-components_1327e844
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/styles.css from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.shareContainer {}\n.shareLoader {}\n.shareLabel {}\n.shareButtons {}\n.shareSocialButton {}\n.shareSocialIcon {}\n```"
}
] |
code_store-components_286f6b97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Wrapper.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useContext } from 'react'\nimport { ProductContext } from 'vtex.product-context'\nimport { path, isEmpty } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { usePixel } from 'vtex.pixel-manager'\n\nimport Share from './index'\n\nconst ShareWrapper = props => {\n const { intl } = props\n\n const valuesFromContext = useContext(ProductContext)\n const { getSettings, account } = useRuntime()\n const settings = getSettings('vtex.store')\n\n const { push } = usePixel()\n\n const shareProps = () => {\n if (!valuesFromContext || isEmpty(valuesFromContext)) {\n return props\n }\n\n const { selectedItem, product } = valuesFromContext\n\n const title = intl.formatMessage(\n { id: 'store/share.title' },\n {\n product: path(['productName'], product),\n sku: path(['name'], selectedItem),\n store: settings.storeName || account,\n }\n )\n\n return {\n ...props,\n shareLabelClass: props.shareLabelClass || 'c-muted-2 t-small mb3',\n className: props.className || 'db',\n imageUrl:\n props.imageUrl || path(['items', 0, 'images', 0, 'imageUrl'], product),\n loading:\n props.loading != null ? props.loading : !path(['name'], selectedItem),\n title: props.title || title,\n sendShareEvent: method => {\n push({\n event: 'share',\n itemId: product.productId,\n contentType: 'product',\n method,\n })\n },\n }\n }\n\n return <Share {...shareProps()} />\n}\n\nShareWrapper.schema = Share.schema\n\nexport default injectIntl(ShareWrapper)\n\n```"
}
] |
code_store-components_9a620900
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport { indexBy, prop } from 'ramda'\nimport React, { Component } from 'react'\nimport ContentLoader from 'react-content-loader'\nimport { FormattedMessage } from 'react-intl'\n\nimport SocialButton from './components/SocialButton'\nimport { SOCIAL_LIST } from './constants/social'\nimport styles from './styles.css'\n\nclass Share extends Component {\n static propTypes = {\n /** Social Networks configuration */\n social: PropTypes.object,\n /** Share buttons options */\n options: PropTypes.shape({\n /** Share buttons size in pixels */\n size: PropTypes.number,\n }),\n /** Share URL title */\n title: PropTypes.string,\n /** Indcates if the component should render the Content Loader */\n loading: PropTypes.bool,\n /** Component and content loader styles */\n styles: PropTypes.object,\n /** Classes to be applied to root element */\n className: PropTypes.string,\n /** Classes to be applied to Share label */\n shareLabelClass: PropTypes.string,\n /** Classes to be applied to social button */\n socialButtonClass: PropTypes.string,\n /** Classes to be applied to container of the buttons */\n buttonsContainerClass: PropTypes.string,\n /** Classes to be applied to icon of the button */\n socialIconClass: PropTypes.string,\n /** Classes to be applied to the Content Loader container */\n loaderContainerClass: PropTypes.string,\n /** Classes to be applied to the Content Loader */\n contentLoaderClass: PropTypes.string,\n /** Image url for share in social medias */\n imageUrl: PropTypes.string,\n /** Function that sends share event to analytics */\n sendShareEvent: PropTypes.func,\n }\n\n static Loader = (loaderProps = {}) => {\n const {\n 'vtex-share__button--loader': button,\n 'vtex-share__button--loader-1': button1,\n 'vtex-share__button--loader-2': button2,\n 'vtex-share__button--loader-3': button3,\n containerClass,\n contentLoaderClass,\n ...rest\n } = loaderProps\n\n const loaderStyles = {\n r: '1em',\n height: '2em',\n cy: '1em',\n ...button,\n }\n\n return (\n <div\n className={classNames(\n styles.shareContainer,\n styles.shareLoader,\n containerClass\n )}\n >\n <ContentLoader\n className={contentLoaderClass}\n style={{\n width: '100%',\n height: '100%',\n }}\n height=\"100\"\n width=\"100\"\n {...rest}\n >\n <circle cx=\"1em\" {...loaderStyles} {...button1} />\n <circle cx=\"3.5em\" {...loaderStyles} {...button2} />\n <circle cx=\"6em\" {...loaderStyles} {...button3} />\n </ContentLoader>\n </div>\n )\n }\n\n static defaultProps = {\n social: {\n Facebook: true,\n Twitter: true,\n WhatsApp: true,\n Pinterest: true,\n },\n options: {},\n className: 'flex flex-row flex-wrap w-100',\n shareLabelClass: 'pv2 pr3 t-small',\n buttonsContainerClass: 'flex flex-row',\n }\n\n static schema = {\n title: 'admin/editor.share.title',\n description: 'admin/editor.share.description',\n type: 'object',\n properties: {\n social: {\n title: 'admin/editor.share.social.title',\n type: 'object',\n properties: {\n ...indexBy(\n prop('title'),\n SOCIAL_LIST.map(socialNetwork => ({\n type: 'boolean',\n title: socialNetwork,\n default: Share.defaultProps.social[socialNetwork],\n }))\n ),\n },\n },\n },\n }\n\n render() {\n const {\n social,\n title,\n loading,\n options: { size },\n className,\n shareLabelClass,\n buttonsContainerClass,\n socialButtonClass,\n socialIconClass,\n loaderContainerClass,\n contentLoaderClass,\n imageUrl,\n sendShareEvent,\n } = this.props\n\n if (loading) {\n return (\n <Share.Loader\n containerClass={loaderContainerClass}\n contentLoaderClass={contentLoaderClass}\n {...this.props.styles}\n />\n )\n }\n\n return (\n <div className={classNames(styles.shareContainer, className)}>\n <div className={classNames(styles.shareLabel, shareLabelClass)}>\n <FormattedMessage id=\"store/store-components.share.label\" />\n </div>\n <div className={classNames(styles.shareButtons, buttonsContainerClass)}>\n {Object.keys(social).map(\n (socialNetwork, index) =>\n social[socialNetwork] && (\n <SocialButton\n key={index}\n imageUrl={imageUrl}\n url={window.location && window.location.href}\n message={title}\n iconClass={socialIconClass}\n buttonClass={socialButtonClass}\n socialEnum={socialNetwork}\n size={size}\n sendShareEvent={sendShareEvent}\n />\n )\n )}\n </div>\n </div>\n )\n }\n}\n\nexport default Share\n\n```"
}
] |
code_store-components_f86d8691
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/constants/PricingMode.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const GROUPED = 'grouped'\nexport const INDIVIDUAL_ITEMS = 'individualItems'\n\n```"
}
] |
code_store-components_5540f5a0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/queries/getShippingEstimates.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getShippingEstimates(\n $items: [ShippingItem]\n $postalCode: String\n $country: String\n) {\n shipping(items: $items, postalCode: $postalCode, country: $country) {\n logisticsInfo {\n itemIndex\n slas {\n id\n friendlyName\n price\n shippingEstimate\n shippingEstimateDate\n }\n }\n }\n}\n\n```"
}
] |
code_store-components_58ee5c43
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/utils/index.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nlet addressId = 1\n\nconst getRandomAddressId = () =>\n (addressId++ * new Date().getTime() * -1).toString().replace('-', '')\n\nexport const getNewAddress = (country, postalCode) => {\n const randomAddressId = getRandomAddressId()\n\n return {\n addressId: randomAddressId,\n addressType: 'residential',\n city: null,\n complement: null,\n country,\n geoCoordinates: [],\n neighborhood: null,\n number: null,\n postalCode: postalCode ?? null,\n receiverName: null,\n reference: null,\n state: null,\n street: null,\n addressQuery: null,\n }\n}\n\n```"
}
] |
code_store-components_0c824423
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/components/ShippingTableRow.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 { useIntl } from 'react-intl'\nimport TranslateEstimate from 'vtex.shipping-estimate-translator/TranslateEstimate'\nimport classNames from 'classnames'\nimport { FormattedCurrency } from 'vtex.format-currency'\n\nimport styles from '../shippingSimulator.css'\n\nconst ShippingTableRow = ({ name, shippingEstimate, price }) => {\n const { formatMessage } = useIntl()\n const etaClassName = classNames(\n `${styles.shippingTableCell} ${styles.shippingTableCellDeliveryEstimate} pv1 ph3 t-small c-muted-2`,\n {\n tc: typeof shippingEstimate === 'undefined',\n }\n )\n\n const valueClassName = classNames(\n `${styles.shippingTableCell} ${styles.shippingTableCellDeliveryPrice} pv1 ph3 t-small c-muted-2`,\n {\n tc: typeof price === 'undefined',\n }\n )\n\n let valueText\n\n if (typeof price === 'undefined') {\n valueText = '-'\n } else if (price === 0) {\n valueText = formatMessage({ id: 'store/shipping.free' })\n } else {\n valueText = <FormattedCurrency value={price / 100} />\n }\n\n return (\n <tr className={styles.shippingTableRow} key={name}>\n <td\n className={`${styles.shippingTableCell} ${styles.shippingTableCellDeliveryName} pv1 ph3 t-small`}\n >\n <label className={styles.shippingTableLabel}>\n <input\n className={`${styles.shippingTableRadioBtn} mr4`}\n name=\"shipping-option\"\n type=\"radio\"\n value={name}\n />\n {name}\n </label>\n </td>\n <td className={etaClassName}>\n <TranslateEstimate shippingEstimate={shippingEstimate} />\n </td>\n <td className={valueClassName}>{valueText}</td>\n </tr>\n )\n}\n\nShippingTableRow.propTypes = {\n name: PropTypes.string,\n shippingEstimate: PropTypes.string,\n price: PropTypes.number,\n}\n\nexport default ShippingTableRow\n\n```"
}
] |
code_store-components_4bb28830
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/ShippingSimulator/components/ShippingTable.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 { FormattedMessage } from 'react-intl'\n\nimport { GROUPED } from '../constants/PricingMode'\nimport ShippingTableRow from './ShippingTableRow'\nimport styles from '../shippingSimulator.css'\n\nconst ShippingTable = ({ shipping, pricingMode }) => {\n if ((shipping?.logisticsInfo?.length ?? 0) === 0) {\n return null\n }\n\n const slaList = shipping.logisticsInfo.reduce(\n (slas, info) => [...slas, ...info.slas],\n []\n )\n\n const slaSumValuesList = []\n\n if (pricingMode === GROUPED) {\n slaList.reduce(function (res, value) {\n if (!res[value.id]) {\n res[value.id] = { id: value.id, ...value, price: 0 }\n slaSumValuesList.push(res[value.id])\n }\n\n res[value.id].price += value.price\n\n return res\n }, {})\n }\n\n if (slaList.length === 0) {\n return (\n <FormattedMessage id=\"store/shipping.empty-sla\">\n {text => (\n <span className={`${styles.shippingNoMessage} dib t-small mt4`}>\n {text}\n </span>\n )}\n </FormattedMessage>\n )\n }\n\n return (\n <table\n className={`${styles.shippingTable} bt bb b--muted-4 c-muted-1 ph0 pv3 mt4 w-100`}\n >\n <thead className={`${styles.shippingTableHead} dn`}>\n <tr className={styles.shippingTableRow}>\n <th className={styles.shippingTableHeadDeliveryName}>\n <FormattedMessage id=\"store/shipping.deliveryName\" />\n </th>\n <th className={styles.shippingTableHeadDeliveryEstimate}>\n <FormattedMessage id=\"store/shipping.deliveryEstimate\" />\n </th>\n <th className={styles.shippingTableHeadDeliveryPrice}>\n <FormattedMessage id=\"store/shipping.deliveryPrice\" />\n </th>\n </tr>\n </thead>\n <tbody className={styles.shippingTableBody}>\n {(pricingMode === GROUPED ? slaSumValuesList : slaList).map(\n shippingItem => (\n <ShippingTableRow\n key={shippingItem.id}\n name={shippingItem.friendlyName}\n shippingEstimate={shippingItem.shippingEstimate}\n price={shippingItem.price}\n />\n )\n )}\n </tbody>\n </table>\n )\n}\n\nShippingTable.propTypes = {\n /** Shipping informations */\n shipping: PropTypes.shape({\n logisticsInfo: PropTypes.arrayOf(\n PropTypes.shape({\n itemIndex: PropTypes.string,\n slas: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.string,\n friendlyName: PropTypes.string,\n price: PropTypes.number,\n shippingEstimate: PropTypes.string,\n })\n ),\n })\n ),\n }),\n pricingMode: PropTypes.enum,\n}\n\nexport default ShippingTable\n\n```"
}
] |
code_store-components_dd2bc06e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/mutations/setOpenMinicart.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation setMinicartOpen($isOpen: Boolean!) {\n setMinicartOpen(isOpen: $isOpen) @client\n}\n\n```"
}
] |
code_store-components_f4027a1b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/mutations/addToCart.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation addToCart($items: [MinicartItem]) {\n addToCart(items: $items) @client\n}\n\n```"
}
] |
code_store-components_54659d12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/queries/installedApp.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery installedAppPublic($slug: String!) {\n installedAppPublic(slug: $slug) @context(provider: \"vtex.apps-graphql\") {\n version\n }\n}\n\n```"
}
] |
code_store-components_e31ada97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/BuyButton/hooks/useMarketingSessionParams.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useState } from 'react'\nimport { path, pathOr } from 'ramda'\n\nconst getUtmParams = publicFields => ({\n source: path(['utm_source', 'value'], publicFields),\n medium: path(['utm_medium', 'value'], publicFields),\n campaign: path(['utm_campaign', 'value'], publicFields),\n})\n\nconst getUtmiParams = publicFields => ({\n campaign: path(['utmi_cp', 'value'], publicFields),\n page: path(['utmi_p', 'value'], publicFields),\n part: path(['utmi_pc', 'value'], publicFields),\n})\n\nconst getSessionPromiseFromWindow = () =>\n !window.__RENDER_8_SESSION__ || !window.__RENDER_8_SESSION__.sessionPromise\n ? Promise.resolve(null)\n : window.__RENDER_8_SESSION__.sessionPromise\n\nconst useMarketingSessionParams = () => {\n const [utmParams, setUtmParams] = useState(undefined)\n const [utmiParams, setUtmiParams] = useState(undefined)\n\n useEffect(() => {\n getSessionPromiseFromWindow()\n .then(data => {\n const publicFields = pathOr(\n {},\n ['response', 'namespaces', 'public'],\n data\n )\n\n if (Object.keys(publicFields).length === 0) {\n return\n }\n\n setUtmParams(getUtmParams(publicFields))\n setUtmiParams(getUtmiParams(publicFields))\n })\n .catch(() => {\n // Do nothing!\n })\n }, [])\n\n return { utmParams, utmiParams }\n}\n\nexport default useMarketingSessionParams\n\n```"
}
] |
code_store-components_0a3f3b4d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Greeting/queries/orderForm.gql from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery orderFormQuery {\n minicart @client {\n orderForm\n }\n}\n\n```"
}
] |
code_store-components_c8507c38
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/utils/ItemsPerPage.js from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { path } from 'ramda'\n\nfunction getItemWidth(slick, maxWidth) {\n const slidesNodeList = path(\n ['innerSlider', 'list', 'childNodes', '0', 'childNodes'],\n slick\n )\n\n let itemWidth = null\n\n if (slidesNodeList) {\n const slidesArray = Array.prototype.slice.call(slidesNodeList)\n\n // eslint-disable-next-line array-callback-return\n slidesArray.map(slide => {\n const attributes = Array.prototype.slice.call(slide.attributes)\n\n // eslint-disable-next-line array-callback-return\n attributes.map(attr => {\n // eslint-disable-next-line vtex/prefer-early-return\n if (attr.nodeName === 'data-index' && attr.nodeValue === '0') {\n itemWidth = path(['childNodes', '0', 'clientWidth'], slide)\n if (maxWidth && maxWidth < itemWidth) itemWidth = maxWidth\n }\n })\n })\n }\n\n return itemWidth || maxWidth\n}\n\n/**\n * Returns the correct number of items to be inside the slider without reduce the item width.\n */\n// eslint-disable-next-line max-params\nexport default function getItemsPerPage(\n slick,\n slideWidth,\n defaultItemWidth,\n actualItemsPerPage\n) {\n if (slideWidth) {\n const shelfItemWidth = getItemWidth(slick, defaultItemWidth)\n const maxItemsPerPage = Math.floor(slideWidth / shelfItemWidth)\n\n if (actualItemsPerPage >= maxItemsPerPage) {\n return maxItemsPerPage || 1\n }\n }\n\n return actualItemsPerPage\n}\n\n```"
}
] |
code_store-components_d8e0be7c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/components/Arrow.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\n/**\n * Arrow component. It's an overriden component of react-slick that controls\n * the slide transition.\n */\n// eslint-disable-next-line react/prefer-stateless-function\nexport default class Arrow extends Component {\n render() {\n const { className, style, onClick, cssClass, customClasses } = this.props\n const arrowClasses = classNames({\n [`${className}`]: className,\n [`${cssClass}`]: cssClass,\n [`${customClasses}`]: customClasses,\n })\n\n return (\n // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions\n <div\n className={`${arrowClasses}`}\n style={{ ...style }}\n onClick={onClick}\n />\n )\n }\n}\n\nArrow.propTypes = {\n /** (react-slick prop) Css class of the element. */\n className: PropTypes.string,\n /** (react-slick prop) Custom style of the element. */\n style: PropTypes.object,\n /** (react-slick prop) Function to be called when the arrow is clicked. */\n onClick: PropTypes.func,\n /** Specifies wich css class the arrow will receive. */\n cssClass: PropTypes.string.isRequired,\n /** Custom classes */\n customClasses: PropTypes.string,\n}\n\n```"
}
] |
code_store-components_186a610e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/Slider/components/Dots.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\n/**\n * Dots component. It's an overriden component of react-slick that controls\n * the slide transition;\n */\n// eslint-disable-next-line react/prefer-stateless-function\nexport default class Dots extends Component {\n render() {\n const { className, style, dots, cssClass, customClass } = this.props\n const dotsClasses = classNames([className, cssClass, customClass])\n\n return (\n <div className={dotsClasses}>\n <ul className=\"ma0 pa0\" style={{ ...style }}>\n {dots}\n </ul>\n </div>\n )\n }\n}\n\nDots.propTypes = {\n /** (react-slick prop) Css class of the element. */\n className: PropTypes.string,\n /** Dots custom classes passed by props. */\n customClass: PropTypes.string,\n /** (react-slick prop) Custom style of the element. */\n style: PropTypes.object,\n /** (react-slick prop) Dots that will be displayed */\n dots: PropTypes.node.isRequired,\n /** Specifies wich css the dots will receive. */\n cssClass: PropTypes.string.isRequired,\n}\n\n```"
}
] |
code_store-components_c7db2b32
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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.d.ts from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport function changeImageUrlSize(\n url: string,\n width: number | string,\n height: number | string\n): string\n\n```"
}
] |
code_store-components_dd0e626b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX 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/aspectRatioUtil.tsx from the store-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { changeImageUrlSize } from './generateUrl'\n\ntype AspectRatio = string | number\n\n/** Parses ratio values into a multiplier to set the image height.\n * For example, turns \"3:4\" into 1.333, so the image height will be\n * 1.333 times its width.\n */\nconst parseAspectRatio = (input?: AspectRatio | null) => {\n if (!input) {\n return null\n }\n\n if (typeof input === 'string') {\n if (input === 'auto') {\n return null\n }\n\n const separator = ':'\n const data = input.split(separator)\n\n if (data.length !== 2) {\n return null\n }\n\n const [width, height] = data\n const ratio = parseFloat(height) / parseFloat(width)\n\n if (typeof ratio !== 'number' || window.isNaN(ratio)) {\n return null\n }\n\n return ratio\n }\n\n if (typeof input === 'number') {\n return input\n }\n\n return null\n}\n\nexport const imageUrl = (\n src: string,\n size: number,\n maxSize: number,\n aspectRatio?: AspectRatio\n // eslint-disable-next-line max-params\n) => {\n let width = size\n let height: number | string = 'auto'\n\n if (aspectRatio && aspectRatio !== 'auto') {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n height = size * (parseAspectRatio(aspectRatio) || 1)\n\n if (width > maxSize) {\n height /= width / maxSize\n width = maxSize\n }\n\n if (height > maxSize) {\n width /= height / maxSize\n height = maxSize\n }\n\n width = Math.round(width)\n height = Math.round(height)\n } else {\n width = Math.min(maxSize, width)\n }\n\n return changeImageUrlSize(src, width, height)\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.