id
stringlengths
12
53
messages
listlengths
3
3
code_store-on-localhost_787a89c9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/blocks.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface ExtensionResult {\n treePath: string\n extension: any\n}\n\nexport const withStar = (treePath: string) => {\n const parts = treePath.split('/')\n parts[0] = '*'\n return parts.join('/')\n}\n\nconst createExtensions = (\n blockTreePath: string,\n extensionPath: string,\n bindingPath: string,\n outerNested: boolean,\n blocksTree: any,\n blocksMap: any,\n contentMap: any\n): ExtensionResult[] => {\n const result: ExtensionResult[] = []\n if (!blocksTree[blockTreePath]) {\n return result\n }\n\n const { blockIdMap, contentIdMap } = blocksTree[blockTreePath]\n const mappedBlockId =\n blockIdMap[extensionPath] ||\n blockIdMap[withStar(extensionPath)] ||\n blockIdMap['*']\n const block = blocksMap[mappedBlockId]\n const { blockId, after = [], around = [], before = [], blocks = [] } = block\n const blockContentMapId =\n contentIdMap[bindingPath] || contentIdMap[withStar(bindingPath)] || blockId\n const blockContentId = `${blockContentMapId}+${blockId}`\n\n const maybeContent = contentMap[blockContentId] ||\n contentMap[blockContentMapId] || { content: {}, contentIds: [] }\n const content = maybeContent.content || maybeContent\n const contentIds = maybeContent.contentIds || []\n\n const self = [\n {\n treePath: extensionPath,\n extension: {\n after: after.map(insertion => insertion.extensionPointId),\n around: around.map(insertion => insertion.extensionPointId),\n before: before.map(insertion => insertion.extensionPointId),\n blockId: block.originalBlockId || blockId,\n blocks: blocks,\n component: block.component,\n composition: block.composition,\n content,\n contentIds,\n context: block.context,\n hasContentSchema: block.hasContentSchema,\n preview: block.preview,\n props: block.props,\n render: block.render,\n title: block.title,\n track: block.track,\n },\n },\n ]\n\n const [afterExtensions, aroundExtensions, beforeExtensions] = [\n after,\n around,\n before,\n ].map(outer => {\n return outer.reduce((acc, { extensionPointId }) => {\n const outerExtensionPath = `${extensionPath}/${extensionPointId}`\n const outerResults = createExtensions(\n extensionPointId,\n outerExtensionPath,\n bindingPath,\n true,\n blocksTree,\n blocksMap,\n contentMap\n )\n acc.push(...outerResults)\n return acc\n }, [] as ExtensionResult[])\n })\n\n const innerExtensions = blocks.reduce((acc, { extensionPointId }) => {\n const innerBlockTreePath = `${blockTreePath}/${extensionPointId}`\n const innerExtensionPath = `${extensionPath}/${extensionPointId}`\n const innerBindingPath = outerNested\n ? bindingPath\n : `${bindingPath}/${extensionPointId}`\n const innerResults = createExtensions(\n innerBlockTreePath,\n innerExtensionPath,\n innerBindingPath,\n outerNested,\n blocksTree,\n blocksMap,\n contentMap\n )\n acc.push(...innerResults)\n return acc\n }, [] as ExtensionResult[])\n\n return result.concat(\n self,\n afterExtensions,\n aroundExtensions,\n beforeExtensions,\n innerExtensions\n )\n}\n\nexport const generateExtensions = (\n blocksTree: any,\n blocks: any,\n contentMap: any,\n page: any\n): any => {\n const extensions: any = {}\n const routeId = page.routeId\n const routeResult = createExtensions(\n routeId,\n routeId,\n routeId,\n false,\n blocksTree,\n blocks,\n contentMap\n )\n routeResult.forEach(eachResult => {\n extensions[eachResult.treePath] = eachResult.extension\n })\n\n return extensions\n}\n\n```" } ]
code_store-on-localhost_1157cee4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/components.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { uniqWith } from 'ramda'\n\nconst FILE_PATH_REX = /([^/]+?)(?:$|\\?)/ // https://regex101.com/r/joJ2p7/1\nconst FILE_EXT_REX = /(\\.min)?(\\.js|\\.css)/ // https://regex101.com/r/8vmjes/1\n\nconst uniqAsset = uniqWith<any, any>((a, b) => a.path === b.path)\n\nexport const traverseListOfComponents = (\n componentsData: any | Record<string, string[]>,\n componentsToTraverse: string[]\n) => {\n const allAssets = componentsToTraverse.reduce((acc, component) => {\n const assets = traverseComponent(componentsData, component, false)\n acc.push(...assets)\n return acc\n }, [] as any[])\n\n return uniqAsset(allAssets)\n}\n\nexport const traverseComponent = (\n components: any | Record<string, string[]>,\n component: string,\n isRoot = true\n): any[] => {\n const entry = components[component]\n const [app] = component.split('/')\n if (Array.isArray(entry)) {\n return entry.map(asset => {\n return { path: asset, app, name: assetName(asset) }\n })\n }\n const { dependencies, assets } = entry\n const assetsForDeps = dependencies.reduce(\n (acc, dependency) => {\n const depAssets = traverseComponent(components, dependency, false)\n return depAssets.concat(acc)\n },\n assets.map(asset => {\n return { path: asset, app, name: assetName(asset) }\n })\n )\n\n if (isRoot) {\n return uniqAsset(assetsForDeps)\n }\n return assetsForDeps\n}\n\nconst assetName = (asset: string) => {\n const baseNameMatch = FILE_PATH_REX.exec(asset)\n const baseName =\n baseNameMatch && baseNameMatch.length > 0 ? baseNameMatch[1] : ''\n const assetName = baseName.replace(FILE_EXT_REX, '')\n return assetName\n}\n\n```" } ]
code_store-on-localhost_5c3b557b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/treePath.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType, useContext, FC, useMemo } from 'react'\n\nconst relative = (parent: string, id: string) => id.replace(`${parent}/`, '')\n\nexport const escapeRegex = (s: string) =>\n s.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n\nexport const isDirectChild = (id: string, parent: string) => {\n return (\n id !== parent &&\n new RegExp(`^${escapeRegex(parent)}/[a-zA-Z0-9-_#]+$`).test(id)\n )\n}\n\nconst parseId = (id: string) => {\n const matches = /^(.*?)(\\d+)?$/.exec(id)\n\n if (matches === null) {\n return []\n }\n\n const [, text, numericText] = matches\n const numbericValue = numericText ? parseInt(numericText, 10) : 0\n return [text, numbericValue]\n}\n\nexport const getDirectChildren = (extensions: any, treePath: string) => {\n return Object.entries(extensions)\n .filter(\n ([id, extension]: any) => extension.component && isDirectChild(id, treePath)\n )\n .map(([id]) => relative(treePath, id))\n .sort((idA, idB) => {\n const [textA, numberA] = parseId(idA)\n const [textB, numberB] = parseId(idB)\n const [valueA, valueB] =\n textA === textB ? [numberA, numberB] : [textA, textB]\n\n return valueA < valueB ? -1 : 1\n })\n}\n\nexport const TreePathContext = React.createContext<TreePathProps>({\n treePath: '',\n})\nTreePathContext.displayName = 'TreePathContext'\n\nexport const TreePathContextProvider: FC<TreePathProps> = ({\n treePath,\n children,\n}) => {\n const value = useMemo(() => ({ treePath }), [treePath])\n return (\n <TreePathContext.Provider value={value}>\n {children}\n </TreePathContext.Provider>\n )\n}\nTreePathContextProvider.displayName = 'TreePathContextProvider'\n\nexport const useTreePath = () => {\n return useContext(TreePathContext)\n}\n\nexport interface TreePathProps {\n treePath: string\n}\n\nexport function withTreePath<TOriginalProps>(\n Component: ComponentType<TOriginalProps & TreePathProps>\n): ComponentType<TOriginalProps> {\n const WithTreePath = (props: TOriginalProps) => {\n const { treePath } = useTreePath()\n return <Component {...props} treePath={treePath} />\n }\n\n WithTreePath.displayName = `TreePath(${Component.displayName ||\n Component.name ||\n 'Component'})`\n WithTreePath.WrappedComponent = Component\n\n return hoistNonReactStatics<any, any>(\n WithTreePath,\n Component\n )\n}\n\n```" } ]
code_store-on-localhost_1d90d782
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/messages.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { pluck, zipObj } from 'ramda'\n\nexport const parseMessages = (messages: any[] | null) => {\n return messages && zipObj(pluck('key', messages), pluck('message', messages))\n}\n\n```" } ]
code_store-on-localhost_73e61bba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/assets.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport queryString from 'query-string'\nimport { getLoadedComponent } from './registerComponent'\nimport { isEnabled } from './flags'\n\nconst imageHost = isEnabled('VTEX_ASSETS_URL')\n ? 'vtexassets.com'\n : 'vteximg.com.br'\n\nfunction getExtension(path: string) {\n const adjPath = path.split('?')[0]\n const result = /\\.\\w+$/.exec(adjPath)\n return result ? result[0] : ''\n}\n\nconst isRelative = (path: string) => {\n return path && path[0] === '/' && path[1] !== '/'\n}\n\nexport const getVTEXImgHost = (account: string) => {\n return `https://${account}.${imageHost}`\n}\n\nconst getAbsoluteURL = (\n account: string,\n url: string,\n production: boolean,\n rootPath: string\n) => {\n if (!isRelative(url)) {\n return url\n }\n\n return production ? `${getVTEXImgHost(account)}${url}` : rootPath + url\n}\n\nclass ServerSideAssetLoadingError extends Error {\n public constructor() {\n super('Loading assets on server side rendering is not supported')\n }\n}\n\nfunction isAbsolute(path: string) {\n return path && !path.startsWith('/')\n}\n\nexport function addScriptToPage(src: string): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const script = document.createElement('script')\n script.onload = () => resolve()\n script.onerror = () => reject()\n script.async = false\n script.src = src\n if (isAbsolute(src)) {\n script.crossOrigin = 'anonymous'\n }\n document.head.appendChild(script)\n })\n}\n\nfunction addStyleToPage(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.type = 'text/css'\n link.rel = 'stylesheet'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n const overrideLink = document.getElementById('override_link_0')\n if (overrideLink) {\n document.head.insertBefore(link, overrideLink)\n } else {\n document.head.appendChild(link)\n }\n}\n\nconst updateHref = (linkElement: Element) => {\n const href = linkElement && linkElement.getAttribute('href')\n\n if (href) {\n const now = Date.now()\n const idPrefix = 'hot_reload_css'\n const modifiedHref = href.replace(\n /build(\\d)+/,\n `build${Math.round(now / 1000)}`\n )\n const newCssElement = document.createElement('link')\n const nextElementSibling = linkElement.nextElementSibling\n newCssElement.rel = 'stylesheet'\n newCssElement.type = 'text/css'\n newCssElement.href = modifiedHref\n newCssElement.id = idPrefix + now\n newCssElement.onload = function onLoadCb() {\n requestAnimationFrame(() => {\n if (\n nextElementSibling &&\n linkElement.parentNode &&\n nextElementSibling.id.indexOf(idPrefix) > -1\n ) {\n linkElement.parentNode.removeChild(nextElementSibling)\n }\n })\n }\n\n if (linkElement.parentNode) {\n linkElement.parentNode.insertBefore(newCssElement, nextElementSibling)\n }\n }\n}\n\nexport const hotReloadOverrides = () => {\n const linkElements = Array.from(document.querySelectorAll('.override_link'))\n linkElements.forEach(updateHref)\n}\n\nexport const hotReloadTachyons = () => {\n const linkElement = document.getElementById('style_link')\n if (linkElement) {\n updateHref(linkElement)\n }\n}\n\nfunction prefetchStyle(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.as = 'style'\n link.rel = 'prefetch'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n document.head.appendChild(link)\n}\n\nfunction prefetchScript(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.as = 'script'\n link.rel = 'prefetch'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n document.head.appendChild(link)\n}\n\nfunction getExistingScriptSrcs() {\n const paths: string[] = []\n for (let i = 0; i < document.scripts.length; i++) {\n const script = document.scripts.item(i)\n if (script !== null) {\n paths.push(script.src)\n }\n }\n return paths\n}\n\nfunction getExistingStyleHrefs() {\n const hrefs: string[] = []\n for (let i = 0; i < document.styleSheets.length; i++) {\n const stylesheet = document.styleSheets.item(i)\n if (stylesheet !== null) {\n const href = stylesheet.href\n if (href) {\n hrefs.push(href)\n }\n }\n }\n return hrefs\n}\n\nfunction getExistingPrefetchScriptLinks() {\n return getExistingPrefetchLinks('script')\n}\nfunction getExistingPrefetchStyleLinks() {\n return getExistingPrefetchLinks('style')\n}\n\nfunction getExistingPrefetchLinks(prefetchType: string[] | string) {\n const paths: string[] = []\n const links = document.getElementsByTagName('link')\n for (let i = 0; i < links.length; i++) {\n const item = links.item(i)\n if (item && item.rel === 'prefetch' && prefetchType.includes(item.as)) {\n paths.push(item.href)\n }\n }\n return paths\n}\n\nfunction assetOnList(path: string, assets: string[]) {\n return assets.some(asset => asset.indexOf(path) !== -1)\n}\n\nfunction isScript(path: string) {\n return getExtension(path) === '.js'\n}\n\nexport function shouldAddScriptToPage(\n path: string,\n scripts: string[] = getExistingScriptSrcs()\n) {\n return isScript(path) && !assetOnList(path, scripts)\n}\n\nexport function getLoadedImplementation<P = {}, S = {}>(component: string) {\n return getLoadedComponent(component) as any\n}\n\nexport function getImplementation<P = {}, S = {}>(component: string) {\n return window.__RENDER_8_COMPONENTS__[component] as any\n}\n\nexport function hasComponentImplementation(component: string) {\n return window.__RENDER_8_COMPONENTS__.hasOwnProperty(component)\n}\n\nexport function getExtensionImplementation<P = {}, S = {}>(\n extensions: any,\n name: string\n) {\n const extension = extensions[name]\n return extension && extension.component\n ? getImplementation<P, S>(extension.component)\n : null\n}\n\nexport function fetchAssets(runtime: any, assets: any) {\n const existingScripts = getExistingScriptSrcs()\n const existingStyles = getExistingStyleHrefs()\n\n const scripts = getAssetsToAdd(runtime, assets, '.js', existingScripts)\n const styles = getAssetsToAdd(runtime, assets, '.css', existingStyles)\n styles.forEach(addStyleToPage)\n return Promise.all(scripts.map(addScriptToPage)).then(() => {\n return\n })\n}\n\nexport function prefetchAssets(runtime: any, assets: any) {\n const existingScripts = getExistingScriptSrcs()\n const existingStyles = getExistingStyleHrefs()\n const existingScriptsPrefetches = getExistingPrefetchScriptLinks()\n const existingStylesPrefetches = getExistingPrefetchStyleLinks()\n\n const scripts = getAssetsToAdd(runtime, assets, '.js', [\n ...existingScripts,\n ...existingScriptsPrefetches,\n ])\n const styles = getAssetsToAdd(runtime, assets, '.css', [\n ...existingStyles,\n ...existingStylesPrefetches,\n ])\n scripts.forEach(prefetchScript)\n styles.forEach(prefetchStyle)\n}\n\nfunction getAssetsToAdd(\n runtime: any,\n assets: any,\n assetExtension: string,\n existingAssets: string[]\n) {\n const { account, production, rootPath = '' } = runtime\n\n const existingBundledAssetsByApp = groupAssetsByApp(existingAssets)\n\n return Array.from(\n assets.reduce((acc, asset) => {\n if (\n shouldAddAssetToPage(\n asset,\n assetExtension,\n existingBundledAssetsByApp,\n existingAssets\n )\n ) {\n const absoluteAsset = getAbsoluteURL(\n account,\n asset.path,\n production,\n rootPath\n )\n acc.add(absoluteAsset)\n }\n return acc\n }, new Set<string>())\n )\n}\n\nfunction shouldAddAssetToPage(\n asset: any,\n assetExtension: string,\n existingBundledAssetsByApp: Record<string, string[]>,\n existingAssets: string[]\n) {\n return (\n hasExtension(asset.path, assetExtension) &&\n !hasBundledAsset(asset.app, asset.name, existingBundledAssetsByApp) &&\n !assetOnList(asset.path, existingAssets)\n )\n}\n\nfunction hasExtension(path: string, fileExtension: string) {\n return getExtension(path) === fileExtension\n}\n\nfunction parseFilesQueryString(filesQueryString: string) {\n const hasSemicolon = filesQueryString.indexOf(';') !== -1\n\n if (hasSemicolon) {\n const [app, joinedPaths] = filesQueryString.split(';')\n const assets = joinedPaths ? joinedPaths.split(',') : []\n return { app, assets }\n } else {\n const [app, ...assets] = filesQueryString.split(',')\n return { app, assets }\n }\n}\n\nfunction groupAssetsByApp(assets: string[]): Record<string, string[]> {\n return assets.reduce((acc: Record<string, string[]>, asset) => {\n if (!asset) {\n return acc\n }\n\n const { query: parsedQuery } = queryString.parseUrl(asset)\n if (!parsedQuery || !parsedQuery.files) {\n return acc\n }\n\n const queryFiles: string[] = Array.isArray(parsedQuery.files)\n ? parsedQuery.files\n : [parsedQuery.files]\n queryFiles.forEach((files: string) => {\n if (!files) {\n return\n }\n\n const { app, assets } = parseFilesQueryString(files)\n if (!app || !assets || assets.length === 0) {\n return\n }\n\n if (!acc[app]) {\n acc[app] = assets\n } else {\n acc[app].push(...assets)\n }\n })\n return acc\n }, {})\n}\n\nfunction hasBundledAsset(\n app: string,\n asset: string,\n assetsByApp: Record<string, string[]>\n) {\n return !!assetsByApp[app] && assetsByApp[app].indexOf(asset) !== -1\n}\n\n```" } ]
code_store-on-localhost_1ea07509
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/session.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType } from 'react'\n\nimport Session from '../components/Session'\n\ninterface Options {\n renderWhileLoading?: boolean\n}\n\nexport const withSession = ({ renderWhileLoading }: Options = {}) => {\n return function<TOriginalProps>(\n Component: ComponentType<TOriginalProps>\n ): ComponentType<TOriginalProps> {\n class WithSession extends React.Component<TOriginalProps> {\n public static get displayName(): string {\n return `WithSession(${Component.displayName ||\n Component.name ||\n 'Component'})`\n }\n\n public static get WrappedComponent() {\n return Component\n }\n\n public render() {\n return (\n <Session renderWhileLoading={renderWhileLoading}>\n <Component {...this.props} />\n </Session>\n )\n }\n }\n\n return hoistNonReactStatics<any, any>(WithSession, Component)\n }\n}\n\n```" } ]
code_store-on-localhost_0ac4c5df
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/pages.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\nimport { History, LocationDescriptorObject } from 'history'\nimport queryString from 'query-string'\nimport { difference, is, isEmpty, keys, startsWith } from 'ramda'\nimport RouteParser from 'route-parser'\n\nimport { isEnabled } from './flags'\n\nconst EMPTY_OBJECT = (Object.freeze && Object.freeze({})) || {}\n\nconst removeTrailingParenthesis = (path: string) =>\n path.endsWith('(') ? path.substr(0, path.length - 1) : path\n\nexport function getComparablePrecedence(path: string): string {\n return path\n .split('/')\n .reduce((acc, pathSegment) => {\n if (pathSegment.startsWith('*')) {\n acc.push(3)\n } else if (pathSegment.startsWith(':')) {\n acc.push(2)\n } else if (pathSegment) {\n acc.push(1)\n }\n\n return acc\n }, [] as number[])\n .join()\n}\n\nfunction isHost(hostname: string) {\n return (\n hostname === (canUseDOM ? window.location.hostname : window.__hostname__)\n )\n}\n\nfunction trimEndingSlash(token: string) {\n return token.replace(/\\/$/, '') || '/'\n}\n\nfunction createLocationDescriptor(\n navigationRoute: any,\n {\n hash,\n query,\n scrollOptions,\n fetchPage,\n }: Pick<NavigateOptions, 'hash' | 'query' | 'scrollOptions' | 'fetchPage'>\n): LocationDescriptorObject {\n return {\n pathname: navigationRoute.path,\n state: {\n fetchPage,\n navigationRoute,\n renderRouting: true,\n scrollOptions,\n },\n ...(query && { search: query }),\n ...(hash && { hash }),\n }\n}\n\nfunction adjustTemplate(template: string) {\n // make last splat capture optional\n return trimEndingSlash(template).replace(/(\\/\\*\\w+)$/, '($1)')\n}\n\nfunction adjustPath(path: string) {\n const [pathname] = path.split('#')\n return trimEndingSlash(pathname)\n}\n\nfunction getValidTemplate(page: string, pages: any) {\n const pageDescriptor = pages[page]\n\n if (!pageDescriptor) {\n console.error(`Page ${page} was not found`)\n return null\n }\n\n const { path: template, canonical } = pageDescriptor\n if (!template) {\n console.error(`Page ${page} has no path`)\n return null\n }\n\n return adjustTemplate(canonical || template)\n}\n\nexport function pathFromPageName(page: string, pages: any, params: any) {\n const validTemplate = getValidTemplate(page, pages)\n if (!validTemplate) {\n return null\n }\n const path = new RouteParser(validTemplate).reverse(params)\n const filters = params\n ? params.rest || (params.terms && `/${params.terms}`) || ''\n : ''\n return path ? `${path}${filters}` : null\n}\n\nexport function queryStringToMap(query: string): Record<string, any> {\n if (!query) {\n return {}\n }\n return queryString.parse(query)\n}\n\nexport function mapToQueryString(query: Record<string, any> = {}): string {\n return queryString.stringify(query, { encode: false })\n}\n\nexport function getPageParams(path: string, routePath: string) {\n const pagePathWithRest =\n routePath && /\\*\\w+$/.test(routePath)\n ? routePath\n : routePath.replace(/\\/?$/, '*_rest')\n return (routePath && getParams(pagePathWithRest, path)) || EMPTY_OBJECT\n}\n\nfunction getParams(template: string, target: string) {\n const properTemplate = adjustTemplate(template)\n const properTarget = adjustPath(target)\n return new RouteParser(properTemplate).match(properTarget)\n}\n\nfunction getPagePath(name: string, pages: any) {\n const { path: pagePath, cname } = pages[name]\n return cname && isHost(cname) ? '/' : pagePath\n}\n\nfunction checkValidParams(id: string, pages: any, path: string, params: any) {\n const template = getValidTemplate(id, pages) || ''\n const validParams = getParams(template, path) as Record<string, any>\n const invalidParams = difference(keys(params), keys(validParams))\n\n if (!isEmpty(invalidParams)) {\n console.warn(\n `The following params are invalid: ${invalidParams.join(', ')}`\n )\n }\n}\n\nfunction getRouteFromPageName(\n id: string,\n pages: any,\n params: any\n): any | null {\n const path = pathFromPageName(id, pages, params) || ''\n checkValidParams(id, pages, path, params)\n return path ? { id, path, params } : null\n}\n\nfunction getCanonicalPath(\n canonicalPathTemplate: string,\n params: Record<string, string>\n): string | false {\n const properPathTemplate = adjustTemplate(canonicalPathTemplate)\n const canonicalPath = new RouteParser(properPathTemplate).reverse(params)\n if (canonicalPath) {\n return canonicalPath\n }\n\n console.warn(\n `Canonical path template '${canonicalPathTemplate}' could not be created with params: ${params}`\n )\n return false\n}\n\nexport function getRouteFromPath(\n path: string,\n pages: any\n): any | null {\n const routeMatch = routeMatchFromPath(path, pages)\n if (!routeMatch) {\n return null\n }\n\n const params = getPageParams(path, routeMatch.path)\n const navigationPath = routeMatch.canonical\n ? getCanonicalPath(routeMatch.canonical, params) || path\n : path\n\n return {\n id: routeMatch.id,\n params,\n path: navigationPath,\n }\n}\n\nexport function getRouteFromPathOld(\n path: string,\n pages: any,\n query?: string,\n hash?: string\n): any | null {\n const queryMap = query ? queryStringToMap(hash ? query + hash : query) : {}\n const routeMatch = routeIdFromPathAndQueryOld(path, queryMap, pages)\n if (!routeMatch) {\n return null\n }\n\n const params = getPageParams(path, routeMatch.path)\n const navigationPath = routeMatch.canonical\n ? getCanonicalPath(routeMatch.canonical, params) || path\n : path\n\n return {\n id: routeMatch.id,\n params,\n path: navigationPath,\n }\n}\n\nconst mergePersistingQueries = (currentQuery: string, query: string) => {\n const KEYS = ['disableUserLand', '__bindingAddress']\n const current = queryStringToMap(currentQuery)\n const next = queryStringToMap(query)\n const has = (value?: string) => !!value || value === null\n const persisting = KEYS.reduce<Record<string, any>>((cur, key) => {\n if (has(current[key]) && current[key] !== 'false') {\n cur[key] = current[key]\n }\n return cur\n }, {})\n return mapToQueryString({ ...persisting, ...next })\n}\n\nexport function navigate(\n history: History | null,\n pages: any,\n options: NavigateOptions\n) {\n const {\n page,\n params,\n query: inputQuery,\n to: inputTo = '',\n scrollOptions,\n fallbackToWindowLocation = true,\n rootPath,\n replace,\n fetchPage = true,\n modifiers,\n modifiersOptions,\n } = options as any\n\n if (!page && !inputTo) {\n console.error(\n `Invalid navigation options. You should use 'page' or 'to' parameters`\n )\n return false\n }\n\n if (inputTo && inputQuery) {\n console.warn(\n `You shouldn't pass 'query' in a separate prop when using 'to'`\n )\n }\n\n // If the prop `to` is something like `to=\"#header\"`\n // just change the hash using location, avoid doing a history navigation\n if (inputTo.indexOf('#') === 0 && inputTo.indexOf('?') === -1) {\n window.location.hash = inputTo\n return true\n }\n\n const [to, extractedQuery] = (is(String, inputTo) ? inputTo : '').split('?')\n const [realQuery, hash] = (is(String, extractedQuery)\n ? extractedQuery\n : ''\n ).split('#')\n const realHash = is(String, hash) ? `#${hash}` : ''\n let query = inputQuery || realQuery\n\n let navigationRoute: any = {}\n\n if (isEnabled('RENDER_NAVIGATION')) {\n const fallbackPage = { path: to, params: {}, id: '' }\n const routeFromPage = page && getRouteFromPageName(page, pages, params)\n const routeFromPath = getRouteFromPath(to, pages)\n navigationRoute = routeFromPage || routeFromPath || fallbackPage\n } else {\n navigationRoute = page\n ? getRouteFromPageName(page, pages, params)\n : getRouteFromPathOld(to, pages, query, realHash)\n }\n\n if (!navigationRoute) {\n console.warn(\n `Unable to find route for ${\n page ? `page '${page}' and the passed parameters` : `path '${to}'`\n }`\n )\n return false\n }\n\n navigationRoute.path = navigationRootPath(navigationRoute.path, rootPath)\n if (modifiers) {\n for (const modifier of modifiers) {\n const { path, query: fixedQuery } = modifier({\n path: navigationRoute.path,\n query,\n options: modifiersOptions,\n })\n navigationRoute.path = path || navigationRoute.path\n query = fixedQuery || query\n }\n }\n\n if (history) {\n const nextQuery = mergePersistingQueries(history.location.search, query)\n const location = createLocationDescriptor(navigationRoute, {\n fetchPage,\n query: nextQuery,\n scrollOptions,\n hash: realHash,\n })\n const method = replace ? 'replace' : 'push'\n window.setTimeout(() => history[method](location), 0)\n return true\n }\n\n if (fallbackToWindowLocation) {\n window.location.href = `${navigationRoute.path}${query}`\n return true\n }\n\n return false\n}\n\nfunction navigationRootPath(path: string, rootPath?: string) {\n // Prefix any non-absolute paths (e.g. http:// or https://) with runtime.rootPath\n if (rootPath && !path.startsWith('http')) {\n return rootPath + path\n }\n\n return path\n}\n\nexport function goBack(history: History | null) {\n if (history) {\n window.setTimeout(() => history.goBack(), 0)\n return true\n }\n\n console.warn('Unable to go to previous page')\n return false\n}\n\nexport function scrollTo(options: any) {\n const { baseElementId = null } = options || {}\n const scrollAnchor =\n baseElementId && document.querySelector(`#${baseElementId}`)\n\n if (!scrollAnchor) {\n return polyfillScrollTo(options)\n }\n\n const { top, left } = scrollAnchor.getBoundingClientRect()\n polyfillScrollTo({\n left: left + window.scrollX + (options.left || 0),\n top: top + window.scrollY + (options.top || 0),\n })\n}\n\nfunction polyfillScrollTo(options: any) {\n try {\n window.scrollTo(options)\n } catch (e) {\n const x = options.left == null ? window.scrollX : options.left\n const y = options.top == null ? window.scrollY : options.top\n window.scrollTo(x, y)\n }\n}\n\nfunction routeMatchForMappedURL(\n mappedSegments: string[],\n routes: any\n): RouteMatch | null {\n let id: string | undefined\n let score: number\n let highScore: number = Number.NEGATIVE_INFINITY\n\n for (const name in routes) {\n const { map = [], path: routePath } = routes[name]\n if (!routePath || map.length === 0 || !startsWith(map, mappedSegments)) {\n continue\n }\n\n score = map.length\n if (highScore > score) {\n continue\n }\n\n highScore = score\n id = name\n }\n\n if (!id) {\n return null\n }\n\n const { path } = routes[id]\n const pathSegments = path.split('/')\n const slicedPathSegments = pathSegments.slice(0, highScore + 1)\n const newPath = slicedPathSegments.join('/')\n\n return {\n id,\n path: removeTrailingParenthesis(newPath),\n }\n}\n\nfunction routeMatchFromPath(path: string, routes: any): RouteMatch | null {\n let id: string | undefined\n let pathPrecedence: string\n let chosenPathPrecedence: string | null = null\n\n for (const name in routes) {\n const pagePath = getPagePath(name, routes)\n if (!pagePath) {\n continue\n }\n\n const matches = !!getParams(pagePath, path)\n if (!matches) {\n continue\n }\n\n pathPrecedence = getComparablePrecedence(pagePath)\n if (\n chosenPathPrecedence !== null &&\n chosenPathPrecedence < pathPrecedence\n ) {\n continue\n }\n\n chosenPathPrecedence = pathPrecedence\n id = name\n }\n\n if (!id) {\n return null\n }\n\n return {\n canonical: routes[id].canonical,\n id,\n path: getPagePath(id, routes),\n }\n}\n\nfunction routeIdFromPathAndQueryOld(\n path: string,\n query: Record<string, string>,\n routes: any\n) {\n const mappedSegments = query.map ? query.map.split(',') : []\n let routeMatch: RouteMatch | null = null\n\n // Don't use map segments to match a route when Render\n // navigation is enabled\n if (mappedSegments.length > 0 && !isEnabled('RENDER_NAVIGATION')) {\n routeMatch = routeMatchForMappedURL(mappedSegments, routes)\n }\n\n if (!routeMatch) {\n routeMatch = routeMatchFromPath(path, routes)\n }\n\n return routeMatch\n}\n\ninterface RouteMatch {\n canonical?: string\n id: string\n path: string\n}\n\nexport interface NavigateOptions {\n hash?: string\n page?: string\n params?: any\n query?: any\n to?: string\n scrollOptions?: any\n fallbackToWindowLocation?: boolean\n replace?: boolean\n fetchPage?: boolean\n rootPath?: string\n modifiers?: Set<NavigationRouteModifier>\n modifiersOptions?: Record<string, any>\n}\n\nexport interface NavigationRouteChange {\n path: string\n query?: string\n options?: Record<string, NavigationRouteChange>\n}\n\nexport type NavigationRouteModifier = (\n navigationRoute: NavigationRouteChange\n) => NavigationRouteChange\n\n```" } ]
code_store-on-localhost_4d02e525
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/location.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport queryString from 'query-string'\nimport { pickBy } from 'ramda'\n\nexport const appendLocationSearch = (\n search: string,\n params: Record<string, string>\n) => {\n if (!search) {\n return `?${queryString.stringify(params, { encode: false })}`\n }\n\n const included = queryString.parse(search)\n const filteredParams = pickBy(\n (_, paramName) => !(paramName in included),\n params\n ) as Record<string, string>\n const additionalSearch = queryString.stringify(filteredParams, {\n encode: false,\n })\n if (!additionalSearch) {\n return search\n }\n\n return `${search}&${additionalSearch}`\n}\n\n```" } ]
code_store-on-localhost_aff94e83
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/cookie.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nconst ONE_YEAR_S = 60 * 60 * 24 * 365\n\nexport const setCookie = (\n key: string,\n value: string,\n path = '/',\n maxAge: number = ONE_YEAR_S\n) => {\n if (!canUseDOM) {\n return\n }\n\n window.document.cookie = `${key}=${value};path=${path};max-age=${maxAge}`\n}\n\n```" } ]
code_store-on-localhost_85b3260d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/reactApollo.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { PureComponent } from 'react'\nimport { Query, Mutation } from 'react-apollo'\nimport { compose } from 'ramda'\n\nconst noop = () => {}\n\nclass RenderRuntimeQuery extends PureComponent<{\n children: (result: any) => JSX.Element | null\n}> {\n public render() {\n const { children, ...rest } = this.props\n\n return (\n <Query {...(rest as any)}>\n {(result: any) => {\n if (result.networkStatus === 1 && result.data === undefined) {\n result.data = {} as any\n result.refetch = noop as any\n }\n return children(result)\n }}\n </Query>\n )\n }\n}\n\nclass RenderRuntimeMutation extends PureComponent<{\n children: (mutateFunction: any, result: any) => JSX.Element | null\n}> {\n public render() {\n const { children, ...rest } = this.props\n\n return (\n <Mutation {...(rest as any)}>\n {(mutateFunction: any, result: any) => {\n return children(mutateFunction, result)\n }}\n </Mutation>\n )\n }\n}\n\nexport const createCustomReactApollo = () => {\n // eslint-disable-next-line no-unused-vars\n const { Query, Mutation, ...rest } = window.ReactApollo\n return {\n ...rest,\n Query: RenderRuntimeQuery,\n Mutation: RenderRuntimeMutation,\n compose,\n }\n}\n\n```" } ]
code_store-on-localhost_b8196b57
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/vteximg.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isEnabled } from './flags'\n\nconst SECURE_PROTOCOL = 'https://'\nconst PROTOCOL_RELATIVE_PREFIX = '//'\nconst ARQUIVOS_RELATIVE_PREFIX = '/arquivos'\nconst ASSETS_RELATIVE_PREFIX = '/assets'\nconst FILE_MANAGER_PATH_REGEX = /url\\(\"?(.*\\/)assets\\/vtex\\.file-manager-graphql/\n\nconst toVtexAssets = (url: string) =>\n isEnabled('VTEX_ASSETS_URL')\n ? url.replace('vteximg.com.br', 'vtexassets.com')\n : url\n\nexport function optimizeSrcForVtexImg(vtexImgHost: string, src?: any) {\n try {\n if (src && src.indexOf(PROTOCOL_RELATIVE_PREFIX) === 0) {\n return toVtexAssets(\n src.replace(PROTOCOL_RELATIVE_PREFIX, SECURE_PROTOCOL)\n )\n }\n\n if (\n src &&\n (src.indexOf(ARQUIVOS_RELATIVE_PREFIX) === 0 ||\n src.indexOf(ASSETS_RELATIVE_PREFIX) === 0)\n ) {\n return vtexImgHost + src\n }\n\n return toVtexAssets(src)\n } catch (e) {\n console.warn('Failed to optimize image source.')\n return src\n }\n}\n\nexport function optimizeStyleForVtexImg(vtexImgHost: string, style?: any) {\n try {\n if (style && style.backgroundImage) {\n const match = FILE_MANAGER_PATH_REGEX.exec(style.backgroundImage)\n if (match && match[1]) {\n style.backgroundImage = style.backgroundImage.replace(\n match[1],\n vtexImgHost + '/'\n )\n }\n }\n\n return style\n } catch (e) {\n console.warn('Failed to optimize style.')\n return style\n }\n}\n\nexport function isStyleWritable(props: any): boolean {\n const propertyDescriptor = Object.getOwnPropertyDescriptor(props, 'style')\n return (propertyDescriptor && propertyDescriptor.writable) || false\n}\n\n```" } ]
code_store-on-localhost_25c72303
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/pages.test.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getComparablePrecedence } from './pages'\n\ndescribe('#getPrecedence', () => {\n it('should set precedence as expected', () => {\n const routes = [\n '/a/b/c',\n '/a/:b/c',\n '/:a/b/c',\n '/a/b/:c',\n '/a/:b/:c',\n '/:a/b/:c',\n '/a/b/*c',\n '/a/:b/*c',\n '/:a/b/*c',\n '/a/*b',\n '/:a/*b',\n '/*a',\n ]\n\n const result = routes.sort((a, b) =>\n getComparablePrecedence(b) > getComparablePrecedence(a) ? -1 : 1\n )\n\n expect(result).toEqual([\n '/a/b/c',\n '/a/b/:c',\n '/a/b/*c',\n '/a/:b/c',\n '/a/:b/:c',\n '/a/:b/*c',\n '/a/*b',\n '/:a/b/c',\n '/:a/b/:c',\n '/:a/b/*c',\n '/:a/*b',\n '/*a',\n ])\n })\n})\n\n```" } ]
code_store-on-localhost_362a6f9f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/events.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport EventEmitter from 'eventemitter3'\nimport { canUseDOM } from 'exenv'\n\ninterface IOEvent {\n key: string\n body: {\n code: string\n type: string\n hash: string\n locales: any\n subject: string\n updated: string[]\n }\n}\n\ninterface EventEmitterSource extends Array<EventEmitter> {\n eventSource?: any\n}\n\ninterface EmittersRegistry {\n [key: string]: EventEmitterSource\n}\n\nconst CONNECTION_CLOSED = 2\n\nconst emittersByWorkspace: EmittersRegistry = {}\n\nconst initSSE = (\n account: string,\n workspace: string,\n baseURI: string,\n isProductionWorkspace: boolean\n) => {\n if (isProductionWorkspace) {\n return undefined\n }\n\n require('eventsource-polyfill')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const myvtexSSE = require('myvtex-sse')\n const path = `vtex.builder-hub:*:react2,pages0,build.status,pages1,styles?workspace=${workspace}`\n const linkInterruptedPath = `colossus:*:link_interrupted?workspace=${workspace}`\n const source: any = myvtexSSE(account, workspace, path, {\n verbose: false,\n host: baseURI,\n })\n const linkInterruptedSource: any = myvtexSSE(\n account,\n workspace,\n linkInterruptedPath,\n {\n verbose: false,\n host: baseURI,\n }\n )\n\n const handler = ({ data }: MessageEvent) => {\n const event = JSON.parse(data) as IOEvent\n const {\n key,\n body: { code, type, hash, locales, subject, updated },\n } = event\n\n if (key === 'build.status') {\n switch (code) {\n case 'start':\n console.log(`[build] Build started. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('build.status', code)\n )\n break\n case 'success':\n console.log(`[build] Build success. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('build.status', code)\n )\n break\n case 'fail':\n console.log(`[build] Build failed. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('build.status', code)\n )\n break\n }\n return\n }\n\n if (key === 'link_interrupted') {\n console.log(`[colossus] Link interrupted.`)\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('link_interrupted', code)\n )\n }\n\n switch (type) {\n case 'hmr':\n console.log(`[react2] Received update. app=${subject} hash=${hash}`)\n if (window.__RENDER_8_HOT__[subject]) {\n window.__RENDER_8_HOT__[subject].emit('webpackHotUpdate', hash)\n }\n break\n case 'reload':\n console.log(`[react2] Received reload. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('build.status', 'reload')\n )\n window.location.reload(true)\n break\n case 'locales':\n console.log(\n `[react2] Received locale update. appId=${subject} locales=${locales}`\n )\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('localesUpdated', locales)\n )\n break\n case 'changed':\n console.log('[pages0] Extensions changed.')\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('extensionsUpdated')\n )\n break\n case 'blocks':\n console.log('[pages1] Blocks changed.')\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('blocksUpdated')\n )\n break\n case 'styles':\n console.log('[styles] Styles changed.')\n if (updated.indexOf('style.json') > -1) {\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('styleTachyonsUpdate')\n )\n }\n if (updated.indexOf('overrides.css') > -1) {\n emittersByWorkspace[`${account}/${workspace}`].forEach(e =>\n e.emit('styleOverrides')\n )\n }\n\n break\n }\n }\n\n source.onmessage = handler\n linkInterruptedSource.onmessage = handler\n source.onopen = () =>\n console.log('[render] Connected to event server successfully')\n source.onerror = () =>\n console.log('[render] Connection to event server failed')\n linkInterruptedSource.onopen = () =>\n console.log('[colossus] Connected to event server successfully')\n linkInterruptedSource.onerror = () =>\n console.log('[colossus] Connection to event server failed')\n\n return source\n}\n\nexport const registerEmitter = (runtime: any, baseURI: string) => {\n if (!canUseDOM) {\n return\n }\n\n const { account, production, workspace } = runtime\n\n // Share SSE connections for same account and workspace\n if (!emittersByWorkspace[`${account}/${workspace}`]) {\n emittersByWorkspace[`${account}/${workspace}`] = []\n emittersByWorkspace[`${account}/${workspace}`].eventSource = initSSE(\n account,\n workspace,\n baseURI,\n production\n )\n\n if (!production) {\n document.addEventListener('visibilitychange', () => {\n const es = emittersByWorkspace[`${account}/${workspace}`].eventSource\n // Ensure SSE server connection\n if (!document.hidden && es && es.readyState === CONNECTION_CLOSED) {\n emittersByWorkspace[`${account}/${workspace}`].eventSource = initSSE(\n account,\n workspace,\n baseURI,\n production\n )\n }\n })\n }\n }\n\n if (!runtime.emitter) {\n runtime.emitter = new EventEmitter()\n emittersByWorkspace[`${account}/${workspace}`].push(runtime.emitter)\n }\n}\n\n```" } ]
code_store-on-localhost_37048420
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/flags.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst flags = {\n RENDER_NAVIGATION: true,\n VTEX_ASSETS_URL: true,\n}\n\nexport const isEnabled = (flag: keyof typeof flags) => flags[flag]\n\n```" } ]
code_store-on-localhost_1e51a28d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/host.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nconst isRenderServedPage = () => {\n const generatorMetaTag = document.querySelector(`meta[name='generator']`)\n const generator = generatorMetaTag && generatorMetaTag.getAttribute('content')\n return generator && generator.startsWith('vtex.render-server')\n}\n\nexport const getBaseURI = (runtime: any) => {\n const { account, workspace, publicEndpoint, rootPath = '' } = runtime\n if (!canUseDOM) {\n return `${workspace}--${account}.${publicEndpoint}`\n } else {\n const {\n location: { hostname },\n } = window\n return hostname.endsWith(`.${publicEndpoint}`) || isRenderServedPage()\n ? hostname + rootPath\n : `${hostname}/api/io`\n }\n}\n\n```" } ]
code_store-on-localhost_dbffb618
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/treePath.test.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { escapeRegex, isDirectChild } from './treePath'\n\ndescribe('#escapeRegex', () => {\n const specialRegexCharacters = [\n '[',\n ']',\n '\\\\',\n '^',\n '$',\n '.',\n '|',\n '?',\n '*',\n '+',\n '(',\n ')',\n ]\n\n it(`should prefix regex special characters: [ '${specialRegexCharacters.join(\n `', '`\n )}' ] with \\\\`, () => {\n specialRegexCharacters.forEach(specialRegexCharacter => {\n expect(escapeRegex(specialRegexCharacter)).toEqual(\n `\\\\${specialRegexCharacter}`\n )\n })\n })\n\n it('should return own string if there are no special characters', () => {\n expect('testString').toBe('testString')\n })\n})\n\ndescribe('#isDirectChild', () => {\n it('should return true for one level of nesting', () => {\n expect(isDirectChild('store/home/shelf', 'store/home')).toBe(true)\n })\n\n it('should allow \"_\" on names', () => {\n expect(isDirectChild('store/home/shelf_0', 'store/home')).toBe(true)\n })\n\n it('should allow regex special characters on names', () => {\n expect(\n isDirectChild('store/home/$before_0/shelf_0', 'store/home/$before_0')\n ).toBe(true)\n })\n\n it('should return false for 2 levels nesting', () => {\n expect(isDirectChild('store/home/shelf/image', 'store/home')).toBe(false)\n })\n})\n\n```" } ]
code_store-on-localhost_57ae8c5a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/withHMR.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport PropTypes from 'prop-types'\nimport React, { Component, ComponentType } from 'react'\n\nimport { withEmitter } from '../components/RenderContext'\nimport { isComponentType } from './registerComponent'\nimport { withTreePath } from './treePath'\n\nexport default (module: any, InitialImplementer: any) => {\n if (!isComponentType(InitialImplementer) || !module.hot) {\n return InitialImplementer\n }\n\n /**\n * We should move this registering code to registerComponent.tsx. We currently\n * can not do this since old apps are still using this function to register\n * thenselves with the old withHMR function\n */\n const instances: HMRComponent[] = []\n const registerInstance = (instance: HMRComponent) => {\n instances.push(instance)\n }\n\n const unregisterInstance = (instance: HMRComponent) => {\n const index = instances.findIndex(registered => registered === instance)\n if (index !== -1) {\n instances.splice(index, 1)\n }\n }\n\n class HMRComponent extends Component<any, { lastUpdate?: number }> {\n public static propTypes = {\n __clearError: PropTypes.func,\n __errorInstance: PropTypes.node,\n }\n\n public static get displayName(): string {\n return (\n HMRComponent.Implementer.displayName ||\n HMRComponent.Implementer.name ||\n 'Component'\n )\n }\n\n public static hotReload = (NewImplementer: ComponentType) => {\n HMRComponent.Implementer = NewImplementer\n hoistNonReactStatics(HMRComponent, NewImplementer)\n instances.forEach(instance => instance.updateComponent())\n }\n\n private static Implementer = InitialImplementer as ComponentType\n\n public updateComponent = () => {\n const { __emitter, treePath, __clearError, __errorInstance } = this.props\n __emitter.emit('build.status', 'hmr:success')\n\n if (__clearError && __errorInstance) {\n __clearError()\n } else {\n this.setState({ lastUpdate: Date.now() })\n }\n\n console.log(\n `[render] Component updated via HMR. treePath=${treePath} updated=${HMRComponent.displayName}`\n )\n }\n\n public componentDidMount() {\n registerInstance(this)\n }\n\n public componentWillUnmount() {\n unregisterInstance(this)\n }\n\n public render() {\n // eslint-disable-next-line\n const { __emitter, __clearError, __errorInstance, treePath, ...props } = this.props\n return (\n this.props.__errorInstance || <HMRComponent.Implementer {...props} />\n )\n }\n }\n\n return hoistNonReactStatics(\n withEmitter(withTreePath(HMRComponent)),\n InitialImplementer\n )\n}\n\n```" } ]
code_store-on-localhost_45a8ef83
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/graphQLErrorsStore.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { GraphQLError } from 'graphql'\n\nexport interface ExtendedGraphQLError extends GraphQLError {\n operationId: string\n extensions: {\n code: string\n exception: {\n stacktrace: string\n name?: string\n }\n }\n}\n\nexport function isExtendedGraphQLError(\n error: GraphQLError\n): error is ExtendedGraphQLError {\n return 'operationId' in error\n}\n\nconst ignoredErrorTypes = [\n 'UserInputError',\n 'AuthenticationError',\n 'ForbiddenError',\n]\n\nclass GraphQLErrorsStore {\n private operationIds: string[] = []\n\n public addOperationIds(errors: readonly GraphQLError[]) {\n const operationIds = errors.reduce<string[]>((acc, error) => {\n if (\n isExtendedGraphQLError(error) &&\n !ignoredErrorTypes.includes(\n (error.extensions.exception && error.extensions.exception.name) || ''\n )\n ) {\n return acc.concat(error.operationId)\n }\n return acc\n }, [])\n this.operationIds = this.operationIds.concat(operationIds)\n }\n\n public getOperationIds() {\n const operationIds = this.operationIds.slice()\n this.operationIds = []\n return operationIds\n }\n}\n\nconst Store = new GraphQLErrorsStore()\n\nexport default Store\n\n```" } ]
code_store-on-localhost_2f321f0a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/cacheControl.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst MINIMUM_MAX_AGE_S = 5\nconst DEFAULT_MAX_AGE_S = 10 * 60\nconst STATIC_PAGE_MAX_AGE_S = 7 * 24 * 60 * 60\n\nconst parseCacheControl = (cacheControl: string) => {\n const cacheDirectives = cacheControl.split(',').map(d => d.trim())\n const maxAgeDirective = cacheDirectives.find(d => d.startsWith('max-age'))\n const maxAgeStr = maxAgeDirective ? maxAgeDirective.split('=')[1] : null\n const maxAge = maxAgeStr ? parseInt(maxAgeStr, 10) : 0\n\n return {\n maxAge,\n noCache: cacheDirectives.includes('no-cache'),\n noStore: cacheDirectives.includes('no-store'),\n }\n}\n\nconst getMaxAge = (response: Response) => {\n const cacheControlHeader = response.headers.get('cache-control')\n if (!cacheControlHeader) {\n return DEFAULT_MAX_AGE_S\n }\n\n const { noCache, noStore, maxAge } = parseCacheControl(cacheControlHeader)\n if (noCache || noStore) {\n return MINIMUM_MAX_AGE_S\n }\n\n return Math.max(MINIMUM_MAX_AGE_S, maxAge)\n}\n\nexport default class PageCacheControl {\n private maxAges: number[] = []\n\n public get maxAge(): number {\n return this.maxAges.length > 0\n ? Math.min(...this.maxAges)\n : STATIC_PAGE_MAX_AGE_S\n }\n\n public evaluate(innerResponse: Response) {\n const responseMaxAge = getMaxAge(innerResponse)\n this.maxAges.push(responseMaxAge)\n }\n}\n\n```" } ]
code_store-on-localhost_60cf7d47
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/reactIntl.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport { FormattedRelativeTime, injectIntl } from 'react-intl'\nimport React, { FC } from 'react'\nimport hoistNonReactStatics from 'hoist-non-react-statics'\n\nfunction getDisplayName(Component: React.ComponentType<any>) {\n return Component.displayName || Component.name || 'Component'\n}\n\n// We do our best to maintain compatibility with the prvious API but this is not perfect\nconst getCorrectUnit = (timeDiff: number) => {\n const years = timeDiff / (millisecondsInDay * 365)\n if (isUnitValid(years)) {\n return {\n value: Math.round(years),\n unit: 'year',\n }\n }\n const months = timeDiff / (millisecondsInDay * 30)\n if (isUnitValid(months)) {\n return {\n value: Math.round(months),\n unit: 'month',\n }\n }\n\n const days = timeDiff / millisecondsInDay\n if (isUnitValid(days)) {\n return {\n value: Math.round(days),\n unit: 'day',\n }\n }\n const hours = timeDiff / millisecondsInHour\n if (isUnitValid(hours)) {\n return {\n value: Math.round(hours),\n unit: 'hour',\n }\n }\n const minutes = (timeDiff / 60) * 1000\n if (isUnitValid(minutes)) {\n return {\n value: Math.round(minutes),\n unit: 'minute',\n }\n }\n return {\n value: Math.round(timeDiff / 1000),\n unit: 'second',\n }\n}\n\nconst FormattedRelative: FC<any> = props => {\n console.warn(\n 'FormattedRelative was removed in react-intl@3.x, you are using an approximation. Plase start using FormattedRelativeTime.'\n )\n const { value } = props\n let timeDiff\n if (value instanceof Date) {\n timeDiff = value.getTime() - Date.now()\n }\n if (typeof value === 'string') {\n timeDiff = new Date(value).getTime() - Date.now()\n }\n if (!timeDiff) {\n return null\n }\n const { value: newValue, unit } = getCorrectUnit(timeDiff)\n return <FormattedRelativeTime value={newValue} unit={unit as any} />\n}\n\nconst addLocaleData = () => {\n console.warn(\n 'addLocaleData was removed in react-intl@3.x and is not needed anymore. Please read: https://github.com/formatjs/react-intl/blob/master/docs/Upgrade-Guide.md#formattedrelativetime'\n )\n}\n\nconst millisecondsInHour = 60 * 60 * 1000\nconst millisecondsInDay = 24 * millisecondsInHour\n\nconst isUnitValid = (value: number) => Math.abs(value) >= 1\n\nconst renderFormatRelative = (intl: any) => (value: any) => {\n console.warn(\n 'formatRelative was removed in react-intl@3.x, please start using formatRelativeTime.'\n )\n let timeDiff\n if (value instanceof Date) {\n timeDiff = value.getTime() - Date.now()\n }\n if (typeof value === 'string') {\n timeDiff = new Date(value).getTime() - Date.now()\n }\n if (!timeDiff) {\n return null\n }\n\n const { value: newValue, unit } = getCorrectUnit(timeDiff)\n\n return intl.formatRelativeTime(newValue, unit)\n}\n\nconst renderRuntimeInjectIntl: FC<any> = (\n WrappedComponent: any,\n options?: any\n) => {\n const intlPropName = (options && options.intlPropName) || 'intl'\n const forwardRef = (options && options.forwardRef) || false\n const WithRenderRuntimeIntl = injectIntl(props => {\n const intlObj = props[intlPropName] as any\n if (intlObj) {\n intlObj.formatRelative = renderFormatRelative(intlObj)\n }\n return (\n <WrappedComponent\n {...props}\n ref={forwardRef ? props.forwardedRef : null}\n />\n )\n }, options)\n\n WithRenderRuntimeIntl.displayName = `renderRuntimeInjectIntl(${getDisplayName(\n WrappedComponent\n )}`\n WithRenderRuntimeIntl.WrappedComponent = WrappedComponent\n\n if (forwardRef) {\n return hoistNonReactStatics(\n // eslint-disable-next-line react/display-name\n React.forwardRef((props, ref) => (\n <WithRenderRuntimeIntl {...(props as any)} forwardedRef={ref} />\n )),\n WrappedComponent\n ) as any\n }\n return hoistNonReactStatics(WithRenderRuntimeIntl, WrappedComponent) as any\n}\n\nexport const createReactIntl = () => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { injectIntl, ...rest } = window.ReactIntl\n if (!window.ReactIntlLocaleData) {\n window.ReactIntlLocaleData = {}\n }\n\n return {\n ...rest,\n injectIntl: renderRuntimeInjectIntl,\n intlShape: PropTypes.any,\n FormattedRelative,\n addLocaleData,\n }\n}\n\n```" } ]
code_store-on-localhost_442a20f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/fetch.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst delay = (ms: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nconst RETRY_STATUSES = [\n 0,\n 408,\n 425,\n 429,\n 500,\n 501,\n 502,\n 503,\n 504,\n 505,\n 506,\n 507,\n 508,\n 510,\n 511,\n]\n\nconst canRetry = (status: number) => RETRY_STATUSES.includes(status)\n\nconst ok = (status: number) => 200 <= status && status < 300\n\nexport const fetchWithRetry = (\n url: string,\n init: any,\n fetcher: any['fetch'],\n maxRetries = 3\n) => {\n let status = 500\n const callFetch = (\n attempt = 0\n ): Promise<{ response: Response; error: any }> =>\n fetcher(url, init)\n .then(response => {\n status = response.status\n return ok(status)\n ? { response, error: null }\n : response\n .json()\n .then(error => ({ response, error }))\n .catch(() => ({\n response,\n error: { message: 'Unable to parse JSON' },\n }))\n })\n .then(({ response, error }) => {\n if (error) {\n throw new Error(error.message || 'Unknown error')\n }\n return { response, error: null }\n })\n .catch(error => {\n console.error(error)\n\n if (attempt >= maxRetries || !canRetry(status)) {\n throw error\n }\n\n const ms = 2 ** attempt * 500\n return delay(ms).then(() => callFetch(++attempt))\n })\n\n return callFetch()\n}\n\n```" } ]
code_store-on-localhost_2e11ebe4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/dom.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'exenv'\nimport React, { Fragment, ReactElement, ReactPortal } from 'react'\nimport { createPortal as reactCreatePortal } from 'react-dom'\n\nconst portalPattern = /START_SERVER_PORTAL_([^!]+)!((\\n|.)+)END_SERVER_PORTAL_\\1!/g\n\n// Map `placeholder/with/slashes` to `render-placeholder-with-slashes`.\nconst hyphenate = (name: string) => name.replace(/[^\\w]/g, '-')\n\nconst portalWrapperId = (name: string) => `render-portal-ssr-${hyphenate(name)}`\n\nexport const RENDER_CONTAINER_CLASS = 'render-container'\n\nexport const ROUTE_CLASS_PREFIX = 'render-route-'\n\nexport const routeClass = (name: string) =>\n `${ROUTE_CLASS_PREFIX}${hyphenate(name)}`\n\nconst renderContainer = (name: string, markup: string) =>\n `<div class=\"${RENDER_CONTAINER_CLASS} ${routeClass(name)}\">${markup}</div>`\n\nconst portalWrapper = (name: string, markup: string) =>\n `<span id=\"${portalWrapperId(name)}\">${markup}</span>`\n\nexport const createPortal = (\n children: ReactElement<any>,\n name: string,\n hydrate: boolean\n) => {\n window.__hasPortals__ = true\n\n if (!hydrate) {\n return canUseDOM ? null : (\n <Fragment>\n {`START_SERVER_PORTAL_${name}!`}\n {children}\n {`END_SERVER_PORTAL_${name}!`}\n </Fragment>\n )\n }\n\n const ssrPortalContainer = document.getElementById(portalWrapperId(name))\n if (ssrPortalContainer) {\n ssrPortalContainer.remove()\n }\n\n const container = document.getElementsByClassName(routeClass(name))[0]\n if (!container) {\n console.warn(`Missing React Portal container div.${routeClass(name)}`)\n return null\n }\n\n return reactCreatePortal(children, container) as ReactPortal\n}\n\nexport const getMarkups = (\n pageName: string,\n pageMarkup: string\n): any[] => {\n const markups: any[] = []\n\n let matches = window.__hasPortals__ && portalPattern.exec(pageMarkup)\n let strippedMarkup = pageMarkup\n while (matches) {\n const [matched, name, markup] = matches\n strippedMarkup = strippedMarkup.replace(matched, '')\n markups.push({\n markup: renderContainer(name, portalWrapper(name, markup)),\n name,\n })\n matches = portalPattern.exec(pageMarkup)\n }\n\n markups.unshift({\n markup: renderContainer(pageName, strippedMarkup),\n name: pageName,\n })\n\n return markups\n}\n\nexport const isSiteEditorIframe =\n canUseDOM &&\n window.top !== window.self &&\n window.top.__provideRuntime &&\n !!window.top.__provideRuntime &&\n window.__RUNTIME__.route.domain === 'store'\n\nexport const getContainer = () => {\n return canUseDOM\n ? document.getElementsByClassName(RENDER_CONTAINER_CLASS)[0]\n : null\n}\n\nexport const ensureContainer = (name: string) => {\n if (!canUseDOM) {\n return false\n }\n\n const existingContainer = document.getElementsByClassName(\n RENDER_CONTAINER_CLASS\n )[0]\n if (existingContainer) {\n return false\n }\n\n const containerDiv = document.createElement('div')\n containerDiv.className = `render-container ${routeClass(name)}`\n containerDiv.style.display = 'none'\n document.body.appendChild(containerDiv)\n return true\n}\n\n```" } ]
code_store-on-localhost_ac9cdb4f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/LoadingBar.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n@keyframes loading-bar-animation {\n 0% {\n transform: scale(0, 1);\n }\n 10% {\n transform: scale(0.5, 1);\n }\n 20% {\n transform: scale(0.75, 1);\n }\n 100% {\n transform: scale(0.95, 1);\n }\n}\n\n.loadingBarAnimation {\n transform-origin: 0 0;\n animation: loading-bar-animation 6s ease-out;\n transform: scale(0.95, 1);\n}\n\n```" } ]
code_store-on-localhost_c582113a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ChildBlock.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useExtension } from '../hooks/extension'\n\nexport function useChildBlock(childBlock: ChildBlock): Block | null {\n if (typeof childBlock === 'string') {\n throw new Error(\n `You are passing a string as a parameter to useChildBlock (\"${childBlock}\"). You should pass an object like {id: \"${childBlock}\"}.`\n )\n }\n\n const { id } = childBlock\n\n if (!id) {\n throw new Error('The id you are sending to useChildBlock is empty')\n }\n\n const extension = useExtension({ children: id })\n\n // We are explicitly not exposing the private API here\n return extension\n ? {\n props: extension.props,\n }\n : null\n}\n\nexport function ChildBlock({ id, children }: ChildBlockProps) {\n const block = useChildBlock({ id })\n\n return children(block)\n}\n\ninterface ChildBlock {\n id: string\n}\n\n/** Placeholder for possible block data in the future */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\ninterface Block {}\n\ninterface ChildBlockProps extends ChildBlock {\n children(block: Block | null): React.ReactNode\n}\n\n```" } ]
code_store-on-localhost_6f9c9cf8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Link.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { MouseEvent, useCallback } from 'react'\nimport { NavigateOptions, pathFromPageName } from '../utils/pages'\nimport { useRuntime } from './RenderContext'\n\nconst isLeftClickEvent = (event: MouseEvent<HTMLAnchorElement>) =>\n event.button === 0\n\nconst isModifiedEvent = (event: MouseEvent<HTMLAnchorElement>) =>\n !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)\n\nconst absoluteRegex = /^https?:\\/\\/|^\\/\\//i\nconst telephoneRegex = /^tel:/i\nconst mailToRegex = /^mailto:/i\n\nconst isAbsoluteUrl = (url: string) => absoluteRegex.test(url)\nconst isTelephoneUrl = (url: string) => telephoneRegex.test(url)\nconst isMailToUrl = (url: string) => mailToRegex.test(url)\n\ninterface Props extends NavigateOptions {\n onClick?: (event: React.MouseEvent) => void\n className?: string\n target?: string\n}\n\nconst Link: React.FunctionComponent<Props> = ({\n page,\n onClick = () => {},\n params,\n to,\n scrollOptions,\n query,\n children,\n modifiers,\n replace,\n modifiersOptions,\n target,\n ...linkProps\n}) => {\n const {\n pages,\n navigate,\n rootPath = '',\n route: { domain },\n } = useRuntime()\n\n const handleClick = useCallback(\n (event: MouseEvent<HTMLAnchorElement>) => {\n if (\n isModifiedEvent(event) ||\n !isLeftClickEvent(event) ||\n (to && (isAbsoluteUrl(to) || isTelephoneUrl(to) || isMailToUrl(to)))\n ) {\n return\n }\n\n onClick(event)\n\n const options: NavigateOptions = {\n fallbackToWindowLocation: false,\n page,\n params,\n query,\n rootPath,\n scrollOptions,\n to,\n modifiers,\n replace,\n modifiersOptions,\n }\n\n // If you pass a target different from \"_self\" the component\n // will behave just like a normal anchor element\n if ((target === '_self' || !target) && navigate(options)) {\n event.preventDefault()\n }\n },\n [\n to,\n onClick,\n page,\n params,\n query,\n rootPath,\n scrollOptions,\n modifiers,\n navigate,\n replace,\n modifiersOptions,\n target,\n ]\n )\n\n const getHref = () => {\n if (to) {\n // Prefix any non-absolute paths (e.g. http:// or https://) and non-special links (e.g. mailto: or tel:)\n // with runtime.rootPath\n if (\n rootPath &&\n !to.startsWith('http') &&\n !to.startsWith(rootPath) &&\n !isTelephoneUrl(to) &&\n !isMailToUrl(to)\n ) {\n return rootPath + to\n }\n return to\n }\n if (page) {\n const path = pathFromPageName(page, pages, params)\n const qs = query ? `?${query}` : ''\n if (path) {\n return rootPath + path + qs\n }\n }\n return '#'\n }\n\n const href = getHref()\n // Href inside admin iframe should omit the `/app/` path\n const hrefWithoutIframePrefix =\n domain && domain === 'admin' && href.startsWith('/admin/app/')\n ? href.replace('/admin/app/', '/admin/')\n : href\n\n return (\n <a\n target={target}\n href={hrefWithoutIframePrefix}\n {...linkProps}\n onClick={handleClick}\n >\n {children}\n </a>\n )\n}\n\nexport default Link\n\n```" } ]
code_store-on-localhost_6bde653b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionPointError.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { ErrorInfo, PureComponent } from 'react'\n\ninterface Props {\n treePath?: string\n error?: Error\n errorInfo?: ErrorInfo | null\n operationIds?: string[]\n}\n\ninterface State {\n errorDetails?: boolean\n}\n\nclass ExtensionPointError extends PureComponent<Props, State> {\n public static propTypes = {\n error: PropTypes.object,\n errorInfo: PropTypes.object,\n treePath: PropTypes.string,\n }\n\n public constructor(props: any) {\n super(props)\n this.state = {}\n }\n\n public handleToggleErrorDetails = () => {\n this.setState({\n errorDetails: !this.state.errorDetails,\n })\n }\n\n public render() {\n const { treePath, error, errorInfo, operationIds } = this.props\n const { errorDetails } = this.state\n\n const componentStack = errorInfo && errorInfo.componentStack\n\n return (\n <div className=\"bg-washed-red pa6 f5 serious-black br3 pre\">\n <span>\n Error rendering extension point <strong>{treePath}</strong>\n </span>\n <button\n type=\"button\"\n className=\"red ph0 ma0 mh3 bg-transparent bn pointer link\"\n onClick={this.handleToggleErrorDetails}\n >\n ({errorDetails ? 'hide' : 'show'} details)\n </button>\n {errorDetails && error && (\n <>\n <ul className=\"f6 list pl0\">\n {operationIds &&\n operationIds.map(operationId => (\n <li key={operationId}>\n <span>Operation ID:</span>{' '}\n <span className=\"i\">{operationId}</span>\n </li>\n ))}\n </ul>\n <pre>\n <code className=\"f6\">{error.stack}</code>\n </pre>\n </>\n )}\n {errorDetails && componentStack && (\n <pre>\n <code className=\"f6\">{componentStack}</code>\n </pre>\n )}\n </div>\n )\n }\n}\n\nexport default ExtensionPointError\n\n```" } ]
code_store-on-localhost_7de25842
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionPoint.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { mergeDeepRight, reduce } from 'ramda'\nimport React, { FC, Fragment, Suspense } from 'react'\n\nimport ExtensionPointComponent from './ExtensionPointComponent'\nimport Loading from './Loading'\nimport { useRuntime } from './RenderContext'\nimport { useTreePath } from '../utils/treePath'\nimport NoSSR from './NoSSR'\nimport { withErrorBoundary } from './ErrorBoundary'\nimport GenericPreview from './Preview/GenericPreview'\nimport LoadingBar from './LoadingBar'\n\n// TODO: Export components separately on @vtex/blocks-inspector, so this import can be simplified\nconst InspectBlockWrapper = React.lazy(\n () =>\n new Promise<{ default: any }>(resolve => {\n \n })\n)\n\ninterface Props {\n id: string\n key?: string\n params?: any\n query?: any\n preview?: boolean\n treePath?: string\n blockProps?: object\n}\n\nfunction mountTreePath(currentId: string, parentTreePath: string) {\n if (parentTreePath === currentId) {\n return parentTreePath\n }\n return [parentTreePath, currentId].filter(id => !!id).join('/')\n}\n\nfunction getChildExtensions(runtime: any, treePath: string) {\n const extension = runtime.extensions && runtime.extensions[treePath]\n\n if (!extension || !extension.blocks) {\n return\n }\n\n // This filter condition is for backwards compatibility\n return extension.blocks\n .filter(block => block.children === undefined || block.children === true)\n .map((child, i) => {\n const childTreePath = mountTreePath(child.extensionPointId, treePath)\n\n const childExtension =\n runtime.extensions && runtime.extensions[childTreePath]\n const childProps = childExtension ? childExtension.props : {}\n\n return (\n <ExtensionPoint\n key={`around-${treePath}-${i}`}\n id={child.extensionPointId}\n blockProps={childProps}\n treePath={treePath}\n />\n )\n })\n}\n\nfunction withOuterExtensions(\n after: string[],\n around: string[],\n before: string[],\n treePath: string,\n props: any,\n element: JSX.Element\n) {\n const beforeElements = before.map(beforeId => (\n <ExtensionPoint\n id={beforeId}\n key={beforeId}\n treePath={treePath}\n params={props.params}\n query={props.query}\n />\n ))\n\n const afterElements = after.map(afterId => (\n <ExtensionPoint\n id={afterId}\n key={afterId}\n treePath={treePath}\n params={props.params}\n query={props.query}\n />\n ))\n\n const isRootTreePath = treePath.indexOf('/') === -1\n\n const wrapped = (\n <Fragment key={`wrapped-${treePath}`}>\n {beforeElements}\n {element}\n {isRootTreePath && <div className=\"flex flex-grow-1\" />}\n {afterElements}\n </Fragment>\n )\n\n return around.reduce((acc, aroundId) => {\n return (\n <ExtensionPoint\n {...props}\n id={aroundId}\n key={aroundId}\n treePath={treePath}\n beforeElements={beforeElements}\n afterElements={afterElements}\n >\n {acc}\n </ExtensionPoint>\n )\n }, wrapped)\n}\n\nconst ExtensionPoint: FC<Props> = props => {\n const runtime = useRuntime()\n\n const { inspect } = runtime\n\n const treePathFromHook = useTreePath()\n\n const { children, params, query, id, blockProps, ...parentProps } = props\n\n const newTreePath = React.useMemo(\n () => mountTreePath(id, props.treePath || treePathFromHook.treePath),\n [id, props.treePath, treePathFromHook.treePath]\n )\n\n const extension = React.useMemo(() => {\n return runtime.extensions && runtime.extensions[newTreePath]\n }, [newTreePath, runtime.extensions])\n\n const {\n component = null,\n after = [],\n around = [],\n before = [],\n content = {},\n render: renderStrategy = null,\n props: extensionProps = {},\n } = extension || {}\n\n const mergedProps = React.useMemo(() => {\n return reduce(mergeDeepRight, {} as any, [\n /** Extra props passed to the ExtensionPoint component\n * e.g. <ExtensionPoint foo=\"bar\" />\n */\n parentProps,\n /** Props that are read from runtime.extensions, that come from the blocks files\n */\n extensionProps,\n /** Props from the blockProps prop, used when the user wants to prevent overriding\n * the native ExtensionPoint props (such as `id`)\n */\n blockProps || {},\n content,\n { params, query },\n ])\n }, [parentProps, extensionProps, blockProps, content, params, query])\n\n if (\n /* Stops rendering if the extension is not found. Useful for optional ExtensionPoints */\n !extension\n ) {\n return null\n }\n\n const isCompositionChildren =\n extension && extension.composition === 'children'\n\n const componentChildren =\n isCompositionChildren && extension.blocks\n ? getChildExtensions(runtime, newTreePath)\n : children\n\n const isRootTreePath = newTreePath.indexOf('/') === -1\n\n const extensionPointComponent = withOuterExtensions(\n after,\n around,\n before,\n newTreePath,\n mergedProps,\n\n <ExtensionPointComponent\n component={component}\n props={mergedProps}\n runtime={runtime}\n treePath={newTreePath}\n >\n {component ? (\n componentChildren\n ) : isRootTreePath ? (\n <GenericPreview />\n ) : (\n <Loading />\n )}\n </ExtensionPointComponent>\n )\n\n // \"client\" component assets are sent to server side rendering,\n // but they should display a loading animation.\n //\n // \"lazy\" components might never be used, so they don't necessarily\n // need a loading animation.\n const maybeClientExtension = (\n <Fragment>\n {runtime.preview && isRootTreePath && <LoadingBar />}\n {renderStrategy === 'client' && !runtime.amp ? (\n <NoSSR onSSR={<Loading />}>{extensionPointComponent}</NoSSR>\n ) : (\n extensionPointComponent\n )}\n </Fragment>\n )\n\n /** If it's on inspect mode (?__inspect on querystring) wraps the block\n * on a block-inspector wrapper */\n if (inspect) {\n return (\n <Suspense fallback={maybeClientExtension}>\n <InspectBlockWrapper extension={extension} treePath={newTreePath}>\n {maybeClientExtension}\n </InspectBlockWrapper>\n </Suspense>\n )\n }\n\n return maybeClientExtension\n}\n\nExtensionPoint.defaultProps = {\n blockProps: {},\n treePath: '',\n}\n\nexport default withErrorBoundary(ExtensionPoint) as any\n\n```" } ]
code_store-on-localhost_e9d5c304
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/MaybeContext.test.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { cleanup, render } from '@vtex/test-tools/react'\nimport 'jest-dom/extend-expect'\nimport MaybeContext from './MaybeContext'\n\nafterEach(cleanup)\n\nconst TEST_STRING = 'This is category '\n\nbeforeAll(() => {\n window.__RENDER_8_COMPONENTS__ = {\n product: function MockProduct(props: any) {\n return (\n <div>\n <h1>{props.title}</h1>\n <p>{TEST_STRING + props.categoryId}!</p>\n </div>\n )\n } as any,\n }\n})\n\ntest(`it should pass props defined in extensions[path]context.props to the underlying component`, () => {\n const PAGE = 'store.product'\n const mockContextProps = { categoryId: 1, title: 'Product!' }\n const mockExtensions: Record<string, Partial<Extension>> = {\n [PAGE]: {\n context: {\n props: mockContextProps,\n component: 'product',\n },\n },\n }\n\n const mockRuntime: any = { extensions: mockExtensions }\n\n const { getByText } = render(\n <MaybeContext nestedPage={PAGE} runtime={mockRuntime} />\n )\n expect(getByText(new RegExp(mockContextProps.title, 'i'))).toBeInTheDocument()\n expect(\n getByText(new RegExp(TEST_STRING + mockContextProps.categoryId, 'i'))\n ).toBeInTheDocument()\n})\n\nafterAll(() => {\n delete window.__RENDER_8_COMPONENTS__\n})\n\n```" } ]
code_store-on-localhost_02e117fd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/LayoutContainer.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport { useTreePath } from '../utils/treePath'\nimport ExtensionPoint from './ExtensionPoint'\nimport { useRuntime } from './RenderContext'\nimport { LoadingWrapper } from './LoadingContext'\n\ntype Element = string | ElementArray\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\ninterface ElementArray extends Array<Element> {}\n\ninterface LayoutContainerProps {\n aboveTheFold?: number\n elements: Element\n}\n\ninterface ContainerProps {\n aboveTheFold?: number\n elements: Element\n isRow: boolean\n isMobile?: boolean\n preview?: boolean\n}\n\ninterface ContainerState {\n shouldRenderBelowTheFold: boolean\n}\n\nconst elementPropType = PropTypes.oneOfType([PropTypes.string, PropTypes.array])\n .isRequired\n\nclass Container extends Component<ContainerProps, ContainerState> {\n public static propTypes = {\n aboveTheFold: PropTypes.number,\n elements: elementPropType,\n isRow: PropTypes.bool,\n isMobile: PropTypes.bool,\n preview: PropTypes.bool,\n }\n\n public state = {\n shouldRenderBelowTheFold: false,\n }\n\n private handleScroll = () => {\n this.setState({\n shouldRenderBelowTheFold: true,\n })\n\n window.document.removeEventListener('scroll', this.handleScroll)\n }\n\n public componentDidMount() {\n window &&\n window.document &&\n window.document.addEventListener('scroll', this.handleScroll)\n }\n\n public componentWillUnmount() {\n window &&\n window.document &&\n window.document.removeEventListener('scroll', this.handleScroll)\n }\n\n public render() {\n const { isRow, isMobile, elements, children, ...props } = this.props\n\n const { shouldRenderBelowTheFold } = this.state\n\n const className = `flex flex-grow-1 w-100 ${\n isRow ? 'flex-row' : 'flex-column'\n }`\n if (typeof elements === 'string') {\n if (elements === '__children__') {\n return children\n }\n return (\n <div className={isRow ? '' : className}>\n <ExtensionPoint id={elements} {...props} />\n </div>\n )\n }\n\n let elementsToRender = this.props.elements.length\n if (this.props.preview && this.props.aboveTheFold != null) {\n elementsToRender = this.props.aboveTheFold\n }\n\n let foldIndex = elements.indexOf('__fold__')\n if (foldIndex === -1) {\n foldIndex = elements.indexOf(\n `__fold__.${isMobile ? 'mobile' : 'desktop'}`\n )\n }\n\n const hasFold = foldIndex > -1\n\n if (hasFold && !shouldRenderBelowTheFold) {\n elementsToRender = foldIndex + 1\n }\n\n const returnValue: JSX.Element[] = elements\n .slice(0, elementsToRender)\n .map((element: Element) => {\n return (\n <Container\n key={element.toString()}\n elements={element}\n isMobile={isMobile}\n isRow={!isRow}\n {...props}\n >\n {children}\n </Container>\n )\n })\n\n return (\n <div\n className={className}\n style={{\n // Forces scrolling if there is below-the-fold content to be rendered\n minHeight: hasFold && !shouldRenderBelowTheFold ? '101vh' : 'auto',\n }}\n >\n {returnValue}\n </div>\n )\n }\n}\n\nconst LayoutContainer: React.FunctionComponent<LayoutContainerProps> = props => {\n const { extensions, preview, hints } = useRuntime()\n const { treePath } = useTreePath()\n\n const extension = extensions[treePath]\n\n const elements =\n (extension &&\n extension.blocks &&\n extension.blocks.map(insertion => insertion.extensionPointId)) ||\n []\n const containerProps = { ...props, elements }\n\n const container = (\n <Container\n {...containerProps}\n preview={preview}\n isRow={false}\n isMobile={hints.mobile}\n />\n )\n\n const isRootTreePath = treePath.indexOf('/') === -1\n\n if (extension.preview && isRootTreePath) {\n /** TODO: LoadingWrapper is in the end a makeshift Suspense.\n * Should probably be replaced in the future. */\n return <LoadingWrapper>{container}</LoadingWrapper>\n }\n\n return container\n}\n\nexport default LayoutContainer\n\n```" } ]
code_store-on-localhost_19e148cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionContainer.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, Fragment } from 'react'\n\nimport { getDirectChildren, useTreePath } from '../utils/treePath'\nimport ExtensionPoint from './ExtensionPoint'\nimport { useRuntime } from './RenderContext'\n\nconst join = (p: string | null, c: string | null): string =>\n [p, c].filter(id => !!id).join('/')\n\ninterface Props {\n id: string | null\n}\n\nconst ExtensionContainer: FC<Props> = props => {\n const { id } = props\n const { extensions } = useRuntime()\n const { treePath } = useTreePath()\n const containerTreePath = join(treePath, id)\n return (\n <Fragment>\n {getDirectChildren(extensions, containerTreePath).map(cid => {\n const childTreePath = join(id, cid)\n return (\n <ExtensionPoint {...props} key={childTreePath} id={childTreePath} />\n )\n })}\n </Fragment>\n )\n}\n\nexport default ExtensionContainer\n\n```" } ]
code_store-on-localhost_00658829
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionPortal.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { Component, ReactPortal } from 'react'\nimport { createPortal } from 'react-dom'\n\nimport { PortalRenderingRequest } from './ExtensionManager'\nimport ExtensionPoint from './ExtensionPoint'\n\ninterface Props {\n extension: PortalRenderingRequest\n}\n\nclass ExtensionPortal extends Component<Props> {\n public static propTypes = {\n extension: PropTypes.object,\n }\n\n public constructor(props: Props) {\n super(props)\n }\n\n public render() {\n const { extensionName, destination, props } = this.props.extension\n return createPortal(\n <ExtensionPoint id={extensionName} {...props} />,\n destination\n ) as ReactPortal\n }\n}\n\nexport default ExtensionPortal\n\n```" } ]
code_store-on-localhost_803f4770
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionManager.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport { any, map, append } from 'ramda'\nimport React, { Component } from 'react'\n\nimport ExtensionPortal from './ExtensionPortal'\n\nexport interface PortalRenderingRequest {\n extensionName: string\n destination: HTMLElement\n props: any\n}\n\ninterface Props {\n runtime: any\n}\n\ninterface State {\n extensionsToRender: PortalRenderingRequest[]\n}\n\nclass ExtensionManager extends Component<Props, State> {\n public static propTypes = {\n runtime: PropTypes.object,\n }\n\n public constructor(props: Props) {\n super(props)\n this.state = {\n extensionsToRender: [],\n }\n }\n\n public componentDidMount() {\n const {\n runtime: { emitter },\n } = this.props\n emitter.addListener(\n 'renderExtensionLoader.addOrUpdateExtension',\n this.updateExtensions\n )\n }\n\n public componentWillUnmount() {\n const {\n runtime: { emitter },\n } = this.props\n emitter.removeListener(\n 'renderExtensionLoader.addOrUpdateExtension',\n this.updateExtensions\n )\n }\n\n public updateExtensions = (extension: PortalRenderingRequest) => {\n this.setState({\n extensionsToRender: this.addOrUpdateExtension(\n this.state.extensionsToRender,\n extension\n ),\n })\n }\n\n public render() {\n return this.state.extensionsToRender.map(el => {\n return <ExtensionPortal key={el.extensionName} extension={el} />\n })\n }\n\n private addOrUpdateExtension = (\n extensionsList: PortalRenderingRequest[],\n newExtension: PortalRenderingRequest\n ): PortalRenderingRequest[] => {\n const exists = any((el: PortalRenderingRequest) => {\n return el.extensionName === newExtension.extensionName\n })(extensionsList)\n const newExtensionsList = exists\n ? map((el: PortalRenderingRequest) => {\n return el.extensionName === newExtension.extensionName\n ? newExtension\n : el\n }, extensionsList)\n : append(newExtension, extensionsList)\n return newExtensionsList\n }\n}\n\nexport default ExtensionManager\n\n```" } ]
code_store-on-localhost_aa3de7b2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Session.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, Fragment, useEffect, useState } from 'react'\nimport Loading from './Loading'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n renderWhileLoading?: boolean\n}\n\nconst Session: FunctionComponent<Props> = ({\n renderWhileLoading,\n children,\n}) => {\n const [ensured, setEnsured] = useState(false)\n const [error, setError] = useState(null)\n const { ensureSession } = useRuntime()\n\n useEffect(() => {\n let isCurrent = true\n if (ensured || error) {\n return\n }\n\n ensureSession?.()\n .then(() => {\n if (isCurrent) {\n setEnsured(true)\n }\n })\n .catch((err: any) => {\n if (isCurrent) {\n setError(err)\n }\n })\n\n return () => {\n isCurrent = false\n }\n }, [ensureSession, ensured, error])\n\n if (ensured || renderWhileLoading) {\n return <Fragment>{children}</Fragment>\n }\n\n if (error) {\n return (\n <div className=\"bg-washed-red pa6 f5 serious-black br3 pre\">\n <span>Error initializing session</span>\n <pre>\n <code className=\"f6\">{error}</code>\n </pre>\n </div>\n )\n }\n\n return <Loading />\n}\n\nexport default Session\n\n```" } ]
code_store-on-localhost_a2322add
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/LoadingBar.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport styles from './LoadingBar.css'\n\nconst LoadingBar = () => (\n <div\n className={`${styles.loadingBarAnimation} fixed top-0 left-0 right-0 z-max bg-action-primary`}\n style={{ height: 4 }}\n >\n <div\n style={{\n background:\n 'linear-gradient(90deg, rgba(255, 255, 255, 0.1) 80%, rgba(255, 255, 255, 0.5) 90%, rgba(255, 255, 255, 0.8))',\n width: '100%',\n height: '100%',\n }}\n />\n </div>\n)\n\nexport default LoadingBar\n\n```" } ]
code_store-on-localhost_e1c13b1f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/RenderProvider.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { NormalizedCacheObject } from 'apollo-cache-inmemory'\nimport ApolloClient from 'apollo-client'\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport debounce from 'debounce'\nimport { canUseDOM } from 'exenv'\nimport { History, UnregisterCallback } from 'history'\nimport PropTypes from 'prop-types'\nimport { forEach, merge, mergeWith, equals } from 'ramda'\nimport React, { Component, Fragment, ReactElement, Suspense } from 'react'\nimport { ApolloProvider } from 'react-apollo'\nimport { Helmet } from 'react-helmet'\nimport { IntlProvider } from 'react-intl'\nimport gql from 'graphql-tag'\n\nimport {\n fetchAssets,\n getLoadedImplementation,\n hotReloadOverrides,\n hotReloadTachyons,\n prefetchAssets,\n hasComponentImplementation,\n} from '../utils/assets'\nimport PageCacheControl from '../utils/cacheControl'\nimport { getClient } from '../utils/client'\nimport { OperationContext } from '../utils/client/links/uriSwitchLink'\nimport {\n traverseComponent,\n traverseListOfComponents,\n} from '../utils/components'\nimport {\n isSiteEditorIframe,\n RENDER_CONTAINER_CLASS,\n ROUTE_CLASS_PREFIX,\n routeClass,\n} from '../utils/dom'\nimport { isEnabled } from '../utils/flags'\nimport {\n goBack as pageGoBack,\n mapToQueryString,\n navigate as pageNavigate,\n NavigateOptions,\n queryStringToMap,\n scrollTo as pageScrollTo,\n NavigationRouteModifier,\n NavigationRouteChange,\n} from '../utils/pages'\nimport {\n fetchDefaultPages,\n fetchNavigationPage,\n fetchServerPage,\n} from '../utils/routes'\nimport { TreePathContextProvider } from '../utils/treePath'\nimport BuildStatus from './BuildStatus'\nimport ExtensionManager from './ExtensionManager'\nimport ExtensionPoint from './ExtensionPoint'\nimport { RenderContextProvider } from './RenderContext'\nimport RenderPage from './RenderPage'\nimport { appendLocationSearch } from '../utils/location'\nimport { setCookie } from '../utils/cookie'\n\n// TODO: Export components separately on @vtex/blocks-inspector, so this import can be simplified\nconst InspectorPopover = React.lazy(\n () =>\n new Promise<{ default: any }>(resolve => {\n \n })\n)\n\ninterface Props {\n children: ReactElement<any> | null\n history: History | null\n cacheControl?: PageCacheControl\n baseURI: string\n root: string\n runtime: any\n}\n\nexport interface RenderProviderState {\n appsEtag: any['appsEtag']\n cacheHints: any['cacheHints']\n components: any['components']\n culture: any['culture']\n defaultExtensions: any['defaultExtensions']\n device: any\n extensions: any['extensions']\n inspect: any['inspect']\n messages: any['messages']\n page: any['page']\n pages: any['pages']\n preview: any['preview']\n production: any['production']\n query: any['query']\n settings: any['settings']\n route: any['route']\n loadedPages: Set<string>\n blocksTree?: any['blocksTree']\n blocks?: any['blocks']\n contentMap?: any['contentMap']\n}\n\nconst SEND_INFO_DEBOUNCE_MS = 100\nconst DISABLE_PREFETCH_PAGES = '__disablePrefetchPages'\n\nconst noop = () => {}\n\nconst areOptionsDifferent = (a: NavigateOptions, b: NavigateOptions) => {\n return (\n a.page !== b.page ||\n a.query !== b.query ||\n a.to !== b.to ||\n a.rootPath !== b.rootPath ||\n !equals(a.params, b.params)\n )\n}\n\ninterface NavigationState {\n isNavigating: boolean\n lastOptions?: NavigateOptions\n}\n\nclass RenderProvider extends Component<Props, RenderProviderState> {\n navigationState: NavigationState = { isNavigating: false }\n public static childContextTypes = {\n account: PropTypes.string,\n addMessages: PropTypes.func,\n amp: PropTypes.bool,\n binding: PropTypes.object,\n blocks: PropTypes.object,\n blocksTree: PropTypes.object,\n contentMap: PropTypes.object,\n components: PropTypes.object,\n culture: PropTypes.object,\n defaultExtensions: PropTypes.object,\n device: PropTypes.string,\n emitter: PropTypes.object,\n ensureSession: PropTypes.func,\n extensions: PropTypes.object,\n fetchComponent: PropTypes.func,\n fetchComponents: PropTypes.func,\n getSettings: PropTypes.func,\n goBack: PropTypes.func,\n hints: PropTypes.object,\n history: PropTypes.object,\n inspect: PropTypes.bool,\n messages: PropTypes.object,\n navigate: PropTypes.func,\n onPageChanged: PropTypes.func,\n page: PropTypes.string,\n pages: PropTypes.object,\n patchSession: PropTypes.func,\n platform: PropTypes.string,\n prefetchDefaultPages: PropTypes.func,\n addNavigationRouteModifier: PropTypes.func,\n prefetchPage: PropTypes.func,\n preview: PropTypes.bool,\n production: PropTypes.bool,\n publicEndpoint: PropTypes.string,\n query: PropTypes.object,\n renderMajor: PropTypes.number,\n rootPath: PropTypes.string,\n route: PropTypes.object,\n setDevice: PropTypes.func,\n setQuery: PropTypes.func,\n updateComponentAssets: PropTypes.func,\n updateExtension: PropTypes.func,\n updateRuntime: PropTypes.func,\n workspace: PropTypes.string,\n }\n\n public static propTypes = {\n children: PropTypes.element,\n history: PropTypes.object,\n root: PropTypes.string,\n runtime: PropTypes.object,\n }\n\n public sendInfoFromIframe = debounce(\n (params?: { shouldUpdateRuntime?: boolean }) => {\n if (!isSiteEditorIframe) {\n return undefined\n }\n\n return (window as any).top.__provideRuntime(\n this.getChildContext(),\n this.state.messages,\n (params && params.shouldUpdateRuntime) || false,\n // Deprecated\n this.updateMessages\n )\n },\n SEND_INFO_DEBOUNCE_MS\n )\n\n private rendered!: boolean\n private sessionPromise: Promise<void>\n private unlisten!: UnregisterCallback | null\n private apolloClient: ApolloClient<NormalizedCacheObject>\n private prefetchRoutes: Set<string>\n private navigationRouteModifiers: Set<NavigationRouteModifier>\n private navigationModifierOptions: Record<string, NavigationRouteChange>\n private fetcher: any['fetch']\n\n public constructor(props: Props) {\n super(props)\n const {\n appsEtag,\n binding,\n blocks,\n blocksTree,\n cacheHints,\n contentMap,\n culture,\n messages,\n components,\n exposeBindingAddress,\n extensions,\n pages,\n page,\n query,\n production,\n rootPath = '',\n route,\n settings,\n queryData,\n } = props.runtime\n const { history, baseURI, cacheControl } = props\n const ignoreCanonicalReplacement = query && query.map\n this.fetcher = fetch\n\n if (binding && canUseDOM) {\n setCookie('vtex_binding_address', binding.canonicalBaseAddress)\n }\n\n if (history) {\n const renderLocation: any = {\n ...history.location,\n search:\n exposeBindingAddress && binding\n ? appendLocationSearch(history.location.search, {\n __bindingAddress: binding.canonicalBaseAddress,\n })\n : history.location.search,\n pathname:\n ignoreCanonicalReplacement || !route.canonicalPath\n ? history.location.pathname\n : rootPath + route.canonicalPath,\n state: {\n navigationRoute: {\n id: route.id,\n params: route.params,\n path: history.location.pathname,\n },\n renderRouting: true,\n },\n }\n // TODO: use something with better performance than equals\n if (!equals(history.location as any, renderLocation)) {\n history.replace(renderLocation)\n }\n // backwards compatibility\n window.browserHistory = (global as any).browserHistory = history\n }\n\n // todo: reload window if client-side created a segment different from server-side\n this.sessionPromise = canUseDOM\n ? window.__RENDER_8_SESSION__.sessionPromise\n : Promise.resolve()\n const runtimeContextLink = this.createRuntimeContextLink()\n this.apolloClient = getClient(\n props.runtime,\n baseURI,\n runtimeContextLink,\n this.sessionPromise,\n this.fetcher,\n cacheControl\n )\n\n if (queryData) {\n this.hydrateApolloCache(queryData)\n }\n\n this.state = {\n appsEtag,\n blocks,\n blocksTree,\n cacheHints,\n contentMap,\n components,\n culture,\n defaultExtensions: {},\n device: 'any',\n extensions,\n loadedPages: new Set([page]),\n messages,\n page,\n pages,\n preview: false,\n production,\n query,\n route,\n settings: settings || {},\n inspect: false,\n }\n\n this.prefetchRoutes = new Set<string>()\n this.navigationRouteModifiers = new Set()\n this.navigationModifierOptions = {}\n }\n\n public componentDidMount() {\n this.rendered = true\n const { history, runtime } = this.props\n const { production, emitter, publicEndpoint } = runtime\n\n this.unlisten = history && history.listen(this.onPageChanged)\n emitter.addListener('localesChanged', this.onLocaleSelected)\n\n if (!production) {\n emitter.addListener('extensionsUpdated', this.updateRuntime)\n emitter.addListener('blocksUpdated', this.updateRuntime)\n emitter.addListener('styleOverrides', hotReloadOverrides)\n emitter.addListener('styleTachyonsUpdate', hotReloadTachyons)\n }\n\n this.sendInfoFromIframe()\n this.prefetchPages()\n\n if (\n publicEndpoint === 'myvtex.com' &&\n !production &&\n '__inspect' in (this.state.query || {})\n ) {\n this.setState({ inspect: true })\n }\n }\n\n public UNSAFE_componentWillReceiveProps(nextProps: Props) {\n // If RenderProvider is being re-rendered, the global runtime might have changed\n // so we must update all extensions.\n if (this.rendered) {\n const {\n runtime: { extensions },\n } = nextProps\n this.setState({ extensions })\n }\n }\n\n public componentWillUnmount() {\n const { runtime } = this.props\n const { production, emitter } = runtime\n if (this.unlisten) {\n this.unlisten()\n }\n emitter.removeListener('localesChanged', this.onLocaleSelected)\n\n if (!production) {\n emitter.removeListener('extensionsUpdated', this.updateRuntime)\n emitter.removeListener('blocksUpdated', this.updateRuntime)\n emitter.removeListener('styleOverrides', hotReloadOverrides)\n emitter.removeListener('styleTachyonsUpdate', hotReloadTachyons)\n }\n }\n\n public getChildContext(): any {\n const { history, runtime } = this.props\n const {\n components,\n contentMap,\n extensions,\n inspect,\n messages,\n page,\n pages,\n preview,\n culture,\n device,\n route,\n query,\n defaultExtensions,\n } = this.state\n\n const {\n account,\n amp,\n binding,\n emitter,\n hints,\n platform,\n production,\n publicEndpoint,\n renderMajor,\n rootPath,\n workspace,\n } = runtime\n\n return {\n account,\n addMessages: this.addMessages,\n amp,\n binding,\n components,\n contentMap,\n culture,\n defaultExtensions,\n device,\n emitter,\n ensureSession: this.ensureSession,\n extensions,\n fetchComponent: this.fetchComponent,\n fetchComponents: this.fetchComponents,\n getSettings: this.getSettings,\n goBack: this.goBack,\n hints,\n history,\n inspect,\n messages,\n navigate: this.navigate,\n onPageChanged: this.onPageChanged,\n page,\n pages,\n patchSession: this.patchSession,\n platform,\n prefetchDefaultPages: this.prefetchDefaultPages,\n addNavigationRouteModifier: this.addNavigationRouteModifier,\n prefetchPage: this.prefetchPage,\n preview,\n production,\n publicEndpoint,\n query,\n renderMajor,\n rootPath,\n route,\n setDevice: this.handleSetDevice,\n setQuery: this.setQuery,\n updateComponentAssets: this.updateComponentAssets,\n updateExtension: this.updateExtension,\n updateRuntime: this.updateRuntime,\n workspace,\n }\n }\n\n public getSettings = (app: string) => {\n const { settings } = this.state\n return settings[app]\n }\n\n public ensureSession = () => {\n return this.sessionPromise\n }\n\n public patchSession = (data?: any) => {\n return this.sessionPromise.then(() =>\n canUseDOM ? window.__RENDER_8_SESSION__.patchSession(data) : undefined\n )\n }\n\n public getCustomMessages = (locale: string) => {\n const { components } = this.state\n const componentsArray = Object.keys(components)\n\n const customMessages = componentsArray\n .map(getLoadedImplementation)\n .filter(\n component =>\n component &&\n (component.getCustomMessages || component.WrappedComponent)\n )\n .map(component => {\n const getCustomMessages =\n component.getCustomMessages ||\n (component.WrappedComponent &&\n component.WrappedComponent.getCustomMessages) ||\n noop\n return getCustomMessages(locale)\n })\n .reduce((acc, strings) => ({ ...acc, ...strings }), {})\n\n return customMessages\n }\n\n public goBack = () => {\n const { history } = this.props\n return pageGoBack(history)\n }\n\n public setQuery = (\n query: Record<string, any> = {},\n {\n merge = true,\n replace = false,\n scrollOptions = false,\n }: any = {}\n ): boolean => {\n const {\n history,\n runtime: { rootPath },\n } = this.props\n const {\n pages,\n page,\n route: { params },\n } = this.state\n if (!history) {\n return false\n }\n const {\n location: { search },\n } = history\n\n const current = queryStringToMap(search)\n const nextQuery = mapToQueryString(merge ? { ...current, ...query } : query)\n\n return pageNavigate(history, pages, {\n fetchPage: false,\n page,\n params,\n query: nextQuery,\n replace,\n scrollOptions,\n rootPath,\n modifiers: this.navigationRouteModifiers,\n })\n }\n\n public navigate = (options: NavigateOptions) => {\n const {\n history,\n runtime: { rootPath },\n } = this.props\n const { pages } = this.state\n options.rootPath = rootPath\n options.modifiers = this.navigationRouteModifiers\n\n this.navigationModifierOptions = {\n ...this.navigationModifierOptions,\n ...options.modifiersOptions,\n }\n options.modifiersOptions = this.navigationModifierOptions\n\n if (this.navigationState.isNavigating) {\n const lastOptions = this.navigationState.lastOptions!\n if (!areOptionsDifferent(lastOptions, options)) {\n return false\n }\n }\n\n this.navigationState = {\n isNavigating: true,\n lastOptions: options,\n }\n\n return pageNavigate(history, pages, options)\n }\n\n public addNavigationRouteModifier = (modifier: NavigationRouteModifier) => {\n this.navigationRouteModifiers.add(modifier)\n }\n\n public replaceRouteClass = (route: string) => {\n try {\n const containers = document.getElementsByClassName(RENDER_CONTAINER_CLASS)\n const currentRouteClass = containers[0].className\n .split(' ')\n .find(c => c.startsWith(ROUTE_CLASS_PREFIX))\n const newRouteClass = routeClass(route)\n\n Array.prototype.forEach.call(containers, (e: Element) => {\n if (currentRouteClass) {\n e.classList.remove(currentRouteClass)\n }\n e.classList.add(newRouteClass)\n })\n } catch (e) {\n console.error('Failed to set route class', routeClass(route))\n }\n }\n\n public scrollTo = (scrollOptions?: any) => {\n try {\n if (scrollOptions === false) {\n return\n }\n\n const options = scrollOptions || { top: 0, left: 0 }\n window.setTimeout(() => pageScrollTo(options), 0)\n } catch (e) {\n console.warn('Failed to scroll after page navigation.')\n }\n }\n\n public afterPageChanged = (\n route: string,\n scrollOptions?: any\n ) => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(route)\n this.scrollTo(scrollOptions)\n this.sendInfoFromIframe()\n }\n\n public onPageChanged = (location: any) => {\n const {\n runtime: { renderMajor },\n } = this.props\n const {\n culture: { locale },\n pages: pagesState,\n production,\n route,\n loadedPages,\n } = this.state\n const { state } = location\n\n // Make sure this is our navigation\n if (!state || !state.renderRouting) {\n return\n }\n\n const { navigationRoute, fetchPage } = state\n const { id: maybePage, params } = navigationRoute\n const transientRoute = { ...route, ...navigationRoute }\n\n // We always have to navigate to a page. If none was found, we\n // navigate to the current page with preview\n const allowConditions =\n pagesState[maybePage] && pagesState[maybePage].allowConditions\n const declarer = pagesState[maybePage] && pagesState[maybePage].declarer\n const shouldSkipFetchNavigationData =\n (!allowConditions && loadedPages.has(maybePage)) || fetchPage === false\n const query = queryStringToMap(location.search) as any['query']\n const page = maybePage || route.id\n\n if (shouldSkipFetchNavigationData) {\n return this.setState(\n {\n page,\n query,\n route: transientRoute,\n },\n () => this.afterPageChanged(page, state.scrollOptions)\n )\n }\n\n // Sets the preloading state, which currently displays\n // a loading bar at the top of the page\n this.setState({\n preview: true,\n })\n\n const paramsJSON = JSON.stringify(params)\n const apolloClient = this.apolloClient\n const routeId = page\n // Retrieve the adequate assets for the new page. Naming will\n // probably change (query will return something like routes) as\n // well as the fields that need to be retrieved, but the logic\n // that the new state (extensions and assets) will be derived from\n // the results of this query will probably remain the same.\n const navigationPromise = isEnabled('RENDER_NAVIGATION')\n ? fetchServerPage({\n fetcher: this.fetcher,\n path: navigationRoute.path,\n query,\n }).then(\n async ({\n appsEtag,\n components,\n extensions,\n matchingPage,\n messages,\n pages,\n settings,\n queryData,\n }: any) => {\n if (queryData) {\n this.hydrateApolloCache(queryData)\n }\n\n await this.fetchComponents(components, extensions)\n\n this.setState(\n state => ({\n ...state,\n appsEtag,\n components: { ...state.components, ...components },\n extensions: { ...state.extensions, ...extensions },\n loadedPages: loadedPages.add(matchingPage.routeId),\n messages: { ...state.messages, ...messages },\n page: matchingPage.routeId,\n pages,\n preview: false,\n query,\n route: matchingPage,\n settings,\n }),\n () => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(matchingPage.routeId)\n this.sendInfoFromIframe()\n this.scrollTo(state.scrollOptions)\n }\n )\n }\n )\n : fetchNavigationPage({\n apolloClient,\n declarer,\n locale,\n paramsJSON,\n production,\n query: JSON.stringify(query),\n renderMajor,\n routeId,\n skipCache: false,\n }).then(\n async ({\n appsEtag,\n cacheHints,\n components,\n extensions,\n matchingPage,\n messages,\n pages,\n settings,\n }: any) => {\n const updatedRoute = { ...transientRoute, ...matchingPage }\n await this.fetchComponents(components, extensions)\n\n this.setState(\n {\n appsEtag,\n cacheHints: mergeWith(merge, this.state.cacheHints, cacheHints),\n components: { ...this.state.components, ...components },\n extensions: { ...this.state.extensions, ...extensions },\n loadedPages: loadedPages.add(page),\n messages: { ...this.state.messages, ...messages },\n page,\n pages,\n preview: false,\n query,\n route: updatedRoute,\n settings,\n },\n () => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(page)\n this.sendInfoFromIframe()\n this.scrollTo(state.scrollOptions)\n }\n )\n }\n )\n navigationPromise.finally(() => {\n if (this.navigationState.isNavigating) {\n this.navigationState = { isNavigating: false }\n }\n })\n return navigationPromise\n }\n\n public prefetchPage = (pageName: string) => {\n const { extensions } = this.state\n const component = extensions[pageName] && extensions[pageName].component\n if (component) {\n const { runtime } = this.props\n const { components } = this.state\n const componentsAssetsMap = traverseComponent(components, component)\n return prefetchAssets(runtime, componentsAssetsMap)\n }\n }\n\n public prefetchDefaultPages = async (routeIds: string[]) => {\n const {\n runtime: { query },\n } = this.props\n\n const disablePrefetch =\n query &&\n DISABLE_PREFETCH_PAGES in query &&\n query[DISABLE_PREFETCH_PAGES] !== 'false'\n if (!disablePrefetch) {\n if (this.rendered) {\n console.warn(\n \"prefetchDefaultPages should only be called before RenderProvider's render.\"\n )\n return\n }\n routeIds.forEach(routeId => this.prefetchRoutes.add(routeId))\n }\n }\n\n public updateComponentAssets = (availableComponents: any) => {\n this.setState({\n components: {\n ...this.state.components,\n ...availableComponents,\n },\n })\n }\n\n public fetchComponents = async (\n components: any['components'],\n extensions?: any['extensions']\n ) => {\n const { runtime } = this.props\n // In order for only fetching `components`, we create corresponding extensions\n // for them if they weren't passed\n if (!extensions) {\n const componentsNames = Object.keys(components)\n extensions = componentsNames.reduce((acc, component) => {\n acc[component] = { component }\n return acc\n }, {} as any['extensions'])\n }\n const componentsToDownload = Object.values(extensions).reduce<string[]>(\n (acc, extension: any) => {\n if (extension.render === 'lazy') {\n return acc\n }\n if (!hasComponentImplementation(extension.component)) {\n acc.push(extension.component)\n }\n const context = extension?.context?.component\n if (context && !hasComponentImplementation(context)) {\n acc.push(context)\n }\n return acc\n },\n []\n )\n\n if (componentsToDownload.length === 0) {\n return\n }\n\n const allAssets = traverseListOfComponents(components, componentsToDownload)\n await fetchAssets(runtime, allAssets)\n this.sendInfoFromIframe({ shouldUpdateRuntime: true })\n }\n\n public fetchComponent = (component: string) => {\n if (!canUseDOM) {\n throw new Error('Cannot fetch components during server side rendering.')\n }\n\n const { runtime } = this.props\n const { components } = this.state\n const componentsAssetsMap = traverseComponent(components, component)\n\n const assetsPromise = fetchAssets(runtime, componentsAssetsMap)\n assetsPromise.then(() => {\n this.sendInfoFromIframe({ shouldUpdateRuntime: true })\n })\n\n return assetsPromise\n }\n\n public onLocaleSelected = (locale: string, domain?: string) => {\n if (locale !== this.state.culture.locale) {\n const sessionData = { public: {} }\n if (domain && domain === 'admin') {\n sessionData.public = {\n admin_cultureInfo: {\n value: locale,\n },\n }\n } else {\n sessionData.public = {\n cultureInfo: {\n value: locale,\n },\n }\n }\n this.patchSession(sessionData)\n .then(() => window.location.reload())\n .catch(e => {\n console.log('Failed to fetch new locale file.')\n console.error(e)\n })\n }\n }\n\n public updateRuntime = async (options?: any) => {\n const {\n runtime: { renderMajor },\n } = this.props\n const {\n page,\n pages: pagesState,\n production,\n culture: { locale },\n route,\n query,\n } = this.state\n const declarer = pagesState[page] && pagesState[page].declarer\n const { pathname } = window.location\n const paramsJSON = JSON.stringify(route.params || {})\n\n const {\n appsEtag,\n cacheHints,\n components,\n extensions,\n messages,\n pages,\n settings,\n } = isEnabled('RENDER_NAVIGATION')\n ? await fetchServerPage({\n path: route.path,\n query,\n fetcher: this.fetcher,\n })\n : await fetchNavigationPage({\n apolloClient: this.apolloClient,\n declarer,\n locale,\n paramsJSON,\n path: pathname,\n production,\n query: '',\n renderMajor,\n routeId: page,\n skipCache: true,\n ...options,\n })\n\n await this.fetchComponents(components, extensions)\n\n await new Promise<void>(resolve => {\n this.setState(\n state => ({\n appsEtag,\n cacheHints: isEnabled('RENDER_NAVIGATION')\n ? state.cacheHints\n : cacheHints,\n components,\n extensions: {\n ...state.extensions,\n ...extensions,\n },\n messages: {\n ...state.messages,\n ...messages,\n },\n page,\n pages,\n route,\n settings,\n }),\n resolve\n )\n })\n\n await this.sendInfoFromIframe()\n }\n\n public createRuntimeContextLink() {\n return new ApolloLink((operation: Operation, forward?: NextLink) => {\n const {\n appsEtag,\n cacheHints,\n components,\n culture,\n extensions,\n messages,\n pages,\n } = this.state\n operation.setContext(\n (currentContext: OperationContext): OperationContext => {\n return {\n ...currentContext,\n runtime: {\n appsEtag,\n cacheHints,\n components,\n culture,\n extensions,\n messages,\n pages,\n },\n }\n }\n )\n return forward ? forward(operation) : null\n })\n }\n\n public updateExtension = async (name: string, extension: any) => {\n const { extensions } = this.state\n\n await new Promise<void>(resolve => {\n this.setState(\n {\n extensions: {\n ...extensions,\n [name]: extension,\n },\n },\n resolve\n )\n })\n\n if (name !== 'store/__overlay') {\n await this.sendInfoFromIframe()\n }\n }\n\n public handleSetDevice = (device: any) => {\n this.setState({ device })\n }\n\n public addMessages = async (newMessages: any['messages']) => {\n await new Promise<void>(resolve => {\n this.setState(\n state => ({\n ...state,\n messages: {\n ...state.messages,\n ...newMessages,\n },\n }),\n resolve\n )\n })\n\n await this.sendInfoFromIframe()\n }\n\n public render() {\n const { children } = this.props\n const {\n culture: { locale },\n messages,\n pages,\n page,\n query,\n production,\n inspect,\n } = this.state\n const customMessages = this.getCustomMessages(locale)\n const mergedMessages = {\n ...messages,\n ...customMessages,\n }\n\n const component = children ? (\n React.cloneElement(children as ReactElement<any>, { query })\n ) : (\n <div className=\"render-provider\">\n <Helmet title={pages[page] && pages[page].title} />\n <RenderPage page={page} query={query} />\n </div>\n )\n\n const context = this.getChildContext()\n\n return (\n <RenderContextProvider runtime={context}>\n <TreePathContextProvider treePath=\"\">\n <ApolloProvider client={this.apolloClient}>\n <IntlProvider\n locale={locale}\n messages={mergedMessages}\n textComponent={Fragment}\n >\n <Fragment>\n <ExtensionManager runtime={this.props.runtime} />\n {!production && !isSiteEditorIframe && <BuildStatus />}\n {component}\n {isSiteEditorIframe ? (\n <ExtensionPoint id=\"store/__overlay\" />\n ) : null}\n {inspect && (\n <Suspense fallback={null}>\n <InspectorPopover />\n </Suspense>\n )}\n </Fragment>\n </IntlProvider>\n </ApolloProvider>\n </TreePathContextProvider>\n </RenderContextProvider>\n )\n }\n\n private hydrateApolloCache = (\n queryData: Array<{\n data: string\n query: string\n variables: Record<string, any>\n }>\n ) => {\n forEach(({ data, query, variables }) => {\n try {\n this.apolloClient.writeQuery({\n query: gql`\n ${query}\n `,\n data: JSON.parse(data),\n variables,\n })\n } catch (error) {\n console.warn(\n `Error writing query from render-server in Apollo's cache`,\n error\n )\n }\n }, queryData)\n }\n\n // Deprecated\n private updateMessages = (newMessages: RenderProviderState['messages']) => {\n this.setState(\n prevState => ({\n ...prevState,\n messages: { ...prevState.messages, ...newMessages },\n }),\n () => {\n this.sendInfoFromIframe()\n }\n )\n }\n\n private prefetchPages = () => {\n if (this.prefetchRoutes.size > 0) {\n setTimeout(this.execPrefetchPages, 6 * 1000)\n }\n }\n\n private execPrefetchPages = async () => {\n const {\n runtime,\n runtime: { renderMajor },\n } = this.props\n\n const {\n pages,\n culture: { locale },\n } = this.state\n\n const { components: defaultComponents } = await fetchDefaultPages({\n apolloClient: this.apolloClient,\n locale,\n pages,\n renderMajor,\n routeIds: Array.from(this.prefetchRoutes),\n })\n\n const allAssets = traverseListOfComponents(\n defaultComponents,\n Object.keys(defaultComponents)\n )\n\n await prefetchAssets(runtime, allAssets)\n }\n}\n\nexport default RenderProvider\n\n```" } ]
code_store-on-localhost_50137ec9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/RenderContext.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType, useContext } from 'react'\n\nexport interface RenderContextProps {\n runtime: any\n}\n\nexport interface EmitterProps {\n __emitter: any\n}\n\nexport const RenderContext = React.createContext<any>({} as any)\nRenderContext.displayName = 'RenderContext'\n\nexport const RenderContextProvider: React.FC<RenderContextProps> = ({\n children,\n runtime,\n}) => (\n <RenderContext.Provider value={runtime}>{children}</RenderContext.Provider>\n)\nRenderContextProvider.displayName = 'RenderContextProvider'\n\nexport const useRuntime = () => {\n return useContext(RenderContext)\n}\n\nexport const withRuntimeContext = <TOriginalProps extends {} = {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n): ComponentType<TOriginalProps> => {\n const WithRuntimeContext = (props: TOriginalProps) => {\n const runtime = useRuntime()\n return <Component {...props} runtime={runtime} />\n }\n WithRuntimeContext.displayName = `withRuntimeContext(${Component.displayName ||\n Component.name ||\n 'Component'})`\n WithRuntimeContext.WrappedComponent = Component\n return hoistNonReactStatics<any, any>(\n WithRuntimeContext,\n Component\n )\n}\n\nexport const withEmitter = <TOriginalProps extends {} = {}>(\n Component: ComponentType<TOriginalProps & EmitterProps>\n): ComponentType<TOriginalProps> => {\n const WithEmitter = (props: TOriginalProps) => {\n const { emitter } = useRuntime()\n return <Component {...props} __emitter={emitter} />\n }\n WithEmitter.displayName = `withEmitter(${Component.displayName ||\n Component.name ||\n 'Component'})`\n WithEmitter.WrappedComponent = Component\n return hoistNonReactStatics<any, any>(\n WithEmitter,\n Component\n )\n}\n\n```" } ]
code_store-on-localhost_a95c3c0f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionPoint.test.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { cleanup, render } from '@vtex/test-tools/react'\nimport 'jest-dom/extend-expect'\nimport ExtensionPoint from './ExtensionPoint'\nimport { TreePathContextProvider } from '../utils/treePath'\nimport { RenderContextProvider } from './RenderContext'\nimport { TEST_ID as PreviewTestId } from './Preview'\n\nafterEach(cleanup)\n\ntest(`it shouldn't show Preview when there is no extension for current tree path`, () => {\n const mockExtensions: Record<string, Partial<Extension>> = {\n 'store.search#category/search-result#category': {\n component: '',\n preview: {\n height: {\n desktop: { defaultValue: 500 },\n mobile: { defaultValue: 500 },\n },\n width: {\n desktop: { defaultValue: 500 },\n mobile: { defaultValue: 500 },\n },\n type: 'box',\n },\n },\n // The extension below is what the ExtensionPoint should use.\n // 'store.search#category/search-result#category/search-title': undefined,\n }\n\n const { queryByTestId } = render(\n <RenderContextProvider runtime={{ extensions: mockExtensions } as any}>\n <TreePathContextProvider treePath=\"store.search#category/search-result#category\">\n <ExtensionPoint treePath=\"\" id=\"search-title\" />\n </TreePathContextProvider>\n </RenderContextProvider>\n )\n\n expect(queryByTestId(PreviewTestId)).toBeNull()\n})\n\n```" } ]
code_store-on-localhost_648e84c6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/RenderPage.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport ExtensionPoint from './ExtensionPoint'\nimport MaybeContext from './MaybeContext'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n page: string\n query?: Record<string, string>\n}\n\nconst RenderPage: FC<Props> = props => {\n const runtime = useRuntime()\n const { page, query } = props\n const {\n route: { params },\n } = runtime\n\n /** Will use the params of the page as a key for the component, so React will\n * unmount and remount it on page change. This is used to reset components\n * to their initial state on page change, to better simulate how regular\n * web pages work. */\n let paramsString = ''\n\n /** TODO: This is a quick fix--the admin, which runs on an iframe, doesn't play\n * nice with unmounting/remounting. Should perhaps try and find a better solution\n * for this issue. */\n if (!page?.startsWith('admin.')) {\n try {\n paramsString = JSON.stringify(params)\n } catch (e) {\n console.warn(\n \"Unable to stringify params for page. This shouldn't be much of a problem, but might prevent components from being reset on page change. The params object is as follows:\",\n params\n )\n }\n }\n\n return (\n <MaybeContext\n nestedPage={page}\n query={query}\n params={params}\n runtime={runtime}\n >\n <ExtensionPoint\n // Key used to unmount/remount the component on page change.\n key={`${page}/${paramsString}`}\n id={page}\n query={query}\n params={params}\n {...props}\n />\n </MaybeContext>\n )\n}\n\nexport default RenderPage\n\n```" } ]
code_store-on-localhost_02013492
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ExtensionPointComponent.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport ReactDOM from 'react-dom'\nimport React, { ErrorInfo, PureComponent } from 'react'\n\nimport { getImplementation } from '../utils/assets'\nimport graphQLErrorsStore from '../utils/graphQLErrorsStore'\n\nimport ExtensionPointError from './ExtensionPointError'\nimport GenericPreview from './Preview/GenericPreview'\nimport { withLoading } from './LoadingContext'\nimport { RenderContextProps } from './RenderContext'\nimport { TreePathContextProvider } from '../utils/treePath'\nimport { isSiteEditorIframe } from '../utils/dom'\nimport { Loading } from '../index'\n\ninterface Props {\n component: string | null\n props: any\n treePath: string\n setLoading?: (treePath: string, value: boolean) => void\n}\n\ninterface State {\n error?: Error | null\n errorInfo?: ErrorInfo | null\n operationIds: string[]\n lastUpdate?: number\n}\n\nconst componentPromiseMap: any = {}\nconst componentPromiseResolvedMap: any = {}\n\nclass ExtensionPointComponent extends PureComponent<\n Props & RenderContextProps,\n State\n> {\n private _isMounted!: boolean\n private mountedError!: boolean\n\n public constructor(props: Props & RenderContextProps) {\n super(props)\n\n this.state = {\n operationIds: [],\n }\n this.mountedError = false\n }\n\n public updateComponentsWithEvent = (component: string) => {\n if (!this._isMounted) {\n return false\n }\n\n this.setState({ error: null, errorInfo: null, lastUpdate: Date.now() })\n const { component: mounted, treePath } = this.props\n\n console.log(\n `[render] Component updated. treePath=${treePath} ${\n mounted !== component ? `mounted=${mounted} ` : ''\n }updated=${component}`\n )\n\n return true\n }\n\n public fetchAndRerender = () => {\n const {\n component,\n runtime: { fetchComponent },\n } = this.props\n const Component = component && getImplementation(component)\n\n // Let's fetch the assets and re-render.\n if (component && !Component) {\n if (!(component in componentPromiseMap)) {\n componentPromiseMap[component] = fetchComponent(component)\n } else if (componentPromiseResolvedMap[component]) {\n this.stopLoading()\n throw new Error(`Unable to fetch component ${component}`)\n }\n\n componentPromiseMap[component]\n .then(() => {\n componentPromiseResolvedMap[component] = true\n this.updateComponentsWithEvent(component)\n this.stopLoading()\n })\n .catch(() => {\n componentPromiseResolvedMap[component] = true\n this.stopLoading()\n })\n } else {\n this.stopLoading()\n }\n }\n\n private stopLoading = () => {\n if (this.props.setLoading) {\n this.props.setLoading(this.props.treePath, false)\n }\n }\n\n private startLoading = () => {\n if (this.props.setLoading) {\n this.props.setLoading(this.props.treePath, true)\n }\n }\n\n public clearError = () => {\n this.setState({\n error: null,\n errorInfo: null,\n operationIds: [],\n })\n }\n\n public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n const { component, treePath: path } = this.props\n\n console.error('Failed to render extension point', path, component)\n const operationIds = graphQLErrorsStore.getOperationIds()\n\n this.setState({\n error,\n errorInfo,\n operationIds,\n })\n }\n\n public componentDidMount() {\n this._isMounted = true\n this.startLoading()\n this.fetchAndRerender()\n this.addDataToElementIfEditable()\n }\n\n public componentDidUpdate() {\n this.fetchAndRerender()\n if (this.state.error) {\n if (this.mountedError) {\n this.clearError()\n } else {\n this.mountedError = true\n }\n }\n this.addDataToElementIfEditable()\n }\n\n public componentWillUnmount() {\n this.removeDataFromElement()\n this._isMounted = false\n }\n\n public render() {\n const {\n component,\n props,\n children,\n treePath,\n runtime: { production, page },\n props: componentProps,\n } = this.props\n const { error, errorInfo, operationIds } = this.state\n const Component = component && getImplementation(component)\n\n // A children of this extension point throwed an uncaught error\n // Only show errors in production if the entire page explodes. (Ignore nested extension points)\n if (error) {\n if (production && !page.startsWith('admin/')) {\n return null\n }\n\n const errorInstance = (\n <ExtensionPointError\n error={error}\n errorInfo={errorInfo}\n operationIds={operationIds}\n treePath={treePath}\n />\n )\n props.__errorInstance = errorInstance\n props.__clearError = this.clearError\n\n if (!Component || !(Component as any).hotReload) {\n return errorInstance\n }\n } else {\n delete props.__errorInstance\n delete props.__clearError\n }\n\n const isRootTreePath = treePath.indexOf('/') === -1\n const isAround = treePath.indexOf('$around') !== -1\n\n return (\n <TreePathContextProvider treePath={treePath}>\n {Component ? (\n <Component {...props}>{children}</Component>\n ) : isRootTreePath || isAround ? (\n /* Adds header/footer before and after the preview during loading,\n * if the component being loaded is a root component--e.g. context\n * wrappers, `around` wrappers */\n <>\n {componentProps.beforeElements}\n <GenericPreview />\n {componentProps.afterElements}\n </>\n ) : (\n <Loading />\n )}\n </TreePathContextProvider>\n )\n }\n\n private addDataToElementIfEditable = () => {\n if (!isSiteEditorIframe) {\n return\n }\n const ComponentImpl =\n this.props.component && getImplementation(this.props.component)\n const isEditable =\n ComponentImpl &&\n (ComponentImpl.hasOwnProperty('schema') ||\n ComponentImpl.hasOwnProperty('getSchema'))\n\n if (!isEditable) {\n return\n }\n\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this) as Element\n\n if (element && element.setAttribute) {\n element.setAttribute('data-extension-point', this.props.treePath)\n }\n }\n\n private removeDataFromElement = () => {\n if (!isSiteEditorIframe) {\n return\n }\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this) as Element\n\n if (element && element.removeAttribute) {\n element.removeAttribute('data-extension-point')\n }\n }\n}\n\n/** TODO: withLoading is in the end a makeshift Suspense\n * wrapper. Should probably be replaced in the future. */\nexport default withLoading(ExtensionPointComponent)\n\n```" } ]
code_store-on-localhost_9798b45a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/LegacyExtensionContainer.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ReactPortal, FC, useState, useEffect, Fragment } from 'react'\n\nimport { createPortal } from '../utils/dom'\nimport { getDirectChildren, useTreePath } from '../utils/treePath'\nimport ExtensionPoint from './ExtensionPoint'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n query: any\n params: any\n}\n\nconst LegacyExtensionContainer: FC<Props> = ({ query, params }) => {\n const [hydrate, setHydrate] = useState(false)\n useEffect(() => {\n setHydrate(true)\n }, [])\n const { extensions } = useRuntime()\n const { treePath } = useTreePath()\n return (\n <Fragment>\n {getDirectChildren(extensions, treePath).map(\n id =>\n createPortal(\n <ExtensionPoint id={id} query={query} params={params} />,\n `${treePath}/${id}`,\n hydrate\n ) as ReactPortal\n )}\n </Fragment>\n )\n}\n\nexport default LegacyExtensionContainer\n\n```" } ]
code_store-on-localhost_e12ae4e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Loading.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport Preview from './Preview'\n\nimport { useExtension } from '../hooks/extension'\n\nconst Loading = () => {\n const extension = useExtension()\n\n if (!extension) {\n return null\n }\n\n const { preview } = extension\n\n if (!preview) {\n return null\n }\n\n return <Preview extension={extension} />\n}\n\nexport default Loading\n\n```" } ]
code_store-on-localhost_96661d5d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/TrackEventsWrapper.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { forEach } from 'ramda'\nimport { PureComponent } from 'react'\nimport ReactDOM from 'react-dom'\n\ninterface Props {\n events?: string[]\n id?: string\n}\n\nconst sendEvent = (id: string, event: string) => {\n window.postMessage(\n {\n pageComponentInteraction: {\n blockId: id,\n interactionType: event,\n namespace: 'renderRuntime',\n },\n },\n '*'\n )\n}\n\nclass TrackEventsWrapper extends PureComponent<Props> {\n public eventsHandler: Record<string, () => void> = {}\n\n public componentDidMount() {\n const { id, events } = this.props\n if (events && events.length && id) {\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this)\n if (element && element.addEventListener) {\n forEach(event => {\n this.eventsHandler[event] = () => sendEvent(id, event)\n element.addEventListener(event, this.eventsHandler[event])\n }, events)\n }\n }\n }\n\n public componentWillUnmount() {\n const { id, events } = this.props\n if (events && events.length && id) {\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this)\n if (element && element.addEventListener) {\n forEach(\n event =>\n element.removeEventListener(event, this.eventsHandler[event]),\n events\n )\n }\n }\n }\n\n public render() {\n const { children } = this.props\n return children\n }\n}\n\nexport default TrackEventsWrapper\n\n```" } ]
code_store-on-localhost_31eff7bd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/MaybeContext.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, Fragment, FC } from 'react'\nimport ExtensionPointComponent from '../components/ExtensionPointComponent'\nimport { RenderContextProps } from './RenderContext'\nimport { ExtensionPoint } from '../index'\n\ninterface Props extends RenderContextProps {\n nestedPage: string\n params?: Record<string, any>\n query?: Record<string, string>\n}\n\nconst useContextComponent = ({\n nestedPage,\n query,\n params,\n runtime,\n}: Props & RenderContextProps) => {\n const { extensions } = runtime\n\n const { context, before, after, props: pageProps } = extensions[nestedPage]\n const pageContextProps = pageProps && pageProps.context\n\n /** Allows rendering header/footer if the Context component is loading,\n * by exposing them to ExtensionPointComponent via props.\n * TODO:This is a bit of a hack. The header/footer should probably be decoupled\n * from the context, but doing so introduces bugs on some stores. */\n const beforeElements =\n before &&\n before.map(beforeId => (\n <ExtensionPoint id={beforeId} key={beforeId} treePath={nestedPage} />\n ))\n\n const afterElements =\n after &&\n after.map(afterId => (\n <ExtensionPoint id={afterId} key={afterId} treePath={nestedPage} />\n ))\n\n const contextProps = useMemo(() => {\n if (!context) {\n return undefined\n }\n return {\n ...pageContextProps,\n beforeElements,\n afterElements,\n nextTreePath: nestedPage,\n params,\n query,\n ...context.props,\n }\n }, [\n context,\n pageContextProps,\n beforeElements,\n afterElements,\n nestedPage,\n params,\n query,\n ])\n const contextComponent = context ? context.component : undefined\n return [contextProps, contextComponent]\n}\n\nconst MaybeContext: FC<Props> = ({\n children,\n nestedPage,\n query,\n params,\n runtime,\n}) => {\n const [contextProps, contextComponent] = useContextComponent({\n nestedPage,\n query,\n params,\n runtime,\n })\n\n return contextComponent ? (\n <ExtensionPointComponent\n component={contextComponent}\n props={contextProps}\n runtime={runtime}\n treePath={nestedPage}\n >\n {children}\n </ExtensionPointComponent>\n ) : (\n <Fragment>{children}</Fragment>\n )\n}\n\nexport default MaybeContext\n\n```" } ]
code_store-on-localhost_d656f3be
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/NoSSR.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, {\n useState,\n useEffect,\n useLayoutEffect,\n FunctionComponent,\n} from 'react'\n\nconst useEnhancedEffect =\n typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nconst useSSR = () => {\n const [isCSRAvailable, setCSR] = useState(false)\n\n useEnhancedEffect(() => {\n setCSR(true)\n }, [])\n\n return !isCSRAvailable\n}\n\ninterface Props {\n onSSR?: React.ReactNode\n}\n\nconst NoSSR: FunctionComponent<Props> = ({ children, onSSR }) => {\n const isSSR = useSSR()\n\n return <>{isSSR ? onSSR : children}</>\n}\n\nexport default NoSSR\n\nexport { useSSR }\n\n```" } ]
code_store-on-localhost_f75ea50a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/BuildStatus.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { RenderContextProps, withRuntimeContext } from './RenderContext'\n\ninterface State {\n animateOut: boolean\n status: string | null\n anchor: 'left' | 'right'\n interrupted: boolean | null\n}\n\nclass BuildStatus extends Component<RenderContextProps, State> {\n private animateOutHandle!: number\n private hideHandle!: number\n\n public constructor(props: RenderContextProps) {\n super(props)\n\n this.state = {\n animateOut: false,\n status: null,\n interrupted: null,\n anchor: 'left',\n }\n }\n\n public clearTimeouts = () => {\n clearTimeout(this.animateOutHandle)\n clearTimeout(this.hideHandle)\n }\n\n public hideWithDelay = (delayMillis: number) => {\n this.animateOutHandle = window.setTimeout(\n () => this.setState({ animateOut: true }),\n delayMillis\n )\n this.hideHandle = window.setTimeout(\n () =>\n this.setState({ status: null, interrupted: null, animateOut: false }),\n delayMillis + 300\n )\n }\n\n private handleMouseOver = () => {\n this.setState(state => ({\n anchor: state.anchor === 'left' ? 'right' : 'left',\n }))\n }\n\n public updateStatus = (status: string) => {\n // After we started a reload, the UI shouldn't move.\n if (this.state.status === 'reload') {\n return\n }\n\n this.setState({ status, animateOut: false })\n this.clearTimeouts()\n\n if (status === 'success' || status === 'hmr:success') {\n const delay = status === 'success' ? 2000 : 0\n this.hideWithDelay(delay)\n }\n }\n\n public updateInterrupted = () => {\n this.clearTimeouts()\n this.setState({ interrupted: true, animateOut: false })\n const delay = 2000\n this.hideWithDelay(delay)\n }\n\n public subscribeToStatus = () => {\n const { emitter } = this.props.runtime\n emitter.addListener('build.status', this.updateStatus)\n }\n\n public unsubscribeToStatus = () => {\n const { emitter } = this.props.runtime\n emitter.removeListener('build.status', this.updateStatus)\n }\n\n public subscribeToLinkInterrupted = () => {\n const { emitter } = this.props.runtime\n emitter.addListener('link_interrupted', this.updateInterrupted)\n }\n\n public unsubscribeToLinkInterrupted = () => {\n const { emitter } = this.props.runtime\n emitter.removeListener('link_interrupted', this.updateInterrupted)\n }\n\n public componentDidMount() {\n this.subscribeToStatus()\n this.subscribeToLinkInterrupted()\n }\n\n public componentWillUnmount() {\n this.unsubscribeToStatus()\n this.unsubscribeToLinkInterrupted()\n this.clearTimeouts()\n }\n\n private renderLoading = () => (\n <svg\n width=\"26px\"\n height=\"26px\"\n viewBox=\"0 0 100 100\"\n preserveAspectRatio=\"xMidYMid\"\n >\n <style>{`\n @keyframes build-status-rotate {\n 0% {\n transform: rotate(0);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n\n .build-status-rotate {\n transform-origin: 50px 50px;\n animation: build-status-rotate 0.7s infinite linear;\n }\n\n `}</style>\n <g>\n <circle\n cx=\"50\"\n opacity=\"0.4\"\n cy=\"50\"\n fill=\"none\"\n stroke=\"#F71963\"\n r=\"40\"\n strokeWidth=\"14\"\n />\n <circle\n cx=\"50\"\n cy=\"50\"\n fill=\"none\"\n stroke=\"#F71963\"\n r=\"40\"\n strokeDasharray=\"60 900\"\n strokeWidth=\"12\"\n strokeLinecap=\"round\"\n className=\"build-status-rotate\"\n />\n </g>\n </svg>\n )\n\n public render() {\n const { status, animateOut, anchor, interrupted } = this.state\n\n if (status === null && interrupted === null) {\n return null\n }\n\n const className = `build-status ${status} z-max fixed animated pa3 bg-near-white br3 rebel-pink flex items-center shadow-4 ${\n animateOut ? 'fadeOut' : 'fadeIn'\n }`\n\n const message = interrupted\n ? 'Link interrupted'\n : status === 'fail'\n ? 'Oops! Build failed. Check your terminal for more information'\n : status === 'reload'\n ? 'Performing full reload'\n : null\n\n return (\n // eslint-disable-next-line jsx-a11y/mouse-events-have-key-events\n <div\n aria-hidden\n className={className}\n style={{\n top: '12px',\n [anchor]: '12px',\n animationDuration: '0.2s',\n opacity: 0.8,\n }}\n onMouseOver={this.handleMouseOver}\n >\n {message ? <p className=\"ma2\">{message}</p> : this.renderLoading()}\n </div>\n )\n }\n}\n\nexport default withRuntimeContext<{}>(BuildStatus)\n\n```" } ]
code_store-on-localhost_0dbdfa32
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/ErrorBoundary.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ErrorInfo, FunctionComponent } from 'react'\nimport ExtensionPointError from './ExtensionPointError'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n runtime: any\n}\n\nclass ErrorBoundary extends React.Component<Props> {\n public state = {\n error: undefined,\n errorInfo: undefined,\n }\n\n public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n this.setState({\n error,\n errorInfo,\n })\n }\n\n public render() {\n const { production } = this.props.runtime\n\n const { error, errorInfo } = this.state\n if (error) {\n if (!production) {\n return <ExtensionPointError error={error} errorInfo={errorInfo} />\n }\n return null\n }\n\n return this.props.children\n }\n}\n\nconst ErrorBoundaryWithContext: FunctionComponent = ({ children }) => {\n const runtime = useRuntime()\n\n return <ErrorBoundary runtime={runtime}>{children}</ErrorBoundary>\n}\n\nexport default ErrorBoundaryWithContext\n\nexport const withErrorBoundary = <P extends object>(\n Component: React.ComponentType<P>\n) => {\n const WithErrorBoundary = (props: P) => {\n const runtime = useRuntime()\n\n return (\n <ErrorBoundary runtime={runtime}>\n <Component {...props} />\n </ErrorBoundary>\n )\n }\n\n const displayName = Component.displayName || Component.name\n\n if (displayName) {\n WithErrorBoundary.displayName = `withErrorBoundary(${displayName})`\n }\n\n return WithErrorBoundary\n}\n\n```" } ]
code_store-on-localhost_4131deef
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/LoadingContext.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, {\n useContext,\n useCallback,\n useMemo,\n useRef,\n ComponentType,\n FunctionComponent,\n useEffect,\n} from 'react'\nimport { canUseDOM } from 'exenv'\n\nimport GenericPreview from './Preview/GenericPreview'\n\ninterface LoadingContext {\n setLoading: (treePath: string, isLoading: boolean) => void\n isParentLoading?: boolean\n}\n\nconst LoadingContext = React.createContext<LoadingContext>({\n setLoading: () => {},\n isParentLoading: false,\n})\n\nLoadingContext.displayName = 'LoadingContext'\n\nconst LoadingContextProvider = LoadingContext.Provider\n\ninterface LoadingState {\n components: { [key: string]: boolean }\n}\n\nconst displayContent = (\n contentRef: React.RefObject<HTMLElement>,\n loaderRef: React.RefObject<HTMLElement>\n) => {\n if (contentRef.current) {\n contentRef.current.style.position = ''\n contentRef.current.style.width = ''\n contentRef.current.style.opacity = ''\n }\n if (loaderRef.current) {\n loaderRef.current.style.display = 'none'\n }\n}\n\nconst displayLoader = (\n contentRef: React.RefObject<HTMLElement>,\n loaderRef: React.RefObject<HTMLElement>\n) => {\n if (contentRef.current) {\n contentRef.current.style.position = 'absolute'\n contentRef.current.style.width = '100%'\n contentRef.current.style.opacity = '0'\n }\n if (loaderRef.current) {\n loaderRef.current.style.display = ''\n }\n}\n\n/** TODO: LoadingWrapper is in the end a makeshift Suspense.\n * Should probably be replaced in the future. */\nconst LoadingWrapper: FunctionComponent = ({ children }) => {\n /* Uses Ref instead of state to prevent rerenders */\n const state = useRef<LoadingState>({ components: {} })\n\n /* A parent component can include a LoadingContext to tell its\n * children that it is loading data. */\n const { isParentLoading } = useContext(LoadingContext)\n\n const contentContainer = useRef<HTMLDivElement>(null)\n const loaderContainer = useRef<HTMLDivElement>(null)\n\n const loadingTimeout = useRef<number | null>(null)\n const loadingComplete = useRef(false)\n\n const updateLoading = useCallback(() => {\n const areComponentsLoading = Object.values(state.current.components).some(\n Boolean\n )\n\n const isLoading = isParentLoading || areComponentsLoading\n\n if (!isLoading) {\n displayContent(contentContainer, loaderContainer)\n loadingComplete.current = true\n } else {\n if (!loadingComplete.current && loadingTimeout.current !== null) {\n window.clearTimeout(loadingTimeout.current)\n loadingTimeout.current = null\n }\n\n if (isParentLoading && loadingComplete.current) {\n loadingComplete.current = false\n displayLoader(contentContainer, loaderContainer)\n }\n }\n }, [isParentLoading])\n\n const setLoading = useCallback(\n (treePath, loading) => {\n if (loadingComplete.current) {\n return\n }\n\n state.current.components[treePath] = loading\n\n updateLoading()\n },\n [updateLoading]\n )\n\n useEffect(() => {\n updateLoading()\n }, [isParentLoading, updateLoading])\n\n const value = useMemo(\n () => ({\n setLoading,\n }),\n [setLoading]\n )\n\n const isSSR = !canUseDOM\n\n const returnValue = useMemo(\n () => (\n /** Renders both the content and the loader, and hides them via changing the\n * style via their refs. This is done for two reasons:\n * 1: to make the content execute its code while it is loading, because the\n * content can in turn require more components to be loaded, thus keeping\n * the loading state for longer.\n * 2: To prevent re-rendering when the loading state changes, which seemed\n * to cause some bugs. */\n <LoadingContextProvider value={value}>\n <div\n // Content container\n ref={contentContainer}\n suppressHydrationWarning\n style={{\n opacity: isSSR ? 1 : 0,\n position: isSSR ? 'unset' : 'absolute',\n width: isSSR ? 'unset' : '100%',\n }}\n >\n {children}\n </div>\n <div\n // Loader container\n ref={loaderContainer}\n suppressHydrationWarning\n style={{ display: isSSR ? 'none' : 'unset' }}\n >\n {/** TODO: Use a better preview in the future */}\n <GenericPreview />\n </div>\n </LoadingContextProvider>\n ),\n [children, isSSR, value]\n )\n\n return returnValue\n}\n\nconst useLoadingContext = () => {\n return useContext(LoadingContext)\n}\n\nconst withLoading = <T extends {}>(Component: ComponentType<T>) => {\n const EnhancedComponent: FunctionComponent<T> = props => {\n const isSSR = !canUseDOM\n const { setLoading } = useLoadingContext()\n\n if (isSSR) {\n return <Component {...props} setLoading={() => {}} />\n }\n\n return <Component {...props} setLoading={setLoading} />\n }\n\n EnhancedComponent.displayName = `WithLoading(${Component.displayName ||\n Component.name ||\n 'Component'})`\n\n return EnhancedComponent\n}\n\nexport {\n LoadingWrapper,\n useLoadingContext,\n withLoading,\n LoadingContextProvider,\n}\n\n```" } ]
code_store-on-localhost_44951d81
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/hooks/extension.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { ReactElement } from 'react'\n\nimport { useRuntime } from '../components/RenderContext'\nimport { useTreePath } from '../utils/treePath'\n\nfunction mountTreePath(base: string, children: string[]) {\n return [base, ...children].filter(id => !!id).join('/')\n}\n\ninterface Options {\n children?: string[] | string\n}\n\nconst useExtension = ({ children }: Options = {}): any | null => {\n const { extensions } = useRuntime()\n\n const { treePath: baseTreePath } = useTreePath()\n\n const treePath = children\n ? mountTreePath(\n baseTreePath,\n Array.isArray(children) ? children : [children]\n )\n : baseTreePath\n\n const extension = treePath && extensions[treePath]\n\n return extension || null\n}\n\ninterface ExtensionContext {\n extension?: any | null\n}\n\ninterface Props {\n children({ extension }: ExtensionContext): ReactElement<any> | null\n}\n\nconst ExtensionConsumer = ({ children }: Props) => {\n const extension = useExtension()\n\n return children({ extension })\n}\n\nexport { useExtension, ExtensionConsumer }\n\n```" } ]
code_store-on-localhost_97ad5680
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/generateHash.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n ArgumentNode,\n BREAK,\n DocumentNode,\n StringValueNode,\n visit,\n} from 'graphql'\n\ninterface HashedDocumentNode extends DocumentNode {\n documentId: string\n}\n\nconst isHashedDocumentNode = (arg: any): arg is HashedDocumentNode => {\n return arg && arg.documentId\n}\n\nexport const generateHash = (query: HashedDocumentNode | DocumentNode) => {\n if (isHashedDocumentNode(query)) {\n return query.documentId\n }\n\n const asset = { hash: '' }\n visit(query, {\n Argument(node: ArgumentNode) {\n if (node.name.value === 'hash') {\n asset.hash = (node.value as StringValueNode).value\n return BREAK\n }\n },\n })\n return asset.hash\n}\n\n```" } ]
code_store-on-localhost_c90e3c9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/index.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n InMemoryCache,\n IntrospectionFragmentMatcher,\n IntrospectionResultData,\n NormalizedCacheObject,\n} from 'apollo-cache-inmemory'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport { onError } from 'apollo-link-error'\nimport { createHttpLink } from 'apollo-link-http'\nimport { createPersistedQueryLink } from 'apollo-link-persisted-queries'\nimport { createUploadLink } from 'apollo-upload-client'\nimport { canUseDOM } from 'exenv'\n\nimport PageCacheControl from '../cacheControl'\nimport graphQLErrorsStore from '../graphQLErrorsStore'\nimport { generateHash } from './generateHash'\nimport { toBase64Link } from './links/base64Link'\nimport { cachingLink } from './links/cachingLink'\nimport { ensureSessionLink } from './links/ensureSessionLink'\nimport { createIOFetchLink } from './links/ioFetchLink'\nimport { omitTypenameLink } from './links/omitVariableTypenameLink'\nimport { createUriSwitchLink } from './links/uriSwitchLink'\nimport { versionSplitterLink } from './links/versionSplitterLink'\n\ninterface ApolloClientsRegistry {\n [key: string]: ApolloClient<NormalizedCacheObject>\n}\n\nconst buildCacheId = (\n vendor: string | undefined,\n app: string | undefined,\n major: string | undefined,\n type: string,\n cacheId: string\n) =>\n app && major\n ? `${vendor}.${app}@${major}.x:${type}:${cacheId}`\n : `${type}:${cacheId}`\n\nconst dataIdFromObject = (value: any) => {\n const { cacheId, __typename } = value || ({} as any)\n if (value && __typename && cacheId) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [vendor, app, major, ...type] = __typename.split('_')\n const typename = type.join('_') || __typename\n return buildCacheId(vendor, app, major, typename, cacheId)\n }\n return null\n}\n\nexport const buildCacheLocator = (\n app: string,\n type: string,\n cacheId: string\n) => {\n const [vendor, appAndMajor] = app.replace(/-/g, '').split('.')\n const [appName, major] = appAndMajor && appAndMajor.split('@')\n return buildCacheId(vendor, appName, major, type, cacheId)\n}\n\nconst clientsByWorkspace: ApolloClientsRegistry = {}\n\nexport const getState = (runtime: any) => {\n const { account, workspace } = runtime\n const apolloClient = clientsByWorkspace[`${account}/${workspace}`]\n return apolloClient ? apolloClient.cache.extract() : {}\n}\n\nexport const getClient = (\n runtime: any,\n baseURI: string,\n runtimeContextLink: ApolloLink,\n sessionPromise: Promise<any>,\n fetcher: any['fetch'],\n cacheControl?: PageCacheControl\n) => {\n const {\n account,\n workspace,\n introspectionResult,\n }: {\n account: string\n workspace: string\n introspectionResult: IntrospectionResultData\n } = runtime\n\n if (!clientsByWorkspace[`${account}/${workspace}`]) {\n const cache = new InMemoryCache({\n addTypename: true,\n dataIdFromObject,\n fragmentMatcher: new IntrospectionFragmentMatcher({\n introspectionQueryResultData: introspectionResult,\n }),\n })\n\n const httpLink = ApolloLink.from([\n toBase64Link,\n createHttpLink({\n credentials: 'include',\n useGETForQueries: false,\n fetch: fetcher,\n }),\n ])\n\n const uploadLink = createUploadLink({\n credentials: 'include',\n })\n\n const fetcherLink = createIOFetchLink(httpLink, uploadLink)\n\n const persistedQueryLink = createPersistedQueryLink({\n disable: () => false,\n generateHash,\n useGETForHashedQueries: true,\n })\n\n const uriSwitchLink = createUriSwitchLink(baseURI, runtime)\n\n const cacheLink = cacheControl ? [cachingLink(cacheControl)] : []\n\n const errorLink = onError(({ graphQLErrors }) => {\n if (graphQLErrors) {\n graphQLErrorsStore.addOperationIds(graphQLErrors)\n }\n })\n\n const link = ApolloLink.from([\n errorLink,\n omitTypenameLink,\n versionSplitterLink,\n runtimeContextLink,\n persistedQueryLink,\n uriSwitchLink,\n ensureSessionLink(sessionPromise),\n ...cacheLink,\n fetcherLink, //this is a final link\n ])\n\n clientsByWorkspace[`${account}/${workspace}`] = new ApolloClient({\n cache: canUseDOM ? cache.restore(window.__STATE__) : cache,\n link,\n resolvers: {},\n ssrMode: !canUseDOM,\n })\n }\n\n return clientsByWorkspace[`${account}/${workspace}`]\n}\n\n```" } ]
code_store-on-localhost_9dfcef1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/base64Link.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { Base64 } from 'js-base64'\n\nexport const toBase64Link = new ApolloLink(\n (operation: Operation, forward?: NextLink) => {\n const { extensions, variables } = operation\n if (variables && Object.keys(variables).length > 0) {\n operation.variables = {}\n operation.extensions = {\n ...extensions,\n variables: Base64.encode(JSON.stringify(variables)),\n }\n }\n return forward ? forward(operation) : null\n }\n)\n\n```" } ]
code_store-on-localhost_31dc1606
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/uriSwitchLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { path } from 'ramda'\nimport { canUseDOM } from 'exenv'\nimport {\n ASTNode,\n DirectiveNode,\n OperationDefinitionNode,\n StringValueNode,\n visit,\n} from 'graphql'\n\nimport { generateHash } from '../generateHash'\nimport { appendLocationSearch } from '../../location'\n\ninterface Assets {\n operationType: string\n queryScope?: string\n}\n\nconst assetsFromQuery = (query: ASTNode) => {\n const assets: Assets = { operationType: 'mutation' }\n visit(query, {\n Directive(node: DirectiveNode) {\n if (node.name.value === 'context') {\n const scopeArg =\n node.arguments &&\n node.arguments.find(argNode => argNode.name.value === 'scope')\n if (scopeArg) {\n assets.queryScope = (scopeArg.value as StringValueNode).value\n }\n }\n },\n OperationDefinition(node: OperationDefinitionNode) {\n assets.operationType = node.operation\n },\n })\n return assets\n}\n\nexport interface OperationContext {\n fetchOptions: any\n runtime: Pick<\n any,\n | 'appsEtag'\n | 'cacheHints'\n | 'components'\n | 'culture'\n | 'extensions'\n | 'messages'\n | 'pages'\n >\n}\n\nconst equals = (a: string, b: string) =>\n a && b && a.toLowerCase() === b.toLowerCase()\n\nconst extractHints = (query: ASTNode, meta: any) => {\n const { operationType, queryScope } = assetsFromQuery(query)\n\n let hints\n if (equals(operationType, 'query')) {\n hints = meta ? meta : { scope: queryScope }\n } else {\n hints = { ...meta, scope: 'private' }\n }\n\n const {\n maxAge = 'long',\n scope = 'public',\n version = 1,\n provider,\n sender,\n } = hints\n return {\n maxAge: maxAge.toLowerCase(),\n operationType,\n scope: scope.toLowerCase(),\n version,\n provider,\n sender,\n }\n}\n\nexport const createUriSwitchLink = (\n baseURI: string,\n initialRuntime: any\n) =>\n new ApolloLink((operation: Operation, forward?: NextLink) => {\n operation.setContext((oldContext: OperationContext) => {\n const {\n fetchOptions = {},\n // Fetches from context for not fetching a stale version of runtime\n runtime: {\n appsEtag,\n cacheHints,\n culture: { locale },\n },\n } = oldContext\n const { extensions } = operation\n const {\n binding,\n workspace,\n route: { domain },\n } = initialRuntime\n const hash = generateHash(operation.query)\n const {\n maxAge,\n scope,\n version,\n operationType,\n provider,\n sender,\n } = extractHints(operation.query, cacheHints[hash])\n const requiresAuthorization = path(\n ['settings', `vtex.${domain}`, 'requiresAuthorization'],\n initialRuntime\n )\n const customScope = requiresAuthorization ? 'private' : scope\n const oldMethod = fetchOptions.method || 'POST'\n const protocol = canUseDOM ? 'https:' : 'http:'\n const method =\n equals(scope, 'private') && equals(operationType, 'query')\n ? 'POST'\n : oldMethod\n extensions.persistedQuery = {\n ...extensions.persistedQuery,\n sender,\n provider,\n }\n\n let query = `?workspace=${workspace}&maxAge=${maxAge}&appsEtag=${appsEtag}&domain=${domain}&locale=${locale}`\n if (binding && binding.id) {\n query = appendLocationSearch(query, { __bindingId: binding.id })\n }\n\n return {\n ...oldContext,\n scope: customScope,\n fetchOptions: { ...fetchOptions, method },\n uri: `${protocol}//${baseURI}/_v/${customScope}/graphql/v${version}${query}`,\n }\n })\n return forward ? forward(operation) : null\n })\n\n```" } ]
code_store-on-localhost_a6b292be
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/omitVariableTypenameLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { canUseDOM } from 'exenv'\n\nconst deepCopyFiles = (src: any, dst: any) =>\n src &&\n typeof src === 'object' &&\n Object.keys(src).forEach(key => {\n if (\n src[key] instanceof File ||\n src[key] instanceof Blob ||\n src[key] instanceof FileList\n ) {\n dst[key] = src[key]\n } else {\n deepCopyFiles(src[key], dst[key])\n }\n })\n\nconst omitTypename = (key: string, value: any) =>\n key === '__typename' ? undefined : value\n\nexport const omitTypenameLink = new ApolloLink(\n (operation: Operation, forward?: NextLink) => {\n const { variables } = operation\n if (variables && canUseDOM) {\n operation.variables = JSON.parse(\n JSON.stringify(operation.variables),\n omitTypename\n )\n deepCopyFiles(variables, operation.variables)\n }\n return forward ? forward(operation) : null\n }\n)\n\n```" } ]
code_store-on-localhost_73b69f2c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/cachingLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport PageCacheControl from '../../cacheControl'\n\nexport const cachingLink = (cacheControl: PageCacheControl) => {\n return new ApolloLink((operation: Operation, forward?: NextLink) => {\n if (forward) {\n return forward(operation).map(data => {\n const { response } = operation.getContext()\n cacheControl.evaluate(response)\n return data\n })\n }\n return null\n })\n}\n\n```" } ]
code_store-on-localhost_44607777
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/ioFetchLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { canUseDOM } from 'exenv'\n\nconst isUploadable = (v: any) =>\n v instanceof File || v instanceof Blob || v instanceof FileList\n\nconst usesUpload = (value: any): boolean => {\n if (isUploadable(value)) {\n return true\n }\n\n // If it isn't an object we can't recurse anymore\n if (Object(value) !== value) {\n return false\n }\n\n return Object.values(value).some(v => usesUpload(v))\n}\n\nconst useHttpLink = (operation: Operation) => {\n const { variables } = operation\n\n // No file upload is allowed during SSR\n if (!canUseDOM) {\n return true\n }\n\n const doUseHttpLink = !usesUpload(variables)\n return doUseHttpLink\n}\n\nconst passthrough = (operation: Operation, forward?: NextLink) =>\n forward ? forward(operation) : null\n\nexport const createIOFetchLink = (\n httpLink: ApolloLink,\n uploadLink: ApolloLink\n) => new ApolloLink(passthrough).split(useHttpLink, httpLink, uploadLink)\n\n```" } ]
code_store-on-localhost_4798cf9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/versionSplitterLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n ApolloLink,\n createOperation,\n FetchResult,\n GraphQLRequest,\n NextLink,\n Observable,\n Operation,\n} from 'apollo-link'\nimport {\n transformOperation,\n validateOperation,\n} from 'apollo-link/lib/linkUtils'\nimport {\n BREAK,\n DirectiveNode,\n DocumentNode,\n OperationDefinitionNode,\n parse,\n print,\n SelectionNode,\n VariableDefinitionNode,\n VariableNode,\n visit,\n} from 'graphql'\n\ninterface Variables {\n [name: string]: VariableDefinitionNode\n}\n\ninterface Node {\n selection: SelectionNode\n usedVariables: Variables\n}\n\nconst pickAvailableVariables = (query: DocumentNode) => {\n const availableVariables: Variables = {}\n visit(query, {\n VariableDefinition(node: VariableDefinitionNode) {\n availableVariables[node.variable.name.value] = node\n },\n })\n return availableVariables\n}\n\nconst isRuntimeMetaDirective = (node: DirectiveNode) =>\n node.name.value === 'runtimeMeta'\n\nconst pickUsedVariables = (\n selection: SelectionNode,\n availableVariables: Variables\n) => {\n const usedVariables: Variables = {}\n visit(selection, {\n Variable(varNode: VariableNode) {\n usedVariables[varNode.name.value] = availableVariables[varNode.name.value]\n },\n })\n return usedVariables\n}\n\nconst pickFields = (query: DocumentNode, availableVariables: Variables) => {\n const nodes: Node[] = []\n visit(query, {\n Field(selection: SelectionNode) {\n if (\n selection.directives &&\n selection.directives.find(isRuntimeMetaDirective)\n ) {\n nodes.push({\n selection,\n usedVariables: pickUsedVariables(selection, availableVariables),\n })\n }\n },\n })\n return nodes\n}\n\nconst operationWhiteList = ['query', 'mutation', 'subscription']\n\nconst queryFromNodeCreator = (query: DocumentNode) => (node: Node) =>\n visit(parse(print(query)), {\n OperationDefinition(opNode: OperationDefinitionNode) {\n if (operationWhiteList.includes(opNode.operation)) {\n return {\n ...opNode,\n selectionSet: {\n ...opNode.selectionSet,\n selections: [node.selection],\n },\n variableDefinitions: Object.values(node.usedVariables),\n }\n }\n\n return null\n },\n }) as DocumentNode\n\nconst isTypeQuery = (docNode: DocumentNode) => {\n const asset = { isQuery: false }\n visit(docNode, {\n OperationDefinition(node: OperationDefinitionNode) {\n if (node.operation === 'query') {\n asset.isQuery = true\n return BREAK\n }\n },\n })\n return asset.isQuery\n}\n\nconst assertSingleOperation = (query: DocumentNode) => {\n const ops = query.definitions.filter(definition =>\n operationWhiteList.includes(\n (definition as OperationDefinitionNode).operation\n )\n )\n\n if (ops.length > 1) {\n throw new Error(\n 'Only one operation definition is allowed per query. Please split your queries in two different files'\n )\n }\n}\n\nconst queriesByRuntimeMetaDirective = (query: DocumentNode) => {\n const availableVariables: Variables = pickAvailableVariables(query)\n const nodes: Node[] = pickFields(query, availableVariables)\n\n assertSingleOperation(query)\n\n return nodes.map(queryFromNodeCreator(query))\n}\n\nconst mergeRecursively = (accumulator: any, value: any) => {\n if (value) {\n Object.keys(value).forEach(key => {\n if (accumulator[key] && typeof value[key] === 'object') {\n accumulator[key] = mergeRecursively(accumulator[key], value[key])\n } else {\n accumulator[key] = value[key]\n }\n })\n }\n\n return accumulator\n}\n\nconst createOperationForQuery = (operation: Operation) => (\n query: DocumentNode\n) => {\n const graphQLRequest: GraphQLRequest = {\n ...operation,\n query,\n extensions: { ...operation.extensions },\n }\n const op = validateOperation(transformOperation(graphQLRequest))\n return createOperation(operation.getContext(), op)\n}\n\nconst operationByRuntimeMetaDirective = (operation: Operation) => {\n const queries = queriesByRuntimeMetaDirective(operation.query)\n return queries.map(createOperationForQuery(operation))\n}\n\nconst observableFromOperations = (operations: Operation[], forward: NextLink) =>\n new Observable(observer => {\n const reduced = {}\n let togo = 0\n\n operations.forEach((op: Operation) =>\n forward(op).subscribe({\n complete: () => {\n if (togo === operations.length) {\n togo++\n observer.next(reduced)\n observer.complete()\n }\n },\n error: err => {\n togo++\n observer.error(err)\n },\n next: data => {\n togo++\n mergeRecursively(reduced, data)\n },\n })\n )\n }) as Observable<\n FetchResult<\n { [key: string]: any },\n Record<string, any>,\n Record<string, any>\n >\n >\n\nexport const versionSplitterLink = new ApolloLink(\n (operation: Operation, forward?: NextLink): any => {\n if (forward) {\n const query = operation.query\n const operations = operationByRuntimeMetaDirective(operation)\n\n if (operations.length && isTypeQuery(query)) {\n return observableFromOperations(operations, forward)\n } else {\n return forward(operation)\n }\n }\n return null\n }\n)\n\n```" } ]
code_store-on-localhost_db85bed0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/runtimeContextLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\n\nexport const createRuntimeContextLink = () =>\n new ApolloLink((operation: Operation, forward?: NextLink) => {\n operation.setContext((currentContext: Record<string, any>) => {\n return {\n ...currentContext,\n runtime: {},\n }\n })\n return forward ? forward(operation) : null\n })\n\n```" } ]
code_store-on-localhost_8bb07f12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/utils/client/links/ensureSessionLink.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Observable, Operation } from 'apollo-link'\nimport { Subscription } from 'apollo-client/util/Observable'\n\nconst sessionRequiredForScope = new Set(['segment', 'private'])\n\nexport const ensureSessionLink = (sessionPromise: Promise<any>) => {\n return new ApolloLink(\n (operation: Operation, forward?: NextLink) =>\n new Observable(observer => {\n let handle: Subscription | undefined\n\n const { scope } = operation.getContext()\n const promise = sessionRequiredForScope.has(scope)\n ? sessionPromise\n : Promise.resolve()\n\n promise\n .then(() => {\n handle =\n forward &&\n forward(operation).subscribe({\n complete: observer.complete.bind(observer),\n error: observer.error.bind(observer),\n next: observer.next.bind(observer),\n })\n })\n .catch(observer.error.bind(observer))\n\n return () => {\n if (handle) {\n handle.unsubscribe()\n }\n }\n })\n )\n}\n\n```" } ]
code_store-on-localhost_ac4e1afa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ReactElement, RefObject } from 'react'\n\nimport Box from './Box'\nimport Circle from './Circle'\nimport Grid from './Grid'\nimport Spinner from './Spinner'\nimport Text from './Text'\n\ninterface Props {\n extension: any\n}\ninterface State {\n containerWidth?: number | null\n}\n\nexport const TEST_ID = 'loading-preview'\n\nexport default class Preview extends React.PureComponent<Props, State> {\n private container: RefObject<HTMLDivElement>\n\n public constructor(props: Props) {\n super(props)\n\n this.container = React.createRef()\n this.state = {\n containerWidth: null,\n }\n }\n\n private renderPreviewGraphic = (\n width: number | string,\n height: number | string,\n type: string,\n options: any = {}\n ): ReactElement<any> | null => {\n if (!type || type === 'none') {\n return null\n }\n\n switch (type) {\n case 'box':\n /** TODO: deprecate block in favor of box */\n // eslint-disable-next-line no-fallthrough\n case 'block':\n return <Box width={width} height={height} />\n case 'text':\n return (\n <Text\n width={width}\n height={height}\n fontSize={options.fontSize}\n lineHeight={options.lineHeight}\n />\n )\n case 'grid':\n return <Grid width={width} height={height} />\n case 'circle':\n return <Circle width={width} height={height} />\n case 'spinner':\n return <Spinner width={width} height={height} />\n case 'transparent':\n return <div style={{ width, height }} />\n default:\n return null\n }\n }\n\n public componentDidMount() {\n /** Fixes a bug on react-content-loader related to limiting\n * the width of the component\n */\n const containerElement = this.container.current\n if (!containerElement) {\n return\n }\n\n this.setState({\n containerWidth: containerElement.offsetWidth,\n })\n }\n\n private getDimension = (dimension: any) => {\n if (typeof dimension === 'number') {\n return dimension\n }\n\n if (!dimension) {\n return null\n }\n\n const { extension } = this.props\n\n // TODO: support mobile\n const dimensionObject = dimension.desktop\n if (!dimensionObject) {\n return null\n }\n\n const { defaultValue } = dimensionObject\n\n const valueFromProp =\n dimensionObject.fromProp && extension.props[dimensionObject.fromProp]\n\n if (typeof valueFromProp === 'number') {\n return valueFromProp\n }\n\n return defaultValue\n }\n\n private getDimensions = () => {\n const { extension } = this.props\n\n if (!extension.preview) {\n return { width: null, height: null }\n }\n\n const { width, height } = extension.preview\n\n return {\n height: this.getDimension(height),\n width: this.getDimension(width),\n }\n }\n\n public render() {\n const { extension } = this.props\n\n if (!extension.preview) {\n return null\n }\n\n const { type, options = {}, fullWidth } = extension.preview\n\n const { width: initialWidth, height: initialHeight } = this.getDimensions()\n\n const { containerWidth } = this.state\n\n const maxWidth =\n containerWidth || (window && window.innerWidth) || initialWidth || 0\n\n const padding = options.padding == null ? 20 : options.padding\n const width = Math.max(\n (typeof initialWidth === 'number'\n ? Math.min(maxWidth, initialWidth)\n : maxWidth) -\n padding * 2,\n 0\n )\n const height =\n initialHeight && initialHeight > padding * 2\n ? initialHeight - padding * 2\n : 0\n\n if (height === 0) {\n return null\n }\n\n return (\n /** TODO: remove this div in favor of the Container component,\n * currently on store-components\n * @author: lbebber\n */\n <div\n ref={this.container}\n className={fullWidth ? '' : 'mw9 center w-100'}\n data-testid={TEST_ID}\n style={{ padding }}\n >\n {this.renderPreviewGraphic(width || '100%', height, type, options)}\n </div>\n )\n }\n}\n\n```" } ]
code_store-on-localhost_6c907007
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/Circle.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ContentLoader, Rect } from './ContentLoader'\n\ninterface Props {\n width: number | string\n height: number | string\n}\n\nconst Circle = ({ width, height }: Props) => (\n <ContentLoader width={width} height={height}>\n <Rect width={width} height={height} borderRadius=\"100%\" />\n </ContentLoader>\n)\n\nexport default Circle\n\n```" } ]
code_store-on-localhost_3359ee13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/Grid.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ContentLoader, Rect } from './ContentLoader'\nimport Box from './Box'\nimport { useSSR } from '../../index'\n\ninterface Props {\n width: number | string\n height: number | string\n}\n\nconst Grid = ({ width, height }: Props) => {\n const isSSR = useSSR()\n\n if (isSSR || typeof width === 'string' || typeof height === 'string') {\n return <Box width={width} height={height} />\n }\n\n // TODO: make these values configurable\n const itemWidth = 250\n const itemHeight = 400\n const minSpacingX = 10\n const minSpacingY = 30\n const itemsNumX = Math.floor(width / (itemWidth + minSpacingX))\n const itemsNumY = Math.floor(height / (itemHeight + minSpacingY))\n // distributes the remaining available space between each item of the grid\n const spacingX =\n (width - itemsNumX * itemWidth) / (itemsNumX > 1 ? itemsNumX - 1 : 2)\n const spacingY =\n (height - itemsNumY * itemHeight) / (itemsNumY > 1 ? itemsNumY - 1 : 2)\n\n return (\n <ContentLoader width={width} height={height}>\n {Array.from({ length: itemsNumX }).map((_, x) =>\n Array.from({ length: itemsNumY }).map((__, y) => (\n <Rect\n key={`${x}-${y}`}\n x={x * (itemWidth + spacingX)}\n y={y * (itemHeight + spacingY)}\n width={itemWidth}\n height={itemHeight}\n />\n ))\n )}\n </ContentLoader>\n )\n}\n\nexport default Grid\n\n```" } ]
code_store-on-localhost_be3ea6ea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/ContentLoader.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n@keyframes slide {\n 0% {\n transform: translate3d(-50%, 0, 0);\n }\n 100% {\n transform: translate3d(0, 0, 0);\n }\n}\n\n.slide {\n animation: slide 1.5s infinite linear;\n}\n\n```" } ]
code_store-on-localhost_241855b7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/Box.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ContentLoader, Rect } from './ContentLoader'\n\ninterface Props {\n width: number | string\n height: number | string\n}\n\nconst Box = ({ width, height }: Props) => (\n <ContentLoader width={width} height={height}>\n <Rect x={0} y={0} width={width} height={height} />\n </ContentLoader>\n)\n\nexport default Box\n\n```" } ]
code_store-on-localhost_ea3e1d98
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/ContentLoader.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport styles from './ContentLoader.css'\n\n// TODO: make these colors dynamic, probably based on\n// muted colors from the color theme\nconst PRIMARY_COLOR = '#e8e8e8'\nconst SECONDARY_COLOR = '#e0e0e0'\n\ninterface RectProps {\n x?: number\n y?: number\n width: number | string\n height: number | string\n preserveAspectRatio?: string\n borderRadius?: number | string\n}\n\nconst Rect: FunctionComponent<RectProps> = ({\n x = 0,\n y = 0,\n width,\n height,\n borderRadius = 5,\n}) => (\n <div\n style={{\n width,\n height,\n overflow: 'hidden',\n position: 'absolute',\n top: y,\n left: x,\n borderRadius,\n }}\n >\n <div\n className={styles.slide}\n style={{\n width: '300vw',\n height: '100%',\n position: 'relative',\n left: -x,\n backgroundColor: SECONDARY_COLOR,\n backgroundImage: `linear-gradient(90deg, ${SECONDARY_COLOR}, ${SECONDARY_COLOR} 50%, ${PRIMARY_COLOR} 60%, ${SECONDARY_COLOR} 65%, ${SECONDARY_COLOR})`,\n backgroundSize: '50% 100%',\n backgroundRepeat: 'repeat-x',\n }}\n />\n </div>\n)\n\ninterface ContentLoaderProps {\n width: number | string\n height: number | string\n}\n\nconst ContentLoader: FunctionComponent<ContentLoaderProps> = ({\n width,\n height,\n children,\n}) => (\n <div style={{ width, height, position: 'relative' }} suppressHydrationWarning>\n {children}\n </div>\n)\n\nexport { ContentLoader, Rect }\n\n```" } ]
code_store-on-localhost_fc3959b5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/GenericPreview.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport Box from './Box'\n\nconst GenericPreview = () => {\n const padding = 20\n const height = (window && window.innerHeight) || 1400\n\n return (\n <div className=\"center w-100 mw9\" style={{ padding }}>\n <Box height={height} width=\"100%\" />\n </div>\n )\n}\n\nexport default GenericPreview\n\n```" } ]
code_store-on-localhost_4ef9e462
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/Text.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ContentLoader, Rect } from './ContentLoader'\nimport Box from './Box'\n\ninterface Props {\n width: number | string\n height: number | string\n lineHeight?: number\n fontSize?: number\n}\n\nconst Text = ({ width, height, fontSize = 16, lineHeight = 1.5 }: Props) => {\n // Height needs to be a value in pixels in order to be able to split it properly into lines.\n // Falls back to `Box` if it's e.g. `100%`\n if (typeof height === 'string') {\n return <Box width={width} height={height} />\n }\n\n // TODO: make the line height configurable\n const lineSize = fontSize * lineHeight\n const lines = Math.round(height / lineSize)\n\n return (\n <ContentLoader width={width} height={height}>\n {Array.from({ length: lines }).map((_, i) => {\n const lineWidth = width\n return (\n <Rect\n key={i}\n x={0}\n y={Math.round(i * lineSize)}\n width={lineWidth}\n height={fontSize}\n />\n )\n })}\n </ContentLoader>\n )\n}\n\nexport default Text\n\n```" } ]
code_store-on-localhost_ddf63048
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/vtex.render-runtime/components/Preview/Spinner.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n width: number | string\n height: number | string\n}\n\nconst Spinner = ({ width, height }: Props) => (\n <div className=\"flex items-center justify-center\" style={{ width, height }}>\n <svg\n width=\"26px\"\n height=\"26px\"\n viewBox=\"0 0 100 100\"\n preserveAspectRatio=\"xMidYMid\"\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlnsXlink=\"http://www.w3.org/1999/xlink\"\n >\n <use xlinkHref=\"#sti-loading\" />\n </svg>\n </div>\n)\n\nexport default Spinner\n\n```" } ]
code_b2b-theme_e04c903e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/checkout-ui-custom/checkout5-custom.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* /files/checkout5-custom.css */\n\n/* Displays the option to enter a foreign document */\n.document-box { display: block; }\n\n/* Displays the option to enter an international phone */\n.phone-box { display: block; }\n\n```" } ]
code_b2b-theme_e8ab3635
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/checkout-ui-custom/checkout6-custom.js from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE. THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.\n!(function (window, jQuery) {\n jQuery(function ($) {\n var disablePersonalInfoEditButton = {\n init: function init() {\n util.waitElement($(\"#edit-profile-data\"), function () {\n $(\n \".accordion-toggle.collapsed .link-box-edit.btn.btn-small\"\n ).remove();\n $(\"#is-not-me\").remove();\n });\n },\n };\n\n var poNumberFeature = {\n showInputOnPOSection: false,\n init: function init() {\n poNumberInput.init();\n fakeSubmitButton.init();\n util.onPageStopLoading(function () {\n if (poNumberFeature.showInputOnPOSection) {\n $(\n \".box-payment-group2.box-payment-option.custom201PaymentGroupPaymentGroup\"\n ).append(poNumberInput.input);\n } else {\n $(\".payment-submit-wrap\").append(poNumberInput.input);\n }\n\n originalSubmitButton.hide();\n $(\".payment-submit-wrap\").append(fakeSubmitButton.btn);\n });\n util.waitElement($(\"#payment-data-submit\"), function () {});\n },\n };\n\n var fakeSubmitButton = {\n btn: null,\n init: function init() {\n fakeSubmitButton.btn = fakeSubmitButton.buildButton();\n fakeSubmitButton.btn.on(\"click\", function () {\n theCheckout.handleSubmit();\n });\n },\n buildButton: function buildButton() {\n return $(\n '<button class=\"jsSubmitFakeButton btn btn-success btn-large btn-block\">\\n <i class=\"icon-lock\"></i>\\n <i class=\"icon-spinner icon-spin\" style=\"display: none;\"></i>\\n <span>Complete Order</span>\\n </button>'\n );\n },\n hideLoadingAndResetButton: function hideLoadingAndResetButton() {\n fakeSubmitButton.btn.find(\"i.icon-spinner\").hide();\n fakeSubmitButton.btn.find(\"i.icon-lock\").show();\n fakeSubmitButton.enableButton();\n },\n setButtonAsLoading: function setButtonAsLoading() {\n fakeSubmitButton.btn.find(\"i.icon-lock\").hide();\n fakeSubmitButton.btn.find(\"i.icon-spinner\").show();\n fakeSubmitButton.disableButton();\n },\n disableButton: function disableButton() {\n fakeSubmitButton.btn.attr(\"disabled\", \"\");\n },\n enableButton: function enableButton() {\n fakeSubmitButton.btn.removeAttr(\"disabled\");\n },\n };\n\n var originalSubmitButton = {\n hide: function hide() {\n $(\"[id=payment-data-submit]\").css(\"visibility\", \"hidden\");\n $(\"[id=payment-data-submit]\").css(\"max-height\", \"0\");\n $(\"[id=payment-data-submit]\").css(\"height\", \"0\");\n $(\"[id=payment-data-submit]\").addClass(\"jsSubmitButton\");\n },\n };\n\n var poNumberInput = {\n input: null,\n init: function init() {\n poNumberInput.input = poNumberInput.buildInput();\n },\n buildInput: function buildInput() {\n return $(\n '\\n <div style=\"\\n padding-right: 15px;\\n margin-bottom: 10px;\\n \" id=\"poWrap\">\\n <label> Purchase Order Number: (optional) </label>\\n <input \\n type=\"text\"\\n id=\"poNumberInput\" style=\"\\n font-size: 20px;\\n height: 36px;\\n line-height: 34px;\\n width: 100%;\" \\n name=\"poNumber\">\\n <span class=\"help error feedback\" style=\"display: none\">This field is required.</span>\\n </div>'\n );\n },\n showError: function showError() {\n $(\"#poNumberInput\").addClass(\"error\");\n $(\"#poWrap\").find(\".feedback\").show();\n },\n hideError: function hideError() {\n $(\"#poNumberInput\").removeClass(\"error\");\n $(\"#poWrap\").find(\".feedback\").hide();\n },\n handleEmpty: function handleEmpty() {\n poNumberInput.showError();\n $(\"#poNumberInput\").on(\"keypress\", poNumberInput.hideError);\n },\n };\n\n var util = {\n waitElement: function waitElement(selector, fn) {\n var element = setInterval(function () {\n if ($(selector).length) {\n clearInterval(element);\n fn();\n }\n }, 200);\n },\n onOrignalButtonStopLoading: function onOrignalButtonStopLoading(fn) {\n var internal = setInterval(function () {\n if (!!!$(\".jsSubmitButton\").prop(\"disabled\")) {\n clearInterval(internal);\n fn();\n }\n }, 200);\n },\n onPageStopLoading: function onPageStopLoading(fn) {\n var internal = setInterval(function () {\n if (!$(\"body.loading\").length) {\n clearInterval(internal);\n fn();\n }\n }, 200);\n },\n onEmailIsSet: function onEmailIsSet(fn) {\n var internal = setInterval(function () {\n if (!!$(\".client-profile-email span.email\").text()) {\n clearInterval(internal);\n fn();\n }\n }, 200);\n },\n };\n\n var theCheckout = {\n submit: function submit() {\n $(\"#payment-data-submit\").click();\n },\n handleSubmit: function handleSubmit() {\n var poNumber = {\n value: $(\"#poNumberInput\")[0].value,\n };\n fakeSubmitButton.setButtonAsLoading();\n util.onOrignalButtonStopLoading(function () {\n fakeSubmitButton.enableButton();\n fakeSubmitButton.hideLoadingAndResetButton();\n });\n vtexjs.checkout.getOrderForm().then(function (data) {\n console.log(\"here: \" + poNumber.value);\n\n if (!!poNumber.value) {\n $.ajax({\n type: \"PUT\",\n url: \"/api/checkout/pub/orderForm/\".concat(\n data.orderFormId,\n \"/customData/profile/poNumber\"\n ),\n data: poNumber,\n dataType: \"json\",\n }).then(theCheckout.submit);\n } else {\n theCheckout.submit();\n }\n });\n },\n };\n\n $(window).on(\"checkoutRequestBegin.vtex\", function (event, orderForm) {\n fakeSubmitButton.setButtonAsLoading();\n setTimeout(function () {\n fakeSubmitButton.hideLoadingAndResetButton();\n }, 1000);\n });\n\n poNumberFeature.init();\n disablePersonalInfoEditButton.init();\n });\n})(window, window.jQuery);\n\n```" } ]
code_b2b-theme_3dfa5891
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/checkout-ui-custom/checkout-confirmation-custom.js from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE.\n// THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.\n\n```" } ]
code_b2b-theme_bfde7295
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/checkout-ui-custom/checkout5-custom.js from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\n// WARNING: THE USAGE OF CUSTOM SCRIPTS IS NOT SUPPORTED. VTEX IS NOT LIABLE FOR ANY DAMAGES THIS MAY CAUSE. THIS MAY BREAK YOUR STORE AND STOP SALES. IN CASE OF ERRORS, PLEASE DELETE THE CONTENT OF THIS SCRIPT.\n\n```" } ]
code_b2b-theme_83232928
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/checkout-ui-custom/checkout6-custom.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* Content copied from \"checkout5-custom.css\" at 2019-03-01T05:12:59.334Z */\n\n/* /files/checkout5-custom.css */\n\n/* Displays the option to enter a foreign document */\n.document-box { display: block; }\n\n/* Displays the option to enter an international phone */\n.phone-box { display: block; }\n\n```" } ]
code_b2b-theme_76b5c681
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/docs/README.md from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Installing the B2B Store Theme\n\nB2B Store Theme is a front-end template to help your store get started with VTEX’s core features for businesses selling to other businesses.\n\n## Prerequisites\n\n### Set up your development environment\n\nBefore starting with the B2B Store Theme setup itself, you must:\n\n1. [Set up a workspace to develop in VTEX IO](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-2-basicsetuptodevelopinvtexio) on your machine.\n2. Follow [these instructions](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-2-prerequesites) to make sure you meet all the prerequisites to develop using Store Framework.\n3. Make sure your store’s catalog is integrated with VTEX Intelligent Search, as described in [this article](https://help.vtex.com/en/tracks/vtex-intelligent-search--19wrbB7nEQcmwzDPl1l4Cb/6wKQgKmu2FT6084BJT7z5V).\n\n### Install required B2B apps\n\nNow you must install the required apps listed below. They are mandatory for the B2B Store Theme to work properly.\n\n- [Wishlist](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#wishlist)\n- [Reviews and Ratings](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#reviews-and-ratings)\n- [Quick Order](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#quick-order)\n- [Location Availability](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#location-availability)\n- [Shopper Location](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#shopper-location)\n- [Wordpress Integration](https://developers.vtex.com/vtex-developer-docs/docs/installing-the-b2b-store-theme#wordpress-integration)\n\n#### Wishlist\n\n[Wishlist](https://github.com/vtex-apps/wish-list) is an app that allows your store’s customers to bookmark their favorite products by clicking on a heart icon.\n\nTo install this app on your store, run the following command on the CLI:\n\n```\nvtex install vtex.wish-list@1.x\n```\n\n#### Reviews and Ratings\n\nThe [Reviews and ratings](https://github.com/vtex-apps/reviews-and-ratings) app enables your clients to submit reviews and ratings — using a star rating system — to your store’s products.\n\nInstall it using the command:\n\n```\nvtex install vtex.reviews-and-ratings@2.x\n```\n\nAfter that, go to your store's Admin to proceed with the installation.\n\nOnce you are logged in, follow these steps:\n\n1. Go to the **Account Settings** module.\n2. Click on `Apps`.\n3. Then, click on `My apps`.\n4. Then, find the **Reviews and Ratings** app card and click on `Settings`.\n5. It is recommended that you check the **Display stars in product-rating-summary if there are no reviews** option and uncheck the **Display total reviews number on product-rating-summary block** option, as illustrated below.\n6. Click on the `Save` button.\n\n![Reviews and Ratings Settings](/assets/image1.png \"Reviews and Ratings Settings\")\n\n#### Quick Order\n\n[Quick Order](https://github.com/vtex-apps/quickorder) is an app that enables customers to make bulk orders.\n\nTo install it, use the following command:\n\n```\n vtex install vtex.quickorder@3.x\n```\n\n#### Location Availability\n\nThe [Location Availability](https://github.com/vtex-apps/location-availability) app shows product availability and shipping information in the storefront based on the customer’s location, providing a personalized shopping experience.\n\nInstall this app on your store using the `vtex.location-availability@0.x ` command.\n\n#### Shopper Location\n\n[Shopper Location](https://github.com/vtex-apps/shopper-location) is a geolocation app. Once it is installed, the app tracks the customer’s location, after permission is granted.\n\nTo install it, use the following command:\n\n```\nvtex install vtex.shopper-location@0.x\n```\n\n#### Wordpress integration\n\nThe [Wordpress integration](https://github.com/vtex-apps/wordpress-integration) app enables the account admin to create content on your store’s front through Wordpress’ API.\n\nTo install this app, run the following command on the CLI:\n\n```\nvtex install vtex.wordpress-integration@2.x\n```\n\n### Install B2B Easy Setup (optional)\n\nIf you are setting up a new store, you can follow the instructions in [this guide](https://developers.vtex.com/vtex-rest-api/docs/installing-b2b-easy-set-up) to quickly set up a test store with sample data using the B2B Easy Setup app.\n\n> 🚨 We strongly advise that you do not run Easy Setup on a production environment. It will make irreversible changes and may delete some previous configurations on your store.\n\n## Installation\n\nAfter following the steps above, you are ready to install the B2B Store Theme. You must:\n\n1. Run the `vtex install vtex.b2bstore@3.x `command on the CLI.\n2. Run the `vtex browse` command to see the B2B Store Theme on your browser.\n\nFinally, your storefront should look like this:\n\n![B2B Store Theme](/assets/image3.png \"B2B Store Theme\")\n\n## Customization\n\nAfter installing the B2B Store Theme, you can customize it according to your store’s business needs. Check our guide on [Customizing the B2B Store Theme](https://developers.vtex.com/vtex-developer-docs/docs/customizing-the-b2b-store-theme) for more information.\n\n```" } ]
code_b2b-theme_b46c5588
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/schemas/SellerRegistrationSchema.json from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"title\": \"Revenda\",\n \"type\": \"object\",\n \"properties\": {\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"title\": \"Email\"\n },\n \"stateRegistration\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"State Registration\"\n },\n \"homePhone\": {\n \"type\": \"string\",\n \"title\": \"Mobile\"\n },\n \"corporateDocument\": {\n \"type\": \"string\",\n \"maxLength\": 14,\n \"title\": \"EIN #: \"\n },\n \"phone\": {\n \"type\": \"string\",\n \"title\": \"Phone\"\n },\n \"lastName\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Last Name\"\n },\n \"tradeName\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Trade Name\"\n },\n \"corporateName\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Company Name\"\n },\n \"firstName\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"First Name\"\n },\n \"streetType\": {\n \"type\": \"string\",\n \"title\": \"Stree Type\",\n \"enum\": [\"Street\", \"Avenue\", \"Boulevard\", \"Road\", \"Junction\"]\n },\n \"city\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"City\"\n },\n \"reference\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Reference\"\n },\n \"street\": {\n \"type\": \"string\",\n \"title\": \"Street\"\n },\n \"state\": {\n \"type\": \"string\",\n \"title\": \"State\",\n \"enum\": [\n \"Alabama\",\n \"Alaska\",\n \"American Samoa\",\n \"Arizona\",\n \"Arkansas\",\n \"California\",\n \"Colorado\",\n \"Connecticut\",\n \"Delaware\",\n \"District Of Columbia\",\n \"Federated States Of Micronesia\",\n \"Florida\",\n \"Georgia\",\n \"Guam\",\n \"Hawaii\",\n \"Idaho\",\n \"Illinois\",\n \"Indiana\",\n \"Iowa\",\n \"Kansas\",\n \"Kentucky\",\n \"Louisiana\",\n \"Maine\",\n \"Marshall Islands\",\n \"Maryland\",\n \"Massachusetts\",\n \"Michigan\",\n \"Minnesota\",\n \"Mississippi\",\n \"Missouri\",\n \"Montana\",\n \"Nebraska\",\n \"Nevada\",\n \"New Hampshire\",\n \"New Jersey\",\n \"New Mexico\",\n \"New York\",\n \"North Carolina\",\n \"North Dakota\",\n \"Northern Mariana Islands\",\n \"Ohio\",\n \"Oklahoma\",\n \"Oregon\",\n \"Palau\",\n \"Pennsylvania\",\n \"Puerto Rico\",\n \"Rhode Island\",\n \"South Carolina\",\n \"South Dakota\",\n \"Tennessee\",\n \"Texas\",\n \"Utah\",\n \"Vermont\",\n \"Virgin Islands\",\n \"Virginia\",\n \"Washington\",\n \"West Virginia\",\n \"Wisconsin\",\n \"Wyoming\"\n ]\n },\n \"complement\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Complement\"\n },\n \"neighborhood\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Neighborhood\"\n },\n \"number\": {\n \"type\": \"string\",\n \"maxLength\": 750,\n \"title\": \"Number\"\n },\n \"postalCode\": {\n \"type\": \"string\",\n \"maxLength\": 9,\n \"title\": \"Zip Code\"\n },\n \"upload\": {\n \"type\": \"string\",\n \"maxLength\": 99999,\n \"title\": \"Operating Agreement\"\n }\n },\n \"required\": [\n \"email\",\n \"stateRegistration\",\n \"corporateDocument\",\n \"tradeName\",\n \"corporateName\",\n \"firstName\",\n \"lastName\",\n \"city\",\n \"street\",\n \"state\",\n \"postalCode\"\n ],\n \"v-security\": {\n \"allowGetAll\": true,\n \"publicWrite\": [\n \"email\",\n \"firstName\",\n \"lastName\",\n \"homePhone\",\n \"corporateName\",\n \"corporateDocument\",\n \"stateRegistration\",\n \"tradeName\",\n \"city\",\n \"street\",\n \"state\",\n \"neighborhood\",\n \"number\",\n \"postalCode\"\n ],\n \"publicRead\": [\n \"email\",\n \"stateRegistration\",\n \"homePhone\",\n \"corporateDocument\",\n \"phone\",\n \"lastName\",\n \"tradeName\",\n \"corporateName\",\n \"firstName\",\n \"city\",\n \"street\",\n \"state\",\n \"streetType\",\n \"neighborhood\",\n \"number\",\n \"postalCode\",\n \"upload\",\n \"complement\",\n \"reference\"\n ],\n \"publicJsonSchema\": true\n },\n \"v-triggers\": [\n {\n \"name\": \"insert-customer-table\",\n \"active\": true,\n \"condition\": \"\",\n \"action\": {\n \"type\": \"save\",\n \"dataEntity\": \"CL\",\n \"json\": {\n \"id\": \"{!id}\",\n \"approved\": \"false\",\n \"firstName\": \"{!firstName}\",\n \"lastName\": \"{!lastName}\",\n \"email\": \"{!email}\",\n \"homePhone\": \"{!homePhone}\",\n \"isCorporate\": \"true\",\n \"corporateName\": \"{!corporateName}\",\n \"tradeName\": \"{!tradeName}\",\n \"stateRegistration\": \"{!stateRegistration}\",\n \"corporateDocument\": \"{!corporateDocument}\",\n \"isOrgAdmin\": \"true\"\n }\n }\n },\n {\n \"name\": \"insert-address-table\",\n \"active\": true,\n \"condition\": \"\",\n \"action\": {\n \"type\": \"save\",\n \"dataEntity\": \"AD\",\n \"json\": {\n \"userId\": \"{!id}\",\n \"city\": \"{!city}\",\n \"reference\": \"{!reference}\",\n \"street\": \"{!street}\",\n \"state\": \"{!state}\",\n \"streetType\": \"{!streetType}\",\n \"neighborhood\": \"{!neighborhood}\",\n \"addressName\": \"Principal\",\n \"number\": \"{!number}\",\n \"country\": \"USA\",\n \"postalCode\": \"{!postalCode}\",\n \"complement\": \"{!complement}\",\n \"upload\": \"{!upload}\"\n }\n }\n }\n ]\n}\n\n```" } ]
code_b2b-theme_a1c0dcb4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/store/interfaces.json from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store.search.product-comparison\": {\n \"around\": [\"comparison-context-wrapper\"]\n },\n \"store.custom.product-comparison\": {\n \"around\": [\"comparison-context-wrapper\"]\n },\n \"search-result-layout.desktop.product-comparison\": {\n \"allowed\": [\"product-comparison-drawer\"]\n }\n}\n\n```" } ]
code_b2b-theme_a17d962f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/store/routes.json from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store.custom#product-comparison-list\": {\n \"path\": \"/product-comparison\"\n },\n \"store.custom#registration\": {\n \"path\": \"/registration\"\n },\n \"store.custom#quickOrderByOne\": {\n \"path\": \"/quickorder/one-by-one\"\n },\n \"store.custom#quickOrderByCategory\": {\n \"path\": \"/quickorder/by-category\"\n },\n \"store.custom#not-allow\": {\n \"path\": \"not-allowed\"\n },\n \"store.custom.product-comparison#deals\": {\n \"path\": \"/deals\"\n },\n \"store.custom.product-comparison#releases\": {\n \"path\": \"/releases\"\n },\n \"store.custom.product-comparison#top-sales\": {\n \"path\": \"/top-sales\"\n },\n \"store.custom#customer-services\": {\n \"path\": \"/services\"\n },\n \"store.custom#gift-cards\": {\n \"path\": \"/gift-cards\"\n },\n \"store.custom.product-comparison#popular\": {\n \"path\": \"/popular\"\n },\n \"store.custom.product-comparison#trending\": {\n \"path\": \"/trending\"\n },\n \"store.custom#company\": {\n \"path\": \"/company\"\n },\n \"store.custom#careers\": {\n \"path\": \"/careers\"\n },\n \"store.custom#sell\": {\n \"path\": \"/sell\"\n },\n \"store.custom#investors\": {\n \"path\": \"/investors\"\n },\n \"store.custom#advertise\": {\n \"path\": \"/advertise\"\n },\n \"store.custom#locations\": {\n \"path\": \"/locations\"\n },\n \"store.custom#accessibility\": {\n \"path\": \"/accessibility\"\n },\n \"store.custom#contact\": {\n \"path\": \"/contact\"\n },\n \"store.custom#help-center\": {\n \"path\": \"/help-center\"\n },\n \"store.custom#pickup\": {\n \"path\": \"/pickup\"\n },\n \"store.custom#recalls\": {\n \"path\": \"/recalls\"\n },\n \"store.custom#returns\": {\n \"path\": \"/returns\"\n }\n}\n\n```" } ]
code_b2b-theme_ca42ed0c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/store/plugins.json from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"my-account-pages > my-account-page\": \"my-account-page.wishlist-page\",\n \"my-account-menu > my-account-link\": \"my-account-link.wishlist-link\"\n}\n\n```" } ]
code_b2b-theme_08d4e35a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.store-link.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.link--popularLink,\n.link--trendingLink {\n text-decoration: none;\n}\n\n.label--popularLink,\n.label--trendingLink {\n color: #0067c7;\n font-size: 14px;\n line-height: 24px;\n font-weight: bold;\n}\n\n.label--popularLink::after,\n.label--trendingLink::after {\n content: url(\"assets/icons/chevronBlue.svg\");\n margin-left: 8px;\n top: 1px;\n position: relative;\n}\n\n.link--networkLink {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.16);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.link--shopByLink {\n width: 100%;\n text-decoration: none;\n}\n\n.link--shopByLink:hover :global(.vtex-rich-text-0-x-paragraph--shopByCategory) {\n color: #0067c7;\n}\n\n.link--shopByLink:hover .childrenContainer {\n border: 1px solid #0067c7;\n}\n\n.childrenContainer--shopByLink {\n display: flex;\n justify-content: center;\n align-items: center;\n flex-flow: column nowrap;\n max-width: 216px;\n height: 196px;\n background: #f3f9ff;\n border-radius: 4px;\n transition: all 0.3s ease;\n border: 1px solid transparent;\n}\n\n.childrenContainer--linkCategorySlider {\n display: flex;\n flex-flow: column nowrap;\n align-items: center;\n}\n\n.link--linkCategorySlider {\n text-decoration: none;\n}\n\n.link--blogLink {\n display: block;\n max-width: 100px;\n width: 100%;\n height: 32px;\n font-size: 14px;\n line-height: 32px;\n text-align: center;\n color: #0067c7;\n background: #f3f9ff;\n text-decoration: none;\n}\n\n.childrenContainer--linkMail,\n.childrenContainer--linkCall {\n display: flex;\n align-items: center;\n margin: 0;\n height: 48px;\n padding: 0px 20px;\n border-radius: 4px;\n max-width: 280px;\n width: 100%;\n}\n\n.childrenContainer--linkCall {\n background: var(--b2b-header-blue-medium);\n}\n\n.childrenContainer--linkMail {\n border: 1px solid var(--b2b-header-blue-medium);\n}\n\n.link--linkCall,\n.link--linkMail {\n text-transform: uppercase;\n color: #fff;\n font-size: 14px;\n line-height: 24px;\n font-weight: 700;\n font-family: Roboto;\n text-decoration: none;\n}\n\n.link--linkCall :global(.vtex-store-components-3-x-imageElement),\n.link--linkMail :global(.vtex-store-components-3-x-imageElement) {\n margin-right: 12px;\n}\n\n.link--linkCall {\n margin-bottom: 12px;\n display: block;\n}\n\n.link--quickLink {\n text-decoration: none;\n position: relative;\n}\n\n.link--quickLink::after {\n content: url(\"assets/icons/nav-arrow-right.svg\");\n display: block;\n position: absolute;\n color: #717786;\n right: 0;\n top: 50%;\n transform: translate(-50%, -50%);\n}\n\n.link--quickOrderButton {\n text-decoration: none;\n padding: 24px;\n background: #f2f5f9;\n border: 1px solid #dee7ef;\n display: block;\n margin-bottom: 8px;\n border-radius: 4px;\n position: relative;\n}\n\n.link--quickOrderButton::after {\n content: url(\"assets/icons/nav-arrow-right-blue.svg\");\n display: block;\n position: absolute;\n color: #717786;\n right: 12px;\n top: 50%;\n transform: translate(-50%, -50%);\n}\n.link--order-quote {\n\tmargin: 0 16px 16px;\n width: 92%;\n padding: 13px 0;\n font-size: 18px;\n}\n\n.link--menu-order-quote {\n\ttext-decoration: none;\n\tfont-size: 16px;\n\tline-height: 44px;\n\tfont-family: Roboto;\n\tcolor: rgb(113, 119, 134);\n font-size: 20px;\n line-height: 28px;\n color: #000;\n font-weight: 500;\n margin: 0;\n margin-bottom: 4px;\n display: flex;\n align-items: center;\n margin-top: 15px;\n}\n\n.link--orderQuote,\n.link--resellerLink {\n display: flex;\n align-items: center;\n text-decoration: none;\n color: #fff;\n height: 100%;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n}\n\n@media (max-width: 64rem) {\n .childrenContainer--accountLink :global(.vtex-store-icons-0-x-profileIcon) {\n color: #fff;\n width: 20px;\n height: 20px;\n }\n\n .link--footerLink {\n color: #fff;\n font-size: 16px;\n line-height: 48px;\n font-weight: 500;\n font-family: Roboto;\n text-decoration: none;\n }\n\n .link--networkLink {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.16);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n}\n\n```" } ]
code_b2b-theme_30159a0c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.product-comparison.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.drawerContainer {\n z-index: 6;\n}\n\n.productSelectorContainer {\n opacity: 0;\n transition: all 0.3s ease;\n}\n\n.productSelectorContainer :global(.vtex-checkbox__line-container) {\n justify-content: center;\n}\n\n.productSelectorContainer :global(.vtex-checkbox__label) {\n width: auto;\n}\n\n.productSelectorContainer :global(.vtex-checkbox__inner-container) {\n width: 20px;\n height: 20px;\n border-width: 1px;\n}\n\n.productSelectorContainer :global(.vtex-checkbox__container),\n.productSelectorContainer :global(.vtex-checkbox__input) {\n width: 20px;\n height: 20px;\n}\n\n.imageElement--paymentImage {\n margin: 0px auto;\n}\n.showDifferencesContainer :global(.vtex-checkbox__inner-container),\n.productSelectorContainer :global(.vtex-checkbox__inner-container) {\n border-color: #a3afbc;\n}\n\n.productSelectorContainer :global(.vtex-checkbox__box-wrapper) {\n width: 20px;\n height: 20px;\n}\n\n.productSelectorContainer :global(.vtex__icon-check) {\n width: 16px;\n height: 16px;\n}\n\n```" } ]
code_b2b-theme_fd24843e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.search.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.tileList .tileListList {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr;\n grid-gap: 12px;\n padding: 0px 24px;\n margin: 0;\n}\n\n.tileListTitle {\n display: none;\n opacity: 0;\n}\n\n.biggy-autocomplete {\n padding-top: 0;\n}\n\n.tileList,\n.itemList--suggestion {\n padding-top: 24px;\n}\n\n.itemListTitle {\n font-size: 20px;\n line-height: 24px;\n font-weight: 500;\n color: #000;\n text-transform: initial;\n}\n\n@media (max-width: 64rem) {\n .biggy-autocomplete {\n padding: 0;\n }\n\n .tileList .tileListList {\n grid-template-columns: 1fr;\n }\n}\n\n```" } ]
code_b2b-theme_6c03e631
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.product-price.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.sellingPrice--desktop {\n font-size: 24px;\n font-weight: normal;\n line-height: 32px;\n color: #000000;\n}\n\n.sellingPrice .sellingPriceValue--desktop {\n display: none;\n}\n\n.sellingPriceWithTax--desktop {\n font-size: 28px;\n font-weight: bold;\n}\n\n.listPrice--desktop {\n font-size: 16px;\n line-height: 20px;\n text-decoration-line: line-through;\n color: #717786;\n}\n\n.savings--desktop {\n font-size: 14px;\n line-height: 20px;\n color: #717786;\n}\n\n.savingsValue--desktop {\n color: #468a2e;\n font-weight: 500;\n}\n\n.savings--savingSummary {\n display: block;\n background: #e5f1e1;\n color: #468a2e;\n text-transform: uppercase;\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n padding: 0px 8px;\n border-radius: 10px;\n}\n\n.savings--savingPercentage {\n display: block;\n background: var(--fresh-orange);\n color: #fff;\n text-transform: uppercase;\n font-size: 12px;\n line-height: 18px;\n font-weight: 700;\n padding: 0px 8px;\n border-radius: 10px;\n}\n\n.savings--savingPercent {\n margin-left: 4px;\n color: #468a2e;\n font-weight: 500;\n}\n\n@media (max-width: 64rem) {\n .savings--savingPercent {\n color: #000;\n }\n\n .currencyContainer--sticky {\n font-size: 20px;\n line-height: 28px;\n color: #000;\n font-weight: bold;\n font-family: Roboto;\n }\n}\n\n/* Seller Name */\n\n.sellerNameContainer--default {\n font-size: 0.875rem;\n color: var(--black-medium);\n margin-bottom: 0.5rem;\n}\n\n.sellerName--default {\n color: var(--black-dark);\n font-weight: 500;\n}\n\n```" } ]
code_b2b-theme_0096f923
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.product-customizer.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.textInputValue {\n margin-top: 8px !important;\n}\n\n.textInputValue :global(.vtex-input-prefix__group) {\n border: none;\n}\n\n.textInputValue :global(.vtex-styleguide-9-x-input) {\n background: #ffffff;\n border: 1px solid #a3afbc;\n box-sizing: border-box;\n border-radius: 4px;\n padding: 0 20px;\n}\n\n.textInputValue :global(.vtex-input__label) {\n display: none;\n}\n\n.textInputValue::after {\n display: inline-block;\n color: #717786;\n content: \"Max. of 20 characters\";\n font-size: 12px;\n margin-top: 8px;\n}\n\n```" } ]
code_b2b-theme_4c42fa90
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.store.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n:global(.vtex-store__template),\n:global(.vtex-modal-layout-0-x-container),\n:global(.vtex-minicart-2-x-drawer),\n:global(.vtex-telemarketing-2-x-portalContainer),\n:global(.vtex-login-2-x-portalContainer) {\n --black-dark: #000000;\n --fresh-blue: #0067c7;\n --fresh-blue-dark: #0067c7;\n --fresh-blue-lightest: #f3f9ff;\n --fresh-orange: #ff5f00;\n --fresh-darkest: #003364;\n --green-dark: #468a2e;\n --black-medium: #717786;\n --b2b-header-blue-medium: #597298;\n --blue-medium: #597298;\n --b2b-blue-darkest: #1b3255;\n --lines-dark: #bdc9d6;\n --lines-darker: #a3afbc;\n --lines-light: #dee7ef;\n --serious-blue-dark: #214d8e;\n --serious-black: #142032;\n --serious-orange: #ff7d30;\n --base: #fff;\n}\n\n```" } ]
code_b2b-theme_c886e6f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.quickorder.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n@media (max-width: 64rem) {\n .categoryButtonAdd {\n padding: 0;\n }\n\n .categoryButtonAdd :global(.vtex-button) {\n width: 100%;\n height: 48px;\n background: #ff7d30;\n border-radius: 4px;\n display: block;\n line-height: 48px;\n border: none;\n margin: 16px 0px 24px;\n }\n\n .categoryContainer .textContainer :not(:global(.vtex-fake)) {\n margin: 0;\n }\n}\n\n```" } ]
code_b2b-theme_ea9c96dd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.orderquote.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.containerCreate,\n.containerList,\n.containerView {\n max-width: 1440px;\n width: 100%;\n padding: 0px;\n margin: 0px auto;\n}\n\n.buttonSave :global(.vtex-button),\n.createButton :global(.vtex-button),\n.buttonUse :global(.vtex-button) {\n background: var(--serious-blue-dark);\n}\n\n```" } ]
code_b2b-theme_9bc43000
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.minicart.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.drawer {\n z-index: 999;\n}\n\n.minicartIconContainer {\n color: #fff;\n}\n\n.closeIconContainer::before {\n content: \"My cart\";\n font-size: 24px;\n line-height: 32px;\n font-family: Roboto;\n color: #000;\n font-weight: 500;\n}\n\n.closeIconButton {\n margin-left: auto;\n padding: 12px 0px;\n}\n\n.closeIconContainer {\n background: #f3f9ff;\n align-items: center;\n padding: 0px 24px;\n}\n\n.minicartTitle {\n display: none;\n opacity: 0;\n}\n\n.openIconContainer {\n padding: 0;\n}\n\n.openIconContainer :global(.vtex-button) {\n border: none;\n border-radius: 0;\n outline: none;\n}\n\n.minicartQuantityBadge {\n background-color: #ff5f00;\n font-weight: 700;\n}\n\n.minicartCheckoutButton {\n padding: 12px 16px 16px;\n margin: 0;\n}\n\n.minicartCheckoutButton :global(.vtex-button) {\n height: 52px;\n background: #ff5f00;\n border-radius: 4px;\n border: none;\n font-weight: 700;\n font-family: Roboto;\n font-size: 18px;\n line-height: 28px;\n outline: none;\n}\n\n@media (max-width: 64rem) {\n .openIconContainer {\n padding: 0;\n }\n\n .drawer {\n width: 100% !important;\n }\n}\n\n```" } ]
code_b2b-theme_f3e0748e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.sku-list.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.skuContentWrapper {\n cursor: pointer;\n border-radius: 0;\n border-width: 0.0625rem;\n margin: 0 -0.5rem -0.0625rem;\n padding: 0.5rem 1rem;\n}\n\n.skuContentWrapper:focus {\n outline: none;\n}\n\n.skuContentWrapper:first-child {\n margin-top: -0.5rem;\n border-top-left-radius: 0.25rem;\n border-top-right-radius: 0.25rem;\n}\n\n.skuContentWrapper:last-child {\n margin-bottom: -0.5rem;\n border-bottom-left-radius: 0.25rem;\n border-bottom-right-radius: 0.25rem;\n}\n\n.itemHighlight,\n.priceContainer,\n.inventoryContainer,\n.highlightContent {\n padding: 0;\n}\n\n```" } ]
code_b2b-theme_18802f1c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.rich-text.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* BEGIN - Header */\n.container--HeaderStripeText {\n margin-right: 24px;\n}\n\n.container--HeaderStripeText .link {\n color: #fff;\n font-weight: 500;\n font-size: 14px;\n line-height: 20px;\n text-decoration: none;\n}\n\n.headingLevel2--menuTitle {\n font-size: 20px;\n line-height: 24px;\n font-weight: 500;\n font-family: Roboto;\n color: #000;\n margin: 0;\n margin-bottom: 24px;\n}\n\n.container--menuTitle {\n margin-top: 38px;\n padding-top: 38px;\n border-top: 1px solid #dee7ef;\n}\n\n.headingLevel2--quickTitle {\n font-size: 20px;\n line-height: 28px;\n color: #000;\n font-weight: 500;\n margin: 0;\n margin-bottom: 4px;\n display: flex;\n align-items: center;\n}\n\n.headingLevel2--quickTitle::before {\n content: url(\"assets/icons/quickOrderIcon.svg\");\n display: block;\n margin-right: 10px;\n width: 22px;\n height: 22px;\n}\n\n.paragraph--quickText {\n font-size: 14px;\n line-height: 20px;\n margin: 0;\n color: #717786;\n}\n\n/* END - Header */\n/* BEGIN - Generic */\n\n.headingLevel3--sectionTitle,\n.headingLevel3--shopByCategoryTitle {\n font-size: 24px;\n font-weight: 500;\n line-height: 32px;\n color: #000000;\n margin: 0;\n margin-bottom: 16px;\n}\n\n.wrapper--alsoView,\n.wrapper--sectionTitle {\n width: 100%;\n}\n\n.headingLevel3--alsoView,\n.headingLevel3--sectionTitle {\n padding-bottom: 16px;\n border-bottom: 1px solid #e9eff5;\n}\n\n.headingLevel3--alsoView {\n font-size: 24px;\n font-weight: 500;\n line-height: 32px;\n color: #000000;\n margin: 0;\n margin-bottom: 16px;\n margin-top: 32px;\n}\n\n/* END - Generic */\n/* BEGIN - ShopByCategory */\n\n.wrapper--shopByCategory {\n width: 100%;\n height: 100%;\n}\n\n.paragraph--shopByCategory {\n margin: 0;\n height: 100%;\n}\n\n.link--shopByCategory {\n display: flex;\n flex-flow: column;\n align-items: center;\n text-decoration: none;\n height: 100%;\n justify-content: center;\n}\n\n.image--shopByCategory {\n display: block;\n margin-bottom: 24px;\n}\n\n.strong--shopByCategory {\n font-size: 18px;\n line-height: 24px;\n color: #000;\n font-weight: 400;\n}\n\n/* END - ShopByCategory */\n/* BEGIN - QuickViewTrigger */\n\n.container--quickviewTrigger .image {\n display: block;\n width: 20px;\n}\n\n/* END - QuickViewTrigger */\n/* BEGIN - BannerThird */\n\n.headingLevel4--bannerTitle {\n margin: 0;\n margin-bottom: 12px;\n font-size: 20px;\n line-height: 28px;\n font-weight: 500;\n color: #000;\n}\n\n.paragraph--bannerDesc {\n max-width: 388px;\n width: 100%;\n margin: 0px auto 16px;\n color: #717786;\n font-size: 16px;\n font-weight: 400;\n line-height: 24px;\n}\n\n.container--bannerTitle,\n.container--bannerDesc,\n.container--bannerLink {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.paragraph--bannerLink {\n margin: 0;\n}\n\n.link--bannerLink {\n width: 244px;\n height: 48px;\n background-color: #0067c7;\n border-radius: 4px;\n color: #fff;\n font-size: 14px;\n line-height: 48px;\n font-weight: 700;\n font-family: Roboto;\n display: block;\n text-decoration: none;\n}\n\n/* END - BannerThird */\n/* BEGIN - Benefits Bar */\n\n.wrapper--benefitsItem .paragraph {\n display: flex;\n flex-flow: column nowrap;\n align-items: center;\n margin: 0;\n color: #717786;\n font-size: 14px;\n line-height: 20px;\n font-family: Roboto;\n}\n\n.wrapper--benefitsItem .image {\n object-fit: contain;\n display: block;\n margin-bottom: 24px;\n width: 34px;\n height: 26px;\n}\n\n.wrapper--benefitsItem .strong {\n font-size: 18px;\n line-height: 24px;\n font-family: Roboto;\n color: #000;\n font-weight: 500;\n display: block;\n margin: 0;\n margin-bottom: 8px;\n}\n/* END - Benefits Bar */\n/* BEGIN - Footer */\n\n.paragraph--footerStripe {\n font-size: 12px;\n line-height: 18px;\n color: rgba(225, 239, 255, 0.5);\n margin: 0;\n padding: 32px 0px;\n}\n\n.paragraph--footerTitle {\n margin: 0;\n color: #e1efff;\n margin-bottom: 16px;\n font-size: 18px;\n line-height: 24px;\n font-family: Roboto;\n font-weight: 500;\n}\n\n.paragraph--mailTo,\n.paragraph--callTo {\n text-transform: uppercase;\n color: #fff;\n font-size: 14px;\n line-height: 24px;\n font-weight: 700;\n font-family: Roboto;\n text-decoration: none;\n margin: 0;\n}\n\n.paragraph--footerText {\n margin: 0;\n color: #e1efff;\n font-size: 12px;\n line-height: 16px;\n font-weight: 500;\n text-align: left;\n}\n\n.paragraph--footerRights {\n font-size: 14px;\n line-height: 24px;\n color: #fff;\n}\n\n.paragraph--followTitle {\n margin: 0;\n margin-bottom: 16px;\n font-size: 14px;\n line-height: 20px;\n font-weight: 500;\n color: rgba(255, 255, 255, 0.5);\n}\n\n/* END - Footer */\n/* BEGIN - Trending Shelf */\n\n.heading--trendingTitle {\n font-size: 24px;\n line-height: 32px;\n color: #000;\n font-family: Roboto;\n margin: 0;\n}\n\n/* END - Trending Shelf */\n/* BEGIN - Popular Shelf */\n\n.headingLevel3--popularTitle {\n font-size: 24px;\n line-height: 32px;\n color: #000;\n font-weight: 500;\n font-family: Roboto;\n margin: 0;\n margin-bottom: 16px;\n}\n\n/* END - Popular Shelf */\n/* BEGIN - QuickOrder */\n\n.headingLevel3--titleQuickorder {\n margin-left: 0.5rem;\n}\n\n/* END - QuickOrder */\n/* BEGIN - Search Page */\n\n.paragraph--SEOText {\n font-size: 14px;\n line-height: 18px;\n font-family: Roboto;\n color: #717786;\n margin: 0;\n margin-bottom: 24px;\n}\n\n.paragraph--textCategorySlider {\n font-size: 14px;\n line-height: 20px;\n color: #717786;\n margin: 0;\n}\n\n.paragraph--blogSEO {\n max-height: 400px;\n overflow: auto scroll;\n padding: 0;\n margin: 0;\n font-size: 14px;\n line-height: 20px;\n color: #717786;\n}\n\n.heading--blogTitle {\n font-size: 16px;\n line-height: 20px;\n font-weight: 500;\n font-family: Roboto;\n margin: 0;\n margin-bottom: 8px;\n color: #000;\n}\n\n.paragraph--blogDescription {\n font-size: 14px;\n line-height: 18px;\n font-family: Roboto;\n color: #717786;\n margin: 0;\n margin-bottom: 24px;\n}\n\n/* END - Search Page */\n\n@media (max-width: 64rem) {\n .paragraph--blogSEO {\n width: 100%;\n max-width: 100%;\n margin: 0;\n padding: 0;\n max-height: initial;\n margin-bottom: 40px;\n }\n\n .headingLevel3--blogSecondarySEO {\n font-size: 18px;\n line-height: 28px;\n color: #000;\n margin: 0;\n margin-bottom: 40px;\n }\n\n .wrapper--shopByCategoryTitle {\n margin: 0px auto;\n }\n\n .headingLevel3--sectionTitle {\n border: none;\n padding: 0;\n margin: 0;\n }\n\n .link--sectionLink {\n text-decoration: none;\n font-size: 14px;\n line-height: 24px;\n color: var(--fresh-blue);\n font-family: Roboto;\n display: flex;\n align-items: center;\n }\n\n .link--sectionLink::after {\n content: url(\"assets/icons/chevronRight.svg\");\n display: block;\n margin-left: 8px;\n height: 21px;\n }\n\n .headingLevel4--bannerTitle {\n max-width: 250px;\n width: 100%;\n margin: 0px auto 12px;\n font-size: 20px;\n line-height: 28px;\n font-weight: 500;\n }\n\n .paragraph--bannerDesc {\n font-size: 14px;\n line-height: 20px;\n }\n\n .link--bannerLink {\n height: 40px;\n line-height: 40px;\n }\n\n .headingLevel3--titleWithBorder {\n font-size: 24px;\n line-height: 32px;\n font-weight: 500;\n font-family: Roboto;\n color: #000;\n margin: 0;\n margin-bottom: 16px;\n padding-bottom: 16px;\n border-bottom: 1px solid #e9eff5;\n text-align: center;\n }\n\n .wrapper--titleWithBorder {\n width: 100%;\n }\n\n .paragraph--benefitsItem {\n text-align: center;\n font-size: 12px;\n line-height: 16px;\n }\n\n .strong--benefitsItem {\n font-size: 16px;\n line-height: 24px;\n }\n\n .container--paymentLabel {\n justify-content: center;\n }\n\n .paragraph--paymentLabel {\n margin: 0;\n font-size: 12px;\n line-height: 16px;\n margin-bottom: 12px;\n color: rgba(255, 255, 255, 0.5);\n }\n\n .paragraph--footerStripe {\n text-align: center;\n padding: 0px;\n margin-bottom: 24px;\n }\n\n .container--copyright {\n justify-content: center;\n }\n\n .paragraph--copyright {\n margin: 0;\n margin-bottom: 8px;\n font-size: 12px;\n line-height: 16px;\n font-weight: 500;\n color: #fff;\n }\n\n .link--HeaderStripeText {\n white-space: nowrap;\n }\n\n .paragraph--HeaderStripeText,\n .container--HeaderStripeText {\n margin: 0;\n }\n\n .paragraph--SEOText {\n font-size: 12px;\n line-height: 16px;\n }\n\n .headingLevel2--quickOrderButtonTitle {\n font-size: 16px;\n line-height: 24px;\n color: #000;\n margin: 0;\n margin-bottom: 4px;\n }\n\n .paragraph--quickOrderButtonText {\n font-size: 14px;\n line-height: 18px;\n color: #717786;\n margin: 0;\n max-width: 240px;\n }\n\n .wrapper--quickOrderTitlePageMobile {\n width: 100%;\n }\n\n .headingLevel1--quickOrderTitlePageMobile {\n font-size: 24px;\n line-height: 32px;\n margin: 0;\n color: #000;\n padding-bottom: 16px;\n margin-bottom: 24px;\n border-bottom: 1px solid #e9eff5;\n }\n}\n\n.paragraph--disclosure-trigger-heading {\n color: #000000;\n font-weight: 500;\n font-size: 20px;\n line-height: 24px;\n margin: 0;\n padding: 0;\n}\n\n.paragraph--skuList {\n margin: 0;\n line-height: 1.5;\n}\n\n.paragraph--modal-trigger-shipping-availability {\n cursor: pointer;\n}\n\n.paragraph--modal-trigger-shipping-availability:hover {\n text-decoration: underline;\n}\n\n/* Reset Spacing */\n\n.container--reset-spacing,\n.container--reset-spacing :not(:global(.vtex-fake)) {\n margin: 0;\n padding: 0;\n}\n\n.container--black-medium {\n color: var(--black-medium);\n}\n\n.container--fw5 {\n font-weight: 500;\n}\n\n.container--newsletter-title,\n.wrapper--newsletter-title {\n width: 100%;\n}\n\n.container--newsletter-title .heading {\n color: #fff;\n font-size: 2rem;\n font-weight: 500;\n line-height: 1.25;\n margin-right: auto;\n}\n\n@media (max-width: 64rem) {\n .container--newsletter-title .heading {\n font-size: 1.25rem;\n line-height: 1.4;\n margin-bottom: 0.75rem;\n text-align: center;\n }\n}\n\n.paragraph--form-section-title {\n margin: 0;\n margin-bottom: 0.5rem;\n}\n\n.paragraph--product-price-message,\n.paragraph--product-summary-price-message {\n text-align: center;\n color: var(--black-medium);\n font-weight: 500;\n margin: 0;\n padding: 0;\n}\n\n.paragraph--product-summary-price-message {\n font-size: 0.75rem;\n line-height: 1.5;\n}\n\n.container--product-price-message,\n.container--product-summary-price-message {\n border: 1px solid var(--lines-dark);\n border-radius: 0.25rem;\n padding: 1rem;\n}\n\n.container--product-summary-price-message {\n margin-bottom: 0.5rem;\n padding: 0.5rem;\n}\n\n.wrapper--product-price-message,\n.wrapper--product-summary-price-message {\n width: 100%;\n}\n\n```" } ]
code_b2b-theme_2931264c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.store-icons.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.caretIcon--fresh-blue {\n color: var(--fresh-blue);\n}\n\n.caretIcon--lines-darker {\n color: var(--lines-darker);\n}\n\n```" } ]
code_b2b-theme_c425547e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.login.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.container :global(.vtex-button) {\n border: 1px solid #fff;\n border-radius: 4px;\n width: 176px;\n height: 48px;\n}\n\n.container :global(.vtex-button__label) {\n padding: 0 0 0 0;\n}\n\n.label {\n color: #fff;\n text-transform: initial;\n font-size: 16px;\n line-height: 24px;\n}\n\n.profile {\n color: #fff;\n}\n\n.sendButton :global(.vtex-button) {\n background: #214d8e;\n border: none;\n}\n\n@media (max-width: 64rem) {\n .profile {\n display: block;\n }\n\n .container :global(.vtex-button) {\n width: 74px;\n height: 32px;\n border-color: #fff;\n }\n\n .label {\n display: block;\n color: #fff;\n font-size: 0;\n padding: 0;\n }\n\n .label::after {\n content: \"Sing in\";\n font-family: Roboto;\n font-size: 14px;\n line-height: 32px;\n font-weight: 500;\n }\n}\n\n```" } ]
code_b2b-theme_6853ecd6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.product-summary.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.container--summaryComplete {\n position: relative;\n max-width: 240px;\n border: 1px solid transparent;\n border-radius: 8px;\n padding: 20px;\n transition: all 0.3s ease;\n}\n\n.containerNormal--minimumSummary {\n padding: 0 0.5rem;\n}\n\n.container--summaryComplete:hover {\n border-color: #dee7ef;\n}\n\n.container--summaryComplete:hover\n :global(.vtex-product-comparison-0-x-productSelectorContainer),\n.container--summaryComplete:hover .buyButtonContainer,\n.container--summaryComplete:hover\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button),\n.container--summaryComplete:hover\n :global(.vtex-wish-list-1-x-wishlistIconContainer),\n.container--summaryComplete:hover\n :global(.vtex-modal-layout-0-x-triggerContainer) {\n opacity: 1;\n}\n\n.container--summaryComplete\n :global(.vtex-store-components-3-x-installmentsPrice) {\n display: none;\n}\n\n.container--summaryComplete .buyButton :global(.vtex-button),\n.container--summaryComplete\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button)\n :global(.vtex-button) {\n border: none;\n background-color: #ff5f00;\n height: 48px;\n border-radius: 4px;\n}\n\n.priceContainer {\n align-items: flex-start;\n}\n\n.nameWrapper,\n.price_sellingPriceContainer,\n.price_listPriceContainer {\n text-align: left;\n padding-bottom: 0;\n margin-bottom: 4px;\n}\n\n.price_sellingPriceLabel,\n.element--minimumSummary .price_listPriceContainer,\n.element--minimumSummary .price_installmentContainer {\n display: none;\n overflow: 0;\n visibility: hidden;\n}\n\n.container--summaryComplete .price_listPrice,\n.container--summaryComplete .price_sellingPrice {\n padding: 0;\n}\n\n.container--summaryComplete .productBrandContainer {\n font-size: 14px;\n color: #0067c7;\n font-weight: 500;\n line-height: 20px;\n text-align: left;\n}\n\n.container--summaryComplete .nameContainer {\n padding: 0;\n}\n\n.container--summaryComplete .productNameContainer {\n text-align: left;\n font-size: 16px;\n line-height: 22px;\n color: #000;\n width: 100%;\n margin-bottom: 16px;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.container--summaryComplete .buyButtonContainer,\n.container--summaryComplete\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button) {\n margin-top: auto;\n margin-bottom: 16px;\n padding: 0;\n}\n\n.container--summaryComplete .image {\n margin-bottom: 16px;\n width: 196px;\n height: 196px;\n object-fit: contain;\n}\n\n.element--summaryComplete {\n padding: 0;\n}\n\n.element--summaryComplete .priceContainer {\n align-items: flex-start;\n padding: 0;\n}\n\n.element--summaryComplete .buyButtonContainer,\n.element--summaryComplete\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button) {\n opacity: 0;\n transition: all 0.3s ease;\n}\n\n.element--summaryComplete .productPriceClass {\n flex-flow: column-reverse;\n}\n\n.element--summaryComplete .listPriceLabel,\n.element--summaryComplete .sellingPriceLabel {\n display: none;\n}\n\n.element--summaryComplete .listPriceValue .currencyContainer {\n font-size: 12px;\n line-height: 16px;\n font-weight: 400;\n font-family: Roboto;\n color: #717786;\n}\n\n.currencyCode {\n margin-right: 4px;\n}\n\n/* BEGIN - Trending Shelg */\n\n.column--summaryCol {\n flex-flow: column nowrap;\n align-items: flex-start;\n}\n\n.element--trendingSummary\n :global(.vtex-reviews-and-ratings-1-x-inlineContainer) {\n margin: 0;\n}\n\n.element--trendingSummary :global(.vtex-flex-layout-0-x-flexRowContent) {\n align-items: center;\n}\n\n.element--trendingSummary .imageStackContainer {\n margin-right: 24px;\n}\n\n.container--trendingSummary {\n max-width: 100% !important;\n width: 100%;\n background: #fff;\n border-radius: 8px;\n padding: 16px 24px;\n border: 1px solid transparent;\n transition: all 0.3s ease;\n}\n\n.container--trendingSummary:hover {\n border: 1px solid var(--fresh-blue);\n box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);\n}\n\n.element--trendingSummary {\n justify-content: center;\n padding: 0;\n}\n\n.element--trendingSummary .price_installmentContainer,\n.element--trendingSummary .listPriceContainer {\n display: none;\n}\n\n.element--trendingSummary .image {\n width: 96px !important;\n height: 96px;\n object-fit: cover;\n}\n\n.element--trendingSummary .nameContainer {\n padding: 0;\n margin-bottom: 8px;\n}\n\n.element--trendingSummary .productBrand {\n font-weight: 700;\n text-align: left;\n color: #000;\n font-size: 16px;\n line-height: 22px;\n}\n\n.element--trendingSummary .price_sellingPrice,\n.element--trendingSummary .price_sellingPriceContainer,\n.element--trendingSummary .priceContainer {\n padding: 0;\n}\n\n/* END - Trending Shelg */\n/* BEGIN - Popular Shelf */\n\n.container--minimumSummary .image {\n width: 192px;\n height: 192px;\n object-fit: contain;\n}\n\n/* END - Popular Shelf */\n\n.column--drawer-summary-col2 {\n align-items: flex-start;\n}\n\n.element--comparison-page-summary .buyButton :global(.vtex-button),\n.element--comparison-page-summary\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button)\n :global(.vtex-button) {\n border: none;\n height: 48px;\n background: #ff5f00;\n}\n\n.element--comparison-page-summary .sellingPrice,\n.element--comparison-page-summary .buyButtonContainer,\n.element--comparison-page-summary\n :global(.vtex-flex-layout-0-x-flexRow--product-summary-buy-button) {\n padding: 0;\n}\n\n/* BEGIN - Search Bar Summary */\n\n.element--summarySearch .imageContainer {\n margin-bottom: 8px;\n width: auto;\n margin-right: auto;\n margin-left: initial;\n}\n\n.element--summarySearch .productBrandContainer {\n text-align: left;\n}\n\n.element--summarySearch .productBrandContainer .productBrandName {\n font-size: 14px;\n color: #0067c7;\n font-weight: 500;\n line-height: 20px;\n margin-bottom: 4px;\n}\n\n.element--summarySearch .nameContainer {\n padding: 0;\n justify-content: flex-start;\n}\n\n.element--summarySearch .nameContainer .productBrand {\n font-size: 12px;\n line-height: 18px;\n color: #000;\n}\n\n/* END - Search Bar Summary */\n\n@media (max-width: 64rem) {\n .container--summaryComplete {\n padding: 8px;\n }\n\n .container--summaryComplete {\n min-width: 144px !important;\n max-width: 100% !important;\n }\n\n .element--minimumSummary\n :global(.vtex-reviews-and-ratings-1-x-inlineContainer) {\n margin: 0;\n }\n\n .element--minimumSummary .priceContainer {\n align-items: flex-start;\n }\n\n .element--summaryComplete .price_sellingPrice {\n font-size: 20px;\n color: #000;\n line-height: 24px;\n font-weight: 500;\n }\n}\n\n```" } ]
code_b2b-theme_38189a04
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.location-availability.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.shippingHeader--desktop {\n display: none;\n font-size: 16px;\n font-weight: 500;\n color: black;\n}\n\n.shippingListItem--desktop {\n display: none;\n}\n\n.shippingListItem--desktop:first-child {\n display: block;\n}\n\n.shippingListEmptyMessage,\n.shippingDeliveryName--desktop,\n.shippingListItem--desktop {\n font-size: 14px;\n color: black;\n}\n\n```" } ]
code_b2b-theme_c4efb2c3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.modal-layout.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.triggerContainer--quickviewTrigger {\n background: #f3f9fe;\n position: absolute;\n width: 38px;\n height: 38px;\n border-radius: 50%;\n top: 76px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: all 0.3s ease;\n outline: none;\n}\n\n.paper--quickviewContainer {\n padding: 32px;\n overflow: visible;\n}\n\n.paper--quickviewContainer\n :global(.vtex-store-components-3-x-carouselGaleryThumbs) {\n display: none;\n opacity: 0;\n visibility: hidden;\n}\n\n.paper--quickviewContainer\n :global(.vtex-store-components-3-x-productImagesContainer),\n.paper--quickviewContainer\n :global(.vtex-store-components-3-x-carouselContainer) {\n width: auto;\n}\n\n.paper--quickviewContainer\n :global(.vtex-store-components-3-x-carouselGaleryCursor) {\n margin-left: initial !important;\n width: initial !important;\n}\n\n.paper--quickviewContainer\n :global(.vtex-store-components-3-x-productImagesContainer--desktop)::after {\n content: none;\n}\n\n.paper--quickviewContainer :global(.vtex-flex-layout-0-x-flexCol--right-col) {\n margin-right: 24px;\n}\n\n.paper--quickviewContainer .closeButton {\n width: 32px;\n height: 32px !important;\n display: block;\n position: absolute;\n top: -12px;\n right: -12px;\n min-height: initial;\n border-radius: 50%;\n background: #dee7ef;\n border: none;\n outline: none;\n}\n\n.paper--quickviewContainer .closeButtonLabel {\n display: none;\n}\n\n.paper--quickviewContainer .closeButton::before {\n content: url(\"assets/icons/closeQuickviewIcon.svg\");\n display: block;\n}\n\n/* Shipping Availability */\n\n.headerContainer--shipping-availability {\n align-items: center;\n border-bottom: 1px solid var(--lines-light);\n position: relative;\n padding: 0.5rem 1rem;\n}\n\n.closeButtonContainer--shipping-availability {\n align-items: center;\n background-color: var(--lines-light);\n border-radius: 999px;\n display: flex;\n height: 2rem;\n justify-content: center;\n top: 1rem;\n right: 1rem;\n width: 2rem;\n}\n\n@media (min-width: 64rem) {\n .paper--shipping-availability {\n overflow: visible;\n }\n .headerContainer--shipping-availability {\n border: none;\n height: 0;\n padding: 0;\n }\n .headerContent--shipping-availability {\n display: none;\n }\n .closeButtonContainer--shipping-availability {\n position: absolute;\n top: 0;\n right: 0;\n transform: translate(50%, -50%);\n }\n}\n\n.closeButton--shipping-availability {\n padding: 0;\n font-style: 0;\n line-height: 0;\n}\n\n.closeIcon--shipping-availability {\n height: 1.25rem;\n width: 1.25rem;\n}\n\n```" } ]
code_b2b-theme_5b68cd39
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.sticky-layout.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.container--headerMobile {\n background: #597298;\n z-index: 999;\n}\n\n.wrapper--box--stuck .container--box {\n left: 50%;\n transform: translateX(-50%);\n width: 0;\n margin-left: 354px;\n z-index: 997;\n}\n\n.container--stickyBuy {\n background: #fff;\n padding: 8px 0px;\n}\n\n.wrapper--stickyBuy {\n height: 0 !important;\n z-index: 999;\n}\n\n.container--stickyBuy :global(.vtex-button) {\n height: 48px;\n background: var(--serious-orange);\n border: none;\n}\n\n```" } ]
code_b2b-theme_6ea9ca34
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.store-components.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.container {\n max-width: 1440px;\n width: 100%;\n padding: 0px 32px;\n margin: 0px auto;\n}\n\n.logoLink {\n display: block;\n transform: none !important;\n}\n\n.logoImage {\n display: block;\n height: 28px;\n width: auto;\n}\n\n.searchBarContainer :global(.vtex-input-prefix__group) {\n height: 48px;\n}\n\n.imageElement--vtexLogo {\n max-width: 67px;\n object-fit: contain;\n margin-right: 16px;\n}\n\n.newsletter {\n max-width: 100%;\n margin: 0;\n height: 104px;\n display: flex;\n align-items: center;\n background: var(--b2b-header-blue-medium);\n}\n\n.newsletter .container {\n padding: 0px 32px;\n}\n\n.productImageTag--sellersPage--main {\n max-width: 168px;\n}\n\n.newsletter .form {\n display: flex;\n align-items: center;\n max-width: 100%;\n}\n\n.newsletter .form .label {\n font-size: 32px;\n line-height: 40px;\n font-weight: 500;\n font-family: \"Roboto\";\n margin-right: auto;\n color: #fff;\n}\n\n.newsletter .inputGroup {\n max-width: 680px;\n width: 100%;\n padding: 0;\n position: relative;\n}\n\n.newsletter :global(.vtex-input-prefix__group) {\n height: initial;\n border: none;\n}\n\n.newsletter :global(.vtex-styleguide-9-x-input) {\n height: 56px;\n background: #fff;\n font-size: 20px;\n line-height: 24px;\n font-family: Roboto;\n color: var(--black-medium);\n}\n\n.newsletter :global(.vtex-styleguide-9-x-input)::placeholder {\n color: var(--black-medium);\n font-size: 20px;\n line-height: 24px;\n font-family: Roboto;\n}\n\n.newsletter .buttonContainer {\n position: absolute;\n right: 24px;\n top: 8px;\n}\n\n.newsletter .buttonContainer :global(.vtex-button) {\n color: var(--fresh-blue);\n font-size: 16px;\n line-height: 24px;\n font-weight: bold;\n font-family: Roboto;\n outline: none;\n border: none;\n background: none;\n}\n\n.newsletter .buttonContainer :global(.vtex-button__label) {\n padding: 0;\n}\n\n.imageElement--bannerThird {\n margin-bottom: 24px;\n}\n\n.logoContainer {\n display: block;\n padding: 0;\n}\n\n.imageElement--quickviewTrigger {\n width: 20px;\n height: 14px;\n object-fit: contain;\n}\n\n.searchBarContainer {\n width: 100%;\n max-width: 856px;\n}\n\n.searchBarContainer :global(.vtex-styleguide-9-x-input) {\n max-width: 100%;\n width: 100%;\n}\n\n.searchBarContainer :global(.vtex-input__suffix) {\n border-radius: 0px;\n}\n\n.imageElement--paymentImage {\n width: 100%;\n object-fit: contain;\n max-height: 18px;\n}\n\n.imageElement--networkImage {\n display: block;\n}\n\n.imageElement--shoByImage {\n width: 80px;\n height: auto;\n object-fit: contain;\n max-height: 80px;\n max-width: 80px;\n margin-bottom: 16px;\n}\n\n.imageElement--imageCategorySlider {\n border: 1px solid #dee7ef;\n padding: 16px;\n border-radius: 50%;\n margin-bottom: 12px;\n}\n\n.imageElement--blogImage {\n display: block;\n margin-bottom: 16px;\n}\n\n.imageElement--benefitImage {\n margin: 0px auto 24px;\n width: 32px;\n height: 34px;\n object-fit: contain;\n}\n\n.userAddressContainer {\n height: 100%;\n background: none;\n padding: 0;\n margin-right: 60px;\n}\n\n.userAddressContainer .container {\n padding: 0;\n}\n\n@media (max-width: 64rem) {\n .imageElement--blogImage {\n width: 100%;\n }\n\n .container {\n padding: 0px 16px;\n }\n\n .imageElement--homeSlider {\n max-height: 384px !important;\n object-fit: cover;\n }\n\n .newsletter {\n height: 136px;\n }\n\n .newsletter .container {\n padding: 0;\n }\n\n .newsletter .form {\n flex-flow: column nowrap;\n }\n\n .newsletter .form .label {\n font-size: 20px;\n line-height: 28px;\n margin-bottom: 12px;\n width: 100%;\n text-align: center;\n }\n\n .newsletter .buttonContainer :global(.vtex-button) {\n font-size: 14px;\n }\n\n .newsletter :global(.vtex-styleguide-9-x-input)::placeholder,\n .newsletter :global(.vtex-styleguide-9-x-input) {\n font-size: 18px;\n line-height: 20px;\n }\n\n .imageElement--paymentImage {\n margin: 0px auto;\n }\n\n .searchBarInnerContainer--searchMobile :global(.vtex-input-prefix__group) {\n border: none;\n }\n\n .searchBarInnerContainer--searchMobile :global(.vtex-styleguide-9-x-input) {\n max-width: 100%;\n }\n\n .searchIcon--searchMobile {\n display: none;\n }\n\n .searchBarIcon--searchMobile:not(.searchBarIcon--searchMobile--clear) {\n background: url(\"assets/icons/searchMobile.svg\");\n width: 18px;\n height: 18px;\n display: block;\n background-repeat: no-repeat;\n background-size: contain;\n }\n\n .imageElement--singleBanner {\n width: 100%;\n object-fit: cover;\n }\n\n .logoLink {\n margin-right: 56px;\n display: flex !important;\n align-items: center;\n }\n\n .logoImage {\n display: block;\n width: 123px;\n height: 24px;\n }\n\n .suffixWrapper--searchMobile {\n align-items: center;\n }\n\n .searchBarContainer {\n padding: 0;\n }\n\n .imageElement--networkImage {\n display: block;\n }\n\n .resultsList--searchMobile {\n height: 100%;\n max-height: 100%;\n padding: 0px 16px;\n }\n\n .resultsItem--searchMobile {\n color: #717786;\n }\n\n .resultsItemName--searchMobile,\n .searchTerm--searchMobile {\n color: #000 !important;\n }\n\n .productImagesContainer--sellersPage {\n height: 106px !important;\n overflow: hidden;\n width: 106px !important;\n margin-right: 24px;\n }\n\n .productImageTag--sellersPage--main {\n max-height: 106px;\n object-fit: contain;\n }\n}\n\n/* Product Images */\n\n.productImagesContainer--desktop,\n.carouselContainer--desktop {\n width: 564px;\n}\n\n.carouselGaleryThumbs--desktop {\n max-width: 100px;\n}\n\n.productImagesThumb--desktop,\n.productImagesThumb--desktop :not(:global(.vtex-fake)) {\n border-radius: 4px;\n overflow: hidden;\n}\n\n.productImagesThumbActive--desktop .carouselThumbBorder--desktop {\n border: 1px solid #0067c7;\n}\n\n.carouselContainer--desktop .carouselGaleryCursor,\n.productImagesGallerySwiperContainer--desktop,\n.productImagesGallerySlide--desktop,\n.productImage--desktop,\n.productImageTag--desktop {\n height: 448px !important;\n width: 448px !important;\n}\n\n.carouselContainer--desktop .carouselGaleryCursor {\n margin-left: 100px;\n width: 464px !important;\n}\n\n.productImagesContainer--desktop {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n\n.productImagesContainer--desktop::after {\n display: block;\n color: #717786;\n content: \"Roll over image to zoom in\";\n padding-top: 20px;\n padding-left: 116px;\n font-size: 12px;\n line-height: 16px;\n text-align: center;\n}\n\n.productImageTag--desktop--zoom {\n display: none;\n}\n\n/* Product Brand */\n\n.productBrandContainer {\n font-size: 14px;\n line-height: 16px;\n color: #0067c7;\n}\n\n/* Product Name */\n\n.productNameContainer--product-page {\n color: var(--serious-black);\n font-size: 24px;\n font-weight: 500;\n line-height: 28px;\n}\n\n.productNameContainer--minicart {\n color: var(--black-dark);\n font-size: 14px;\n line-height: 18px;\n}\n\n/* Sku Selector */\n\n.skuSelectorContainer--desktop .skuSelectorSubcontainer {\n margin-bottom: 20px;\n}\n\n.skuSelectorContainer--desktop .skuSelectorNameContainer {\n margin: 0;\n}\n\n.skuSelectorContainer--desktop .skuSelectorName,\n.skuSelectorContainer--desktop .skuSelectorNameSeparator,\n.skuSelectorContainer--desktop .skuSelectorSelectorImageValue {\n font-size: 14px;\n line-height: 20px;\n font-weight: 500;\n color: #717786;\n}\n\n.skuSelectorContainer--desktop .skuSelectorSelectorImageValue {\n color: #000000;\n}\n\n.skuSelectorContainer--desktop .skuSelectorTextContainer {\n margin-bottom: 8px;\n}\n\n.skuSelectorContainer--desktop .skuSelectorOptionsList {\n margin: 0;\n}\n\n.skuSelectorContainer--desktop .skuSelectorItem.skuSelectorItemImage {\n height: 48px;\n width: 48px;\n}\n\n.skuSelectorContainer--desktop .skuSelectorItem {\n height: 40px;\n}\n\n/* Round SKU Selector */\n\n.skuSelectorContainer--color-round .frameAround {\n border: 1px solid #bdc9d6;\n bottom: 0;\n left: 0;\n right: 0;\n top: 0;\n}\n\n.skuSelectorContainer--color-round .skuSelectorItem--selected .frameAround {\n box-shadow: 0 0 0 4px #f3f9ff;\n border-color: #0067c7;\n}\n\n.skuSelectorContainer--color-round .skuSelectorInternalBox {\n border: none;\n}\n\n.skuSelectorContainer--color-round\n .skuSelectorSubcontainer--cor\n .skuSelectorOptionsList\n :not(:global(.vtex-fake)) {\n border-radius: 9999px;\n}\n\n.productImagesContainer--fake-summary {\n pointer-events: none !important;\n}\n\n.productImagesContainer--fake-summary :not(:global(.vtex-fake)) {\n display: block;\n float: left;\n overflow: hidden;\n width: 100%;\n height: 100%;\n}\n\n.productImagesContainer--fake-summary,\n.productImageTag--fake-summary {\n height: 96px !important;\n overflow: hidden;\n width: 96px !important;\n}\n\n.productImagesGallerySwiperContainer--fake-summary .swiper-pagination,\n.swiperCaret--fake-summary,\n.carouselGaleryThumbs--fake-summary {\n display: none !important;\n}\n\n.carouselContainer--fake-summary .carouselGaleryCursor {\n padding: 0;\n margin: 0;\n width: 100%;\n}\n\n.productNameContainer--fake-summary {\n font-size: 14px;\n line-height: 16px;\n}\n\n.productSKUAttributesContainer--inline {\n color: #717786;\n font-size: 14px;\n line-height: 16px;\n}\n\n.attributeLine--inline,\n.attributeName--inline {\n color: inherit;\n display: inline;\n font-weight: inherit;\n font-size: inherit;\n margin: 0;\n padding: 0;\n}\n\n.attributeName--inline::after {\n content: \" \";\n}\n\n.attributeLine--inline::after {\n content: \", \";\n}\n\n.attributeLine--inline:last-child::after {\n content: \"\";\n}\n\n/* Product Description */\n\n@media (min-width: 64rem) {\n .productDescriptionContainer--desktop {\n max-width: 300px;\n }\n}\n\n.productDescriptionText {\n font-size: 14px;\n line-height: 1.25;\n color: var(--black-medium);\n}\n\n.productDescriptionTitle {\n display: none;\n}\n\n.productDescriptionTitle--desktop {\n display: block;\n font-weight: 500;\n font-size: 24px;\n line-height: 32px;\n color: var(--black-dark);\n margin-bottom: 24px;\n}\n\n/* Product Images Gallery */\n\n.productImagesGallerySwiperContainer--gallery {\n margin: 0;\n padding: 0;\n}\n\n@media (min-width: 64rem) {\n .productImagesGallerySwiperContainer--gallery {\n height: 464px;\n width: 664px;\n }\n}\n\n.carouselGaleryThumbs--gallery {\n display: none;\n}\n\n.productImagesGallerySlide--gallery {\n margin: 0;\n margin-bottom: 16px;\n}\n\n@media (min-width: 64rem) {\n .productImagesGallerySlide--gallery {\n height: 224px;\n width: 50% !important;\n max-width: 324px;\n }\n}\n\n.productImagesGallerySwiperContainer--gallery :not(:global(.vtex-fake)) {\n flex-wrap: wrap;\n justify-content: space-between;\n transform: translate3d(0, 0px, 0px) !important; /* Disables swiping */\n}\n\n.productImageTag--gallery {\n border-radius: 4px;\n}\n\n/* Dots Around */\n\n.productImagesGallerySlide--dots-around {\n padding-bottom: 32px;\n}\n\n.productImagesContainer--dots-around .swiper-pagination {\n bottom: 0;\n}\n\n.productImagesContainer--dots-around .swiperBullet {\n background-color: var(--lines-dark);\n opacity: 1;\n}\n\n.productImagesContainer--dots-around .swiperBullet--active {\n background-color: var(--serious-blue-dark);\n}\n\n/* Shipping Simulator */\n\n.shippingContainer\n :not(:global(.vtex-address-form__postalCode)):not(:global(.vtex-input)):not(:global(.vtex-input-prefix__group)):not(:global(.vtex-address-form-4-x-input)):not(:global(.vtex-button)):not(:global(.vtex-button__label)) {\n display: none;\n}\n\n.shippingContainer {\n display: flex;\n}\n\n@media (min-width: 40rem) {\n .shippingContainer {\n width: 18rem;\n }\n}\n\n.shippingContainer :global(.vtex-address-form__postalCode),\n.shippingContainer :global(.vtex-button) {\n flex: 1 1 auto;\n}\n\n.shippingContainer :global(.vtex-address-form__postalCode) {\n width: 100%;\n}\n\n.shippingContainer :global(.vtex-input-prefix__group) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n border-right: none;\n border-width: 0.0625rem;\n height: 2.75rem;\n}\n\n.shippingContainer :global(.vtex-address-form-4-x-input) {\n color: var(--black-dark);\n}\n\n.shippingContainer :global(.vtex-button) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n border-left: none;\n color: var(--fresh-blue-dark);\n width: auto;\n}\n\n.shippingContainer :global(.vtex-button):focus {\n outline: none;\n}\n\n.shippingContainer :global(.vtex-button):disabled {\n color: var(--lines-light);\n}\n\n.shippingContainer :global(.vtex-input-prefix__group),\n.shippingContainer :global(.vtex-button) {\n border-width: 0.0625rem;\n border-color: var(--lines-light);\n background-color: #fff;\n}\n\n.shippingContainer :global(.vtex-button__label) {\n color: inherit;\n font-size: 0;\n}\n\n.shippingContainer :global(.vtex-button__label)::before {\n content: \"OK\";\n font-size: 0.875rem;\n}\n\n.shippingTable,\n.shippingTableBody,\n.shippingTableRow {\n border: none;\n}\n\n.shippingTable {\n margin: 0;\n margin-top: 1rem;\n padding: 0;\n}\n\n.shippingTableCell {\n padding: 16px;\n}\n\n.shippingTableCellDeliveryName {\n background-color: #f3f9ff;\n padding-top: 32px;\n padding-bottom: 32px;\n height: 92px;\n width: 0px;\n padding-left: 0;\n padding-right: 0;\n}\n\n.shippingTableCellDeliveryEstimate {\n border-left: none;\n}\n\n.shippingTableRow {\n background-color: #fff;\n border: 1px solid #dee7ef;\n border-radius: 0.25rem;\n display: flex;\n align-items: center;\n margin-bottom: 0.5rem;\n}\n\n.shippingTableRow:last-child {\n margin-bottom: 0;\n}\n\n.shippingTableLabel {\n white-space: pre;\n font-weight: 500;\n color: #000;\n position: relative;\n padding-left: 16px;\n}\n\n.shippingTableRadioBtn {\n display: none;\n margin-right: 36px;\n margin-left: 4px;\n top: 8px;\n position: relative;\n}\n\n.shippingTableCellDeliveryPrice {\n font-weight: 500;\n padding-left: 0;\n padding-right: 16px;\n text-align: right;\n width: 100%;\n}\n\n.shippingTableCellDeliveryEstimate,\n.shippingTableCellDeliveryPrice {\n white-space: pre;\n}\n\n.shippingTableCellDeliveryEstimate::before,\n.shippingTableCellDeliveryPrice::after {\n content: \"\\a\";\n display: block;\n}\n\n.shippingNoMessage {\n color: var(--black-medium);\n text-align: center;\n}\n\n```" } ]
code_b2b-theme_4cb6869c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.wish-list.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.wishlistIconContainer {\n position: absolute;\n width: 38px;\n height: 38px;\n display: block;\n border-radius: 50%;\n background: #f3f9fe;\n transition: all .3s ease;\n opacity: 0;\n text-align: center;\n}\n\n.wishlistIconContainer :global(.vtex-button):hover,\n.wishlistIconContainer :global(.vtex-button){\n outline: none;\n background: none;\n}\n\n.wishlistIconContainer :global(.vtex-button__label){\n padding: 0;\n}\n\n.wishlistIcon.outline {\n background: url(\"assets/icons/heartIcon.svg\");\n background-repeat: no-repeat;\n background-size: contain;\n width: 19px;\n height: 15px;\n}\n\n.wishlistIcon.fill {\n background: url(\"assets/icons/heartFilled.svg\");\n background-repeat: no-repeat;\n background-size: contain;\n width: 19px;\n height: 15px;\n}\n```" } ]
code_b2b-theme_04c210fb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.wordpress-integration.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.categoryBlockTitle,\n.categoryBlockLink {\n display: none;\n}\n\n.categoryBlockContainer,\n.categoryBlockFlex {\n margin: 0;\n padding: 0;\n}\n\n.categoryBlockFlex {\n margin-left: -1rem;\n margin-right: -1rem;\n}\n\n.categoryBlockFlexItem {\n margin: 0;\n padding-left: 1rem;\n padding-right: 1rem;\n width: 50%;\n}\n\n.categoryBlockFlexItem:first-child {\n width: 100%;\n}\n\n@media (min-width: 64em) {\n .categoryBlockFlexItem,\n .categoryBlockFlexItem:first-child {\n width: 25%;\n }\n}\n\n.categoryBlockFlexItem :global(.vtex-card) {\n box-shadow: none !important;\n}\n\n.teaserImage {\n border-radius: 0.25rem;\n height: auto;\n margin-bottom: 1rem;\n width: 100%;\n}\n\n.teaserTitle,\n.teaserTitleLink,\n.teaserBody {\n padding: 0;\n margin: 0;\n}\n\n.teaserTitle,\n.teaserTitleLink {\n color: #000;\n font-size: 1rem;\n line-height: 1.25;\n font-weight: 500;\n margin-bottom: 8px;\n text-decoration: none;\n}\n\n.teaserBody {\n font-size: 0.875rem;\n line-height: 1.2857142857;\n color: #717786;\n margin-bottom: 24px;\n}\n\n```" } ]
code_b2b-theme_19fa6f55
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.store-footer.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.footerLayout {\n background: var(--b2b-blue-darkest);\n padding-top: 40px;\n padding-bottom: 0px;\n}\n\n.footerLayout--relative {\n position: relative;\n}\n\n.footerLayout--z-999 {\n z-index: 999;\n}\n\n.footerLayout--z-998 {\n z-index: 998;\n}\n\n@media (max-width: 64rem) {\n .footerLayout {\n padding-top: 24px;\n padding-bottom: 32px;\n }\n}\n\n```" } ]
code_b2b-theme_3edc79dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.product-identifier.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.product-identifier--productReference {\n font-size: 12px;\n line-height: 16px;\n color: #717786;\n}\n\n```" } ]
code_b2b-theme_a81043f3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of b2b-theme/styles/css/vtex.locale-switcher.css from the b2b-theme VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.button {\n padding: 8px 48px 8px 16px;\n border: 1px solid rgba(255, 255, 255, 0.4);\n border-radius: 4px;\n height: 42px;\n position: relative;\n}\n\n.globeIcon {\n color: rgba(255, 255, 255, 0.4);\n margin-right: 8px;\n}\n\n.buttonText {\n color: #fff;\n}\n\n.button::after {\n content: url(\"assets/icons/chevronDownSwitcher.svg\");\n position: absolute;\n right: 16px;\n top: 45%;\n transform: translateY(-50%);\n}\n\n.container--locationDrawer {\n width: auto;\n display: flex;\n justify-content: start;\n margin: 0;\n}\n\n.buttonText--locationDrawer {\n color: #000;\n font-size: 16px;\n line-height: 32px;\n}\n\n.button--locationDrawer {\n padding: 0;\n border: none;\n}\n\n.button--locationDrawer::before {\n content: url(\"assets/icons/globe.svg\");\n width: 20px;\n height: 20px;\n margin-right: 16px;\n}\n\n.button--locationDrawer::after {\n content: none;\n}\n\n.globeIcon--locationDrawer {\n display: none;\n opacity: 0;\n}\n\n@media (max-width: 64rem) {\n .button {\n border: none;\n }\n}\n\n```" } ]