id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-on-localhost_a5b0d045
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/utils/index.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { prop, filter, clone, reject } from 'ramda'\nimport slugify from 'slugify'\nimport { SelectorProductItem, SelectedVariations } from '../types'\n\n/**\n * Return the maximum sku price\n * @param {array of sku's} items\n */\nexport const getMaxSkuPrice = (items: SelectorProductItem[]) => {\n if (!items) return 0\n\n return items.reduce((max, sku) => {\n const [\n {\n commertialOffer: { Price },\n },\n ] = sku.sellers\n\n return Math.max(max, Price)\n }, 0)\n}\n\n/**\n * Remove the 'https' from the given url\n * @param {string} url\n */\nexport const stripUrl = (url: string) => url.replace(/^https?:/, '')\n\n/**\n * Parse the variations field in the sku object\n * @param {sku} sku\n */\nexport const parseSku = (sku: ProductItem) => {\n const result = clone(sku) as any\n const variationValues = {} as Record<string, string>\n for (const variation of sku.variations) {\n variationValues[variation.name] = variation.values[0]\n }\n const variations = sku.variations.map(prop('name'))\n\n result.variationValues = variationValues\n result.variations = variations\n return result as SelectorProductItem\n}\n\n/**\n * Verifies if the variation is color\n * @param {string} variation\n */\nexport const isColor = (variation: string) => {\n if (!variation) return false\n\n const possibleValues = [\n 'cor',\n 'color',\n 'colour',\n 'farbe',\n 'couleur',\n 'kleuren',\n 'colori',\n ]\n\n return possibleValues.includes(variation.toLowerCase())\n}\n\n/**\n * Choose wich variation will be the main one.\n * @param {Array[string]} variations\n */\nexport const getMainVariationName = (variations: string[]) => {\n for (let i = 0; i < variations.length; i++) {\n if (isColor(variations[i])) return variations[i]\n }\n\n return variations[0]\n}\n\n/**\n * Given a selectedVariations, find the first item that has those variations selected\n * selectedVariations format: { \"color\": \"black\", size: \"small\", fabric: null }\n * items: skuItems parsed with variations fields\n * Output: item or null, if not present\n */\n\nexport const findItemWithSelectedVariations = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations\n) => {\n const selectedNotNull = filter(\n Boolean,\n selectedVariations\n ) as SelectedVariationsNotNull\n const selectedCount = Object.keys(selectedNotNull).length\n if (selectedCount === 0) {\n // may return any item, return first element\n return items[0]\n }\n return items.find(isSkuSelected(selectedNotNull))\n}\n\n/**\n * Given a selectedVariations, find items that have those variations selected\n * selectedVariations format: { \"color\": \"black\", size: \"small\", fabric: null }\n * items: skuItems parsed with variations fields\n * Output: list of items with those variations\n */\n\nexport const findListItemsWithSelectedVariations = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations\n) => {\n const selectedNotNull = filter(\n Boolean,\n selectedVariations\n ) as SelectedVariationsNotNull\n const selectedCount = Object.keys(selectedNotNull).length\n if (selectedCount === 0) {\n // return all\n return items\n }\n return items.filter(isSkuSelected(selectedNotNull))\n}\n\nexport const uniqueOptionToSelect = (\n items: SelectorProductItem[],\n selectedVariations: SelectedVariations,\n isMainAndImpossible: boolean\n) => {\n const possibleItems = !isMainAndImpossible\n ? items\n : findListItemsWithSelectedVariations(items, selectedVariations)\n const unselected = reject(Boolean, selectedVariations)\n const unselectedNames = Object.keys(unselected)\n const availableOptions = buildAvailableVariations(\n possibleItems,\n unselectedNames\n )\n const variationsWithOne = filter(\n setValues => setValues.size === 1,\n availableOptions\n )\n\n const variationsNames = Object.keys(variationsWithOne)\n const finalUniqueVariations = {} as Record<string, string>\n // Transform set to plain value\n for (const variationName of variationsNames) {\n const value = variationsWithOne[variationName].values().next().value\n finalUniqueVariations[variationName] = value\n }\n return finalUniqueVariations\n}\n\nexport function slug(str: string) {\n const replaced = (str && str.replace(/[*+~.()'\"!:@&\\[\\]]/g, '')) || ''\n const slugified = slugify(replaced, { lower: true }) || ''\n return slugified\n}\ntype SelectedVariationsNotNull = Record<string, string>\n\n/** Private functions */\nconst isSkuSelected = (selectedNotNull: SelectedVariationsNotNull) => (\n sku: SelectorProductItem\n) => {\n const hasAll = Object.keys(selectedNotNull).every(variationName => {\n const selectedValue = selectedNotNull[variationName]\n return sku.variationValues[variationName] === selectedValue\n })\n return hasAll\n}\n\nconst buildAvailableVariations = (\n items: SelectorProductItem[],\n variationNames: string[]\n) => {\n const result = {} as Record<string, Set<string>>\n for (const variationName of variationNames) {\n result[variationName] = new Set()\n }\n for (const item of items) {\n for (const variationName of variationNames) {\n const variationValue = item.variationValues[variationName]\n const currentSet = result[variationName]\n if (variationValue) {\n currentSet.add(variationValue)\n }\n }\n }\n return result\n}\n\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex: RegExp = new RegExp(/.+ids\\/(\\d+)/)\n\nexport function cleanImageUrl(imageUrl: string) {\n const result = baseUrlRegex.exec(imageUrl) || []\n return result.length > 0 ? result[0] : null\n}\n\nfunction replaceLegacyFileManagerUrl(imageUrl: string, width: number | string, height: number | string) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n if (!isLegacyUrl) return imageUrl\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize(\n imageUrl: string,\n width: string | number = DEFAULT_WIDTH,\n height: string | number = DEFAULT_HEIGHT,\n) {\n if (!imageUrl) return\n typeof width === 'number' && (width = Math.min(width, MAX_WIDTH))\n typeof height === 'number' && (height = Math.min(height, MAX_HEIGHT))\n\n const normalizedImageUrl = replaceLegacyFileManagerUrl(imageUrl, width, height)\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\nexport const DEFAULT_BOTTOM_MARGIN = 7\nconst MAX_POSSIBLE_MARGIN = 11\nconst MIN_POSSIBLE_MARGIN = 0\n\nexport function getValidMarginBottom(variationsSpacing?: number) {\n if (typeof variationsSpacing === 'undefined') {\n return DEFAULT_BOTTOM_MARGIN\n }\n\n return Math.max(Math.min(MAX_POSSIBLE_MARGIN, variationsSpacing), MIN_POSSIBLE_MARGIN)\n}\n\nexport const NO_BOTTOM_MARGIN = 'none'\n\n```"
}
] |
code_store-on-localhost_a05d7e6c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/ErrorMessage.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport useCssHandles from '../../../../CssHandles/useCssHandles'\nimport { FormattedMessage } from 'react-intl'\n\nconst CSS_HANDLES = ['errorMessage'] as const\n\nfunction ErrorMessage() {\n const handles = useCssHandles(CSS_HANDLES)\n const className = `${handles.errorMessage} c-danger`\n\n return (\n <FormattedMessage id=\"store/sku-selector.variation.select-an-option\">\n {message => (\n <>{' '}{/* this space is necessary */}\n <span className={className}>\n {message}\n </span>\n </>\n )}\n </FormattedMessage>\n )\n}\n\nexport default ErrorMessage\n\n```"
}
] |
code_store-on-localhost_2a65e4ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/SKUSelector.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useCallback, memo, useState, FC, useMemo } from 'react'\nimport { compose, flip, gt, filter, pathOr, clone } from 'ramda'\nimport { ResponsiveInput } from 'vtex.responsive-values'\n\nimport styles from '../styles.css'\nimport {\n isColor,\n getValidMarginBottom,\n findItemWithSelectedVariations,\n findListItemsWithSelectedVariations,\n} from '../utils'\nimport {\n SelectorProductItem,\n CallbackItem,\n SelectedVariations,\n ImageMap,\n DisplayOption,\n DisplayVariation,\n Variations,\n DisplayMode,\n} from '../types'\n\nimport Variation from './Variation'\nimport useEffectSkipMount from './hooks/useEffectSkipMount'\n\nexport enum ShowValueForVariation {\n none = 'none',\n image = 'image',\n all = 'all',\n}\n\nfunction getShowValueForVariation(\n showValueForVariation: ShowValueForVariation,\n variationName: string\n) {\n const isImage = isColor(variationName)\n return (\n showValueForVariation === ShowValueForVariation.all ||\n (showValueForVariation === ShowValueForVariation.image && isImage)\n )\n}\n\ninterface Props {\n seeMoreLabel: string\n maxItems: number\n variations: Variations\n skuItems: SelectorProductItem[]\n onSelectItem: (callbackItem: CallbackItem) => void\n imagesMap: ImageMap\n selectedVariations: Record<string, string | null>\n hideImpossibleCombinations: boolean\n showValueForVariation: ShowValueForVariation\n showBorders?: boolean\n imageHeight?: number\n imageWidth?: number\n showVariationsLabels: boolean\n variationsSpacing?: number\n showVariationsErrorMessage: boolean\n displayMode: DisplayMode\n sliderDisplayThreshold: number\n sliderArrowSize: number\n sliderItemsPerPage: any\n}\n\nconst isSkuAvailable = compose<\n SelectorProductItem | undefined,\n number,\n boolean\n>(\n flip(gt)(0),\n pathOr(0, ['sellers', '0', 'commertialOffer', 'AvailableQuantity'])\n)\n\nconst showItemAsAvailable = (\n possibleItems: SelectorProductItem[],\n selectedVariations: SelectedVariations,\n variationCount: number,\n isSelected: boolean\n) => {\n const selectedNotNull = filter(Boolean, selectedVariations)\n const selectedCount = Object.keys(selectedNotNull).length\n if (selectedCount === variationCount && isSelected) {\n const item = findItemWithSelectedVariations(\n possibleItems,\n selectedVariations\n )\n return isSkuAvailable(item)\n }\n return possibleItems.some(isSkuAvailable)\n}\n\ninterface AvailableVariationParams {\n variations: Variations\n selectedVariations: SelectedVariations\n imagesMap: ImageMap\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n skuItems: SelectorProductItem[]\n hideImpossibleCombinations: boolean\n}\n\nconst parseOptionNameToDisplayOption = ({\n selectedVariations,\n variationName,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n}: {\n selectedVariations: SelectedVariations\n variationName: string\n skuItems: SelectorProductItem[]\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n imagesMap: ImageMap\n variationCount: number\n hideImpossibleCombinations: boolean\n}) => (variationValue: string): DisplayOption | null => {\n const isSelected = selectedVariations[variationName] === variationValue\n const image = imagesMap?.[variationName]?.[variationValue]\n\n const newSelectedVariation = clone(selectedVariations)\n newSelectedVariation[variationName] = isSelected ? null : variationValue\n\n const possibleItems = findListItemsWithSelectedVariations(\n skuItems,\n newSelectedVariation\n )\n if (possibleItems.length > 0) {\n // This is a valid combination option\n const [item] = possibleItems\n const callbackFn = onSelectItemMemo({\n name: variationName,\n value: variationValue,\n skuId: item.itemId,\n isMainAndImpossible: false,\n possibleItems,\n })\n return {\n label: variationValue,\n onSelectItem: callbackFn,\n image,\n available: showItemAsAvailable(\n possibleItems,\n selectedVariations,\n variationCount,\n isSelected\n ),\n impossible: false,\n }\n }\n if (hideImpossibleCombinations && isColor(variationName)) {\n // This is a visual (with picture) variation and should not be hidden.\n // If the hideImpossibleCombinations is true, we should display it as normal but when pressed it will reset the selected variations.\n const callbackFn = onSelectItemMemo({\n name: variationName,\n value: variationValue,\n skuId: null,\n isMainAndImpossible: true,\n possibleItems: skuItems,\n })\n return {\n label: variationValue,\n onSelectItem: callbackFn,\n image,\n available: true,\n impossible: false,\n }\n }\n if (!hideImpossibleCombinations) {\n // This is a impossible combination and will only appear if the prop allows.\n return {\n label: variationValue,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onSelectItem: () => {},\n image,\n available: true,\n impossible: true,\n }\n }\n // This is a impossible combination and will be hidden.\n return null\n}\n\nconst variationNameToDisplayVariation = ({\n variations,\n selectedVariations,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n}: {\n variations: Variations\n selectedVariations: SelectedVariations\n skuItems: SelectorProductItem[]\n imagesMap: ImageMap\n onSelectItemMemo: (callbackItem: CallbackItem) => () => void\n variationCount: number\n hideImpossibleCombinations: boolean\n}) => (variationName: string): DisplayVariation => {\n const name = variationName\n const values = variations[variationName]\n const options = values\n .map(\n parseOptionNameToDisplayOption({\n selectedVariations,\n variationName,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n })\n )\n .filter(Boolean) as DisplayOption[]\n return { name, options }\n}\n\n// Parameters are explained on PropTypes\nconst getAvailableVariations = ({\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n}: AvailableVariationParams): DisplayVariation[] => {\n const variationCount = Object.keys(variations).length\n return Object.keys(variations).map(\n variationNameToDisplayVariation({\n variations,\n selectedVariations,\n skuItems,\n onSelectItemMemo,\n imagesMap,\n variationCount,\n hideImpossibleCombinations,\n })\n )\n}\n\nconst getAvailableVariationsPromise = (\n params: AvailableVariationParams\n): Promise<DisplayVariation[]> => {\n return new Promise(resolve => {\n const result = getAvailableVariations(params)\n resolve(result)\n })\n}\n\n/** Renders the main and the secondary variation, if it exists. */\nconst SKUSelector: FC<Props> = ({\n seeMoreLabel,\n maxItems,\n variations,\n skuItems,\n onSelectItem,\n imagesMap,\n imageHeight,\n imageWidth,\n showBorders,\n displayMode,\n selectedVariations,\n showVariationsLabels,\n showValueForVariation,\n hideImpossibleCombinations,\n showVariationsErrorMessage,\n variationsSpacing: marginBottomProp,\n sliderDisplayThreshold,\n sliderArrowSize,\n sliderItemsPerPage,\n}) => {\n const variationsSpacing = getValidMarginBottom(marginBottomProp)\n const onSelectItemMemo = useCallback(\n ({\n name,\n value,\n skuId,\n isMainAndImpossible,\n possibleItems,\n }: CallbackItem) => () =>\n onSelectItem({ name, value, skuId, isMainAndImpossible, possibleItems }),\n [onSelectItem]\n )\n const availableVariationsPayload = useMemo(\n () => ({\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n }),\n [\n variations,\n selectedVariations,\n imagesMap,\n onSelectItemMemo,\n skuItems,\n hideImpossibleCombinations,\n ]\n )\n const [displayVariations, setDisplayVariations] = useState<\n DisplayVariation[]\n >(() => getAvailableVariations(availableVariationsPayload))\n\n useEffectSkipMount(() => {\n let isCurrent = true\n const promise = getAvailableVariationsPromise(availableVariationsPayload)\n promise.then(availableVariations => {\n if (isCurrent) {\n setDisplayVariations(availableVariations)\n }\n })\n return () => {\n isCurrent = false\n }\n }, [availableVariationsPayload])\n\n const variationClasses = `mb${variationsSpacing}`\n return (\n <div className={styles.skuSelectorContainer}>\n {displayVariations.map((variationOption, index) => {\n const selectedItem = selectedVariations[variationOption.name]\n\n return (\n <Variation\n mode={displayMode}\n maxItems={maxItems}\n imageWidth={imageWidth}\n imageHeight={imageHeight}\n showBorders={showBorders}\n variation={variationOption}\n selectedItem={selectedItem}\n seeMoreLabel={seeMoreLabel}\n showLabel={showVariationsLabels}\n containerClasses={variationClasses}\n key={`${variationOption.name}-${index}`}\n showErrorMessage={showVariationsErrorMessage}\n showValueForVariation={getShowValueForVariation(\n showValueForVariation,\n variationOption.name\n )}\n sliderDisplayThreshold={sliderDisplayThreshold}\n sliderArrowSize={sliderArrowSize}\n sliderItemsPerPage={sliderItemsPerPage}\n />\n )\n })}\n </div>\n )\n}\n\nexport default memo(SKUSelector)\n\n```"
}
] |
code_store-on-localhost_680ec74e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/Variation.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, memo, useState, Fragment, useCallback } from 'react'\nimport Button from '../../../../Styleguide/Button'\nimport IOMessage from '../../../../NativeTypes/IOMessage'\nimport SliderLayout from '../../../../SliderLayout/SliderLayout'\nimport { findIndex, propEq } from 'ramda'\nimport classnames from 'classnames'\nimport useProduct from '../../../../ProductContext/useProduct'\n\nimport { stripUrl, isColor, slug } from '../utils'\nimport styles from '../styles.css'\nimport { DisplayVariation, DisplayMode } from '../types'\nimport { imageUrlForSize, VARIATION_IMG_SIZE } from '../../module/images'\nimport ErrorMessage from './ErrorMessage'\nimport SelectModeVariation from './SelectVariationMode'\nimport SelectorItem from './SelectorItem'\n\ninterface Props {\n variation: DisplayVariation\n maxSkuPrice?: number | null\n seeMoreLabel: string\n maxItems: number\n selectedItem: string | null\n showValueForVariation: boolean\n imageHeight?: number\n imageWidth?: number\n showBorders?: boolean\n showLabel: boolean\n containerClasses?: string\n showErrorMessage: boolean\n mode?: string\n sliderDisplayThreshold: number\n sliderArrowSize: number\n sliderItemsPerPage: any\n}\n\nconst ITEMS_VISIBLE_THRESHOLD = 2\n\nconst findSelectedOption = (selectedItem: string | null) =>\n findIndex(propEq('label', selectedItem))\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst noop = () => {}\n\nconst Variation: FC<Props> = ({\n mode = 'default',\n maxItems,\n showLabel,\n variation,\n imageWidth,\n imageHeight,\n showBorders,\n maxSkuPrice,\n seeMoreLabel,\n selectedItem,\n showErrorMessage,\n showValueForVariation,\n containerClasses: containerClassesProp,\n sliderArrowSize,\n sliderDisplayThreshold,\n sliderItemsPerPage,\n}) => {\n const { name, options } = variation\n\n const visibleItemsWhenCollapsed = maxItems - ITEMS_VISIBLE_THRESHOLD\n\n const [showAll, setShowAll] = useState(() => {\n const selectedOptionPosition = findSelectedOption(selectedItem)(options)\n return selectedOptionPosition >= visibleItemsWhenCollapsed\n })\n\n const {\n buyButton = {\n clicked: false,\n },\n } = useProduct() as any\n\n const displayImage = isColor(name)\n\n const shouldCollapse = !showAll && options.length > maxItems\n\n const overflowQuantity = options.length - visibleItemsWhenCollapsed\n const displayOptions = options.slice(\n 0,\n shouldCollapse ? visibleItemsWhenCollapsed : options.length\n )\n const showAllAction = useCallback(() => setShowAll(true), [setShowAll])\n const containerClasses = classnames(\n 'flex flex-column',\n containerClassesProp,\n styles.skuSelectorSubcontainer,\n `${styles.skuSelectorSubcontainer}--${slug(name)}`\n )\n\n const shouldUseSlider =\n displayOptions.length > sliderDisplayThreshold &&\n mode === DisplayMode.slider\n\n const sliderConfigurationProps = {\n itemsPerPage: sliderItemsPerPage,\n infinite: true,\n showNavigationArrows: 'always',\n showPaginationDots: 'never',\n arrowSize: sliderArrowSize,\n fullWidth: false,\n }\n\n const selectorItemsArray = displayOptions.map(option => {\n return (\n <SelectorItem\n isSelected={option.label === selectedItem}\n key={`\u001c${option.label}-${name}`}\n isAvailable={option.available}\n maxPrice={maxSkuPrice}\n onClick={option.impossible ? noop : option.onSelectItem}\n isImage={displayImage}\n variationValue={option.label}\n imageHeight={imageHeight}\n imageWidth={imageWidth}\n showBorders={showBorders}\n imageUrl={\n option.image &&\n imageUrlForSize(stripUrl(option.image.imageUrl), VARIATION_IMG_SIZE)\n }\n imageLabel={option.image && option.image.imageLabel}\n isImpossible={option.impossible}\n />\n )\n })\n\n return (\n <div className={containerClasses}>\n <div className={`${styles.skuSelectorNameContainer} ma1`}>\n <div className={`${styles.skuSelectorTextContainer} db mb3`}>\n {showLabel && (\n <span\n className={`${styles.skuSelectorName} c-muted-1 t-small overflow-hidden`}\n >\n {name}\n {showErrorMessage && buyButton.clicked && !selectedItem && (\n <ErrorMessage />\n )}\n </span>\n )}\n {selectedItem && showValueForVariation && (\n <Fragment>\n <span\n className={`${styles.skuSelectorNameSeparator} c-muted-1 t-small`}\n >\n :{' '}\n </span>\n <span\n className={`${styles.skuSelectorSelectorImageValue} c-muted-1 t-small`}\n >\n {selectedItem}\n </span>\n </Fragment>\n )}\n </div>\n <div\n className={`${styles.skuSelectorOptionsList} w-100 inline-flex flex-wrap ml2 items-center`}\n >\n {mode === DisplayMode.select && !displayImage ? (\n <SelectModeVariation\n selectedItem={selectedItem}\n displayOptions={displayOptions}\n />\n ) : shouldUseSlider ? (\n <SliderLayout {...sliderConfigurationProps}>\n {selectorItemsArray}\n </SliderLayout>\n ) : (\n selectorItemsArray\n )}\n {!showAll && shouldCollapse && (\n <div className={styles.seeMoreButton}>\n <Button\n variation=\"tertiary\"\n onClick={showAllAction}\n size=\"small\"\n collapseLeft\n >\n <IOMessage\n id={seeMoreLabel}\n values={{ quantity: overflowQuantity }}\n data-testid=\"seeMoreLabel\"\n />\n </Button>\n </div>\n )}\n </div>\n </div>\n </div>\n )\n}\n\nexport default memo(Variation)\n\n```"
}
] |
code_store-on-localhost_981fa755
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/SelectVariationMode.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport Dropdown from '../../../../Styleguide/Dropdown'\nimport { injectIntl, WrappedComponentProps, defineMessages } from 'react-intl'\nimport styles from '../styles.css'\nimport { DisplayOption } from '../types'\n\ninterface VariationSelectModeProps extends WrappedComponentProps {\n selectedItem: string | null\n displayOptions: DisplayOption[]\n}\n\nconst messages = defineMessages({\n selectPlaceholder: {\n id: 'store/sku-selector.select.placeholder',\n defaultMessage: '',\n }\n})\n\nfunction SelectVariationMode(props: VariationSelectModeProps) {\n const {\n intl,\n selectedItem,\n displayOptions,\n } = props\n\n const options = displayOptions.map(op => ({\n label: op.label,\n value: op.label,\n }))\n\n const handleClick = (_: React.MouseEvent, value: string) => {\n const options = displayOptions\n .reduce<Record<string, DisplayOption>>((acc, cur) => {\n acc[cur.label] = cur\n return acc\n }, {})\n if (options && options[value] && options[value].onSelectItem) {\n options[value].onSelectItem()\n }\n }\n\n return (\n <div className={styles.skuSelectorSelectContainer}>\n <Dropdown\n options={options}\n value={selectedItem}\n onChange={handleClick}\n placeholder={intl.formatMessage(messages.selectPlaceholder)}\n />\n </div>\n )\n}\n\nexport default injectIntl(SelectVariationMode)\n\n```"
}
] |
code_store-on-localhost_04a89aa6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/SelectorItem.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { memo, FC, SyntheticEvent } from 'react'\nimport { FormattedNumber } from 'react-intl'\nimport classNames from 'classnames'\n\nimport styles from '../styles.css'\nimport { slug, changeImageUrlSize } from '../utils'\n\ninterface Props {\n isAvailable: boolean\n isSelected: boolean\n maxPrice?: number | null\n price?: number | null\n onClick: (e: SyntheticEvent<HTMLDivElement>) => void\n isImage: boolean\n variationValue: string\n imageUrl?: string\n imageLabel?: string | null\n isImpossible: boolean\n imageHeight?: number | string\n imageWidth?: number | string\n showBorders?: boolean\n}\n\nconst getDiscount = (maxPrice?: number | null, price?: number | null) => {\n let discount = 0\n if (maxPrice && price) {\n discount = 1 - price / maxPrice\n }\n return discount\n}\n\n/**\n * Inherits the components that should be displayed inside the Selector component.\n */\nconst SelectorItem: FC<Props> = ({\n isAvailable = true,\n isSelected = false,\n maxPrice,\n price,\n onClick,\n isImage,\n variationValue,\n imageUrl,\n imageLabel,\n isImpossible,\n imageHeight,\n imageWidth,\n showBorders = true,\n}) => {\n const discount = getDiscount(maxPrice, price)\n\n const containerClasses = classNames(\n styles.skuSelectorItem,\n `${styles.skuSelectorItem}--${slug(variationValue)}`,\n 'relative di pointer flex items-center outline-0 ma2',\n {\n [styles.skuSelectorItemImage]: isImage,\n 'o-20': isImpossible,\n }\n )\n\n const passedAnyDimension = Boolean(imageHeight || imageWidth)\n let containerStyles = {}\n if (isImage && passedAnyDimension && imageUrl) {\n containerStyles = {\n height: imageHeight || 'auto',\n width: imageWidth || 'auto',\n padding: 0,\n }\n imageUrl = changeImageUrlSize(imageUrl, imageWidth, imageHeight)\n }\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n onClick={onClick}\n style={containerStyles}\n className={containerClasses}\n onKeyDown={e => e.key === 'Enter' && onClick(e)}\n >\n <div\n className={classNames(\n styles.frameAround,\n 'absolute b--action-primary br3 bw1',\n {\n ba: isSelected,\n }\n )}\n />\n <div\n className={classNames(\n 'w-100 h-100 b--muted-4 br2 b z-1 c-muted-5 flex items-center overflow-hidden',\n {\n 'hover-b--muted-2': !isSelected && !isImpossible,\n ba: showBorders,\n }\n )}\n >\n <div\n className={classNames('absolute absolute--fill', {\n [styles.diagonalCross]: !isAvailable,\n })}\n />\n <div\n className={classNames({\n [`${styles.skuSelectorItemTextValue} c-on-base center pl5 pr5 z-1 t-body`]: !isImage,\n 'h-100': isImage,\n })}\n >\n {isImage && imageUrl ? (\n <img\n className={styles.skuSelectorItemImageValue}\n src={imageUrl}\n alt={imageLabel as string | undefined}\n />\n ) : (\n variationValue\n )}\n </div>\n </div>\n {discount > 0 && (\n <span className={`${styles.skuSelectorBadge} b`}>\n <FormattedNumber value={discount} style=\"percent\" />\n </span>\n )}\n </div>\n )\n}\n\nexport default memo(SelectorItem)\n\n```"
}
] |
code_store-on-localhost_ed302798
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SKUSelector/components/hooks/useEffectSkipMount.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useEffect, useRef, EffectCallback } from 'react'\n\nconst useEffectSkipMount = (func: EffectCallback, deps: any[]) => {\n const isFirstRender = useRef(true)\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false\n return\n }\n return func()\n }, deps)\n}\n\nexport default useEffectSkipMount\n\n```"
}
] |
code_store-on-localhost_a1fafa8e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/AutocompleteResults/queries/autocomplete.gql from the store-on-localhost 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-on-localhost_053b21de
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Newsletter/mutations/subscribeNewsletter.graphql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation subscribeNewsletter($email: String) {\n subscribeNewsletter(email: $email)\n}\n```"
}
] |
code_store-on-localhost_5c3ba63e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/CategoriesHighlights/components/CategoryCard.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport { Link } from '../../../../../../../vtex.render-runtime'\n\nimport { RECTANGULAR, SQUARED } from '../constants'\nimport rectangularPlaceholder from '../images/rectangular-placeholder.svg'\nimport squaredPlaceholder from '../images/squared-placeholder.svg'\n\nimport categoriesHighlights from '../categoriesHighlights.css'\n\n/**\n * CategoryCard is a component responsible to display an image of a category\n * and provides the link to the category specified by its name.\n */\nclass CategoryCard extends Component {\n static propTypes = {\n /** Name of the category */\n name: PropTypes.string.isRequired,\n /** Image of the category */\n image: PropTypes.string,\n /** Shape of the category card */\n shape: PropTypes.oneOf([RECTANGULAR, SQUARED]),\n }\n\n render() {\n const { name, image, shape } = this.props\n\n return (\n <div className={`${categoriesHighlights[`${shape}Card`]} shadow-1 ma1`}>\n {/* TODO: Redirect to the page of the category specified by its name */}\n\n <Link>\n {image ? (\n <img\n src={image}\n alt={name}\n className={`${categoriesHighlights[`${shape}CardImage`]}`}\n />\n ) : (\n <img\n src={\n shape == SQUARED ? squaredPlaceholder : rectangularPlaceholder\n }\n alt=\"\"\n className={`${categoriesHighlights[`${shape}CardImage`]}`}\n />\n )}\n </Link>\n </div>\n )\n }\n}\n\nexport default CategoryCard\n\n```"
}
] |
code_store-on-localhost_4dcf3089
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Share/constants/social.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const SOCIAL_TO_ENUM = {\n facebook: 'Facebook',\n whatsapp: 'WhatsApp',\n twitter: 'Twitter',\n telegram: 'Telegram',\n googleplus: 'Google+',\n email: 'E-mail',\n pinterest: 'Pinterest',\n}\n\nexport const SOCIAL_ENUM = Object.values(SOCIAL_TO_ENUM)\n\nexport const SOCIAL_ENUM_TO_COMPONENT = {\n [SOCIAL_TO_ENUM.facebook]: 'Facebook',\n [SOCIAL_TO_ENUM.twitter]: 'Twitter',\n [SOCIAL_TO_ENUM.telegram]: 'Telegram',\n [SOCIAL_TO_ENUM.googleplus]: 'GooglePlus',\n [SOCIAL_TO_ENUM.whatsapp]: 'Whatsapp',\n [SOCIAL_TO_ENUM.email]: 'Email',\n [SOCIAL_TO_ENUM.pinterest]: 'Pinterest',\n}\n\n```"
}
] |
code_store-on-localhost_40f596a1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/Share/components/SocialButton.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport * as ReactShare from 'react-share'\n\nimport { SOCIAL_TO_ENUM, SOCIAL_ENUM_TO_COMPONENT } from '../constants/social'\nimport styles from '../styles.css'\n\nexport default class SocialButton extends Component {\n static propTypes = {\n /** Share URL */\n url: PropTypes.string.isRequired,\n /** Message to be shared */\n message: PropTypes.string,\n /** Social Network Enum */\n socialEnum: PropTypes.string.isRequired,\n /** Button size in pixels */\n size: PropTypes.number,\n /** Classes to be applied to social button */\n buttonClass: PropTypes.string,\n /** Classes to be applied to icon of the button */\n iconClass: PropTypes.string,\n /** Image url to share in social medias */\n imageUrl: PropTypes.string,\n }\n\n static defaultProps = {\n size: 32,\n buttonClass: 'mh1 pointer outline-0 dim',\n }\n\n render() {\n const {\n url,\n message,\n size,\n socialEnum,\n buttonClass,\n iconClass,\n imageUrl,\n } = this.props\n const socialComponentName = SOCIAL_ENUM_TO_COMPONENT[socialEnum]\n const SocialComponent = ReactShare[`${socialComponentName}ShareButton`]\n const SocialIcon = ReactShare[`${socialComponentName}Icon`]\n const additionalProps = message && resolveMessageProp(message, socialEnum)\n\n const icon = (\n <SocialIcon\n round\n size={size}\n className={classNames(styles.shareSocialIcon, iconClass)}\n />\n )\n\n /* Pinterest requires imageUrl for the \"media\" prop, but\n * it might not be loaded yet */\n if (socialComponentName === SOCIAL_TO_ENUM.pinterest && !imageUrl) {\n return icon\n }\n\n return (\n <SocialComponent\n url={url}\n className={classNames(styles.shareSocialButton, buttonClass)}\n media={imageUrl}\n {...additionalProps}\n >\n {icon}\n </SocialComponent>\n )\n }\n}\n\nfunction resolveMessageProp(message, socialEnum) {\n const titlePropMessage = [\n SOCIAL_TO_ENUM.whatsapp,\n SOCIAL_TO_ENUM.twitter,\n SOCIAL_TO_ENUM.telegram,\n SOCIAL_TO_ENUM.pinterest,\n ]\n\n return titlePropMessage.includes(socialEnum)\n ? { title: message }\n : socialEnum === SOCIAL_TO_ENUM.facebook\n ? { quote: message }\n : { body: message }\n}\n\n```"
}
] |
code_store-on-localhost_62d95e4d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ReactPortal/components/Portal.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FunctionComponent } from 'react'\nimport ReactDOM from 'react-dom'\n\nexport interface Props {\n cover?: boolean\n target?: HTMLElement\n zIndex?: number\n}\n\nconst Portal: FunctionComponent<Props> = ({\n children,\n target,\n zIndex = 2147483647,\n cover,\n}) => {\n if (!target) {\n target = window && window.document && window.document.body\n }\n\n if (!target) {\n return null\n }\n\n return ReactDOM.createPortal(\n <div\n style={{\n position: 'fixed',\n top: 0,\n left: 0,\n ...(cover\n ? {\n bottom: 0,\n right: 0,\n pointerEvents: 'none',\n }\n : {}),\n zIndex,\n }}\n >\n <div style={{ pointerEvents: 'auto' }}>{children}</div>\n </div>,\n target\n )\n}\n\nexport default Portal\n\n```"
}
] |
code_store-on-localhost_12bce45b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductContext/typings/Context.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype Action<K, V = void> = V extends void ? { type: K } : { type: K } & V\n\ninterface ProductAndQuery {\n query: Record<string, any>\n product: MaybeProduct\n}\n\ntype GroupId = string\n\ninterface 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\ninterface BuyButtonContextState {\n clicked: boolean\n}\n\ninterface ProductContextState {\n selectedItem?: Item | null\n product: MaybeProduct\n selectedQuantity: number\n skuSelector: {\n isVisible: boolean\n areAllVariationsSelected: boolean\n }\n buyButton: BuyButtonContextState\n assemblyOptions: {\n items: Record<GroupId, AssemblyOptionItem[]>\n inputValues: Record<GroupId, InputValues>\n areGroupsValid: Record<GroupId, boolean>\n }\n}\n\ntype InputValues = Record<string, string>\n\ntype Actions =\n | Action<'SET_QUANTITY', { args: { quantity: number } }>\n | Action<\n 'SKU_SELECTOR_SET_VARIATIONS_SELECTED',\n { args: { allSelected: boolean } }\n >\n | Action<'SET_BUY_BUTTON_CLICKED', { args: { clicked: boolean } }>\n | Action<'SKU_SELECTOR_SET_IS_VISIBLE', { args: { isVisible: boolean } }>\n | Action<'SET_SELECTED_ITEM', { args: { item: Item | undefined | null } }>\n | Action<\n 'SET_ASSEMBLY_OPTIONS',\n {\n args: {\n groupId: string\n groupItems: AssemblyOptionItem[]\n groupInputValues: InputValues\n isValid: boolean\n }\n }\n >\n | Action<'SET_PRODUCT', { args: { product: MaybeProduct } }>\n\n```"
}
] |
code_store-on-localhost_aac8a4ac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductContext/typings/Product.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype Maybe<T> = T | null | undefined\n\ntype MaybeProduct = Maybe<Product>\n\ninterface Product {\n cacheId: string\n productName: string\n productId: string\n description: string\n titleTag: string\n metaTagDescription: string\n linkText: string\n productReference: string\n categoryId: string\n categoriesIds: string[]\n categories: string[]\n categoryTree: {\n id: string\n name: string\n href: string\n }[]\n brand: string\n brandId: string\n properties: {\n name: string\n values: string\n }[]\n specificationGroups: {\n name: string\n specifications: {\n name: string\n values: string[]\n }[]\n }[]\n items: Item[]\n skuSpecifications: SkuSpecification[]\n itemMetadata: {\n items: ItemMetadata[]\n priceTable: any[]\n }\n}\n\ninterface Item {\n itemId: string\n name: string\n nameComplete: string\n complementName: string\n ean: string\n referenceId: {\n Key: string\n Value: string\n }[]\n measurementUnit: string\n unitMultiplier: number\n images: {\n imageId: string\n imageLabel: string\n imageTag: string\n imageUrl: string\n imageText: string\n }[]\n videos: {\n videoUrl: string\n }[]\n sellers: Seller[]\n variations: {\n name: string\n values: string[]\n }[]\n productClusters: {\n id: string\n name: string\n }[]\n clusterHighlights: {\n id: string\n name: string\n }[]\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\ninterface Seller {\n sellerId: string\n sellerName: string\n addToCartLink: string\n sellerDefault: string\n commertialOffer: {\n discountHighlights: {\n name: string\n }[]\n teasers: {\n name: string\n }[]\n Price: number\n ListPrice: number\n PriceWithoutDiscount: number\n RewardValue: number\n PriceValidUntil: string\n AvailableQuantity: number\n Tax: number\n CacheVersionUsedToCallCheckout: string\n }\n}\n\ninterface ItemMetadata {\n items: {\n id: string\n name: string\n imageUrl: string\n seller: string\n assemblyOptions: {\n id: string\n name: string\n required: boolean\n inputValues: InputValue[]\n composition: Composition | null\n }\n }[]\n priceTable: {\n type: string\n values: {\n id: string\n assemblyId: string\n price: number | null\n }[]\n }[]\n}\n\ntype InputValue = TextInputValue | BooleanInputValue | OptionsInputValue\n\nenum InputValueType {\n 'TEXT' = 'TEXT',\n 'BOOLEAN' = 'BOOLEAN',\n 'OPTIONS' = 'OPTIONS',\n}\n\ninterface TextInputValue {\n type: InputValueType.TEXT\n defaultValue: ''\n label: string\n maxLength: number\n domain: null\n}\n\ninterface BooleanInputValue {\n type: InputValueType.BOOLEAN\n defaultValue: boolean\n label: string\n maxLength: null\n domain: null\n}\n\ninterface OptionsInputValue {\n type: InputValueType.OPTIONS\n defaultValue: string\n label: string\n maxLength: null\n domain: string[]\n}\n\ninterface Composition {\n minQuantity: number\n maxQuantity: number\n items: {\n id: string\n minQuantity: number\n maxQuantity: number\n priceTable: string\n seller: string\n initialQuantity: number\n }[]\n}\n\n```"
}
] |
code_store-on-localhost_ab08fd26
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductContext/reducer/index.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useReducer } from 'react'\nimport { path, find, propEq, compose, flip, gt, pathOr } from 'ramda'\nimport { getSelectedSKUFromQueryString } from '../modules/skuQueryString'\n\nconst defaultState: ProductContextState = {\n product: undefined,\n selectedItem: null,\n selectedQuantity: 1,\n skuSelector: {\n isVisible: false,\n areAllVariationsSelected: true,\n },\n buyButton: {\n clicked: false,\n },\n assemblyOptions: {\n items: {},\n inputValues: {},\n areGroupsValid: {},\n },\n}\n\nfunction reducer(\n state: ProductContextState,\n action: any\n): ProductContextState {\n switch (action.type) {\n case 'SET_QUANTITY': {\n const args = action.args || {}\n return {\n ...state,\n selectedQuantity: args.quantity,\n }\n }\n\n case 'SKU_SELECTOR_SET_VARIATIONS_SELECTED': {\n const args = action.args || {}\n return {\n ...state,\n skuSelector: {\n ...state.skuSelector,\n areAllVariationsSelected: args.allSelected,\n },\n }\n }\n\n case 'SET_BUY_BUTTON_CLICKED': {\n const args = action.args || {}\n return {\n ...state,\n buyButton: {\n ...state.buyButton,\n clicked: args.clicked,\n },\n }\n }\n\n case 'SKU_SELECTOR_SET_IS_VISIBLE': {\n const args = action.args || {}\n return {\n ...state,\n skuSelector: {\n ...state.skuSelector,\n isVisible: args.isVisible,\n },\n }\n }\n\n case 'SET_SELECTED_ITEM': {\n const args = action.args || {}\n return {\n ...state,\n selectedItem: args.item,\n }\n }\n\n case 'SET_ASSEMBLY_OPTIONS': {\n const {\n groupId = '',\n groupItems = [],\n groupInputValues = {},\n isValid = false,\n } = action.args || {}\n\n return {\n ...state,\n assemblyOptions: {\n ...state.assemblyOptions,\n inputValues: {\n ...state.assemblyOptions.inputValues,\n [groupId]: groupInputValues,\n },\n items: {\n ...state.assemblyOptions.items,\n [groupId]: groupItems,\n },\n areGroupsValid: {\n ...state.assemblyOptions.areGroupsValid,\n [groupId]: isValid,\n },\n },\n }\n }\n\n case 'SET_PRODUCT': {\n const args = action.args || {}\n const differentSlug =\n path(['product', 'linkText'], state) !==\n path(['product', 'linkText'], args)\n\n return {\n ...state,\n ...(differentSlug ? defaultState : {}),\n product: args.product,\n }\n }\n default:\n return state\n }\n}\n\nconst isSkuAvailable = compose<Seller, number, boolean>(\n flip(gt)(0),\n pathOr(0, ['commertialOffer', 'AvailableQuantity'])\n)\n\nconst findItemById = (id: string) => find<Item>(propEq<any, any>('itemId', id))\nfunction findAvailableProduct(item: Item) {\n return item.sellers.find(isSkuAvailable)\n}\n\nexport function getSelectedItem(skuId: string | undefined, items: Item[]) {\n return skuId\n ? findItemById(skuId)(items)\n : items.find(findAvailableProduct) || items[0]\n}\n\nfunction initReducer({ query, product }: ProductAndQuery) {\n const items = (product && product.items) || []\n return {\n ...defaultState,\n selectedItem: getSelectedItem(getSelectedSKUFromQueryString(query), items as any),\n product,\n }\n}\n\nexport const useProductReducer = ({ query, product }: ProductAndQuery) =>\n useReducer(reducer, { query, product }, initReducer)\n\n```"
}
] |
code_store-on-localhost_d898a696
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductContext/__tests__/ProductContextProvider.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-env jest */\nimport React, { useContext } from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { getProduct, getItem } from '../__mocks__/productMock'\nimport ProductContextProvider from '../ProductContextProvider'\nimport ProductContext from '../ProductContext'\nimport ProductDispatchContext from '../ProductDispatchContext'\nconst { useProductDispatch } = ProductDispatchContext\n\nconst ProductPageMock = () => {\n const { selectedItem, product, selectedQuantity } = useContext(ProductContext) as any\n return (\n <div>\n <div>Product Page</div>\n <div>Selected Item id: {selectedItem && selectedItem.itemId}</div>\n <div>Selected Item name: {selectedItem && selectedItem.name}</div>\n {product ? <div>product slug: {product && product.linkText}</div> : <div>no product</div>}\n <div>Selected Quantity: {selectedQuantity}</div>\n </div>\n )\n}\n\ndescribe('ProductContextProvider component', () => {\n const getProps = (customProps: Partial<ProductAndQuery>): ProductAndQuery => {\n const product = getProduct()\n const props = {\n product,\n query: {},\n ...customProps,\n }\n return props\n }\n\n const renderComponent = (customProps: Partial<ProductAndQuery> = {}) => {\n const component = render(\n <ProductContextProvider {...getProps(customProps)}>\n <ProductPageMock />\n </ProductContextProvider>\n )\n\n const { getByText, rerender } = component\n\n return {\n ...component,\n testNoProduct: () => getByText('no product'),\n getSelectedItemId: (item: { itemId: string }) => getByText(`Selected Item id: ${item.itemId}`),\n getSelectedItemName: (item: { name: string }) =>\n getByText(`Selected Item name: ${item.name}`),\n getProductSlug: (product: { linkText: string }) => getByText(`product slug: ${product.linkText}`),\n rerender: (newProps: any) => rerender(<ProductContextProvider {...newProps}>\n <ProductPageMock />\n </ProductContextProvider>)\n }\n }\n\n it('should render with product', () => {\n const product = getProduct()\n const { getProductSlug } = renderComponent()\n getProductSlug(product)\n })\n\n it('should render with no product and then switch', () => {\n const { getProductSlug, rerender, testNoProduct } = renderComponent({ product: undefined })\n\n testNoProduct()\n\n const product = getProduct()\n rerender({ product, query: {} })\n\n getProductSlug(product)\n })\n\n it('should switch items and reset state', () => {\n const product = getProduct()\n const {\n rerender,\n getSelectedItemId,\n getSelectedItemName,\n getProductSlug,\n } = renderComponent()\n\n const newItem = getItem('2')\n const newProduct = getProduct({\n items: [newItem],\n productId: '2',\n linkText: 'product-slug-2',\n titleTag: 'Product 2',\n productName: 'Product 2',\n })\n\n getSelectedItemId(product.items[0])\n getSelectedItemName(product.items[0])\n getProductSlug(product)\n\n rerender({ product: newProduct, query: {} })\n\n getSelectedItemId(newProduct.items[0])\n getSelectedItemName(newProduct.items[0])\n getProductSlug(newProduct)\n })\n\n it('should select first item with available quantity', async () => {\n const noQuantity = getItem('no quantity', 90, 0)\n const itemWithQuantity = getItem('Item with quantity', 90, 10)\n const otherItemWithQuantity = getItem('other item with quantity', 90, 10)\n const newProduct = getProduct({\n items: [noQuantity, noQuantity, itemWithQuantity, otherItemWithQuantity],\n })\n const { getSelectedItemId, getSelectedItemName } = renderComponent({\n product: newProduct,\n })\n\n getSelectedItemId(itemWithQuantity)\n getSelectedItemName(itemWithQuantity)\n })\n\n it('should switch items when changing query prop', async () => {\n const itemone = getItem('1', 90, 1)\n const itemtwo = getItem('2', 90, 10)\n const itemthree = getItem('3', 90, 10)\n const newProduct = getProduct({\n items: [itemone, itemtwo, itemthree],\n })\n const props = {\n product: newProduct,\n params: { slug: newProduct.linkText },\n productQuery: { product: newProduct, loading: false },\n }\n const {\n getSelectedItemId,\n getSelectedItemName,\n rerender,\n } = renderComponent(props)\n\n getSelectedItemId(itemone)\n getSelectedItemName(itemone)\n\n rerender({ product: newProduct, query: { skuId: itemtwo.itemId } })\n\n getSelectedItemId(itemtwo)\n getSelectedItemName(itemtwo)\n })\n\n it('should dispatch action with bad args and not break anything', () => {\n const BadComponent = () => {\n const dispatch = useProductDispatch()\n dispatch && dispatch({ type: 'SET_QUANTITY', quantity: 1 } as any)\n dispatch && dispatch({ type: 'SKU_SELECTOR_SET_VARIATIONS_SELECTED', quantity: 1 } as any)\n dispatch && dispatch({ type: 'SKU_SELECTOR_SET_IS_VISIBLE', quantity: 1 } as any)\n dispatch && dispatch({ type: 'SET_SELECTED_ITEM', quantity: 1 } as any)\n dispatch && dispatch({ type: 'SET_ASSEMBLY_OPTIONS', quantity: 1 } as any)\n dispatch && dispatch({ type: 'SET_PRODUCT', quantity: 1 } as any)\n return <div>Bad Component rendered OK</div>\n }\n\n const { getByText } = render(\n <ProductContextProvider {...getProps({})}>\n <BadComponent />\n </ProductContextProvider>\n )\n\n getByText('Bad Component rendered OK')\n })\n})\n\n```"
}
] |
code_store-on-localhost_5878e9d0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductContext/modules/skuQueryString.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface QueryParams {\n skuId?: string\n idsku?: string\n}\n\n// `idsku` querystring is to keep compatibility with Google Shopping integration\nexport const getSelectedSKUFromQueryString = (query: QueryParams) => query.skuId || query.idsku\n\n```"
}
] |
code_store-on-localhost_d0821b25
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/images/FacebookIcon.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\n/**\n * Profile icon component in svg\n */\nexport default class FacebookIcon extends Component {\n static propTypes = {\n /* Percentage size of the icon */\n size: PropTypes.number,\n }\n\n static defaultProps = {\n size: 20,\n }\n\n render() {\n const { size } = this.props\n return (\n <svg\n width={size}\n height={size}\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"88.428 12.828 107.543 207.085\"\n >\n <path\n d=\"M158.232 219.912v-94.461h31.707l4.747-36.813h-36.454V65.134c0-10.658 2.96-17.922 18.245-17.922l19.494-.009V14.278c-3.373-.447-14.944-1.449-28.406-1.449-28.106 0-47.348 17.155-47.348 48.661v27.149H88.428v36.813h31.788v94.461l38.016-.001z\"\n fill=\"#3c5a9a\"\n />\n </svg>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_7c7ca77e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/images/GoogleIcon.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\n/**\n * Profile icon component in svg\n */\nexport default class GoogleIcon extends Component {\n static propTypes = {\n /* Percentage size of the icon */\n size: PropTypes.number,\n }\n\n static defaultProps = {\n size: 20,\n }\n\n render() {\n const { size } = this.props\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n x=\"0px\"\n y=\"0px\"\n width={size}\n height={size}\n viewBox=\"0 0 48 48\"\n >\n <g id=\"surface1\">\n <path\n style={{ fill: '#FFC107' }}\n d=\"M 43.609375 20.082031 L 42 20.082031 L 42 20 L 24 20 L 24 28 L 35.304688 28 C 33.652344 32.65625 29.222656 36 24 36 C 17.371094 36 12 30.628906 12 24 C 12 17.371094 17.371094 12 24 12 C 27.058594 12 29.84375 13.152344 31.960938 15.039063 L 37.617188 9.382813 C 34.046875 6.054688 29.269531 4 24 4 C 12.953125 4 4 12.953125 4 24 C 4 35.046875 12.953125 44 24 44 C 35.046875 44 44 35.046875 44 24 C 44 22.660156 43.863281 21.351563 43.609375 20.082031 Z \"\n />\n <path\n style={{ fill: '#FF3D00' }}\n d=\"M 6.304688 14.691406 L 12.878906 19.511719 C 14.65625 15.109375 18.960938 12 24 12 C 27.058594 12 29.84375 13.152344 31.960938 15.039063 L 37.617188 9.382813 C 34.046875 6.054688 29.269531 4 24 4 C 16.316406 4 9.65625 8.335938 6.304688 14.691406 Z \"\n />\n <path\n style={{ fill: '#4CAF50' }}\n d=\"M 24 44 C 29.164063 44 33.859375 42.023438 37.410156 38.808594 L 31.21875 33.570313 C 29.210938 35.089844 26.714844 36 24 36 C 18.796875 36 14.382813 32.683594 12.71875 28.054688 L 6.195313 33.078125 C 9.503906 39.554688 16.226563 44 24 44 Z \"\n />\n <path\n style={{ fill: '#1976D2' }}\n d=\"M 43.609375 20.082031 L 42 20.082031 L 42 20 L 24 20 L 24 28 L 35.304688 28 C 34.511719 30.238281 33.070313 32.164063 31.214844 33.570313 C 31.21875 33.570313 31.21875 33.570313 31.21875 33.570313 L 37.410156 38.808594 C 36.972656 39.203125 44 34 44 24 C 44 22.660156 43.863281 21.351563 43.609375 20.082031 Z \"\n />\n </g>\n </svg>\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_a519e532
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/profile.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst getProfileFromQueryResponse = data => {\n if (!data || !data.getProfile || !data.getProfile.profile) return null\n\n const { email, firstName } = data.getProfile.profile\n if (!email) {\n return null\n }\n\n return {\n email,\n firstName,\n }\n}\n\nconst getProfileFromApiResponse = data => {\n if (!data || !data.namespaces) {\n return null\n }\n\n const { namespaces: { profile } = {} } = data\n if (!profile) {\n return null\n }\n\n const {\n email: { value: email } = { value: null },\n firstName: { value: firstName } = { value: null },\n } = profile\n\n if (!email) {\n return null\n }\n\n return {\n email,\n firstName,\n }\n}\n\nexport const getProfile = data => {\n if (!data) return null\n\n if (data.getSession) return getProfileFromQueryResponse(data)\n\n if (data.namespaces) return getProfileFromApiResponse(data)\n\n return null\n}\n\n```"
}
] |
code_store-on-localhost_bbec5cfc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/translate.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const translate = (id, intl) => {\n return intl.formatMessage({ id: `${id}` })\n}\n\n```"
}
] |
code_store-on-localhost_8a960f30
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/steps.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const steps = {\n LOGIN_OPTIONS: -1,\n EMAIL_VERIFICATION: 0,\n EMAIL_PASSWORD: 1,\n CODE_CONFIRMATION: 2,\n ACCOUNT_OPTIONS: 3,\n CREATE_PASSWORD: 4,\n}\n\n```"
}
] |
code_store-on-localhost_3c3ffac2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/format-string.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport Slugify from 'slugify'\n\nexport const truncateString = str => {\n const MAX_LENGTH = 7\n return str <= MAX_LENGTH ? str : str.substring(0, MAX_LENGTH).concat('...')\n}\n\nexport const slugify = string => Slugify(string, { replacement: '-', lower: true })\n\n```"
}
] |
code_store-on-localhost_e2c765b8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/format-check.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const isValidPassword = password => {\n const pattern = new RegExp(/(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)\n return pattern.test(password)\n}\n\nexport const isValidEmail = email => {\n // eslint-disable-next-line no-useless-escape\n const pattern = new RegExp(/^(([^<>()\\[\\]\\\\.,;:\\s@!\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@!\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/)\n return pattern.test(email)\n}\n\nexport const isValidAccessCode = code => {\n const pattern = new RegExp(/^[0-9]{6}$/)\n return pattern.test(code)\n}\n\n```"
}
] |
code_store-on-localhost_3633ab53
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/utils/set-cookie.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { compose, map, fromPairs, split, tail } from 'ramda'\nimport Cookies from 'js-cookie'\n/**\n * Set Cookie from the URL name=value and clean up the URL query params.\n * Used in the OAuth login.\n *\n * @param {String} url To set cookie and cleaned up.\n */\nexport const setCookie = (url) => {\n const { accountAuthCookieName, accountAuthCookieValue } = compose(\n fromPairs, map(split('=')), split('&'), tail\n )(url)\n if (accountAuthCookieName && accountAuthCookieValue) {\n Cookies.set(accountAuthCookieName, accountAuthCookieValue, { expires: 1, path: '/', secure: true })\n const cleanUrl = url.substring(0, url.indexOf('?'))\n window.history.replaceState({}, document.title, cleanUrl)\n window.location.assign(window.location.origin)\n }\n}\n\n```"
}
] |
code_store-on-localhost_f22f20f2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/LoginOptions.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport classNames from 'classnames'\nimport PropTypes from 'prop-types'\nimport React, { Component, Fragment } from 'react'\nimport { injectIntl } from 'react-intl'\nimport { ExtensionContainer } from '../../../../../vtex.render-runtime'\n\nimport Button from '../../Styleguide/Button'\n\nimport FacebookIcon from '../images/FacebookIcon'\nimport GoogleIcon from '../images/GoogleIcon'\nimport { translate } from '../utils/translate'\nimport FormTitle from './FormTitle'\nimport OAuth from './OAuth'\n\nimport styles from '../styles.css'\n\nconst PROVIDERS_ICONS = {\n Google: GoogleIcon,\n Facebook: FacebookIcon,\n}\n\n/** LoginOptions tab component. Displays a list of login options */\nclass LoginOptions extends Component {\n handleOptionClick = el => () => {\n this.props.onOptionsClick(el)\n }\n\n showOption = (option, optionName) => {\n const { isAlwaysShown, currentStep, options } = this.props\n return (\n options &&\n ((options[option] && !isAlwaysShown) || currentStep !== optionName)\n )\n }\n\n render() {\n const {\n className,\n title,\n fallbackTitle,\n options,\n loginCallback,\n intl,\n isAlwaysShown,\n providerPasswordButtonLabel,\n } = this.props\n\n const classes = classNames(styles.options, className, {\n [styles.optionsSticky]: isAlwaysShown,\n })\n\n return (\n <div className={classes}>\n <FormTitle>{title || translate(fallbackTitle, intl)}</FormTitle>\n <ul className={`${styles.optionsList} list pa0`}>\n <Fragment>\n {options.accessKeyAuthentication &&\n this.showOption(\n 'accessKeyAuthentication',\n 'store/loginOptions.emailVerification'\n ) && (\n <li className={`${styles.optionsListItem} mb3`}>\n <div className={classNames(styles.button, styles.accessCodeOptionBtn)}>\n <Button\n variation=\"secondary\"\n onClick={this.handleOptionClick(\n 'store/loginOptions.emailVerification'\n )}\n >\n <span>\n {translate(\n 'store/loginOptions.emailVerification',\n intl\n )}\n </span>\n </Button>\n </div>\n </li>\n )}\n {options.classicAuthentication &&\n this.showOption(\n 'classicAuthentication',\n 'store/loginOptions.emailAndPassword'\n ) && (\n <li className={`${styles.optionsListItem} mb3`}>\n <div className={classNames(styles.button, styles.emailPasswordOptionBtn)}>\n <Button\n variation=\"secondary\"\n onClick={this.handleOptionClick(\n 'store/loginOptions.emailAndPassword'\n )}\n >\n <span>\n {providerPasswordButtonLabel ||\n translate(\n 'store/loginOptions.emailAndPassword',\n intl\n )}\n </span>\n </Button>\n </div>\n </li>\n )}\n {options.providers &&\n options.providers.map(({ providerName }, index) => {\n const hasIcon = PROVIDERS_ICONS.hasOwnProperty(providerName)\n return (\n <li\n className={`${styles.optionsListItem} mb3`}\n key={`${providerName}-${index}`}\n >\n <OAuth\n provider={providerName}\n loginCallback={loginCallback}\n >\n {hasIcon\n ? React.createElement(\n PROVIDERS_ICONS[providerName],\n null\n )\n : null}\n </OAuth>\n </li>\n )\n })}\n </Fragment>\n <li\n className={`${styles.optionsListItem} ${styles.optionsListItemContainer} mb3`}\n >\n <ExtensionContainer id=\"container\" />\n </li>\n </ul>\n </div>\n )\n }\n}\n\nLoginOptions.propTypes = {\n /** Function to change de active tab */\n onOptionsClick: PropTypes.func.isRequired,\n /** Title that will be shown on top */\n title: PropTypes.string.isRequired,\n /** Fallback title that will be shown if there's no title */\n fallbackTitle: PropTypes.string.isRequired,\n /** List of options to be displayed */\n options: PropTypes.shape({\n accessKeyAuthentication: PropTypes.bool,\n classicAuthentication: PropTypes.bool,\n providers: PropTypes.arrayOf(\n PropTypes.shape({\n className: PropTypes.string,\n providerName: PropTypes.string,\n })\n ),\n }),\n /** Class of the root element */\n className: PropTypes.string,\n /** Whether this component is always rendered */\n isAlwaysShown: PropTypes.bool,\n /** Current option being displayed */\n currentStep: PropTypes.string,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n /** Password login button text */\n providerPasswordButtonLabel: PropTypes.string,\n}\n\nexport default injectIntl(LoginOptions)\n\n```"
}
] |
code_store-on-localhost_3767b027
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/Tooltip.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nimport styles from '../styles.css'\n\nexport default class Tooltip extends Component {\n render() {\n const { children, title, top } = this.props\n\n const classes = classNames(`${styles.tooltipContainer} pa5 br2 absolute z-max bg-near-black`, {\n [`${styles.tooltipContainerTop} mb2`]: top,\n [`${styles.tooltipContainerLeft} mr2`]: !top,\n })\n\n return (\n <div className={classes}>\n <div className=\"pa2\">\n {title &&\n <div className=\"mb3\">\n <span className=\"t-action b ttu c-on-base--inverted\">\n {title}\n </span>\n </div>\n }\n {children}\n </div>\n </div>\n )\n }\n}\n\nTooltip.propTypes = {\n /** Title to appear into the Tooltip */\n title: PropTypes.string,\n /** Children to appear inside the Tooltip */\n children: PropTypes.object.isRequired,\n /** Set the tooltip position */\n top: PropTypes.bool,\n}\n\n```"
}
] |
code_store-on-localhost_5a66d968
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/EmailVerification.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport AuthStateLazy from '../../VtexId/AuthStateLazy'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\nimport Input from '../../Styleguide/Input'\nimport Button from '../../Styleguide/Button'\n\nimport Form from './Form'\nimport FormError from './FormError'\nimport { translate } from '../utils/translate'\nimport { steps } from '../utils/steps'\nimport GoBackButton from './GoBackButton'\n\nimport styles from '../styles.css'\n\n/**\n * EmailVerification tab component.\n * Receive a email from an input and call the sendEmailVerification API\n */\nclass EmailVerification extends Component {\n static propTypes = {\n /** Next step */\n next: PropTypes.number.isRequired,\n /** Previous step */\n previous: PropTypes.number.isRequired,\n /** State that will send user to CreatePassword tab */\n isCreatePassword: PropTypes.bool.isRequired,\n /** Title to be displayed */\n title: PropTypes.string,\n /** Placeholder to email input */\n emailPlaceholder: PropTypes.string,\n /** Function to change de active tab */\n onStateChange: PropTypes.func.isRequired,\n /** Whether to display the back button */\n showBackButton: PropTypes.bool,\n }\n\n state = {\n isInvalidEmail: false,\n isUserBlocked: false,\n }\n\n handleOnSubmit = (event, email, validate, sendToken) => {\n event.preventDefault()\n if (!validate(email)) {\n this.setState({ isInvalidEmail: true })\n } else {\n sendToken()\n }\n }\n\n render() {\n const {\n title,\n intl,\n onStateChange,\n previous,\n isCreatePassword,\n showBackButton,\n emailPlaceholder,\n } = this.props\n const { isInvalidEmail, isUserBlocked } = this.state\n\n return (\n <Form\n className={`${styles.emailVerification} ${styles.emailForm} w-100`}\n title={title || translate('store/loginOptions.emailVerification', intl)}\n onSubmit={e => this.handleOnSubmit(e)}\n content={\n <Fragment>\n <div className={`${styles.inputContainer} ${styles.inputContainerEmail}`}>\n <AuthStateLazy.Email>\n {({ value, setValue }) => (\n <Input\n type=\"email\"\n name=\"email\"\n value={value || ''}\n onChange={e => setValue(e.target.value)}\n placeholder={\n emailPlaceholder ||\n translate('store/login.email.placeholder', intl)\n }\n />\n )}\n </AuthStateLazy.Email>\n </div>\n <FormError show={isInvalidEmail}>\n {translate('store/login.invalidEmail', intl)}\n </FormError>\n <FormError show={isUserBlocked}>\n {translate('store/login.userBlocked', intl)}\n </FormError>\n </Fragment>\n }\n footer={\n <Fragment>\n {(showBackButton || isCreatePassword) && (\n <GoBackButton\n onStateChange={onStateChange}\n changeTab={\n isCreatePassword ? {\n step: steps.EMAIL_PASSWORD,\n isCreatePassword: false,\n } : { step: previous }\n }\n />\n )}\n <div className={`${styles.sendButton} ml-auto`}>\n <AuthServiceLazy.SendAccessKey\n useNewSession\n onSuccess={() => {\n isCreatePassword\n ? onStateChange({\n step: steps.CREATE_PASSWORD,\n isCreatePassword: false,\n })\n : onStateChange({ step: this.props.next })\n }}\n onFailure={() => {\n this.setState({ isUserBlocked: true })\n }}\n >\n {({\n state: { email },\n loading,\n action: sendToken,\n validation: { validateEmail },\n }) => (\n <Button\n variation=\"primary\"\n size=\"small\"\n type=\"submit\"\n isLoading={loading}\n onClick={e =>\n this.handleOnSubmit(e, email, validateEmail, sendToken)\n }\n >\n <span className=\"t-small\">{translate('store/login.send', intl)}</span>\n </Button>\n )}\n </AuthServiceLazy.SendAccessKey>\n </div>\n </Fragment>\n }\n />\n )\n }\n}\n\nexport default injectIntl(EmailVerification)\n\n```"
}
] |
code_store-on-localhost_fd7b96f8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/OAuthAutoRedirect.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable react-hooks/exhaustive-deps */\nimport React, { useEffect } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport Spinner from '../../Styleguide/Spinner'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\n\nimport styles from '../styles.css'\n\nfunction OAuthAutoRedirect({ intl, provider, redirect }) {\n useEffect(() => {\n redirect()\n }, [])\n return (\n <div className={styles.oauthAutoRedirect}>\n <div className=\"w-100 flex flex-column pv5\">\n <p className=\"tc ph4\">\n {intl.formatMessage(\n {\n id: 'store/login.autoRedirect.message',\n },\n { provider }\n )}\n </p>\n <div className={`self-center c-emphasis ${styles.oauthAutoRedirectLoading}`}>\n <Spinner color=\"currentColor\" size={24} />\n </div>\n </div>\n </div>\n )\n}\nOAuthAutoRedirect.propTypes = {\n redirect: PropTypes.func.isRequired,\n provider: PropTypes.string.isRequired,\n loading: PropTypes.bool,\n}\n\nfunction Wrapper({ provider, ...props }) {\n return (\n <AuthServiceLazy.OAuthRedirect useNewSession provider={provider}>\n {({ loading, action: redirectToOAuthPage }) => (\n <OAuthAutoRedirect\n {...props}\n loading={loading}\n provider={provider}\n redirect={redirectToOAuthPage}\n />\n )}\n </AuthServiceLazy.OAuthRedirect>\n )\n}\nWrapper.propTypes = {\n provider: PropTypes.string.isRequired,\n}\n\nexport default injectIntl(Wrapper)\n\n```"
}
] |
code_store-on-localhost_c046d94b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/Loading.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport Spinner from '../../Styleguide/Spinner'\n\nimport styles from '../styles.css'\n\nfunction Loading() {\n return (\n <div className=\"bg-base relative\">\n <div className={styles.loading}>\n <div className=\"w-100 tc c-emphasis pv8\">\n <Spinner color=\"currentColor\" size={32} />\n </div>\n </div>\n </div>\n )\n}\n\nexport default Loading\n\n```"
}
] |
code_store-on-localhost_d63216c2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/FormTitle.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport styles from '../styles.css'\n\nexport default function FormTitle({ children }) {\n return (\n <h3 className={`${styles.formTitle} t-body v-mid ttu tc relative pv2 ph3 br2`}>\n {children}\n </h3>\n )\n}\n\nFormTitle.propTypes = {\n children: PropTypes.node,\n}\n\n\n```"
}
] |
code_store-on-localhost_df75e7e6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/CodeConfirmation.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport Input from '../../Styleguide/Input'\nimport Button from '../../Styleguide/Button'\nimport AuthStateLazy from '../../VtexId/AuthStateLazy'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\n\nimport { translate } from '../utils/translate'\nimport { isValidAccessCode } from '../utils/format-check'\nimport Form from './Form'\nimport FormError from './FormError'\nimport GoBackButton from './GoBackButton'\n\nimport styles from '../styles.css'\n\n/** CodeConfirmation tab component. Receive the code from an input and call the signIn API */\nclass CodeConfirmation extends Component {\n constructor(props) {\n super(props)\n this.state = {\n isInvalidCode: false,\n isWrongCredentials: false,\n }\n }\n\n handleSuccess = () => this.props.loginCallback()\n\n handleFailure = err => {\n err.code === 'WrongCredentials'\n ? this.setState({ isWrongCredentials: true })\n : console.error(err)\n }\n\n handleOnSubmit = (event, confirmToken, token) => {\n event.preventDefault()\n if (!isValidAccessCode(token)) {\n this.setState({ isInvalidCode: true })\n } else {\n confirmToken()\n }\n }\n\n render() {\n const { intl, onStateChange, previous, accessCodePlaceholder } = this.props\n const { isInvalidCode, isWrongCredentials } = this.state\n\n return (\n <Form\n className={`${styles.codeConfirmation} w-100`}\n title={translate('store/login.accessCodeTitle', intl)}\n onSubmit={e => this.handleOnSubmit(e)}\n content={\n <Fragment>\n <div className={`${styles.inputContainer} ${styles.inputContainerAccessCode} pv3`}>\n <AuthStateLazy.Token>\n {({ value, setValue }) => (\n <Input\n token\n name=\"token\"\n value={value || ''}\n onChange={e => {\n setValue(e.target.value)\n this.setState({ isInvalidCode: false })\n }}\n placeholder={\n accessCodePlaceholder ||\n translate('store/login.accessCode.placeholder', intl)\n }\n />\n )}\n </AuthStateLazy.Token>\n </div>\n <FormError show={isInvalidCode}>\n {translate('store/login.invalidCode', intl)}\n </FormError>\n <FormError show={isWrongCredentials}>\n {translate('store/login.wrongCredentials', intl)}\n </FormError>\n </Fragment>\n }\n footer={\n <Fragment>\n <GoBackButton\n onStateChange={onStateChange}\n changeTab={{ step: previous }}\n />\n <div className={`${styles.sendButton} ml-auto`}>\n <AuthServiceLazy.LoginWithAccessKey\n onSuccess={this.handleSuccess}\n onFailure={this.handleFailure}\n >\n {({ state: { token }, loading, action: confirmToken }) => (\n <Button\n variation=\"primary\"\n size=\"small\"\n type=\"submit\"\n onClick={e => this.handleOnSubmit(e, confirmToken, token)}\n isLoading={loading}\n >\n <span className=\"t-small\">\n {translate('store/login.confirm', intl)}\n </span>\n </Button>\n )}\n </AuthServiceLazy.LoginWithAccessKey>\n </div>\n </Fragment>\n }\n />\n )\n }\n}\n\nCodeConfirmation.propTypes = {\n /** Next step */\n next: PropTypes.number.isRequired,\n /** Previous step */\n previous: PropTypes.number.isRequired,\n /** Function to change de active tab */\n onStateChange: PropTypes.func.isRequired,\n /** Placeholder to access code input */\n accessCodePlaceholder: PropTypes.string,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n}\n\nexport default injectIntl(CodeConfirmation)\n\n```"
}
] |
code_store-on-localhost_6a78a98c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/LoginContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Suspense } from 'react'\n\nimport { compose, path } from 'ramda'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport { graphql } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\nimport { withSession, withRuntimeContext } from '../../../../../vtex.render-runtime'\n\nimport Loading from './Loading'\nimport LoginOptions from './LoginOptions'\nimport AccountOptions from './AccountOptions'\nimport EmailAndPassword from './EmailAndPassword'\nimport CodeConfirmation from './CodeConfirmation'\nimport RecoveryPassword from './RecoveryPassword'\nimport EmailVerification from './EmailVerification'\nimport OAuthAutoRedirect from './OAuthAutoRedirect'\n\nimport { steps } from '../utils/steps'\nimport { setCookie } from '../utils/set-cookie'\n\n// import { LoginSchema } from '../schema'\nimport { LoginPropTypes } from '../propTypes'\nimport { getProfile } from '../utils/profile'\n\nimport AuthStateLazy from '../../VtexId/AuthStateLazy'\nimport { SELF_APP_NAME_AND_VERSION } from '../common/global'\nimport { loader } from 'graphql.macro'\n\n\nimport styles from '../styles.css'\n\nconst session = loader('../../StoreResources/queries/session.gql')\n\nconst STEPS = [\n /* eslint-disable react/display-name, react/prop-types */\n (props, state, func, isOptionsMenuDisplayed) => {\n return style => (\n <div style={style} key={0}>\n <EmailVerification\n next={steps.CODE_CONFIRMATION}\n previous={steps.LOGIN_OPTIONS}\n isCreatePassword={state.isCreatePassword}\n title={props.accessCodeTitle}\n emailPlaceholder={props.emailPlaceholder}\n onStateChange={func}\n showBackButton={!isOptionsMenuDisplayed}\n />\n </div>\n )\n },\n (props, state, func, isOptionsMenuDisplayed) => {\n return style => (\n <div style={style} key={1}>\n <EmailAndPassword\n next={steps.ACCOUNT_OPTIONS}\n previous={steps.LOGIN_OPTIONS}\n title={props.emailAndPasswordTitle}\n emailPlaceholder={props.emailPlaceholder}\n passwordPlaceholder={props.passwordPlaceholder}\n showPasswordVerificationIntoTooltip={\n props.showPasswordVerificationIntoTooltip\n }\n onStateChange={func}\n showBackButton={!isOptionsMenuDisplayed}\n loginCallback={props.loginCallback}\n identifierPlaceholder={props.hasIdentifierExtension ? props.identifierPlaceholder : ''}\n invalidIdentifierError={props.hasIdentifierExtension ? props.invalidIdentifierError : ''}\n />\n </div>\n )\n },\n (props, state, func) => {\n return style => (\n <div style={style} key={2}>\n <CodeConfirmation\n next={steps.ACCOUNT_OPTIONS}\n previous={steps.EMAIL_VERIFICATION}\n accessCodePlaceholder={props.accessCodePlaceholder}\n onStateChange={func}\n loginCallback={props.loginCallback}\n />\n </div>\n )\n },\n () => {\n return style => (\n <div style={style} key={3}>\n <AccountOptions />\n </div>\n )\n },\n (props, state, func) => {\n return style => (\n <div style={style} key={4}>\n <RecoveryPassword\n next={steps.ACCOUNT_OPTIONS}\n previous={steps.EMAIL_PASSWORD}\n passwordPlaceholder={props.passwordPlaceholder}\n showPasswordVerificationIntoTooltip={\n props.showPasswordVerificationIntoTooltip\n }\n accessCodePlaceholder={props.accessCodePlaceholder}\n onStateChange={func}\n loginCallback={props.loginCallback}\n />\n </div>\n )\n },\n]\n\nclass LoginContent extends Component {\n static propTypes = {\n /** User profile information */\n profile: PropTypes.shape({}),\n /** Which screen option will renderize */\n isInitialScreenOptionOnly: PropTypes.bool,\n /** Step that will be render first */\n defaultOption: PropTypes.number,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n /** Runtime context. */\n runtime: PropTypes.shape({\n navigate: PropTypes.func,\n page: PropTypes.string,\n history: PropTypes.shape({\n location: PropTypes.shape({\n pathname: PropTypes.string,\n search: PropTypes.string,\n }),\n }),\n }),\n /* Reused props */\n optionsTitle: LoginPropTypes.optionsTitle,\n emailAndPasswordTitle: LoginPropTypes.emailAndPasswordTitle,\n accessCodeTitle: LoginPropTypes.accessCodePlaceholder,\n emailPlaceholder: LoginPropTypes.emailPlaceholder,\n passwordPlaceholder: LoginPropTypes.passwordPlaceholder,\n accessCodePlaceholder: LoginPropTypes.accessCodePlaceholder,\n showPasswordVerificationIntoTooltip:\n LoginPropTypes.showPasswordVerificationIntoTooltip,\n providerPasswordButtonLabel: PropTypes.string,\n hasIdentifierExtension: PropTypes.bool,\n identifierPlaceholder: PropTypes.string,\n invalidIdentifierError: PropTypes.string,\n }\n\n static defaultProps = {\n isInitialScreenOptionOnly: true,\n defaultOption: 0,\n optionsTitle: '',\n }\n\n static contextTypes = {\n patchSession: PropTypes.func,\n }\n\n state = {\n isOnInitialScreen: !this.props.profile,\n isCreatePassword: false,\n step: this.props.defaultOption,\n email: '',\n password: '',\n code: '',\n }\n\n get returnUrl() {\n const {\n runtime: {\n page,\n history: {\n location: { pathname, search },\n },\n },\n } = this.props\n const currentUrl = page !== 'store.login' ? `${pathname}${search}` : '/'\n return path(['query', 'returnUrl'], this.props) || currentUrl\n }\n\n componentDidMount() {\n if (window.location.href.indexOf('accountAuthCookieName') > 0) {\n setCookie(window.location.href)\n }\n }\n\n get shouldRenderLoginOptions() {\n return this.props.isInitialScreenOptionOnly\n ? this.state.isOnInitialScreen\n : true\n }\n\n get shouldRenderForm() {\n if (this.props.profile) {\n return true\n }\n\n return (\n !this.props.isInitialScreenOptionOnly || !this.state.isOnInitialScreen\n )\n }\n\n shouldRedirectToOAuth = loginOptions => {\n if (!loginOptions) return [false, null]\n const { accessKey, oAuthProviders, password } = loginOptions\n const { runtime } = this.props\n if (runtime && runtime.query && runtime.query.oAuthRedirect) {\n const redirectProvider =\n oAuthProviders &&\n oAuthProviders.find(provider => provider.providerName === runtime.query.oAuthRedirect)\n if (redirectProvider) {\n return [true, redirectProvider]\n }\n }\n if (accessKey || password) return [false, null]\n if (!oAuthProviders || oAuthProviders.length !== 1) return [false, null]\n return [true, oAuthProviders[0]]\n }\n\n handleUpdateState = state => {\n if (state.hasOwnProperty('step')) {\n if (state.step === -1) {\n state.step = 0\n state.isOnInitialScreen = true\n } else if (state.step !== this.props.defaultOption) {\n state.isOnInitialScreen = false\n }\n }\n\n this.setState({ ...state })\n }\n\n handleOptionsClick = option => {\n let nextStep\n\n if (option === 'store/loginOptions.emailVerification') {\n nextStep = 0\n } else if (option === 'store/loginOptions.emailAndPassword') {\n nextStep = 1\n }\n\n this.setState({\n step: nextStep,\n isOnInitialScreen: false,\n isCreatePassword: false,\n })\n }\n\n redirect = () => {\n this.props.runtime.navigate({\n to: this.returnUrl,\n fallbackToWindowLocation: true,\n })\n }\n\n /**\n * Action after login success. If loginCallback isn't\n * a prop, it will call a root page redirect as default.\n */\n onLoginSuccess = () => {\n const { loginCallback } = this.props\n return this.context.patchSession().then(() => {\n if (loginCallback) {\n loginCallback()\n } else {\n // the use of location.assign here, instead of\n // the redirect method, is because on CSR the\n // components using authentication and relying\n // on the session cookie haven't been updated yet,\n // so the refresh is intentional.\n window.location.assign(\n `/api/vtexid/pub/authentication/redirect?returnUrl=${encodeURIComponent(\n this.returnUrl\n )}`\n )\n }\n })\n }\n\n renderChildren = style => {\n const {\n profile,\n isInitialScreenOptionOnly,\n optionsTitle,\n defaultOption,\n providerPasswordButtonLabel,\n } = this.props\n const { isOnInitialScreen } = this.state\n\n let step = this.state.step\n if (profile) {\n step = steps.ACCOUNT_OPTIONS\n } else if (isOnInitialScreen) {\n step = defaultOption\n }\n\n return (\n <div style={style} key={0}>\n <AuthStateLazy.IdentityProviders>\n {({ value: options }) => {\n const [\n shouldRedirectToOauth,\n oauthProvider,\n ] = this.shouldRedirectToOAuth(options)\n return shouldRedirectToOauth && oauthProvider ? (\n <OAuthAutoRedirect provider={oauthProvider.providerName} />\n ) : (\n <LoginOptions\n page=\"login-options\"\n fallbackTitle=\"store/loginOptions.title\"\n title={optionsTitle}\n options={{\n accessKeyAuthentication: options.accessKey,\n classicAuthentication: options.password,\n providers: options.oAuthProviders,\n }}\n currentStep={\n step === 0\n ? 'store/loginOptions.emailVerification'\n : 'store/loginOptions.emailAndPassword'\n }\n isAlwaysShown={!isInitialScreenOptionOnly}\n onOptionsClick={this.handleOptionsClick}\n loginCallback={this.onLoginSuccess}\n providerPasswordButtonLabel={providerPasswordButtonLabel}\n />\n )\n }}\n </AuthStateLazy.IdentityProviders>\n </div>\n )\n }\n\n render() {\n const {\n profile,\n isInitialScreenOptionOnly,\n defaultOption,\n session,\n } = this.props\n\n const { isOnInitialScreen } = this.state\n\n // Check if the user is already logged and redirect to the return URL if it didn't receive\n // the profile by the props and current endpoint are /login, if receive it, should render the account options.\n if (getProfile(session) && !profile) {\n if (window.location.pathname.includes('/login')) {\n this.redirect()\n }\n }\n\n let step = this.state.step\n if (profile) {\n step = steps.ACCOUNT_OPTIONS\n } else if (isOnInitialScreen) {\n step = defaultOption\n }\n\n const renderForm = STEPS[step](\n {\n ...this.props,\n loginCallback: this.onLoginSuccess,\n },\n this.state,\n this.handleUpdateState,\n this.shouldRenderLoginOptions\n )\n\n const className = classNames(\n `${styles.content} flex relative bg-base justify-around overflow-visible pa4 center`,\n (this.shouldRenderForm && this.shouldRenderLoginOptions) ? 'items-start-ns' : 'items-baseline-ns',\n {\n [styles.contentInitialScreen]: this.state.isOnInitialScreen,\n [`${styles.contentAlwaysWithOptions} mw6-ns flex-column-reverse items-center flex-row-ns`]: !isInitialScreenOptionOnly,\n 'items-baseline': isInitialScreenOptionOnly,\n }\n )\n\n const formClassName = classNames(styles.contentForm, 'dn ph4 pb6', {\n [`${styles.contentFormVisible} db `]: this.shouldRenderForm,\n })\n\n return (\n <AuthStateLazy skip={!!profile} scope=\"STORE\" parentAppId={SELF_APP_NAME_AND_VERSION} returnUrl={this.returnUrl}>\n {({ loading }) => (\n loading ? (\n <div data-testid=\"loading-session\">\n <Loading />\n </div>\n ) : (\n <div className={className}>\n {!profile && this.shouldRenderLoginOptions && !loading\n ? this.renderChildren()\n : null}\n <div className={formClassName}>\n {this.shouldRenderForm && renderForm ? (\n /** If it renders both the form and the menu, wrap the\n * form in a Suspense, so it doesn't hide the options \n * while it's loading */\n this.shouldRenderLoginOptions ? ( \n <Suspense fallback={<Loading />}>\n {renderForm()}\n </Suspense>\n ) : renderForm()\n ) : null}\n </div>\n </div>\n )\n )}\n </AuthStateLazy>\n )\n }\n}\n\nconst config = {\n name: 'session',\n options: () => ({ ssr: false, fetchPolicy: 'no-cache' }),\n}\n\nconst content = withSession()(\n compose(\n injectIntl,\n graphql(session, config)\n )(LoginContent)\n)\n\nexport default withRuntimeContext(content)\n\n```"
}
] |
code_store-on-localhost_31251681
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/GoBackButton.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport ButtonWithIcon from '../../Styleguide/ButtonWithIcon'\nimport { ExtensionPoint, useChildBlock } from '../../../../../vtex.render-runtime'\nimport IconArrowBack from '../../StoreIcons/IconArrowBack'\n\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport { translate } from '../utils/translate'\nimport styles from '../styles.css'\n\nconst Arrow = () => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-arrow-back' }))\n\n return hasIconBlock ? (\n <ExtensionPoint id=\"icon-arrow-back\" size={10} viewBox=\"0 0 16 11\" />\n ) : (\n <IconArrowBack size={10} viewBox=\"0 0 16 11\" />\n )\n}\n\nclass GoBackButton extends Component {\n static propTypes = {\n /** Function to change the active tab */\n onStateChange: PropTypes.func,\n /** Data that change the active tab */\n changeTab: PropTypes.object,\n }\n\n render() {\n const { onStateChange, intl, changeTab } = this.props\n return (\n <Fragment>\n <div className={styles.backButton}>\n <ButtonWithIcon\n icon={<Arrow />}\n iconPosition=\"left\"\n variation=\"tertiary\"\n size=\"small\"\n onClick={() => onStateChange(changeTab)}\n >\n <span className=\"t-small ml2\">\n {translate('store/login.goBack', intl)}\n </span>\n </ButtonWithIcon>\n </div>\n </Fragment>\n )\n }\n}\nexport default injectIntl(GoBackButton)\n\n```"
}
] |
code_store-on-localhost_e85b2dfb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/FormError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport styles from '../styles.css'\n\nexport default function FormError({ children, show }) {\n if (!show) {\n return null\n }\n\n return (\n <div className={`${styles.formError} bg-danger--faded t-small tc pa1 mv1 mh0`}>\n {children}\n </div>\n )\n}\n\nFormError.defaultProps = {\n show: false,\n}\n\nFormError.propTypes = {\n children: PropTypes.node,\n show: PropTypes.bool,\n}\n\n```"
}
] |
code_store-on-localhost_3685f214
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/Popover.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport styles from '../styles.css'\n\nconst Popover = ({ children, mirrorTooltipToRight }) => (\n <div\n className={`${styles.box} z-max absolute`}\n style={mirrorTooltipToRight ? { left: 50 } : { right: -50 }}\n >\n <div\n className={`${styles.arrowUp} absolute top-0 ${\n mirrorTooltipToRight ? 'left-0 ml3' : 'right-0 mr3'\n } shadow-3 bg-base rotate-45 h2 w2`}\n />\n <div className={`${styles.contentContainer} shadow-3 mt3`}>{children}</div>\n </div>\n)\n\nexport default Popover\n\n```"
}
] |
code_store-on-localhost_ff1154c8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/PasswordInput.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport Input from '../../Styleguide/Input'\nimport IconEyeSight from '../../StoreIcons/IconEyeSight'\nimport { ExtensionPoint, useChildBlock } from '../../../../../vtex.render-runtime'\n\nimport { translate } from '../utils/translate'\nimport PasswordValidationContent from './PasswordValidationContent'\nimport TooltipVerification from './TooltipVerification'\n\nconst SuffixIcon = ({ handleEyeIcon, showPassword }) => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-eye-sight' }))\n\n return (\n <span className=\"pointer\" onClick={handleEyeIcon}>\n {hasIconBlock ? (\n <ExtensionPoint\n id=\"icon-eye-sight\"\n type=\"filled\"\n state={showPassword ? 'off' : 'on'}\n size={16}\n />\n ) : (\n <IconEyeSight\n type=\"filled\"\n state={showPassword ? 'off' : 'on'}\n size={16}\n />\n )}\n </span>\n )\n}\n\nclass PasswordInput extends Component {\n constructor(props) {\n super(props)\n this.state = {\n showVerification: false,\n showPassword: false,\n }\n this.timeout = 0\n }\n\n handleEyeIcon = () =>\n this.setState({ showPassword: !this.state.showPassword })\n\n handlePasswordChange = event => {\n const lowerCaseLetters = /[a-z]/g\n const upperCaseLetters = /[A-Z]/g\n const numbers = /[0-9]/g\n\n const value = event.target.value\n\n if (this.timeout) {\n clearTimeout(this.timeout)\n }\n\n this.timeout = setTimeout(() => {\n this.setState({\n containsLowerLetter:\n value.length > 0 ? value.match(lowerCaseLetters) : undefined,\n containsUpperLetter:\n value.length > 0 ? value.match(upperCaseLetters) : undefined,\n containsNumber: value.length > 0 ? value.match(numbers) : undefined,\n atLeastEightCharacteres:\n value.length > 0 ? value.length >= 8 : undefined,\n })\n }, 300)\n\n this.props.onStateChange({ password: value })\n }\n\n render() {\n const {\n showVerification,\n containsLowerLetter,\n containsUpperLetter,\n containsNumber,\n atLeastEightCharacteres,\n showPassword,\n } = this.state\n\n const { intl, password, showPasswordVerificationIntoTooltip } = this.props\n\n const fields = [\n {\n id: 0,\n prefix: 'ABC',\n label: translate('store/login.password.uppercaseLetter', intl),\n valid: containsUpperLetter,\n },\n {\n id: 1,\n prefix: 'abc',\n label: translate('store/login.password.lowercaseLetter', intl),\n valid: containsLowerLetter,\n },\n {\n id: 2,\n prefix: '123',\n label: translate('store/login.password.number', intl),\n valid: containsNumber,\n },\n {\n id: 3,\n prefix: '***',\n label: translate('store/login.password.eightCharacteres', intl),\n valid: atLeastEightCharacteres,\n },\n ]\n\n return (\n <div className=\"relative\">\n <Input\n type={`${showPassword ? 'text' : 'password'}`}\n value={password}\n onChange={this.handlePasswordChange}\n placeholder={\n this.props.placeholder ||\n translate('store/login.password.placeholder', intl)\n }\n onBlur={() =>\n this.setState({\n showVerification: !showPasswordVerificationIntoTooltip,\n })\n }\n onFocus={() => this.setState({ showVerification: true })}\n suffixIcon={\n <SuffixIcon\n showPassword={showPassword}\n handleEyeIcon={this.handleEyeIcon}\n />\n }\n />\n {showVerification &&\n (!showPasswordVerificationIntoTooltip ? (\n <div className=\"pa2\">\n <PasswordValidationContent fields={fields} />\n </div>\n ) : (\n <TooltipVerification fields={fields} />\n ))}\n </div>\n )\n }\n}\n\nPasswordInput.propTypes = {\n /** Password set on state */\n password: PropTypes.string.isRequired,\n /** Placeholder to appear into the input */\n placeholder: PropTypes.string.isRequired,\n /** Set the type of password verification ui */\n showPasswordVerificationIntoTooltip: PropTypes.bool,\n /** Function to change de active tab */\n onStateChange: PropTypes.func.isRequired,\n}\n\nexport default injectIntl(PasswordInput)\n\n```"
}
] |
code_store-on-localhost_9a6e98cc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/OAuth.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport Button from '../../Styleguide/Button'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\n\nimport { translate } from '../utils/translate'\nimport styles from '../styles.css'\n\n// Component that shows account options to the user.\nimport className from 'classnames'\n\nconst styleByProviderName = {\n Facebook: styles.facebookOptionBtn,\n Google: styles.googleOptionBtn,\n}\n\nclass OAuth extends Component {\n static propTypes = {\n /** Name of the Provider to proceed with the Authentication */\n provider: PropTypes.string,\n /** Actual button */\n children: PropTypes.node,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n }\n\n render() {\n const { intl, children, provider, loginCallback } = this.props\n return (\n <div className={className(styles.button, styles.buttonSocial, styleByProviderName[provider] || styles.customOAuthOptionBtn)}>\n <AuthServiceLazy.OAuthPopup useNewSession provider={provider} onSuccess={() => loginCallback()}>\n {({ loading, action: openOAuthPopup }) => (\n <Button\n isLoading={loading}\n variation=\"tertiary\"\n onClick={openOAuthPopup}\n >\n {children}\n <span className={`t-action--small ${styles.oauthLabel} relative normal`}>\n {translate('store/loginOptions.oAuth', intl)}\n <span className={`${styles.oauthProvider} b ml2`}>{provider}</span>\n </span>\n </Button>\n )}\n </AuthServiceLazy.OAuthPopup>\n </div>\n )\n }\n}\n\nexport default injectIntl(OAuth)\n\n```"
}
] |
code_store-on-localhost_0574c2d1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/OutsideClickHandler.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nconst DISPLAY = {\n BLOCK: 'block',\n FLEX: 'flex',\n INLINE: 'inline',\n INLINE_BLOCK: 'inline-block',\n CONTENTS: 'contents',\n}\n\nconst propTypes = {\n children: PropTypes.node.isRequired,\n onOutsideClick: PropTypes.func.isRequired,\n disabled: PropTypes.bool,\n useCapture: PropTypes.bool,\n display: PropTypes.oneOf(Object.values(DISPLAY)),\n}\n\nconst defaultProps = {\n disabled: false,\n\n // `useCapture` is set to true by default so that a `stopPropagation` in the\n // children will not prevent all outside click handlers from firing - maja\n useCapture: true,\n display: DISPLAY.BLOCK,\n}\n\nexport default class OutsideClickHandler extends React.Component {\n constructor(...args) {\n super(...args)\n\n this.onMouseDown = this.onMouseDown.bind(this)\n this.onMouseUp = this.onMouseUp.bind(this)\n this.setChildNodeRef = this.setChildNodeRef.bind(this)\n }\n\n componentDidMount() {\n const { disabled, useCapture } = this.props\n\n if (!disabled) this.addMouseDownEventListener(useCapture)\n }\n\n componentDidUpdate({ disabled: prevDisabled }) {\n const { disabled, useCapture } = this.props\n if (prevDisabled !== disabled) {\n if (disabled) {\n this.removeEventListeners()\n } else {\n this.addMouseDownEventListener(useCapture)\n }\n }\n }\n\n componentWillUnmount() {\n this.removeEventListeners()\n }\n\n // Use mousedown/mouseup to enforce that clicks remain outside the root's\n // descendant tree, even when dragged. This should also get triggered on\n // touch devices.\n onMouseDown(e) {\n const { useCapture } = this.props\n\n const isDescendantOfRoot =\n this.childNode && this.childNode.contains(e.target)\n if (!isDescendantOfRoot) {\n document.removeEventListener('mouseup', this.onMouseUp, { useCapture })\n document.addEventListener('mouseup', this.onMouseUp, { useCapture })\n }\n }\n\n // Use mousedown/mouseup to enforce that clicks remain outside the root's\n // descendant tree, even when dragged. This should also get triggered on\n // touch devices.\n onMouseUp(e) {\n const { onOutsideClick, useCapture } = this.props\n\n const isDescendantOfRoot =\n this.childNode && this.childNode.contains(e.target)\n document.removeEventListener('mouseup', this.onMouseUp, { useCapture })\n\n if (!isDescendantOfRoot) {\n onOutsideClick(e)\n }\n }\n\n setChildNodeRef(ref) {\n this.childNode = ref\n }\n\n addMouseDownEventListener(useCapture) {\n document.addEventListener('mousedown', this.onMouseDown, { useCapture })\n }\n\n removeEventListeners() {\n const { useCapture } = this.props\n document.removeEventListener('mousedown', this.onMouseDown, { useCapture })\n document.removeEventListener('mouseup', this.onMouseUp, { useCapture })\n }\n\n render() {\n const { children, display } = this.props\n\n return (\n <div\n ref={this.setChildNodeRef}\n style={\n display !== DISPLAY.BLOCK && Object.values(DISPLAY).includes(display)\n ? { display }\n : undefined\n }\n >\n {children}\n </div>\n )\n }\n}\n\nOutsideClickHandler.propTypes = propTypes\nOutsideClickHandler.defaultProps = defaultProps\n\n```"
}
] |
code_store-on-localhost_a3c572ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/PasswordValidationContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\n\nimport PasswordValidationItem from './PasswordValidationItem'\n\nexport default class PasswordValidationContent extends Component {\n render() {\n const { fields } = this.props\n\n return (\n <Fragment>\n {fields.map(\n field => (\n <div className=\"mt2\" key={field.id}>\n <PasswordValidationItem\n label={field.label}\n prefix={field.prefix}\n valid={field.valid}\n />\n </div>\n )\n )}\n </Fragment>\n )\n }\n}\n\nPasswordValidationContent.propTypes = {\n /** Fields to appear into the content */\n fields: PropTypes.array.isRequired,\n}\n\n```"
}
] |
code_store-on-localhost_4b945498
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/Form.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport FormTitle from './FormTitle'\nimport FormFooter from './FormFooter'\n\nexport default function Form({ className, title, content, footer, onSubmit, children }) {\n return (\n <div className={className}>\n <FormTitle>\n {title}\n </FormTitle>\n <form onSubmit={onSubmit}>\n {content}\n <FormFooter>\n {footer}\n </FormFooter>\n {children}\n </form>\n </div>\n )\n}\n\nForm.propTypes = {\n className: PropTypes.string,\n title: PropTypes.node,\n content: PropTypes.node,\n footer: PropTypes.node,\n children: PropTypes.node,\n onSubmit: PropTypes.func,\n}\n\n```"
}
] |
code_store-on-localhost_1233054e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/LoginComponent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment, Suspense } from 'react'\nimport {\n Link,\n withRuntimeContext,\n ExtensionPoint,\n useChildBlock,\n} from '../../../../../vtex.render-runtime'\n\nimport classNames from 'classnames'\n\nimport IconProfile from '../../StoreIcons/IconProfile'\nimport Overlay from '../../ReactPortal/Overlay'\nimport ButtonWithIcon from '../../Styleguide/ButtonWithIcon'\n\nimport { truncateString } from '../utils/format-string'\nimport { translate } from '../utils/translate'\nimport { LoginPropTypes } from '../propTypes'\n\nimport styles from '../styles.css'\nimport Loading from './Loading'\nimport Popover from './Popover'\nimport OutsideClickHandler from './OutsideClickHandler'\n\nconst LoginContent = React.lazy(() => import('./LoginContent'))\n\nconst ProfileIcon = ({ iconSize, labelClasses, classes }) => {\n const hasIconBlock = Boolean(useChildBlock({ id: 'icon-profile' }))\n\n if (hasIconBlock) {\n return (\n <div className={classNames(labelClasses, classes)}>\n <ExtensionPoint id=\"icon-profile\" size={iconSize} />\n </div>\n )\n }\n\n return (\n <div className={classNames(labelClasses, classes)}>\n <IconProfile size={iconSize} />\n </div>\n )\n}\n\nclass LoginComponent extends Component {\n static propTypes = LoginPropTypes\n\n /** Function called after login success */\n onClickLoginButton = () => {\n window.location.reload()\n }\n\n renderIcon = () => {\n const {\n iconSize,\n iconLabel: iconLabelProfile,\n labelClasses,\n intl,\n renderIconAsLink,\n onProfileIconClick,\n sessionProfile,\n showIconProfile,\n runtime: { history },\n } = this.props\n\n const pathname = history && history.location && history.location.pathname\n\n const iconClasses = 'flex items-center'\n const iconLabel = iconLabelProfile || translate('store/login.signIn', intl)\n const iconContent = (\n <Fragment>\n {showIconProfile && renderIconAsLink && (\n <ProfileIcon\n iconSize={iconSize}\n labelClasses={labelClasses}\n iconClasses={iconClasses}\n />\n )}\n {sessionProfile ? (\n <span\n className={`${styles.profile} t-action--small order-1 pl4 ${labelClasses} dn db-l`}\n >\n {translate('store/login.hello', intl)}{' '}\n {sessionProfile.firstName || truncateString(sessionProfile.email)}\n </span>\n ) : (\n iconLabel && (\n <span\n className={`${styles.label} t-action--small pl4 ${labelClasses} dn db-l`}\n >\n {iconLabel}\n </span>\n )\n )}\n </Fragment>\n )\n\n if (renderIconAsLink) {\n const linkTo = sessionProfile ? 'store.account' : 'store.login'\n const returnUrl =\n !sessionProfile && `returnUrl=${encodeURIComponent(pathname)}`\n return (\n <Link\n page={linkTo}\n query={returnUrl}\n className={`${styles.buttonLink} h1 w2 tc flex items-center w-100-s h-100-s pa4-s`}\n >\n {iconContent}\n </Link>\n )\n }\n\n return (\n <ButtonWithIcon\n variation=\"tertiary\"\n icon={\n showIconProfile && (\n <ProfileIcon iconSize={iconSize} labelClasses={labelClasses} />\n )\n }\n iconPosition={showIconProfile ? 'left' : 'right'}\n onClick={onProfileIconClick}\n >\n <div\n className=\"flex pv2 items-center\"\n ref={e => {\n this.iconRef = e\n }}\n >\n {iconContent}\n </div>\n </ButtonWithIcon>\n )\n }\n\n render() {\n const {\n isBoxOpen,\n onOutSideBoxClick,\n sessionProfile,\n mirrorTooltipToRight,\n } = this.props\n\n return (\n <div className={`${styles.container} flex items-center fr`}>\n <div className=\"relative\">\n {this.renderIcon()}\n {isBoxOpen && (\n <Overlay>\n <OutsideClickHandler onOutsideClick={onOutSideBoxClick}>\n <Popover mirrorTooltipToRight={mirrorTooltipToRight}>\n <Suspense fallback={<Loading />}>\n <LoginContent\n profile={sessionProfile}\n loginCallback={this.onClickLoginButton}\n isInitialScreenOptionOnly\n {...this.props}\n />\n </Suspense>\n </Popover>\n </OutsideClickHandler>\n </Overlay>\n )}\n </div>\n </div>\n )\n }\n}\n\nexport default withRuntimeContext(LoginComponent)\n\n```"
}
] |
code_store-on-localhost_982819b1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/PasswordValidationItem.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nexport default class PasswordValidationItem extends Component {\n render() {\n const { valid, prefix, label } = this.props\n const className = classNames('flex flex-row', {\n 'c-success': valid !== undefined && valid,\n 'c-danger': valid !== undefined && !valid,\n 'c-muted-2': valid === undefined,\n })\n return (\n <div className={className}>\n <div className=\"w-20\">\n <span className=\"t-small\">{prefix}</span>\n </div>\n <div className=\"w-80\">\n <span className=\"t-small\">{label}</span>\n </div>\n </div>\n )\n }\n}\n\nPasswordValidationItem.propTypes = {\n /** Switch the icon to appear with the text (failed or success) */\n valid: PropTypes.bool,\n /** Label to appear before the text */\n prefix: PropTypes.string.isRequired,\n /** Label to appear into the item */\n label: PropTypes.string.isRequired,\n}\n\n```"
}
] |
code_store-on-localhost_e636a22a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/TooltipVerification.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport { isMobile } from 'react-device-detect'\nimport { translate } from '../utils/translate'\nimport Tooltip from './Tooltip'\nimport PasswordValidationContent from './PasswordValidationContent'\n\nclass TooltipVerification extends Component {\n render() {\n const { fields, intl } = this.props\n if (isMobile) {\n return (\n <Tooltip top title={translate('store/login.password.tooltip.title', intl)}>\n <PasswordValidationContent fields={fields} />\n </Tooltip>\n )\n }\n\n return (\n <Tooltip title={translate('store/login.password.tooltip.title', intl)}>\n <PasswordValidationContent fields={fields} />\n </Tooltip>\n )\n }\n}\n\nTooltipVerification.propTypes = {\n /** Fields to be verified in the tooltip */\n fields: PropTypes.array,\n}\n\nexport default injectIntl(TooltipVerification)\n\n```"
}
] |
code_store-on-localhost_8cd1a219
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/AccountOptions.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport { injectIntl } from 'react-intl'\nimport { Link } from '../../../../../vtex.render-runtime'\n\nimport Button from '../../Styleguide/Button'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\n\nimport { translate } from '../utils/translate'\nimport styles from '../styles.css'\n\n// Component that shows account options to the user.\nclass AccountOptions extends Component {\n\n render() {\n const { intl } = this.props\n return (\n <div className={`${styles.accountOptions} items-center w-100`}>\n <div className=\"ma4 min-h-2 b--muted-4\">\n <Link page={'store.account'}>\n <button\n className={`${styles.button} bw1 ba ttu br2 t-action--small v-mid relative pv3 ph5 t-heading-5 bg-base b--transparent c-action-primary hover-c-action-primary pointer`}\n closeonclick=\"\"\n >\n <span className=\"t-action--small\">\n {translate('store/login.myAccount', intl)}\n </span>\n </button>\n </Link>\n </div>\n <hr className=\"mv2 o-30\" />\n <div className=\"ma4 min-h-2 b--muted-4\">\n <AuthServiceLazy.RedirectLogout returnUrl=\"/\">\n {({ action: logout }) => (\n <Button\n variation=\"tertiary\"\n size=\"small\"\n onClick={logout}\n >\n <span className=\"t-action--small\">\n {translate('store/login.logoutLabel', intl)}\n </span>\n </Button>\n )}\n </AuthServiceLazy.RedirectLogout>\n </div>\n </div>\n )\n }\n}\n\nexport default injectIntl(AccountOptions)\n\n```"
}
] |
code_store-on-localhost_689740bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/FormFooter.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport styles from '../styles.css'\n\nexport default function FormFooter({ children }) {\n return (\n <div className={`${styles.formFooter} bt b--muted-4 pt4 flex mt3`}>\n {children}\n </div>\n )\n}\n\nFormFooter.propTypes = {\n children: PropTypes.node,\n}\n\n```"
}
] |
code_store-on-localhost_a6f88699
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/RecoveryPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport Button from '../../Styleguide/Button'\nimport Input from '../../Styleguide/Input'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\nimport AuthStateLazy from '../../VtexId/AuthStateLazy'\n\nimport { translate } from '../utils/translate'\nimport { isValidPassword, isValidAccessCode } from '../utils/format-check'\nimport Form from './Form'\nimport FormError from './FormError'\nimport PasswordInput from './PasswordInput'\nimport GoBackButton from './GoBackButton'\n\nimport styles from '../styles.css'\n\n/** RecoveryPassword tab component. Receive a code and new password from an input\n * and call the recoveryPassword API.\n */\nclass RecoveryPassword extends Component {\n constructor(props) {\n super(props)\n this.state = {\n isInvalidPassword: false,\n isPasswordsMatch: true,\n isInvalidCode: false,\n isWrongCode: false,\n isUserBlocked: false,\n confirmPassword: '',\n }\n }\n\n handleConfirmPasswordChange = event => {\n this.setState({\n isPasswordsMatch: true,\n confirmPassword: event.target.value,\n })\n }\n\n handleSuccess = () => {\n const { onStateChange, next } = this.props\n onStateChange({ step: next })\n this.props.loginCallback()\n }\n\n handleFailure = err => {\n if (err.code === 'BlockedUser') {\n this.setState({ isUserBlocked: true })\n } else if (err.code === 'WrongCredentials') {\n this.setState({ isWrongCode: true })\n } else {\n console.error(err)\n }\n }\n\n handleOnSubmit = (event, newPassword, token, setPassword) => {\n event.preventDefault()\n const { confirmPassword } = this.state\n if (!isValidAccessCode(token)) {\n this.setState({ isInvalidCode: true })\n } else if (!isValidPassword(newPassword)) {\n this.setState({ isInvalidPassword: true })\n } else if (newPassword !== confirmPassword) {\n this.setState({ isPasswordsMatch: false })\n } else {\n setPassword()\n }\n }\n\n render() {\n const {\n intl,\n previous,\n onStateChange,\n passwordPlaceholder,\n accessCodePlaceholder,\n showPasswordVerificationIntoTooltip,\n } = this.props\n\n const {\n isInvalidPassword,\n isUserBlocked,\n isInvalidCode,\n isWrongCode,\n isPasswordsMatch,\n } = this.state\n\n return (\n <Form\n className={`${styles.emailVerification} ${styles.forgotPasswordForm} w-100`}\n title={translate('store/login.createPassword', intl)}\n onSubmit={e => this.handleOnSubmit(e)}\n content={\n <Fragment>\n <div className={`${styles.inputContainer} ${styles.inputContainerAccessCode} pv3`}>\n <AuthStateLazy.Token>\n {({ value, setValue }) => (\n <Input\n token\n name=\"token\"\n onChange={e => {\n setValue(e.target.value)\n this.setState({ isInvalidCode: false, isWrongCode: false })\n }}\n value={value || ''}\n placeholder={\n accessCodePlaceholder ||\n translate('store/login.accessCode.placeholder', intl)\n }\n />\n )}\n </AuthStateLazy.Token>\n </div>\n <FormError show={isInvalidCode}>\n {translate('store/login.invalidCode', intl)}\n </FormError>\n <FormError show={isWrongCode}>\n {translate('store/login.wrongCode', intl)}\n </FormError>\n <div className={`${styles.inputContainer} ${styles.inputContainerPassword} pv3`}>\n <AuthStateLazy.Password>\n {({ value, setValue }) => (\n <PasswordInput\n onStateChange={({ password }) => {\n setValue(password)\n this.setState({ isInvalidPassword: false })\n }}\n placeholder={passwordPlaceholder || translate('store/login.password.placeholder', intl)}\n password={value || ''}\n showPasswordVerificationIntoTooltip={\n showPasswordVerificationIntoTooltip\n }\n />\n )}\n </AuthStateLazy.Password>\n </div>\n <FormError show={isInvalidPassword}>\n {translate('store/login.invalidPassword', intl)}\n </FormError>\n <FormError show={isUserBlocked}>\n {translate('store/login.userBlocked', intl)}\n </FormError>\n <div className={`${styles.inputContainer} ${styles.inputContainerPassword} pv3`}>\n <Input\n type=\"password\"\n onChange={this.handleConfirmPasswordChange}\n placeholder={translate('store/login.confirmPassword', intl)}\n />\n </div>\n <FormError show={!isPasswordsMatch}>\n {translate('store/login.invalidMatch', intl)}\n </FormError>\n </Fragment>\n }\n footer={\n <Fragment>\n <GoBackButton\n onStateChange={onStateChange}\n changeTab={{ step: previous }}\n />\n <div className={`${styles.sendButton} ml-auto`}>\n <AuthServiceLazy.SetPassword\n onSuccess={this.handleSuccess}\n onFailure={this.handleFailure}\n >\n {({\n state: { password, token },\n loading,\n action: setPassword,\n validation: {\n validatePassword,\n },\n }) => (\n <Button\n variation=\"primary\"\n size=\"small\"\n type=\"submit\"\n onClick={e => this.handleOnSubmit(e, password, token, setPassword)}\n isLoading={loading}\n disabled={!validatePassword(password)}\n >\n <span className=\"t-small\">\n {translate('store/login.create', intl)}\n </span>\n </Button>\n )}\n </AuthServiceLazy.SetPassword>\n </div>\n </Fragment>\n }\n />\n )\n }\n}\n\nRecoveryPassword.propTypes = {\n /** Next step */\n next: PropTypes.number.isRequired,\n /** Previous step */\n previous: PropTypes.number.isRequired,\n /** Set the type of password verification ui */\n showPasswordVerificationIntoTooltip: PropTypes.bool,\n /** Function to change de active tab */\n onStateChange: PropTypes.func.isRequired,\n /** Placeholder to password input */\n passwordPlaceholder: PropTypes.string,\n /** Placeholder to access code input */\n accessCodePlaceholder: PropTypes.string,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n}\n\nexport default injectIntl(RecoveryPassword)\n\n```"
}
] |
code_store-on-localhost_319cf9ea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/components/EmailAndPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jsx-a11y/anchor-is-valid */\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport Input from '../../Styleguide/Input'\nimport Button from '../../Styleguide/Button'\nimport AuthStateLazy from '../../VtexId/AuthStateLazy'\nimport AuthServiceLazy from '../../VtexId/AuthServiceLazy'\nimport { ExtensionPoint, useChildBlock } from '../../../../../vtex.render-runtime'\n\nimport { translate } from '../utils/translate'\nimport { isValidEmail, isValidPassword } from '../utils/format-check'\nimport { steps } from '../utils/steps'\nimport Form from './Form'\nimport FormError from './FormError'\nimport PasswordInput from './PasswordInput'\nimport GoBackButton from './GoBackButton'\nimport { USER_IDENTIFIER_INTERFACE_ID } from '../common/global'\n\nimport styles from '../styles.css'\n\n/** EmailAndPasswordLogin component. */\nclass EmailAndPassword extends Component {\n static propTypes = {\n /** Next step */\n next: PropTypes.number.isRequired,\n /** Previous step */\n previous: PropTypes.number.isRequired,\n /** Set the type of password verification ui */\n showPasswordVerificationIntoTooltip: PropTypes.bool,\n /** Title to be displayed */\n title: PropTypes.string,\n /** Placeholder to email input */\n emailPlaceholder: PropTypes.string,\n /** Placeholder to password input */\n passwordPlaceholder: PropTypes.string,\n /** Function to change de active tab */\n onStateChange: PropTypes.func.isRequired,\n /** Whether to display the back button */\n showBackButton: PropTypes.bool,\n /** Function called after login success */\n loginCallback: PropTypes.func,\n /* Whether the user identifier interface has been extended */\n hasUserIdentifierExtension: PropTypes.bool,\n /** Placeholder for the identifier extension */\n identifierPlaceholder: PropTypes.string,\n /** Error message for the user identifier */\n invalidIdentifierError: PropTypes.string,\n }\n\n state = {\n isInvalidEmail: false,\n isInvalidPassword: false,\n isWrongCredentials: false,\n isUserBlocked: false,\n userIdentifierExtensionSubmitter: null,\n }\n\n handlePasswordChange = () => {\n this.setState({ isInvalidPassword: false, isWrongCredentials: false })\n }\n\n handleCreatePassword = event => {\n this.props.onStateChange({\n step: steps.EMAIL_VERIFICATION,\n isCreatePassword: true,\n isOnInitialScreen: false,\n })\n event.preventDefault()\n }\n\n handleSuccess = () => {\n this.props.loginCallback()\n }\n\n handleFailure = err => {\n err.code === 'WrongCredentials'\n ? this.setState({ isWrongCredentials: true })\n : err.code === 'BlockedUser'\n ? this.setState({ isUserBlocked: true })\n : console.error(err)\n }\n\n registerUserIdentifierExtensionSubmitter = userIdentifierExtensionSubmitter => {\n this.setState({ userIdentifierExtensionSubmitter })\n }\n\n trySubmit = (email, password, login) => {\n if (!isValidEmail(email)) {\n this.setState({ isInvalidEmail: true })\n } else if (!isValidPassword(password)) {\n this.setState({ isInvalidPassword: true })\n } else {\n login()\n }\n }\n\n handleOnSubmit = async (email, password, login, setEmail) => {\n if (this.state.userIdentifierExtensionSubmitter) {\n const emailResult = await this.state.userIdentifierExtensionSubmitter()\n setEmail(emailResult, () => {\n this.trySubmit(emailResult, password, login)\n })\n } else {\n this.trySubmit(email, password, login)\n }\n }\n\n render() {\n const {\n title,\n intl,\n onStateChange,\n previous,\n showBackButton,\n emailPlaceholder,\n passwordPlaceholder,\n showPasswordVerificationIntoTooltip,\n hasUserIdentifierExtension,\n identifierPlaceholder,\n invalidIdentifierError,\n } = this.props\n\n const {\n isInvalidEmail,\n isInvalidPassword,\n isWrongCredentials,\n isUserBlocked,\n } = this.state\n\n return (\n <Form\n className={`${styles.emailVerification} ${styles.emailAndPasswordForm} w-100`}\n title={title || translate('store/loginOptions.emailAndPassword', intl)}\n onSubmit={e => this.handleOnSubmit(e)}\n content={\n <Fragment>\n <div className={`${styles.inputContainer} ${styles.inputContainerEmail}`}>\n <AuthStateLazy.Email>\n {({ value, setValue }) => {\n if (hasUserIdentifierExtension) {\n return (\n <ExtensionPoint\n id={USER_IDENTIFIER_INTERFACE_ID}\n identifierPlaceholder={\n identifierPlaceholder || emailPlaceholder\n }\n renderInput={({ value, onChange, placeholder }) => (\n <Input\n value={value}\n onChange={e => {\n onChange(e)\n this.setState({ isInvalidEmail: false })\n }}\n placeholder={placeholder}\n />\n )}\n registerSubmitter={\n this.registerUserIdentifierExtensionSubmitter\n }\n />\n )\n }\n return (\n <Input\n value={value || ''}\n onChange={e => {\n setValue(e.target.value)\n this.setState({ isInvalidEmail: false })\n }}\n placeholder={\n emailPlaceholder ||\n translate('store/login.email.placeholder', intl)\n }\n />\n )\n }}\n </AuthStateLazy.Email>\n </div>\n <FormError show={isInvalidEmail}>\n {invalidIdentifierError ||\n translate('store/login.invalidEmail', intl)}\n </FormError>\n <div className={`${styles.inputContainer} ${styles.inputContainerPassword} pv3 flex flex-column`}>\n <AuthStateLazy.Password>\n {({ value, setValue }) => (\n <PasswordInput\n password={value || ''}\n onStateChange={({ password }) => {\n setValue(password)\n this.handlePasswordChange()\n }}\n placeholder={\n passwordPlaceholder ||\n translate('store/login.password.placeholder', intl)\n }\n showPasswordVerificationIntoTooltip={\n showPasswordVerificationIntoTooltip\n }\n />\n )}\n </AuthStateLazy.Password>\n </div>\n <FormError show={isInvalidPassword}>\n {translate('store/login.invalidPassword', intl)}\n </FormError>\n <FormError show={isWrongCredentials}>\n {translate('store/login.wrongCredentials', intl)}\n </FormError>\n <FormError show={isUserBlocked}>\n {translate('store/login.userBlocked', intl)}\n </FormError>\n <div\n className={`${styles.formLinkContainer} flex justify-end ph0 pv2`}\n >\n <a\n href=\"\"\n className=\"link dim c-link\"\n onClick={this.handleCreatePassword}\n >\n <span className=\"t-small\">\n {translate('store/login.forgotPassword', intl)}\n </span>\n </a>\n </div>\n </Fragment>\n }\n footer={\n <Fragment>\n {showBackButton && (\n <GoBackButton\n onStateChange={onStateChange}\n changeTab={{ step: previous }}\n />\n )}\n <div className={`${styles.sendButton} ml-auto`}>\n <AuthServiceLazy.LoginWithPassword\n useNewSession\n onSuccess={this.handleSuccess}\n onFailure={this.handleFailure}\n >\n {({\n state: { email, password },\n loading,\n action: loginWithPassword,\n }) => (\n <AuthStateLazy.Email>\n {({ setValue: setEmail }) => (\n <Button\n variation=\"primary\"\n size=\"small\"\n type=\"submit\"\n onClick={e => {\n e.preventDefault()\n this.handleOnSubmit(\n email,\n password,\n loginWithPassword,\n setEmail\n )\n }}\n isLoading={loading}\n >\n <span className=\"t-small\">\n {translate('store/login.signIn', intl)}\n </span>\n </Button>\n )}\n </AuthStateLazy.Email>\n )}\n </AuthServiceLazy.LoginWithPassword>\n </div>\n </Fragment>\n }\n >\n <div\n className={`${styles.formLinkContainer} flex justify-center ph0 mt4`}\n >\n <a\n href=\"\"\n className=\"link dim c-link\"\n onClick={e => this.handleCreatePassword(e)}\n >\n <span className=\"t-small\">\n {translate('store/login.notHaveAccount', intl)}\n </span>\n </a>\n </div>\n </Form>\n )\n }\n}\n\nconst withHasUserIdentifierExtension = Component => {\n const Wrapper = props => {\n const hasUserIdentifierExtension = !!useChildBlock({\n id: USER_IDENTIFIER_INTERFACE_ID,\n })\n return (\n <Component\n {...props}\n hasUserIdentifierExtension={hasUserIdentifierExtension}\n />\n )\n }\n return Wrapper\n}\n\nexport default withHasUserIdentifierExtension(injectIntl(EmailAndPassword))\n\n```"
}
] |
code_store-on-localhost_3b8e1929
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/common/global.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const USER_IDENTIFIER_INTERFACE_ID = 'user-identifier'\nexport const SELF_APP_NAME_AND_VERSION = process.env.VTEX_APP_ID || process.env.VTEX_APP_NAME || null\n\n```"
}
] |
code_store-on-localhost_6eb46297
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/__tests__/LoginContent.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { renderWithIntl } from '../testUtils/intl-utils'\n\nimport LoginContent from '../components/LoginContent'\n\ndescribe('<LoginContent /> component', () => {\n it('should match snapshot when loading', () => {\n const { asFragment } = renderWithIntl(\n <LoginContent data={{ loading: true }} />\n )\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot', () => {\n const { asFragment } = renderWithIntl(\n <LoginContent data={{ loading: false }} />\n )\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_cd1d5b78
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/__tests__/Login.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { renderWithIntl } from '../testUtils/intl-utils'\n\nimport Login from '../Login'\n\nimport { AuthStateLazy } from 'vtex.react-vtexid'\nimport { waitForElement } from '@vtex/test-tools/react'\n\ndescribe('<Login /> component', () => {\n it('should match snapshot when loading', async () => {\n AuthStateLazy.mockImplementationOnce(({ children }) => children({ loading: true }))\n\n const { asFragment, getByTestId } = renderWithIntl(<Login isBoxOpen />)\n await Promise.resolve()\n await waitForElement(() => getByTestId('loading-session'))\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot without profile', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = Promise.resolve({\n response: {},\n })\n const { asFragment } = renderWithIntl(<Login isBoxOpen />)\n await Promise.resolve()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with profile without name', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = Promise.resolve({\n response: {\n namespaces: {\n profile: { email: { value: 'email@vtex.com' } },\n },\n },\n })\n const { asFragment } = renderWithIntl(<Login isBoxOpen />)\n await Promise.resolve()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with profile with name', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = Promise.resolve({\n response: {\n namespaces: {\n profile: {\n email: { value: 'email@vtex.com' },\n firstName: { value: 'firstName' },\n },\n },\n },\n })\n const { asFragment } = renderWithIntl(<Login isBoxOpen />)\n await Promise.resolve()\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_7849e613
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/testUtils/setupTests.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport 'react-testing-library/cleanup-after-each'\nimport '@testing-library/jest-dom/extend-expect'\n\n```"
}
] |
code_store-on-localhost_d77c2dda
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Login/testUtils/intl-utils.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { IntlProvider } from 'react-intl'\nimport defautMessages from '../../messages/en.json'\n\nexport const renderWithIntl = (node, options) => {\n const rendered = render(\n <IntlProvider messages={defautMessages} locale=\"en-US\">\n {node}\n </IntlProvider>,\n options\n )\n\n return {\n ...rendered,\n rerender: newUi =>\n renderWithIntl(newUi, {\n container: rendered.container,\n baseElement: rendered.baseElement,\n }),\n }\n}\n\n```"
}
] |
code_store-on-localhost_25291717
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useEffect, useState } from 'react'\nimport classNames from 'classnames'\nimport PropTypes from 'prop-types'\nimport { ExtensionPoint, useRuntime } from '../../../../../vtex.render-runtime'\nimport TopMenu from './components/TopMenu'\nimport Spacer from './components/Helpers/Spacer'\nimport { logo, collapsible, icons, searchBar, login } from './defaults'\n\nimport styles from './store-header.css'\nimport useDevice from './hooks/useDevice'\n\n/**\n * Main header component\n */\nconst Header = ({\n leanWhen,\n linkUrl,\n logoUrl,\n logoTitle,\n logoSize,\n showSearchBar,\n showLogin,\n iconClasses,\n labelClasses,\n collapsibleAnimation,\n}) => {\n const { page, getSettings } = useRuntime()\n const { mobile } = useDevice()\n const [containerHeight, setContainerHeight] = useState(null)\n const { storeName } = getSettings('vtex.store')\n\n useEffect(() => {\n if (document) {\n const containerElement = document.querySelector(\n '.vtex-store-header-2-x-container'\n )\n const elementHeight = containerElement && containerElement.offsetHeight\n setContainerHeight(elementHeight)\n }\n })\n\n const topMenuOptions = {\n linkUrl,\n logoUrl,\n logoTitle: logoTitle || storeName || '',\n logoSize,\n showSearchBar,\n showLogin,\n iconClasses,\n labelClasses,\n collapsibleAnimation,\n mobile,\n }\n\n const isLeanMode = () => {\n const acceptedPaths = new RegExp(leanWhen)\n return acceptedPaths.test(page)\n }\n\n const containerClasses = classNames(\n styles.container,\n 'fixed top-0 z-4 w-100',\n isLeanMode() ? styles.leanMode : ''\n )\n\n return (\n <Fragment>\n <div className={containerClasses}>\n <TopMenu\n {...topMenuOptions}\n leanMode={isLeanMode()}\n extraHeaders={\n <div\n className=\"left-0 w-100\"\n style={{\n transform: 'translateZ(0)', //Avoid shaking\n }}\n >\n <ExtensionPoint id=\"telemarketing\" />\n <ExtensionPoint id=\"menu-link\" />\n </div>\n }\n />\n </div>\n <Spacer containerHeight={containerHeight} />\n </Fragment>\n )\n}\n\nHeader.propTypes = {\n /** Cases in which the menu is in lean mode */\n leanWhen: PropTypes.string,\n ...login.propTypes,\n ...searchBar.propTypes,\n ...icons.propTypes,\n ...logo.propTypes,\n ...collapsible.propTypes,\n}\n\nHeader.defaultProps = {\n leanWhen: 'a^',\n ...login.defaultProps,\n ...searchBar.defaultProps,\n ...icons.defaultProps,\n ...logo.defaultProps,\n ...collapsible.defaultProps,\n}\n\nHeader.schema = {\n title: 'admin/editor.header.title',\n description: 'admin/editor.header.description',\n type: 'object',\n properties: {\n logoUrl: {\n type: 'string',\n title: 'admin/editor.header.logo.image',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n linkUrl: {\n type: 'string',\n title: 'admin/editor.header.link.url',\n },\n showSearchBar: {\n title: 'admin/editor.header.show.searchbar.title',\n type: 'boolean',\n default: true,\n isLayout: true,\n },\n showLogin: {\n title: 'admin/editor.header.show.login.title',\n type: 'boolean',\n default: true,\n isLayout: true,\n },\n },\n}\n\nexport default Header\n\n```"
}
] |
code_store-on-localhost_4daff8af
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/store-header.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.logoLink {\n font-size: 0px;\n}\n\n.container {\n}\n.leanMode {\n}\n\n.topMenuLogo {\n}\n.topMenuSearchBar {\n}\n.topMenuIcons {\n}\n.topMenuContainer {\n}\n\n.topMenuCollapsible {\n}\n\n.topMenuCompatibilityContainer {\n}\n```"
}
] |
code_store-on-localhost_a57f4278
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/defaults.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nexport const lean = {\n propTypes: {\n /** If it is leanMode or not */\n leanMode: PropTypes.bool,\n },\n defaultProps: {\n leanMode: false,\n },\n}\n\nexport const logo = {\n propTypes: {\n /** Address opened when the user clicks the logo */\n linkUrl: PropTypes.string,\n /** URL of the logo image */\n logoUrl: PropTypes.string,\n /** Alt text for the logo */\n logoTitle: PropTypes.string,\n /** Size of the logo */\n logoSize: PropTypes.shape({\n /** Size on desktop */\n desktop: PropTypes.shape({\n width: PropTypes.number,\n height: PropTypes.number,\n }),\n /** Size on mobile */\n mobile: PropTypes.shape({\n width: PropTypes.number,\n height: PropTypes.number,\n }),\n }),\n },\n defaultProps: {\n linkUrl: '/',\n logoUrl: '',\n logoSize: {\n desktop: {\n width: 132,\n height: 40,\n },\n mobile: {\n width: 90,\n height: 40,\n },\n },\n },\n}\n\nexport const searchBar = {\n propTypes: {\n /** Sets whether the search bar is visible or not */\n showSearchBar: PropTypes.bool,\n },\n defaultProps: {\n showSearchBar: true,\n },\n}\n\nexport const login = {\n propTypes: {\n /** Sets whether the login button is displayed or not*/\n showLogin: PropTypes.bool,\n },\n defaultProps: {\n showLogin: true,\n },\n}\n\nexport const icons = {\n propTypes: {\n /** Classes for icons */\n iconClasses: PropTypes.string,\n /** Classes for labels */\n labelClasses: PropTypes.string,\n },\n defaultProps: {\n iconClasses: 'c-on-base',\n labelClasses: 'c-on-base',\n },\n}\n\nexport const collapsible = {\n propTypes: {\n collapsibleAnimation: PropTypes.shape({\n /** If should animate on scroll */\n onScroll: PropTypes.bool,\n /** If should animate on every scroll up or down */\n always: PropTypes.bool,\n /** Scroll value that animation starts to be active */\n anchor: PropTypes.number,\n /** Initial height */\n from: PropTypes.number,\n /** Target height */\n to: PropTypes.number,\n /** Animation configuration presets: know more @ https://www.react-spring.io/docs/hooks/api */\n preset: PropTypes.oneOf([\n 'default',\n 'gentle',\n 'wobbly',\n 'stiff',\n 'slow',\n 'molasses',\n ]),\n /** Animation configuration: know more @ https://www.react-spring.io/docs/hooks/api */\n config: PropTypes.shape({\n mass: PropTypes.number,\n tension: PropTypes.number,\n friction: PropTypes.number,\n clamp: PropTypes.bool,\n precision: PropTypes.number,\n velocity: PropTypes.number,\n duration: PropTypes.number,\n easing: PropTypes.func,\n }),\n }),\n },\n\n defaultProps: {\n collapsibleAnimation: {\n onScroll: true,\n always: true,\n anchor: 100,\n from: 4,\n to: 0,\n preset: 'default',\n config: {},\n },\n },\n}\n\nexport const spacer = {\n propTypes: {\n /** Height on mobile mode */\n spacerHeightMobile: PropTypes.number,\n /** Height on desktop mode */\n spacerHeightDesktop: PropTypes.number,\n /** Width on mobile and desktop */\n spacerWidth: PropTypes.number,\n },\n\n defaultProps: {\n spacerHeightMobile: 96,\n spacerHeightDesktop: 160,\n spacerWidth: 0,\n },\n}\n\n```"
}
] |
code_store-on-localhost_8b07cb67
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/Border.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport StickyRow from './StickyRow'\n\ninterface Props {\n sticky: boolean\n}\n\nconst CSS_HANDLES = ['headerBorder'] as const\n\nconst Border: FunctionComponent<Props> = ({ sticky }) => {\n const handles = useCssHandles(CSS_HANDLES)\n return (\n <StickyRow sticky={sticky}>\n <div className={`${handles.headerBorder} bb b--muted-3`} />\n </StickyRow>\n )\n}\n\nexport default Border\n\n```"
}
] |
code_store-on-localhost_3f2fb328
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/Spacer.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nconst CSS_HANDLES = ['headerSpacer'] as const\n\nconst Spacer: FunctionComponent = () => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return <div className={`${handles.headerSpacer} flex flex-grow-1`} />\n}\n\nexport default Spacer\n\n```"
}
] |
code_store-on-localhost_63e2c764
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/StickyRow.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useContext, CSSProperties } from 'react'\nimport ReactResizeDetector from 'react-resize-detector'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport { RowContext } from './StickyRows'\n\ninterface Props {\n sticky?: boolean\n zIndex?: number\n}\n\nconst CSS_HANDLES = ['headerStickyRow'] as const\n\nconst StickyRow: FunctionComponent<Props> = ({ children, sticky, zIndex }) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { offset, onResize } = useContext(RowContext)\n\n const stickyStyle: CSSProperties = {\n top: offset,\n zIndex,\n }\n\n return (\n <div\n style={sticky ? stickyStyle : undefined}\n className={`${handles.headerStickyRow} ${\n sticky ? `sticky ${!zIndex ? 'z-999' : ''}` : ''\n }`}\n >\n {children}\n\n {sticky && (\n <ReactResizeDetector\n handleHeight\n onResize={(_, height) => {\n onResize(height)\n }}\n />\n )}\n </div>\n )\n}\n\nexport default StickyRow\n\n```"
}
] |
code_store-on-localhost_03c72336
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/Layout.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\n\nimport StickyRows from './StickyRows'\n\nconst Layout: FunctionComponent = ({ children }) => {\n return <StickyRows>{children}</StickyRows>\n}\n\nexport default Layout\n\n```"
}
] |
code_store-on-localhost_78c1713b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/Row.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport classNames from 'classnames'\nimport Container from '../../StoreComponents/Container'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport StickyRow from './StickyRow'\n\ninterface Props {\n sticky?: boolean\n zIndex?: number\n fullWidth?: boolean\n inverted?: boolean\n blockClass?: string\n}\n\nconst CSS_HANDLES = [\n 'headerRowContainer',\n 'headerRow',\n 'headerRowBackground',\n 'headerRowContentContainer',\n] as const\n\nconst Row: FunctionComponent<Props> = ({\n children,\n sticky,\n zIndex,\n fullWidth,\n inverted,\n blockClass,\n}) => {\n const handles = useCssHandles(CSS_HANDLES, {blockClass})\n\n const content = (\n <div className={`${handles?.headerRowContainer} w-100 flex items-center`}>\n {children}\n </div>\n )\n\n return (\n <StickyRow sticky={sticky} zIndex={zIndex}>\n <div className={handles?.headerRow}>\n <div\n className={classNames(\n `${handles?.headerRowBackground} w-100`,\n inverted\n ? 'bg-base--inverted c-on-base--inverted'\n : 'bg-base c-on-base'\n )}\n >\n {fullWidth ? (\n content\n ) : (\n <Container\n className={`${handles?.headerRowContentContainer} w-100 flex`}\n >\n {content}\n </Container>\n )}\n </div>\n </div>\n </StickyRow>\n )\n}\n\nexport default Row\n\n```"
}
] |
code_store-on-localhost_a2ce8290
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/CustomHeader.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { Block } from '../../../../../vtex.render-runtime'\nimport useDevice from '../../DeviceDetector/useDevice'\n\nenum Device {\n mobile = 'mobile',\n desktop = 'desktop',\n}\n\nconst CustomHeaderLayout = React.memo(({ device }: { device: Device }) => {\n switch (device) {\n case Device.mobile:\n return (\n <>\n <Block id=\"header-layout.mobile\" />\n <Block id=\"unstable--header-layout.mobile\" />\n </>\n )\n case Device.desktop:\n default:\n return (\n <>\n <Block id=\"header-layout.desktop\" />\n <Block id=\"unstable--header-layout.desktop\" />\n </>\n )\n }\n})\n\nCustomHeaderLayout.displayName = 'CustomHeaderLayout'\n\nconst CustomHeader: FunctionComponent = () => {\n const { isMobile } = useDevice()\n\n return (\n <CustomHeaderLayout device={isMobile ? Device.mobile : Device.desktop} />\n )\n}\n\nexport default CustomHeader\n\n```"
}
] |
code_store-on-localhost_17052c96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/components/StickyRows.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\n\nimport useCumulativeHeightState from '../hooks/useCumulativeHeightState'\n\nconst RowContext = React.createContext<{\n onResize(height: number): void\n offset: number\n}>({\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onResize: () => {},\n offset: 0,\n})\n\nconst StickyRows: FunctionComponent = ({ children }) => {\n const { updateRowHeight, getAccumulatedHeight } = useCumulativeHeightState()\n\n return (\n <React.Fragment>\n {React.Children.map(children, (child, index) => (\n <RowContext.Provider\n value={{\n onResize: (height: number) => updateRowHeight({ height, index }),\n offset: getAccumulatedHeight(index),\n }}\n >\n {child}\n </RowContext.Provider>\n ))}\n </React.Fragment>\n )\n}\n\nexport default StickyRows\nexport { RowContext }\n\n```"
}
] |
code_store-on-localhost_626664b4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/__tests__/Header.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport { useRuntime } from '../../../../../vtex.render-runtime'\n\nimport Header from '../legacy/index'\n\ndescribe('Header Component', () => {\n beforeEach(() => {\n const { setHints } = useRuntime()\n setHints({ mobile: false, desktop: true })\n })\n\n it('should be rendered', () => {\n const component = render(<Header />)\n expect(component).toBeTruthy()\n })\n\n it('should match snapshot without leanmode', () => {\n const component = render(<Header />)\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot with leanmode', () => {\n const component = render(<Header leanWhen=\"test\" />)\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot mobile without leanmode', () => {\n const { setHints } = useRuntime()\n setHints({ mobile: true, desktop: false })\n\n const component = render(<Header />)\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should match snapshot mobile with leanmode', () => {\n const { setHints } = useRuntime()\n setHints({ mobile: true, desktop: false })\n\n const component = render(<Header leanWhen=\"test\" />)\n expect(component.asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_896303eb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/hooks/useCumulativeHeightState.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface State {\n [id: string]: number\n}\n\nenum ActionTypes {\n UPDATE = 'update',\n}\n\ninterface UpdateAction {\n type: ActionTypes.UPDATE\n payload: {\n index: number\n height: number\n }\n}\n\ntype Actions = UpdateAction\n\nconst reducer = (state: State, action: Actions) => {\n switch (action.type) {\n case 'update':\n return {\n ...state,\n [action.payload.index]: action.payload.height,\n }\n default:\n return state\n }\n}\n\nconst useCumulativeHeightState = () => {\n const [state, dispatch]: [\n State,\n React.Dispatch<UpdateAction>\n ] = React.useReducer(reducer, {})\n\n const updateRowHeight = ({\n height,\n index,\n }: {\n height: number\n index: number\n }) => {\n if (state[index] === height) {\n return\n }\n\n dispatch({\n payload: {\n height,\n index,\n },\n type: ActionTypes.UPDATE,\n })\n }\n\n const getAccumulatedHeight = (index: number) => {\n const sortedIndices = Object.keys(state)\n .map(key => parseInt(key, 10))\n .sort((a, b) => a - b)\n\n const indices = sortedIndices.slice(0, sortedIndices.indexOf(index))\n\n return indices.reduce((acc, cur) => (state[cur] || 0) + acc, 0)\n }\n\n return {\n getAccumulatedHeight,\n updateRowHeight,\n }\n}\n\nexport default useCumulativeHeightState\n\n```"
}
] |
code_store-on-localhost_56a06e17
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/testUtils/setupTests.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// react-testing-library renders your components to document.body,\n// this will ensure they're removed after each test.\nimport 'react-testing-library/cleanup-after-each'\n\n// this adds jest-dom's custom assertions\nimport 'jest-dom/extend-expect'\n\n```"
}
] |
code_store-on-localhost_03d924bc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/testUtils/test-utils.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport * as reactTestingLibrary from 'react-testing-library'\nimport { IntlProvider } from 'react-intl'\n\nimport defaultStrings from '../../messages/en.json'\n\nconst customRender = (node, options) => {\n const rendered = reactTestingLibrary.render(\n <IntlProvider messages={defaultStrings} locale=\"en-US\">\n {node}\n </IntlProvider>,\n options\n )\n\n return {\n ...rendered,\n rerender: newUi =>\n customRender(newUi, {\n container: rendered.container,\n baseElement: rendered.baseElement,\n }),\n }\n}\n\n// re-export everything\nmodule.exports = {\n ...reactTestingLibrary,\n render: customRender,\n}\n\n```"
}
] |
code_store-on-localhost_e160a265
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/FixedContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment, useState } from 'react'\nimport { ExtensionPoint } from '../../../../../../vtex.render-runtime'\nimport PropTypes from 'prop-types'\nimport Container from '../../../StoreComponents/Container'\nimport classNames from 'classnames'\nimport Logo from './Logo'\nimport SearchBar from './SearchBar'\nimport Actions from './Actions'\nimport { logo, icons, lean, searchBar, login } from '../defaults'\n\nimport styles from '../store-header.css'\n\n/**\n * Component that deals with content thats always fixed on top\n * Also handles the toggle between mobile search and mobile navbar\n */\nconst FixedContent = ({\n leanMode,\n logoUrl,\n linkUrl,\n logoTitle,\n logoSize,\n showSearchBar,\n showLogin,\n iconClasses,\n labelClasses,\n mobile,\n}) => {\n const [mobileSearchActive, toggleSearch] = useState(false)\n const containerClasses = classNames(\n `${\n styles.topMenuContainer\n } relative flex justify-center bg-base h3 bb bw0 b--white`\n )\n const contentClasses = classNames(\n 'w-100 mw9 flex justify-center',\n leanMode ? 'pv0' : 'pv6-l pv2-m'\n )\n\n return (\n <div className=\"w-100 bg-base\">\n <Container\n className={containerClasses}\n style={{\n transform: 'translateZ(0)', //Avoid shaking\n }}\n >\n <div className={contentClasses} style={{ pointerEvents: 'none' }}>\n <div\n className=\"flex w-100 justify-between-m items-center pv3\"\n style={{\n pointerEvents: 'auto',\n }}\n >\n {mobileSearchActive ? (\n mobile &&\n showSearchBar && (\n <div className=\"flex justify-start pa2 relative w-100\">\n <SearchBar\n mobile={mobile}\n iconClasses={iconClasses}\n onCancel={() => toggleSearch(false)}\n />\n </div>\n )\n ) : (\n <Fragment>\n {!leanMode && mobile && (\n <ExtensionPoint\n id=\"category-menu\"\n mobileMode\n iconClasses={iconClasses}\n />\n )}\n\n <Logo\n logoUrl={logoUrl}\n logoTitle={logoTitle}\n linkUrl={linkUrl}\n logoSize={logoSize}\n mobile={mobile}\n />\n\n {!leanMode && !mobile && showSearchBar && (\n <div className=\"dn db-ns flex-grow-1\">\n <SearchBar mobile={mobile} />\n </div>\n )}\n\n <ExtensionPoint id=\"locale-switcher\"/>\n\n <Actions\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n showSearchBar={showSearchBar}\n showSearchIcon={showSearchBar}\n leanMode={leanMode}\n showLogin={showLogin}\n onActiveSearch={() => toggleSearch(true)}\n mobile={mobile}\n />\n\n {!mobile && (\n <ExtensionPoint id=\"user-address\" variation=\"inline\" />\n )}\n </Fragment>\n )}\n </div>\n </div>\n </Container>\n </div>\n )\n}\n\nFixedContent.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n ...lean.propTypes,\n ...login.propTypes,\n ...searchBar.propTypes,\n ...logo.propTypes,\n ...icons.propTypes,\n}\n\nFixedContent.defaultProps = {\n ...lean.defaultProps,\n ...login.defaultProps,\n ...searchBar.defaultProps,\n ...logo.defaultProps,\n ...icons.defaultProps,\n}\n\nexport default FixedContent\n\n```"
}
] |
code_store-on-localhost_639780a9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/Collapsible.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport classNames from 'classnames'\nimport { NoSSR, ExtensionPoint } from '../../../../../../vtex.render-runtime'\nimport PropTypes from 'prop-types'\nimport {\n useSpring,\n animated,\n config as springPresets,\n} from 'react-spring/web.cjs'\nimport useScrollDirection from '../hooks/useScrollDirection'\nimport Border from './Helpers/Border'\nimport { collapsible, lean } from '../defaults'\n\nimport styles from '../store-header.css'\n\n/**\n * Represents a collapsible part of the header\n */\nconst Collapsible = ({ children, leanMode, collapsibleAnimation, mobile }) => {\n const { scroll, scrollingUp } = useScrollDirection()\n const {\n onScroll,\n anchor,\n always,\n from,\n to,\n preset,\n config,\n } = collapsibleAnimation\n\n let animationTrigger = true\n\n if (onScroll) {\n const animateWhen = scroll < anchor\n const elastic = always ? scrollingUp : false\n animationTrigger = animateWhen || elastic\n }\n\n const animationStyle =\n !!window.requestAnimationFrame && // Fix SSR Issues\n useSpring({\n config: preset ? springPresets[preset] : config,\n transform: animationTrigger\n ? `translate3d(0, ${to}rem, 0)`\n : `translate3d(0, ${-from}rem, 0)`,\n })\n\n const collapsibleClassnames = classNames(\n styles.topMenuCollapsible,\n 'bg-base flex justify-center relative bb bw1 b--muted-4'\n )\n\n const fallback = <div className={collapsibleClassnames}>{children}</div>\n\n return (\n <React.Fragment>\n {!mobile && !leanMode ? (\n <NoSSR onSSR={fallback}>\n <animated.div\n className={collapsibleClassnames}\n style={{ ...animationStyle, zIndex: -2 }}\n >\n {children}\n </animated.div>\n </NoSSR>\n ) : (\n <Border />\n )}\n {mobile && !leanMode && (\n <ExtensionPoint id=\"user-address\" variation=\"bar\" />\n )}\n </React.Fragment>\n )\n}\n\nCollapsible.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n ...lean.propTypes,\n ...collapsible.propTypes,\n}\n\nCollapsible.defaultProps = {\n ...lean.defaultProps,\n ...collapsible.defaultProps,\n}\n\nexport default Collapsible\n\n```"
}
] |
code_store-on-localhost_f3a636d1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/TopMenu.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { ExtensionPoint, useChildBlock } from '../../../../../../vtex.render-runtime'\nimport Collapsible from './Collapsible'\nimport FixedContent from './FixedContent'\nimport { logo, collapsible, icons, lean, searchBar, login } from '../defaults'\nimport styles from '../store-header.css'\n\n/**\n * Top menu that contains the fixed and collapsible parts\n */\nconst TopMenu = ({\n extraHeaders,\n leanMode,\n logoUrl,\n linkUrl,\n logoTitle,\n logoSize,\n showLogin,\n showSearchBar,\n iconClasses,\n labelClasses,\n collapsibleAnimation,\n mobile,\n}) => {\n const hasMenu = !!useChildBlock({ id: 'menu' })\n const hasUnstableMenu = !!useChildBlock({ id: 'unstable--menu' })\n\n if (hasUnstableMenu) {\n console.warn(\n 'The flag `unstable--` from the menu component will be deprecated soon, in favor of just `menu`. The `second-level-menu` will also be deprecated in favor of `menu`.'\n )\n }\n\n return (\n <Fragment>\n {extraHeaders}\n\n <FixedContent\n leanMode={leanMode}\n logoUrl={logoUrl}\n linkUrl={linkUrl}\n logoSize={logoSize}\n logoTitle={logoTitle}\n showSearchBar={showSearchBar}\n showLogin={showLogin}\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n mobile={mobile}\n />\n\n <Collapsible\n collapsibleAnimation={collapsibleAnimation}\n leanMode={leanMode}\n mobile={mobile}\n >\n {hasMenu || hasUnstableMenu ? (\n <div className={styles.topMenuCompatibilityContainer}>\n <div className=\"flex flex-grow-1\" />\n <ExtensionPoint id={hasMenu ? 'menu' : 'unstable--menu'} />\n <div className=\"flex flex-grow-1\" />\n </div>\n ) : (\n <ExtensionPoint id=\"category-menu\" />\n )}\n </Collapsible>\n </Fragment>\n )\n}\n\nTopMenu.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n /** Very top aditional sections */\n extraHeaders: PropTypes.element,\n ...lean.propTypes,\n ...login.propTypes,\n ...searchBar.propTypes,\n ...logo.propTypes,\n ...icons.propTypes,\n ...collapsible.propTypes,\n}\n\nTopMenu.defaultProps = {\n ...lean.defaultProps,\n ...login.defaultProps,\n ...searchBar.defaultProps,\n ...logo.defaultProps,\n ...icons.defaultProps,\n ...collapsible.defaultProps,\n}\n\nexport default TopMenu\n\n```"
}
] |
code_store-on-localhost_27ba849a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/Actions.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { ExtensionPoint } from '../../../../../../vtex.render-runtime'\nimport { FormattedMessage } from 'react-intl'\nimport ButtonWithIcon from '../../../Styleguide/ButtonWithIcon'\nimport IconSearch from '../../../StoreIcons/IconSearch'\nimport { lean, icons, searchBar, login } from '../defaults'\n\nimport styles from '../store-header.css'\n\n/**\n * Represents the header icon buttons\n */\nconst Actions = ({\n showSearchBar,\n leanMode,\n iconClasses,\n labelClasses,\n showLogin,\n onActiveSearch,\n mobile,\n}) => {\n return (\n <div\n className={`${\n styles.topMenuIcons\n } flex justify-end flex-grow-1 flex-grow-0-ns items-center order-1-s ml-auto-s order-2-ns`}\n >\n {mobile && (\n <div className=\"flex mr3\">\n {showSearchBar && !leanMode && (\n <ButtonWithIcon\n icon={\n <span className={iconClasses}>\n <IconSearch />\n </span>\n }\n variation=\"tertiary\"\n onClick={onActiveSearch}\n />\n )}\n\n {showLogin && (\n <ExtensionPoint\n id=\"login\"\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n />\n )}\n\n {!leanMode && (\n <ExtensionPoint\n id=\"minicart\"\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n />\n )}\n </div>\n )}\n\n {!mobile && (\n <div className=\"flex\">\n {showLogin && (\n <ExtensionPoint\n id=\"login\"\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n iconLabel={\n <FormattedMessage id=\"store/header.topMenu.login.icon.label\" />\n }\n />\n )}\n\n {!leanMode && (\n <ExtensionPoint\n id=\"minicart\"\n iconClasses={iconClasses}\n labelClasses={labelClasses}\n iconLabel={\n <FormattedMessage id=\"store/header.topMenu.minicart.icon.label\" />\n }\n />\n )}\n </div>\n )}\n </div>\n )\n}\n\nActions.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n /** Callback function for search active */\n onActiveSearch: PropTypes.func,\n ...lean.propTypes,\n ...login.propTypes,\n ...searchBar.propTypes,\n ...icons.propTypes,\n}\n\nActions.defaultProps = {\n onActiveSearch: () => {},\n ...lean.defaultProps,\n ...login.defaultProps,\n ...searchBar.defaultProps,\n ...icons.defaultProps,\n}\n\nexport default Actions\n\n```"
}
] |
code_store-on-localhost_d83dac8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/SearchBar.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { FormattedMessage } from 'react-intl'\nimport { Adopt } from 'react-adopt'\nimport { ExtensionPoint } from '../../../../../../vtex.render-runtime'\nimport Button from '../../../Styleguide/Button'\nimport classNames from 'classnames'\nimport { icons } from '../defaults'\n\nimport styles from '../store-header.css'\n\n/**\n * Represents the search bar of the header\n */\nconst SearchBar = ({ onCancel, iconClasses, mobile }) => {\n const searchBarClassNames = classNames(\n `${styles.topMenuSearchBar} flex pa2-m flex-grow-1`,\n mobile ? 'justify-between' : 'justify-center'\n )\n\n const cancelClassNames = classNames(`${iconClasses} ttl`)\n\n return (\n <div className={searchBarClassNames}>\n <div className=\"w-75\">\n <Adopt\n mapper={{\n placeholder: <FormattedMessage id=\"store/header.search-placeholder\" />,\n emptyPlaceholder: (\n <FormattedMessage id=\"store/header.search-emptyPlaceholder\" />\n ),\n }}\n >\n {({ placeholder, emptyPlaceholder }) => (\n <ExtensionPoint\n id=\"search-bar\"\n placeholder={placeholder}\n emptyPlaceholder={emptyPlaceholder}\n autoFocus={mobile}\n hasIconLeft={mobile}\n iconClasses={iconClasses}\n />\n )}\n </Adopt>\n </div>\n {mobile && (\n <div className=\"w-25 pa2-m pt2-s\">\n <Button size=\"small\" variation=\"tertiary\" onClick={onCancel}>\n <span className={cancelClassNames}>\n <FormattedMessage id=\"store/header.search-cancel\" />\n </span>\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nSearchBar.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n /** Callback function on cancel */\n onCancel: PropTypes.func,\n ...icons.propTypes,\n}\n\nSearchBar.defaultProps = {\n onCancel: () => {},\n ...icons.defaultProps,\n}\n\nexport default SearchBar\n\n```"
}
] |
code_store-on-localhost_b9e907f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/Logo.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { ExtensionPoint, Link } from '../../../../../../vtex.render-runtime'\nimport PropTypes from 'prop-types'\nimport { logo } from '../defaults'\n\nimport styles from '../store-header.css'\n\n/**\n * Represents the header logo\n */\nconst Logo = ({ logoUrl, logoTitle, linkUrl, logoSize, mobile }) => {\n return (\n <div className={`${styles.topMenuLogo} pv2 mr5`}>\n <Link to={linkUrl} className={`outline-0 ${styles.logoLink}`}>\n <ExtensionPoint\n id=\"logo\"\n url={logoUrl}\n title={logoTitle}\n width={mobile ? logoSize.mobile.width : logoSize.desktop.width}\n height={mobile ? logoSize.mobile.height : logoSize.desktop.height}\n isMobile={mobile}\n />\n </Link>\n </div>\n )\n}\n\nLogo.propTypes = {\n /** If it's mobile mode */\n mobile: PropTypes.bool.isRequired,\n ...logo.propTypes,\n}\n\nLogo.defaultProps = {\n ...logo.defaultProps,\n}\n\nexport default Logo\n\n```"
}
] |
code_store-on-localhost_da736455
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/hooks/useScrollDirection.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useEffect } from 'react'\nimport useScroll from './useScroll'\n\n/**\n * Hook that handles the scroll direction\n * @returns {Number, Boolean, Boolean} - the current scroll value and if the scroll is up, or down\n */\nconst useScrollDirection = () => {\n const { scroll } = useScroll()\n const [scrollingUp, setScrollingUp] = useState(false)\n const [lastScroll, setLastScroll] = useState(0)\n\n useEffect(() => {\n setLastScroll(scroll)\n setScrollingUp(lastScroll > scroll)\n }, [scroll])\n\n return { scroll, scrollingUp }\n}\n\nexport default useScrollDirection\n\n```"
}
] |
code_store-on-localhost_8537c8f0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/hooks/useScroll.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useEffect } from 'react'\nimport throttle from 'throttleit'\n\n/**\n * Hook that handles the scroll position\n * @returns {Number} - scroll position value\n */\nconst useScroll = () => {\n const [scroll, setScroll] = useState(0)\n\n useEffect(() => {\n const handleScroll = () => {\n setScroll(window.scrollY)\n }\n const throttled = throttle(handleScroll, 100)\n window.addEventListener('scroll', throttled)\n return () => window.removeEventListener('scroll', throttled)\n }, [])\n\n return { scroll }\n}\n\nexport default useScroll\n\n```"
}
] |
code_store-on-localhost_5c158976
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/hooks/useDevice.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useLayoutEffect } from 'react'\nimport { useRuntime } from '../../../../../../vtex.render-runtime'\nimport { debounce } from 'debounce'\n\n/**\n * Hook that handles dynamic device change on resize\n * @param {Number} mobileBreakpoint - break point of mobile change\n * @returns {Boolean, Boolean} - if its mobile or desktop\n */\nconst useDevice = (mobileBreakpoint = 640) => {\n const { hints } = useRuntime()\n\n const isMobile = !!window.innerWidth\n ? window.innerWidth <= mobileBreakpoint\n : hints.mobile\n\n const [mobile, setMobile] = useState(isMobile)\n const [desktop, setDesktop] = useState(!isMobile)\n\n useLayoutEffect(() => {\n const handleResize = () => {\n setMobile(window.innerWidth <= mobileBreakpoint)\n setDesktop(window.innerWidth > mobileBreakpoint)\n }\n const debounced = debounce(handleResize, 100)\n window.addEventListener('resize', debounced)\n window.addEventListener('load', handleResize)\n return () => {\n window.removeEventListener('resize', debounced)\n window.removeEventListener('load', handleResize)\n }\n }, [mobileBreakpoint])\n\n return {\n mobile,\n desktop,\n }\n}\n\nexport default useDevice\n\n```"
}
] |
code_store-on-localhost_aae71ce6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/Helpers/Spacer.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { spacer } from '../../defaults'\nimport useDevice from '../../hooks/useDevice'\n\n/**\n * Spacer necessary to content due fixed Header\n */\nconst Spacer = ({ spacerHeightDesktop, spacerHeightMobile, spacerWidth, containerHeight }) => {\n const { desktop } = useDevice()\n\n const height = containerHeight || (desktop ? spacerHeightDesktop : spacerHeightMobile)\n\n return (\n <div\n className=\"z-1 bg-base w-100 relative\"\n style={{\n height,\n width: spacerWidth,\n }}\n />\n )\n}\n\nSpacer.propTypes = {\n ...spacer.propTypes,\n}\n\nSpacer.defaultProps = {\n ...spacer.defaultProps,\n}\n\nexport default Spacer\n\n```"
}
] |
code_store-on-localhost_f969bf78
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/header/legacy/components/Helpers/Border.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\n/**\n * Simple border\n */\nconst Border = () => {\n return (\n <div\n className=\"bb bw1 b--muted-4 relative\"\n style={{\n top: 'inherit',\n boxSizing: 'content-box',\n zIndex: -2,\n }}\n />\n )\n}\n\nexport default Border\n\n```"
}
] |
code_store-on-localhost_717766ac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/mutations/updateItems.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateItems($orderFormId: String, $items: [OrderFormItemInput]) {\n updateItems(orderFormId: $orderFormId, items: $items) @context(provider:\"vtex.store-graphql\") {\n cacheId\n orderFormId\n value\n totalizers {\n id\n name\n value\n }\n items {\n id\n name\n imageUrl\n detailUrl\n productRefId\n additionalInfo {\n brandName\n }\n productCategoryIds\n productCategories\n skuName\n quantity\n sellingPrice\n listPrice\n parentItemIndex\n parentAssemblyBinding\n seller\n cartIndex\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n }\n shippingData {\n address {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n }\n availableAddresses {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n }\n }\n clientProfileData {\n email\n firstName\n }\n storePreferencesData {\n countryCode\n currencyCode\n timeZone\n }\n checkedInPickupPointId\n isCheckedIn\n }\n}\n\n```"
}
] |
code_store-on-localhost_7a1f440c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/mutations/updateOrderFormCheckin.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateOrderFormCheckin(\n $orderFormId: String\n $checkin: OrderFormCheckinInput\n) {\n updateOrderFormCheckin(orderFormId: $orderFormId, checkin: $checkin) @context(provider:\"vtex.store-graphql\"){\n isCheckedIn\n checkedInPickupPointId\n shippingData {\n selectedAddresses {\n id\n street\n number\n receiverName\n complement\n neighborhood\n country\n state\n geoCoordinates\n postalCode\n city\n reference\n addressName\n addressType\n }\n }\n }\n}\n```"
}
] |
code_store-on-localhost_c62194be
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/mutations/updateOrderFormProfile.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateOrderFormProfile(\n $orderFormId: String\n $fields: OrderFormProfileInput\n) {\n updateOrderFormProfile(orderFormId: $orderFormId, fields: $fields) @context(provider:\"vtex.store-graphql\"){\n orderFormId\n }\n}\n\n```"
}
] |
code_store-on-localhost_defeecee
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/mutations/addToCart.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation addItem($orderFormId: String, $items: [OrderFormItemInput], $utmParams: OrderFormInputUTMParams, $utmiParams: OrderFormInputUTMIParams) {\n addItem(orderFormId: $orderFormId, items: $items, utmParams: $utmParams, utmiParams: $utmiParams) @context(provider:\"vtex.store-graphql\") {\n cacheId\n orderFormId\n value\n totalizers {\n id\n name\n value\n }\n items {\n id\n name\n imageUrl\n detailUrl\n productRefId\n additionalInfo {\n brandName\n }\n productCategoryIds\n productCategories\n skuName\n quantity\n sellingPrice\n listPrice\n parentItemIndex\n parentAssemblyBinding\n seller\n cartIndex\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n }\n shippingData {\n address {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n }\n availableAddresses {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n }\n }\n clientProfileData {\n email\n firstName\n }\n storePreferencesData {\n countryCode\n currencyCode\n timeZone\n }\n checkedInPickupPointId\n isCheckedIn\n }\n}\n\n```"
}
] |
code_store-on-localhost_51e1fac9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/mutations/updateOrderFormShipping.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateOrderFormShipping(\n $orderFormId: String\n $address: OrderFormAddressInput\n) {\n updateOrderFormShipping(orderFormId: $orderFormId, address: $address) @context(provider:\"vtex.store-graphql\"){\n orderFormId\n isCheckedIn\n checkedInPickupPointId\n shippingData {\n address {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n availableAddresses {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_e1c2961e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/recommendationsAndBenefits.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\n# File deprecated. To be removed in next major!\nquery RecommendationsAndBenefits(\n $slug: String\n $identifier: ProductUniqueIdentifier\n) {\n product(slug: $slug, identifier: $identifier)\n @context(provider: \"vtex.search-graphql\") {\n cacheId\n recommendations {\n view {\n cacheId\n productId\n productName\n description\n link\n linkText\n brand\n items {\n name\n itemId\n referenceId {\n Value\n }\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n }\n }\n buy {\n cacheId\n productId\n productName\n description\n link\n linkText\n brand\n items {\n name\n itemId\n referenceId {\n Value\n }\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n }\n }\n similars {\n cacheId\n productId\n productName\n description\n link\n linkText\n brand\n items {\n name\n itemId\n referenceId {\n Value\n }\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n }\n }\n }\n benefits {\n featured\n id\n name\n items {\n benefitProduct {\n cacheId\n productName\n productId\n description\n linkText\n categoryId\n brand\n properties {\n name\n values\n }\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n variations {\n name\n }\n }\n }\n discount\n minQuantity\n benefitSKUIds\n }\n teaserType\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_ecd94df5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/product.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Product(\n $slug: String\n $identifier: ProductUniqueIdentifier\n $skipCategoryTree: Boolean = false\n) {\n product(slug: $slug, identifier: $identifier)\n @context(provider: \"vtex.search-graphql\") {\n cacheId\n productName\n productId\n description\n titleTag\n metaTagDescription\n linkText\n productReference\n categoryId\n categories\n categoryTree @skip(if: $skipCategoryTree) {\n id\n name\n href\n }\n brand\n brandId\n properties {\n name\n values\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images(quantity: 10) {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n videos {\n videoUrl\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n discountHighlights {\n name\n }\n teasers {\n name\n conditions {\n minimumQuantity\n parameters {\n name\n value\n }\n }\n effects {\n parameters {\n name\n value\n }\n }\n }\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n variations {\n name\n values\n }\n kitItems {\n itemId\n amount\n product {\n productName\n productId\n description\n linkText\n categoryTree {\n id\n name\n href\n }\n categoryId\n brand\n properties {\n name\n values\n }\n }\n sku {\n itemId\n name\n referenceId {\n Key\n Value\n }\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n discountHighlights {\n name\n }\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n }\n }\n attachments {\n id\n name\n required\n }\n }\n skuSpecifications {\n field {\n name\n }\n values {\n name\n }\n }\n itemMetadata {\n items {\n id\n name\n imageUrl\n seller\n assemblyOptions {\n id\n name\n required\n inputValues {\n label\n maxLength\n type\n domain\n defaultValue\n }\n composition {\n minQuantity\n maxQuantity\n items {\n id\n minQuantity\n maxQuantity\n priceTable\n seller\n initialQuantity\n }\n }\n }\n }\n priceTable {\n type\n values {\n id\n assemblyId\n price\n }\n }\n }\n productClusters {\n id\n name\n }\n clusterHighlights {\n id\n name\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_c012e54d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/productBenefits.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery ProductBenefits($slug: String, $identifier: ProductUniqueIdentifier) {\n product(slug: $slug, identifier: $identifier)\n @context(provider: \"vtex.search-graphql\") {\n cacheId\n benefits {\n featured\n id\n name\n items {\n benefitProduct {\n cacheId\n productName\n productId\n description\n linkText\n categoryId\n brand\n properties {\n name\n values\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n }\n }\n variations {\n name\n }\n }\n }\n discount\n minQuantity\n benefitSKUIds\n }\n teaserType\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_60649c60
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/productSearch.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery productSearch(\n $query: String\n $map: String\n $facetQuery: String\n $facetMap: String\n $orderBy: String\n $priceRange: String\n $from: Int\n $to: Int\n $withFacets: Boolean = true\n) {\n products(\n query: $query\n map: $map\n orderBy: $orderBy\n priceRange: $priceRange\n from: $from\n to: $to\n ) @context(provider: \"vtex.search-graphql\") {\n cacheId\n productId\n description\n productName\n linkText\n brand\n link\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n cacheId\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n commertialOffer {\n discountHighlights {\n name\n }\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n }\n }\n }\n productClusters {\n id\n name\n }\n }\n facets(query: $facetQuery, map: $facetMap)\n @include(if: $withFacets)\n @context(provider: \"vtex.search-graphql\") {\n departments {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n brands {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n specificationFilters {\n name\n facets {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n }\n categoriesTrees {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n }\n }\n }\n priceRanges {\n quantity\n name\n link\n linkEncoded\n slug\n map\n }\n recordsFiltered\n # Backwards compatibility with search-result v3\n Departments {\n Quantity\n Name\n Link\n }\n Brands {\n Quantity\n Name\n Link\n }\n SpecificationFilters {\n name\n facets {\n Quantity\n Name\n Link\n }\n }\n CategoriesTrees {\n Id\n Quantity\n Name\n Link\n href\n name\n Children {\n Id\n Quantity\n Name\n Link\n href\n name\n Children {\n Id\n Quantity\n Name\n Link\n href\n name\n }\n }\n }\n PriceRanges {\n Quantity\n Name\n Link\n Slug\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_1862cbb3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/orderForm.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\n query orderForm {\n orderForm @context(provider:\"vtex.store-graphql\"){\n cacheId\n orderFormId\n userProfileId\n customData {\n customApps {\n id\n fields\n }\n }\n value\n totalizers {\n id\n name\n value\n }\n items {\n id\n name\n imageUrl\n detailUrl\n productRefId\n additionalInfo {\n brandName\n }\n productCategoryIds\n productCategories\n skuName\n quantity\n sellingPrice\n listPrice\n parentItemIndex\n parentAssemblyBinding\n cartIndex\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n assemblyOptions {\n added {\n item {\n name\n sellingPrice\n quantity\n sellingPriceWithAssemblies\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n }\n normalizedQuantity\n choiceType\n extraQuantity\n }\n removed {\n removedQuantity\n initialQuantity\n name\n }\n parentPrice\n }\n seller\n }\n shippingData {\n address {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n availableAddresses {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n }\n clientProfileData {\n email\n firstName\n lastName\n }\n storePreferencesData {\n countryCode\n currencyCode\n timeZone\n }\n checkedInPickupPointId\n isCheckedIn\n }\n}\n\n```"
}
] |
code_store-on-localhost_600cd5cb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/pwaData.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery pwaData {\n pwaSettings {\n disablePrompt\n promptOnCustomEvent\n }\n manifest {\n theme_color\n }\n iOSIcons {\n src\n type\n sizes\n }\n splashes {\n src\n type\n sizes\n }\n}\n```"
}
] |
code_store-on-localhost_0a4db688
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/search.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery search(\n $query: String\n $map: String\n $rest: String\n $orderBy: String\n $priceRange: String\n $from: Int\n $to: Int\n $withFacets: Boolean = true\n) {\n search(\n query: $query\n map: $map\n rest: $rest\n orderBy: $orderBy\n priceRange: $priceRange\n from: $from\n to: $to\n ) @context(provider: \"vtex.store-graphql\") {\n titleTag\n metaTagDescription\n facets @include(if: $withFacets) {\n Departments {\n Quantity\n Name\n Link\n }\n Brands {\n Quantity\n Name\n Link\n }\n SpecificationFilters {\n name\n facets {\n Quantity\n Name\n Link\n }\n }\n CategoriesTrees {\n Id\n Quantity\n Name\n Link\n href\n name\n Children {\n Id\n Quantity\n Name\n Link\n href\n name\n Children {\n Id\n Quantity\n Name\n Link\n href\n name\n }\n }\n }\n PriceRanges {\n Quantity\n Name\n Link\n Slug\n }\n }\n products {\n cacheId\n categories\n categoryTree {\n name\n href\n }\n productId\n description\n productName\n linkText\n brand\n link\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n cacheId\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n commertialOffer {\n discountHighlights {\n name\n }\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n }\n }\n }\n productClusters {\n id\n name\n }\n }\n recordsFiltered\n }\n}\n\n```"
}
] |
code_store-on-localhost_2dca2010
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/searchMetadata.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery SearchMetadata($query: String, $map: String) {\n searchMetadata(query: $query, map: $map)\n @context(provider: \"vtex.search-graphql\") {\n titleTag\n metaTagDescription\n }\n}\n\n```"
}
] |
code_store-on-localhost_b34217e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/facets.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery facets(\n $query: String\n $map: String\n $hideUnavailableItems: Boolean = false\n $behavior: String = \"Static\"\n) {\n facets(query: $query, map: $map, hideUnavailableItems: $hideUnavailableItems, behavior: $behavior)\n @context(provider: \"vtex.search-graphql\") {\n departments {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n brands {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n specificationFilters {\n name\n facets {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n }\n categoriesTrees {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n }\n }\n }\n }\n }\n priceRanges {\n quantity\n name\n link\n linkEncoded\n slug\n map\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_a9afcd30
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/session.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Session {\n getSession {\n id\n adminUserId\n impersonable\n adminUserEmail\n address {\n cacheId\n id\n addressId\n userId\n receiverName\n complement\n neighborhood\n country\n state\n number\n street\n geoCoordinates\n postalCode\n city\n reference\n addressName\n addressType\n }\n profile {\n id\n firstName\n lastName\n email\n }\n impersonate {\n profile {\n phone\n email\n lastName\n document\n firstName\n }\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_86528c35
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/address.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery address {\n orderForm @context(provider:\"vtex.store-graphql\"){\n pickupPointCheckedIn {\n friendlyName\n }\n cacheId\n orderFormId\n shippingData {\n address {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n availableAddresses {\n id\n neighborhood\n complement\n number\n street\n postalCode\n city\n reference\n addressName\n addressType\n geoCoordinates\n state\n receiverName\n country\n }\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_21980075
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/productSearchV2.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery productSearchV2(\n $query: String\n $map: String\n $facetQuery: String\n $facetMap: String\n $category: String\n $collection: String\n $specificationFilters: [String]\n $orderBy: String\n $priceRange: String\n $from: Int\n $to: Int\n $withFacets: Boolean = true\n $hideUnavailableItems: Boolean = false\n $skusFilter: ItemsFilter = ALL_AVAILABLE\n $simulationBehavior: SimulationBehavior = default\n) {\n productSearch(\n query: $query\n map: $map\n category: $category\n collection: $collection\n specificationFilters: $specificationFilters\n orderBy: $orderBy\n priceRange: $priceRange\n from: $from\n to: $to\n hideUnavailableItems: $hideUnavailableItems\n simulationBehavior: $simulationBehavior\n ) @context(provider: \"vtex.search-graphql\") {\n products {\n cacheId\n productId\n description\n productName\n productReference\n linkText\n brand\n brandId\n link\n categories\n priceRange {\n sellingPrice {\n highPrice\n lowPrice\n }\n listPrice {\n highPrice\n lowPrice\n }\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n items(filter: $skusFilter) {\n itemId\n name\n nameComplete\n complementName\n ean\n variations {\n name\n values\n }\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n cacheId\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n commertialOffer {\n discountHighlights {\n name\n }\n teasers {\n name\n conditions {\n minimumQuantity\n parameters {\n name\n value\n }\n }\n effects {\n parameters {\n name\n value\n }\n }\n }\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n }\n }\n }\n productClusters {\n id\n name\n }\n properties {\n name\n values\n }\n }\n recordsFiltered\n breadcrumb {\n name\n href\n }\n }\n facets(\n query: $facetQuery\n map: $facetMap\n hideUnavailableItems: $hideUnavailableItems\n ) @include(if: $withFacets) @context(provider: \"vtex.search-graphql\") {\n departments {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n brands {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n specificationFilters {\n name\n facets {\n quantity\n name\n link\n linkEncoded\n map\n selected\n value\n }\n }\n categoriesTrees {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n children {\n id\n quantity\n name\n link\n href\n linkEncoded\n map\n selected\n value\n }\n }\n }\n }\n }\n priceRanges {\n quantity\n name\n link\n linkEncoded\n slug\n map\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_9cbf5fbc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/UNSTABLE__productCategoryTree.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery ProductCategoryTree($slug: String, $identifier: ProductUniqueIdentifier) {\n product(slug: $slug, identifier: $identifier)\n @context(provider: \"vtex.search-graphql\") {\n cacheId\n categoryTree {\n id\n name\n href\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_76cb3cae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreResources/queries/productPreview.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nfragment product on Product {\n cacheId\n productId\n productName\n linkText\n titleTag\n metaTagDescription\n categories\n categoryTree {\n name\n href\n }\n items {\n itemId\n name\n nameComplete\n complementName\n ean\n referenceId {\n Key\n Value\n }\n measurementUnit\n unitMultiplier\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n }\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_69c0e9fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/routes.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { stringify } from 'query-string'\nimport { isEmpty } from 'ramda'\nimport { parse, format } from 'url'\n\n// import navigationPageQuery from '../queries/navigationPage.graphql'\n// import routePreviews from '../queries/routePreviews.graphql'\nimport { generateExtensions } from './blocks'\nimport { fetchWithRetry } from './fetch'\nimport { parseMessages } from './messages'\n\nconst navigationPageQuery: any = ''\nconst routePreviews: any = ''\n\nconst parsePageQueryResponse = (\n page: any\n): any => {\n const {\n appsEtag,\n appsSettingsJSON,\n blocksJSON,\n blocksTreeJSON,\n contentMapJSON,\n cacheHintsJSON,\n componentsJSON,\n extensionsJSON,\n messages,\n pagesJSON,\n page: {\n blockId,\n canonicalPath,\n metaTags,\n pageContext: { id, type },\n routeId,\n title,\n },\n } = page\n\n const [\n blocks,\n blocksTree,\n contentMap,\n cacheHints,\n components,\n pages,\n settings,\n ] = [\n blocksJSON,\n blocksTreeJSON,\n contentMapJSON,\n cacheHintsJSON,\n componentsJSON,\n pagesJSON,\n appsSettingsJSON,\n ].map(json => JSON.parse(json))\n\n const extensions = isEmpty(blocksTree)\n ? JSON.parse(extensionsJSON)\n : generateExtensions(blocksTree, blocks, contentMap, pages[routeId])\n\n return {\n appsEtag,\n cacheHints,\n blocks,\n blocksTree,\n contentMap,\n components,\n extensions,\n matchingPage: {\n blockId,\n canonicalPath,\n metaTags,\n pageContext: { id, type },\n routeId,\n title,\n },\n messages: parseMessages(messages),\n pages,\n settings,\n }\n}\n\nconst parseDefaultPagesQueryResponse = (\n defaultPages: any\n): any => {\n const { componentsJSON } = defaultPages\n const components = JSON.parse(componentsJSON)\n return {\n components,\n }\n}\n\nconst runtimeFields = [\n 'appsEtag',\n 'blocks',\n 'blocksTree',\n 'components',\n 'contentMap',\n 'extensions',\n 'messages',\n 'page',\n 'pages',\n 'query',\n 'queryData',\n 'route',\n 'runtimeMeta',\n 'settings',\n].join(',')\n\nexport const fetchServerPage = async ({\n fetcher,\n path,\n query: rawQuery,\n}: {\n path: string\n query?: Record<string, string>\n fetcher: any['fetch']\n}): Promise<any> => {\n const parsedUrl = parse(path)\n parsedUrl.search = undefined\n parsedUrl.query = {\n ...rawQuery,\n __pickRuntime: runtimeFields,\n } as any\n const url = format(parsedUrl)\n const page: any = await fetchWithRetry(\n url,\n {\n credentials: 'same-origin',\n headers: {\n accept: 'application/json',\n },\n },\n fetcher\n ).then(({ response }) => response.json())\n const {\n blocksTree,\n blocks,\n contentMap,\n extensions: pageExtensions,\n pages,\n route,\n route: { routeId },\n queryData,\n } = page\n if (routeId === 'redirect') {\n window.location.href = route.path\n }\n\n const queryString = stringify(rawQuery || {})\n const routePath = `${path}${queryString ? '?' + queryString : queryString}`\n\n const extensions =\n !isEmpty(blocksTree) && blocksTree && blocks && contentMap\n ? generateExtensions(blocksTree, blocks, contentMap, pages[routeId])\n : pageExtensions\n\n return {\n ...page,\n extensions,\n matchingPage: {\n ...route,\n path: routePath,\n },\n queryData,\n }\n}\n\nexport const fetchNavigationPage = ({\n apolloClient,\n routeId,\n declarer,\n production,\n paramsJSON,\n renderMajor,\n skipCache,\n query,\n}: any) =>\n apolloClient\n .query({\n fetchPolicy: production && !skipCache ? 'cache-first' : 'network-only',\n query: navigationPageQuery,\n variables: {\n declarer,\n params: paramsJSON,\n production,\n query,\n renderMajor,\n routeId,\n },\n })\n .then(\n ({\n data: { navigationPage: pageData },\n errors,\n }) =>\n errors ? Promise.reject(errors) : parsePageQueryResponse(pageData)\n )\n\nconst getRoutesParam = (routeIds: string[], pages: any) => {\n return routeIds\n .filter(routeId => routeId in pages)\n .map(routeId => {\n const page = pages[routeId]\n return {\n declarer: page.declarer,\n routeId,\n }\n })\n}\n\nexport const fetchDefaultPages = ({\n apolloClient,\n pages,\n routeIds,\n renderMajor,\n}: any) => {\n return apolloClient\n .query({\n query: routePreviews,\n variables: { renderMajor, routes: getRoutesParam(routeIds, pages) },\n })\n .then(\n ({ data: { defaultPages }, errors }) => {\n return errors\n ? Promise.reject(errors)\n : parseDefaultPagesQueryResponse(defaultPages)\n }\n )\n}\n\n```"
}
] |
code_store-on-localhost_994d2aaf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/registerComponent.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { path } from 'ramda'\nimport { ComponentType } from 'react'\n\nimport maybeWrapWithHMR from './withHMR'\n\nconst loadedComponents: Record<string, { implementer: any }> = {}\n\nexport const isComponentType = (Arg: any): Arg is ComponentType => {\n const isFunction = typeof Arg === 'function'\n\n /** If Arg is a function, assumes an UpperCamelCase naming convention\n * for components, and lowerCamelCase for functions.\n * (See https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)\n * If the function name is unable to be determined, defaults\n * to true (i.e. assumes the function is probably a component)\n *\n * This is needed so that functions exported on IO (e.g. HOC) don't\n * get treated as components, so they can be callable.\n */\n if (isFunction) {\n const name: string | undefined = path(\n ['prototype', 'constructor', 'name'],\n Arg\n )\n if (!name) {\n return true\n }\n\n const firstChar = name.charAt(0)\n\n if (!firstChar || firstChar === '') {\n return true\n }\n\n const isFirstCharUpperCase = firstChar.toUpperCase() === firstChar\n\n return isFirstCharUpperCase\n }\n\n return !!(Arg && Arg.prototype && Arg.prototype.render)\n}\n\nconst idToAppAtMajor = (appId: string) => {\n const [name, version] = appId.split('@')\n const [major] = version.split('.')\n return `${name}@${major}.x`\n}\n\nexport const getLoadedComponent = (componentLocator: string) => {\n return (\n loadedComponents[componentLocator] &&\n loadedComponents[componentLocator].implementer\n )\n}\n\nexport default (\n module: any,\n InitialImplementer: any,\n app: string,\n name: string,\n lazy = false\n) => {\n const componentLocators = [`${app}/${name}`, `${idToAppAtMajor(app)}/${name}`]\n\n if (module.hot || !lazy) {\n const implementer = lazy ? InitialImplementer() : InitialImplementer\n const wrappedComponent = maybeWrapWithHMR(module, implementer)\n componentLocators.forEach(locator => {\n window.__RENDER_8_COMPONENTS__[locator] = wrappedComponent\n loadedComponents[locator] = { implementer: wrappedComponent }\n })\n\n return wrappedComponent\n }\n\n componentLocators.forEach(locator => {\n Object.defineProperty(window.__RENDER_8_COMPONENTS__, locator, {\n get: () => {\n if (loadedComponents[locator]) {\n return loadedComponents[locator].implementer\n }\n\n const implementer = InitialImplementer()\n componentLocators.forEach(eachLocator => {\n loadedComponents[eachLocator] = { implementer }\n })\n\n return implementer\n },\n })\n })\n\n return InitialImplementer\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.