id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store_45ae6943
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/messages/es.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.product-search.title\": \"Contexto de búsqueda de productos\",\n \"admin/editor.product-search.maxItemsPerPage\": \"Número máximo de elementos por página\",\n \"admin/editor.product-search.hideUnavailableItems\": \"Esconder elementos no disponibles\",\n \"store/store.network-status.offline\": \"Sin conexión a internet.\",\n \"admin/actions.enable-binding\": \"Activar la configuración por vinculación\",\n \"admin/actions.binding-configurations\": \"Configuración de vinculación\",\n \"admin/actions.binding-id\": \"ID de vínculo\",\n \"admin/actions.binding-description\": \"Introduce el ID de vínculo\"\n}\n\n```"
}
] |
code_store_a9ec8aa7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/messages/ar.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.product-search.title\": \"سياق البحث عن المنتج\",\n \"admin/editor.product-search.maxItemsPerPage\": \"الحد الأقصى لعدد العناصر في كل صفحة\",\n \"admin/editor.product-search.hideUnavailableItems\": \"إخفاء العناصر غير المتاحة\",\n \"store/store.network-status.offline\": \"لا يوجد اتصال بالإنترنت.\",\n \"admin/actions.enable-binding\": \"Enable configuration by binding\",\n \"admin/actions.binding-configurations\": \"Binding configurations\",\n \"admin/actions.binding-id\": \"Binding ID\",\n \"admin/actions.binding-description\": \"Enter the binding ID\"\n}\n\n```"
}
] |
code_store_eaca9684
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/docs/README.md from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# VTEX Store Framework\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\nFramework that is used by all ecommerce stores build on VTEX IO.\n\n⚠️⚠️ **All stores MUST use this app. Using a forked version WILL break your store.** ⚠️⚠️\n\n## Table of Contents\n\n- [Description](#description)\n- [Release schedule](#release-schedule)\n- [Store Builder](#store-builder)\n - [Overview](#overview)\n - [Blocks Language](#blocks-language)\n - [Interface Structure](#interface-structure)\n - [Recipes](#recipes)\n- [Blocks Reference](#blocks-reference)\n- [Pixel Architecture](#pixel-architecture)\n- [Contributing](#contributing)\n\n## Description\n\nStore Framework is responsible for defining the basic structure of any ecommerce store of the platform. With this app, we want to provide an abstraction for our clients and partners not worry about SEO and fetch basic data from VTEX. Any account has this app installed.\n\nThis project has the following capabilities:\n\n- Setup metatags for all pages. \n- Fetch product and products search data from VTEX APIs \n- Dispatch view events to analytics tools. \n- Define the necessary interfaces and routes of the store.\n\n## Release schedule\n\n| Release | Status | Initial Release | Maintenance LTS Start | End-of-life | Store Compatibility |\n| :-----: | :-----------------: | :-------------: | :-------------------: | :---------: | :-----------------: |\n| [2.x] | **Current Release** | 2018-11-28 | | | 2.x |\n| [1.x] | **Maintenance LTS** | 2018-08-21 | 2018-11-28 | March 2019 | 1.x |\n\nSee our [LTS policy](https://github.com/vtex-apps/awesome-io#lts-policy) for more information.\n\n## Store Builder\n\nVTEX IO created a powerful way to configure the behavior [React](https://reactjs.org/) components yielding the basic building *blocks* for a web app.\n\nIO **store builder** is a opinionated way to use IO capabilities to quickly build store components that can be reused\nacross ecommerce stores and interact seamlessly with its APIs and existing components.\n\n### Overview \n\nThe Store builder allows you to extend existing blocks, like the ones provided by the Store Framework, allowing them to replace the blocks they extend via the VTEX IO Content Management System (CMS). They also allow you to build new blocks that provide functionality specific to your business needs and, then, create templates to insert those new blocks in your clients' ecommerce store while still benefiting from the continuous progress made by the native store components and it's extensions on the other parts of your store.\n\n### Blocks Language\n\nBlocks are instances of configured React components that follow a defined contract - or *interface*.\nBlocks can be shared between apps and can contain other blocks. They can be used to create simple widgets \nlike buttons and forms, ready to use features like a review system or whole web pages.\n\nTo create web pages - or *templates*, a block must be acessible by a **route**. Routes associate blocks with paths that \ncan be used to match URLS. These **templates** are configurable in VTEX IO CMS.\n\nApps can also insert its blocks on specific page components as soon as the app is installed, via **plugins**.\nPlugins provide an easy way to add specific functionality in a plug and play fashion to any store - \ne.g. Visa Checkout button on the shopping cart, 360º image on the product galery.\n\nTo ensure that blocks would be reusable across stores, any VTEX IO store contain a set of *interfaces* \nwhich blocks must implement. **Interfaces** are contracts that define the block component and which interfaces \nit may contain, among other constraints.\n\nThe store builder validates and exports blocks, routes, interfaces and plugins defined in the app.\nThis allows the admin CMS and the store to use them. The configuration files which declares those\ncomponents must be in the `store/` folder on the root of the app. \nThe following sections we detail more about this concepts. \n\n### Interface Structure\n[TODO]\nExplain interface structure, how it make stores \"compatible\" and its components reusable.\n\n### Recipes\n[TODO]\n\nHow to extend VTEX Store interfaces?\n\nHow to create a block / interface / route / plugin?\n\nExamples, examples, examples...\n\n## Blocks Reference\n\nPlease refer to [Blocks](./BLOCKS.md)\n\n## Pixel Architecture\n\n- Home: `homeView` event.\n\n- Product: `productView` event.\n\n- Department: `departmentView` event.\n\n- Category: `categoryPath` event.\n\n- Internal Site Search: `internalSiteSearchView` event.\n\n- OrderPlaced Page: `orderPlaced` event.\n\n- Other: `otherView` event.\n\n### Enhanced Ecommerce\n\n- Measuring Additions to a Shopping Cart: `addTocart` event.\n\n- Measuring Removals from a Shopping Cart: `removeFromCart` event.\n\n## Contributing\n\nCheck it out [how to contribute](https://github.com/vtex-apps/awesome-io#contributing) with this project. \n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\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/gustavopvasconcellos\"><img src=\"https://avatars1.githubusercontent.com/u/49173685?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>gustavopvasconcellos</b></sub></a><br /><a href=\"https://github.com/vtex-apps/store/commits?author=gustavopvasconcellos\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\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```"
}
] |
code_store_6f589318
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/StoreWrapper.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable react/jsx-filename-extension */\nimport React, { Fragment, useEffect, useMemo } from 'react'\nimport {\n canUseDOM,\n ExtensionPoint,\n Helmet,\n NoSSR,\n useRuntime,\n} from 'vtex.render-runtime'\nimport PropTypes from 'prop-types'\nimport { PixelProvider } from 'vtex.pixel-manager/PixelContext'\nimport { ToastProvider } from 'vtex.styleguide'\nimport { PWAProvider } from 'vtex.store-resources/PWAContext'\nimport { OrderQueueProvider } from 'vtex.order-manager/OrderQueue'\nimport { OrderItemsProvider } from 'vtex.order-items/OrderItems'\nimport { OrderFormProvider as OrderFormProviderCheckout } from 'vtex.order-manager/OrderForm'\nimport { ShippingOptionProvider } from 'vtex.shipping-option-components/ShippingOptionContext'\n\nimport UserDataPixel from './components/UserDataPixel'\nimport PageViewPixel from './components/PageViewPixel'\nimport OrderFormProvider from './components/OrderFormProvider'\nimport NetworkStatusToast from './components/NetworkStatusToast'\nimport WrapperContainer from './components/WrapperContainer'\nimport { normalizeNavigation } from './utils/navigation'\nimport { useCanonicalLink } from './hooks/useCanonicalLink'\nimport { VTEXAdsProvider } from './components/VTEXAdsProvider'\n\nconst APP_LOCATOR = 'vtex.store'\nconst CONTENT_TYPE = 'text/html; charset=utf-8'\nconst META_ROBOTS = 'index, follow'\nconst MOBILE_SCALING = 'width=device-width, initial-scale=1'\nconst CUSTOM_PAGE = 'store.custom'\n\nconst isSiteEditorIframe = () => {\n try {\n return (\n canUseDOM && window.top !== window.self && window.top.__provideRuntime\n )\n } catch {\n return false\n }\n}\n\nconst getCustomPagesOpenGraph = ({ title, description, url }) => {\n return [\n { property: 'og:type', content: 'website' },\n { property: 'og:title', content: title },\n { property: 'og:url', content: url },\n { property: 'og:description', content: description },\n ]\n}\n\nconst useFavicons = faviconLinks => {\n const { rootPath = '' } = useRuntime()\n if (!rootPath) {\n return faviconLinks\n }\n\n return (faviconLinks || []).map(favicon => {\n // Only fix if is relative path\n const { href } = favicon\n if (!href || href[0] !== '/') {\n return favicon\n }\n return { ...favicon, href: rootPath + href }\n })\n}\n\nconst StoreWrapper = ({ children, CustomContext }) => {\n const {\n amp,\n culture: { country, locale, currency },\n route,\n route: { metaTags, title: pageTitle, rootName },\n getSettings,\n rootPath = '',\n prefetchDefaultPages,\n addNavigationRouteModifier,\n } = useRuntime()\n\n const supportsServiceWorker = canUseDOM && 'serviceWorker' in navigator\n\n useEffect(() => {\n prefetchDefaultPages([\n 'store.custom',\n 'store.product',\n 'store.search',\n 'store.search#brand',\n 'store.search#category',\n 'store.search#configurable',\n 'store.search#custom',\n 'store.search#department',\n 'store.search#subcategory',\n 'store.search#subcategory-terms',\n ])\n }, [prefetchDefaultPages])\n\n useEffect(() => {\n addNavigationRouteModifier(normalizeNavigation)\n }, [addNavigationRouteModifier])\n\n const settings = getSettings(APP_LOCATOR) || {}\n const {\n titleTag,\n metaTagDescription,\n metaTagRobots,\n storeName,\n faviconLinks,\n enableOrderFormOptimization = false,\n enableServiceWorker = true,\n } = settings\n\n const description = (metaTags && metaTags.description) || metaTagDescription\n const title = pageTitle || titleTag\n const robots = (metaTags || {}).robots || metaTagRobots\n\n const [queryMatch] = route.path.match(/\\?.*/) || ['?']\n\n const canonicalLink = useCanonicalLink()\n\n const parsedFavicons = useFavicons(faviconLinks)\n\n const CustomContextElement = CustomContext || Fragment\n\n const isCustomPage = useMemo(() => rootName.includes(CUSTOM_PAGE), [rootName])\n\n const content = (\n <OrderQueueProvider>\n <OrderFormProviderCheckout>\n <OrderItemsProvider>\n <ShippingOptionProvider>\n <VTEXAdsProvider>\n <WrapperContainer className=\"vtex-store__template bg-base\">\n <CustomContextElement>{children}</CustomContextElement>\n </WrapperContainer>\n </VTEXAdsProvider>\n </ShippingOptionProvider>\n </OrderItemsProvider>\n </OrderFormProviderCheckout>\n </OrderQueueProvider>\n )\n return (\n <Fragment>\n <Helmet\n title={title}\n meta={[\n ...(isCustomPage\n ? getCustomPagesOpenGraph({\n title,\n description,\n url: canonicalLink,\n })\n : []),\n // viewport meta tag is already handled in render-server for AMP pages\n !amp && { name: 'viewport', content: MOBILE_SCALING },\n { name: 'description', content: description },\n { name: 'copyright', content: storeName },\n { name: 'author', content: storeName },\n { name: 'country', content: country },\n { name: 'language', content: locale },\n { name: 'currency', content: currency },\n { name: 'robots', content: robots || META_ROBOTS },\n { name: 'storefront', content: 'store_framework' },\n { httpEquiv: 'Content-Type', content: CONTENT_TYPE },\n ]\n .filter(Boolean)\n .filter(meta => meta.content && meta.content.length > 0)}\n script={[\n supportsServiceWorker && {\n type: 'text/javascript',\n src: `${rootPath}/register.js${queryMatch}${\n enableServiceWorker ? '' : '&__disableSW=true'\n }&scope=${encodeURIComponent(rootPath)}`,\n defer: true,\n },\n ].filter(Boolean)}\n link={[\n ...(parsedFavicons || []),\n ...(!amp && canonicalLink\n ? [\n /* {\n rel: 'amphtml',\n href: encodeURI(`${canonicalLink}?amp`),\n }, */\n {\n rel: 'canonical',\n href: encodeURI(canonicalLink),\n },\n ]\n : []),\n ].filter(Boolean)}\n />\n <PixelProvider currency={currency}>\n <PWAProvider rootPath={rootPath}>\n <PageViewPixel title={title} />\n <UserDataPixel />\n <ToastProvider positioning=\"window\">\n <NetworkStatusToast />\n {enableOrderFormOptimization ? (\n content\n ) : (\n /** This is necessary for backwards compatibility, since stores\n * might still need the OrderFormProvider from store-resources.\n * If a store does not have `enableOrderFormOptimization` enabled,\n * we should always add this provider.\n */\n <OrderFormProvider>{content}</OrderFormProvider>\n )}\n </ToastProvider>\n </PWAProvider>\n </PixelProvider>\n {isSiteEditorIframe() && (\n <NoSSR>\n <ExtensionPoint id=\"highlight-overlay\" />\n </NoSSR>\n )}\n </Fragment>\n )\n}\n\nStoreWrapper.propTypes = {\n children: PropTypes.element,\n CustomContext: PropTypes.any,\n}\n\nexport default StoreWrapper\n\n```"
}
] |
code_store_57efdfd6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/ProductWrapper.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { useMemo, Fragment } from 'react'\nimport {\n LoadingContextProvider,\n canUseDOM,\n useRuntime,\n} from 'vtex.render-runtime'\nimport { ProductOpenGraph } from 'vtex.open-graph'\nimport useProduct from 'vtex.product-context/useProduct'\nimport ProductContextProvider from 'vtex.product-context/ProductContextProvider'\nimport { Product as ProductStructuredData } from 'vtex.structured-data'\n\nimport WrapperContainer from './components/WrapperContainer'\nimport ProductTitleAndPixel from './components/ProductTitleAndPixel'\n\nconst Content = ({ listName, loading, children, childrenProps }) => {\n const { product, selectedItem } = useProduct()\n return (\n <Fragment>\n <ProductTitleAndPixel\n listName={listName}\n product={product}\n selectedItem={selectedItem}\n loading={loading}\n />\n {product && <ProductOpenGraph />}\n {product && selectedItem && (\n <ProductStructuredData product={product} selectedItem={selectedItem} />\n )}\n {React.cloneElement(children, childrenProps)}\n </Fragment>\n )\n}\n\nconst ProductWrapper = ({\n params: { slug, __listName: listName },\n productQuery,\n productQuery: { product, loading } = {},\n query,\n CustomContext,\n children,\n ...props\n}) => {\n const { getSettings } = useRuntime()\n const { enableFullSSROnProduct } = getSettings('vtex.store')\n const childrenProps = useMemo(\n () => ({\n productQuery,\n slug,\n ...props,\n }),\n [productQuery, slug, props]\n )\n\n const hasProductData = !!product\n\n const loadingValue = useMemo(\n () => ({\n isParentLoading: loading || !hasProductData,\n }),\n [loading, hasProductData]\n )\n\n const isSSRLoading =\n loadingValue.isParentLoading && enableFullSSROnProduct && !canUseDOM\n\n const CustomContextElement = CustomContext || Fragment\n\n return (\n <WrapperContainer className=\"vtex-product-context-provider\">\n <ProductContextProvider query={query} product={product}>\n <Content\n listName={listName}\n loading={loading}\n childrenProps={childrenProps}\n >\n <LoadingContextProvider value={loadingValue}>\n <CustomContextElement>\n {isSSRLoading ? <Fragment /> : children}\n </CustomContextElement>\n </LoadingContextProvider>\n </Content>\n </ProductContextProvider>\n </WrapperContainer>\n )\n}\n\nProductWrapper.propTypes = {\n params: PropTypes.object,\n productQuery: PropTypes.object,\n children: PropTypes.node,\n /* URL query params */\n query: PropTypes.object,\n CustomContext: PropTypes.any,\n}\n\nexport default ProductWrapper\n\n```"
}
] |
code_store_8ea1477f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/ProfileChallenge.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect, FC } from 'react'\nimport {\n useRuntime,\n canUseDOM,\n Loading,\n SessionResponse,\n Session,\n} from 'vtex.render-runtime'\n\nimport { getSession } from './modules/session'\n\nconst loginPath = '/login'\n\nconst getLocation = () =>\n canUseDOM\n ? {\n url:\n window.location.pathname +\n window.location.search +\n window.location.hash,\n pathName: window.location.pathname,\n }\n : {\n url: (global as any).__pathname__,\n pathName: (global as any).__pathname__,\n }\n\nconst useSessionResponse = () => {\n const [session, setSession] = useState<SessionResponse>()\n const sessionPromise = getSession()\n\n useEffect(() => {\n if (!sessionPromise) {\n return\n }\n\n sessionPromise.then(sessionResponse => {\n const response = sessionResponse.response as SessionResponse\n\n setSession(response)\n })\n }, [sessionPromise])\n\n return session\n}\n\nfunction hasSession(session: SessionResponse | undefined): session is Session {\n return (\n session !== undefined &&\n session.type !== 'Unauthorized' &&\n session.type !== 'Forbidden'\n )\n}\n\nconst useLoginRedirect = (isLoggedIn: boolean | null, page: string) => {\n const { rootPath = '' } = useRuntime()\n\n useEffect(() => {\n const { url, pathName } = getLocation()\n if (\n isLoggedIn === false &&\n page !== 'store.login' &&\n pathName !== loginPath &&\n canUseDOM\n ) {\n window.location.assign(\n `${rootPath}${loginPath}?returnUrl=${encodeURIComponent(url)}`\n )\n }\n }, [page, isLoggedIn, rootPath])\n}\n\ninterface Props {\n page: string\n}\n\nconst ProfileChallenge: FC<Props> = ({ children, page }) => {\n const session = useSessionResponse()\n const isLoggedIn = hasSession(session)\n ? session.namespaces?.profile?.isAuthenticated?.value === 'true'\n : null\n\n useLoginRedirect(isLoggedIn, page)\n\n // isLoggedIn null means that we still don't know, session is loading\n if (isLoggedIn === null) {\n return (\n <div className=\"flex justify-center ma4\">\n <Loading />\n </div>\n )\n }\n\n if (isLoggedIn === false) {\n return null\n }\n\n return <>{children}</>\n}\n\nexport default ProfileChallenge\n\n```"
}
] |
code_store_9b5d4ff8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/HomeWrapper.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport { useRuntime, canUseDOM } from 'vtex.render-runtime'\nimport SearchAction from 'vtex.structured-data/SearchAction'\nimport { HomeOpenGraph } from 'vtex.open-graph'\n\nimport useDataPixel from './hooks/useDataPixel'\n\nconst HomeWrapper = ({ children }) => {\n const { account, route, getSettings } = useRuntime()\n const { searchTermPath } = getSettings('vtex.store')\n\n const pixelEvents = useMemo(() => {\n if (!canUseDOM) {\n return null\n }\n\n return [\n {\n event: 'pageInfo',\n eventType: 'homeView',\n accountName: account,\n pageTitle: document.title,\n // eslint-disable-next-line no-restricted-globals\n pageUrl: location.href,\n pageCategory: 'Home',\n },\n ]\n }, [account])\n\n useDataPixel(pixelEvents, route.routeId)\n\n return (\n <Fragment>\n <SearchAction searchTermPath={searchTermPath} />\n <HomeOpenGraph />\n {children}\n </Fragment>\n )\n}\n\nHomeWrapper.propTypes = {\n children: PropTypes.element,\n}\n\nexport default HomeWrapper\n\n```"
}
] |
code_store_69a07f9e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/SearchWrapper.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n Fragment,\n useState,\n useMemo,\n useEffect,\n FC,\n ReactElement,\n ComponentType,\n} from 'react'\nimport {\n Helmet,\n useRuntime,\n LoadingContextProvider,\n canUseDOM,\n RuntimeWithRoute,\n StoreSettings,\n} from 'vtex.render-runtime'\nimport { SearchOpenGraph } from 'vtex.open-graph'\nimport { ProductList as ProductListStructuredData } from 'vtex.structured-data'\nimport queryString from 'query-string'\n\nimport { capitalize } from './modules/capitalize'\nimport useDataPixel from './hooks/useDataPixel'\nimport { usePageView } from './components/PageViewPixel'\nimport {\n getDepartmentMetadata,\n getCategoryMetadata,\n getSearchMetadata,\n} from './modules/searchMetadata'\nimport { SearchQuery } from './modules/searchTypes'\nimport { PixelEvent } from './typings/event'\nimport { useCanonicalLink } from './hooks/useCanonicalLink'\n\nconst APP_LOCATOR = 'vtex.store'\n\ninterface SearchRouteParams {\n term?: string\n department?: string\n category?: string\n}\n\nconst pageCategory = (products: unknown[], params: SearchRouteParams) => {\n if (!products || products.length === 0) {\n return 'EmptySearch'\n }\n const { category, term } = params\n return term ? 'InternalSiteSearch' : category ? 'Category' : 'Department'\n}\n\ntype PageEventName =\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n\nconst mapEvent = {\n InternalSiteSearch: 'internalSiteSearchView',\n Category: 'categoryView',\n Department: 'departmentView',\n EmptySearch: 'emptySearchView',\n}\nconst fallbackView = 'otherView'\n\nconst getPageEventName = (\n products: unknown[],\n params: SearchRouteParams\n): PageEventName => {\n if (!products) {\n return fallbackView as PageEventName\n }\n\n const category = pageCategory(products, params)\n\n return (mapEvent[category] || fallbackView) as PageEventName\n}\n\nconst getDecodeURIComponent = (encodedURIComponent: string) => {\n try {\n return decodeURIComponent(encodedURIComponent)\n } catch {\n return encodedURIComponent\n }\n}\n\ninterface GetTitleTagParams {\n titleTag: string\n storeTitle: string\n term?: string\n pageTitle?: string\n pageNumber?: number\n removeStoreNameTitle?: boolean\n}\n\nconst getTitleTag = ({\n titleTag,\n storeTitle,\n term,\n pageTitle,\n pageNumber = 0,\n removeStoreNameTitle,\n}: GetTitleTagParams) => {\n /*\n titleNumber and storeTitleFormatted depend on the value of enablePageNumberTitle and removeStoreNameTitle params,\n by default, the value of enablePageNumberTitle and removeStoreNameTitle is false, only if the value of these\n parameters is true, it will affect the value of titleNumber or storeTitleFormatted\n */\n const titleNumber = pageNumber > 0 ? ` #${pageNumber}` : ''\n const storeTitleFormatted = removeStoreNameTitle ? '' : ` - ${storeTitle}`\n\n if (titleTag) {\n return `${getDecodeURIComponent(\n titleTag\n )}${titleNumber}${storeTitleFormatted}`\n }\n\n if (pageTitle) {\n return `${getDecodeURIComponent(\n pageTitle\n )}${titleNumber}${storeTitleFormatted}`\n }\n\n if (term) {\n return `${capitalize(\n getDecodeURIComponent(term)\n )}${titleNumber}${storeTitleFormatted}`\n }\n\n return storeTitle\n}\n\nconst getSearchIdentifier = (\n searchQuery: SearchQuery,\n orderBy?: string,\n page?: string\n) => {\n const { variables } = searchQuery\n\n if (!variables) {\n return\n }\n const { query, map } = variables\n return query + map + (orderBy ?? '') + (page ?? '')\n}\n\ninterface GetSearchCanonicalParams {\n canonicalLink: string\n page?: number\n map?: string\n term?: string\n}\n\nfunction shouldNotIncludeMap(map?: string) {\n if (!map || map === 'b' || map === 'brand') {\n return true\n }\n\n const mapTree = map.split(',')\n\n if (mapTree.length > 4) {\n return false\n }\n\n return mapTree.every(mapItem => mapItem === 'c')\n}\n\nfunction getSearchCanonical({\n canonicalLink,\n page,\n map,\n term,\n}: GetSearchCanonicalParams) {\n if (page !== null && page !== undefined && page < 1) {\n return null\n }\n\n const query = {\n page: page !== undefined && page !== null && page > 1 ? page : undefined,\n map: shouldNotIncludeMap(map) ? undefined : map,\n _q: term,\n }\n\n const canonicalWithPage = queryString.stringifyUrl({\n url: decodeURI(canonicalLink),\n query,\n })\n\n return canonicalWithPage\n}\n\ninterface GetHelmetLinkParams {\n canonicalLink: string | null\n page: number\n map?: string\n term?: string\n rel: 'canonical' | 'prev' | 'next'\n}\n\nexport function getHelmetLink({\n canonicalLink,\n page,\n map,\n rel,\n term,\n}: GetHelmetLinkParams) {\n if (!canonicalLink) {\n return null\n }\n\n let pageAfterTransformation = 0\n\n if (rel === 'canonical') {\n pageAfterTransformation = page\n } else if (rel === 'next') {\n pageAfterTransformation = page + 1\n } else if (rel === 'prev') {\n pageAfterTransformation = page - 1\n }\n\n const canonicalWithParams = getSearchCanonical({\n canonicalLink,\n page: pageAfterTransformation,\n map,\n term,\n })\n\n if (!canonicalWithParams) {\n return null\n }\n\n return {\n rel,\n href: canonicalWithParams,\n }\n}\n\nfunction isNotLastPage(\n products: SearchQuery['products'],\n to: number | undefined,\n recordsFiltered: number | undefined\n) {\n if (\n !products ||\n to === undefined ||\n to === null ||\n recordsFiltered === undefined ||\n recordsFiltered === null\n ) {\n return null\n }\n\n return to + 1 < recordsFiltered\n}\n\ninterface AppliedFilters {\n name: string\n}\n\ninterface SearchPageInfoEvent {\n department?: DepartmentMetadata | null\n category?: CategoryMetadata | null\n search?: SearchMetadata | null\n orderBy?: string\n page?: string\n appliedFilters?: AppliedFilters[]\n}\n\ninterface DepartmentMetadata {\n id: string\n name: string\n}\n\ninterface CategoryMetadata {\n id: string\n name: string\n}\n\ninterface SearchMetadata {\n term?: string\n category: CategoryMetadata | null\n results: number\n}\n\ninterface SearchWrapperProps {\n children: ReactElement\n params: SearchRouteParams\n searchQuery: SearchQuery\n orderBy?: string\n to?: number\n page?: number\n maxItemsPerPage?: number\n CustomContext?: ComponentType\n facetsLoading?: boolean\n}\n\nconst SearchWrapper: FC<SearchWrapperProps> = props => {\n const {\n params,\n orderBy,\n searchQuery,\n facetsLoading,\n searchQuery: {\n variables: { map } = {},\n data: {\n searchMetadata: { titleTag = '', metaTagDescription = '' } = {},\n productSearch: { recordsFiltered = undefined } = {},\n } = {},\n } = {},\n CustomContext,\n page: pageFromQuery = 0,\n to,\n maxItemsPerPage,\n children,\n } = props\n const {\n account,\n getSettings,\n query: { page, _q: termFromQuery },\n route: { title: pageTitle, metaTags },\n } = useRuntime() as RuntimeWithRoute\n\n const settings = getSettings(APP_LOCATOR) || ({} as StoreSettings)\n const loading = searchQuery ? searchQuery.loading : undefined\n const {\n titleTag: defaultStoreTitle,\n storeName,\n enablePageNumberTitle = false,\n canonicalWithoutUrlParams = false,\n removeStoreNameTitle = false,\n } = settings\n\n const title = getTitleTag({\n titleTag,\n storeTitle: storeName || defaultStoreTitle,\n term: params.term,\n pageTitle,\n pageNumber: enablePageNumberTitle ? Number(page) : 0,\n removeStoreNameTitle,\n })\n\n const canonicalLink = useCanonicalLink()\n\n const helmetCanonicalLink = getHelmetLink({\n canonicalLink,\n page: pageFromQuery,\n map: canonicalWithoutUrlParams ? '' : map,\n term: termFromQuery,\n rel: 'canonical',\n })\n\n const openGraphParams = {\n title,\n description: metaTagDescription || metaTags?.description,\n canonical: helmetCanonicalLink?.href,\n }\n\n const pixelEvents = useMemo(() => {\n if (\n !searchQuery ||\n !canUseDOM ||\n !searchQuery.products ||\n !searchQuery.data?.facets?.queryArgs ||\n facetsLoading\n ) {\n return null\n }\n\n const { products } = searchQuery\n\n const event = getPageEventName(products, params)\n const pageInfoEvent: SearchPageInfoEvent & PixelEvent = {\n event: 'pageInfo',\n eventType: event,\n accountName: account,\n pageTitle: title,\n pageUrl: window.location.href,\n orderBy,\n appliedFilters: map?.split(',').map(name => ({ name })),\n page,\n category: searchQuery?.data\n ? getCategoryMetadata(searchQuery.data)\n : null,\n department: searchQuery?.data\n ? getDepartmentMetadata(searchQuery.data)\n : null,\n search: searchQuery?.data\n ? getSearchMetadata(searchQuery.data, pageFromQuery, maxItemsPerPage)\n : null,\n }\n\n return [\n pageInfoEvent,\n {\n event,\n products,\n },\n ]\n }, [\n searchQuery,\n facetsLoading,\n params,\n account,\n title,\n orderBy,\n map,\n page,\n pageFromQuery,\n maxItemsPerPage,\n ])\n\n const [hasLoaded, setHasLoaded] = useState(true)\n\n const loadingValue = useMemo(\n () => ({\n isParentLoading: loading && hasLoaded,\n }),\n [loading, hasLoaded]\n )\n\n const pixelCacheKey = getSearchIdentifier(searchQuery, orderBy, page)\n usePageView({ title, cacheKey: pixelCacheKey })\n useDataPixel(pixelEvents, pixelCacheKey, loading)\n\n /** Prevents the loader from showing up after initial data is loaded,\n * e.g. when setQuery changes the query variables */\n useEffect(() => {\n if (!loading) {\n setHasLoaded(false)\n }\n }, [loading])\n\n const CustomContextElement = CustomContext ?? Fragment\n return (\n <Fragment>\n <Helmet\n title={title}\n meta={[\n params.term && {\n name: 'robots',\n content: 'noindex,follow',\n },\n metaTagDescription && {\n name: 'description',\n content: metaTagDescription,\n },\n ].filter(Boolean)}\n link={[\n helmetCanonicalLink,\n getHelmetLink({\n canonicalLink,\n page: pageFromQuery,\n map,\n rel: 'prev',\n }),\n isNotLastPage(searchQuery.products, to, recordsFiltered)\n ? getHelmetLink({\n canonicalLink,\n page: pageFromQuery,\n map,\n rel: 'next',\n })\n : null,\n ].filter(Boolean)}\n />\n\n <ProductListStructuredData products={searchQuery.products} />\n <SearchOpenGraph meta={openGraphParams} />\n <LoadingContextProvider value={loadingValue}>\n <CustomContextElement>\n {React.cloneElement(children, props)}\n </CustomContextElement>\n </LoadingContextProvider>\n </Fragment>\n )\n}\n\nexport default SearchWrapper\n\n```"
}
] |
code_store_b4e2055b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/cacheLocator.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { buildCacheLocator } from 'vtex.render-runtime'\n\nconst SEARCH_GRAPHQL = 'vtex.search-graphql@0.x'\n\nexport const cacheLocator = {\n product: slug => buildCacheLocator(SEARCH_GRAPHQL, 'Product', slug),\n}\n\n```"
}
] |
code_store_2a2834bd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/ContentPageContext.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n// This context simplifies the check for content pages\nconst ContentPageContext = ({ children }) => children\n\nexport default ContentPageContext\n\n```"
}
] |
code_store_fc577866
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/ProductContext.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable no-restricted-imports */\nimport PropTypes from 'prop-types'\nimport React, { useEffect, useMemo } from 'react'\nimport { withApollo, graphql, compose } from 'react-apollo'\nimport { isEmpty } from 'ramda'\nimport { useRuntime } from 'vtex.render-runtime'\nimport product from 'vtex.store-resources/QueryProduct'\nimport productPreviewFragment from 'vtex.store-resources/QueryProductPreviewFragment'\nimport productBenefits from 'vtex.store-resources/QueryProductBenefits'\nimport productCategoryTree from 'vtex.store-resources/QueryUNSTABLEProductCategoryTree'\n\nimport { cacheLocator } from './cacheLocator'\n\nconst EMPTY_OBJECT = {}\n\nconst emptyOrNull = value => (value != null ? isEmpty(value) : true)\n\nconst getInfoFromQuery = (queryObj = {}) => {\n const { product: productFromQuery, loading = true } = queryObj\n return !loading && productFromQuery ? productFromQuery : EMPTY_OBJECT\n}\n\nconst useProduct = ({\n catalog,\n productBenefits: productBenefitsQueryResult,\n categoryTree,\n}) => {\n const catalogInfo = getInfoFromQuery(catalog)\n const benefitsInfo = getInfoFromQuery(productBenefitsQueryResult)\n const categoryTeeInfo = getInfoFromQuery(categoryTree)\n\n return useMemo(() => {\n const allEmpty = [catalogInfo, benefitsInfo, categoryTeeInfo].every(\n emptyOrNull\n )\n return allEmpty\n ? null\n : { ...catalogInfo, ...benefitsInfo, ...categoryTeeInfo }\n }, [benefitsInfo, catalogInfo, categoryTeeInfo])\n}\n\nfunction getLoading(props) {\n const { catalog: { loading: catalogLoading = true } = {} } = props\n return catalogLoading\n}\n\nfunction useNotFound(loading, propsProduct, slug) {\n const { navigate } = useRuntime()\n\n useEffect(() => {\n if (!propsProduct && !loading) {\n navigate({\n page: 'store.search',\n params: { term: slug },\n query: `productLinkNotFound=${slug}`,\n })\n }\n }, [loading, propsProduct, navigate, slug])\n}\n\nconst ProductContext = _props => {\n const {\n params,\n params: { slug },\n client,\n catalog: { refetch },\n ...props\n } = _props\n\n const loading = getLoading(_props)\n const propsProduct = useProduct(_props)\n\n useNotFound(loading, propsProduct, slug)\n\n const productPreview = client.readFragment({\n id: cacheLocator.product(slug),\n fragment: productPreviewFragment,\n })\n\n const productToQueryFor =\n propsProduct ||\n (productPreview && productPreview.items ? productPreview : null)\n\n const productQuery = useMemo(\n () => ({\n loading,\n product: productToQueryFor,\n refetch,\n error:\n !productToQueryFor && !loading\n ? {\n message: 'Product not found!',\n }\n : null,\n }),\n [loading, productToQueryFor, refetch]\n )\n\n const childrenProps = useMemo(\n () => ({\n productQuery,\n slug,\n params,\n }),\n [productQuery, slug, params]\n )\n\n return React.cloneElement(props.children, childrenProps)\n}\n\nProductContext.propTypes = {\n params: PropTypes.object,\n query: PropTypes.shape({\n skuId: PropTypes.string,\n }),\n data: PropTypes.object,\n children: PropTypes.node,\n client: PropTypes.object,\n catalog: PropTypes.object,\n productBenefits: PropTypes.object,\n}\n\nconst catalogOptions = {\n name: 'catalog',\n options: props => ({\n variables: {\n slug: props.params.slug,\n skipCategoryTree: true,\n identifier: {\n field: 'id',\n value: props.params.id || '',\n },\n },\n errorPolicy: 'all',\n }),\n}\n\nconst productBenefitsOptions = {\n name: 'productBenefits',\n options: props => ({\n variables: {\n slug: props.params.slug,\n identifier: {\n field: 'id',\n value: props.params.id || '',\n },\n },\n errorPolicy: 'all',\n ssr: false,\n }),\n}\n\nconst categoryTreeOptions = {\n name: 'categoryTree',\n options: props => ({\n variables: {\n slug: props.params.slug,\n identifier: {\n field: 'id',\n value: props.params.id || '',\n },\n },\n errorPolicy: 'all',\n ssr: false,\n }),\n}\n\nexport default compose(\n withApollo,\n graphql(product, catalogOptions),\n graphql(productBenefits, productBenefitsOptions),\n graphql(productCategoryTree, categoryTreeOptions)\n)(ProductContext)\n\n```"
}
] |
code_store_948e9638
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/package.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"private\": true,\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"eslint --ext js,jsx,ts,tsx .\"\n },\n \"dependencies\": {\n \"@vtex/ads-react\": \"0.3.1\",\n \"hoist-non-react-statics\": \"^3.0.1\",\n \"prop-types\": \"^15.5.10\",\n \"query-string\": \"^7.0.1\",\n \"ramda\": \"^0.26.1\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.4\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/ramda\": \"^0.26.21\",\n \"@vtex/test-tools\": \"^3.4.3\",\n \"@vtex/tsconfig\": \"^0.3.0\",\n \"apollo-client-preset\": \"^1.0.8\",\n \"graphql\": \"^0.13.0\",\n \"graphql-tag\": \"^2.7.3\",\n \"prettier\": \"^1.19.1\",\n \"react\": \"^16.2.0\",\n \"react-apollo\": \"^3.1.5\",\n \"react-dom\": \"^16.2.0\",\n \"react-intl\": \"3.9.1\",\n \"typescript\": \"3.9.7\",\n \"vtex.blog-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.blog-interfaces@0.0.6/public/@types/vtex.blog-interfaces\",\n \"vtex.login\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.login@2.28.0/public/_types/react\",\n \"vtex.my-account\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.my-account@1.13.2/public/@types/vtex.my-account\",\n \"vtex.open-graph\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.open-graph@1.0.5/public/@types/vtex.open-graph\",\n \"vtex.order-items\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.7.0/public/@types/vtex.order-items\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.8.4/public/@types/vtex.order-manager\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.1.4/public/@types/vtex.pixel-manager\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.7.1/public/@types/vtex.product-context\",\n \"vtex.product-review-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-review-interfaces@1.0.2/public/_types/react\",\n \"vtex.product-specification-badges\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-specification-badges@0.1.1/public/@types/vtex.product-specification-badges\",\n \"vtex.pwa-components\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pwa-components@0.4.1/public/@types/vtex.pwa-components\",\n \"vtex.pwa-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pwa-graphql@1.15.1/public/@types/vtex.pwa-graphql\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.99.0/public/@types/vtex.render-runtime\",\n \"vtex.rich-text\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rich-text@0.9.0/public/@types/vtex.rich-text\",\n \"vtex.search-result\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-result@3.55.1/public/_types/react\",\n \"vtex.store-footer\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-footer@2.20.1/public/@types/vtex.store-footer\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.120.0/public/@types/vtex.store-graphql\",\n \"vtex.store-header\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-header@2.25.5/public/_types/react\",\n \"vtex.store-indexer\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-indexer@0.12.0/public/_types/react\",\n \"vtex.store-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.55.0/public/_types/react\",\n \"vtex.structured-data\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.structured-data@0.3.2/public/@types/vtex.structured-data\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.113.0/public/@types/vtex.styleguide\",\n \"vtex.telemarketing\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.telemarketing@2.10.1/public/@types/vtex.telemarketing\"\n },\n \"resolutions\": {\n \"json-schema\": \"^0.4.0\",\n \"jsdom\": \"^16.5.0\",\n \"jest-environment-jsdom\": \"^26.0.0\",\n \"node-notifier\": \"^8.0.1\"\n },\n \"version\": \"2.145.0\"\n}\n\n```"
}
] |
code_store_74383bd0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/Fold.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nconst Fold = () => <React.Fragment />\n\nexport default Fold\n\n```"
}
] |
code_store_06e4858a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/DefaultChallenge.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst DefaultChallenge = ({ children }) => {\n return children\n}\n\nexport default DefaultChallenge\n\n```"
}
] |
code_store_a867a551
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/SearchContext.jsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable no-restricted-imports */\nimport PropTypes from 'prop-types'\nimport { path } from 'ramda'\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\nimport SearchQuery from 'vtex.search-result/SearchQuery'\n\nimport { initializeMap, SORT_OPTIONS } from './modules/search'\nimport { VTEXAdsProvider } from './components/VTEXAdsProvider'\n\nconst DEFAULT_MAX_ITEMS_PER_PAGE = 10\n\nconst trimStartingSlash = value => value && value.replace(/^\\//, '')\n\nconst SearchContext = props => {\n const {\n nextTreePath,\n params,\n maxItemsPerPage = DEFAULT_MAX_ITEMS_PER_PAGE,\n queryField,\n mapField,\n orderByField,\n hideUnavailableItems,\n facetsBehavior = 'Static',\n __unstableCategoryTreeBehavior = 'default',\n skusFilter,\n simulationBehavior,\n installmentCriteria,\n excludedPaymentSystems,\n includedPaymentSystems,\n sponsoredProductsBehavior = 'sync',\n query: {\n order: orderBy = orderByField || SORT_OPTIONS[0].value,\n page: pageQuery,\n map: mapQuery,\n priceRange,\n // backwards-compatibility\n rest,\n fuzzy,\n operator,\n searchState,\n },\n children,\n __unstableProductOriginVtex,\n } = props\n\n const {\n page: runtimePage,\n query: runtimeQuery,\n route: {\n queryString: { map: renderMap },\n },\n } = useRuntime()\n\n const fieldsFromQueryString = {\n mapField: runtimeQuery.map,\n queryField: trimStartingSlash(runtimeQuery.query),\n }\n\n const areFieldsFromQueryStringValid = !!(\n fieldsFromQueryString.mapField && fieldsFromQueryString.queryField\n )\n\n const map = areFieldsFromQueryStringValid\n ? fieldsFromQueryString.mapField\n : renderMap || mapQuery || initializeMap(params)\n\n // Remove params which don't compose a search path\n const { id, ...searchParams } = params\n const query = Object.values(searchParams)\n .filter(term => term && term.length > 0)\n .join('/')\n .replace(/\\/\\//g, '/') // This cleans some bad cases of two // on some terms.\n\n const getCorrectQueryValue = () => {\n let queryValue = query\n\n // Checks if this is on the format of preventRouteChange and get the correct data\n if (areFieldsFromQueryStringValid) {\n queryValue = fieldsFromQueryString.queryField\n }\n\n // Normal query format, without preventRouteChange\n else if (queryField) {\n queryValue = queryField\n }\n\n // Legacy search\n else if (rest && rest.length > 0) {\n queryValue = `${query}/${rest.replace(',', '/')}`\n }\n\n try {\n return decodeURI(queryValue)\n } catch {\n return queryValue\n }\n }\n\n const queryValue = getCorrectQueryValue()\n const mapValue = queryField ? mapField : map\n const state =\n (typeof sessionStorage !== 'undefined' &&\n sessionStorage.getItem('searchState')) ||\n searchState\n\n return (\n <VTEXAdsProvider>\n <SearchQuery\n maxItemsPerPage={maxItemsPerPage}\n query={queryValue}\n map={mapValue}\n orderBy={orderBy}\n priceRange={priceRange}\n hideUnavailableItems={hideUnavailableItems}\n facetsBehavior={facetsBehavior}\n categoryTreeBehavior={__unstableCategoryTreeBehavior}\n pageQuery={pageQuery}\n skusFilter={skusFilter}\n simulationBehavior={simulationBehavior}\n installmentCriteria={installmentCriteria}\n excludedPaymentSystems={excludedPaymentSystems}\n includedPaymentSystems={includedPaymentSystems}\n operator={operator}\n fuzzy={fuzzy}\n searchState={state}\n __unstableProductOriginVtex={__unstableProductOriginVtex}\n sponsoredProductsBehavior={sponsoredProductsBehavior}\n >\n {(searchQuery, extraParams) => {\n return React.cloneElement(children, {\n searchQuery: {\n ...searchQuery,\n // backwards-compatibility\n data: {\n ...(searchQuery.data || {}),\n products: path(\n ['data', 'productSearch', 'products'],\n searchQuery\n ),\n },\n facets: path(['data', 'facets'], searchQuery),\n products: path(\n ['data', 'productSearch', 'products'],\n searchQuery\n ),\n recordsFiltered: path(\n ['data', 'productSearch', 'recordsFiltered'],\n searchQuery\n ),\n },\n searchContext: runtimePage,\n pagesPath: nextTreePath,\n map,\n orderBy,\n priceRange,\n page: extraParams.page,\n from: extraParams.from,\n to: extraParams.to,\n facetsLoading: extraParams.facetsLoading,\n maxItemsPerPage,\n // backwards-compatibility\n rest,\n lazyItemsRemaining: extraParams.lazyItemsRemaining,\n })\n }}\n </SearchQuery>\n </VTEXAdsProvider>\n )\n}\n\nSearchContext.propTypes = {\n /** Route parameters */\n params: PropTypes.shape({\n category: PropTypes.string,\n department: PropTypes.string,\n term: PropTypes.string,\n id: PropTypes.string,\n }),\n /** Query params */\n query: PropTypes.shape({\n map: PropTypes.string,\n page: PropTypes.string,\n order: PropTypes.oneOf(SORT_OPTIONS.map(o => o.value)),\n priceRange: PropTypes.string,\n rest: PropTypes.any,\n operator: PropTypes.string,\n fuzzy: PropTypes.string,\n searchState: PropTypes.string,\n }),\n /** Custom query `query` param */\n queryField: PropTypes.string,\n /** Custom query `map` param */\n mapField: PropTypes.string,\n /** Custom query `orderBy` param */\n orderByField: PropTypes.string,\n /** Current extension point name */\n nextTreePath: PropTypes.string,\n /** Component to be rendered */\n children: PropTypes.node.isRequired,\n /** Max items to show per result page */\n maxItemsPerPage: PropTypes.number,\n hideUnavailableItems: PropTypes.bool,\n facetsBehavior: PropTypes.string,\n __unstableCategoryTreeBehavior: PropTypes.string,\n skusFilter: PropTypes.string,\n simulationBehavior: PropTypes.string,\n installmentCriteria: PropTypes.string,\n excludedPaymentSystems: PropTypes.string,\n includedPaymentSystems: PropTypes.string,\n __unstableProductOriginVtex: PropTypes.bool,\n sponsoredProductsBehavior: PropTypes.string,\n}\n\nSearchContext.schema = {\n title: 'admin/editor.product-search.title',\n type: 'object',\n properties: {\n maxItemsPerPage: {\n title: 'admin/editor.product-search.maxItemsPerPage',\n type: 'number',\n },\n queryField: {\n title: 'Query',\n type: 'string',\n },\n mapField: {\n title: 'Map',\n type: 'string',\n },\n orderByField: {\n title: 'Order by field',\n type: 'string',\n default: SORT_OPTIONS[0].value,\n enum: SORT_OPTIONS.map(opt => opt.value),\n enumNames: SORT_OPTIONS.map(opt => opt.label),\n },\n hideUnavailableItems: {\n title: 'admin/editor.product-search.hideUnavailableItems',\n type: 'boolean',\n default: false,\n },\n sponsoredProductsBehavior: {\n title: 'Sponsored products behavior',\n type: 'string',\n default: 'sync',\n },\n },\n}\n\nexport default SearchContext\n\n```"
}
] |
code_store_98236372
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/store/contentSchemas.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"definitions\": {\n \"StoreSettings\": {\n \"title\": \"VTEX Store\",\n \"type\": \"object\",\n \"properties\": {\n \"storeName\": {\n \"title\": \"Store Name\",\n \"type\": \"string\"\n },\n \"requiresAuthorization\": {\n \"title\": \"Enables B2B behavior\",\n \"type\": \"boolean\"\n },\n \"titleTag\": {\n \"title\": \"Default title tag\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\"\n },\n \"metaTagDescription\": {\n \"title\": \"Meta description tag\",\n \"$ref\": \"app:vtex.native-types#/definitions/text\"\n },\n \"metaTagRobots\": {\n \"title\": \"Meta robots tag\",\n \"type\": \"string\",\n \"description\": \"Default value: index, follow\"\n },\n \"faviconLinks\": {\n \"title\": \"Favicons\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"rel\": {\n \"title\": \"Favicon Relationship\",\n \"type\": \"string\",\n \"description\": \"This favicon relationship, e.g: 'icon', 'shortcut icon', 'apple-touch-icon'\"\n },\n \"type\": {\n \"title\": \"Favicon Media Type\",\n \"type\": \"string\",\n \"description\": \"(Optional) Favicon type, e.g: image/png\"\n },\n \"sizes\": {\n \"title\": \"Favicon Size\",\n \"type\": \"string\",\n \"pattern\": \"^[0-9]+x[0-9]+$\",\n \"description\": \"(Optional) Favicon size, format: {width}x{height} e.g: 180x180\"\n },\n \"href\": {\n \"title\": \"Favicon href\",\n \"type\": \"string\"\n }\n },\n \"required\": [\"rel\", \"href\"]\n },\n \"description\": \"Configure your store's favicons\"\n },\n \"searchTermPath\": {\n \"title\": \"Search Term Path\",\n \"type\": \"string\",\n \"description\": \"Indicate the search path of your store\"\n },\n \"advancedSettings\": {\n \"title\": \"Advanced Store settings\",\n \"type\": \"object\",\n \"properties\": {\n \"enableOrderFormOptimization\": {\n \"title\": \"Enable orderForm optimization\",\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"This setting disables the legacy orderForm provider. More at: https://vtex.io/docs/recipes/store-management/enabling-order-form-optimization.\"\n },\n \"fetchSponsoredProductsOnSearch\": {\n \"title\": \"[BETA] Fetch sponsored products in search results\",\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"If this store's account has configured VTEX Ads, this option enables the fetching of sponsored products within search results.\"\n },\n \"a11ySemanticHtmlMigration\": {\n \"title\": \"Enable accessibility semantic HTML migration\",\n \"type\": \"boolean\",\n \"default\": false,\n \"description\": \"Enables semantic HTML improvements for accessibility that may introduce breaking changes. Components will use proper HTML elements like <label>, <main>, <nav> etc.\"\n },\n \"publisherId\": {\n \"title\": \"VTEX Ads Publisher ID\",\n \"type\": \"string\",\n \"default\": \"\",\n \"description\": \"Publisher ID used by VTEX Ads to identify your store. It is used to display ads on your store.\"\n }\n }\n },\n \"enablePageNumberTitle\": {\n \"title\": \"Enable page number in meta title\",\n \"type\": \"boolean\",\n \"description\": \"Add a #{Number} to the end of the title to avoid the title duplication issue.\"\n },\n \"canonicalWithoutUrlParams\": {\n \"title\": \"Canonical url without url params\",\n \"type\": \"boolean\",\n \"description\": \"Remove map parameter from canonical url. May cause issues when going to a page with facets selected. Test with caution after turning it on.\"\n },\n \"removeStoreNameTitle\": {\n \"title\": \"Remove store name from title\",\n \"type\": \"boolean\",\n \"description\": \"Remove store name at the end of Product and Category meta titles.\"\n }\n }\n }\n }\n}\n\n```"
}
] |
code_store_76e3be29
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/store/blocks.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.search#brand\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#department\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#category\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#subcategory\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#subcategory-terms\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#custom\": {\n \"blocks\": [\"search-result\"]\n },\n \"store.search#configurable\": {\n \"blocks\": [\"search-result\"]\n },\n \"rich-text#not-found\": {\n \"props\": {\n \"textAlignment\": \"CENTER\",\n \"textPosition\": \"CENTER\",\n \"text\": \"**PAGE NOT FOUND**\",\n \"font\": \"t-heading-1\"\n }\n },\n \"store.not-found#product\": {\n \"blocks\": [\"rich-text#not-found\"]\n },\n \"store.not-found#search\": {\n \"blocks\": [\"rich-text#not-found\"]\n },\n \"store.custom\": {\n \"parent\": {\n \"header\": \"header.full\"\n }\n },\n \"store.offline\": {\n \"blocks\": [\"offline-warning\"]\n }\n}\n\n```"
}
] |
code_store_b198f63f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/store/interfaces.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store\": {\n \"allowConditions\": true,\n \"component\": \"*\",\n \"around\": [\"storeWrapper\", \"challenge\"],\n \"before\": [\"header.full\"],\n \"after\": [\"footer\", \"pixels\"],\n \"preview\": {\n \"type\": \"transparent\",\n \"height\": 600\n }\n },\n \"store.home\": {\n \"around\": [\"homeWrapper\"],\n \"preview\": {\n \"type\": \"box\",\n \"height\": 1400\n }\n },\n \"store.product\": {\n \"around\": [\"productWrapper\"],\n \"before\": [\"header.full\"],\n \"context\": \"ProductContext\",\n \"preview\": {\n \"type\": \"box\",\n \"height\": 800\n }\n },\n \"store.search\": {\n \"around\": [\"searchWrapper\"],\n \"context\": \"SearchContext\",\n \"preview\": {\n \"type\": \"grid\",\n \"height\": 1400\n }\n },\n \"store.account\": {\n \"required\": [\"my-account\"],\n \"around\": [\"challenge.profile\"],\n \"preview\": {\n \"type\": \"text\",\n \"height\": 800\n }\n },\n \"store.login\": {\n \"required\": [\"vtex.login:login-content\"],\n \"preview\": {\n \"type\": \"spinner\",\n \"height\": 600\n }\n },\n \"store.orderplaced\": {\n \"preview\": {\n \"type\": \"spinner\",\n \"height\": 600\n }\n },\n \"store.product-review-form\": {\n \"preview\": {\n \"type\": \"spinner\",\n \"height\": 800\n }\n },\n \"store.blog-home\": {\n \"before\": [\"header.full\"]\n },\n \"store.blog-category\": {\n \"before\": [\"header.full\"],\n \"required\": [\"blog-category-list\"]\n },\n \"store.blog-post\": {\n \"before\": [\"header.full\"],\n \"required\": [\"blog-post-details\"]\n },\n \"store.blog-search-result\": {\n \"before\": [\"header.full\"],\n \"required\": [\"blog-search-list\"]\n },\n \"store.not-found\": {\n \"preview\": {\n \"type\": \"box\",\n \"height\": 800\n }\n },\n \"storeWrapper\": {\n \"allowed\": [\"highlight-overlay\"],\n \"component\": \"StoreWrapper\"\n },\n \"homeWrapper\": {\n \"component\": \"HomeWrapper\"\n },\n \"productWrapper\": {\n \"component\": \"ProductWrapper\"\n },\n \"searchWrapper\": {\n \"component\": \"SearchWrapper\"\n },\n \"challenge\": {\n \"component\": \"DefaultChallenge\",\n \"extensible\": \"public\"\n },\n \"highlight-overlay\": {\n \"component\": \"*\",\n \"extensible\": \"vtex\"\n },\n \"challenge.profile\": {\n \"component\": \"ProfileChallenge\"\n },\n \"promo-bar\": {\n \"component\": \"*\"\n },\n \"store.custom\": {},\n \"store.content\": {\n \"context\": \"ContentPageContext\"\n },\n \"store.offline\": {\n \"required\": [\"offline-warning\"]\n },\n \"__fold__\": {\n \"component\": \"Fold\"\n },\n \"__fold__.mobile\": {},\n \"__fold__.desktop\": {},\n \"__fold__.experimentalLazyImages\": {},\n \"__fold__.experimentalLazyAssets\": {}\n}\n\n```"
}
] |
code_store_18399241
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/store/routes.json from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store.home\": {\n \"path\": \"/\"\n },\n \"store.account\": {\n \"path\": \"/account\"\n },\n \"store.login\": {\n \"path\": \"/login\"\n },\n \"store.product\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/product/:id/:slug/p\",\n \"canonical\": \"/:slug/p\",\n \"contentType\": \"product\"\n },\n \"store.search\": {\n \"path\": \"/:term/s\",\n \"canonical\": \"/:term\",\n \"contentType\": \"search\"\n },\n \"store.search#brand\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/brand/:id/:brand(/*terms)\",\n \"canonical\": \"/:brand\",\n \"map\": [\"b\"],\n \"contentType\": \"brand\"\n },\n \"store.search#department\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/department/:id/:department(/*terms)\",\n \"canonical\": \"/:department\",\n \"map\": [\"c\"],\n \"contentType\": \"department\"\n },\n \"store.search#category\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/category/:id/:department/:category(/*terms)\",\n \"canonical\": \"/:department/:category\",\n \"map\": [\"c\", \"c\"],\n \"contentType\": \"category\"\n },\n \"store.search#subcategory\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/subcategory/:id/:department/:category/:subcategory(/*terms)\",\n \"canonical\": \"/:department/:category/:subcategory\",\n \"map\": [\"c\", \"c\", \"c\"],\n \"contentType\": \"subcategory\"\n },\n \"store.search#configurable\": {\n \"path\": \"/s/*terms\"\n },\n \"store.orderplaced\": {\n \"path\": \"/checkout/orderPlaced\"\n },\n \"store.offline\": {\n \"path\": \"/_v/offline\"\n },\n \"store.custom\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/userRoute/:id(/*terms)\",\n \"contentType\": \"userRoute\",\n \"canonical\": \"/*terms\"\n },\n \"store.not-found#product\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/notFoundProduct/:id/:slug/p\",\n \"canonical\": \"/:slug/p\",\n \"contentType\": \"notFoundProduct\"\n },\n \"store.not-found#search\": {\n \"path\": \"/_v/segment/routing/vtex.store@2.x/notFoundSearch/:id/*terms\",\n \"canonical\": \"/*terms\",\n \"contentType\": \"notFoundSearch\"\n }\n}\n\n```"
}
] |
code_store_efac5b55
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/images/SearchIcon.jsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React from 'react'\n\nconst SearchIcon = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 16 16\"\n width=\"18\"\n height=\"18\"\n >\n <path\n d=\"M12.7,11.3c0.9-1.2,1.4-2.6,1.4-4.2C14.1,3.2,11,0,7.1,0S0,3.2,0,7.1c0,3.9,3.2,7.1,7.1,7.1 c1.6,0,3.1-0.5,4.2-1.4l3,3c0.2,0.2,0.5,0.3,0.7,0.3s0.5-0.1,0.7-0.3c0.4-0.4,0.4-1,0-1.4L12.7,11.3z M7.1,12.1 C4.3,12.1,2,9.9,2,7.1S4.3,2,7.1,2s5.1,2.3,5.1,5.1S9.9,12.1,7.1,12.1z\"\n className=\"nc-icon-wrapper\"\n fill=\"#368df7\"\n />\n </svg>\n)\n\nexport default SearchIcon\n\n```"
}
] |
code_store_070ed079
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/images/VTEXIcon.jsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React from 'react'\n\nconst VTEXIcon = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 1566 800\"\n width=\"100\"\n height=\"50\"\n >\n <g className=\"nc-icon-wrapper\" fill=\"#FFF\">\n <path d=\"M657.59 186.14h-374c-29 0-47.57 30.83-34 56.46L287 313.44h-67.82A24.94 24.94 0 0 0 197.12 350l120.33 227.75a24.94 24.94 0 0 0 44.08 0l32.68-61.52 41 77.62c14.43 27.3 53.52 27.35 68 .08l187.46-352.76c13.25-24.95-4.83-55.03-33.08-55.03zm-168 150.72L408.76 489a16.6 16.6 0 0 1-29.33 0l-80.05-151.5A16.6 16.6 0 0 1 314 313.13h161.33a16.15 16.15 0 0 1 14.26 23.73z\" />\n <path d=\"M1055.39 349.79h-40.91V490a4.83 4.83 0 0 1-4.82 4.82h-31.55a4.83 4.83 0 0 1-4.82-4.82V349.79h-41.15a4.63 4.63 0 0 1-4.82-4.58v-24.8a4.63 4.63 0 0 1 4.82-4.58h123.24a4.84 4.84 0 0 1 5.06 4.58v24.81a4.84 4.84 0 0 1-5.05 4.57z\" />\n <path d=\"M1186.72 493.81c-8.43 1.2-22.61 3.13-48.62 3.13-31.07 0-58.52-7.95-58.52-51.78v-80c0-43.83 27.7-51.54 58.76-51.54 26 0 39.95 1.93 48.38 3.13 3.37.48 4.82 1.69 4.82 4.82V344a4.83 4.83 0 0 1-4.82 4.82h-50.78c-11.32 0-15.41 3.85-15.41 16.38v21.92h64.27a4.83 4.83 0 0 1 4.82 4.82v22.88a4.83 4.83 0 0 1-4.82 4.82h-64.27v25.53c0 12.52 4.09 16.38 15.41 16.38h50.78a4.83 4.83 0 0 1 4.82 4.82v22.4c0 3.11-1.45 4.56-4.82 5.04z\" />\n <path d=\"M1368.43 494.77h-38.29c-3.13 0-4.58-1-6.26-3.61l-33.2-52.71L1260.6 490c-1.69 2.89-3.37 4.82-6 4.82h-35.64c-2.41 0-3.61-1.45-3.61-3.13a4.47 4.47 0 0 1 .48-1.69l52.17-87-52.71-82.61a3.42 3.42 0 0 1-.48-1.45 3.47 3.47 0 0 1 3.61-3.13h38.77c2.65 0 4.58 2.41 6 4.58l30.81 48.65 29.82-48.65c1.2-2.17 3.37-4.58 6-4.58h35.64a3.47 3.47 0 0 1 3.61 3.13 3.42 3.42 0 0 1-.48 1.45l-52.45 83.12 54.7 86.49a5.38 5.38 0 0 1 .72 2.41c.01 1.4-1.2 2.36-3.13 2.36z\" />\n <path d=\"M869.6 316.31a3.72 3.72 0 0 0-3.64 3L831 448.7c-.48 2.65-1.2 3.61-3.37 3.61s-2.89-1-3.37-3.61l-35-129.42a3.72 3.72 0 0 0-3.64-3h-34.41a3.72 3.72 0 0 0-3.62 4.56s42.7 148.39 43.17 149.85c5.7 17.68 19.53 26.13 37.13 26.13 16.76 0 31.39-8.85 37.11-26.08.68-2 42.43-149.91 42.43-149.91a3.72 3.72 0 0 0-3.62-4.55z\" />\n <path d=\"M657.59 186.14h-374c-29 0-47.57 30.83-34 56.46L287 313.44h-67.82A24.94 24.94 0 0 0 197.12 350l120.33 227.75a24.94 24.94 0 0 0 44.08 0l32.68-61.52 41 77.62c14.43 27.3 53.52 27.35 68 .08l187.46-352.76c13.25-24.95-4.83-55.03-33.08-55.03zm-168 150.72L408.76 489a16.6 16.6 0 0 1-29.33 0l-80.05-151.5A16.6 16.6 0 0 1 314 313.13h161.33a16.15 16.15 0 0 1 14.26 23.73z\" />\n </g>\n </svg>\n)\n\nexport default VTEXIcon\n\n```"
}
] |
code_store_18ab87e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/typings/vtex.render-runtime.d.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n interface Runtime {\n account: string\n rootPath: string\n query: Record<string, string>\n navigate: (args: NavigateArgs) => void\n getSettings(id: string): StoreSettings\n route: {\n routeId: string\n }\n }\n\n interface RuntimeWithRoute extends Runtime {\n route: {\n routeId: string\n title?: string\n metaTags?: MetaTagsParams\n canonicalPath?: string\n }\n }\n\n interface MetaTagsParams {\n description: string\n keywords: string[]\n }\n\n interface NavigateArgs {\n fallbackToWindowLocation: boolean\n to: string\n }\n\n interface StoreSettings {\n storeName: string\n titleTag: string\n enablePageNumberTitle: boolean\n canonicalWithoutUrlParams: boolean\n removeStoreNameTitle: boolean\n a11ySemanticHtmlMigration: boolean\n publisherId: string\n }\n\n interface KeyValue {\n value: string\n }\n\n interface Session {\n id: string\n type: undefined\n namespaces: {\n store: {\n channel: string\n }\n profile: {\n isAuthenticated: KeyValue\n email: string\n }\n }\n }\n\n interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n }\n\n interface SessionForbidden {\n type: 'Forbidden'\n message: string\n }\n\n export interface RenderSession {\n sessionPromise: Promise<SessionPromise>\n }\n\n export interface SessionPromise {\n response: SessionResponse\n }\n\n export type SessionResponse = Session | SessionUnauthorized | SessionForbidden\n\n export function useRuntime(): Runtime\n export const Helmet\n export const canUseDOM: boolean\n export const LoadingContextProvider\n}\n\nexport {}\n\n```"
}
] |
code_store_0022030e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/typings/global.d.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n dataLayer: any[]\n __hostname__: string | undefined\n}\n\ndeclare module 'vtex.store-resources/QueryProductSearchV3' {\n const query: any\n export default query\n}\n\n```"
}
] |
code_store_9bbb05a7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/typings/vtex.pixel-manager.d.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.pixel-manager/PixelContext' {\n interface Pixel {\n push(data: unknown): void\n }\n\n export function usePixel(): Pixel\n}\n\n```"
}
] |
code_store_334fa5ed
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/typings/event.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelEvent {\n event: string\n eventType: string\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\n```"
}
] |
code_store_3f5f3c42
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/utils/navigation.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable no-restricted-globals */\n// eslint-disable-next-line no-restricted-imports\nimport { contains, path as ramdaPath, zip } from 'ramda'\nimport queryString from 'query-string'\n\nconst SPEC_FILTER = 'specificationFilter'\nconst MAP_CATEGORY_CHAR = 'c'\nconst MAP_VALUES_SEP = ','\nconst PATH_SEPARATOR = '/'\nconst INTELLIGENT_SEARCH_BRAND = 'brand'\n\nconst isLegacySearchFormat = (pathSegments, map) => {\n if (!map) {\n return false\n }\n return map.split(MAP_VALUES_SEP).length === pathSegments.length\n}\n\nconst categoriesInSequence = mapValues => {\n let count = 0\n for (const value of mapValues) {\n if (value !== MAP_CATEGORY_CHAR) {\n return count\n }\n count++\n }\n return count\n}\n\nconst queryMapComparator = (tuple1, tuple2) => {\n const [, specFilterVal1] = tuple1 && tuple1[0].split(`${SPEC_FILTER}_`)\n const [, specFilterVal2] = tuple2 && tuple2[0].split(`${SPEC_FILTER}_`)\n const [facetName1, facetValue1] = tuple1\n const [facetName2, facetValue2] = tuple2\n\n const intelligentSearchCategoryRegex = /category-[0-9]+/\n const isISCategory1 = intelligentSearchCategoryRegex.test(facetName1)\n const isISCategory2 = intelligentSearchCategoryRegex.test(facetName2)\n const isISBrand1 = facetName1 === INTELLIGENT_SEARCH_BRAND\n const isISBrand2 = facetName2 === INTELLIGENT_SEARCH_BRAND\n\n // Makes the URL in the IS have the following order:\n // /[category hierarchy/alphabetically]/[brand alphabetically]/[specs alphabetically]\n // Example: category-1/category-2/brand/spec1/spec2\n if (isISCategory1 && !isISCategory2) {\n return -1\n }\n if (isISCategory2 && !isISCategory1) {\n return 1\n }\n if (isISCategory1 && isISCategory2) {\n return (\n facetName1.localeCompare(facetName2) ||\n facetValue1.localeCompare(facetValue2)\n )\n }\n if (isISBrand1 && !isISBrand2) {\n return -1\n }\n if (isISBrand2 && !isISBrand1) {\n return 1\n }\n\n const considerSpecificationFilter =\n specFilterVal1 &&\n specFilterVal2 &&\n !isNaN(Number(specFilterVal1)) &&\n !isNaN(Number(specFilterVal2))\n\n return considerSpecificationFilter\n ? Number(specFilterVal1) -\n Number(specFilterVal2) +\n facetValue1.localeCompare(facetValue2)\n : facetValue1.localeCompare(facetValue2)\n}\n\nconst normalizeQueryMap = (pathSegments, mapSegments) => {\n const categoryTreeDepth = categoriesInSequence(mapSegments)\n const zippedMapQuery = zip(mapSegments, pathSegments)\n\n const sorted =\n zippedMapQuery &&\n zippedMapQuery.slice(categoryTreeDepth).sort(queryMapComparator)\n\n const assembledSortedQuery = zippedMapQuery\n .slice(0, categoryTreeDepth)\n .concat(sorted)\n\n const sortedMap = assembledSortedQuery\n .map(value => (Array.isArray(value) ? value[0] : value))\n .join(',')\n const sortedPathSegments = assembledSortedQuery.map(tuple => tuple[1])\n\n return {\n map: sortedMap,\n pathSegments: sortedPathSegments,\n }\n}\n\nconst normalizeSearchNavigation = (pathSegments, map) => {\n return {\n pathSegments,\n map,\n }\n}\n\nconst normalizeLegacySearchNavigation = (pathSegments, queryMap, query) => {\n if (queryMap.map) {\n const mapValues = queryMap.map.split(MAP_VALUES_SEP)\n let convertedSegments = zip(\n pathSegments,\n mapValues\n ).map(([pathSegment, mapValue]) =>\n contains(SPEC_FILTER, mapValue) ? pathSegment : pathSegment.toLowerCase()\n )\n\n const {\n pathSegments: sortedPathSegments,\n map: sortedMap,\n } = normalizeQueryMap(\n queryMap.query ? queryMap.query.split('/').slice(1) : convertedSegments,\n mapValues\n )\n\n queryMap.map = sortedMap\n if (queryMap.query) {\n queryMap.query = `/${sortedPathSegments.join('/')}`\n } else {\n convertedSegments = sortedPathSegments\n }\n\n const normalizedQuery = queryString.stringify(queryMap, {\n encode: false,\n })\n\n return { pathSegments: convertedSegments, query: normalizedQuery }\n }\n return { pathSegments, query }\n}\n\nexport const normalizeNavigation = navigation => {\n if (ramdaPath(['__RUNTIME__', 'route', 'domain'], window) !== 'store') {\n return navigation\n }\n\n const { path, query } = navigation\n const parsedQuery = query ? queryString.parse(query) : {}\n const { map } = parsedQuery\n\n const pathSegments = path.startsWith(PATH_SEPARATOR)\n ? path.split(PATH_SEPARATOR).slice(1)\n : path.split(PATH_SEPARATOR)\n\n const normalizedNavigation =\n parsedQuery.query || isLegacySearchFormat(pathSegments, map)\n ? normalizeLegacySearchNavigation(pathSegments, parsedQuery, query)\n : normalizeSearchNavigation(pathSegments, query)\n\n navigation.path = path.startsWith('/')\n ? `/${normalizedNavigation.pathSegments.join('/')}`\n : normalizedNavigation.pathSegments.join('/')\n navigation.query = normalizedNavigation.query\n return navigation\n}\n\n```"
}
] |
code_store_c13b849b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/ProductTitleAndPixel.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-restricted-imports */\nimport React, { useMemo, FC } from 'react'\nimport { Helmet, useRuntime, canUseDOM } from 'vtex.render-runtime'\nimport { path } from 'ramda'\n\nimport useDataPixel from '../hooks/useDataPixel'\nimport { usePageView } from './PageViewPixel'\nimport { PixelEvent } from '../typings/event'\nimport { useCanonicalLink } from '../hooks/useCanonicalLink'\n\nconst titleSeparator = ' - '\n\nconst STORE_APP = 'vtex.store'\n\ninterface Product {\n linkText: string\n productName: string\n brand: string\n brandId: string\n categoryId: string\n categories: string[]\n categoryTree: Category[]\n productId: string\n titleTag: string\n metaTagDescription: string\n productReference: string\n items: SKU[]\n}\n\ninterface ProductViewEvent {\n detailUrl: string\n brand: string\n brandId: string\n productReference: string\n linkText: string\n categoryId: string\n categories: string[]\n categoryTree: Category[]\n productId: string\n productName: string\n items: SKUEvent[]\n selectedSku: SKUEvent\n}\n\ninterface Category {\n id: string\n name: string\n}\n\ninterface SKUEvent extends Omit<SKU, 'images'> {\n imageUrl: string\n}\n\ninterface SKU {\n itemId: string\n ean: string\n name: string\n images: Image[]\n referenceId: [{ Value: string }]\n sellers: Seller[]\n}\n\ninterface Image {\n imageId: string\n imageLabel: string\n imageUrl: string\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n sellerName: string\n sellerDefault: boolean\n}\n\ninterface CommertialOffer {\n ListPrice: number\n Price: number\n AvailableQuantity: number\n PriceWithoutDiscount: number\n}\n\ntype MaybeProduct = Product | null\n\nfunction usePageInfo(\n titleTag: string,\n product: MaybeProduct,\n loading: boolean\n) {\n const { account } = useRuntime()\n\n const pageEvents = useMemo(() => {\n if (!product || !canUseDOM) {\n return []\n }\n\n const pageInfo: PixelEvent = {\n event: 'pageInfo',\n eventType: 'productView',\n accountName: account,\n pageTitle: titleTag,\n pageUrl: window.location.href,\n }\n\n return pageInfo\n }, [account, product, titleTag])\n\n useDataPixel(pageEvents, path(['linkText'], product), loading)\n}\n\nfunction getSkuProperties(item: SKU): SKUEvent {\n return {\n itemId: item.itemId,\n name: item.name,\n ean: item.ean,\n referenceId: item.referenceId,\n imageUrl:\n item.images && item.images.length > 0 ? item.images[0].imageUrl : '',\n sellers: item.sellers.map(seller => ({\n sellerId: seller.sellerId,\n sellerName: seller.sellerName,\n sellerDefault: seller.sellerDefault,\n commertialOffer: {\n Price: seller.commertialOffer.Price,\n ListPrice: seller.commertialOffer.ListPrice,\n AvailableQuantity: seller.commertialOffer.AvailableQuantity,\n PriceWithoutDiscount:\n seller.commertialOffer?.PriceWithoutDiscount ||\n seller.commertialOffer.Price,\n },\n })),\n }\n}\n\ninterface UseProductEventsParams {\n product: Product\n selectedItem: SKU\n loading: boolean\n listName?: string\n}\n\nfunction useProductEvents({\n product,\n selectedItem,\n loading,\n listName,\n}: UseProductEventsParams) {\n const productEvents = useMemo(() => {\n const hasCategoryTree = Boolean(product?.categoryTree?.length)\n\n if (!product || !canUseDOM || !selectedItem || !hasCategoryTree) {\n return []\n }\n\n const eventProduct: ProductViewEvent = {\n detailUrl: `/${product.linkText}/p`,\n brand: product.brand,\n brandId: product.brandId,\n productReference: product.productReference,\n linkText: product.linkText,\n categoryId: product.categoryId,\n categories: product.categories,\n categoryTree: product.categoryTree,\n productId: product.productId,\n productName: product.productName,\n items: product.items.map(getSkuProperties),\n selectedSku: getSkuProperties(selectedItem),\n }\n\n return [\n {\n event: 'productView',\n product: eventProduct,\n list: listName,\n },\n ]\n }, [product, selectedItem, listName])\n\n // When linkText or selectedItem changes, it will trigger the productEvents\n const pixelCacheKey = `${product?.linkText}${selectedItem?.itemId}`\n\n useDataPixel(productEvents, pixelCacheKey, loading)\n}\n\nfunction useTitle(product: Product) {\n const { getSettings } = useRuntime()\n const { titleTag = undefined, productName = undefined } = product || {}\n let title = titleTag ?? productName ?? ''\n\n const settings = getSettings(STORE_APP)\n\n if (settings?.removeStoreNameTitle === false) {\n const { storeName, titleTag: storeTitleTag } = settings\n const storeData = storeName || storeTitleTag\n if (storeData) {\n title += title ? titleSeparator + storeData : storeData\n }\n }\n\n return title\n}\n\ninterface UseProductCanonicalLinkParams {\n linkText?: string\n}\n\nfunction useProductCanonicalLink({ linkText }: UseProductCanonicalLinkParams) {\n const canonicalLink = useCanonicalLink()\n\n if (!canonicalLink) {\n return null\n }\n\n const rel = 'canonical'\n\n if (!linkText) {\n return {\n rel,\n href: encodeURI(canonicalLink),\n }\n }\n\n const lowerCaseLinkText = linkText.toLowerCase()\n const lowerCaseCanonical = canonicalLink.toLowerCase()\n\n const linkTextIndexOnCanonical = lowerCaseCanonical.lastIndexOf(\n lowerCaseLinkText\n )\n\n if (linkTextIndexOnCanonical === -1) {\n return {\n rel,\n href: encodeURI(canonicalLink),\n }\n }\n\n const canonicalBase = canonicalLink.substring(0, linkTextIndexOnCanonical)\n\n const canonicalEnd = canonicalLink.substring(\n linkTextIndexOnCanonical + linkText.length\n )\n\n const appropriateCanonical = `${canonicalBase}${linkText}${canonicalEnd}`\n\n return {\n rel,\n href: encodeURI(appropriateCanonical),\n }\n}\n\ninterface Props {\n listName?: string\n product: Product\n selectedItem: SKU\n loading: boolean\n}\n\nconst ProductTitleAndPixel: FC<Props> = ({\n product,\n selectedItem,\n loading,\n listName,\n}) => {\n const { metaTagDescription = undefined } = product || {}\n const title = useTitle(product)\n\n const pixelCacheKey = path<string>(['linkText'], product)\n usePageView({\n title,\n skip: pixelCacheKey === undefined,\n cacheKey: pixelCacheKey,\n })\n usePageInfo(title, product, loading)\n useProductEvents({ product, selectedItem, loading, listName })\n\n const productCanonical = useProductCanonicalLink({\n linkText: product?.linkText,\n })\n\n return (\n <Helmet\n title={title}\n meta={[\n metaTagDescription && {\n name: 'description',\n content: metaTagDescription,\n },\n ].filter(Boolean)}\n link={[productCanonical].filter(Boolean)}\n />\n )\n}\n\nexport default ProductTitleAndPixel\n\n```"
}
] |
code_store_75004b41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/UserDataPixel.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useEffect, FC } from 'react'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\n\nimport {\n getSessionPromiseFromWindow,\n getUserData,\n SessionResponse,\n} from '../hooks/getUserData'\n\nconst UserDataPixel: FC = () => {\n const { push } = usePixel()\n\n useEffect(() => {\n getSessionPromiseFromWindow().then((data: SessionResponse) => {\n const profileFields = data?.response?.namespaces?.profile\n\n if (!profileFields) {\n return\n }\n\n const userData = getUserData(profileFields)\n\n push({\n event: 'userData',\n ...userData,\n })\n })\n }, [push])\n\n return null\n}\n\nexport default UserDataPixel\n\n```"
}
] |
code_store_fe7ad3e8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/OrderFormProvider.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport { graphql, compose } from 'react-apollo'\n\nimport addToCart from 'vtex.store-resources/MutationAddToCart'\nimport updateItems from 'vtex.store-resources/MutationUpdateItems'\nimport updateOrderFormProfile from 'vtex.store-resources/MutationUpdateOrderFormProfile'\nimport updateOrderFormShipping from 'vtex.store-resources/MutationUpdateOrderFormShipping'\nimport updateOrderFormCheckin from 'vtex.store-resources/MutationUpdateOrderFormCheckin'\n\nimport { Provider } from 'vtex.store-resources/OrderFormContext'\nimport orderForm from 'vtex.store-resources/QueryOrderForm'\n\nclass OrderFormProvider extends Component {\n state = {\n orderFormContext: {\n message: { isSuccess: null, text: null },\n loading: true,\n orderForm: {},\n refetch: () => {},\n addItem: this.props.addItem,\n updateToastMessage: this.handleMessageUpdate,\n updateOrderForm: this.props.updateOrderForm,\n updateAndRefetchOrderForm: this.handleUpdateAndRefetchOrderForm,\n updateOrderFormProfile: this.props.updateOrderFormProfile,\n updateOrderFormShipping: this.props.updateOrderFormShipping,\n updateOrderFormCheckin: this.props.updateOrderFormCheckin,\n },\n }\n\n static getDerivedStateFromProps(props, state) {\n if (!props.data.loading && !props.data.error) {\n const orderFormContext = props.data\n\n orderFormContext.message = state.orderFormContext.message\n\n return {\n orderFormContext,\n }\n }\n\n return state\n }\n\n handleUpdateAndRefetchOrderForm = vars => {\n return this.props.updateOrderForm(vars).then(() => {\n return this.props.data.refetch()\n })\n }\n\n handleMessageUpdate = message => {\n const context = this.state.orderFormContext\n context.message = message\n\n this.setState({ orderFormContext: context })\n }\n\n render() {\n const state = this.state\n\n state.orderFormContext.updateToastMessage = this.handleMessageUpdate\n state.orderFormContext.updateAndRefetchOrderForm = this.handleUpdateAndRefetchOrderForm\n state.orderFormContext.updateOrderForm = this.props.updateOrderForm\n state.orderFormContext.addItem = this.props.addItem\n state.orderFormContext.updateOrderFormProfile = this.props.updateOrderFormProfile\n state.orderFormContext.updateOrderFormShipping = this.props.updateOrderFormShipping\n state.orderFormContext.updateOrderFormCheckin = this.props.updateOrderFormCheckin\n\n return <Provider value={this.state}>{this.props.children}</Provider>\n }\n}\n\nconst options = {\n options: () => ({\n ssr: false,\n }),\n}\n\nexport default compose(\n graphql(orderForm, options),\n graphql(addToCart, { name: 'addItem' }),\n graphql(updateItems, { name: 'updateOrderForm' }),\n graphql(updateOrderFormProfile, { name: 'updateOrderFormProfile' }),\n graphql(updateOrderFormShipping, { name: 'updateOrderFormShipping' }),\n graphql(updateOrderFormCheckin, { name: 'updateOrderFormCheckin' })\n)(OrderFormProvider)\n\n```"
}
] |
code_store_0edd2815
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/WrapperContainer.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nconst WrapperContainer = ({ children, className }) => (\n <div className={className}>\n <div className=\"flex flex-column min-vh-100 w-100\">{children}</div>\n </div>\n)\n\nexport default WrapperContainer\n\n```"
}
] |
code_store_dc0cac38
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/NetworkStatusToast.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable no-restricted-imports */\nimport { path, pathOr } from 'ramda'\nimport { useCallback, useContext, useEffect, useState, useRef } from 'react'\nimport { injectIntl, intlShape } from 'react-intl'\nimport { ToastContext } from 'vtex.styleguide'\n\nfunction NetworkStatusToast({ intl }) {\n const [offline, setOffline] = useState(false)\n // Useful to dismissable toast flow.\n const [showingOffline, setShowingOffline] = useState(false)\n const { showToast, hideToast, toastState } = useContext(ToastContext)\n\n const toastConfig = useRef({\n message: '',\n dismissable: true,\n duration: Infinity,\n })\n\n const updateStatus = useCallback(() => {\n if (navigator) {\n setOffline(!pathOr(true, ['onLine'], navigator))\n }\n }, [])\n\n useEffect(() => {\n if (window) {\n window.addEventListener('online', updateStatus)\n window.addEventListener('offline', updateStatus)\n }\n updateStatus()\n return function cleanUp() {\n if (window) {\n window.removeEventListener('online', updateStatus)\n window.removeEventListener('offline', updateStatus)\n }\n }\n }, [updateStatus])\n\n useEffect(() => {\n if (offline && !toastState.currentToast) {\n const message = intl.formatMessage({\n id: 'store/store.network-status.offline',\n })\n toastConfig.current.message = message\n\n if (!showingOffline) {\n showToast(toastConfig.current)\n }\n setShowingOffline(!showingOffline)\n } else if (\n !offline &&\n toastState.isToastVisible &&\n path(['currentToast', 'message'], toastState) ===\n toastConfig.current.message\n ) {\n hideToast()\n setShowingOffline(false)\n }\n }, [\n offline,\n toastState,\n toastConfig,\n showingOffline,\n showToast,\n hideToast,\n intl,\n ])\n\n return null\n}\n\nNetworkStatusToast.propTypes = {\n intl: intlShape.isRequired,\n}\n\nexport default injectIntl(NetworkStatusToast)\n\n```"
}
] |
code_store_6f6a5079
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/VTEXAdsProvider.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { AdsProvider } from '@vtex/ads-react'\nimport { Offer } from '@vtex/ads-core'\nimport productSearchV3 from 'vtex.store-resources/QueryProductSearchV3'\nimport { useApolloClient } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport {\n getSessionPromiseFromWindow,\n getUserData,\n SessionResponse,\n} from '../hooks/getUserData'\n\ninterface VTEXAdsProviderProps {\n children?: React.ReactNode\n}\n\ninterface Product {\n items: Array<{\n ean: string\n itemId: string\n sellers: Array<{ sellerId: string }>\n }>\n}\n\nconst matcher = (product: Product, offer: Offer): boolean => {\n const productSku = product.items.find(\n item =>\n item.itemId === offer.skuId &&\n item.sellers.some(seller => seller.sellerId === offer.sellerId)\n )\n\n if (productSku === undefined) {\n return false\n }\n\n const seller = productSku.sellers.find(\n item => item.sellerId === offer.sellerId\n )\n\n if (!seller) {\n return false\n }\n\n productSku.sellers = [seller]\n product.items = [productSku]\n\n return true\n}\n\nexport const VTEXAdsProvider = ({ children }: VTEXAdsProviderProps) => {\n const { account, getSettings } = useRuntime()\n const publisherId = getSettings('vtex.store')?.publisherId\n\n const [userId, setUserId] = useState<string | undefined>(undefined)\n const [sessionId, setSessionId] = useState<string>('session-id')\n\n useEffect(() => {\n getSessionPromiseFromWindow()\n .then((data: SessionResponse) => {\n const profileFields = data?.response?.namespaces?.profile\n\n if (!profileFields) {\n return\n }\n\n setSessionId(data.response?.id ?? 'session-id')\n\n const userData = getUserData(profileFields)\n setUserId(userData.id as string | undefined)\n })\n .catch(() => {})\n }, [])\n\n const client = useApolloClient()\n const fetcher = async (offers: Offer[]): Promise<Product[]> => {\n if (offers.length === 0) {\n return []\n }\n\n try {\n const skuIds = offers.map(o => o.skuId).join(';')\n const { data } = await client.query<{\n productSearch: { products: Product[] }\n }>({\n query: productSearchV3,\n variables: { fullText: `sku.id:${skuIds}` },\n })\n return data?.productSearch.products ?? []\n } catch {\n return []\n }\n }\n\n if (!publisherId) {\n return children\n }\n\n return (\n <AdsProvider\n identity={{\n accountName: account,\n publisherId,\n userId,\n sessionId,\n channel: 'site',\n }}\n hydrationStrategy={{ fetcher, matcher, key: 'sf' }}\n >\n {children}\n </AdsProvider>\n )\n}\n\n```"
}
] |
code_store_bb388ab3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/components/PageViewPixel.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-restricted-globals */\nimport { useMemo } from 'react'\nimport { useRuntime, canUseDOM } from 'vtex.render-runtime'\n\nimport useDataPixel from '../hooks/useDataPixel'\n\ninterface UsePageViewArgs {\n title?: string\n cacheKey?: string\n skip?: boolean\n}\n\nexport const usePageView = ({\n title,\n cacheKey,\n skip,\n}: UsePageViewArgs = {}) => {\n const { route, account } = useRuntime()\n const pixelCacheKey = cacheKey ?? route.routeId\n\n const eventData = useMemo(() => {\n if (!canUseDOM || skip) {\n return null\n }\n\n return {\n event: 'pageView',\n pageTitle: title ?? document.title,\n pageUrl: location.href,\n referrer:\n document.referrer.indexOf(location.origin) === 0\n ? undefined\n : document.referrer,\n accountName: account,\n routeId: route?.routeId ? route.routeId : '',\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [account, title, canUseDOM, pixelCacheKey])\n\n useDataPixel(skip ? null : eventData, pixelCacheKey)\n}\n\n// Those pages already use the hook above (`usePageView`)\n// They need to handle the pageView event because they set the page title async\nconst SKIP_PAGES = ['store.search', 'store.product']\n\n/** When you navigate to a new page, the route object will remain the one from the previous route.\n * So we save the ref on the first mount. After that, we wait for the first time route changes to send a page view with the correct title.\n * A possible better implementation for the future, is add a loading state in the route object.\n */\nconst PageViewPixel = ({ title }: Partial<UsePageViewArgs>) => {\n const { route } = useRuntime()\n\n const skip =\n route && SKIP_PAGES.some(routeId => route.routeId.indexOf(routeId) === 0)\n usePageView({ title, skip })\n\n return null\n}\n\nexport default PageViewPixel\n\n```"
}
] |
code_store_a135d1fc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/__tests__/ProductWrapper.test.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable jest/no-mocks-import */\n/* eslint-env jest */\nimport React, { useContext } from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport { getProduct } from '../__mocks__/productMock'\nimport ProductWrapper from '../ProductWrapper'\nimport { ProductContext } from '../__mocks__/vtex.product-context'\n\nconst ProductPageMock = () => {\n const { selectedItem, product, selectedQuantity } = useContext(ProductContext)\n return (\n <div>\n <div>Product Page</div>\n <div>Selected Item id: {selectedItem && selectedItem.itemId}</div>\n <div>Selected Item name: {selectedItem && selectedItem.name}</div>\n <div>product slug: {product && product.linkText}</div>\n <div>Selected Quantity: {selectedQuantity}</div>\n </div>\n )\n}\n\nconst descriptionId = 'description'\n\ndescribe('ProductWrapper component', () => {\n const getProps = customProps => {\n const product = getProduct()\n const productQuery = {\n product,\n loading: false,\n }\n const props = {\n params: { slug: product.linkText },\n productQuery,\n query: {},\n ...customProps,\n }\n return props\n }\n const renderComponent = customProps => {\n const component = render(\n <ProductWrapper {...getProps(customProps)}>\n <ProductPageMock />\n </ProductWrapper>\n )\n const { getByText } = component\n return {\n ...component,\n getTitleTag: product => getByText(new RegExp(product.titleTag)),\n }\n }\n\n it('should render with correct title and no meta', () => {\n const product = getProduct()\n const { queryByTestId, getTitleTag } = renderComponent()\n getTitleTag(product)\n // Doesnt have metatag description, <meta> should not be rendered\n expect(queryByTestId(descriptionId)).toBeNull()\n })\n\n it('should render with correct title and meta', () => {\n const product = getProduct({ metaTagDescription: 'MetaDescription' })\n const { getTitleTag, getByTestId } = renderComponent({\n product,\n params: { slug: product.linkText },\n productQuery: { product, loading: false },\n })\n getByTestId(descriptionId)\n getTitleTag(product)\n })\n\n it('product wont break if category tree is an empty array', () => {\n const product = getProduct({ categoryTree: [] })\n const { getTitleTag } = renderComponent({\n product,\n params: { slug: product.linkText },\n productQuery: { product, loading: false },\n })\n getTitleTag(product)\n })\n})\n\n```"
}
] |
code_store_6be24533
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/__tests__/SearchWrapper.test.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport queryString from 'query-string'\n\nimport { getHelmetLink } from '../SearchWrapper'\n\ndescribe('getHelmetLink function', () => {\n it('should return null if no canonical is provided', () => {\n const result = getHelmetLink({\n canonicalLink: null,\n page: 1,\n rel: 'canonical',\n })\n\n // Cannot generate meta links if there's no canonical link to use\n expect(result).toBeNull()\n })\n\n it('should return null if resulting page is less than 1', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: -1,\n rel: 'canonical',\n })\n\n const nextLinkResult = getHelmetLink({\n canonicalLink,\n page: -1,\n rel: 'next',\n })\n\n const prevLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n rel: 'prev',\n })\n\n expect(canonicalLinkResult).toBeNull()\n expect(nextLinkResult).toBeNull()\n expect(prevLinkResult).toBeNull()\n })\n\n it('should not return page number if page is equal to 1', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n rel: 'canonical',\n })\n\n const nextLinkResult = getHelmetLink({\n canonicalLink,\n page: 0,\n rel: 'next',\n })\n\n const prevLinkResult = getHelmetLink({\n canonicalLink,\n page: 2,\n rel: 'prev',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n expect(nextLinkResult).toHaveProperty('href', expectedResult)\n expect(prevLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should return canonical link with page querystring appended to it', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const page = 2\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page,\n rel: 'canonical',\n })\n\n const nextLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n rel: 'next',\n })\n\n const prevLinkResult = getHelmetLink({\n canonicalLink,\n page: 3,\n rel: 'prev',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n page,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n expect(nextLinkResult).toHaveProperty('href', expectedResult)\n expect(prevLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should not return the map on the canonical url of department pages', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n map: 'c',\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should not return the map on the canonical url of category pages', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'c,c'\n const page = 2\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n page,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should not return the map on the canonical url of subcategory pages', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'c,c,c'\n const page = 3\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n page,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should not return the map on the canonical url of brand pages', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'b'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should return the map on the canonical url when map has more than 4 categories', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'c,c,c,c,c'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n map,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should return the map on the canonical url when map has category and brand', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'c,b'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n map,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n\n it('should return the map on the canonical url when map has any weird value', () => {\n const canonicalLink = 'https://storetheme.vtex.com/apparel---accessories/'\n const map = 'productClusterIds,c'\n\n const canonicalLinkResult = getHelmetLink({\n canonicalLink,\n page: 1,\n map,\n rel: 'canonical',\n })\n\n const expectedResult = queryString.stringifyUrl({\n url: canonicalLink,\n query: {\n map,\n },\n })\n\n expect(canonicalLinkResult).toHaveProperty('href', expectedResult)\n })\n})\n\n```"
}
] |
code_store_5be4805f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/__tests__/navigation.test.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { normalizeNavigation } from '../utils/navigation'\n\ndescribe('Navigation route modifier', () => {\n window.__RUNTIME__ = {\n route: {\n domain: 'store',\n },\n }\n\n it('should lowercase the path', () => {\n const path = '/Category1/category2/Category3'\n const query =\n 'map=c,c,c,specificationFilter_1&query=/Category1/category2/Category3/xpto'\n const expectedPath = path.toLocaleLowerCase()\n const expectedQuery = query\n const result = normalizeNavigation({ path, query })\n\n expect(result).toEqual({ path: expectedPath, query: expectedQuery })\n })\n it('should sort specification filters', () => {\n const path = '/Category1/category2/Category3'\n const query =\n 'map=c,c,c,specificationFilter_2,specificationFilter_0,specificationFilter_1&query=/Category1/category2/Category3/xpto2/xpto0/xpto1'\n const expectedPath = path.toLocaleLowerCase()\n const expectedQuery =\n 'map=c,c,c,specificationFilter_0,specificationFilter_1,specificationFilter_2&query=/Category1/category2/Category3/xpto0/xpto1/xpto2'\n const result = normalizeNavigation({ path, query })\n\n expect(result).toEqual({ path: expectedPath, query: expectedQuery })\n })\n it('intelligent search queries should have the following order: /[category hierarchy/alphabetically]/[brand alphabetically]/[specs alphabetically]', () => {\n const path = '/departmentvalue/categoryvalue1/categoryvalue2'\n const query =\n 'map=specificationFilter,category-2,category-2,brand,category-1,brand,&query=/specvalue/categoryvalue2/categoryvalue1/brandvalue2/departmentvalue/brandvalue1'\n const expectedPath = path.toLocaleLowerCase()\n const expectedQuery =\n 'map=category-1,category-2,category-2,brand,brand,specificationFilter&query=/departmentvalue/categoryvalue1/categoryvalue2/brandvalue1/brandvalue2/specvalue'\n const result = normalizeNavigation({ path, query })\n\n expect(result).toEqual({ path: expectedPath, query: expectedQuery })\n })\n it('should preserve case for new routes pattern', () => {\n const path = '/foo/bar/nice_Bar'\n const expectedPath = '/foo/bar/nice_Bar'\n const ignore = { 'nice-bar': { path: 'nice_Bar' } }\n const result = normalizeNavigation({ path, ignore })\n expect(result).toEqual({ path: expectedPath, ignore, query: undefined })\n })\n})\n\n```"
}
] |
code_store_2d98eb42
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/hooks/useCanonicalLink.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { RuntimeWithRoute, useRuntime } from 'vtex.render-runtime'\n\nexport function useCanonicalLink() {\n const { route, rootPath = '' } = useRuntime() as RuntimeWithRoute\n const { canonicalPath } = route\n\n const canonicalHost =\n window.__hostname__ || (window.location && window.location.hostname)\n\n if (!canonicalHost || !canonicalPath) {\n return null\n }\n\n const canonicalLink = `https://${canonicalHost}${rootPath}${canonicalPath}`\n\n return canonicalLink\n}\n\n```"
}
] |
code_store_9675227b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/hooks/getUserData.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nconst fields = [\n 'firstName',\n 'lastName',\n 'document',\n 'id',\n 'email',\n 'phone',\n 'isAuthenticated',\n] as const\n\nexport interface SessionResponse {\n response: {\n id: string\n namespaces: {\n profile?: {\n firstName?: {\n value: string\n }\n lastName?: {\n value: string\n }\n document?: {\n value: string\n }\n id?: {\n value: string\n }\n email?: {\n value: string\n }\n phone?: {\n value: string\n }\n isAuthenticated?: {\n value: string\n }\n }\n }\n }\n}\n\nexport const getSessionPromiseFromWindow: any = () =>\n !(window as any).__RENDER_8_SESSION__ ||\n !(window as any).__RENDER_8_SESSION__.sessionPromise\n ? Promise.resolve(null)\n : (window as any).__RENDER_8_SESSION__.sessionPromise\n\nconst toBoolean = (value: string) => value.toLowerCase() === 'true'\n\nexport function getUserData(\n profileFields: SessionResponse['response']['namespaces']['profile']\n) {\n if (!profileFields) {\n return {}\n }\n\n return fields.reduce<Record<string, string | boolean>>((acc, key) => {\n const value = profileFields[key]?.value\n\n if (value) {\n acc[key] = key === 'isAuthenticated' ? toBoolean(value) : value\n }\n\n return acc\n }, {})\n}\n\n```"
}
] |
code_store_2a16afa8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/hooks/useDataPixel.tsx from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-restricted-imports */\nimport { useEffect, useRef } from 'react'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\nimport { isEmpty } from 'ramda'\n\ntype Data = unknown[] | unknown\n\nconst useDataPixel = (data: Data, pageIdentifier = '', isLoading = false) => {\n const { push } = usePixel()\n const previousIdRef = useRef<string | null>(null)\n\n const previousId = previousIdRef.current\n\n useEffect(() => {\n if (pageIdentifier && !isLoading && previousId !== pageIdentifier) {\n if (!data || isEmpty(data)) {\n return\n }\n if (Array.isArray(data)) {\n data.forEach(push)\n } else {\n push(data)\n }\n\n previousIdRef.current = pageIdentifier\n }\n }, [data, isLoading, pageIdentifier, previousId, push])\n}\n\nexport default useDataPixel\n\n```"
}
] |
code_store_c0cbfb4d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/scripts/gtm.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const gtmScript = gtmId => `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\nnew Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\nj=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n})(window,document,'script','dataLayer','${gtmId}')`\n\nexport const gtmFrame = gtmId =>\n `<iframe src=\"https://www.googletagmanager.com/ns.html?id=${gtmId}\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe>`\n\n```"
}
] |
code_store_c424bd26
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/capitalize.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const capitalize = (str?: string) => {\n return str && str.charAt(0).toUpperCase() + str.slice(1)\n}\n\n```"
}
] |
code_store_78643a2a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/searchMetadata.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// eslint-disable-next-line no-restricted-imports\nimport { zipObj } from 'ramda'\n\nimport { SearchQueryData, CategoriesTrees, Facets } from './searchTypes'\n\nconst getDepartmentFromSpecificationFilters = (facets?: Facets) => {\n if (!facets?.queryArgs?.map.split(',').includes('c')) {\n return\n }\n\n const departmentFilter = facets.specificationFilters?.find(specFilter => {\n return specFilter.facets?.[0].key === 'category-1'\n })\n\n return departmentFilter?.facets?.find(facet => facet.selected)\n}\n\nconst getDepartment = (searchQuery: SearchQueryData) => {\n if (searchQuery.facets?.categoriesTrees?.length) {\n return searchQuery.facets.categoriesTrees.find(\n department => department.selected\n )\n }\n return getDepartmentFromSpecificationFilters(searchQuery.facets)\n}\n\nexport const getDepartmentMetadata = (searchQuery?: SearchQueryData) => {\n if (\n !searchQuery ||\n !searchQuery.facets ||\n !searchQuery.facets.categoriesTrees\n ) {\n return\n }\n\n const department = getDepartment(searchQuery)\n\n if (!department) {\n return\n }\n\n return {\n id: department.id,\n name: department.name,\n }\n}\n\nconst getCategoryFromSpecificationFilters = (facets?: Facets) => {\n const totalCategories =\n facets?.queryArgs?.map.split(',').filter((key: string) => key === 'c')\n .length ?? 0\n\n if (totalCategories <= 1) {\n return\n }\n const categoryFilter = facets?.specificationFilters?.find(specFilter => {\n return specFilter.facets?.[0].key === 'category-2'\n })\n\n return categoryFilter?.facets?.find(facet => facet.selected)\n}\n\nconst getLastCategory = (\n category: CategoriesTrees,\n facets?: Facets\n): CategoriesTrees => {\n const selectedCategory =\n category.children &&\n category.children.length > 0 &&\n category.children.find(currCategory => currCategory.selected)\n\n if (!selectedCategory) {\n return getCategoryFromSpecificationFilters(facets) ?? category\n }\n\n return getLastCategory(selectedCategory)\n}\n\nexport const getCategoryMetadata = (searchQuery?: SearchQueryData) => {\n if (\n !searchQuery ||\n !searchQuery.facets ||\n !searchQuery.facets.categoriesTrees\n ) {\n return\n }\n\n const department = getDepartment(searchQuery)\n\n if (!department) {\n return\n }\n\n const category = getLastCategory(department, searchQuery.facets)\n\n if (category === department) {\n return\n }\n\n return {\n id: category.id,\n name: category.name,\n }\n}\n\nexport const getSearchMetadata = (\n searchQuery?: SearchQueryData,\n page?: number,\n maxItemsPerPage?: number\n) => {\n if (\n !searchQuery ||\n !searchQuery.productSearch ||\n !searchQuery.facets ||\n !searchQuery.facets.queryArgs\n ) {\n return\n }\n\n const { query, map } = searchQuery.facets.queryArgs\n const queryMap = zipObj(map.split(','), query.split('/'))\n\n const searchTerm = queryMap.ft\n\n let decodedTerm = ''\n // This try/catch works to prevent decoding search terms that end in \"%\".\n try {\n decodedTerm = decodeURIComponent(searchTerm || '')\n } catch (e) {\n decodedTerm = decodeURIComponent(encodeURIComponent(searchTerm || ''))\n }\n\n const department = getDepartment(searchQuery)\n\n const products = searchQuery?.products?.map(product => {\n return {\n productId: product.productId,\n }\n })\n\n return {\n term: decodedTerm || undefined,\n category: department ? { id: department.id, name: department.name } : null,\n results: searchQuery.productSearch.recordsFiltered,\n operator: searchQuery.productSearch.operator,\n searchState: searchQuery.productSearch.searchState,\n correction: searchQuery.productSearch.correction,\n products,\n page,\n maxItemsPerPage,\n }\n}\n\n```"
}
] |
code_store_7c62bb96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/session.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SessionPromise } from 'vtex.render-runtime'\n\nexport function getSession() {\n return window &&\n (window as any).__RENDER_8_SESSION__ &&\n (window as any).__RENDER_8_SESSION__.sessionPromise\n ? ((window as any).__RENDER_8_SESSION__.sessionPromise as Promise<\n SessionPromise\n >)\n : null\n}\n\n```"
}
] |
code_store_daed7992
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/searchTypes.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface SearchQuery {\n loading: boolean\n products: any\n data?: SearchQueryData\n variables: {\n query: string\n map: string\n }\n}\n\nexport interface SearchQueryData {\n searchMetadata?: {\n titleTag: string\n metaTagDescription: string\n }\n productSearch?: {\n breadcrumb: Breadcrumb[]\n recordsFiltered: number\n operator?: string\n searchState?: string\n correction?: {\n misspelled: boolean\n }\n }\n products?: Product[]\n facets?: Facets\n}\n\nexport interface Facets {\n categoriesTrees?: CategoriesTrees[]\n queryArgs?: QueryArgs\n specificationFilters?: SpecificationFilter[]\n}\n\ninterface SpecificationFilter {\n facets?: any[]\n hidden: boolean\n name: string\n quantity: number\n type: string\n}\n\nexport interface Breadcrumb {\n name: string\n href: string\n}\n\nexport interface Product {\n productId: string\n}\n\nexport interface CategoriesTrees {\n id: string\n name: string\n selected: boolean\n children?: CategoriesTrees[]\n}\n\ninterface QueryArgs {\n query: string\n map: string\n}\n\n```"
}
] |
code_store_661176e5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/searchMetadata.test.ts from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n getDepartmentMetadata,\n getCategoryMetadata,\n getSearchMetadata,\n} from './searchMetadata'\n\ntest('should get department metadata', () => {\n const searchQuery = {\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: true,\n children: [\n {\n id: '2',\n name: 'bar',\n selected: false,\n children: [],\n },\n ],\n },\n ],\n },\n }\n\n const result = getDepartmentMetadata(searchQuery)\n\n expect(result!.id).toBe('1')\n expect(result!.name).toBe('foo')\n})\n\ntest('should get category metadata', () => {\n const searchQuery = {\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: true,\n children: [\n {\n id: '2',\n name: 'bar',\n selected: true,\n children: [],\n },\n ],\n },\n ],\n },\n }\n\n const result = getCategoryMetadata(searchQuery)\n\n expect(result!.id).toBe('2')\n expect(result!.name).toBe('bar')\n})\n\ntest('should not get category metadata if none is selected', () => {\n const searchQuery = {\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: true,\n children: [\n {\n id: '2',\n name: 'bar',\n selected: false,\n children: [],\n },\n ],\n },\n ],\n },\n }\n\n const result = getCategoryMetadata(searchQuery)\n\n expect(result).toBeUndefined()\n})\n\ntest('should get deepest category metadata', () => {\n const searchQuery = {\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: true,\n children: [\n {\n id: '2',\n name: 'bar',\n selected: true,\n children: [\n {\n id: '3',\n name: 'baz',\n selected: true,\n children: [],\n },\n ],\n },\n ],\n },\n ],\n },\n }\n\n const result = getCategoryMetadata(searchQuery)\n\n expect(result!.id).toBe('3')\n expect(result!.name).toBe('baz')\n})\n\ntest('should get the searched metadata', () => {\n const searchQuery = {\n productSearch: {\n recordsFiltered: 3,\n breadcrumb: [\n {\n name: 'Top',\n href: '/electronics/top?map=c,ft',\n },\n ],\n operator: 'and',\n searchState: 'placeholder',\n correction: { misspelled: false },\n },\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: true,\n children: [],\n },\n ],\n queryArgs: {\n query: 'Top',\n map: 'ft',\n },\n },\n }\n\n const result = getSearchMetadata(searchQuery)\n\n expect(result!.term).toBe('Top')\n expect(result!.category!.id).toBe('1')\n expect(result!.category!.name).toBe('foo')\n expect(result!.results).toBe(3)\n expect(result!.operator).toBe('and')\n expect(result!.searchState).toBe('placeholder')\n expect(result!.correction!.misspelled).toBe(false)\n})\n\ntest('should get the searched metadata without category', () => {\n const searchQuery = {\n productSearch: {\n recordsFiltered: 3,\n breadcrumb: [\n {\n name: 'Top',\n href: '/electronics/top?map=c,ft',\n },\n ],\n operator: 'and',\n searchState: 'placeholder',\n correction: { misspelled: true },\n },\n facets: {\n categoriesTrees: [\n {\n id: '1',\n name: 'foo',\n selected: false,\n children: [],\n },\n ],\n queryArgs: {\n query: 'Top',\n map: 'ft',\n },\n },\n }\n\n const result = getSearchMetadata(searchQuery)\n\n expect(result!.term).toBe('Top')\n expect(result!.category).toBeNull()\n expect(result!.results).toBe(3)\n expect(result!.operator).toBe('and')\n expect(result!.searchState).toBe('placeholder')\n expect(result!.correction!.misspelled).toBe(true)\n})\n\n```"
}
] |
code_store_3f9b1040
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store/react/modules/search.js from the store VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const SORT_OPTIONS = [\n {\n value: '',\n label: 'store/ordenation.relevance',\n },\n {\n value: 'OrderByTopSaleDESC',\n label: 'store/ordenation.sales',\n },\n {\n value: 'OrderByReleaseDateDESC',\n label: 'store/ordenation.release.date',\n },\n {\n value: 'OrderByBestDiscountDESC',\n label: 'store/ordenation.discount',\n },\n {\n value: 'OrderByPriceDESC',\n label: 'store/ordenation.price.descending',\n },\n {\n value: 'OrderByPriceASC',\n label: 'store/ordenation.price.ascending',\n },\n {\n value: 'OrderByNameASC',\n label: 'store/ordenation.name.ascending',\n },\n {\n value: 'OrderByNameDESC',\n label: 'store/ordenation.name.descending',\n },\n]\n\n// Quick function to get querystring\n// https://stackoverflow.com/a/901144/5313009\n// TODO: Replace this with a better function\nconst getParameterByName = (name, url) => {\n if (!url) url = window && window.location && window.location.href\n name = name.replace(/[[\\]]/g, '\\\\$&')\n\n const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`)\n const results = regex.exec(url)\n\n if (!results) return null\n if (!results[2]) return ''\n\n return (\n window &&\n window.decodeURIComponent &&\n window.decodeURIComponent(results[2].replace(/\\+/g, ' '))\n )\n}\n\nexport function getMapFromURL(url) {\n getParameterByName('map', url)\n}\n\nexport function createInitialMap(params) {\n if (params.subcategory) {\n return 'c,c,c'\n }\n if (params.category) {\n return 'c,c'\n }\n if (params.department) {\n return 'c'\n }\n if (params.brand) {\n return 'b'\n }\n if (params.term) {\n return 'ft'\n }\n\n return params.terms\n .split('/')\n .map(() => 'ft')\n .join(',')\n}\n\nexport function initializeMap(params, url) {\n return getMapFromURL(url) || createInitialMap(params)\n}\n\n```"
}
] |
code_console_49ddba58
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/messages/pt.json from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"console.menu.title\": \"Console\",\n \"console.submenu.metrics\": \"Métricas\",\n \"console.submenu.publishes\": \"Publicações\",\n \"console.admin.tabs.metrics\": \"Métricas\",\n \"console.admin.tabs.errors\": \"Erros\",\n \"console.admin.metrics.button.add\": \"Adicionar Novo\",\n \"console.context\": \"Contexto\",\n \"console.newMetric\": \"Nova Métrica\",\n \"console.available.apps\": \"Apps Disponíveis\",\n \"console.app.version\": \"Versão\",\n \"console.app.region\": \"Região\",\n \"console.app.environment\": \"Ambiente\",\n \"console.any\": \"Qualquer\",\n \"console.envPicker.production\": \"Produção\",\n \"console.envPicker.development\": \"Desenvolvimento\",\n \"console.empty.time.range.headline\": \"Por favor defina um intervalo de tempo\",\n \"console.empty.time.range.explanation\": \"Por favor defina um intervalo de tempo para analisar sua métrica\",\n \"console.button.set.time.range\": \"Definir Intervalo de Tempo\",\n \"console.button.apply.time.range\": \"Aplicar\",\n \"console.date.picker.from\": \"De\",\n \"console.date.picker.to\": \"Até\",\n \"console.range.step.picker.stepSize\": \"Passo\",\n \"console.cpuUsage.lineChart\": \"Uso de Cpu (percentual) durante o Tempo\",\n \"console.latency.lineChart\": \"Latência (milisegundos) durante o Tempo\",\n \"console.memoryUsage.lineChart\": \"Consumo de Memória (bytes) durante o Tempo\",\n \"console.empty.context.headline\": \"Por favor selecione um contexto\",\n \"console.empty.context.explanation\": \"Por favor selecione o contexto no qual suas métricas serão analisadas\",\n \"console.time.controller.absolute\": \"Absoluto\",\n \"console.time.controller.relative\": \"Relativo\",\n \"console.statusCode.barChart\": \"Distribuição de Http Status Code\",\n \"console.statusCode.lineChart\": \"Http Status Code (percentual) durante o tempo\",\n \"console.time.controller.relative.earliest\": \"De\",\n \"console.time.controller.relative.earliestModifier.seconds.ago\": \"Segundos Atrás\",\n \"console.time.controller.relative.earliestModifier.minutes.ago\": \"Minutos Atrás\",\n \"console.time.controller.relative.earliestModifier.hours.ago\": \"Horas Atrás\",\n \"console.time.controller.relative.earliestModifier.days.ago\": \"Dias Atrás\",\n \"console.time.controller.relative.earliestModifier.months.ago\": \"Meses Atrás\",\n \"console.time.controller.relative.earliestModifier.years.ago\": \"Anos Atrás\"\n}\n\n```"
}
] |
code_console_dbc16bdc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/messages/en.json from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"console.menu.title\": \"Console\",\n \"console.submenu.metrics\": \"Metrics\",\n \"console.submenu.publishes\": \"Publishes\",\n \"console.admin.tabs.metrics\": \"Metrics\",\n \"console.admin.tabs.errors\": \"Errors\",\n \"console.admin.metrics.button.add\": \"Add New\",\n \"console.context\": \"Context\",\n \"console.newMetric\": \"New Metric\",\n \"console.available.apps\": \"Available Apps\",\n \"console.app.version\": \"Version\",\n \"console.app.region\": \"Region\",\n \"console.app.environment\": \"Environment\",\n \"console.any\": \"Any\",\n \"console.envPicker.production\": \"Production\",\n \"console.envPicker.development\": \"Development\",\n \"console.empty.time.range.headline\": \"Please set a time range\",\n \"console.empty.time.range.explanation\": \"Please set a time range to analyze your metric\",\n \"console.button.set.time.range\": \"Set Time Range\",\n \"console.button.apply.time.range\": \"Apply\",\n \"console.date.picker.from\": \"From\",\n \"console.date.picker.to\": \"To\",\n \"console.range.step.picker.stepSize\": \"Step\",\n \"console.cpuUsage.lineChart\": \"Cpu usage (percentage) over Time\",\n \"console.latency.lineChart\": \"Latency (miliseconds) over Time\",\n \"console.memoryUsage.lineChart\": \"Memory (bytes) consumption over Time\",\n \"console.empty.context.headline\": \"Please select a context\",\n \"console.empty.context.explanation\": \"Please select the context in which your metrics will be analyzed\",\n \"console.time.controller.absolute\": \"Absolute\",\n \"console.time.controller.relative\": \"Relative\",\n \"console.statusCode.barChart\": \"Http Status Code Distribution\",\n \"console.statusCode.lineChart\": \"Http Status Code (percentage) over Time\",\n \"console.time.controller.relative.earliest\": \"From\",\n \"console.time.controller.relative.earliestModifier.seconds.ago\": \"Seconds Ago\",\n \"console.time.controller.relative.earliestModifier.minutes.ago\": \"Minutes Ago\",\n \"console.time.controller.relative.earliestModifier.hours.ago\": \"Hours Ago\",\n \"console.time.controller.relative.earliestModifier.days.ago\": \"Days Ago\",\n \"console.time.controller.relative.earliestModifier.months.ago\": \"Months Ago\",\n \"console.time.controller.relative.earliestModifier.years.ago\": \"Years Ago\"\n}\n\n```"
}
] |
code_console_c861b89c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/messages/context.json from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"console.menu.title\": \"\",\n \"console.submenu.metrics\": \"\",\n \"console.submenu.publishes\": \"\",\n \"console.admin.tabs.metrics\": \"\",\n \"console.admin.tabs.errors\": \"\",\n \"console.context\": \"\",\n \"console.newMetric\": \"\",\n \"console.available.apps\": \"\",\n \"console.app.version\": \"\",\n \"console.app.region\": \"\",\n \"console.app.environment\": \"\",\n \"console.any\": \"\",\n \"console.envPicker.production\": \"\",\n \"console.envPicker.development\": \"\",\n \"console.empty.time.range.headline\": \"\",\n \"console.empty.time.range.explanation\": \"\",\n \"console.button.set.time.range\": \"\",\n \"console.button.apply.time.range\": \"\",\n \"console.date.picker.from\": \"\",\n \"console.date.picker.to\": \"\",\n \"console.range.step.picker.stepSize\": \"\",\n \"console.cpuUsage.lineChart\": \"\",\n \"console.latency.lineChart\": \"\",\n \"console.memoryUsage.lineChart\": \"\",\n \"console.empty.context.headline\": \"\",\n \"console.empty.context.explanation\": \"\",\n \"console.time.controller.absolute\": \"\",\n \"console.time.controller.relative\": \"\",\n \"console.statusCode.barChart\": \"\",\n \"console.statusCode.lineChart\": \"\",\n \"console.time.controller.relative.earliest\": \"\",\n \"console.time.controller.relative.earliestModifier.seconds.ago\": \"\",\n \"console.time.controller.relative.earliestModifier.minutes.ago\": \"\",\n \"console.time.controller.relative.earliestModifier.hours.ago\": \"\",\n \"console.time.controller.relative.earliestModifier.days.ago\": \"\",\n \"console.time.controller.relative.earliestModifier.months.ago\": \"\",\n \"console.time.controller.relative.earliestModifier.years.ago\": \"\"\n}\n\n```"
}
] |
code_console_58c37f48
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/docs/README.md from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# React+GraphQL\nExample app to show how to create an app using React and GraphQL. \n\nThis App acts as a catalog management system and uses some advanced VTEX IO GraphQL features, like `@autopersisted` and `@cacheControl` directives.\n\n## Autopersisted Types\nOnce a GraphQL type is decorated with the `@autopersisted` directive, VTEX IO Builders automatically generates all CRUD operations for that type. If you want to know more about autopersisted types, read our [wiki](https://github.com/vtex/graphql-server/wiki/Features#autopersisted-types)\n\n## Cached Types\nVTEX IO GraphQL increases the performance of your queries by caching types decorated with `@cacheControl` hints directly in the CDN. To know more about GraphQL cache hints, visit [apollo](https://www.apollographql.com/docs/engine/caching.html)\n\n```"
}
] |
code_console_cfc8bd60
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/pages/pages.json from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"routes\": {\n \"admin/console\": {\n \"path\": \"/admin/console\"\n },\n \"admin/console/publishes\": {\n \"path\": \"/admin/console/publishes\"\n },\n \"admin/console/tab\": {\n \"path\": \"/admin/console/*tab\"\n }\n },\n \"extensions\": {\n \"admin/console\": {\n \"component\": \"vtex.render-runtime/LayoutContainer\",\n \"props\": {\n \"elements\": [\n \"__children__\"\n ]\n }\n },\n \"admin/console/tab\": {\n \"component\": \"Console\"\n },\n \"admin/console/publishes\": {\n \"component\": \"vtex.builder-log/Publishes\"\n },\n \"admin/navigation/analytics/console\": {\n \"component\": \"vtex.admin/InjectNavigationData\",\n \"props\": {\n \"icon\": \"extensions-ic\",\n \"id\": \"38\",\n \"tag\": \"appframe.new\",\n \"titleId\": \"console.menu.title\",\n \"subItems\": [\n {\n \"labelId\": \"console.submenu.metrics\",\n \"path\": \"/admin/console/metrics\"\n },\n {\n \"labelId\": \"console.submenu.publishes\",\n \"path\": \"/admin/console/publishes\"\n }\n ]\n }\n }\n }\n}\n\n```"
}
] |
code_console_6c9ce03e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/copiedcss.global.css from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@import '~react-select/dist/react-select.css';\n\n@import 'datePicker.css';\n\nhtml, body {\n height: 100%;\n}\n\n.track-1 {\n letter-spacing: 0.2px;\n}\n\n.min-h-2 {\n min-height: 2rem;\n}\n\n.render-provider {\n height: 100%;\n background-color: #fff;\n}\n\n.editor-provider {\n height: 100%;\n}\n\n.editor-provider .preview-button {\n display: none;\n}\n\n.shadow-editor {\n -webkit-box-shadow: 0px -2px 1px 0px rgba(0, 0, 0, 0.25);\n -moz-box-shadow: 0px -2px 1px 0px rgba(0, 0, 0, 0.25);\n box-shadow: 0px -2px 1px 0px rgba(0, 0, 0, 0.25);\n}\n\n.form-group {\n padding-top: 10px;\n padding-bottom: 10px;\n}\n\n.form-group.field.field-object > label {\n border-top: 2px solid #f0f2f4;\n color: #c3c4c5;\n font-weight: 700;\n margin-top: 10px;\n padding: 20px 0px 5px;\n text-transform: uppercase;\n}\n\n.form-group.field.field-object:first-child > label {\n border-top: none;\n margin-top: 0;\n padding-top: 0;\n}\n\n.checkbox span {\n padding-left: 5px;\n font-size: 0.875rem;\n}\n\n.editor-form {\n padding: 15px 24px 0px;\n overflow-x: hidden;\n}\n\n.field-description {\n font-size: 12px;\n color: #979899;\n margin-top: 0px;\n font-style: italic;\n}\n\n.editor-form > label {\n padding: 0px !important;\n margin: 0px !important;\n}\n\n.form-control {\n border: 2px solid #e1e3e5;\n height: 40px;\n width: 100%;\n font-size: 14px;\n padding-left: 12px;\n background-color: #ffffff;\n}\n\n.draggable {\n cursor: move;\n}\n\n.h-3em {\n height: 48px;\n}\n\n.build-status {\n top: 0 !important;\n left: 0 !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n background-color: #fff !important;\n margin: 11px !important;\n padding: 0 !important;\n}\n\n.build-status.reload {\n margin-top: 0 !important;\n width: 100% !important;\n height: 46px !important;\n}\n\n.build-status.fail {\n margin-top: 0 !important;\n width: 100% !important;\n height: 46px !important;\n}\n\n.radio-inline > span > span {\n padding-left: 5px;\n padding-right: 15px;\n}\n\n.editor-form .vtex-textarea textarea {\n max-width: 100%;\n min-width: 100%;\n}\n\n.field-range-wrapper > input {\n width: 80%;\n}\n\n.field-range-wrapper {\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n\n.field-range-wrapper > span {\n font-size: 16px;\n font-weight: 700;\n padding-right: 3px;\n color: #368df7;\n}\n\n.panel-danger {\n position: fixed;\n width: 100%;\n}\n\n@media only screen and (max-width: 40em) {\n .size-editor {\n bottom: 0;\n height: 100%;\n }\n}\n\n@media only screen and (min-width: 40em) {\n .field-range-wrapper > input {\n width: 85%;\n }\n .form-schema {\n min-height: 300px;\n }\n .size-editor {\n max-width: 450px;\n }\n .shadow-editor-desktop {\n -webkit-box-shadow: 0px 4px 10px 0px rgba(86, 88, 107, 0.5);\n -moz-box-shadow: 0px 4px 10px 0px rgba(86, 88, 107, 0.5);\n box-shadow: 0px 4px 10px 0px rgba(86, 88, 107, 0.5);\n }\n}\n\n.calc--height-relative {\n height: calc(100% - 3em);\n}\n\n/* Non small */\n@media screen and (min-width: 30em) {\n .h-3em-ns {\n height: 3em;\n }\n .calc--height-ns {\n height: calc(100vh - 3em);\n }\n .calc--height-relative-ns {\n height: calc(100% - 3em);\n }\n .top-3em-ns {\n top: 3em;\n }\n .calc--width-ns {\n width: calc(100% - 18em);\n }\n .calc--minified-width-ns {\n width: calc(100% - 3em);\n }\n .w-3em-ns {\n width: 3em;\n }\n .w-18em-ns {\n width: 18em;\n }\n\n .admin-sidebar {\n border-left: 2px solid #f2f4f5;\n }\n\n .admin-sidebar::-webkit-scrollbar,\n .admin-sidebar::-webkit-scrollbar-track {\n width: 2px;\n background: #f2f4f5;\n }\n\n .admin-sidebar::-webkit-scrollbar-thumb {\n width: 2px;\n background: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n }\n}\n\n.mobile-preview {\n width: 360px;\n height: 640px;\n overflow-x: hidden;\n box-shadow: 1px 4px 8px rgba(0, 0, 0, 0.2);\n}\n\n.tablet-preview {\n width: 768px;\n height: 1024px;\n overflow-x: hidden;\n box-shadow: 1px 4px 8px rgba(0, 0, 0, 0.2);\n}\n\n.stroke-blue {\n stroke: #368df7;\n}\n\n.stroke-mid-gray {\n stroke: #727273;\n}\n\n.fill-blue {\n fill: #368df7;\n}\n\n.fill-mid-gray {\n fill: #727273;\n}\n\n.accordion-list-container--sorting .accordion-item {\n pointer-events: none;\n}\n\n.accordion-item {\n transition: height 300ms ease-in-out, opacity 150ms ease-in-out;\n background-color: white;\n}\n\n.accordion-item--dragged {\n z-index: 999;\n}\n\n.accordion-label {\n display: flex;\n position: relative;\n justify-content: space-between;\n margin: 0 -24px 0;\n height: 57px;\n padding: 19px 16.5px 14px 16px;\n cursor: pointer;\n user-select: none;\n}\n\n.accordion-content .accordion-label {\n margin-left: 0;\n}\n\n.accordion-content .accordion-content {\n padding-left: 14px;\n}\n\n.accordion-item--dragged .accordion-label,\n.accordion-label:hover {\n background-color: #f2f4f5;\n padding-left: 26px;\n}\n\n.accordion-item--handle-hidden .accordion-label {\n padding-left: 16px;\n}\n\n.accordion-item--dragged .accordion-label {\n box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);\n}\n\n.accordion-label-buttons {\n display: none;\n}\n\n.accordion-label:hover .accordion-label-buttons {\n display: flex;\n}\n\n.accordion-label-title {\n color: #727273;\n font-weight: bold;\n cursor: pointer;\n}\n\n.accordion-icon-button {\n padding: 0;\n background: none;\n border: none;\n cursor: pointer;\n}\n\n.accordion-icon-button--remove {\n margin-left: 17px;\n}\n\n.accordion-icon-button--down {\n margin-left: 8px;\n}\n\n.editor-icon--stroke path,\n.editor-icon--stroke circle {\n stroke: #727273;\n}\n\n.editor-icon--fill path,\n.editor-icon--fill circle {\n fill: #727273;\n}\n\n.accordion-icon-button:hover .editor-icon--stroke path,\n.accordion-icon-button:hover .editor-icon--stroke circle {\n stroke: #368df7;\n}\n\n.accordion-icon-button:hover .editor-icon--fill path,\n.accordion-icon-button:hover .editor-icon--fill circle {\n fill: #368df7;\n}\n\n.accordion-handle {\n display: none;\n position: absolute;\n left: 5px;\n padding: 3px;\n}\n\n.accordion-item--dragged .accordion-handle,\n.accordion-label:hover .accordion-handle {\n display: block;\n}\n\n.accordion-item--dragged .accordion-content {\n display: none;\n}\n\n.iframe-pointer-none {\n pointer-events: none;\n}\n\n```"
}
] |
code_console_67cf0dc6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/datePicker.css from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@charset \"UTF-8\";\n.react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view--down-arrow,\n.react-datepicker-popper[data-placement^=\"top\"] .react-datepicker__triangle,\n.react-datepicker-popper[data-placement^=\"bottom\"] .react-datepicker__triangle {\n margin-left: -8px;\n position: absolute;\n}\n.react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view--down-arrow,\n.react-datepicker-popper[data-placement^=\"top\"] .react-datepicker__triangle,\n.react-datepicker-popper[data-placement^=\"bottom\"] .react-datepicker__triangle,\n.react-datepicker__year-read-view--down-arrow::before,\n.react-datepicker__month-read-view--down-arrow::before,\n.react-datepicker__month-year-read-view--down-arrow::before,\n.react-datepicker-popper[data-placement^=\"top\"]\n .react-datepicker__triangle::before,\n.react-datepicker-popper[data-placement^=\"bottom\"]\n .react-datepicker__triangle::before {\n box-sizing: content-box;\n position: absolute;\n border: 8px solid transparent;\n height: 0;\n width: 1px;\n}\n.react-datepicker__year-read-view--down-arrow::before,\n.react-datepicker__month-read-view--down-arrow::before,\n.react-datepicker__month-year-read-view--down-arrow::before,\n.react-datepicker-popper[data-placement^=\"top\"]\n .react-datepicker__triangle::before,\n.react-datepicker-popper[data-placement^=\"bottom\"]\n .react-datepicker__triangle::before {\n content: \"\";\n z-index: -1;\n border-width: 8px;\n left: -8px;\n border-bottom-color: #e3e4e6;\n}\n\n.react-datepicker-popper[data-placement^=\"bottom\"] .react-datepicker__triangle {\n top: 0;\n margin-top: -8px;\n}\n.react-datepicker-popper[data-placement^=\"bottom\"] .react-datepicker__triangle,\n.react-datepicker-popper[data-placement^=\"bottom\"]\n .react-datepicker__triangle::before {\n border-top: none;\n border-bottom-color: #f0f0f0;\n}\n.react-datepicker-popper[data-placement^=\"bottom\"]\n .react-datepicker__triangle::before {\n top: -1px;\n border-bottom-color: #e3e4e6;\n}\n\n.react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view--down-arrow,\n.react-datepicker-popper[data-placement^=\"top\"] .react-datepicker__triangle {\n bottom: 0;\n margin-bottom: -8px;\n}\n.react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view--down-arrow,\n.react-datepicker-popper[data-placement^=\"top\"] .react-datepicker__triangle,\n.react-datepicker__year-read-view--down-arrow::before,\n.react-datepicker__month-read-view--down-arrow::before,\n.react-datepicker__month-year-read-view--down-arrow::before,\n.react-datepicker-popper[data-placement^=\"top\"]\n .react-datepicker__triangle::before {\n border-bottom: none;\n border-top-color: #fff;\n}\n.react-datepicker__year-read-view--down-arrow::before,\n.react-datepicker__month-read-view--down-arrow::before,\n.react-datepicker__month-year-read-view--down-arrow::before,\n.react-datepicker-popper[data-placement^=\"top\"]\n .react-datepicker__triangle::before {\n bottom: -1px;\n border-top-color: #e3e4e6;\n}\n\n.react-datepicker-wrapper {\n display: inline-block;\n}\n\n.react-datepicker {\n font-family: Fabriga, -apple-system, BlinkMacSystemFont, avenir next, avenir,\n helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif;\n font-size: 0.8rem;\n background-color: white;\n color: #142032;\n border: 1px solid #e3e4e6;\n border-radius: 0.3rem;\n display: inline-block;\n position: relative;\n}\n\n.react-datepicker--time-only .react-datepicker__triangle {\n left: 35px;\n}\n.react-datepicker--time-only .react-datepicker__time-container {\n border-left: 0;\n}\n.react-datepicker--time-only .react-datepicker__time {\n border-radius: 0.3rem;\n}\n.react-datepicker--time-only .react-datepicker__time-box {\n border-radius: 0.3rem;\n}\n\n.react-datepicker__triangle {\n position: absolute;\n left: 50px;\n}\n\n.react-datepicker-popper {\n z-index: 1;\n}\n.react-datepicker-popper[data-placement^=\"bottom\"] {\n margin-top: 10px;\n}\n.react-datepicker-popper[data-placement^=\"top\"] {\n margin-bottom: 10px;\n}\n.react-datepicker-popper[data-placement^=\"right\"] {\n margin-left: 8px;\n}\n.react-datepicker-popper[data-placement^=\"right\"] .react-datepicker__triangle {\n left: auto;\n right: 42px;\n}\n.react-datepicker-popper[data-placement^=\"left\"] {\n margin-right: 8px;\n}\n.react-datepicker-popper[data-placement^=\"left\"] .react-datepicker__triangle {\n left: 42px;\n right: auto;\n}\n\n.react-datepicker__header {\n text-align: center;\n background-color: #f0f0f0;\n border-bottom: 1px solid #e3e4e6;\n border-top-left-radius: 0.3rem;\n border-top-right-radius: 0.3rem;\n padding-top: 8px;\n position: relative;\n}\n.react-datepicker__header--time {\n padding-bottom: 8px;\n padding-left: 5px;\n padding-right: 5px;\n}\n\n.react-datepicker__year-dropdown-container--select,\n.react-datepicker__month-dropdown-container--select,\n.react-datepicker__month-year-dropdown-container--select,\n.react-datepicker__year-dropdown-container--scroll,\n.react-datepicker__month-dropdown-container--scroll,\n.react-datepicker__month-year-dropdown-container--scroll {\n display: inline-block;\n margin: 0 2px;\n}\n\n.react-datepicker__current-month,\n.react-datepicker-time__header {\n margin-top: 0;\n color: #000;\n font-weight: bold;\n font-size: 0.944rem;\n}\n\n.react-datepicker-time__header {\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.react-datepicker__navigation {\n background: none;\n line-height: 1.7rem;\n text-align: center;\n cursor: pointer;\n position: absolute;\n top: 10px;\n width: 0;\n padding: 0;\n border: 0.45rem solid transparent;\n z-index: 1;\n}\n.react-datepicker__navigation--previous {\n left: 10px;\n border-right-color: #ccc;\n}\n.react-datepicker__navigation--previous:hover {\n border-right-color: #b3b3b3;\n}\n.react-datepicker__navigation--previous--disabled,\n.react-datepicker__navigation--previous--disabled:hover {\n border-right-color: #e6e6e6;\n cursor: default;\n}\n.react-datepicker__navigation--next {\n right: 10px;\n border-left-color: #ccc;\n}\n.react-datepicker__navigation--next--with-time:not(.react-datepicker__navigation--next--with-today-button) {\n right: 80px;\n}\n.react-datepicker__navigation--next:hover {\n border-left-color: #b3b3b3;\n}\n.react-datepicker__navigation--next--disabled,\n.react-datepicker__navigation--next--disabled:hover {\n border-left-color: #e6e6e6;\n cursor: default;\n}\n.react-datepicker__navigation--years {\n position: relative;\n top: 0;\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n.react-datepicker__navigation--years-previous {\n top: 4px;\n border-top-color: #ccc;\n}\n.react-datepicker__navigation--years-previous:hover {\n border-top-color: #b3b3b3;\n}\n.react-datepicker__navigation--years-upcoming {\n top: -4px;\n border-bottom-color: #ccc;\n}\n.react-datepicker__navigation--years-upcoming:hover {\n border-bottom-color: #b3b3b3;\n}\n\n.react-datepicker__month-container {\n float: left;\n}\n\n.react-datepicker__month {\n margin: 0.4rem;\n text-align: center;\n}\n\n.react-datepicker__time-container {\n float: right;\n border-left: 1px solid #e3e4e6;\n width: 70px;\n}\n.react-datepicker__time-container--with-today-button {\n display: inline;\n border: 1px solid #e3e4e6;\n border-radius: 0.3rem;\n position: absolute;\n right: -72px;\n top: 0;\n}\n.react-datepicker__time-container .react-datepicker__time {\n position: relative;\n background: white;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box {\n width: 70px;\n overflow-x: hidden;\n margin: 0 auto;\n text-align: center;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list {\n list-style: none;\n margin: 0;\n height: calc(195px + (1.7rem / 2));\n overflow-y: scroll;\n padding-right: 30px;\n padding-left: 0px;\n width: 100%;\n box-sizing: content-box;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item {\n padding: 5px 10px;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item:hover {\n cursor: pointer;\n background-color: #f0f0f0;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--selected {\n background-color: #368df7;\n color: white;\n font-weight: bold;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--selected:hover {\n background-color: #368df7;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--disabled {\n color: #ccc;\n}\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--disabled:hover {\n cursor: default;\n background-color: transparent;\n}\n\n.react-datepicker__week-number {\n color: #ccc;\n display: inline-block;\n width: 1.7rem;\n line-height: 1.7rem;\n text-align: center;\n margin: 0.166rem;\n}\n.react-datepicker__week-number.react-datepicker__week-number--clickable {\n cursor: pointer;\n}\n.react-datepicker__week-number.react-datepicker__week-number--clickable:hover {\n border-radius: 0.3rem;\n background-color: #f0f0f0;\n}\n\n.react-datepicker__day-names,\n.react-datepicker__week {\n white-space: nowrap;\n}\n\n.react-datepicker__day-name,\n.react-datepicker__day,\n.react-datepicker__time-name {\n color: #000;\n display: inline-block;\n width: 1.7rem;\n line-height: 1.7rem;\n text-align: center;\n margin: 0.166rem;\n}\n\n.react-datepicker__day {\n cursor: pointer;\n}\n.react-datepicker__day:hover {\n border-radius: 0.3rem;\n background-color: #f0f0f0;\n}\n.react-datepicker__day--today {\n font-weight: bold;\n}\n.react-datepicker__day--highlighted {\n border-radius: 0.3rem;\n background-color: #3dcc4a;\n color: #fff;\n}\n.react-datepicker__day--highlighted:hover {\n background-color: #32be3f;\n}\n.react-datepicker__day--highlighted-custom-1 {\n color: magenta;\n}\n.react-datepicker__day--highlighted-custom-2 {\n color: green;\n}\n.react-datepicker__day--selected,\n.react-datepicker__day--in-selecting-range,\n.react-datepicker__day--in-range {\n border-radius: 0.3rem;\n background-color: #368df7;\n color: #fff;\n}\n.react-datepicker__day--selected:hover,\n.react-datepicker__day--in-selecting-range:hover,\n.react-datepicker__day--in-range:hover {\n background-color: #2a6dbf;\n}\n.react-datepicker__day--keyboard-selected {\n border-radius: 0.3rem;\n background-color: #368df7;\n color: #fff;\n}\n.react-datepicker__day--keyboard-selected:hover {\n background-color: #2a6dbf;\n}\n.react-datepicker__day--in-selecting-range:not(.react-datepicker__day--in-range) {\n background-color: rgba(33, 107, 165, 0.5);\n}\n.react-datepicker__month--selecting-range\n .react-datepicker__day--in-range:not(.react-datepicker__day--in-selecting-range) {\n background-color: #f0f0f0;\n color: #000;\n}\n.react-datepicker__day--disabled {\n cursor: default;\n color: #ccc;\n}\n.react-datepicker__day--disabled:hover {\n background-color: transparent;\n}\n\n.react-datepicker__input-container {\n position: relative;\n display: inline-block;\n color: #3f3f40;\n font-size: 0.875rem;\n border-width: 0.125rem;\n border-color: #e3e4e6;\n}\n\n.react-datepicker__year-read-view,\n.react-datepicker__month-read-view,\n.react-datepicker__month-year-read-view {\n border: 1px solid transparent;\n border-radius: 0.3rem;\n}\n.react-datepicker__year-read-view:hover,\n.react-datepicker__month-read-view:hover,\n.react-datepicker__month-year-read-view:hover {\n cursor: pointer;\n}\n.react-datepicker__year-read-view:hover\n .react-datepicker__year-read-view--down-arrow,\n.react-datepicker__year-read-view:hover\n .react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-read-view:hover\n .react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view:hover\n .react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view:hover\n .react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-year-read-view:hover\n .react-datepicker__month-read-view--down-arrow {\n border-top-color: #b3b3b3;\n}\n.react-datepicker__year-read-view--down-arrow,\n.react-datepicker__month-read-view--down-arrow,\n.react-datepicker__month-year-read-view--down-arrow {\n border-top-color: #ccc;\n float: right;\n margin-left: 20px;\n top: 8px;\n position: relative;\n border-width: 0.45rem;\n}\n\n.react-datepicker__year-dropdown,\n.react-datepicker__month-dropdown,\n.react-datepicker__month-year-dropdown {\n background-color: #f0f0f0;\n position: absolute;\n width: 50%;\n left: 25%;\n top: 30px;\n z-index: 1;\n text-align: center;\n border-radius: 0.3rem;\n border: 1px solid #e3e4e6;\n}\n.react-datepicker__year-dropdown:hover,\n.react-datepicker__month-dropdown:hover,\n.react-datepicker__month-year-dropdown:hover {\n cursor: pointer;\n}\n.react-datepicker__year-dropdown--scrollable,\n.react-datepicker__month-dropdown--scrollable,\n.react-datepicker__month-year-dropdown--scrollable {\n height: 150px;\n overflow-y: scroll;\n}\n\n.react-datepicker__year-option,\n.react-datepicker__month-option,\n.react-datepicker__month-year-option {\n line-height: 20px;\n width: 100%;\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n.react-datepicker__year-option:first-of-type,\n.react-datepicker__month-option:first-of-type,\n.react-datepicker__month-year-option:first-of-type {\n border-top-left-radius: 0.3rem;\n border-top-right-radius: 0.3rem;\n}\n.react-datepicker__year-option:last-of-type,\n.react-datepicker__month-option:last-of-type,\n.react-datepicker__month-year-option:last-of-type {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n border-bottom-left-radius: 0.3rem;\n border-bottom-right-radius: 0.3rem;\n}\n.react-datepicker__year-option:hover,\n.react-datepicker__month-option:hover,\n.react-datepicker__month-year-option:hover {\n background-color: #ccc;\n}\n.react-datepicker__year-option:hover\n .react-datepicker__navigation--years-upcoming,\n.react-datepicker__month-option:hover\n .react-datepicker__navigation--years-upcoming,\n.react-datepicker__month-year-option:hover\n .react-datepicker__navigation--years-upcoming {\n border-bottom-color: #b3b3b3;\n}\n.react-datepicker__year-option:hover\n .react-datepicker__navigation--years-previous,\n.react-datepicker__month-option:hover\n .react-datepicker__navigation--years-previous,\n.react-datepicker__month-year-option:hover\n .react-datepicker__navigation--years-previous {\n border-top-color: #b3b3b3;\n}\n.react-datepicker__year-option--selected,\n.react-datepicker__month-option--selected,\n.react-datepicker__month-year-option--selected {\n position: absolute;\n left: 15px;\n}\n\n.react-datepicker__close-icon {\n background-color: transparent;\n border: 0;\n cursor: pointer;\n display: inline-block;\n height: 0;\n outline: 0;\n padding: 0;\n vertical-align: middle;\n}\n.react-datepicker__close-icon::after {\n background-color: #368df7;\n border-radius: 50%;\n bottom: 0;\n box-sizing: border-box;\n color: #fff;\n content: \"×\";\n cursor: pointer;\n font-size: 12px;\n height: 16px;\n width: 16px;\n line-height: 1;\n margin: -8px auto 0;\n padding: 2px;\n position: absolute;\n right: 7px;\n text-align: center;\n top: 50%;\n}\n\n.react-datepicker__today-button {\n background: #f0f0f0;\n border-top: 1px solid #e3e4e6;\n cursor: pointer;\n text-align: center;\n font-weight: bold;\n padding: 5px 0;\n clear: left;\n}\n\n.react-datepicker__portal {\n position: fixed;\n width: 100vw;\n height: 100vh;\n background-color: rgba(0, 0, 0, 0.8);\n left: 0;\n top: 0;\n justify-content: center;\n align-items: center;\n display: flex;\n z-index: 2147483647;\n}\n.react-datepicker__portal .react-datepicker__day-name,\n.react-datepicker__portal .react-datepicker__day,\n.react-datepicker__portal .react-datepicker__time-name {\n width: 3rem;\n line-height: 3rem;\n}\n@media (max-width: 400px), (max-height: 550px) {\n .react-datepicker__portal .react-datepicker__day-name,\n .react-datepicker__portal .react-datepicker__day,\n .react-datepicker__portal .react-datepicker__time-name {\n width: 2rem;\n line-height: 2rem;\n }\n}\n.react-datepicker__portal .react-datepicker__current-month,\n.react-datepicker__portal .react-datepicker-time__header {\n font-size: 1.44rem;\n}\n.react-datepicker__portal .react-datepicker__navigation {\n border: 0.81rem solid transparent;\n}\n.react-datepicker__portal .react-datepicker__navigation--previous {\n border-right-color: #ccc;\n}\n.react-datepicker__portal .react-datepicker__navigation--previous:hover {\n border-right-color: #b3b3b3;\n}\n.react-datepicker__portal .react-datepicker__navigation--previous--disabled,\n.react-datepicker__portal\n .react-datepicker__navigation--previous--disabled:hover {\n border-right-color: #e6e6e6;\n cursor: default;\n}\n.react-datepicker__portal .react-datepicker__navigation--next {\n border-left-color: #ccc;\n}\n.react-datepicker__portal .react-datepicker__navigation--next:hover {\n border-left-color: #b3b3b3;\n}\n.react-datepicker__portal .react-datepicker__navigation--next--disabled,\n.react-datepicker__portal .react-datepicker__navigation--next--disabled:hover {\n border-left-color: #e6e6e6;\n cursor: default;\n}\n\n/*# sourceMappingURL=react-datepicker.css.map */\n\n```"
}
] |
code_console_8a9997c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/package.json from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"apollo-client\": \"^2.4.8\",\n \"graphql\": \"^14.0.2\",\n \"moment\": \"^2.22.2\",\n \"prop-types\": \"^15.6.2\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.5.2\",\n \"react-apollo\": \"^2.2.4\",\n \"react-datepicker\": \"^1.7.0\",\n \"react-intl\": \"^2.7.1\",\n \"react-vega\": \"^4.0.2\",\n \"recharts\": \"^1.4.2\",\n \"semver\": \"^5.6.0\",\n \"vega-lib\": \"^4.3.0\"\n },\n \"devDependencies\": {\n \"@types/history\": \"^4.7.2\",\n \"@types/moment\": \"^2.13.0\",\n \"@types/node\": \"^10.12.0\",\n \"@types/ramda\": \"^0.25.47\",\n \"@types/react\": \"^16.4.17\",\n \"@types/react-intl\": \"^2.3.11\",\n \"@types/recharts\": \"^1.1.6\",\n \"@types/semver\": \"^5.5.0\",\n \"@types/vega\": \"^0.0.30\",\n \"tslint\": \"^5.11.0\",\n \"tslint-config-vtex\": \"^2.0.0\",\n \"typescript\": \"3.7.3\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n },\n \"version\": \"0.6.1\"\n}\n\n```"
}
] |
code_console_6f9e7505
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/Console.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { pluck } from 'ramda'\nimport React, { Component } from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { withRuntimeContext } from 'render'\nimport { PageHeader, Tab, Tabs } from 'vtex.styleguide'\n\nimport Errors from './components/Errors'\nimport Metrics from './components/Metrics'\nimport StylesContainer from './components/StylesContainer'\n\n\ninterface Props extends InjectedIntlProps {\n params: {\n tab: string\n }\n runtime: RenderContext\n}\n\ninterface Field {\n path: string\n name: string\n titleId: string\n}\n\n\nconst DivHeight = { minHeight: 'calc(100vh - 3em)' }\n\nconst fields: Field[] = [\n {\n name: 'metrics',\n path: 'metrics',\n titleId: 'console.admin.tabs.metrics',\n },\n]\n\nclass Console extends Component<Props, {}> {\n\n public componentDidMount() {\n window.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }\n\n public render() {\n const {\n params: { tab },\n intl,\n runtime: { navigate },\n } = this.props\n\n if (!pluck('name', fields).includes(tab)) {\n navigate({ to: '/admin/console/metrics' })\n }\n\n return (\n <div className=\"bg-muted-5\" style={DivHeight}>\n <div className=\"w-90 center\">\n <PageHeader title=\"IO Console\" />\n <Tabs>\n {fields.map(({ name, path, titleId }: Field) => (\n <Tab\n key={name}\n label={intl.formatMessage({ id: titleId })}\n active={tab === path}\n onClick={() => navigate({ to: `/admin/console/${path}` })}\n />\n ))}\n </Tabs>\n </div>\n <div>\n <StylesContainer>\n {tab === 'metrics' && <Metrics />}\n </StylesContainer>\n </div>\n </div>\n )\n }\n}\n\nexport default withRuntimeContext(injectIntl(Console))\n\n```"
}
] |
code_console_4cc1eafc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/typings/events.d.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface EventWithValue extends Event {\n value: any\n}\n\n```"
}
] |
code_console_324dcd0c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/typings/render.d.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'render' {\n import { Component, ReactElement } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n export const ExtensionPoint: ReactElement\n export const Helmet: ReactElement\n export const Link: ReactElement\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const buildCacheLocator = (app: string, type: string, cacheId: string) => string\n\n interface RenderComponent<P = {}, S = {}> extends Component<P, S> {\n getCustomMessages?: (locale: string) => any\n schema: ComponentSchema\n getSchema?: (a: any, b: any?) => ComponentSchema\n uiSchema: UISchema\n }\n\n export interface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n }\n\n export interface Window extends Window {\n __RENDER_7_COMPONENTS__: ComponentsRegistry\n }\n\n let global: Window\n}\n\n```"
}
] |
code_console_d73af5dd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/typings/gql.d.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_console_13ac0962
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/typings/global.d.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface RenderContext {\n account: RenderRuntime['account']\n components: RenderRuntime['components']\n culture: RenderRuntime['culture']\n device: ConfigurationDevice\n emitter: RenderRuntime['emitter']\n extensions: RenderRuntime['extensions']\n fetchComponent: (component: string) => Promise<void>\n getSettings: (app: string) => any\n history: any | null\n navigate: (options: NavigateOptions) => boolean\n onPageChanged: (location: Location) => void\n page: RenderRuntime['page']\n pages: RenderRuntime['pages']\n prefetchPage: (name: string) => Promise<void>\n production: RenderRuntime['production']\n setDevice: (device: ConfigurationDevice) => void\n updateComponentAssets: (availableComponents: Components) => void\n updateExtension: (name: string, extension: Extension) => void\n updateRuntime: (options?: PageContextOptions) => Promise<void>\n workspace: RenderRuntime['workspace']\n}\n\ninterface NavigateOptions {\n page?: string\n params?: any\n query?: any\n to?: string\n scrollOptions?: RenderScrollOptions\n fallbackToWindowLocation?: boolean\n}\n\ninterface AppController {\n appName?: string\n appVersion?: string\n region?: string\n production?: string\n}\n\ninterface TimeController {\n startDate?: Date\n endDate?: Date\n mode?: TimeRange\n}\n\ntype TimeRange = 'absolute' | 'relative'\n\ntype SetTimeControllers = (timeControllers: TimeController) => void\n\ntype SetAppControllers = (appControllers: AppController) => void\n\n\n```"
}
] |
code_console_4c3b8420
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/typings/vtex.styleguide.d.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ReactElement } from 'react'\n\n const Badge: ReactElement\n const Button: ReactElement\n const Checkbox: ReactElement\n const DatePicker: ReactElement\n const Dropdown: ReactElement\n const EmptyState: ReactElement\n const IconCaretRight: ReactElement\n const Input: ReactElement\n const Layout: ReactElement\n const NumericStepper: ReactElement\n const Tab: ReactElement\n const Tabs: ReactElement\n const Textarea: ReactElement\n const Radio: ReactElement\n const RadioGroup: ReactElement\n const Spinner: ReactElement\n const PageHeader: ReactElement\n const PageBlock: ReactElement\n\n export { Button, Dropdown, DatePicker, EmptyState, Input, Layout, NumericStepper, Tab, Tabs, Radio, RadioGroup, Spinner, PageBlock, PageHeader }\n}\n\n```"
}
] |
code_console_7cf97a4e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Errors.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { EmptyState } from 'vtex.styleguide'\n\n\nconst Errors = () => {\n return (\n <EmptyState title=\"Coming Soon\">\n <p>\n Coming soon!\n </p>\n </EmptyState>\n )\n}\n\nexport default Errors\n\n```"
}
] |
code_console_c3a640ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/StylesContainer.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n children: React.ReactNode\n}\n\nconst StylesContainer: React.SFC<Props> = (props) => (\n <div className=\"w-90 mt7 mr-auto ml-auto\">{props.children}</div>\n)\n\nexport default StylesContainer\n\n```"
}
] |
code_console_97c4230c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/common/utils.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { compose, map, uniqWith } from 'ramda'\nimport { InjectedIntl } from 'react-intl'\n\n\nexport interface Option {\n label: string\n value: string\n}\n\n\nexport const adjustStartDate = (earliestSize: number, earliestModifier: string) => {\n const startDate: Date = new Date()\n switch (earliestModifier) {\n case 'Seconds Ago':\n startDate.setSeconds(startDate.getSeconds() - earliestSize)\n return startDate\n case 'Minutes Ago':\n startDate.setMinutes(startDate.getMinutes() - earliestSize)\n return startDate\n case 'Hours Ago':\n startDate.setHours(startDate.getHours() - earliestSize)\n return startDate\n case 'Days Ago':\n startDate.setDate(startDate.getDate() - earliestSize)\n return startDate\n case 'Months Ago':\n startDate.setMonth(startDate.getMonth() - earliestSize)\n return startDate\n case 'Years Ago':\n startDate.setFullYear(startDate.getFullYear() - earliestSize)\n return startDate\n default:\n startDate.setHours(startDate.getHours() - earliestSize)\n return startDate\n }\n}\n\nexport const adjustStartDateHour = () => {\n const date = new Date()\n date.setHours(date.getHours() - 1)\n return date\n}\n\nexport const adjustEndDate = (endDate: Date) => {\n // always decrease one second to avoid taking the next bucket\n endDate.setSeconds(endDate.getSeconds() - 1)\n return endDate\n}\n\nexport const getAppVersion = (chosenMajor: string, chosenMinor: string, chosenPatch: string) => {\n return (chosenMajor && chosenMinor && chosenPatch)\n ? `${chosenMajor}.${chosenMinor}.${chosenPatch}`\n : undefined\n}\n\nconst strEq = (str1: string, str2: string) => str1 === str2\n\nexport const dropdownOptions = (options: string[]) => compose(\n map((optionName: string) => ({ value: optionName, label: optionName })),\n uniqWith(strEq)\n)(options)\n\nexport const formattedDropdownOptions = (options: Option[], intl: InjectedIntl) => map(\n (option: Option) => {\n return {\n label: intl.formatMessage({ id: option.label, defaultMessage: option.label }),\n value: option.value,\n }\n },\n options)\n\n```"
}
] |
code_console_210d9785
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/common/constants.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const CHART_PROPERTIES = {\n height: 250,\n width: '100%',\n}\n\nexport const colors = ['#1f77b4', '#17becf', '#2ca02c', '#ff7f0e', '#d62728', '#bcbd22', '#8c564b', '#e377c2', '#9467bd', '#7f7f7f']\n\n```"
}
] |
code_console_7bec4a0c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/common/layoutContent.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport CpuUsageLineChart from '../components/Metrics/DataAnalysis/Charts/CpuUsageLineChart'\nimport MemoryUsageLineChart from '../components/Metrics/DataAnalysis/Charts/MemoryUsageLineChart'\nimport StatusCodeBarChart from '../components/Metrics/DataAnalysis/Charts/StatusCodeBarChart'\nimport StatusCodeLineChart from '../components/Metrics/DataAnalysis/Charts/StatusCodeLineChart'\n\n\nexport default [\n {\n ChartComponent: MemoryUsageLineChart,\n chartType: 'LineChart',\n id: 1,\n storedash: {\n metricParams: {\n fields: 'data.summary.external, data.summary.heapTotal, data.summary.heapUsed, data.summary.rss, count',\n metricName: 'memoryUsage',\n operation: 'sum',\n },\n name: 'runtime',\n },\n },\n {\n ChartComponent: StatusCodeBarChart,\n chartType: 'BarChart',\n id: 2,\n storedash: {\n metricParams: {\n aggregateBy: 'data.key.httpStatus',\n fields: 'data.summary.count',\n metricName: 'routeStats',\n operation: 'sum',\n },\n name: 'runtime',\n },\n },\n {\n ChartComponent: CpuUsageLineChart,\n chartType: 'LineChart',\n id: 3,\n storedash: {\n metricParams: {\n fields: 'data.summary.system, data.summary.user, count',\n metricName: 'cpuUsage',\n operation: 'sum',\n },\n name: 'runtime',\n },\n },\n {\n ChartComponent: StatusCodeLineChart,\n chartType: 'LineChart',\n id: 4,\n storedash: {\n metricParams: {\n aggregateBy: 'data.key.httpStatus',\n fields: 'data.summary.count',\n metricName: 'routeStats',\n operation: 'sum',\n },\n name: 'runtime',\n },\n },\n]\n\n\n```"
}
] |
code_console_77229324
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/common/dataAnalysis.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { addIndex, has, isEmpty, isNil, map } from 'ramda'\nimport { InjectedIntl } from 'react-intl'\n\n\nexport const isNilOrEmpty = (x: any) => isEmpty(x) || isNil(x)\n\nexport const mapIndexed = addIndex(map)\n\nconst periodName: string[] = ['s', 'm', 'h', 'd', 'M', 'y']\n\nconst periodDuration: number[] = [1, 60, 60 * 60, 24 * 60 * 60, 30 * 24 * 60 * 60, 12 * 30 * 24 * 60 * 60]\n\nconst adjustRangeStep = (rangeStepSize: number): string => {\n let i: number = 1\n while (i <= periodName.length && rangeStepSize > periodDuration[i]) {\n i++\n }\n i--\n rangeStepSize = Math.round(rangeStepSize / periodDuration[i])\n return rangeStepSize + periodName[i]\n}\n\nexport const getRangeStep = (startDate: Date, endDate: Date): string => {\n const elapsedTime: number = ((endDate.getTime() + 1000) - startDate.getTime()) / 1000\n const rangeStepSize = Math.round(elapsedTime / 12)\n const rangeStep = adjustRangeStep(rangeStepSize)\n return rangeStep\n}\n\nexport const getStepModifier = (metricParams: any): string => {\n let stepModifier = ''\n if (has('interval', metricParams)) {\n stepModifier = metricParams.interval[metricParams.interval.length - 1]\n }\n return stepModifier\n}\n\nexport const getFormattedTime = (date: any, intl: InjectedIntl, stepModifier: string): string => {\n switch (stepModifier) {\n case 's':\n return intl.formatTime(date, {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n })\n case 'm':\n return intl.formatTime(date, {\n hour: 'numeric',\n minute: 'numeric',\n })\n case 'h':\n return intl.formatTime(date, {\n hour: 'numeric',\n minute: 'numeric',\n })\n case 'd':\n return intl.formatDate(date, {\n day: 'numeric',\n month: 'numeric',\n year: 'numeric',\n })\n case 'M':\n return intl.formatDate(date, {\n month: 'numeric',\n year: 'numeric',\n })\n case 'y':\n return intl.formatDate(date, {\n year: 'numeric',\n })\n default:\n return intl.formatDate(date, {\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n month: 'numeric',\n year: 'numeric',\n })\n }\n}\n\n\n// Source: stackoverflow.com/questions/2685911/is-there-a-way-to-round-numbers-into-a-reader-friendly-format-e-g-1-1k\nexport const abbrNum = (value: number, decPlaces: number): string => {\n decPlaces = Math.pow(10, decPlaces)\n const abbrev = [' k', ' M', ' G', ' T']\n\n let tickValue: string = '0'\n for (let i = abbrev.length - 1; i >= 0; i--) {\n const size = Math.pow(10, (i + 1) * 3)\n\n if (size <= value) {\n value = Math.round((value * decPlaces) / size) / decPlaces\n\n if (value === 1000 && i < abbrev.length - 1) {\n value = 1\n i++\n }\n\n tickValue = value + abbrev[i]\n\n break\n }\n }\n\n return tickValue\n}\n\nexport const abbrPerc = (value: any, intl: InjectedIntl): string => {\n return intl.formatNumber(\n Number(value),\n {\n maximumFractionDigits: 2,\n style: 'percent',\n }\n )\n}\n\n```"
}
] |
code_console_8b02de54
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/graphql/data.graphql from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery GetData($name: String!, $params:StoreDashInput) {\n data(\n name:$name,\n params: $params\n )\n}\n\n```"
}
] |
code_console_323d798d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { Location } from 'history'\nimport React, { Component } from 'react'\nimport { FormattedMessage, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { withRuntimeContext } from 'render'\nimport { EmptyState } from 'vtex.styleguide'\n\nimport layoutContent from '../../common/layoutContent'\nimport { AppContext } from './Contexts/AppContext'\nimport { TimeContext } from './Contexts/TimeContext'\nimport Controllers from './Controllers'\nimport DataAnalysis from './DataAnalysis'\n\n\ninterface Props extends InjectedIntlProps {\n runtime: RenderContext\n}\n\ninterface State {\n appControllers: AppController\n timeControllers: TimeController\n}\n\n\nclass Metrics extends Component<Props, State> {\n private searchParams: URLSearchParams = new URLSearchParams()\n constructor(props: Props) {\n super(props)\n this.props.runtime.history.listen(this.listenChangesInHistoryLocation)\n this.state = this.stateFromUrl(this.props.runtime.history.location)\n }\n\n public render() {\n const { appControllers: { appName } } = this.state\n const { timeControllers: { startDate, endDate } } = this.state\n const appContextValue = {\n appControllers: this.state.appControllers,\n setAppControllers: this.setAppControllers,\n }\n const timeContextValue = {\n setTimeControllers: this.setTimeControllers,\n timeControllers: this.state.timeControllers,\n }\n\n return (\n <AppContext.Provider value={appContextValue}>\n <TimeContext.Provider value={timeContextValue} >\n <div className=\"flex flex-wrap w-100\">\n <div className=\"w-100\">\n <Controllers />\n </div>\n <div className=\"w-100\">\n {appName && startDate && endDate && Array.isArray(layoutContent)\n ? (\n <DataAnalysis layout={layoutContent} />\n ) : (\n <EmptyState title={this.props.intl.formatMessage({ id: 'console.empty.context.headline' })}>\n <FormattedMessage id=\"console.empty.context.explanation\" />\n </EmptyState>\n )\n }\n </div>\n </div>\n </TimeContext.Provider>\n </AppContext.Provider>\n )\n }\n\n private setAppControllers = (appControllers: AppController) => {\n if (appControllers.appName) {\n this.searchParams.set('appName', appControllers.appName)\n }\n if (appControllers.appVersion) {\n this.searchParams.set('appVersion', appControllers.appVersion)\n }\n if (appControllers.production) {\n this.searchParams.set('production', appControllers.production)\n }\n if (appControllers.region) {\n this.searchParams.set('region', appControllers.region)\n }\n\n if (!appControllers.appVersion && this.searchParams.has('appVersion')) {\n this.searchParams.delete('appVersion')\n }\n\n if (!appControllers.production && this.searchParams.has('production')) {\n this.searchParams.delete('production')\n }\n\n if (!appControllers.region && this.searchParams.has('region')) {\n this.searchParams.delete('region')\n }\n\n this.changeCurrentLocationInHistory()\n }\n\n private setTimeControllers = (timeControllers: TimeController) => {\n if (timeControllers.startDate) {\n this.searchParams.set('startDate', timeControllers.startDate.toString())\n }\n if (timeControllers.endDate) {\n this.searchParams.set('endDate', timeControllers.endDate.toString())\n }\n if (timeControllers.mode) {\n this.searchParams.set('mode', timeControllers.mode)\n }\n\n this.changeCurrentLocationInHistory()\n }\n\n private changeCurrentLocationInHistory = () => {\n const { runtime: { history } } = this.props\n const newRelativePathQuery = history.location.pathname + '?' + this.searchParams.toString()\n history.push(newRelativePathQuery)\n }\n\n private listenChangesInHistoryLocation = (location: Location<any>) => {\n this.setState(this.stateFromUrl(location))\n }\n\n private stateFromUrl = (location: Location<any>) => {\n this.searchParams = new URLSearchParams(location.search)\n const startDate = this.searchParams.get('startDate')\n const endDate = this.searchParams.get('endDate')\n const mode = this.searchParams.get('mode')\n return {\n appControllers: {\n appName: this.searchParams.get('appName') || '',\n appVersion: this.searchParams.get('appVersion') || '',\n production: this.searchParams.get('production') || '',\n region: this.searchParams.get('region') || '',\n },\n timeControllers: {\n endDate: endDate ? new Date(endDate) : undefined,\n mode: mode as TimeRange,\n startDate: startDate ? new Date(startDate) : undefined,\n },\n }\n }\n}\n\nexport default withRuntimeContext(injectIntl(Metrics))\n\n```"
}
] |
code_console_83b5bd66
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Contexts/TimeContext.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n\ninterface TimeContextInterface {\n timeControllers: TimeController\n setTimeControllers: SetTimeControllers\n}\n\n\nexport const TimeContext = React.createContext<TimeContextInterface>({\n setTimeControllers: (timeControllers: TimeController) => undefined,\n timeControllers: {\n endDate: new Date(),\n mode: undefined,\n startDate: new Date(),\n },\n})\n\n\n```"
}
] |
code_console_c44b6637
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Contexts/AppContext.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n\ninterface AppContextInterface {\n appControllers: AppController\n setAppControllers: SetAppControllers\n}\n\n\nexport const AppContext = React.createContext<AppContextInterface>({\n appControllers: {\n appName: '',\n appVersion: '',\n production: 'true',\n region: 'Any',\n },\n setAppControllers: (appControllers: AppController) => undefined,\n})\n\n```"
}
] |
code_console_a22b975a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { map, reject } from 'ramda'\nimport React from 'react'\nimport { PageBlock } from 'vtex.styleguide'\n\nimport { getRangeStep, isNilOrEmpty } from '../../../common/dataAnalysis'\nimport { AppContext } from '../Contexts/AppContext'\nimport { TimeContext } from '../Contexts/TimeContext'\n\n\ninterface Props {\n layout: any[]\n}\n\n\nconst DataAnalysis: React.SFC<Props> = (props) => {\n const setAppParams = (metricParams: object, appControllers: AppController) => {\n return reject(isNilOrEmpty, {\n ...metricParams,\n appName: appControllers.appName,\n appVersion: appControllers.appVersion,\n production: appControllers.production,\n region: appControllers.region,\n })\n }\n\n const setTimeRange = (metricParams: object, timeControllers: TimeController, chartType: string) => {\n return reject(isNilOrEmpty, {\n ...metricParams,\n from: timeControllers.startDate,\n interval: (chartType === 'BarChart') ? '' : getRangeStep(timeControllers.startDate!, timeControllers.endDate!),\n to: timeControllers.endDate,\n })\n }\n\n const { layout } = props\n\n return (\n <AppContext.Consumer>\n {({ appControllers }) => (\n <TimeContext.Consumer>\n {({ timeControllers }) => (\n <div className=\"flex flex-wrap mt5 w-100\" >\n {\n map(\n (chartDescription) => {\n const {\n ChartComponent,\n chartType,\n id,\n storedash: {\n name,\n },\n } = chartDescription\n let {\n storedash: {\n metricParams,\n },\n } = chartDescription\n\n metricParams = setAppParams(metricParams, appControllers)\n metricParams = setTimeRange(metricParams, timeControllers, chartType)\n\n return (\n <div className=\"w-33 pa4\">\n <PageBlock key={id} variation=\"full\">\n <ChartComponent name={name} metricParams={metricParams} />\n </PageBlock>\n </div>\n )\n }, layout)\n }\n </div>\n )}\n </TimeContext.Consumer>\n )}\n </AppContext.Consumer>\n )\n}\n\nexport default DataAnalysis\n\n\n```"
}
] |
code_console_db1aab4a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Button, PageBlock } from 'vtex.styleguide'\n\nimport { FormattedMessage, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { TimeContext } from '../Contexts/TimeContext'\nimport AppControllers from './AppControllers'\nimport TimeControllers from './TimeControllers'\n\n\nconst Controllers: React.SFC<InjectedIntlProps> = (props) => {\n const { intl } = props\n\n return (\n <PageBlock\n title={intl.formatMessage({ id: 'console.context' })}\n variation=\"half\"\n >\n <AppControllers />\n <TimeContext.Consumer>\n {({ timeControllers, setTimeControllers }) => (\n <TimeControllers\n timeControllers={timeControllers}\n setTimeControllers={setTimeControllers}\n />\n )}\n </TimeContext.Consumer>\n </PageBlock>\n )\n}\n\nexport default injectIntl(Controllers)\n\n```"
}
] |
code_console_a5af6bec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/Charts/CpuUsageLineChart.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'\nimport { withRuntimeContext } from 'render'\nimport { Spinner } from 'vtex.styleguide'\n\nimport { CHART_PROPERTIES } from '../../../../common/constants'\nimport { getFormattedTime, getStepModifier } from '../../../../common/dataAnalysis'\nimport dataQuery from '../../../../graphql/data.graphql'\nimport BlockTitle from '../CustomElements/BlockTitle'\nimport CustomTooltip from '../CustomElements/CustomTooltip'\nimport CustomYAxisTick from '../CustomElements/CustomYAxisTick'\n\n\ninterface Props extends InjectedIntlProps {\n name: string\n metricParams: any\n}\n\n\nconst CpuUsageLineChart: React.SFC<Props> = (props) => {\n const { name, metricParams, intl } = props\n\n return (\n <Fragment>\n <BlockTitle title={intl.formatMessage({ id: 'console.cpuUsage.lineChart' })} />\n\n <Query query={dataQuery} ssr={false} variables={{ name, params: metricParams }} >\n {({ loading, error, data: { data: rawChartData } }) => {\n let chartData: any\n const stepModifier = getStepModifier(metricParams)\n\n if (!loading) {\n chartData = JSON.parse(rawChartData)\n console.log({chartData})\n }\n\n return (\n loading ? (\n <Spinner />\n ) : (\n <ResponsiveContainer\n width={CHART_PROPERTIES.width}\n height={CHART_PROPERTIES.height}\n >\n <LineChart data={chartData}>\n <CartesianGrid strokeDasharray=\"3 3\" />\n <XAxis\n dataKey=\"date\"\n tickFormatter={(rawDate: string) => getFormattedTime(rawDate, intl, stepModifier) }\n />\n <YAxis\n type=\"number\"\n tick={<CustomYAxisTick name=\"cpuUsageLineChart\" />}\n />\n <Legend />\n <Tooltip content={<CustomTooltip name=\"cpuUsageLineChart\" stepModifier={stepModifier} />} />\n <Line name=\"system\" type=\"monotone\" dataKey=\"summary.system\" stroke=\"Green\" />\n <Line name=\"user\" type=\"monotone\" dataKey=\"summary.user\" stroke=\"Navy\" />\n </LineChart>\n </ResponsiveContainer>\n )\n )\n }}\n </Query>\n </Fragment>\n )\n}\n\nexport default withRuntimeContext(injectIntl(CpuUsageLineChart))\n\n```"
}
] |
code_console_a4c981a3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/Charts/LatencyLineChart.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { CartesianGrid, Legend, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'\nimport { Spinner } from 'vtex.styleguide'\n\nimport { CHART_PROPERTIES } from '../../../../common/constants'\nimport { getFormattedTime, getStepModifier } from '../../../../common/dataAnalysis'\nimport dataQuery from '../../../../graphql/data.graphql'\nimport BlockTitle from '../CustomElements/BlockTitle'\nimport CustomTooltip from '../CustomElements/CustomTooltip'\nimport CustomYAxisTick from '../CustomElements/CustomYAxisTick'\n\n\ninterface Props extends InjectedIntlProps {\n name: string\n metricParams: any\n}\n\n\nconst LatencyLineChart: React.SFC<Props> = (props) => {\n const { name, metricParams, intl } = props\n\n return (\n <Fragment>\n <BlockTitle title={intl.formatMessage({ id: 'console.latency.lineChart' })} />\n\n <Query query={dataQuery} ssr={false} variables={{ name, params: metricParams }} >\n {({ loading, data: { data: rawChartData } }) => {\n let chartData: any\n const stepModifier = getStepModifier(metricParams)\n\n if (!loading) {\n chartData = JSON.parse(rawChartData)\n }\n\n return (\n loading ? (\n <Spinner />\n ) : (\n <ResponsiveContainer\n width={CHART_PROPERTIES.width}\n height={CHART_PROPERTIES.height}\n >\n <LineChart data={chartData}>\n <CartesianGrid strokeDasharray=\"3 3\" />\n <XAxis\n dataKey=\"date\"\n tickFormatter={(rawDate: string) => getFormattedTime(rawDate, intl, stepModifier) }\n />\n <YAxis\n type=\"number\"\n tick={<CustomYAxisTick name=\"latencyLineChart\" />}\n />\n <Legend />\n <Tooltip content={<CustomTooltip name=\"latencyLineChart\" stepModifier={stepModifier} />} />\n {/* { this.drawLatencyLine() } */}\n </LineChart>\n </ResponsiveContainer>\n )\n )\n }}\n </Query>\n </Fragment>\n )\n}\n\nexport default injectIntl(LatencyLineChart)\n\n```"
}
] |
code_console_03e3fadd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/Charts/MemoryUsageLineChart.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'\nimport { Spinner } from 'vtex.styleguide'\n\nimport { CHART_PROPERTIES } from '../../../../common/constants'\nimport { getFormattedTime, getStepModifier } from '../../../../common/dataAnalysis'\nimport dataQuery from '../../../../graphql/data.graphql'\nimport BlockTitle from '../CustomElements/BlockTitle'\nimport CustomTooltip from '../CustomElements/CustomTooltip'\nimport CustomYAxisTick from '../CustomElements/CustomYAxisTick'\n\n\ninterface Props extends InjectedIntlProps {\n name: string\n metricParams: any\n}\n\nconst MemoryUsageLineChart: React.SFC<Props> = (props) => {\n const { name, metricParams, intl } = props\n\n return (\n <Fragment>\n <BlockTitle title={intl.formatMessage({ id: 'console.memoryUsage.lineChart' })} />\n\n <Query query={dataQuery} ssr={false} variables={{ name, params: metricParams }} >\n {({ loading, data: { data: rawChartData } }) => {\n let chartData: any\n const stepModifier = getStepModifier(metricParams)\n\n if (!loading) {\n chartData = JSON.parse(rawChartData)\n console.log({chartData})\n }\n\n return (\n loading ? (\n <Spinner />\n ) : (\n <ResponsiveContainer\n width={CHART_PROPERTIES.width}\n height={CHART_PROPERTIES.height}\n >\n <LineChart data={chartData}>\n <CartesianGrid strokeDasharray=\"3 3\" />\n <XAxis\n dataKey=\"date\"\n tickFormatter={(rawDate: string) => getFormattedTime(rawDate, intl, stepModifier) }\n />\n <YAxis\n type=\"number\"\n tick={<CustomYAxisTick name=\"memoryUsageLineChart\" />}\n />\n <Legend />\n <Tooltip content={<CustomTooltip name=\"memoryUsageLineChart\" stepModifier={stepModifier} />} />\n <Line name=\"external\" type=\"monotone\" dataKey=\"summary.external\" stroke=\"Green\" />\n <Line name=\"heapUsed\" type=\"monotone\" dataKey=\"summary.heapUsed\" stroke=\"Navy\" />\n <Line name=\"heapTotal\" type=\"monotone\" dataKey=\"summary.heapTotal\" stroke=\"Maroon\" />\n <Line name=\"rss\" type=\"monotone\" dataKey=\"summary.rss\" stroke=\"Orange\" />\n </LineChart>\n </ResponsiveContainer>\n )\n )\n }}\n </Query>\n </Fragment>\n )\n}\n\nexport default injectIntl(MemoryUsageLineChart)\n\n```"
}
] |
code_console_47cb02d3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/Charts/StatusCodeBarChart.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'\nimport { Spinner } from 'vtex.styleguide'\n\nimport { CHART_PROPERTIES, colors } from '../../../../common/constants'\nimport { getStepModifier } from '../../../../common/dataAnalysis'\nimport dataQuery from '../../../../graphql/data.graphql'\nimport BlockTitle from '../CustomElements/BlockTitle'\nimport CustomTooltip from '../CustomElements/CustomTooltip'\nimport CustomYAxisTick from '../CustomElements/CustomYAxisTick'\n\n\ninterface DataStatusCode {\n httpStatus: number\n count: number\n}\n\ninterface Props extends InjectedIntlProps {\n name: string\n metricParams: any\n}\n\n\nconst StatusCodeBarChart: React.SFC<Props> = (props) => {\n const { name, metricParams, intl } = props\n\n return (\n <Fragment>\n <BlockTitle title={intl.formatMessage({ id: 'console.statusCode.barChart' })} />\n\n <Query query={dataQuery} ssr={false} variables={{ name, params: metricParams }} >\n {({ loading, data: { data: rawChartData } }) => {\n let chartData: any\n const stepModifier = getStepModifier(metricParams)\n\n if (!loading) {\n chartData = JSON.parse(rawChartData)\n console.log({chartData})\n }\n\n return (\n loading ? (\n <Spinner />\n ) : (\n <ResponsiveContainer\n width={CHART_PROPERTIES.width}\n height={CHART_PROPERTIES.height}\n >\n <BarChart data={chartData} >\n <CartesianGrid strokeDasharray=\"3 3\" />\n <XAxis dataKey=\"key.httpStatus\" />\n <YAxis\n type=\"number\"\n tick={<CustomYAxisTick name=\"statusCodeBarChart\" />}\n />\n <Tooltip content={<CustomTooltip name=\"statusCodeBarChart\" stepModifier={stepModifier} />} />\n <Bar name=\"count\" dataKey=\"summary.count\" >\n {\n chartData.map((entry: DataStatusCode, index: number) => (\n <Cell key={`cell-${index}`} fill={colors[index % 20]} />\n ))\n }\n </Bar>\n </BarChart>\n </ResponsiveContainer>\n )\n )\n }}\n </Query>\n </Fragment>\n )\n}\n\nexport default injectIntl(StatusCodeBarChart)\n\n```"
}
] |
code_console_7b678c5a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/Charts/StatusCodeLineChart.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'\nimport { withRuntimeContext } from 'render'\nimport { Spinner } from 'vtex.styleguide'\n\nimport { CHART_PROPERTIES, colors } from '../../../../common/constants'\nimport { getFormattedTime, getStepModifier, mapIndexed } from '../../../../common/dataAnalysis'\nimport dataQuery from '../../../../graphql/data.graphql'\nimport BlockTitle from '../CustomElements/BlockTitle'\nimport CustomTooltip from '../CustomElements/CustomTooltip'\nimport CustomYAxisTick from '../CustomElements/CustomYAxisTick'\n\n\ninterface Props extends InjectedIntlProps {\n name: string\n metricParams: any\n}\n\nconst StatusCodeLineChart: React.SFC<Props> = (props) => {\n const { name, metricParams, intl } = props\n\n return (\n <Fragment>\n <BlockTitle title={intl.formatMessage({ id: 'console.statusCode.lineChart' })} />\n\n <Query query={dataQuery} ssr={false} variables={{ name, params: metricParams }} >\n {({ loading, error, data: { data: rawChartData } }) => {\n let chartData: any\n const stepModifier = getStepModifier(metricParams)\n\n if (!loading) {\n chartData = JSON.parse(rawChartData)\n }\n\n return (\n loading ? (\n <Spinner />\n ) : (\n <ResponsiveContainer\n width={CHART_PROPERTIES.width}\n height={CHART_PROPERTIES.height}\n >\n <LineChart>\n <CartesianGrid strokeDasharray=\"3 3\" />\n <XAxis\n dataKey=\"label\"\n allowDuplicatedCategory={false}\n tickFormatter={(rawDate: string) => getFormattedTime(rawDate, intl, stepModifier)}\n />\n <YAxis\n type=\"number\"\n dataKey=\"value\"\n tick={<CustomYAxisTick name=\"statusCodeLineChart\" />}\n />\n <Legend />\n <Tooltip\n content={<CustomTooltip name=\"statusCodeLineChart\" stepModifier={stepModifier} />}\n />\n {\n mapIndexed(\n (chartLine: any, index: number) => (\n <Line\n isAnimationActive={false}\n dataKey=\"value\"\n data={chartLine.data}\n name={chartLine.name}\n key={chartLine.name}\n stroke={colors[index % 20]}\n />\n ), chartData)\n }\n </LineChart>\n </ResponsiveContainer>\n )\n )\n }}\n </Query>\n </Fragment>\n )\n}\n\nexport default withRuntimeContext(injectIntl(StatusCodeLineChart))\n\n```"
}
] |
code_console_85643731
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/CustomYAxisTick.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\n\nimport { abbrNum, abbrPerc } from '../../../../common/dataAnalysis'\nimport RenderYAxisTick from './RenderYAxisTick'\n\n\ninterface Props extends InjectedIntlProps {\n name: string\n x?: number\n y?: number\n payload?: any\n toFixed?: number\n textAnchor?: string\n}\n\nconst CustomYAxisTick: React.SFC<Props> = (props) => {\n const { name, intl, x, y, payload, toFixed, textAnchor = 'middle' } = props\n let tickValue: string\n\n if (name === 'cpuUsageLineChart' || name === 'statusCodeLineChart') {\n tickValue = abbrPerc(payload.value, intl)\n } else {\n tickValue = abbrNum(toFixed ? payload.value.toFixed(toFixed) : payload.value, 0)\n }\n\n return (\n <RenderYAxisTick\n tickValue={tickValue}\n x={x}\n y={y}\n textAnchor={textAnchor}\n />\n )\n}\n\nexport default injectIntl(CustomYAxisTick)\n\n```"
}
] |
code_console_551dab2d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/RenderTooltip.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\n\n\ninterface Props extends InjectedIntlProps {\n label: string\n labelColor: string\n value: string\n}\n\n\nconst RenderTooltip: React.SFC<Props> = (props) => {\n const { label, labelColor, value } = props\n\n return (\n <div className=\"flex justify-between\" >\n <div className=\"pa2\" style={{ color: labelColor }} >\n {`${label}: `}\n </div>\n <div className=\"pa2\" >\n {value}\n </div>\n </div>\n )\n}\n\nexport default injectIntl(RenderTooltip)\n\n```"
}
] |
code_console_9ff051b8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/RenderYAxisTick.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n\ninterface Props {\n tickValue: string\n x?: number\n y?: number\n textAnchor?: string\n}\n\nconst RenderYAxisTick: React.SFC<Props> = (props) => {\n const { tickValue, x, y, textAnchor } = props\n return (\n <g transform={`translate(${x},${y})`}>\n <text x={0} y={0} dy={5} textAnchor={textAnchor} fill=\"#666\" className=\"f6\">\n {tickValue}\n </text>\n </g>\n )\n}\n\nexport default RenderYAxisTick\n\n```"
}
] |
code_console_51fef99a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/CustomTooltip.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { map } from 'ramda'\nimport React from 'react'\nimport { InjectedIntl, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { TooltipPayload, TooltipProps } from 'recharts'\nimport { PageBlock } from 'vtex.styleguide'\n\nimport { abbrPerc, getFormattedTime } from '../../../../common/dataAnalysis'\nimport RenderTooltip from './RenderTooltip'\n\n\ntype Props = InjectedIntlProps & TooltipProps & {\n name: string\n stepModifier: string\n}\n\n\nconst getLabel = (label: string | number, name: string, intl: InjectedIntl, stepModifier: string) => {\n if (name !== 'statusCodeBarChart') {\n return getFormattedTime(label, intl, stepModifier)\n }\n return label\n}\n\nconst getColor = (dataPoint: TooltipPayload) => {\n if (dataPoint.color === undefined) {\n return dataPoint.fill\n }\n return dataPoint.color\n}\n\nconst CustomTooltip: React.SFC<Props> = (props) => {\n const { active, intl, name, payload, label, stepModifier } = props\n\n return active\n ? (\n <PageBlock>\n <div className=\"t-small\">\n <div className=\"pa2\">\n {getLabel(label!, name, intl, stepModifier)}\n </div>\n {\n map((item) => {\n const itemLabelColor: string = getColor(item) || ''\n const itemLabel: string = String(item.name)\n let itemValue: string\n if (name === 'cpuUsageLineChart' || name === 'statusCodeLineChart') {\n itemValue = abbrPerc(item.value, intl)\n } else {\n itemValue = intl.formatNumber(Number(item.value))\n }\n return (\n <RenderTooltip\n key={itemLabel}\n label={itemLabel}\n labelColor={itemLabelColor}\n value={itemValue}\n />\n )\n }, payload || [])\n }\n </div>\n </PageBlock>\n ) : null\n}\n\nexport default injectIntl(CustomTooltip)\n\n```"
}
] |
code_console_9e36a48e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/CustomXAxisTick.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n\ninterface Props {\n x?: number\n y?: number\n payload?: any\n}\n\n\nconst CustomXAxisTick: React.SFC<Props> = (props) => {\n const { x, y, payload } = props\n return (\n <g transform={`translate(${x},${y})`}>\n <text x={0} y={0} dy={5} textAnchor=\"middle\" fill=\"#666\" className=\"f6\">\n {payload.value}\n </text>\n </g>\n )\n}\n\nexport default CustomXAxisTick\n\n```"
}
] |
code_console_295f661b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/DataAnalysis/CustomElements/BlockTitle.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n\ninterface Props {\n title: string\n}\n\n\nconst BlockTitle: React.SFC<Props> = ({ title }) => {\n return (<h3 className=\"block__title mt0\">{title}</h3>)\n}\n\nexport default BlockTitle\n\n```"
}
] |
code_console_36ceb559
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/TimeControllers/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component, Fragment } from 'react'\nimport { FormattedMessage, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Button, EmptyState, RadioGroup } from 'vtex.styleguide'\n\nimport { adjustEndDate, adjustStartDateHour, formattedDropdownOptions } from '../../../../common/utils'\nimport Absolute from './Absolute'\nimport Relative from './Relative'\nimport { timeControllerOptions } from './utils'\n\n\ninterface Props extends InjectedIntlProps {\n timeControllers: TimeController\n setTimeControllers: SetTimeControllers\n}\n\ninterface State {\n locale: string\n startDate: Date\n endDate: Date\n}\n\n\nclass TimeControllers extends Component<Props, State> {\n constructor(props: Props) {\n super(props)\n this.state = {\n endDate: this.props.timeControllers.endDate || new Date(),\n locale: 'pt-BR',\n startDate: this.props.timeControllers.startDate || adjustStartDateHour(),\n }\n }\n\n public render() {\n const { intl, timeControllers } = this.props\n const { locale, startDate, endDate } = this.state\n\n return (\n !timeControllers.mode\n ? (\n <Fragment>\n <EmptyState title={intl.formatMessage({ id: 'console.empty.time.range.headline' })}>\n <FormattedMessage id=\"console.empty.time.range.explanation\" />\n </EmptyState>\n <div className=\"pa4 mh2 flex justify-end\">\n <Button\n variation=\"primary\"\n size=\"small\"\n onClick={this.handleOnClickMode}\n >\n <FormattedMessage id=\"console.button.set.time.range\" />\n </Button>\n </div>\n </Fragment>\n ) : (\n <div className=\"flex flex-row\">\n <div className=\"pa1 mr6\">\n <RadioGroup\n name=\"timeController\"\n options={formattedDropdownOptions(timeControllerOptions, intl)}\n value={timeControllers.mode}\n onChange={this.handleOnChangeMode}\n />\n </div>\n <div className=\"flex items-center flex-wrap w-100\">\n {timeControllers.mode === 'absolute'\n ? (\n <Absolute\n startDate={startDate}\n endDate={endDate}\n handleStartDate={this.setStartDate}\n handleEndDate={this.setEndDate}\n locale={locale}\n />\n ) : (\n <Relative\n startDate={startDate}\n endDate={endDate}\n handleStartDate={this.setStartDate}\n handleEndDate={this.setEndDate}\n />\n )\n }\n <div className=\"content-end pa4 pt7 mr1 mh4\">\n <Button\n variation=\"primary\"\n size=\"small\"\n disabled={!this.isButtonActive}\n onClick={this.handleOnClickTimeControllers}\n >\n <FormattedMessage id=\"console.button.apply.time.range\" />\n </Button>\n </div>\n </div>\n </div>\n )\n )\n }\n\n private setStartDate = (startDate: Date) => {\n this.setState({ startDate })\n }\n\n private setEndDate = (endDate: Date) => {\n this.setState({ endDate: adjustEndDate(endDate) })\n }\n\n private handleOnClickMode = () => {\n this.props.setTimeControllers({\n ...this.props.timeControllers,\n mode: 'absolute',\n })\n }\n\n private handleOnChangeMode = (e: React.ChangeEvent<HTMLInputElement>) => {\n this.props.setTimeControllers({\n ...this.props.timeControllers,\n mode: e.currentTarget\n ? e.currentTarget.value as TimeRange\n : 'absolute',\n })\n }\n\n private handleOnClickTimeControllers = () => {\n this.props.setTimeControllers({\n ...this.props.timeControllers,\n endDate: this.state.endDate,\n startDate: this.state.startDate,\n })\n }\n\n private isButtonActive = () => {\n const startDate = this.state.startDate\n const endDate = this.state.endDate\n const currentTime = new Date()\n return (startDate && endDate &&\n startDate <= endDate &&\n endDate <= currentTime)\n }\n}\n\nexport default injectIntl(TimeControllers)\n\n```"
}
] |
code_console_15f0682d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/TimeControllers/utils.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Option } from '../../../../common/utils'\n\n\nexport const timeControllerOptions: Option[] = [\n { value: 'absolute', label: 'console.time.controller.absolute' },\n { value: 'relative', label: 'console.time.controller.relative' },\n]\n\n```"
}
] |
code_console_f08b88d7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/AppControllers/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport AppNamePicker from './AppNamePicker'\nimport EnvPicker from './EnvPicker'\nimport RegionPicker from './RegionPicker'\nimport VersionInput from './VersionInput'\n\n\nconst AppControllers = () => {\n return (\n <div className=\"flex br4 bg-base flex-wrap w-100 pa2\">\n <div className=\"pa4\">\n <AppNamePicker />\n </div>\n <div className=\"pa4\">\n <VersionInput />\n </div>\n <div className=\"pa4\">\n <RegionPicker />\n </div>\n <div className=\"pa4\">\n <EnvPicker />\n </div>\n </div>\n )\n}\n\nexport default AppControllers\n\n```"
}
] |
code_console_1c7980d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/AppControllers/EnvPicker.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { map } from 'ramda'\nimport React from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Dropdown } from 'vtex.styleguide'\n\nimport { formattedDropdownOptions } from '../../../../common/utils'\nimport { AppContext } from '../../Contexts/AppContext'\n\n\nconst options = [\n {\n label: 'console.any',\n value: '',\n },\n {\n label: 'console.envPicker.production',\n value: 'true',\n },\n {\n label: 'console.envPicker.development',\n value: 'false',\n },\n]\n\n\nconst EnvPicker: React.SFC<InjectedIntlProps> = ({ intl }) => {\n return (\n <AppContext.Consumer>\n {({ appControllers, setAppControllers }) => (\n <Dropdown\n value={appControllers.production}\n label={intl.formatMessage({ id: 'console.app.environment' })}\n options={formattedDropdownOptions(options, intl)}\n onChange={(_: Event, isProduction: string) => setAppControllers({\n ...appControllers,\n production: isProduction,\n })}\n />\n )}\n </AppContext.Consumer>\n )\n}\n\nexport default injectIntl(EnvPicker)\n\n```"
}
] |
code_console_d7687d27
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/AppControllers/VersionInput.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { any } from 'ramda'\nimport React, { Component } from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport * as semver from 'semver'\nimport { Input } from 'vtex.styleguide'\n\nimport { getAppVersion } from '../../../../common/utils'\nimport { AppContext } from '../../Contexts/AppContext'\n\n\ninterface State {\n inputIsNotSemver: boolean\n}\n\n\nconst semverRangesRegex = [\n /([0-9])+\\.x/,\n /([0-9])+\\.([0-9])+\\.x/,\n /\\bv?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[\\da-z-]+(?:\\.[\\da-z-]+)*)?(?:\\+[\\da-z-]+(?:\\.[\\da-z-]+)*)?\\b/,\n]\n\nconst isValidVersion = (version: string) => any((regex: RegExp) => regex.test(version), semverRangesRegex)\n\nclass VersionInput extends Component<InjectedIntlProps, State> {\n constructor(props: InjectedIntlProps) {\n super(props)\n this.state = {\n inputIsNotSemver: false,\n }\n }\n\n public setStateAsync(state: State) {\n return new Promise((resolve) => {\n this.setState(state, resolve)\n })\n }\n\n public render() {\n return (\n <AppContext.Consumer>\n {({ appControllers, setAppControllers }) => (\n <Input\n placeholder={appControllers.appVersion || 'Ex: 1.0.x'}\n label={this.props.intl.formatMessage({ id: 'console.app.version' })}\n onChange={(event: any) => this.parseInputAndSetState(event.target.value, appControllers, setAppControllers)}\n errorMessage={this.state.inputIsNotSemver ? 'Version is not in the SemVer spec' : ''}\n />\n )}\n </AppContext.Consumer>\n )\n }\n\n private parseInputAndSetState = (version: string, appControllers: AppController, setAppControllers: SetAppControllers) => {\n const isValid = version.length === 0 || isValidVersion(version)\n if (!isValid) {\n this.setState({ inputIsNotSemver: true })\n } else {\n this.setState(\n { inputIsNotSemver: false },\n () => this.updateAppControllers(version, appControllers, setAppControllers)\n )\n }\n }\n\n private updateAppControllers = (version: string, appControllers: AppController, setAppControllers: SetAppControllers) => {\n let chosenMajor = ''\n let chosenMinor = ''\n let chosenPatch = ''\n try {\n const { major, minor, patch } = semver.parse(version) as any\n chosenMajor = major\n chosenMinor = minor\n chosenPatch = patch\n } catch (err) {\n const [major, minor, patch] = version.replace('x', '').split('.')\n chosenMajor = major\n chosenMinor = minor\n chosenPatch = patch\n }\n\n const appVersion = getAppVersion(String(chosenMajor), String(chosenMinor), String(chosenPatch))\n setAppControllers({\n ...appControllers,\n appVersion,\n })\n }\n}\n\nexport default injectIntl(VersionInput)\n\n```"
}
] |
code_console_a2ca11f9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/AppControllers/AppNamePicker.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Query } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Dropdown } from 'vtex.styleguide'\n\nimport { dropdownOptions } from '../../../../common/utils'\nimport appsQuery from '../../../../graphql/apps.graphql'\nimport { AppContext } from '../../Contexts/AppContext'\n\n\nconst AppNamePicker: React.SFC<InjectedIntlProps> = ({ intl }) => {\n return (\n <AppContext.Consumer>\n {({ appControllers, setAppControllers }) => (\n <Query query={appsQuery} ssr={false}>\n {({ loading, data: { appsWithStats } }) => !loading && appsWithStats &&\n <Dropdown\n value={appControllers.appName}\n label={intl.formatMessage({ id: 'console.available.apps' })}\n options={dropdownOptions(appsWithStats)}\n onChange={(_: Event, appName: string) => setAppControllers({\n ...appControllers,\n appName,\n })}\n />\n }\n </Query>\n )}\n </AppContext.Consumer>\n )\n}\n\nexport default injectIntl(AppNamePicker)\n\n```"
}
] |
code_console_5d035612
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/AppControllers/RegionPicker.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { map } from 'ramda'\nimport React from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Dropdown } from 'vtex.styleguide'\n\nimport { formattedDropdownOptions } from '../../../../common/utils'\nimport { AppContext } from '../../Contexts/AppContext'\n\n\nconst options = [\n {\n label: 'console.any',\n value: '',\n },\n {\n label: 'East-1',\n value: 'aws-us-east-1',\n },\n {\n label: 'East-2',\n value: 'aws-us-east-2',\n },\n]\n\n\nconst RegionPicker: React.SFC<InjectedIntlProps> = ({ intl }) => {\n return (\n <AppContext.Consumer>\n {({ appControllers, setAppControllers }) => (\n <Dropdown\n value={appControllers.region}\n label={intl.formatMessage({ id: 'console.app.region' })}\n options={formattedDropdownOptions(options, intl)}\n onChange={(_: Event, region: string) => setAppControllers({\n ...appControllers,\n region,\n })}\n />\n )}\n </AppContext.Consumer>\n )\n}\n\nexport default injectIntl(RegionPicker)\n\n```"
}
] |
code_console_738fd433
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/TimeControllers/Relative/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Dropdown, NumericStepper } from 'vtex.styleguide'\n\nimport { adjustStartDate, formattedDropdownOptions } from '../../../../../common/utils'\nimport { EventWithValue } from '../../../../../typings/events'\nimport { earliestModifierOptions } from './utils'\n\n\ntype EarliestModifier = 'Seconds Ago' | 'Minutes Ago' | 'Hours Ago' | 'Days Ago' | 'Months Ago' | 'Years Ago'\n\ninterface Props extends InjectedIntlProps {\n startDate: Date\n endDate: Date\n handleStartDate: (date: Date) => void\n handleEndDate: (date: Date) => void\n}\n\ninterface State {\n earliestSize: number\n earliestModifier: EarliestModifier\n}\n\n\nclass Relative extends Component<Props, State> {\n constructor(props: Props) {\n super(props)\n this.state = {\n earliestModifier: 'Days Ago',\n earliestSize: 1,\n }\n this.constructTimeRange()\n }\n\n public componentDidUpdate(_: Props, prevState: State) {\n if ((this.state.earliestSize !== prevState.earliestSize) || (this.state.earliestModifier !== prevState.earliestModifier)) {\n this.constructTimeRange()\n }\n }\n\n public render() {\n const { intl } = this.props\n\n return (\n <div className=\"flex flex-colunm items-end pa4 mh0\">\n <NumericStepper\n label={this.props.intl.formatMessage({ id: 'console.time.controller.relative.earliest' })}\n size=\"small\"\n value={this.state.earliestSize}\n onChange={this.handleEarliestSize}\n />\n <Dropdown\n size=\"small\"\n options={formattedDropdownOptions(earliestModifierOptions, intl)}\n value={this.state.earliestModifier}\n onChange={this.handleEarliestModifier}\n />\n </div>\n )\n }\n\n private handleEarliestSize = (e: EventWithValue) => {\n this.setState({ earliestSize: e.value })\n }\n\n private handleEarliestModifier = (e: Event, earliestModifier: EarliestModifier) => {\n this.setState({ earliestModifier })\n }\n\n private constructTimeRange = () => {\n const startDate: Date = adjustStartDate(this.state.earliestSize, this.state.earliestModifier)\n const endDate: Date = new Date()\n\n this.props.handleStartDate(startDate)\n this.props.handleEndDate(endDate)\n }\n}\n\nexport default injectIntl(Relative)\n\n```"
}
] |
code_console_c04e4249
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/TimeControllers/Relative/utils.ts from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Option } from '../../../../../common/utils'\n\n\nexport const earliestModifierOptions: Option[] =[\n { value: 'Seconds Ago', label: 'console.time.controller.relative.earliestModifier.seconds.ago' },\n { value: 'Minutes Ago', label: 'console.time.controller.relative.earliestModifier.minutes.ago' },\n { value: 'Hours Ago', label: 'console.time.controller.relative.earliestModifier.hours.ago' },\n { value: 'Days Ago', label: 'console.time.controller.relative.earliestModifier.days.ago' },\n { value: 'Months Ago', label: 'console.time.controller.relative.earliestModifier.months.ago' },\n { value: 'Years Ago', label: 'console.time.controller.relative.earliestModifier.years.ago' },\n]\n\n```"
}
] |
code_console_2a9039f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of console/react/components/Metrics/Controllers/TimeControllers/Absolute/index.tsx from the console VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { DatePicker } from 'vtex.styleguide'\n\n\ninterface Props extends InjectedIntlProps {\n locale: string\n startDate: Date\n endDate: Date\n handleStartDate: (date: Date) => void\n handleEndDate: (date: Date) => void\n}\n\n\nconst Absolute: React.SFC<Props> = (props) => {\n return (\n <div className=\"flex flex-wrap\">\n <Fragment>\n <div className=\"pa4 mh2\">\n <DatePicker\n name={'startDate'}\n label={props.intl.formatMessage({ id: 'console.date.picker.from' })}\n locale={props.locale}\n useTime={true}\n value={props.startDate}\n onChange={props.handleStartDate}\n />\n </div>\n <div className=\"pa4 mh2\">\n <DatePicker\n name={'endDate'}\n label={props.intl.formatMessage({ id: 'console.date.picker.to' })}\n locale={props.locale}\n useTime={true}\n value={props.endDate}\n onChange={props.handleEndDate}\n />\n </div>\n </Fragment>\n </div>\n\n )\n}\n\nexport default injectIntl(Absolute)\n\n```"
}
] |
code_facebook-domain-verification_7d061a55
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of facebook-domain-verification/docs/README.md from the facebook-domain-verification VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Facebook Domain Verification\n\nThe **Facebook Domain Verification** app sets the meta-tag containing the verification code into the `<head>` section of your website's homepage.\n\n\n\n## Before you begin\n\nAccess the [Facebook Business Settings](https://business.facebook.com/settings/owned-domains/) and log in to your account to check your domain verification code. Click the `Meta-tag Verification` tag and copy the code inside the content attribute.\n\n## Configuration\n\nYou can install the **Facebook Domain Verification** app in your account either via the App Store or the VTEX IO CLI.\n\n### Using VTEX App Store\n\n1. Access the **Apps** section in your account's Admin page and look for the Facebook Domain Verification box.\n2. Click the `Install` button. You should see a warning message requiring the necessary configurations. Scroll down and type in your verification code.\n4. Click `Save`.\n\n### Using VTEX IO CLI\n\n1. [Install](https://developers.vtex.com/docs/guides/vtex-io-documentation-installing-an-app) the `vtex.facebook-domain-verification@1.x` app.\n2. Access the **Apps** section in your account's admin page and look for the `Facebook Domain Verification` box. Once you find it, click on the box.\n3. Fill in the domain verification code.\n4. Click `Save`.\n\n```"
}
] |
code_product-list_14ce8fc4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/hu.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"/ {unitMultiplier} {measurementUnit}.\",\n \"store/product-list.availableItems\": \"{quantity, plural, one {# termék érhető el} other {# termék érhető el}}\",\n \"store/product-list.unavailableItems\": \"{quantity, plural, one {# termék nem érhető el} other {# termék nem érhető el}}\",\n \"store/product-list.message.cantBeDelivered\": \"Ez a termék nem kézbesíthető a megadott címre.\",\n \"store/product-list.message.noLongerAvailable\": \"Ez a termék már nem érhető el.\",\n \"store/product-list.message.remove\": \"eltávolítás\",\n \"store/product-list.quantity-selector.remove\": \"Eltávolítás\",\n \"store/product-list.quantity-label\": \"{quantity} egység\",\n \"store/product-list.delete-button.default-label\": \"Termék eltávolítása\",\n \"store/product-list.priceChanged\": \"Módosítva\",\n \"store/product-list.priceOptions\": \"Árlehetőségek\",\n \"store/product-list.changePrice\": \"Ár módosítása\",\n \"store/product-list.revertToOriginal\": \"Visszaállítás ez eredetire\",\n \"store/product-list.originalPrice\": \"Eredeti ár\",\n \"store/product-list.changeTo\": \"Módosítás a következőre:\",\n \"store/product-list.manualPricePlaceholder\": \"Írja be a pénzbeli értéket\",\n \"store/product-list.applyManualPrice\": \"rendben\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"Ezt a terméket {unitMultiplier}{measurementUnit} kiadásokban értékesítik. Ezért a megadott mennyiség kerekítésre került: {roundedValue}{measurementUnit}.\",\n \"store/product-list.quantityStepper.label\": \"Termékmennyiség\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"Mennyiség növelése\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"Mennyiség csökkentése\"\n}\n\n```"
}
] |
code_product-list_515faec5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/el-GR.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"ανά {unitMultiplier} {measurementUnit}.\",\n \"store/product-list.availableItems\": \"{quantity, plural, one {# διαθέσιμο προϊόν} other {# διαθέσιμα προϊόντα}}\",\n \"store/product-list.unavailableItems\": \"{quantity, plural, one {# μη διαθέσιμο προϊόν} other {# μη διαθέσιμα προϊόντα}}\",\n \"store/product-list.message.cantBeDelivered\": \"Αυτό το προϊόν δεν μπορεί να παραδοθεί στην παρεχόμενη διεύθυνση.\",\n \"store/product-list.message.noLongerAvailable\": \"Αυτό το προϊόν δεν είναι πλέον διαθέσιμο.\",\n \"store/product-list.message.remove\": \"αφαίρεση\",\n \"store/product-list.quantity-selector.remove\": \"Αφαιρώ\",\n \"store/product-list.quantity-label\": \"{quantity} un.\",\n \"store/product-list.delete-button.default-label\": \"Αφαίρεση προϊόντος\",\n \"store/product-list.priceChanged\": \"Άλλαξε\",\n \"store/product-list.priceOptions\": \"Επιλογές τιμής\",\n \"store/product-list.changePrice\": \"Αλλαγή τιμής\",\n \"store/product-list.revertToOriginal\": \"Επιστροφή στο αρχικό\",\n \"store/product-list.originalPrice\": \"Αρχική τιμή\",\n \"store/product-list.changeTo\": \"Άλλαξε σε\",\n \"store/product-list.manualPricePlaceholder\": \"Πληκτρολογήστε μια χρηματική αξία\",\n \"store/product-list.applyManualPrice\": \"οκ\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"Αυτό το προϊόν πωλείται με κλάσματα του {unitMultiplier}{measurementUnit}. Δεδομένου αυτού, η εισαγόμενη ποσότητα έχει στρογγυλοποιηθεί σε {roundedValue}{measurementUnit}.\",\n \"store/product-list.quantityStepper.label\": \"Ποιότητα προϊόντος\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"Αύξηση ποσότητας\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"Μείωση ποσότητας\"\n}\n\n```"
}
] |
code_product-list_3ccd26e2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/nl.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"per {unitMultiplier} {measurementUnit}.\",\n \"store/product-list.availableItems\": \"{quantity, plural, one {# beschikbaar product} other {# beschikbare producten}}\",\n \"store/product-list.unavailableItems\": \"{quantity, plural, one {# niet beschikbaar product} other {# niet beschikbare producten}}\",\n \"store/product-list.message.cantBeDelivered\": \"Dit product kan niet worden geleverd op het opgegeven adres.\",\n \"store/product-list.message.noLongerAvailable\": \"Dit product is niet langer verkrijgbaar.\",\n \"store/product-list.message.remove\": \"verwijder\",\n \"store/product-list.quantity-selector.remove\": \"Verwijder\",\n \"store/product-list.quantity-label\": \"{quantity} un.\",\n \"store/product-list.delete-button.default-label\": \"Product verwijderen\",\n \"store/product-list.priceChanged\": \"Veranderd\",\n \"store/product-list.priceOptions\": \"Prijsopties\",\n \"store/product-list.changePrice\": \"Prijs wijzigen\",\n \"store/product-list.revertToOriginal\": \"Ga terug naar het origineel\",\n \"store/product-list.originalPrice\": \"Originele prijs\",\n \"store/product-list.changeTo\": \"Wijzigen naar\",\n \"store/product-list.manualPricePlaceholder\": \"Typ een monetaire waarde\",\n \"store/product-list.applyManualPrice\": \"ok\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"Dit product wordt verkocht met een fractie van {unitMultiplier}{measurementUnit}. Gegeven dat, de ingevoegde hoeveelheid is afgerond op {roundedValue}{measurementUnit}.\",\n \"store/product-list.quantityStepper.label\": \"Productaantal\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"Aantal verhogen\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"Aantal verlagen\"\n}\n\n```"
}
] |
code_product-list_cc80a232
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/it-IT.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"per {unitMultiplier} {measurementUnit}.\",\n \"store/product-list.availableItems\": \"{quantity, plural, one {# prodotto disponibile} other {# prodotti disponibili}}\",\n \"store/product-list.unavailableItems\": \"{quantity, plural, one {# prodotto non disponibile} other {# prodotti non disponibili}}\",\n \"store/product-list.message.cantBeDelivered\": \"Questo prodotto non può essere consegnalo presso l'indirizzo indicato.\",\n \"store/product-list.message.noLongerAvailable\": \"Questo prodotto non è più disponibile.\",\n \"store/product-list.message.remove\": \"rimuovi\",\n \"store/product-list.quantity-selector.remove\": \"Rimuovi\",\n \"store/product-list.quantity-label\": \"{quantity}.\",\n \"store/product-list.delete-button.default-label\": \"Rimuovi prodotto\",\n \"store/product-list.priceChanged\": \"Modificato\",\n \"store/product-list.priceOptions\": \"Opzioni di prezzo\",\n \"store/product-list.changePrice\": \"Modifica il prezzo\",\n \"store/product-list.revertToOriginal\": \"Ripristina l'originale\",\n \"store/product-list.originalPrice\": \"Prezzo originale\",\n \"store/product-list.changeTo\": \"Modifica in\",\n \"store/product-list.manualPricePlaceholder\": \"Inserisci una valuta\",\n \"store/product-list.applyManualPrice\": \"ok\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"Questo prodotto è venduto per frazioni di {unitMultiplier}{measurementUnit}. Per questo motivo, la quantità inserita è stata arrotondata a {roundedValue}{measurementUnit}.\",\n \"store/product-list.quantityStepper.label\": \"Quantità del prodotto\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"Aumenta la quantità\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"Riduci la quantità\"\n}\n\n```"
}
] |
code_product-list_7ada952a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/th-TH.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"ต่อ {unitMultiplier} {measurementUnit}\",\n \"store/product-list.availableItems\": \"ผลิตภัณฑ์ที่พร้อม {quantity, plural, one {# รายการ} other {# รายการ}}\",\n \"store/product-list.unavailableItems\": \"ผลิตภัณฑ์ที่ไม่พร้อม {quantity, plural, one {# รายการ} other {# รายการ}}\",\n \"store/product-list.message.cantBeDelivered\": \"ไม่สามารถจัดส่งผลิตภัณฑ์นี้ไปยังที่อยู่ที่ให้มา\",\n \"store/product-list.message.noLongerAvailable\": \"ผลิตภัณฑ์นี้ไม่มีจำหน่ายแล้ว\",\n \"store/product-list.message.remove\": \"ลบออก\",\n \"store/product-list.quantity-selector.remove\": \"ลบออก\",\n \"store/product-list.quantity-label\": \"{quantity} หน่วย\",\n \"store/product-list.delete-button.default-label\": \"ลบผลิตภัณฑ์ออก\",\n \"store/product-list.priceChanged\": \"เปลี่ยนแปลงแล้ว\",\n \"store/product-list.priceOptions\": \"ตัวเลือกราคา\",\n \"store/product-list.changePrice\": \"เปลี่ยนราคา\",\n \"store/product-list.revertToOriginal\": \"เปลี่ยนกลับเป็นค่าเดิม\",\n \"store/product-list.originalPrice\": \"ราคาเดิม\",\n \"store/product-list.changeTo\": \"เปลี่ยนเป็น\",\n \"store/product-list.manualPricePlaceholder\": \"พิมพ์จำนวนเงิน\",\n \"store/product-list.applyManualPrice\": \"ตกลง\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"ผลิตภัณฑ์นี้ขายทีละ {unitMultiplier} {measurementUnit} ดังนั้นจำนวนที่ใส่จะถูกปัดเป็น {roundedValue} {measurementUnit}\",\n \"store/product-list.quantityStepper.label\": \"จำนวนผลิตภัณฑ์\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"จำนวนเพิ่ม\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"จำนวนลด\"\n}\n\n```"
}
] |
code_product-list_e50e4f62
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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-list/messages/ja.json from the product-list VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/product-list.pricePerUnit\": \"{price} {perMeasurementUnit}\",\n \"store/product-list.pricePerUnit.measurementUnit\": \"{unitMultiplier} {measurementUnit} あたり。\",\n \"store/product-list.availableItems\": \"{quantity, plural, one {# 個の製品が在庫あり} other {# 個の製品が在庫あり}}\",\n \"store/product-list.unavailableItems\": \"{quantity, plural, one {# 個の製品が在庫切れ} other {# 個の製品が在庫切れ}}\",\n \"store/product-list.message.cantBeDelivered\": \"この製品は入力された住所に配送できません。\",\n \"store/product-list.message.noLongerAvailable\": \"この製品はもう在庫がありません。\",\n \"store/product-list.message.remove\": \"削除\",\n \"store/product-list.quantity-selector.remove\": \"削除\",\n \"store/product-list.quantity-label\": \"{quantity} un.\",\n \"store/product-list.delete-button.default-label\": \"製品を削除\",\n \"store/product-list.priceChanged\": \"変更済み\",\n \"store/product-list.priceOptions\": \"価格オプション\",\n \"store/product-list.changePrice\": \"価格を変更\",\n \"store/product-list.revertToOriginal\": \"元に戻す\",\n \"store/product-list.originalPrice\": \"元の価格\",\n \"store/product-list.changeTo\": \"変更\",\n \"store/product-list.manualPricePlaceholder\": \"金額を入力\",\n \"store/product-list.applyManualPrice\": \"oK\",\n \"store/product-list.quantitySelector.label\": \"{quantity} {measurementUnit}\",\n \"store/product-list.quantitySelector.maxValueLabel\": \"{quantity} {measurementUnit} +\",\n \"store/product-list.quantityUnitMultiplierMismatch\": \"この製品は {unitMultiplier}{measurementUnit} に分けて販売されます。その場合、挿入された数量は {roundedValue}{measurementUnit} に丸められています。\",\n \"store/product-list.quantityStepper.label\": \"製品の数量\",\n \"store/product-list.quantityStepper.increaseQuantity\": \"数量を増やす\",\n \"store/product-list.quantityStepper.decreaseQuantity\": \"数量を減らす\"\n}\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.