id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_shelf-components_e52769ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/typings/vtex.pixel-manager.d.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.pixel-manager/PixelContext' {\n export const usePixel\n}\n\n```"
}
] |
code_shelf-components_04bccc6a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/typings/graphql.d.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const query: DocumentNode\n export default query\n}\n\n```"
}
] |
code_shelf-components_c2a3d3c7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/typings/vtex.product-summary.d.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.product-summary/ProductSummaryCustom' {\n export const mapCatalogProductToProductSummary: (product: any) => any\n}\n\ndeclare module 'vtex.product-summary' {\n export const ProductSummaryList\n export const ProductSummaryListWithoutQuery\n}\n\n```"
}
] |
code_shelf-components_6ce1475d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/typings/vtex.styleguide.d.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const ButtonWithIcon\n export const ButtonPlain\n export const IconClear\n export const IconPlusLines\n}\n\n```"
}
] |
code_shelf-components_2155ecd8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/queries/productsByIdentifier.gql from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery productsByIdentifier(\n $field: ProductUniqueIdentifierField!\n $values: [ID!]\n) {\n productsByIdentifier(field: $field, values: $values)\n @context(provider: \"vtex.search-graphql\") {\n brand\n brandId\n cacheId\n categoryTree {\n slug\n }\n description\n items {\n images {\n imageLabel\n imageTag\n imageUrl\n }\n itemId\n measurementUnit\n name\n sellers {\n commertialOffer {\n AvailableQuantity\n Installments {\n InterestRate\n Name\n NumberOfInstallments\n TotalValuePlusInterestRate\n Value\n }\n ListPrice\n Price\n PriceWithoutDiscount\n Tax\n discountHighlights {\n name\n }\n taxPercentage\n teasers {\n name\n }\n }\n sellerId\n }\n unitMultiplier\n variations {\n name\n values\n }\n }\n link\n linkText\n priceRange {\n listPrice {\n highPrice\n lowPrice\n }\n sellingPrice {\n highPrice\n lowPrice\n }\n }\n productClusters {\n id\n name\n }\n productId\n productName\n productReference\n properties {\n name\n values\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n }\n}\n\n```"
}
] |
code_shelf-components_78e198ab
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/utils/events.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst enum EventType {\n ProductClick = 'productClick',\n AddToCart = 'addToCart',\n View = 'shelfView',\n}\n\nexport const handleProductClick = (push: (data: any) => void, page: string) => {\n return (product: any) => {\n push({\n page,\n event: 'shelf',\n eventType: EventType.ProductClick,\n product,\n })\n }\n}\n\nexport const handleView = (push: (data: any) => void, page: string) => {\n return (shelf: string) => {\n push({\n page,\n event: 'shelf',\n eventType: EventType.View,\n shelf,\n })\n }\n}\n\n```"
}
] |
code_shelf-components_7d702a46
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/utils/index.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const mapSKUItemsToCartItems = (\n skuItems: Item[]\n): Array<CartItem | null> =>\n skuItems.map(item => {\n const {\n selectedItem: {\n itemId,\n name,\n measurementUnit,\n images,\n referenceId,\n seller,\n sellers,\n },\n product: {\n productId,\n linkText,\n productName,\n brand,\n categories,\n productReference,\n },\n } = item\n const selectedSeller = seller ?? sellers[0]\n\n if (!selectedSeller) {\n return null\n }\n\n return {\n id: itemId,\n productId,\n quantity: 1,\n uniqueId: '',\n detailUrl: `/${linkText}/p`,\n name: productName,\n brand,\n category: categories && categories.length > 0 ? categories[0] : '',\n productRefId: productReference,\n seller: selectedSeller.sellerId,\n variant: name,\n skuName: name,\n price: selectedSeller.commertialOffer.PriceWithoutDiscount * 100,\n listPrice: selectedSeller.commertialOffer.ListPrice * 100,\n sellingPrice: selectedSeller.commertialOffer.Price * 100,\n sellingPriceWithAssemblies: selectedSeller.commertialOffer.Price * 100,\n measurementUnit,\n skuSpecifications: [],\n imageUrl: images[0]?.imageUrl,\n options: [],\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: selectedSeller.commertialOffer.Price,\n },\n referenceId,\n }\n })\n\nexport const sortBaseProductsBySuggestedLists = (\n products: Product[],\n suggestedLists: SuggestedProductsList[]\n) => {\n const ids =\n suggestedLists\n ?.map(list => list.baseProductId)\n .filter(id => id && id !== '') ?? []\n return products?.sort(\n (a: Product, b: Product) =>\n ids.indexOf(a.productId) - ids.indexOf(b.productId)\n )\n}\n\nexport const sortProductsBySuggestedIds = (\n products: Product[],\n suggestedIds: string[]\n) => {\n return products?.sort(\n (a: Product, b: Product) =>\n suggestedIds.indexOf(a.productId) - suggestedIds.indexOf(b.productId)\n )\n}\n\nexport const sortItemsByLists = (\n items: Item[],\n suggestedLists: SuggestedList[]\n) => {\n const ids = suggestedLists.map(list => list.products[list.current].productId)\n const copyItems: Item[] = Object.assign([], items)\n return copyItems.sort(\n (a: Item, b: Item) =>\n ids.indexOf(a.product.productId) - ids.indexOf(b.product.productId)\n )\n}\n\n```"
}
] |
code_shelf-components_7fca1517
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/hooks/useEvents.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useMemo } from 'react'\n\nimport { handleView, handleProductClick } from '../utils/events'\n\nexport const useEvents = (\n recommendation: { shouldSendEvents: boolean },\n push: (data: any) => void,\n page: string\n) => {\n const shouldSendEvents = useMemo(() => {\n return recommendation?.shouldSendEvents\n }, [recommendation])\n const onView = shouldSendEvents ? handleView(push, page) : () => {}\n const onProductClick = shouldSendEvents\n ? handleProductClick(push, page)\n : () => {}\n\n return {\n onView,\n onProductClick,\n }\n}\n\n```"
}
] |
code_shelf-components_4fc0cfef
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/hooks/useOnView.ts from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/** Code borrowed from vtex.render-runtime */\n/* eslint-disable @typescript-eslint/no-use-before-define */\nimport { useEffect, useRef, MutableRefObject } from 'react'\n\ninterface IntersectionEvent {\n entry: IntersectionObserverEntry\n unobserve: () => void\n}\n\ninterface HookOptions {\n ref: MutableRefObject<HTMLElement | null>\n onView?: (event: IntersectionEvent) => any\n threshold?: number\n once?: boolean\n bailOut?: boolean\n initializeOnInteraction?: boolean\n}\n\n/** Hook for detecting when an element is inside the viewport.\n * Differs from react-intersection-observer (https://www.npmjs.com/package/react-intersection-observer)\n * in that this hook doesn't use setState, using a callback approach instead, to improve\n * performance by preventing re-rendering.\n */\nconst useOnView = ({\n ref,\n onView,\n threshold = 0,\n once = false,\n bailOut = false,\n initializeOnInteraction = false,\n}: HookOptions) => {\n const isObserving = useRef(false)\n const didIntersect = useRef(false)\n\n useEffect(() => {\n const initializeObserver = () => {\n const element = ref.current\n\n if (\n bailOut ||\n isObserving.current ||\n !element ||\n !onView ||\n (once && didIntersect.current)\n ) {\n return () => {}\n }\n\n isObserving.current = true\n\n const unobserve = () => {\n if (isObserving.current) {\n observer.unobserve(element)\n isObserving.current = false\n }\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (!entry.isIntersecting) {\n return\n }\n\n if (entry.intersectionRatio < threshold) {\n return\n }\n\n if (once) {\n unobserve()\n }\n\n didIntersect.current = true\n onView({ entry, unobserve })\n })\n\n observer.observe(element)\n\n return unobserve\n }\n\n if (initializeOnInteraction) {\n const cleanUpEvents = () => {\n window?.document?.removeEventListener('scroll', handleInteraction)\n window?.document?.removeEventListener('mouseover', handleInteraction)\n }\n\n let unobserve = () => {\n cleanUpEvents()\n }\n\n const handleInteraction = () => {\n cleanUpEvents()\n unobserve = initializeObserver()\n }\n\n window?.document?.addEventListener('scroll', handleInteraction)\n window?.document?.addEventListener('mouseover', handleInteraction)\n\n return unobserve\n }\n\n return initializeObserver()\n }, [bailOut, initializeOnInteraction, onView, once, ref, threshold])\n}\n\nexport { useOnView }\n\n```"
}
] |
code_shelf-components_95955a73
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/icons/IconRefresh.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\n\ninterface Props {\n size?: number\n color?: string\n}\n\nconst IconRefresh: FC<Props> = ({ size = 16, color = 'currentColor' }) => {\n return (\n <svg width={size} height={size} viewBox=\"0 0 1792 1792\">\n <path\n d=\"M1639 1056q0 5-1 7-64 268-268 434.5t-478 166.5q-146 0-282.5-55t-243.5-157l-129 129q-19 19-45 19t-45-19-19-45v-448q0-26 19-45t45-19h448q26 0 45 19t19 45-19 45l-137 137q71 66 161 102t187 36q134 0 250-65t186-179q11-17 53-117 8-23 30-23h192q13 0 22.5 9.5t9.5 22.5zm25-800v448q0 26-19 45t-45 19h-448q-26 0-45-19t-19-45 19-45l138-138q-148-137-349-137-134 0-250 65t-186 179q-11 17-53 117-8 23-30 23h-199q-13 0-22.5-9.5t-9.5-22.5v-7q65-268 270-434.5t480-166.5q146 0 284 55.5t245 156.5l130-129q19-19 45-19t45 19 19 45z\"\n fill={color}\n />\n </svg>\n )\n}\n\nexport default IconRefresh\n\n```"
}
] |
code_shelf-components_dd2e09d1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/icons/IconEqual.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\n\ninterface Props {\n size?: number\n color?: string\n}\n\nconst IconEqual: FC<Props> = ({ size = 16, color = 'currentColor' }) => {\n return (\n <svg width={size} height={size} viewBox=\"0 0 16 16\" version=\"1.1\">\n <g stroke=\"none\" strokeWidth=\"1\" fill=\"none\" fillRule=\"evenodd\">\n <g fill={color}>\n <path d=\"M0,3 L0,5 C6.76353751e-17,5.55228475 0.44771525,6 1,6 L15,6 C15.5522847,6 16,5.55228475 16,5 L16,3 C16,2.44771525 15.5522847,2 15,2 L1,2 C0.44771525,2 -6.76353751e-17,2.44771525 0,3 Z\" />\n <path d=\"M0,11 L0,13 C6.76353751e-17,13.5522847 0.44771525,14 1,14 L15,14 C15.5522847,14 16,13.5522847 16,13 L16,11 C16,10.4477153 15.5522847,10 15,10 L1,10 C0.44771525,10 -6.76353751e-17,10.4477153 0,11 Z\" />\n </g>\n </g>\n </svg>\n )\n}\n\nexport default IconEqual\n\n```"
}
] |
code_shelf-components_123f181a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/RefreshShelf/index.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect, useMemo, useRef } from 'react'\nimport { useLazyQuery } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { QueryProducts as productsQuery } from 'vtex.store-resources'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\nimport { useRecommendation } from 'vtex.recommendation-context/RecommendationContext'\n\nimport productsByIdentifier from '../../queries/productsByIdentifier.gql'\nimport RefreshProductSummary from './RefreshProductSummary'\nimport SuggestedProducts from './SuggestedProducts'\nimport styles from './styles.css'\nimport {\n sortBaseProductsBySuggestedLists,\n sortProductsBySuggestedIds,\n} from '../../utils'\nimport { useOnView } from '../../hooks/useOnView'\nimport { useEvents } from '../../hooks/useEvents'\n\nenum ProductUniqueIdentifierField {\n id = 'id',\n slug = 'slug',\n ean = 'ean',\n reference = 'reference',\n sku = 'sku',\n}\n\ninterface RefreshShelfProps {\n baseProductTitle?: string\n suggestedProductsTitle?: string\n suggestedLists?: SuggestedProductsList[]\n recommendedLists?: RecommendedList[]\n sliderLayout: {\n showNavigationArrows: string\n showPaginationDots: string\n }\n isSecondary?: boolean\n secondaryBaseProductTitle?: string\n secondarySuggestedProductsTitle?: string\n}\n\nconst parseFilters = ({ id, value }: SpecificationFilter) =>\n `specificationFilter_${id}:${value}`\n\nconst RefreshShelf: StorefrontFunctionComponent<RefreshShelfProps> = ({\n baseProductTitle,\n suggestedProductsTitle,\n suggestedLists,\n recommendedLists,\n isSecondary,\n secondaryBaseProductTitle,\n secondarySuggestedProductsTitle,\n ...props\n}) => {\n const { push } = usePixel()\n const { page } = useRuntime()\n const [current, setCurrent] = useState(0)\n const ref = useRef<HTMLDivElement | null>(null)\n const recommendation = useRecommendation?.()\n const { onView, onProductClick } = useEvents(recommendation, push, page)\n\n useOnView({\n ref,\n onView: () => onView('refresh'),\n once: true,\n initializeOnInteraction: true,\n })\n\n const [\n queryProducts,\n { data: productsData, loading: loadingProducts, called, refetch },\n ] = useLazyQuery(productsQuery, {\n notifyOnNetworkStatusChange: true,\n })\n const currentList = suggestedLists?.[current]\n\n const [\n queryBaseProductsByID,\n {\n data: baseProductsData,\n loading: loadingBaseProducts,\n called: queryBaseProductsCalled,\n refetch: baseProductsRefetch,\n },\n ] = useLazyQuery(productsByIdentifier, { notifyOnNetworkStatusChange: true })\n\n const [\n querySuggestedProductsByID,\n {\n data: suggestedProductsData,\n loading: loadingProductsById,\n called: calledById,\n refetch: refetchQueryById,\n },\n ] = useLazyQuery(productsByIdentifier, { notifyOnNetworkStatusChange: true })\n\n const baseProducts = useMemo(() => {\n if (recommendedLists) {\n return recommendedLists.map((list: RecommendedList) => list.base[0])\n }\n if (!suggestedLists || suggestedLists.length === 0) {\n return []\n }\n if (baseProductsData?.productsByIdentifier) {\n const sortProducts = sortBaseProductsBySuggestedLists(\n baseProductsData?.productsByIdentifier,\n suggestedLists\n )\n return sortProducts\n }\n if (productsData?.products?.[0]) {\n return productsData?.products?.[0]\n }\n }, [baseProductsData, productsData, suggestedLists, recommendedLists])\n\n const suggestedProducts = useMemo(() => {\n if (recommendedLists) {\n return recommendedLists[current].recommended\n }\n if (!suggestedLists) {\n return []\n }\n if (\n currentList?.suggestedProductsIds &&\n suggestedProductsData?.productsByIdentifier\n ) {\n const sortProducts = sortProductsBySuggestedIds(\n suggestedProductsData?.productsByIdentifier,\n currentList.suggestedProductsIds.split(',')\n )\n return sortProducts\n }\n if (productsData?.products) {\n return productsData.products\n }\n }, [\n productsData,\n suggestedLists,\n recommendedLists,\n current,\n currentList,\n suggestedProductsData,\n ])\n\n useEffect(() => {\n if (!suggestedLists || recommendedLists) {\n return\n }\n\n const baseIds = suggestedLists\n .map(list => list.baseProductId)\n .filter(id => id && id !== '')\n\n if (baseIds.length === 0) {\n return\n }\n\n const executeQuery = (variables: Record<string, any>) =>\n queryBaseProductsCalled\n ? baseProductsRefetch(variables)\n : queryBaseProductsByID({ variables })\n\n executeQuery({\n field: ProductUniqueIdentifierField.id,\n values: baseIds,\n })\n }, [\n suggestedLists,\n recommendedLists,\n queryBaseProductsCalled,\n queryBaseProductsByID,\n baseProductsRefetch,\n ])\n\n useEffect(() => {\n const executeQuery = (variables: Record<string, any>) =>\n called ? refetch(variables) : queryProducts({ variables })\n\n if (!suggestedLists || suggestedLists.length === 0 || recommendedLists) {\n executeQuery({\n category: '',\n collection: '',\n specificationFilters: [],\n orderBy: 'OrderByTopSaleDESC',\n from: 0,\n to: 9,\n hideUnavailableItems: false,\n skusFilter: 'ALL_AVAILABLE',\n installmentCriteria: 'MAX_WITHOUT_INTEREST',\n })\n return\n }\n\n if (!currentList) {\n return\n }\n\n if (currentList.suggestedProductsIds) {\n const executeQueryById = (variables: Record<string, any>) =>\n calledById\n ? refetchQueryById(variables)\n : querySuggestedProductsByID({ variables })\n\n const suggestedIds = currentList.suggestedProductsIds.split(',')\n\n executeQueryById({\n field: ProductUniqueIdentifierField.id,\n values: suggestedIds,\n })\n } else {\n const {\n category = '',\n collection,\n hideUnavailableItems = false,\n orderBy = 'OrderByTopSaleDESC',\n specificationFilters = [],\n maxItems = 10,\n skusFilter,\n installmentCriteria,\n } = currentList\n\n executeQuery({\n category,\n ...(collection != null\n ? {\n collection,\n }\n : {}),\n specificationFilters: specificationFilters.map(parseFilters),\n orderBy,\n from: 0,\n to: maxItems - 1,\n hideUnavailableItems,\n skusFilter,\n installmentCriteria,\n })\n }\n }, [\n suggestedLists,\n recommendedLists,\n currentList,\n called,\n calledById,\n queryProducts,\n querySuggestedProductsByID,\n refetch,\n refetchQueryById,\n ])\n\n const handleChangeProduct = () => {\n const newIndex = current < baseProducts?.length - 1 ? current + 1 : 0\n setCurrent(newIndex)\n }\n\n const loading = useMemo(\n () => loadingBaseProducts || loadingProducts || loadingProductsById,\n [loadingBaseProducts, loadingProducts, loadingProductsById]\n )\n\n if (\n !loading &&\n (!baseProducts ||\n !suggestedProducts ||\n !baseProducts.length ||\n !suggestedProducts.length)\n ) {\n return null\n }\n\n return (\n <div\n className={`flex flex-wrap flex-nowrap-ns justify-around ${styles.refreshShelf}`}\n ref={ref}\n >\n <RefreshProductSummary\n title={isSecondary ? secondaryBaseProductTitle : baseProductTitle}\n loading={loading}\n selected={current}\n products={baseProducts}\n onChangeSelected={handleChangeProduct}\n onProductClick={onProductClick}\n />\n <SuggestedProducts\n title={\n isSecondary ? secondarySuggestedProductsTitle : suggestedProductsTitle\n }\n loading={loading}\n products={suggestedProducts}\n sliderProps={props.sliderLayout}\n key={baseProducts?.[current]?.productId}\n onProductClick={onProductClick}\n />\n </div>\n )\n}\n\nRefreshShelf.schema = {\n title: 'admin/editor.refresh-shelf.title',\n}\n\nexport default RefreshShelf\n\n```"
}
] |
code_shelf-components_3189f080
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/RefreshShelf/RefreshProductSummary.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect } from 'react'\nimport { ExtensionPoint } from 'vtex.render-runtime'\nimport ProductSummary from 'vtex.product-summary/ProductSummaryCustom'\nimport { ButtonPlain } from 'vtex.styleguide'\nimport { useIntl, defineMessages } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport IconRefresh from '../../icons/IconRefresh'\nimport ProductSummaryLoader from './ProductSummaryLoader'\nimport styles from './styles.css'\n\ninterface RefreshProductSummaryProps {\n products: Product[]\n selected: number\n loading: boolean\n onChangeSelected?: () => void\n title?: string\n onProductClick: (product: Product) => void\n}\n\nconst messages = defineMessages({\n title: {\n id: 'store/shelf.refresh.refresh-product-summary.title',\n defaultMessage: '',\n },\n})\n\nconst CSS_HANDLES = ['refreshProductSummary', 'refreshProductTitleContainer']\n\nconst RefreshProductSummary: StorefrontFunctionComponent<RefreshProductSummaryProps> = ({\n products,\n selected,\n onChangeSelected,\n loading,\n title,\n onProductClick,\n}) => {\n const intl = useIntl()\n const handles = useCssHandles(CSS_HANDLES)\n const [selectedProduct, setSelectedProduct] = useState(\n products?.[selected]\n ? ProductSummary.mapCatalogProductToProductSummary(products[selected])\n : {}\n )\n\n useEffect(() => {\n if (products?.[selected]) {\n const normalized = ProductSummary.mapCatalogProductToProductSummary(\n products[selected]\n )\n setSelectedProduct(normalized)\n }\n }, [selected, products])\n\n const handleRefresh = () => {\n onChangeSelected?.()\n }\n\n return (\n <div className={`tc w-70 w-40-ns w-20-l ${handles.refreshProductSummary}`}>\n <div\n className={`nowrap mv4 f4 v-mid ${handles.refreshProductTitleContainer}`}\n >\n <span className={`mr3 ${styles.refreshProductTitle}`}>\n {title && title !== '' ? title : intl.formatMessage(messages.title)}\n </span>\n {products?.length > 1 && (\n <ButtonPlain onClick={handleRefresh} className=\"ml2\">\n <IconRefresh size={20} />\n </ButtonPlain>\n )}\n </div>\n {loading && <ProductSummaryLoader />}\n {!loading && selectedProduct && selectedProduct.productId && (\n <div key={selectedProduct.productId}>\n <ExtensionPoint\n id=\"product-summary\"\n product={selectedProduct}\n actionOnClick={() => onProductClick(selectedProduct)}\n />\n </div>\n )}\n </div>\n )\n}\n\nexport default RefreshProductSummary\n\n```"
}
] |
code_shelf-components_7f74b043
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/RefreshShelf/styles.css from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.refreshProductSummary {\n margin-left: 0.25rem;\n margin-right: 0.25rem;\n}\n\n.refreshShelf {\n margin-bottom: 25px;\n}\n\n.suggestedProductsTitleContainer {\n height: 40px;\n font-weight: 600;\n text-transform: uppercase;\n}\n\n.refreshProductTitleContainer {\n margin: 0.75rem;\n text-transform: uppercase;\n font-weight: 600;\n height: 40px;\n}\n\n.suggestedProductsContainer {\n max-width: -webkit-fill-available;\n text-align: center;\n}\n\n.suggestedProductsTitle {\n vertical-align: middle;\n}\n\n.refreshProductTitle {\n vertical-align: middle;\n}\n\n@media screen and (min-width: 64.125em) {\n .suggestedProductsContainer {\n width: 75%;\n }\n}\n\n@media screen and (min-width: 40em) and (max-width: 64.124em) {\n .suggestedProductsContainer {\n width: 60%;\n }\n}\n\n\n.slide {\n margin-bottom: 25px;\n margin-left: .5rem;\n margin-right: .5rem;\n}\n\n```"
}
] |
code_shelf-components_6b54b591
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/RefreshShelf/ProductSummaryLoader.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport ContentLoader from 'react-content-loader'\nimport React from 'react'\n\nconst ProductSummaryLoader = () => (\n <ContentLoader height=\"560\" width=\"300\" speed={2}>\n <rect x=\"0\" y=\"0\" rx=\"3\" ry=\"3\" width=\"100%\" height=\"300\" />\n <rect x=\"0\" y=\"310\" rx=\"3\" ry=\"3\" width=\"100%\" height=\"30\" />\n <rect x=\"0\" y=\"370\" rx=\"3\" ry=\"3\" width=\"50%\" height=\"16\" />\n <rect x=\"0\" y=\"390\" rx=\"3\" ry=\"3\" width=\"80%\" height=\"23\" />\n <rect x=\"0\" y=\"420\" rx=\"3\" ry=\"3\" width=\"80%\" height=\"16\" />\n <rect x=\"0\" y=\"480\" rx=\"3\" ry=\"3\" width=\"100%\" height=\"40\" />\n </ContentLoader>\n)\n\nexport default ProductSummaryLoader\n\n```"
}
] |
code_shelf-components_bb8b2872
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/RefreshShelf/SuggestedProducts.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo } from 'react'\nimport { useIntl, defineMessages } from 'react-intl'\nimport { SliderLayout } from 'vtex.slider-layout'\nimport { ProductSummaryListWithoutQuery } from 'vtex.product-summary'\nimport ProductSummary from 'vtex.product-summary/ProductSummaryCustom'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useDevice } from 'vtex.device-detector'\n\nimport styles from './styles.css'\nimport ProductSummaryLoader from './ProductSummaryLoader'\n\ninterface Props {\n title?: string\n products: any[]\n loading: boolean\n sliderProps?: {\n showNavigationArrows: string\n showPaginationDots: string\n }\n onProductClick: (product: Product) => void\n}\n\nconst messages = defineMessages({\n title: {\n id: 'store/shelf.refresh.suggested-products.title',\n defaultMessage: '',\n },\n})\n\nconst CSS_HANDLES = ['suggestedProductsTitleContainer']\n\nconst itemsPerPage = {\n desktop: 3,\n phone: 1,\n tablet: 1,\n}\n\nconst SliderLayoutLoader = () => (\n <div className=\"flex mh8\">\n <div className=\"mr7\">\n <ProductSummaryLoader />\n </div>\n <div className=\"mr7\">\n <ProductSummaryLoader />\n </div>\n <div>\n <ProductSummaryLoader />\n </div>\n </div>\n)\n\nconst SuggestedProducts: StorefrontFunctionComponent<Props> = ({\n title,\n products,\n loading,\n sliderProps,\n onProductClick,\n}) => {\n const { isMobile } = useDevice()\n const intl = useIntl()\n const handles = useCssHandles(CSS_HANDLES)\n const normalizedProducts = useMemo(\n () =>\n products?.length > 0\n ? products.map(product =>\n ProductSummary.mapCatalogProductToProductSummary(product)\n )\n : [],\n [products]\n )\n\n return (\n <div className={styles.suggestedProductsContainer}>\n <div\n className={`mv4 f4 v-mid ${handles.suggestedProductsTitleContainer}`}\n >\n <span className={styles.suggestedProductsTitle}>\n {title && title !== '' ? title : intl.formatMessage(messages.title)}\n </span>\n </div>\n {(loading || !normalizedProducts) &&\n (isMobile ? <ProductSummaryLoader /> : <SliderLayoutLoader />)}\n {!loading && normalizedProducts?.length > 0 && (\n <ProductSummaryListWithoutQuery\n products={normalizedProducts}\n actionOnProductClick={onProductClick}\n >\n <SliderLayout\n showNavigationArrows={sliderProps?.showNavigationArrows ?? 'always'}\n showPaginationDots={sliderProps?.showPaginationDots ?? 'always'}\n fullWidth={false}\n itemsPerPage={itemsPerPage}\n infinite\n />\n </ProductSummaryListWithoutQuery>\n )}\n </div>\n )\n}\n\nexport default SuggestedProducts\n\n```"
}
] |
code_shelf-components_36c8cef3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/BuyTogether/index.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, Fragment, useMemo, useRef } from 'react'\nimport { FormattedMessage, defineMessages } from 'react-intl'\nimport { IconPlusLines } from 'vtex.styleguide'\nimport { ProductListContext } from 'vtex.product-list-context'\nimport { useProduct } from 'vtex.product-context'\nimport { useTreePath, ExtensionPoint, useRuntime } from 'vtex.render-runtime'\nimport { FormattedCurrency } from 'vtex.format-currency'\nimport ProductSummary from 'vtex.product-summary/ProductSummaryCustom'\nimport { ProductGroupContext } from 'vtex.product-group-context'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\nimport { useRecommendation } from 'vtex.recommendation-context/RecommendationContext'\n\nimport styles from './styles.css'\nimport IconEqual from '../../icons/IconEqual'\nimport ProductSummaryWithActions from './ProductSummaryWithActions'\nimport { mapSKUItemsToCartItems, sortItemsByLists } from '../../utils'\nimport { useOnView } from '../../hooks/useOnView'\nimport { useEvents } from '../../hooks/useEvents'\n\nconst { ProductGroupProvider, useProductGroup } = ProductGroupContext\n\ninterface Props {\n title?: string\n suggestedProducts?: Product[][]\n BuyButton: React.ComponentType<{ skuItems: CartItem[] }>\n}\n\nconst { ProductListProvider } = ProductListContext\n\nconst messages = defineMessages({\n title: {\n id: 'store/shelf.buy-together.title',\n defaultMessage: '',\n },\n totalProducts: {\n id: 'store/shelf.buy-together.total-products.label',\n defaultMessage: '',\n },\n})\n\nconst CSS_HANDLES = [\n 'buyTogetherContainer',\n 'buyTogetherTitleContainer',\n 'buyTogetherTitle',\n 'totalValue',\n]\n\nconst notNull = (item: CartItem | null): item is CartItem => item !== null\n\nconst BuyTogether: StorefrontFunctionComponent<Props> = ({\n title,\n suggestedProducts,\n BuyButton,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { page } = useRuntime()\n const { push } = usePixel()\n const ref = useRef<HTMLDivElement | null>(null)\n const { product: baseProduct } = useProduct() as any\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { items } = useProductGroup()!\n const { treePath } = useTreePath()\n const recommendation = useRecommendation?.()\n const { onView, onProductClick } = useEvents(recommendation, push, page)\n\n useOnView({\n ref,\n onView: () => onView('buy-together'),\n once: true,\n initializeOnInteraction: true,\n })\n\n const [suggestedLists, setSuggestedLists] = useState<SuggestedList[]>(\n suggestedProducts?.map(list => {\n return { products: list, hidden: false, current: 0 }\n }) ?? []\n )\n const normalizedBaseProduct = useMemo(\n () => ProductSummary.mapCatalogProductToProductSummary(baseProduct),\n [baseProduct]\n )\n\n const filteredItems = useMemo(() => {\n const sortedItems = sortItemsByLists(items, suggestedLists)\n return sortedItems.filter((item, index) => {\n if (index === 0) {\n return true\n }\n if (item.quantity === 1) {\n return !suggestedLists[index - 1].hidden\n }\n return !(suggestedLists[index - 1].hidden && suggestedLists[index].hidden)\n })\n }, [items, suggestedLists])\n\n const treePathList =\n (typeof treePath === 'string' && treePath.split('/')) || []\n const trackingId = treePathList[treePathList.length - 1] || 'BuyTogetherShelf'\n\n const onChangeProduct = (index: number) => {\n const newSuggestedLists = suggestedLists.map((list, listIndex) => {\n if (listIndex !== index) {\n return list\n }\n const current =\n list.current + 1 < list.products.length ? list.current + 1 : 0\n return { ...list, current }\n })\n setSuggestedLists(newSuggestedLists)\n }\n\n const onDeleteOrAdd = (index: number) => {\n let newSuggestedLists = []\n if (suggestedLists[index].hidden) {\n newSuggestedLists = suggestedLists.map((list, listIndex) =>\n listIndex !== index ? list : { ...list, hidden: false }\n )\n } else {\n newSuggestedLists = suggestedLists.map((list, listIndex) =>\n listIndex !== index ? list : { ...list, hidden: true }\n )\n }\n setSuggestedLists(newSuggestedLists)\n }\n\n const cartItems = useMemo(() => {\n return mapSKUItemsToCartItems(filteredItems).filter(notNull)\n }, [filteredItems])\n\n const totalProducts = cartItems.length\n const totalPrice = useMemo(() => {\n return cartItems.reduce((total: number, currentItem: CartItem) => {\n return total + currentItem.sellingPrice / 100\n }, 0)\n }, [cartItems])\n\n if (!suggestedLists.length) {\n return null\n }\n\n return (\n <div className={`flex-none tc ${handles.buyTogetherContainer}`} ref={ref}>\n <div className={`mv4 v-mid ${handles.buyTogetherTitleContainer}`}>\n <span className={handles.buyTogetherTitle}>\n {title && title !== '' ? (\n title\n ) : (\n <FormattedMessage {...messages.title} />\n )}\n </span>\n </div>\n <div className=\"flex flex-column flex-row-l\">\n <ProductListProvider listName={trackingId}>\n <div className=\"w-100 w-20-l\">\n <div className={styles.productSummary} />\n <div>\n <ExtensionPoint\n id=\"product-summary\"\n product={normalizedBaseProduct}\n actionOnClick={() => onProductClick(normalizedBaseProduct)}\n />\n </div>\n </div>\n {suggestedLists.map((suggestedList, index) => {\n const { products, current } = suggestedList\n return (\n <Fragment key={`${products[current]?.productId}-${index}`}>\n <div className=\"self-center ma5\">\n <IconPlusLines size={20} />\n </div>\n <ProductSummaryWithActions\n onDeleteOrAdd={onDeleteOrAdd}\n index={index}\n hidden={suggestedList.hidden}\n hideChangeAction={products.length <= 1}\n onChangeProduct={onChangeProduct}\n product={products[current]}\n onProductClick={onProductClick}\n />\n </Fragment>\n )\n })}\n <div className=\"self-center ma5\">\n <IconEqual />\n </div>\n <div className=\"w-100 mh2 mh6-l w-20-l self-center\">\n <div className=\"mb5\">\n <FormattedMessage\n {...messages.totalProducts}\n values={{ total: totalProducts }}\n />\n </div>\n <div className={`mv5 ${handles.totalValue}`}>\n <FormattedCurrency value={totalPrice} />\n </div>\n <BuyButton skuItems={cartItems} />\n </div>\n </ProductListProvider>\n </div>\n </div>\n )\n}\n\nconst EnhancedBuyTogether: StorefrontFunctionComponent<Props> = props => {\n return (\n <ProductGroupProvider>\n <BuyTogether {...props} />\n </ProductGroupProvider>\n )\n}\n\nEnhancedBuyTogether.schema = {\n title: 'admin/editor.buy-together.title',\n}\n\nexport default EnhancedBuyTogether\n\n```"
}
] |
code_shelf-components_688c066b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/BuyTogether/styles.css from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.productSummary {\n padding-bottom: 3rem;\n}\n\n.totalValue {\n font-size: 1.25rem;\n font-weight: 600;\n}\n\n.buyTogetherTitle {\n text-transform: uppercase;\n font-weight: 600;\n font-size: 1.25rem;\n}\n\n.buyTogetherContainer {\n padding-bottom: 2.5rem;\n}\n\n.disabledProduct {\n opacity: 50%;\n pointer-events: none;\n}\n\n```"
}
] |
code_shelf-components_13203551
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/BuyTogether/ProductSummaryWithActions.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo } from 'react'\nimport classnames from 'classnames'\nimport { FormattedMessage, defineMessages } from 'react-intl'\nimport { ExtensionPoint } from 'vtex.render-runtime'\nimport ProductSummary from 'vtex.product-summary/ProductSummaryCustom'\nimport { ButtonWithIcon, IconClear, IconPlusLines } from 'vtex.styleguide'\n\nimport IconRefresh from '../../icons/IconRefresh'\nimport styles from './styles.css'\n\ninterface Props {\n product: Product\n index: number\n hidden?: boolean\n hideChangeAction?: boolean\n onDeleteOrAdd: (index: number) => void\n onChangeProduct: (index: number) => void\n onProductClick: (product: Product) => void\n}\n\nconst messages = defineMessages({\n changeLabel: {\n id: 'store/shelf.buy-together.change.label',\n defaultMessage: '',\n },\n removeLabel: {\n id: 'store/shelf.buy-together.remove.label',\n defaultMessage: '',\n },\n addLabel: {\n id: 'store/shelf.buy-together.add.label',\n defaultMessage: '',\n },\n})\n\nconst ProductSummaryWithActions: StorefrontFunctionComponent<Props> = ({\n product,\n index,\n hidden,\n hideChangeAction,\n onDeleteOrAdd,\n onChangeProduct,\n onProductClick,\n}) => {\n const normalizedProduct = useMemo(\n () => ProductSummary.mapCatalogProductToProductSummary(product),\n [product]\n )\n\n return (\n <div className=\"w-100 w-20-l\">\n <div className=\"tc nowrap mb3\">\n {!hideChangeAction && (\n <ButtonWithIcon\n icon={<IconRefresh />}\n variation=\"tertiary\"\n onClick={() => onChangeProduct(index)}\n >\n <FormattedMessage {...messages.changeLabel} />\n </ButtonWithIcon>\n )}\n <ButtonWithIcon\n icon={hidden ? <IconPlusLines /> : <IconClear />}\n variation=\"tertiary\"\n onClick={() => onDeleteOrAdd(index)}\n >\n {hidden ? (\n <FormattedMessage {...messages.addLabel} />\n ) : (\n <FormattedMessage {...messages.removeLabel} />\n )}\n </ButtonWithIcon>\n </div>\n <div className={classnames({ [styles.disabledProduct]: hidden })}>\n <ExtensionPoint\n id=\"product-summary\"\n product={normalizedProduct}\n actionOnClick={() => onProductClick(normalizedProduct)}\n />\n </div>\n </div>\n )\n}\n\nexport default ProductSummaryWithActions\n\n```"
}
] |
code_shelf-components_29601d97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/Shelf/index.tsx from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useRef } from 'react'\nimport { ExtensionPoint, useRuntime } from 'vtex.render-runtime'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\nimport { useRecommendation } from 'vtex.recommendation-context/RecommendationContext'\n\nimport styles from './styles.css'\nimport { useOnView } from '../../hooks/useOnView'\nimport { useEvents } from '../../hooks/useEvents'\n\ninterface Props {\n title?: string\n products?: Product[]\n isSecondary?: boolean\n secondaryTitle?: string\n}\n\nconst CSS_HANDLES = ['shelfTitleContainer', 'shelfTitle']\n\nconst Shelf: StorefrontFunctionComponent<Props> = ({\n title,\n products,\n isSecondary,\n secondaryTitle,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { page } = useRuntime()\n const { push } = usePixel()\n const ref = useRef<HTMLDivElement | null>(null)\n const recommendation = useRecommendation?.()\n const { onView, onProductClick } = useEvents(recommendation, push, page)\n\n useOnView({\n ref,\n onView: () => onView('default'),\n once: true,\n initializeOnInteraction: true,\n })\n\n const currentTitle = isSecondary ? secondaryTitle : title\n\n return (\n <div className=\"flex-none tc\" ref={ref}>\n {currentTitle && (\n <div className={`mv4 v-mid ${handles.shelfTitleContainer}`}>\n <span className={`${styles.shelfTitle} ${handles.shelfTitle}`}>\n {currentTitle}\n </span>\n </div>\n )}\n {(!products || products.length === 0) && (\n <ExtensionPoint\n id=\"list-context.product-list\"\n actionOnProductClick={onProductClick}\n />\n )}\n {products && products.length > 0 && (\n <ExtensionPoint\n id=\"list-context.product-list-static\"\n products={products}\n actionOnProductClick={onProductClick}\n />\n )}\n </div>\n )\n}\n\nShelf.schema = {\n title: 'admin/editor.shelf.title',\n}\n\nexport default Shelf\n\n```"
}
] |
code_shelf-components_94fa4c99
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of shelf-components/react/components/Shelf/styles.css from the shelf-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.shelfTitle {\n text-transform: uppercase;\n font-weight: 600;\n font-size: 1.25rem;\n}\n\n```"
}
] |
code_store-video_ca717a05
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/messages/pt.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.video.title\": \"Video\",\n \"admin/editor.video.src.title\": \"URL\",\n \"admin/editor.video.width.title\": \"Largura\",\n \"admin/editor.video.height.title\": \"Altura\",\n \"admin/editor.video.autoplay.title\": \"Reproduzir automaticamente\",\n \"admin/editor.video.loop.title\": \"Reproduzir em loop\",\n \"admin/editor.video.playsInline.title\": \"Reproduzir in-line (em dispositivos móveis)\",\n \"admin/editor.video.poster.title\": \"URL da imagem de thumbnail\",\n \"admin/editor.video.poster.description\": \"Imagem a ser exibida quando o video ainda não estiver disponível\",\n \"admin/editor.video.name.title\": \"Nome\",\n \"admin/editor.video.name.description\": \"Nome do video para SEO e acessibilidade\",\n \"admin/editor.video.description.title\": \"Descrição\",\n \"admin/editor.video.description.description\": \"Descrição do video para SEO e acessibilidade\",\n \"admin/editor.video.uploadDate.title\": \"Data de upload\",\n \"admin/editor.video.uploadDate.description\": \"Data de upload do video para SEO, no formato `aaaa-mm-dd hh:mm:ss`\",\n \"admin/editor.video.fallbackImageUrl.title\": \"Fallback Image URL\",\n \"admin/editor.video.fallbackImageUrl.description\": \"URL da imagem a ser exibida caso o video não esteja disponível\"\n}\n\n```"
}
] |
code_store-video_e28924c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/messages/en.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.video.title\": \"Video\",\n \"admin/editor.video.src.title\": \"URL\",\n \"admin/editor.video.width.title\": \"Width\",\n \"admin/editor.video.height.title\": \"Height\",\n \"admin/editor.video.autoplay.title\": \"Play automatically\",\n \"admin/editor.video.loop.title\": \"Play in loop\",\n \"admin/editor.video.playsInline.title\": \"Play inline (in mobile devices)\",\n \"admin/editor.video.poster.title\": \"Thumbnail image URL\",\n \"admin/editor.video.poster.description\": \"Image to be displayed when video is not available yet\",\n \"admin/editor.video.name.title\": \"Name\",\n \"admin/editor.video.name.description\": \"Video name for SEO and accessibility\",\n \"admin/editor.video.description.title\": \"Description\",\n \"admin/editor.video.description.description\": \"Video resume for SEO and accessibility\",\n \"admin/editor.video.uploadDate.title\": \"Upload date\",\n \"admin/editor.video.uploadDate.description\": \"Video upload date for SEO, in the format `yyyy-mm-dd hh:mm:ss`\",\n \"admin/editor.video.fallbackImageUrl.title\": \"Fallback Image URL\",\n \"admin/editor.video.fallbackImageUrl.description\": \"Video fallback image URL to be displayed if the video is not available\"\n}\n\n```"
}
] |
code_store-video_5b639763
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/messages/context.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.video.title\": \"Video\",\n \"admin/editor.video.src.title\": \"URL\",\n \"admin/editor.video.width.title\": \"Width\",\n \"admin/editor.video.height.title\": \"Height\",\n \"admin/editor.video.autoplay.title\": \"Play automatically\",\n \"admin/editor.video.loop.title\": \"Play in loop\",\n \"admin/editor.video.playsInline.title\": \"Play inline (in mobile devices)\",\n \"admin/editor.video.poster.title\": \"Thumbnail image URL\",\n \"admin/editor.video.poster.description\": \"Image to be displayed when video is not available yet\",\n \"admin/editor.video.name.title\": \"Name\",\n \"admin/editor.video.name.description\": \"Video name for SEO and accessibility\",\n \"admin/editor.video.description.title\": \"Description\",\n \"admin/editor.video.description.description\": \"Video resume for SEO and accessibility\",\n \"admin/editor.video.uploadDate.title\": \"Upload date\",\n \"admin/editor.video.uploadDate.description\": \"Video upload date for SEO, in the format `yyyy-mm-dd hh:mm:ss`\",\n \"admin/editor.video.fallbackImageUrl.title\": \"Fallback Image URL\",\n \"admin/editor.video.fallbackImageUrl.description\": \"Video fallback image URL to be displayed if the video is not available\"\n}\n\n```"
}
] |
code_store-video_29d83567
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/messages/es.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.video.title\": \"Video\",\n \"admin/editor.video.src.title\": \"URL\",\n \"admin/editor.video.width.title\": \"Anchura\",\n \"admin/editor.video.height.title\": \"Altura\",\n \"admin/editor.video.autoplay.title\": \"Jugar automáticamente\",\n \"admin/editor.video.loop.title\": \"Reproducción en bucle\",\n \"admin/editor.video.playsInline.title\": \"Reproducción intercalada (en dispositivos móviles)\",\n \"admin/editor.video.poster.title\": \"URL de la imagen en Thumbnail\",\n \"admin/editor.video.poster.description\": \"Imagen que se mostrará cuando el video aún no esté disponible\",\n \"admin/editor.video.name.title\": \"Nombre\",\n \"admin/editor.video.name.description\": \"Nombre del video para SEO y accesibilidad\",\n \"admin/editor.video.description.title\": \"Descripción\",\n \"admin/editor.video.description.description\": \"Video descripción para SEO y accesibilidad\",\n \"admin/editor.video.uploadDate.title\": \"Fecha de carga\",\n \"admin/editor.video.uploadDate.description\": \"Video fecha para SEO, en el formato `aaaa-mm-dd hh:mm:ss`\",\n \"admin/editor.video.fallbackImageUrl.title\": \"Fallback Image URL\",\n \"admin/editor.video.fallbackImageUrl.description\": \"URL de la imagen de respaldo del video que se mostrará si el video no está disponible\"\n}\n\n```"
}
] |
code_store-video_f288fabf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/docs/README.md from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/store-video) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Video\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nThe Video app allows you to display video assets on your store pages.\n\n\n\n## Configuration\n\n1. Add the `store-video` app to your theme's dependencies in the `manifest.json` file:\n\n```diff\n \"dependencies \": {\n+ \"vtex.store-video\": \"1.x\"\n }\n```\n\n2. In any desired theme template, add the `video` block with the desirable props. For example:\n\n```json\n \"video#background\": {\n \"props\": {\n \"width\": \"100%\",\n \"height\": \"600px\",\n \"loop\": false,\n \"autoPlay\": true,\n \"muted\": false,\n \"src\": \"https://www.youtube.com/watch?v=wygFqZXMIco\",\n \"blockClass\": \"videoEl\"\n }\n }\n```\n\n### `video` props\n\n| Prop name | Type | Description | Default value |\n| ---------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------- |\n| `name` | `string` | Video name for SEO and accessibility. | `undefined` |\n| `description` | `string` | Video description for SEO and accessibility. | `undefined` |\n| `src` | `string` | Video URL. It can be a `youtube` URL, `vimeo` URL or a self-hosted video URL. | `undefined` |\n| `type` | `string` | Video type. | `undefined` |\n| `poster` | `string` | Cover image URL to be displayed before the video playback. | `undefined` |\n| `controlsType` | `enum` | The type of controls. It can be `custom-vtex`( only works if the video URL represents a HTML5 player ), `native` or `none`. | `undefined` |\n| `autoPlay` | `boolean` | Whether the video will start automatically after loaded(`true`) or not(`false`). Note that if the value is `true`, the muted property will automatically be setted to `true`. | `false` |\n| `muted` | `boolean` | Whether the video will start with the audio on(`false`) or not(`true`). | `false` |\n| `loop` | `boolean` | Whether the video will run in a loop(`true`) or not(`false`). | `false` |\n| `playsInline` | `boolean` | Whether the video will play inline(`true`) or not(`false`). | `false` |\n| `width` | `number` or `string` | The width of the video exhibition area. It could be as %(`string`) or pixels(`number`). | `undefined` |\n| `height` | `number` or `string` | The height of the video exhibition area. It could be as %(`string`) or pixels(`number`). | `undefined` |\n| `PlayIcon` | `string` | Video play icon for `custom-vtex` controls. | `icon-play` |\n| `PauseIcon` | `string` | Video pause icon for `custom-vtex` controls. | `icon-pause` |\n| `VolumeOnIcon` | `string` | Video volume on icon for `custom-vtex` controls. | `icon-volume-on` |\n| `VolumeOffIcon` | `string` | Video volume off icon for `custom-vtex` controls. | `icon-volume-off` |\n| `FullscreenIcon` | `string` | Video fullscreen icon for `custom-vtex` controls. | `icon-extend` |\n| `classes` | `CustomCSSClasses` | Used to override default CSS handles. To better understand how this prop works, we recommend reading about it here. Note that this is only useful if you're importing this block as a React component. | `undefined` |\n\nUse the **admin's Site Editor** to manage some props declared in the `video` block.\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\n| CSS Handles |\n| ------------------- |\n| `controlsContainer` |\n| `fallbackContainer` |\n| `fallbackImage` |\n| `fullscreenButton` |\n| `playButton` |\n| `trackBar` |\n| `trackContainer` |\n| `trackTimer` |\n| `videoContainer` |\n| `videoElement` |\n| `volumeContainer` |\n| `volumeButton` |\n| `volumeSlider` |\n\n:warning: \\_It's required that `controlsType` prop is set as `custom-vtex` in order to have the following CSS Handles properly working: `controlsContainer`, `fullscreenButton`, `playButton`, `trackContainer`, `trackTimer`, `trackBar`, `volumeContainer`, `volumeSlider`, and `volumeButton`.\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_store-video_735ae8fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/useVideoTrack.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { RefObject } from 'react'\nimport { useState, useEffect } from 'react'\n\ninterface State {\n currentTime?: number\n duration?: number\n}\n\nexport const formatTime = (timeInSeconds: number) => {\n let seconds: string = Math.floor(timeInSeconds % 60).toString()\n\n if (seconds.length === 1) {\n seconds = `0${seconds}`\n }\n\n const minutes: number = Math.floor((timeInSeconds / 60) % 60)\n const hours: number = Math.floor(timeInSeconds / 3600)\n\n if (hours) {\n return `${hours}:${minutes}:${seconds}`\n }\n\n return `${minutes}:${seconds}`\n}\n\nexport const useVideoTrack = (\n videoRef: RefObject<HTMLVideoElement>,\n trackBarRef: RefObject<HTMLInputElement>\n) => {\n const [state, setState] = useState<State>({})\n const currentVideoRef = videoRef?.current\n const currentTrackBarRef = trackBarRef?.current\n\n const updateMetaData = () => {\n setState({ currentTime: 0, duration: currentVideoRef?.duration })\n }\n\n const updateCurrentTime = () => {\n if (currentTrackBarRef) {\n currentTrackBarRef.value = `${currentVideoRef?.currentTime}`\n }\n\n return setState({ ...state, currentTime: currentVideoRef?.currentTime })\n }\n\n const setCurrentTime = (timeInSeconds: number) => {\n if (!currentVideoRef) return\n\n currentVideoRef.currentTime = timeInSeconds\n }\n\n useEffect(() => {\n currentVideoRef?.addEventListener('loadedmetadata', updateMetaData)\n currentVideoRef?.addEventListener('timeupdate', updateCurrentTime)\n\n return () => {\n currentVideoRef?.removeEventListener('loadedmetadata', updateMetaData)\n currentVideoRef?.removeEventListener('timeupdate', updateCurrentTime)\n }\n // Disabling because it is necessary to define some event listeners only when video ref is available\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentVideoRef])\n\n return {\n duration: currentVideoRef?.duration,\n currentTime: state.currentTime,\n setCurrentTime,\n formatTime,\n }\n}\n\nexport default useVideoTrack\n\n```"
}
] |
code_store-video_c4908b89
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/VideoTypes.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { VideoHTMLAttributes, ElementType } from 'react'\nimport type { CssHandlesTypes } from 'vtex.css-handles'\n\nimport type { CSS_HANDLES } from './players/HTML5Player'\n\nexport interface VideoPlayer extends VideoHTMLAttributes<HTMLVideoElement> {\n name?: string\n description?: string\n src: string\n fallbackImageUrl?: string\n type?: string\n controlsType?: string\n IconPlay?: ElementType<unknown>\n IconPause?: ElementType<unknown>\n IconFullscreen?: ElementType<unknown>\n IconVolumeOn?: ElementType<unknown>\n IconVolumeOff?: ElementType<unknown>\n uploadDate?: string\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\n```"
}
] |
code_store-video_08000fc4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/useVideo.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { RefObject } from 'react'\nimport { useState, useEffect } from 'react'\n\ninterface State {\n isMuted: boolean | null\n isPlaying: boolean | null\n networkStatus: string | null\n volume: number | undefined\n}\n\nconst NETWORK_STATUS: string[] = [\n 'NETWORK_EMPTY',\n 'NETWORK_IDLE',\n 'NETWORK_LOADING',\n 'NETWORK_NO_SOURCE',\n]\n\nconst useVideo = (\n videoRef: RefObject<HTMLVideoElement>,\n containerRef: RefObject<HTMLDivElement>\n) => {\n const currentVideoRef = videoRef?.current\n const currentContainerRef = containerRef?.current\n const [state, setState] = useState<State>({\n isMuted: null,\n isPlaying: null,\n volume: undefined,\n networkStatus: null,\n })\n\n const play = () => {\n currentVideoRef?.play()\n\n setState({ ...state, isPlaying: currentVideoRef?.paused === false })\n }\n\n const pause = () => {\n currentVideoRef?.pause()\n\n if (currentVideoRef?.autoplay) currentVideoRef.autoplay = false\n\n setState({ ...state, isPlaying: currentVideoRef?.paused === false })\n }\n\n const setVolume = (volume: number) => {\n if (!currentVideoRef) return\n\n if (volume < 0 || volume > 1) return\n\n currentVideoRef.volume = volume\n\n setState({ ...state, volume })\n }\n\n const toggleMute = () => {\n if (!currentVideoRef) return\n\n currentVideoRef.muted = !currentVideoRef.muted\n\n setState({ ...state, isMuted: currentVideoRef.muted })\n }\n\n const toggleFullscreenMode = () => {\n if (document.fullscreenElement) {\n return document.exitFullscreen()\n }\n\n return currentContainerRef?.requestFullscreen()\n }\n\n const changeState = (property: string, value: unknown) => {\n setState({ ...state, [property]: value })\n }\n\n const setNetworkStatus = (networkStatus: string): void => {\n setState({ ...state, networkStatus })\n }\n\n const getNetworkStatus = (): string => {\n return NETWORK_STATUS[currentVideoRef?.networkState ?? 0]\n }\n\n const handleEnd = () => {\n setState({ ...state, isPlaying: false })\n }\n\n useEffect(() => {\n currentVideoRef?.addEventListener('ended', handleEnd)\n\n setState({\n ...state,\n isMuted: currentVideoRef?.muted === true,\n isPlaying:\n Boolean(currentVideoRef?.autoplay) || currentVideoRef?.paused === false,\n networkStatus: getNetworkStatus(),\n })\n\n return () => {\n currentVideoRef?.removeEventListener('ended', handleEnd)\n }\n // Disabling because it is necessary to set some default values only when video ref is available\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentVideoRef])\n\n return {\n isPlaying: state.isPlaying,\n isMuted: state.isMuted,\n volume: state.volume,\n networkStatus: state.networkStatus,\n hasEnded: currentVideoRef?.ended,\n play,\n pause,\n setVolume,\n setNetworkStatus,\n toggleMute,\n toggleFullscreenMode,\n changeState,\n }\n}\n\nexport default useVideo\n\n```"
}
] |
code_store-video_4a4c21c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/Video.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { jsonLdScriptProps } from 'react-schemaorg'\n\nimport type { VideoPlayer } from './VideoTypes'\nimport VimeoPlayer from './players/VimeoPlayer'\nimport HTML5Player, { CSS_HANDLES } from './players/HTML5Player'\nimport YoutubePlayer from './players/YoutubePlayer'\n\nconst VIMEO_PATTERN = /vimeo/\nconst YOUTUBE_PATTERN = /youtube|youtu.be/\n\nfunction Video(props: VideoPlayer) {\n const { src, name, description, poster, uploadDate } = props\n const isVimeo = VIMEO_PATTERN.test(src)\n const isYoutube = YOUTUBE_PATTERN.test(src)\n\n const StructuredData = () => {\n return (\n <script\n {...jsonLdScriptProps({\n '@context': 'http://schema.org',\n '@type': 'VideoObject',\n name,\n description,\n contentUrl: src,\n uploadDate: uploadDate ? new Date(uploadDate) : undefined,\n thumbnailUrl: poster ?? src,\n })}\n />\n )\n }\n\n let Player = HTML5Player\n\n if (isVimeo) {\n Player = VimeoPlayer\n }\n\n if (isYoutube) {\n Player = YoutubePlayer\n }\n\n return (\n <>\n <StructuredData />\n <Player {...props} />\n </>\n )\n}\n\nVideo.schema = {\n title: 'admin/editor.video.title',\n}\n\nVideo.cssHandles = CSS_HANDLES\n\nexport default Video\n\n```"
}
] |
code_store-video_d8bc6b57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/package.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\",\n \"react-schemaorg\": \"^1.3.1\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@1.0.0/public/@types/vtex.css-handles\",\n \"vtex.native-types\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.native-types@0.7.5/public/@types/vtex.native-types\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.4/public/@types/vtex.render-runtime\",\n \"vtex.store-icons\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-icons@0.18.0/public/@types/vtex.store-icons\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.134.1/public/@types/vtex.styleguide\"\n },\n \"version\": \"1.4.3\"\n}\n\n```"
}
] |
code_store-video_95132205
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/HandlesContext.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { CSS_HANDLES } from './players/HTML5Player'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n CSS_HANDLES\n)\n\nexport {\n CssHandlesProvider as VideoHandlesProvider,\n useContextCssHandles as useVideoHandles,\n}\n\n```"
}
] |
code_store-video_ba32214c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/store/contentSchemas.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"definitions\": {\n \"Video\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"title\": \"admin/editor.video.name.title\",\n \"description\": \"admin/editor.video.name.description\",\n \"type\": \"string\"\n },\n \"description\": {\n \"title\": \"admin/editor.video.description.title\",\n \"description\": \"admin/editor.video.description.description\",\n \"type\": \"string\"\n },\n \"width\": {\n \"title\": \"admin/editor.video.width.title\",\n \"type\": \"string\"\n },\n \"height\": {\n \"title\": \"admin/editor.video.height.title\",\n \"type\": \"string\"\n },\n \"src\": {\n \"title\": \"admin/editor.video.src.title\",\n \"type\": \"string\"\n },\n \"autoPlay\": {\n \"title\": \"admin/editor.video.autoplay.title\",\n \"type\": \"boolean\",\n \"default\": false\n },\n \"loop\": {\n \"title\": \"admin/editor.video.loop.title\",\n \"type\": \"boolean\",\n \"default\": false\n },\n \"playsInline\": {\n \"title\": \"admin/editor.video.playsInline.title\",\n \"type\": \"boolean\",\n \"default\": false\n },\n \"poster\": {\n \"title\": \"admin/editor.video.poster.title\",\n \"description\": \"admin/editor.video.poster.description\",\n \"type\": \"string\"\n },\n \"uploadDate\": {\n \"title\": \"admin/editor.video.uploadDate.title\",\n \"description\": \"admin/editor.video.uploadDate.description\",\n \"type\": \"string\"\n }\n }\n }\n }\n}\n\n```"
}
] |
code_store-video_5b8e4458
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/store/interfaces.json from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"video\": {\n \"component\": \"Video\",\n \"content\": {\n \"$ref\": \"app:vtex.store-video#/definitions/Video\"\n }\n }\n}\n\n```"
}
] |
code_store-video_08cf91ea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/players/YoutubePlayer.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport type { VideoPlayer } from '../VideoTypes'\n\nconst CSS_HANDLES = ['videoContainer', 'videoElement'] as const\n\n// https://regex101.com/r/CWmgOb/1\nconst YOUTUBE_REGEX = /(?:youtube(?:-nocookie)?\\.com\\/(?:[^/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})/\n\nfunction YoutubePlayer({\n width,\n height,\n autoPlay,\n controlsType,\n loop,\n playsInline,\n muted,\n src,\n description,\n classes,\n}: VideoPlayer) {\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n const matchedSrc = src.match(YOUTUBE_REGEX)\n const videoId = matchedSrc?.[1]\n const params = `autoplay=${autoPlay}&loop=${\n loop ? `1&playlist=${videoId}` : '0'\n }&enablejsapi=1&iv_load_policy=3&modestbranding=1&rel=0&controls=${\n controlsType === 'none' ? 0 : 1\n }&playsinline=${playsInline ? '1' : '0'}&mute=${\n autoPlay || muted ? '1' : '0'\n }`\n\n return (\n <div className={`relative ${handles.videoContainer}`}>\n <iframe\n data-testid=\"youtube-player\"\n width={width}\n height={height}\n title={description}\n className={`${handles.videoElement}`}\n src={`https://www.youtube.com/embed/${videoId}?${params}`}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n}\n\nexport default YoutubePlayer\n\n```"
}
] |
code_store-video_2ceb7f25
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/players/HTML5Player.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable jsx-a11y/media-has-caption */\nimport React, { useRef } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport useVideo from '../useVideo'\nimport styles from '../styles/styles.css'\nimport type { VideoPlayer } from '../VideoTypes'\nimport PlayButton, {\n CSS_HANDLES as PLAY_BUTTON_CSS_HANDLES,\n} from '../controls/PlayButton'\nimport FullscreenButton, {\n CSS_HANDLES as FULLSCREEN_BUTTON_CSS_HANDLES,\n} from '../controls/FullscreenButton'\nimport TrackControl, {\n CSS_HANDLES as TRACK_CONTROL_CSS_HANDLES,\n} from '../controls/TrackControl'\nimport VolumeControl, {\n CSS_HANDLES as VOLUME_CONTROL_CSS_HANDLES,\n} from '../controls/VolumeControl'\nimport { useVideoHandles, VideoHandlesProvider } from '../HandlesContext'\n\nexport const CSS_HANDLES = [\n 'videoContainer',\n 'videoElement',\n 'fallbackContainer',\n 'fallbackImage',\n 'controlsContainer',\n ...PLAY_BUTTON_CSS_HANDLES,\n ...TRACK_CONTROL_CSS_HANDLES,\n ...FULLSCREEN_BUTTON_CSS_HANDLES,\n ...VOLUME_CONTROL_CSS_HANDLES,\n] as const\n\ninterface FallbackImageProps {\n imageUrl?: string\n description?: string\n}\n\nfunction FallbackImage({\n imageUrl = 'https://storecomponents.vtexassets.com/arquivos/ids/155639',\n description,\n}: FallbackImageProps) {\n const { handles } = useVideoHandles()\n\n return (\n <div className={`${handles.fallbackContainer}`}>\n <img\n className={`w-100 h-100 ${handles.fallbackImage}`}\n src={imageUrl}\n alt={description}\n />\n </div>\n )\n}\n\nfunction HTML5Player({\n src,\n type,\n width,\n height,\n autoPlay,\n playsInline,\n loop,\n poster,\n controlsType,\n description,\n muted,\n IconPlay,\n IconPause,\n IconFullscreen,\n IconVolumeOn,\n IconVolumeOff,\n classes,\n ...props\n}: VideoPlayer) {\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES, { classes })\n const videoRef = useRef<HTMLVideoElement>(null)\n const containerRef = useRef<HTMLDivElement>(null)\n const {\n isPlaying,\n isMuted,\n networkStatus,\n volume,\n play,\n pause,\n setVolume,\n toggleMute,\n toggleFullscreenMode,\n changeState,\n } = useVideo(videoRef, containerRef)\n\n const hasCustomControls = controlsType === 'custom-vtex'\n const hasNativeControls = controlsType === 'native'\n\n if (hasCustomControls && networkStatus === 'NETWORK_NO_SOURCE') {\n return <FallbackImage imageUrl={poster} description={description} />\n }\n\n return (\n <VideoHandlesProvider withModifiers={withModifiers} handles={handles}>\n <div\n ref={containerRef}\n aria-label={description}\n style={{ width, height }}\n className={`relative ${handles.videoContainer} ba b--gray`}\n >\n <video\n {...props}\n ref={videoRef}\n data-testid=\"html5-player\"\n className={`${handles.videoElement} ${styles.videoElement} w-100 h-100`}\n poster={poster}\n loop={loop}\n autoPlay={autoPlay}\n controls={hasNativeControls}\n muted={autoPlay ? true : muted}\n playsInline={autoPlay ? true : playsInline}\n >\n <source src={src} type={type && `video/${type}`} />\n\n {<FallbackImage imageUrl={poster} description={description} />}\n </video>\n\n {videoRef && hasCustomControls && (\n <div\n data-testid=\"controls-container\"\n className={`${handles.controlsContainer} absolute left-2 right-2 lh-copy`}\n >\n <>\n <PlayButton\n isPlaying={isPlaying}\n IconPlay={IconPlay}\n IconPause={IconPause}\n play={play}\n pause={pause}\n />\n <TrackControl videoRef={videoRef} changeState={changeState} />\n <FullscreenButton\n IconFullscreen={IconFullscreen}\n toggleFullscreenMode={toggleFullscreenMode}\n />\n <VolumeControl\n IconVolumeOn={IconVolumeOn}\n IconVolumeOff={IconVolumeOff}\n isMuted={isMuted}\n volume={volume}\n setVolume={setVolume}\n toggleMute={toggleMute}\n />\n </>\n </div>\n )}\n </div>\n </VideoHandlesProvider>\n )\n}\n\nexport default HTML5Player\n\n```"
}
] |
code_store-video_1502232f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/players/VimeoPlayer.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport type { VideoPlayer } from '../VideoTypes'\n\nconst CSS_HANDLES = ['videoContainer', 'videoElement'] as const\n\n// https://regex101.com/r/wdKKHO/1\nconst VIMEO_REGEX = /^.*(vimeo\\.com\\/)((channels\\/[A-z]+\\/)|(groups\\/[A-z]+\\/videos\\/))?([0-9]+)/\n\nfunction VimeoPlayer({\n width,\n height,\n autoPlay,\n loop,\n playsInline,\n src,\n description,\n classes,\n}: VideoPlayer) {\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n const params = `autoplay=${autoPlay}&loop=${loop}&playsinline=${Boolean(\n playsInline\n )}&enablejsapi=1&iv_load_policy=3&modestbranding=1`\n\n const matchedSrc = src.match(VIMEO_REGEX)\n const videoId = matchedSrc?.[5]\n\n return (\n <div className={`relative ${handles.videoContainer}`}>\n <iframe\n data-testid=\"vimeo-player\"\n width={width}\n height={height}\n title={description}\n className={`${handles.videoElement}`}\n src={`https://player.vimeo.com/video/${videoId}?${params}`}\n frameBorder=\"0\"\n allowFullScreen\n allow=\"autoplay\"\n />\n </div>\n )\n}\n\nexport default VimeoPlayer\n\n```"
}
] |
code_store-video_dff9ec6f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/typings/css.d.ts from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: CSSHandles\n export default css\n}\n\n```"
}
] |
code_store-video_dc5124e2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/controls/TrackControl.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { RefObject, ChangeEvent } from 'react'\nimport React, { useRef } from 'react'\n\nimport { useVideoHandles } from '../HandlesContext'\nimport useVideoTrack, { formatTime } from '../useVideoTrack'\n\nexport const CSS_HANDLES = ['trackContainer', 'trackTimer', 'trackBar'] as const\n\nexport interface TrackControlProps {\n videoRef: RefObject<HTMLVideoElement>\n changeState: (property: string, value: unknown) => void\n}\n\nfunction TrackControl({ videoRef, changeState }: TrackControlProps) {\n const { handles } = useVideoHandles()\n const trackBarRef = useRef<HTMLInputElement>(null)\n const { duration, currentTime, setCurrentTime } = useVideoTrack(\n videoRef,\n trackBarRef\n )\n\n const handleChange = (event: ChangeEvent<HTMLInputElement>) => {\n if (videoRef?.current?.ended) {\n changeState('isPlaying', false)\n }\n\n setCurrentTime(parseFloat(event?.target?.value))\n }\n\n return (\n <div\n className={`${handles.trackContainer} w-100 absolute bottom-1 lh-title`}\n >\n {currentTime != null && duration != null && (\n <span className={`${handles.trackTimer} ml7 white v-mid`}>\n {`${formatTime(currentTime)} / ${formatTime(duration)}`}\n </span>\n )}\n\n <input\n ref={trackBarRef}\n onChange={handleChange}\n className={`${handles.trackBar} w-100 v-mid`}\n type=\"range\"\n min={0}\n step={0.05}\n defaultValue=\"0\"\n max={duration ?? 0}\n />\n </div>\n )\n}\n\nexport default TrackControl\n\n```"
}
] |
code_store-video_17b08ded
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/controls/FullscreenButton.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ElementType } from 'react'\nimport React from 'react'\nimport { IconExpand as DefaultIconFullscreen } from 'vtex.store-icons'\n\nimport { useVideoHandles } from '../HandlesContext'\nimport styles from '../styles/styles.css'\n\nexport const CSS_HANDLES = ['fullscreenButton'] as const\nexport interface FullscreenButtonProps {\n toggleFullscreenMode: () => void\n IconFullscreen?: ElementType\n}\n\nfunction FullscreenButton({\n toggleFullscreenMode,\n IconFullscreen,\n}: FullscreenButtonProps) {\n const { handles } = useVideoHandles()\n\n return (\n <button\n className={`${handles.fullscreenButton} ${styles.button} ml4 absolute bottom-2 right-0`}\n onClick={toggleFullscreenMode}\n >\n {IconFullscreen ? <IconFullscreen /> : <DefaultIconFullscreen />}\n </button>\n )\n}\n\nexport default FullscreenButton\n\n```"
}
] |
code_store-video_e1a3477f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/controls/PlayButton.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ElementType } from 'react'\nimport React from 'react'\nimport {\n IconPlay as DefaultIconPlay,\n IconPause as DefaultIconPause,\n} from 'vtex.store-icons'\n\nimport { useVideoHandles } from '../HandlesContext'\nimport styles from '../styles/styles.css'\n\nexport const CSS_HANDLES = ['playButton'] as const\n\nexport interface PlayButtonProps {\n isPlaying: boolean | null\n play: () => void\n pause: () => void\n IconPlay?: ElementType<unknown>\n IconPause?: ElementType<unknown>\n}\n\nfunction PlayButton({\n isPlaying,\n IconPlay,\n IconPause,\n play,\n pause,\n}: PlayButtonProps) {\n const { handles } = useVideoHandles()\n\n const PauseIcon = IconPause ? (\n <IconPause />\n ) : (\n DefaultIconPause && <DefaultIconPause />\n )\n\n const PlayIcon = IconPlay ? (\n <IconPlay />\n ) : (\n DefaultIconPlay && <DefaultIconPlay />\n )\n\n return (\n <button\n className={`${handles.playButton} ${styles.button} absolute bottom-2 left-0 v-mid z-1`}\n onClick={() => (isPlaying ? pause() : play())}\n >\n {isPlaying ? PauseIcon : PlayIcon}\n </button>\n )\n}\n\nexport default PlayButton\n\n```"
}
] |
code_store-video_46737fea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/controls/VolumeControl.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ElementType, MouseEventHandler } from 'react'\nimport React, { useState } from 'react'\nimport {\n IconVolumeOff as DefaultIconVolumeOff,\n IconVolumeOn as DefaultIconVolumeOn,\n} from 'vtex.store-icons'\n\nimport { useVideoHandles } from '../HandlesContext'\nimport styles from '../styles/styles.css'\n\nexport const CSS_HANDLES = [\n 'volumeContainer',\n 'volumeSlider',\n 'volumeButton',\n] as const\n\nexport interface VolumeControlProps {\n setVolume: (volume: number) => void\n toggleMute: MouseEventHandler<HTMLButtonElement>\n isMuted: boolean | null\n volume: number | undefined\n IconVolumeOn?: ElementType<unknown>\n IconVolumeOff?: ElementType<unknown>\n}\n\nfunction VolumeControl({\n setVolume,\n toggleMute,\n isMuted,\n volume,\n IconVolumeOn,\n IconVolumeOff,\n}: VolumeControlProps) {\n const { handles } = useVideoHandles()\n\n const [showVolumeSlider, setShowVolumeSlider] = useState(false)\n\n const VolumeOffIcon = IconVolumeOff ? (\n <IconVolumeOff />\n ) : (\n DefaultIconVolumeOff && <DefaultIconVolumeOff />\n )\n\n const VolumeOnIcon = IconVolumeOn ? (\n <IconVolumeOn />\n ) : (\n DefaultIconVolumeOn && <DefaultIconVolumeOn />\n )\n\n return (\n <div\n className={`${handles.volumeContainer} dib absolute bottom-2 right-2`}\n onMouseEnter={() => setShowVolumeSlider(true)}\n onMouseLeave={() => setShowVolumeSlider(false)}\n >\n {showVolumeSlider && (\n <input\n className={`${handles.volumeSlider} ${styles.volumeSlider} v-mid`}\n disabled={isMuted === true}\n type=\"range\"\n defaultValue={volume && volume * 10}\n min={0}\n max={10}\n onChange={(event) => setVolume(parseInt(event.target.value, 10) / 10)}\n />\n )}\n\n <button\n onClick={toggleMute}\n className={`${handles.volumeButton} ${styles.button} v-mid ml4`}\n >\n {isMuted ? VolumeOffIcon : VolumeOnIcon}\n </button>\n </div>\n )\n}\n\nexport default VolumeControl\n\n```"
}
] |
code_store-video_48bc1002
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/styles/styles.css from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.videoContainer:fullscreen .videoElement {\n width: 100%;\n height: 100%;\n}\n\n.videoElement {\n object-fit: cover;\n}\n\n.volumeSlider {\n width: 5rem;\n margin-top: 0;\n}\n\n.button {\n border: none;\n background: none;\n color: white;\n cursor: pointer;\n}\n\n.button:fullscreen {\n position: fixed;\n}\n\n```"
}
] |
code_store-video_108f03ef
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-video/react/__tests__/Video.test.tsx from the store-video VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { RefObject } from 'react'\nimport { renderHook, render } from '@vtex/test-tools/react'\nimport { act } from 'react-test-renderer'\n\nimport Video from '../Video'\nimport useVideoTrack from '../useVideoTrack'\nimport useVideo from '../useVideo'\n\ndescribe('Video rendering', () => {\n it.todo('should show a loading when the network status is not ready')\n\n it('should render youtube player correctly', () => {\n const { queryByTestId } = render(\n <Video src=\"https://www.youtube.com/watch?v=hT0OMD11b0A\" />\n )\n\n expect(queryByTestId('html5-player')).not.toBeInTheDocument()\n expect(queryByTestId('vimeo-player')).not.toBeInTheDocument()\n expect(queryByTestId('youtube-player')).toBeInTheDocument()\n })\n\n it('should render vimeo player correctly', () => {\n const { queryByTestId } = render(<Video src=\"https://vimeo.com/89404519\" />)\n\n expect(queryByTestId('html5-player')).not.toBeInTheDocument()\n expect(queryByTestId('vimeo-player')).toBeInTheDocument()\n expect(queryByTestId('youtube-player')).not.toBeInTheDocument()\n })\n\n it('should have native controls if controlsType is `native`', () => {\n const { queryByTestId } = render(\n <Video controlsType=\"native\" src=\"vtex.mp4\" />\n )\n\n expect(queryByTestId('html5-player')).toHaveAttribute('controls')\n expect(queryByTestId('controls-container')).not.toBeInTheDocument()\n })\n\n it('should have custom controls if controlsType is `vtex`', () => {\n const { queryByTestId } = render(\n <Video controlsType=\"custom-vtex\" src=\"vtex.mp4\" />\n )\n\n expect(queryByTestId('html5-player')).not.toHaveAttribute('controls')\n expect(queryByTestId('controls-container')).toBeInTheDocument()\n })\n})\n\ndescribe('Video logic', () => {\n let video: HTMLVideoElement\n let container: HTMLDivElement\n let videoRef: RefObject<HTMLVideoElement>\n let containerRef: RefObject<HTMLDivElement>\n\n beforeEach(() => {\n video = document.createElement('video')\n container = document.createElement('div')\n container.appendChild(video)\n videoRef = { current: video }\n containerRef = { current: container }\n })\n\n it('should change the volume of the video', () => {\n const {\n result: {\n current: { toggleMute, setVolume },\n },\n } = renderHook(() => useVideo(videoRef, containerRef))\n\n act(() => {\n setVolume(0.5)\n })\n\n expect(videoRef?.current?.muted).toBe(false)\n expect(videoRef?.current?.volume).toBe(0.5)\n\n act(() => {\n setVolume(0.3)\n toggleMute()\n })\n\n expect(videoRef?.current?.muted).toBe(true)\n expect(videoRef?.current?.volume).toBe(0.3)\n\n act(() => {\n setVolume(30)\n })\n\n expect(videoRef?.current?.volume).toBe(0.3)\n })\n\n it('should pause the video', () => {\n jest.spyOn(window.HTMLMediaElement.prototype, 'pause').mockImplementation()\n\n Object.defineProperty(HTMLMediaElement.prototype, 'paused', {\n get() {\n return true\n },\n })\n\n const {\n result: {\n current,\n current: { pause },\n },\n } = renderHook(() => useVideo(videoRef, containerRef))\n\n act(() => {\n pause()\n })\n\n expect(videoRef?.current?.pause).toHaveBeenCalled()\n expect(current.isPlaying).toBeFalsy()\n })\n\n it('should play the video', () => {\n jest\n .spyOn(window.HTMLMediaElement.prototype, 'play')\n .mockImplementation(() => Promise.resolve())\n\n Object.defineProperty(HTMLMediaElement.prototype, 'paused', {\n get() {\n return false\n },\n })\n\n const {\n result: {\n current,\n current: { play, pause },\n },\n } = renderHook(() => useVideo(videoRef, containerRef))\n\n act(() => {\n play()\n pause()\n play()\n })\n\n expect(videoRef?.current?.play).toHaveBeenCalled()\n expect(current.isPlaying).toBeTruthy()\n })\n\n it('should get the track timer with the right format', () => {\n const trackBar: HTMLInputElement = document.createElement('input')\n const trackBarRef = { current: trackBar }\n\n const {\n result: {\n current: { formatTime = () => {} },\n },\n } = renderHook(() => useVideoTrack(videoRef, trackBarRef))\n\n expect(formatTime(7)).toBe('0:07')\n expect(formatTime(30)).toBe('0:30')\n expect(formatTime(120)).toBe('2:00')\n expect(formatTime(10300)).toBe('2:51:40')\n })\n\n it('should update the current time when video is playing', () => {\n const trackBar: HTMLInputElement = document.createElement('input')\n const trackBarRef = { current: trackBar }\n\n const {\n result: {\n current: { setCurrentTime },\n },\n } = renderHook(() => useVideoTrack(videoRef, trackBarRef))\n\n act(() => {\n setCurrentTime(2)\n })\n\n expect(videoRef?.current?.currentTime).toBe(2)\n\n act(() => {\n videoRef?.current?.dispatchEvent(new window.Event('timeupdate'))\n })\n\n expect(trackBarRef?.current.value).toBe('2')\n })\n})\n\n```"
}
] |
code_pwa-components_5429d1b8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/messages/pt.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/promotion-banner.button-dismiss.label\": \"Agora não\",\n \"store/promotion-banner.install.title\": \"Acompanhe seus pedidos\",\n \"store/promotion-banner.install.description\": \"Nosso app é rápido, pequeno e funciona offline\",\n \"store/promotion-banner.install.button-accept.label\": \"Instalar\",\n \"store/promotion-banner.push-notification.title\": \"Acompanhe seus pedidos\",\n \"store/promotion-banner.push-notification.description\": \"Receba notificações sobre os status do seus pedidos.\",\n \"store/promotion-banner.push-notification.button-accept.label\": \"Aceitar\",\n \"store/offline-warning.button\": \"Atualizar\",\n \"store/offline-warning.message\": \"Não é possível carregar está página. Verifique sua conexão de rede\",\n \"store/offline-warning.title\": \"Esta página não pode ser carregada\"\n}\n```"
}
] |
code_pwa-components_1eed5093
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/messages/en.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/promotion-banner.button-dismiss.label\": \"Not now\",\n \"store/promotion-banner.install.title\": \"Keep track of your orders\",\n \"store/promotion-banner.install.description\": \"Our app is fast, small, and works offline\",\n \"store/promotion-banner.install.button-accept.label\": \"Install\",\n \"store/promotion-banner.push-notification.title\": \"Keep track of your orders\",\n \"store/promotion-banner.push-notification.description\": \"Receive notifications about your orders status\",\n \"store/promotion-banner.push-notification.button-accept.label\": \"Accept\",\n \"store/offline-warning.button\": \"Refresh\",\n \"store/offline-warning.message\": \"Unable to load this page. Check your network connection\",\n \"store/offline-warning.title\": \"This page cannot be loaded\"\n}\n```"
}
] |
code_pwa-components_78b982bf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/messages/context.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/promotion-banner.button-dismiss.label\": \"store/promotion-banner.button-dismiss.label\",\n \"store/promotion-banner.install.title\": \"store/promotion-banner.install.title\",\n \"store/promotion-banner.install.description\": \"store/promotion-banner.install.description\",\n \"store/promotion-banner.install.button-accept.label\": \"store/promotion-banner.install.button-accept.label\",\n \"store/promotion-banner.push-notification.title\": \"store/promotion-banner.push-notification.title\",\n \"store/promotion-banner.push-notification.description\": \"store/promotion-banner.push-notification.description\",\n \"store/promotion-banner.push-notification.button-accept.label\": \"store/promotion-banner.push-notification.button-accept.label\",\n \"store/offline-warning.button\": \"store/offline-warning.button\",\n \"store/offline-warning.message\": \"store/offline-warning.message\",\n \"store/offline-warning.title\": \"store/offline-warning.title\"\n}\n```"
}
] |
code_pwa-components_bc9c95f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/messages/es.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/promotion-banner.button-dismiss.label\": \"Ahora no\",\n \"store/promotion-banner.install.title\": \"Lleve un registro de sus pedidos\",\n \"store/promotion-banner.install.description\": \"Nuestra aplicación es rápida, pequeña y funciona sin conexión\",\n \"store/promotion-banner.install.button-accept.label\": \"Instalar\",\n \"store/promotion-banner.push-notification.title\": \"Lleve un registro de sus pedidos\",\n \"store/promotion-banner.push-notification.description\": \"Reciba notificaciones sobre el estado de sus pedidos\",\n \"store/promotion-banner.push-notification.button-accept.label\": \"Aceptar\",\n \"store/offline-warning.button\": \"Actualizar\",\n \"store/offline-warning.message\": \"No se puede cargar esta página. Comprueba tu conexión de red\",\n \"store/offline-warning.title\": \"Esta página no se puede cargar.\"\n}\n```"
}
] |
code_pwa-components_e7558625
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/docs/README.md from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# PWA Components\n\n[](https://travis-ci.org/vtex-apps/pwa-components)\n\n## Description\n\nVTEX PWA Components is a collection of components PWA-related.\n\n:loudspeaker: **Disclaimer:** Don't fork this project; Use, contribute or open issue with your feature request.\n\n## Table of Contents\n\n- [Usage](#Usage)\n- [Components Specs](#components-specs)\n\n## Usage\n\nThis app uses our store builder with the blocks architecture. To know more about Store Builder [click here.](https://help.vtex.com/en/tutorial/understanding-storebuilder-and-stylesbuilder#structuring-and-configuring-our-store-with-object-object)\n\nTo use this app, you need to import in your dependencies on `manifest.json`.\n\n```json\n \"dependencies\": {\n \"vtex.pwa-components\": \"0.x\"\n }\n```\n\n## Components Specs\n\nBelow we have a README for each component of this project that explains how to use them.\n\n- [PromotionBanner](PromotionBanner.md)\n- [OfflineWarning](OfflineWarning.md)\n\n\n```"
}
] |
code_pwa-components_9049666a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/react/OfflineWarning.tsx from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { Button, EmptyState } from 'vtex.styleguide'\nimport { injectIntl, intlShape, InjectedIntlProps } from 'react-intl'\nimport PropTypes from 'prop-types'\n\nconst propTypes = {\n intl: intlShape,\n}\n\ntype Props = PropTypes.InferProps<typeof propTypes>\n\nconst OfflineWarning: FC<Props & InjectedIntlProps> = ({ intl }) => {\n const handleReload = () => {\n if (window && window.location) {\n window.location.reload()\n }\n }\n\n return (\n <EmptyState\n title={intl.formatMessage({ id: 'store/offline-warning.title' })}\n >\n <p>{intl.formatMessage({ id: 'store/offline-warning.message' })}</p>\n <div className=\"pt5\">\n <Button variation=\"secondary\" size=\"small\" onClick={handleReload}>\n <span className=\"flex align-baseline\">\n {intl.formatMessage({ id: 'store/offline-warning.button' })}\n </span>\n </Button>\n </div>\n </EmptyState>\n )\n}\n\nOfflineWarning.propTypes = propTypes\n\nexport default injectIntl(OfflineWarning)\n\n```"
}
] |
code_pwa-components_3993cea8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/react/PWAHelmet.tsx from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport PropTypes from 'prop-types'\n\n// @ts-ignore\nimport { Helmet, useRuntime } from 'vtex.render-runtime'\n\nconst propTypes = {\n appId: PropTypes.string.isRequired,\n}\n\ntype Props = PropTypes.InferProps<typeof propTypes>\n\nconst PWAHelmet: FC<Props> = ({ appId }) => {\n const { rootPath = '' } = useRuntime()\n\n return (\n <Helmet\n meta={[\n { name: 'theme-color', content: '#F71963' },\n { name: 'apple-mobile-web-app-capable', content: 'yes' },\n ]}\n script={[\n {\n type: 'text/javascript',\n src: `${rootPath}/pwa/workers/register.js?scope=${encodeURIComponent(\n rootPath\n )}`,\n defer: true,\n },\n ]}\n link={[\n {\n rel: 'manifest',\n href: `${rootPath}/pwa/manifest.json?app=${appId}`,\n },\n ]}\n />\n )\n}\n\nPWAHelmet.propTypes = propTypes\n\nexport default PWAHelmet\n\n```"
}
] |
code_pwa-components_2f8f73bd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/react/package.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"pwa-components\",\n \"version\": \"0.4.2\",\n \"description\": \"Components related to PWA features\",\n \"scripts\": {\n \"pretest\": \"yarn\",\n \"test\": \"vtex-test-tools test --passWithNoTests\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.7.7\",\n \"@types/prop-types\": \"^15.7.3\",\n \"@types/react\": \"^16.9.3\",\n \"@vtex/test-tools\": \"^1.2.0\",\n \"prop-types\": \"^15.7.2\",\n \"vtex.pwa-graphql\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.pwa-graphql@1.10.0/public/@types/vtex.pwa-graphql\",\n \"vtex.render-runtime\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.render-runtime@8.66.2/public/@types/vtex.render-runtime\",\n \"vtex.store-resources\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.store-resources@0.30.0/public/@types/vtex.store-resources\",\n \"vtex.styleguide\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.styleguide@9.87.2/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"react\": \"^16.9.0\",\n \"react-intl\": \"2.8.0\"\n }\n}\n\n```"
}
] |
code_pwa-components_42221a0d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/react/PromotionBanner.tsx from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useCallback } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl, InjectedIntlProps, intlShape } from 'react-intl'\n\n// @ts-ignore\nimport { Button } from 'vtex.styleguide'\n\n// @ts-ignore\nimport { usePWA } from 'vtex.store-resources/PWAContext'\n\nconst propTypes = {\n intl: intlShape,\n type: PropTypes.oneOf(['install', 'push-notification']),\n onDismiss: PropTypes.func,\n}\n\nconst CONSTANTS = {\n TYPE_INSTALL: 'install',\n TYPE_PUSH_NOTIFICATION: 'push-notification',\n INSTALL_TITLE: 'store/promotion-banner.install.title',\n INSTALL_DESCRIPTION: 'store/promotion-banner.install.description',\n INSTALL_ACCEPT_BUTTON_LABEL:\n 'store/promotion-banner.install.button-accept.label',\n PUSH_NOTIFICATION_TITLE: 'store/promotion-banner.push-notification.title',\n PUSH_NOTIFICATION_DESCRIPTION:\n 'store/promotion-banner.push-notification.description',\n PUSH_NOTIFICATIONS_ACCEPT_BUTTON_LABEL:\n 'store/promotion-banner.push-notification.button-accept.label',\n DISMISS_BUTTON_LABEL: 'store/promotion-banner.button-dismiss.label',\n}\n\ntype Props = PropTypes.InferProps<typeof propTypes>\n\nconst PromotionBanner: FC<Props & InjectedIntlProps> = ({\n intl,\n type = 'install',\n onDismiss,\n}) => {\n const { showInstallPrompt = null } = usePWA() || {}\n\n const handleDismiss = useCallback(async () => {\n if (type === CONSTANTS.TYPE_INSTALL)\n localStorage.setItem('webAppInstallDismissed', 'true')\n else localStorage.setItem('pushNotificationsDismissed', 'true')\n\n if (onDismiss) {\n onDismiss()\n }\n }, [type, onDismiss])\n\n const handleAccept = useCallback(() => {\n if (type === CONSTANTS.TYPE_INSTALL) {\n showInstallPrompt()\n }\n }, [type, showInstallPrompt])\n\n return (\n <div className=\"pa6 br2 bg-muted-5 mb8 mw5 w-80-ns w-90 center fr-l\">\n <p className=\"t-body\">\n {intl.formatMessage({\n id:\n type === CONSTANTS.TYPE_INSTALL\n ? CONSTANTS.INSTALL_TITLE\n : CONSTANTS.PUSH_NOTIFICATION_TITLE,\n })}\n </p>\n <p className=\"t-small c-muted-1\">\n {intl.formatMessage({\n id:\n type === CONSTANTS.TYPE_INSTALL\n ? CONSTANTS.INSTALL_DESCRIPTION\n : CONSTANTS.PUSH_NOTIFICATION_DESCRIPTION,\n })}\n </p>\n <Button onClick={handleDismiss} variation=\"tertiary\" size=\"small\">\n {intl.formatMessage({\n id: CONSTANTS.DISMISS_BUTTON_LABEL,\n })}\n </Button>\n <Button onClick={handleAccept} size=\"small\">\n {intl.formatMessage({\n id:\n type === CONSTANTS.TYPE_INSTALL\n ? CONSTANTS.INSTALL_ACCEPT_BUTTON_LABEL\n : CONSTANTS.PUSH_NOTIFICATIONS_ACCEPT_BUTTON_LABEL,\n })}\n </Button>\n </div>\n )\n}\n\nPromotionBanner.propTypes = propTypes\n\nexport default injectIntl(PromotionBanner)\n\n```"
}
] |
code_pwa-components_5871ad8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/store/interfaces.json from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"promotion-banner\": {\n \"component\": \"PromotionBanner\"\n }, \n \"offline-warning\": {\n \"component\": \"OfflineWarning\"\n }\n}\n```"
}
] |
code_pwa-components_27636b5c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of pwa-components/react/typings/vtex.styleguide.d.ts from the pwa-components VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const Button\n export const EmptyState\n}\n\n```"
}
] |
code_octopia-scheduler_48470d0b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/graphql/schema.graphql from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n getAllSchedulers: [SchedulerInformation]\n getSchedulerById(id: ID!): SchedulerInformation\n}\n\ntype Mutation {\n createOrUpdateScheduler(\n configuration: SchedulerConfigurationInput\n ): SchedulerInformation\n\n deleteScheduler(id: ID!): Boolean\n}\n\n```"
}
] |
code_octopia-scheduler_9a1847a4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/service.json from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"getAllSchedulers\": {\n \"path\": \"/_v/octopia-scheduler/pvt/schedulers\",\n \"public\": false\n },\n \"getSchedulerById\": {\n \"path\": \"/_v/octopia-scheduler/pvt/schedulers/:id\",\n \"public\": false\n },\n \"createOrUpdateScheduler\": {\n \"path\": \"/_v/octopia-scheduler/pvt/schedulers/create-or-update/:type\",\n \"public\": false\n },\n \"deleteScheduler\": {\n \"path\": \"/_v/octopia-scheduler/pvt/schedulers/delete/:id\",\n \"public\": false\n }\n }\n}\n\n```"
}
] |
code_octopia-scheduler_348820ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/package.json from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.15\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\",\n \"vtex.octopia-scheduler\": \"https://octopia--edydemo.myvtex.com/_v/private/typings/linked/v1/vtex.octopia-scheduler@0.0.1+build1683562679/public/@types/vtex.octopia-scheduler\"\n },\n \"resolutions\": {\n \"@types/testing-library__dom\": \"6.12.1\",\n \"@types/express\": \"4.16.0\",\n \"@types/express-serve-static-core\": \"4.16.0\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.2.21\"\n}\n\n```"
}
] |
code_octopia-scheduler_75eab78d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/index.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ParamsContext, RecorderState } from '@vtex/api'\nimport { Service } from '@vtex/api'\n\nimport type { Clients } from './clients'\nimport { clientsConfig } from './clients'\nimport { applicationRoutes } from './middlewares/routes'\nimport { resolvers } from './resolvers'\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients: clientsConfig,\n routes: applicationRoutes,\n graphql: {\n resolvers,\n },\n})\n\n```"
}
] |
code_octopia-scheduler_5c2faac9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/graphql/types/Scheduler.graphql from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype SchedulerInformation {\n id: ID!\n workspace: String!\n app: String!\n attempt: Int!\n endDate: String!\n expression: String!\n NextExecution: String!\n request: Request!\n retry: Retry!\n}\n\ntype SchedulerConfiguration {\n id: ID!\n scheduler: Scheduler\n request: Request\n retry: Retry\n}\n\ntype SchedulerConfigurationPayload {\n type: String!\n production: Boolean!\n account: String!\n workspace: String!\n id: String\n endDate: String\n expression: String\n uri: String\n headers: JSON\n body: JSON\n}\n\nscalar JSON\n\ntype Request {\n uri: String!\n method: String!\n headers: JSON!\n body: JSON\n}\n\ntype Retry {\n delay: Delay\n times: Int!\n backOffRate: Int!\n}\n\ntype Delay {\n addMinutes: Int!\n addHours: Int!\n addDays: Int!\n}\n\ntype Scheduler {\n expression: String!\n endDate: String!\n}\n\ninput SchedulerConfigurationInput {\n type: String!\n production: Boolean!\n account: String!\n workspace: String!\n id: String\n endDate: String\n expression: String\n uri: String\n headers: JSON\n body: JSON\n}\n\n```"
}
] |
code_octopia-scheduler_0f846014
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/clients/scheduler.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { IOContext, InstanceOptions } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\nimport type {\n SchedulerConfiguration,\n SchedulerInformation,\n} from 'vtex.octopia-scheduler'\n\nimport { SCHEDULER_VERSION, VTEX_APP_NAME } from '../constants'\n\nexport class SchedulerClient extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n params: {\n version: SCHEDULER_VERSION,\n },\n headers: {\n ...options?.headers,\n VtexIdclientAutCookie: ctx.authToken,\n },\n })\n }\n\n private baseRoute = `/api/scheduler/${this.context.workspace}/${VTEX_APP_NAME}`\n\n public getAll(): Promise<SchedulerInformation[]> {\n return this.http.get(this.baseRoute, {\n metric: 'scheduler-list-all',\n })\n }\n\n public getById(schedulerId: string): Promise<SchedulerInformation> {\n return this.http.get(`${this.baseRoute}/${schedulerId}`, {\n metric: 'scheduler-get-by-id',\n })\n }\n\n public createOrUpdate(\n config: SchedulerConfiguration\n ): Promise<SchedulerInformation> {\n return this.http.put(this.baseRoute, config, {\n metric: 'scheduler-create-or-update',\n })\n }\n\n public delete(schedulerId: string) {\n return this.http.delete(`${this.baseRoute}/${schedulerId}`, {\n metric: 'scheduler-delete',\n })\n }\n}\n\n```"
}
] |
code_octopia-scheduler_e25cedc7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/clients/index.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig } from '@vtex/api'\nimport { IOClients } from '@vtex/api'\n\nimport { SchedulerClient } from './scheduler'\n\nexport class Clients extends IOClients {\n public get scheduler() {\n return this.getOrSet('scheduler', SchedulerClient)\n }\n}\n\nexport const clientsConfig: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: 10000,\n },\n },\n}\n\n```"
}
] |
code_octopia-scheduler_84c78300
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/constants/index.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const VTEX_APP_NAME = 'vtex.octopia-scheduler'\nexport const SCHEDULER_VERSION = '4'\n\n```"
}
] |
code_octopia-scheduler_072fd589
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/typings/global.d.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ServiceContext } from '@vtex/api'\nimport type { Clients } from '../clients'\n\ndeclare global {\n type Context = ServiceContext<Clients>\n}\n\n```"
}
] |
code_octopia-scheduler_a1f5e513
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/resolvers/index.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { getAllSchedulers } from './schedulers/getAll'\nimport { getSchedulerById } from './schedulers/getById'\nimport { createOrUpdateScheduler } from './schedulers/createOrUpdate'\nimport { deleteScheduler } from './schedulers/delete'\n\nexport const resolvers = {\n Query: {\n getAllSchedulers,\n getSchedulerById,\n },\n Mutation: {\n createOrUpdateScheduler,\n deleteScheduler,\n },\n}\n\n```"
}
] |
code_octopia-scheduler_31b68a1f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/helpers/serviceError.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype ServiceErrorArgs = {\n message: string\n reason: string\n status?: number\n}\n\nexport class ServiceError extends Error {\n constructor({ message, reason, status }: ServiceErrorArgs) {\n super(message)\n this.reason = reason ?? 'INTERNAL_SERVER_ERROR'\n this.status = status ?? 500\n }\n\n public readonly reason: string\n public readonly status: number\n}\n\n```"
}
] |
code_octopia-scheduler_97fd54fd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/helpers/scheduler.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n SchedulerConfiguration,\n SchedulerConfigurationPayload,\n} from 'vtex.octopia-scheduler'\n\n/**\n * Function to create the scheduler configuration\n * @param args\n * @returns SchedulerConfiguration\n */\nexport function createSchedulerConfiguration(\n args: SchedulerConfigurationPayload\n): SchedulerConfiguration {\n const {\n type,\n production,\n account,\n workspace,\n id,\n endDate,\n expression,\n uri,\n headers = defaultHeaders(),\n body = defaultBody(type),\n } = args\n\n return {\n id: id ?? createId(type),\n scheduler: {\n expression: expression ?? defaultExpression(type),\n endDate: endDate ?? createEndDate(production),\n },\n retry: {\n delay: {\n addMinutes: 2,\n addHours: 0,\n addDays: 0,\n },\n times: 2,\n backOffRate: 2,\n },\n request: {\n uri: uri ?? defaultUri(workspace, account, type),\n method: 'POST',\n headers,\n body,\n },\n }\n}\n\nfunction createId(type: SchedulerConfigurationPayload['type']) {\n return `${type.toUpperCase()}_SCHEDULER`\n}\n\nfunction createEndDate(production: boolean) {\n const endDate = new Date()\n\n // If the environment is not production, the endDate will be 24 hours from now\n endDate.setHours(endDate.getHours() + 24)\n\n // If the environment is production, the endDate will be 10 years from now\n if (production) {\n endDate.setFullYear(endDate.getFullYear() + 10)\n }\n\n return endDate.toISOString()\n}\n\nfunction defaultExpression(type: SchedulerConfigurationPayload['type']) {\n return type === 'offers' ? '0 0/12 * * *' : '0 * * * *'\n}\n\nfunction defaultUri(\n workspace: string,\n account: string,\n type: SchedulerConfigurationPayload['type']\n) {\n return `https://${workspace}--${account}.myvtex.com/_v/octopia-integration/${type}`\n}\n\nfunction defaultHeaders() {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n}\n\nfunction defaultBody(type: SchedulerConfigurationPayload['type']) {\n return {\n text: `${type} scheduler`,\n }\n}\n\n```"
}
] |
code_octopia-scheduler_d5ca1482
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/errorHandler.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function errorHandler(ctx: Context, next: () => Promise<void>) {\n try {\n await next()\n } catch (error) {\n if (process.env.VTEX_APP_LINKED) {\n console.error(error)\n\n return\n }\n\n const {\n vtex: { logger },\n } = ctx\n\n logger.error({\n message: error.message,\n reason: error.reason,\n exception: error,\n })\n\n ctx.status = error.status || error.response?.status || 500\n ctx.body = { error: error.message, reason: error.reason }\n ctx.app.emit('error', error, ctx)\n }\n}\n\n```"
}
] |
code_octopia-scheduler_df69ac5e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/index.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { method } from '@vtex/api'\n\nimport { errorHandler } from './errorHandler'\nimport { getAllSchedulers } from './schedulers/getAll'\nimport { getSchedulerById } from './schedulers/getById'\nimport { createOrUpdateScheduler } from './schedulers/createOrUpdate'\nimport { deleteScheduler } from './schedulers/delete'\n\nexport const applicationRoutes = {\n getAllSchedulers: method({\n GET: [errorHandler, getAllSchedulers],\n }),\n getSchedulerById: method({\n GET: [errorHandler, getSchedulerById],\n }),\n createOrUpdateScheduler: method({\n PUT: [errorHandler, createOrUpdateScheduler],\n }),\n deleteScheduler: method({\n DELETE: [errorHandler, deleteScheduler],\n }),\n}\n\n```"
}
] |
code_octopia-scheduler_fb343285
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/schedulers/createOrUpdate.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport { ServiceError } from '../../../helpers/serviceError'\nimport { createOrUpdateSchedulerService } from '../../../services/schedulers/createOrUpdate'\n\nexport async function createOrUpdateScheduler(ctx: Context) {\n const {\n params: { type },\n } = ctx\n\n const body = await json(ctx.req)\n\n const configuration = {\n type,\n ...body,\n }\n\n try {\n const schedulerInformation = await createOrUpdateSchedulerService(\n configuration,\n ctx\n )\n\n ctx.body = schedulerInformation\n } catch (error) {\n throw new ServiceError({\n message: 'Error creating or updating scheduler',\n reason: error.message,\n })\n }\n}\n\n```"
}
] |
code_octopia-scheduler_5e4a5871
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/schedulers/getAll.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ServiceError } from '../../../helpers/serviceError'\nimport { getAllSchedulersService } from '../../../services/schedulers/getAll'\n\nexport async function getAllSchedulers(ctx: Context) {\n try {\n const schedulers = await getAllSchedulersService(ctx)\n\n ctx.body = schedulers\n } catch (error) {\n throw new ServiceError({\n message: 'Error getting schedulers',\n reason: error.message,\n })\n }\n}\n\n```"
}
] |
code_octopia-scheduler_5afda250
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/schedulers/getById.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ServiceError } from '../../../helpers/serviceError'\nimport { getSchedulerByIdService } from '../../../services/schedulers/getById'\n\nexport async function getSchedulerById(ctx: Context) {\n const {\n vtex: {\n route: {\n params: { id },\n },\n },\n } = ctx\n\n try {\n const schedulerInformation = await getSchedulerByIdService(\n id as string,\n ctx\n )\n\n ctx.body = schedulerInformation\n } catch (error) {\n throw new ServiceError({\n message: 'Error getting scheduler',\n reason: error.message,\n })\n }\n}\n\n```"
}
] |
code_octopia-scheduler_ffd2f4a3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/middlewares/routes/schedulers/delete.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ServiceError } from '../../../helpers/serviceError'\nimport { deleteSchedulerService } from '../../../services/schedulers/delete'\n\nexport async function deleteScheduler(ctx: Context) {\n const {\n vtex: {\n route: {\n params: { id },\n },\n },\n } = ctx\n\n try {\n await deleteSchedulerService(id as string, ctx)\n\n ctx.status = 204\n } catch (error) {\n throw new ServiceError({\n message: 'Error deleting scheduler',\n reason: error.message,\n })\n }\n}\n\n```"
}
] |
code_octopia-scheduler_8bf7b833
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/resolvers/schedulers/createOrUpdate.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport type { SchedulerConfigurationPayload } from 'vtex.octopia-scheduler'\n\nimport { createOrUpdateSchedulerService } from '../../services/schedulers/createOrUpdate'\n\nexport async function createOrUpdateScheduler(\n _: unknown,\n args: { configuration: SchedulerConfigurationPayload },\n ctx: Context\n) {\n // eslint-disable-next-line no-console\n console.log('Args', args)\n\n const { configuration } = args\n\n if (configuration.type !== 'offers' && configuration.type !== 'orders') {\n throw new ResolverError('Invalid type', 400, 'INVALID_TYPE')\n }\n\n try {\n const schedulerInformation = await createOrUpdateSchedulerService(\n configuration,\n ctx\n )\n\n return schedulerInformation\n } catch (error) {\n throw new ResolverError(\n 'Error creating or updating scheduler',\n error.statusCode ?? 500,\n error.message ?? 'INTERNAL_SERVER_ERROR'\n )\n }\n}\n\n```"
}
] |
code_octopia-scheduler_49a6bae2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/resolvers/schedulers/getAll.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { getAllSchedulersService } from '../../services/schedulers/getAll'\n\nexport async function getAllSchedulers(_: unknown, __: unknown, ctx: Context) {\n try {\n const schedulers = await getAllSchedulersService(ctx)\n\n return schedulers\n } catch (error) {\n throw new ResolverError(\n 'Error getting all schedulers',\n error.statusCode ?? 500,\n error.message ?? 'INTERNAL_SERVER_ERROR'\n )\n }\n}\n\n```"
}
] |
code_octopia-scheduler_4b10ddbb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/resolvers/schedulers/getById.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nexport async function getSchedulerById(\n _: unknown,\n args: { id: string },\n ctx: Context\n) {\n const { id } = args\n\n const {\n clients: { scheduler },\n } = ctx\n\n try {\n const schedulerInformation = await scheduler.getById(id)\n\n return schedulerInformation\n } catch (error) {\n throw new ResolverError(\n 'Error getting scheduler',\n error.statusCode ?? 500,\n error.message ?? 'INTERNAL_SERVER_ERROR'\n )\n }\n}\n\n```"
}
] |
code_octopia-scheduler_059af463
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/resolvers/schedulers/delete.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { deleteSchedulerService } from '../../services/schedulers/delete'\n\nexport async function deleteScheduler(\n _: unknown,\n args: { id: string },\n ctx: Context\n) {\n // eslint-disable-next-line no-console\n console.log('Args', args)\n\n const { id } = args\n\n try {\n await deleteSchedulerService(id, ctx)\n\n return true\n } catch (error) {\n throw new ResolverError(\n 'Error deleting scheduler',\n error.statusCode ?? 500,\n error.message ?? 'INTERNAL_SERVER_ERROR'\n )\n }\n}\n\n```"
}
] |
code_octopia-scheduler_12b5f53d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/services/schedulers/createOrUpdate.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport type { SchedulerConfigurationPayload } from 'vtex.octopia-scheduler'\n\nimport { createSchedulerConfiguration } from '../../helpers/scheduler'\n\nexport async function createOrUpdateSchedulerService(\n configuration: SchedulerConfigurationPayload,\n ctx: Context\n) {\n const {\n clients: { scheduler },\n vtex: { production, workspace, account },\n } = ctx\n\n try {\n const { type } = configuration\n\n if (type !== 'offers' && type !== 'orders') {\n throw new UserInputError('Invalid type')\n }\n\n const schedulerConfiguration = createSchedulerConfiguration({\n ...configuration,\n production,\n account,\n workspace,\n })\n\n const schedulerInformation = await scheduler.createOrUpdate(\n schedulerConfiguration\n )\n\n return schedulerInformation\n } catch (error) {\n throw new Error(error.message)\n }\n}\n\n```"
}
] |
code_octopia-scheduler_c5e0a3bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/services/schedulers/getAll.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function getAllSchedulersService(ctx: Context) {\n const {\n clients: { scheduler },\n } = ctx\n\n try {\n const schedulers = await scheduler.getAll()\n\n return schedulers\n } catch (error) {\n throw new Error(error.message)\n }\n}\n\n```"
}
] |
code_octopia-scheduler_a792204e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/services/schedulers/getById.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function getSchedulerByIdService(id: string, ctx: Context) {\n const {\n clients: { scheduler },\n } = ctx\n\n try {\n const schedulerInformation = await scheduler.getById(id)\n\n return schedulerInformation\n } catch (error) {\n throw new Error(error.message)\n }\n}\n\n```"
}
] |
code_octopia-scheduler_fcf8405e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of octopia-scheduler/node/services/schedulers/delete.ts from the octopia-scheduler VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function deleteSchedulerService(id: string, ctx: Context) {\n const {\n clients: { scheduler },\n } = ctx\n\n try {\n await scheduler.delete(id)\n\n return true\n } catch (error) {\n throw new Error(error.message)\n }\n}\n\n```"
}
] |
code_product-context_0c7f4525
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/docs/README.md from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/product-context) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Product Context\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nThe Product Context app is designed to provide essential product data to all child blocks within your store theme.\n\n## Configuration\n\n1. Add the `product-context` app as a dependency to your store theme's `manifest.json` file:\n \n ```diff manifest.json\n \"dependencies\": {\n + \"vtex.product-context\": \"0.x\"\n }\n ```\n \n2. Install the TypeScript types exported by the app by running the following command:\n \n ```sh\n vtex setup\n ```\n\nNow, you're ready to import components and hooks from the app. Check this example component that displays the product name using data stored in the nearest `ProductContext`:\n\n```tsx\n// Notice that this is TypeScript, and this code should be in a .tsx file\nimport React, { FC } from 'react'\nimport { useProduct } from 'vtex.product-context'\n\nconst MyComponent: FC = () => {\n const productContextValue = useProduct();\n\n return (\n <Fragment>\n {productContextValue?.product?.productName}\n </Fragment>\n )\n}\n\nexport default MyComponent\n```\n\n## Hooks\n\n### `useProduct`\n\nThe `useProduct` hook allows your app to retrieve data from the nearest `ProductContext` relative to its caller. Expect an object with the structure below as the return value:\n\n```ts\ninterface ProductContextState {\n selectedItem?: Item | null\n product: MaybeProduct\n selectedQuantity: number\n skuSelector: {\n selectedImageVariationSKU: string | null\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```\n\n> Note that if the hook is called outside a `ProductContextProvider`, the return value may be `undefined` or an empty object.\n\n### `useProductDispatch`\n\nThe `useProductDispatch` hook provides a `dispatch` function to manipulate the nearest `ProductContext`. The function supports the following actions:\n\n- `SELECT_IMAGE_VARIATION`: Sets the value for the `skuSelector.selectedImageVariationSKU` property.\n- `SET_QUANTITY`: Sets the value for the `selectedQuantity` property.\n- `SKU_SELECTOR_SET_VARIATIONS_SELECTED`: Sets the value for the `skuSelector.areAllVariationsSelected` property.\n- `SET_BUY_BUTTON_CLICKED`: Sets the value for the `buyButton.clicked` property.\n- `SKU_SELECTOR_SET_IS_VISIBLE`: Sets the value for the `skuSelector.isVisible` property.\n- `SET_SELECTED_ITEM`: Sets the value for the `selectedItem` property.\n- `SET_ASSEMBLY_OPTIONS`: Sets the value for the `assemblyOptions` property.\n- `SET_PRODUCT`: Sets the value for the `product` property.\n- `SET_LOADING_ITEM`: Sets the value of whether a selected item is loading.\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/sahanljc\"><img src=\"https://avatars.githubusercontent.com/u/42151054?v=4?s=100\" width=\"100px;\" alt=\"\"/><br /><sub><b>Sahan Jayawardana</b></sub></a><br /><a href=\"https://github.com/vtex-apps/product-context/commits?author=sahanljc\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_product-context_b3d4c405
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/ProductContext.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createContext } from 'react'\n\nimport type { ProductContextState } from './ProductContextProvider'\n\nconst ProductContext = createContext<Partial<ProductContextState> | undefined>(\n {}\n)\n\nexport default ProductContext\n\n```"
}
] |
code_product-context_431b4b51
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/useProductDispatch.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport { ProductDispatchContext } from './ProductDispatchContext'\n\n/**\n * useProductDispatch hook. Use this hook to make changes to the data from the nearest\n * `ProductContext`.\n *\n * @returns `dispatch` function | `null`.\n */\nfunction useProductDispatch() {\n return useContext(ProductDispatchContext)\n}\n\nexport default useProductDispatch\n\n```"
}
] |
code_product-context_b4b8e70b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/ProductContextProvider.tsx from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useEffect, Dispatch } from 'react'\n\nimport ProductContext from './ProductContext'\nimport { ProductDispatchContext } from './ProductDispatchContext'\nimport { useProductReducer, getSelectedItem } from './reducer'\nimport { getSelectedSKUFromQueryString } from './modules/skuQueryString'\nimport { MaybeProduct, Item } from './ProductTypes'\n\nexport interface ProductAndQuery {\n query: Record<string, any>\n product: MaybeProduct\n}\n\ntype GroupId = string\n\nexport interface AssemblyOptionItem {\n id: string\n quantity: number\n seller: string\n initialQuantity: number\n choiceType: string\n name: string\n price: number\n children: Record<string, AssemblyOptionItem[]> | null\n}\n\nexport interface BuyButtonContextState {\n clicked: boolean\n}\n\nexport interface SkuSelectorContextState {\n selectedImageVariationSKU: string | null\n isVisible: boolean\n areAllVariationsSelected: boolean\n}\n\nexport interface ProductContextState {\n loadingItem: boolean\n selectedItem?: Item | null\n product: MaybeProduct\n selectedQuantity: number\n skuSelector: Partial<SkuSelectorContextState>\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 Action<K, V = void> = V extends void ? { type: K } : { type: K } & V\n\nexport type Actions =\n | Action<\n 'SELECT_IMAGE_VARIATION',\n { args: { selectedImageVariationSKU: string | null } }\n >\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 | Action<'SET_LOADING_ITEM', { args: { loadingItem: boolean } }>\n\nfunction useProductInState(product: MaybeProduct, dispatch: Dispatch<Actions>) {\n useEffect(() => {\n if (product) {\n dispatch({\n type: 'SET_PRODUCT',\n args: { product },\n })\n }\n }, [product, dispatch])\n}\n\nfunction useSelectedItemFromId(\n dispatch: Dispatch<Actions>,\n product: MaybeProduct,\n skuId?: string\n) {\n useEffect(() => {\n const items = product?.items ?? []\n\n dispatch({\n type: 'SET_SELECTED_ITEM',\n args: { item: getSelectedItem(skuId, items) },\n })\n }, [dispatch, skuId, product])\n}\n\nconst ProductContextProvider: FC<ProductAndQuery> = ({\n query,\n product,\n children,\n}) => {\n const [state, dispatch] = useProductReducer({ query, product })\n\n // These hooks are used to keep the state in sync with API data, specially when switching between products without exiting the product page\n useProductInState(product, dispatch)\n const selectedSkuQueryString = getSelectedSKUFromQueryString(\n query,\n product?.items\n )\n\n useSelectedItemFromId(dispatch, product, selectedSkuQueryString)\n\n return (\n <ProductContext.Provider value={state}>\n <ProductDispatchContext.Provider value={dispatch}>\n {children}\n </ProductDispatchContext.Provider>\n </ProductContext.Provider>\n )\n}\n\nexport default ProductContextProvider\n\n```"
}
] |
code_product-context_6e7b03f8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/useProduct.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport ProductContext from './ProductContext'\n\n/**\n * useProduct hook. Use this hook to access the data from the nearest\n * `ProductContext`.\n *\n * Be aware that this could be an empty Object if used outside of a\n * `ProductContextProvider`.\n *\n * @returns `ProductContextState` | `undefined` | `{}`\n */\nfunction useProduct() {\n return useContext(ProductContext)\n}\n\nexport default useProduct\n\n```"
}
] |
code_product-context_d39c3e55
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/ProductDispatchContext.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Dispatch } from 'react'\nimport { createContext, useContext } from 'react'\n\nimport type { Actions } from './ProductContextProvider'\n\nexport const ProductDispatchContext = createContext<Dispatch<Actions> | null>(\n null\n)\n\nfunction useProductDispatch() {\n return useContext(ProductDispatchContext)\n}\n\nexport default { ProductDispatchContext, useProductDispatch }\n\n```"
}
] |
code_product-context_d0e124b5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/package.json from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^4.0.0\",\n \"@types/node\": \"^11.13.4\",\n \"@types/ramda\": \"^0.26.21\",\n \"@types/react\": \"^16.8.13\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"react-intl\": \"^5.4.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vteximg.com.br/_v/public/typings/v1/vtex.render-runtime@8.62.2/public/_types/react\"\n },\n \"version\": \"0.10.1\"\n}\n\n```"
}
] |
code_product-context_c36c3fa4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/ProductTypes.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport type {\n ProductContextState,\n AssemblyOptionItem,\n SkuSelectorContextState,\n} from './ProductContextProvider'\n\ntype Maybe<T> = T | null | undefined\n\nexport type MaybeProduct = Maybe<Product>\n\nexport type ProductSpecification = {\n name: string\n originalName: string\n values: string[]\n}\n\n/** @deprecated Use `ProductSpecification` */\nexport type SpecificationGroupItem = ProductSpecification\n\nexport type SpecificationGroup = {\n name: string\n originalName: string\n specifications: ProductSpecification[]\n}\n\nexport type Product = {\n brand: string\n brandId: string\n cacheId: string\n categories: string[]\n categoriesIds: string[]\n categoryId: string\n categoryTree: Array<{ id: string; name: string; href: string }>\n clusterHighlights: Array<{ id: string; name: string }>\n description: string\n itemMetadata: ItemMetadata\n items: Item[]\n link: string\n linkText: string\n metaTagDescription: string\n priceRange: {\n sellingPrice: { highPrice: number; lowPrice: number }\n listPrice: { highPrice: number; lowPrice: number }\n }\n productClusters: Array<{ id: string; name: string }>\n productId: string\n productName: string\n productReference: string\n properties: ProductSpecification[]\n skuSpecifications: SkuSpecification[]\n specificationGroups: SpecificationGroup[]\n titleTag: string\n}\n\nexport type Item = {\n complementName: string\n ean: string\n images: Array<{\n imageId: string\n imageLabel: string\n imageTag: string\n imageUrl: string\n imageText: string\n }>\n itemId: string\n measurementUnit: string\n name: string\n nameComplete: string\n referenceId: Array<{ Key: string; Value: string }>\n sellers: Seller[]\n unitMultiplier: number\n variations: Array<{ name: string; values: string[] }>\n videos: Array<{ videoUrl: string }>\n}\n\nexport type SkuSpecification = {\n field: SkuSpecificationField\n values: SkuSpecificationValues[]\n}\n\nexport type SkuSpecificationField = {\n name: string\n}\n\nexport type SkuSpecificationValues = {\n name: string\n}\n\nexport type Seller = {\n sellerId: string\n sellerName: string\n addToCartLink: string\n sellerDefault: boolean\n commertialOffer: CommercialOffer\n}\n\ntype TeaserCondition = {\n minimumQuantity: number\n parameters: Array<{\n name: string\n value: string\n }>\n}\n\ntype TeaserEffects = {\n parameters: Array<{\n name: string\n value: string\n }>\n}\n\nexport type Teaser = {\n name: string\n conditions: TeaserCondition\n effects: TeaserEffects\n}\n\nexport type CommercialOffer = {\n Installments: Installment[]\n discountHighlights: Array<{ name: string }>\n teasers: Teaser[]\n Price: number\n ListPrice: number\n spotPrice: number\n SellingPrice?: number\n PriceWithoutDiscount: number\n RewardValue: number\n PriceValidUntil: string\n AvailableQuantity: number\n Tax: number\n taxPercentage: number\n CacheVersionUsedToCallCheckout: string\n}\n\nexport type Installment = {\n Value: number\n InterestRate: number\n TotalValuePlusInterestRate: number\n NumberOfInstallments: number\n PaymentSystemName: string\n PaymentSystemGroupName: string\n Name: string\n}\n\nexport type ItemMetadata = {\n items: Array<{\n id: string\n name: string\n imageUrl: string\n seller: string\n assemblyOptions: Array<{\n id: string\n name: string\n required: boolean\n inputValues: InputValue[]\n composition: Composition | null\n }>\n }>\n priceTable: Array<{\n type: string\n values: Array<{ id: string; assemblyId: string; price: number | null }>\n }>\n}\n\nexport type InputValue = TextInputValue | BooleanInputValue | OptionsInputValue\n\nconst enum InputValueType {\n 'TEXT' = 'TEXT',\n 'BOOLEAN' = 'BOOLEAN',\n 'OPTIONS' = 'OPTIONS',\n}\n\nexport type TextInputValue = {\n type: InputValueType.TEXT\n defaultValue: ''\n label: string\n maxLength: number\n domain: null\n}\n\nexport type BooleanInputValue = {\n type: InputValueType.BOOLEAN\n defaultValue: boolean\n label: string\n maxLength: null\n domain: null\n}\n\nexport type OptionsInputValue = {\n type: InputValueType.OPTIONS\n defaultValue: string\n label: string\n maxLength: null\n domain: string[]\n}\n\nexport type Composition = {\n minQuantity: number\n maxQuantity: number\n items: Array<{\n id: string\n minQuantity: number\n maxQuantity: number\n priceTable: string\n seller: string\n initialQuantity: number\n }>\n}\n\n```"
}
] |
code_product-context_fe850ee0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/reducer/index.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useReducer } from 'react'\n\nimport { getSelectedSKUFromQueryString } from '../modules/skuQueryString'\nimport { findAvailableProduct } from '../modules/items'\nimport type { Item } from '../ProductTypes'\nimport type {\n ProductContextState,\n Actions,\n ProductAndQuery,\n} from '../ProductContextProvider'\n\nconst defaultState: ProductContextState = {\n loadingItem: false,\n product: undefined,\n selectedItem: null,\n selectedQuantity: 1,\n skuSelector: {\n selectedImageVariationSKU: null,\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: Actions\n): ProductContextState {\n switch (action.type) {\n case 'SET_QUANTITY': {\n const args = action.args || {}\n\n return {\n ...state,\n selectedQuantity: args.quantity,\n }\n }\n\n case 'SELECT_IMAGE_VARIATION': {\n const args = action.args || {}\n\n return {\n ...state,\n skuSelector: {\n ...state.skuSelector,\n selectedImageVariationSKU: args.selectedImageVariationSKU,\n },\n }\n }\n\n case 'SKU_SELECTOR_SET_VARIATIONS_SELECTED': {\n const args = action.args || {}\n\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\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\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\n return {\n ...state,\n loadingItem: false,\n selectedItem: args.item,\n }\n }\n\n case 'SET_LOADING_ITEM': {\n return {\n ...state,\n loadingItem: Boolean(action.args.loadingItem),\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 = state?.product?.linkText !== args?.product?.linkText\n\n return {\n ...state,\n ...(differentSlug ? defaultState : {}),\n product: args.product,\n }\n }\n\n default:\n return state\n }\n}\n\nexport function getSelectedItem(skuId: string | undefined, items: Item[]) {\n return skuId\n ? items.find((item) => item.itemId === skuId)\n : items.find(findAvailableProduct) ?? items[0]\n}\n\nfunction initReducer({ query, product }: ProductAndQuery) {\n const items = product?.items ?? []\n\n return {\n ...defaultState,\n selectedItem: getSelectedItem(\n getSelectedSKUFromQueryString(query, items),\n items\n ),\n product,\n }\n}\n\nexport const useProductReducer = ({ query, product }: ProductAndQuery) =>\n useReducer(reducer, { query, product }, initReducer)\n\n```"
}
] |
code_product-context_6c1e0a28
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/__tests__/ProductContextProvider.test.tsx from the product-context 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'\n\n// eslint-disable-next-line jest/no-mocks-import\nimport { getProduct, getItem } from '../__mocks__/productMock'\nimport ProductContextProvider from '../ProductContextProvider'\nimport ProductContext from '../ProductContext'\nimport ProductDispatchContext from '../ProductDispatchContext'\n\nconst { useProductDispatch } = ProductDispatchContext\n\nconst ProductPageMock = () => {\n const { selectedItem, product, selectedQuantity } = useContext(\n ProductContext\n ) as any\n\n return (\n <div>\n <div>Product Page</div>\n <div>Selected Item id: {selectedItem?.itemId}</div>\n <div>Selected Item name: {selectedItem?.name}</div>\n {product ? (\n <div>product slug: {product?.linkText}</div>\n ) : (\n <div>no product</div>\n )}\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\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 }) =>\n getByText(`Selected Item id: ${item.itemId}`),\n getSelectedItemName: (item: { name: string }) =>\n getByText(`Selected Item name: ${item.name}`),\n getProductSlug: (product: { linkText: string }) =>\n getByText(`product slug: ${product.linkText}`),\n rerender: (newProps: any) =>\n rerender(\n <ProductContextProvider {...newProps}>\n <ProductPageMock />\n </ProductContextProvider>\n ),\n }\n }\n\n it('should render with product', () => {\n const product = getProduct()\n const { getProductSlug } = renderComponent()\n\n getProductSlug(product)\n })\n\n it('should render with no product and then switch', () => {\n const { getProductSlug, rerender, testNoProduct } = renderComponent({\n product: undefined,\n })\n\n testNoProduct()\n\n const product = getProduct()\n\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\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\n const props = {\n product: newProduct,\n params: { slug: newProduct.linkText },\n productQuery: { product: newProduct, loading: false },\n }\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\n dispatch?.({ type: 'SET_QUANTITY', quantity: 1 } as any)\n dispatch?.({\n type: 'SKU_SELECTOR_SET_VARIATIONS_SELECTED',\n quantity: 1,\n } as any)\n dispatch?.({ type: 'SKU_SELECTOR_SET_IS_VISIBLE', quantity: 1 } as any)\n dispatch?.({ type: 'SET_SELECTED_ITEM', quantity: 1 } as any)\n dispatch?.({ type: 'SET_ASSEMBLY_OPTIONS', quantity: 1 } as any)\n dispatch?.({ type: 'SET_PRODUCT', quantity: 1 } as any)\n\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_product-context_5e5fccec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/modules/items.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Item, Seller } from '../ProductTypes'\n\nexport function findAvailableProduct(item: Item) {\n return item.sellers.find((seller: Seller) => {\n return seller?.commertialOffer?.AvailableQuantity > 0\n })\n}\n\nexport function itemHasVariation(\n item: Item,\n { name, value }: { name: string; value: string }\n) {\n return Boolean(\n item.variations.find(\n (variation) =>\n variation.name === name &&\n variation.values.some((variationValue) => variationValue === value)\n )\n )\n}\n\n```"
}
] |
code_product-context_333d8bc3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of product-context/react/modules/skuQueryString.ts from the product-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { itemHasVariation, findAvailableProduct } from './items'\nimport type { Item } from '../ProductTypes'\n\ninterface QueryParams {\n skuId?: string\n idsku?: string\n}\n\nconst QUERY_STRING_VARIANT_PREFIX = 'property__'\n\n// `idsku` querystring is to keep compatibility with Google Shopping integration\nexport const getSelectedSKUFromQueryString = (\n query: QueryParams,\n items: Item[] = []\n) => {\n const skuId = query.skuId ?? query.idsku\n\n if (skuId) {\n return skuId\n }\n\n const variantQueryProps = Object.entries(query)\n .filter(([key]) => key.startsWith(QUERY_STRING_VARIANT_PREFIX))\n .map(([key, value]) => [\n key.slice(QUERY_STRING_VARIANT_PREFIX.length),\n value,\n ])\n\n if (variantQueryProps.length === 0) {\n return\n }\n\n const itemsWithVariation = items.filter((item) =>\n variantQueryProps.every(([name, value]) => {\n return itemHasVariation(item, { name, value })\n })\n )\n\n if (itemsWithVariation.length === 0) {\n return\n }\n\n const availableItem = itemsWithVariation.find((item) =>\n findAvailableProduct(item)\n )\n\n if (availableItem) {\n return availableItem.itemId\n }\n\n return itemsWithVariation[0].itemId\n}\n\n```"
}
] |
code_admin-vbase-example_d13129d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/messages/pt.json from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin-example.navigation.label\": \"Aplicação de Exemplo de Admin\",\n \"admin-example.navigation.search.kws\": \"token\",\n \"admin-example.navigation.insight\": \"Insights\",\n \"admin-example.navigation.management\": \"Gerenciamento\"\n}\n\n```"
}
] |
code_admin-vbase-example_a510de70
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/messages/en.json from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin-example.navigation.label\": \"Admin Example Application\",\n \"admin-example.navigation.search.kws\": \"token\",\n \"admin-example.navigation.insight\": \"Insights\",\n \"admin-example.navigation.management\": \"Management\"\n}\n\n```"
}
] |
code_admin-vbase-example_c1301211
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/messages/es.json from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin-example.navigation.label\": \"Aplicacíon de Ejemplo de Admin\",\n \"admin-example.navigation.search.kws\": \"token\",\n \"admin-example.navigation.insight\": \"Insights\",\n \"admin-example.navigation.management\": \"Management\"\n}\n\n```"
}
] |
code_admin-vbase-example_bb5fd7a2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/admin/navigation.json from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"section\": \"orders\",\n \"titleId\": \"admin-example.navigation.label\",\n \"searchKeyWordsHelpers\": \"admin-example.navigation.search.kws\",\n \"subSectionItems\": [\n {\n \"labelId\": \"admin-example.navigation.insight\",\n \"path\": \"/admin/adminExample\"\n },\n {\n \"labelId\": \"admin-example.navigation.management\",\n \"path\": \"/admin/adminOtherExample\"\n }\n ]\n}\n\n```"
}
] |
code_admin-vbase-example_cdeb55f2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/admin/routes.json from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin.app.example\": {\n \"component\": \"adminExample\",\n \"path\": \"/admin/app/adminExample\"\n },\n \"admin.app.otherexample\": {\n \"component\": \"adminOtherExample\",\n \"path\": \"/admin/app/adminOtherExample\"\n }\n}\n\n```"
}
] |
code_admin-vbase-example_dea5e422
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/docs/README.md from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Admin Example - VBase\n\nThis example is an admin app with VBase save and retrieval implementation.\n\n\n\n```"
}
] |
code_admin-vbase-example_ea71eaf4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-vbase-example/graphql/schema.graphql from the admin-vbase-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n token: String\n}\n\ntype Mutation {\n saveToken(token: String): String\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.