id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-on-localhost_42fac1a8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n interface ChildBlock<BlockProps> {\n props: BlockProps\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n export const useChildBlock: <BlockProps>({id}: {id: string}) => ChildBlock<BlockProps> | null\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: any\n export const TreePathContextConsumer: any\n export const useTreePath: any\n export const useRuntime: any\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const withSession: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const buildCacheLocator = (app: string, type: string, cacheId: string) => string\n\n interface RenderComponent<P = {}, S = {}> extends Component<P, S> {\n getCustomMessages?: (locale: string) => any\n schema: ComponentSchema\n getSchema?: (a: any, b: any?) => ComponentSchema\n uiSchema: UISchema\n }\n\n export interface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n }\n\n export interface Window extends Window {\n __RENDER_7_COMPONENTS__: ComponentsRegistry\n }\n\n let global: Window\n}\n\n```"
}
] |
code_store-on-localhost_87b8e9f6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.native-types.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.native-types' {\n import { Component } from 'react'\n import { InjectedIntl, WrappedComponentProps } from 'react-intl'\n\n interface FormatIOMessageParams {\n id: string\n intl: InjectedIntl\n }\n\n export const formatIOMessage: (params: FormatIOMessageParams) => string\n\n interface IOMessageProps extends WrappedComponentProps {\n id: string\n }\n\n export const IOMessage: Component<IOMessageProps>\n}\n\n```"
}
] |
code_store-on-localhost_397480ca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/menu.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n```"
}
] |
code_store-on-localhost_00497f3c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/vtex.store-icons.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-icons' {\n export const Icon\n} \n```"
}
] |
code_store-on-localhost_52591508
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n schema?: object\n getSchema?(props?: P): object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n schema?: object\n getSchema?(props: P): object\n }\n\n interface StorefrontElement extends ReactElement {\n schema?: object\n getSchema?(props: P): object\n }\n}\n```"
}
] |
code_store-on-localhost_99d1469a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/typings/graphql.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n```"
}
] |
code_store-on-localhost_78d12867
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/LevelContext.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { createContext } from 'react'\n\nconst LevelContext = createContext(0)\n\nexport default LevelContext\n\n```"
}
] |
code_store-on-localhost_4fd23731
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/MenuContext.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { createContext } from 'react'\n\nconst MenuContext = createContext<MenuContextValue>({\n experimentalOptimizeRendering: false,\n hasTitle: false,\n orientation: 'horizontal',\n textType: 't-body',\n})\n\ninterface MenuContextValue {\n hasTitle: boolean\n orientation: 'horizontal' | 'vertical'\n textType: string\n experimentalOptimizeRendering?: boolean\n}\n\nexport default MenuContext\n\n```"
}
] |
code_store-on-localhost_094c6d8b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/CustomItem.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { injectIntl, WrappedComponentProps } from 'react-intl'\nimport StyledLink, { StyledLinkProps } from './StyledLink'\nimport formatIOMessage from '../../NativeTypes/formatIOMessage'\n\nconst CustomItem: FunctionComponent<CustomItemProps & WrappedComponentProps> = props => {\n const { type, noFollow, tagTitle, text, href, intl, ...rest } = props\n\n return (\n <StyledLink\n {...rest}\n to={href}\n title={formatIOMessage({ id: tagTitle, intl })}\n {...(type === 'external' ? { target: '_blank', rel: 'noopener' } : {})}\n {...(noFollow ? { rel: 'nofollow noopener' } : {})}\n >\n {formatIOMessage({ id: text, intl })}\n </StyledLink>\n )\n}\n\nexport interface CustomItemProps extends CustomItemSchema, StyledLinkProps {}\n\nexport interface CustomItemSchema {\n type: 'internal' | 'external'\n href: string\n noFollow: boolean\n tagTitle: string\n text: string\n}\n\nexport default injectIntl(CustomItem)\n\n```"
}
] |
code_store-on-localhost_342973ab
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/Item.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport CategoryItem, {\n CategoryItemSchema,\n} from './CategoryItem'\nimport CustomItem, { CustomItemSchema } from './CustomItem'\nimport { StyledLinkProps } from './StyledLink'\n\n// TODO use this\n// type ItemComponent = (\n// props: CategoryItemProps | CustomItemProps\n// ) => React.ReactElement\n\nconst menuItemTypes = {\n category: CategoryItem,\n custom: CustomItem,\n}\n\nconst Item: FunctionComponent<ItemProps> = props => {\n const { type, itemProps, ...rest } = props\n\n // TODO: fix\n const Component = menuItemTypes[type] as any\n\n if (!Component) {\n return null\n }\n\n return <Component {...rest} {...itemProps} />\n}\n\ninterface ItemProps extends StyledLinkProps {\n type: 'category' | 'custom'\n accordion?: boolean\n itemProps: CategoryItemSchema | CustomItemSchema\n}\n\nexport default Item\n\n```"
}
] |
code_store-on-localhost_4e4344e5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/StyledLink.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport classNames from 'classnames'\nimport React, { FunctionComponent, useContext } from 'react'\nimport useCssHandles from '../../CssHandles/useCssHandles'\nimport { Link } from '../../../../../vtex.render-runtime'\nimport Icon from '../../StoreIcons/Icon'\n\nimport LevelContext from './LevelContext'\nimport MenuContext from './MenuContext'\n\nconst CSS_HANDLES = ['styledLink', 'styledLinkIcon', 'styledLinkContainer'] as const\n\nconst defaultTypography: Record<number, string> = {\n 1: 't-body',\n 2: 't-small',\n 3: 't-small',\n}\n\nconst StyledLink: FunctionComponent<StyledLinkProps> = props => {\n const level = useContext(LevelContext)\n const { orientation, hasTitle } = useContext(MenuContext)\n const handles = useCssHandles(CSS_HANDLES)\n\n const {\n typography = defaultTypography[level],\n accordion,\n highlight,\n isHovered,\n active,\n isTitle,\n disabled,\n to,\n children,\n iconId,\n iconProps,\n iconPosition,\n treePath,\n ...rest\n } = props\n\n const hasLink = to && to !== '#'\n\n const linkClassNames = classNames(handles.styledLink, 'no-underline pointer', {\n [typography]: true,\n 'c-emphasis': highlight,\n 'c-muted-1': !highlight && hasTitle && !isTitle,\n 'c-on-base': !highlight && !hasTitle,\n 'fw5 c-on-base': !highlight && isTitle,\n pointer: !disabled,\n })\n\n const iconTestId = `icon-${iconPosition}`\n const iconComponent = iconProps ?\n <span className={`${handles.styledLinkIcon} mh2`} data-testid={iconTestId}>\n <Icon \n id={iconProps.id} \n isActive={iconProps.isActive}\n size={iconProps.size}\n viewBox={iconProps.viewBox}\n activeClassName={iconProps.activeClassName}\n mutedClassName={iconProps.mutedClassName}\n />\n </span> : null \n\n const content = (\n <div className=\"flex justify-between nowrap\">\n {iconPosition === 'left' && iconComponent}\n {children}\n {iconPosition === 'right' && iconComponent}\n {accordion && <div className=\"ml3 c-muted-2\">{active ? '-' : '+'}</div>}\n </div>\n )\n\n return (\n <div\n className={classNames(handles.styledLinkContainer, 'mh6', {\n pv2: orientation === 'vertical',\n pv5: orientation === 'horizontal' && level === 1,\n })}\n >\n {disabled || !hasLink || accordion ? (\n <span className={linkClassNames}>{content}</span>\n ) : (\n <Link\n to={to}\n {...rest}\n className={linkClassNames}\n >\n {content}\n </Link>\n )}\n </div>\n )\n}\n\nexport interface StyledLinkProps extends LinkProps {\n highlight?: boolean\n isHovered?: boolean\n active?: boolean\n isTitle?: boolean\n typography?: string\n disabled?: boolean\n accordion?: boolean\n treePath?: string\n iconId?: string,\n iconProps?: IconProps\n iconPosition?: 'left' | 'right'\n}\n\nexport interface IconProps {\n id: string\n isActive?: boolean\n size?: number\n viewBox?: string\n activeClassName?: string\n mutedClassName?: string\n}\n\ninterface LinkProps {\n to?: any\n title?: string\n target?: string\n rel?: string\n}\n\nStyledLink.defaultProps = {\n iconPosition: 'left'\n}\n\nexport default StyledLink\n\n```"
}
] |
code_store-on-localhost_1cae5f33
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/CategoryItem.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { Query, QueryResult } from 'react-apollo'\nimport { loader } from 'graphql.macro'\n\nimport StyledLink, { StyledLinkProps } from './StyledLink'\n\nconst category = loader('../graphql/category.graphql')\n\nclass CategoryItem extends Component<CategoryItemProps, State> {\n public static getDerivedStateFromError() {\n return { hasError: true }\n }\n\n public state = { hasError: false }\n\n public componentDidCatch(error: any) {\n console.log({ error })\n }\n\n public render() {\n const { categoryId, text, ...rest } = this.props\n\n if (this.state.hasError) {\n return null\n }\n\n return (\n <Query query={category} variables={{ id: categoryId }}>\n {({ data, loading, error }: QueryResult) => {\n if (error) {\n throw new Error(\n `GraphQL error while rendering Menu rendered Category id ${categoryId}`\n )\n }\n\n if (loading) {\n // TODO: Add a ContentLoader here\n return null\n }\n\n const {\n category: { name, titleTag, href },\n } = data\n\n return (\n <StyledLink {...rest} title={titleTag} to={href}>\n {text ? text : name}\n </StyledLink>\n )\n }}\n </Query>\n )\n }\n}\n\nexport interface CategoryItemProps\n extends CategoryItemSchema,\n StyledLinkProps { }\n\nexport interface CategoryItemSchema {\n categoryId: number\n text?: string\n}\n\ninterface State {\n hasError: boolean\n}\n\nexport default CategoryItem\n\n```"
}
] |
code_store-on-localhost_5bc6b5ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/Collapsible.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useRef, useEffect, useContext, FunctionComponent, useMemo } from 'react'\n\nconst TRANSITION_DELAY = 250\n\nfunction isFunction(value: any): value is (...rest: any) => any {\n return typeof value === 'function'\n}\n\ninterface Props {\n open: boolean\n}\n\ninterface CollapsibleContextValue {\n updateHeight?: (height: number) => void\n}\n\nconst CollapsibleContext = React.createContext<CollapsibleContextValue>({})\n\nconst Collapsible: FunctionComponent<Props> = ({ children, open }) => {\n const { updateHeight: updateParentHeight } = useContext(CollapsibleContext)\n\n const [height, setHeight] = useState(0)\n\n const contextValue = useMemo(() => ({\n updateHeight: (heightDelta: number) => {\n setHeight(height + heightDelta)\n if (isFunction(updateParentHeight)) {\n updateParentHeight(heightDelta)\n }\n },\n }), [ updateParentHeight, height ])\n\n return (\n <CollapsibleContext.Provider value={contextValue}>\n <CollapsibleContainer open={open} height={height}>\n {children}\n </CollapsibleContainer>\n </CollapsibleContext.Provider>\n )\n}\n\ninterface ContainerProps {\n open: boolean\n height: number\n}\n\nconst CollapsibleContainer: FunctionComponent<ContainerProps> = ({ children, open, height }) => {\n const { updateHeight } = useContext(CollapsibleContext)\n\n const container = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n /** Calculates the content size on the next browser render tick,\n * because the content might not exist right at the time of\n * changing the open prop\n */\n requestAnimationFrame(() => {\n const element = container.current\n\n /** The second verification here prevents it from trying to close\n * the menu on initialization (because `open` inits as `false`)\n */\n if (!element || (!open && height === 0)) {\n return\n }\n\n const initialHeight = element.offsetHeight\n const initialMaxHeight = element.style.maxHeight\n\n element.style.height = 'auto'\n element.style.maxHeight = 'none'\n\n const childrenHeight = element.offsetHeight\n\n element.style.height = `${initialHeight}px`\n element.style.maxHeight = initialMaxHeight\n\n /** Runs `getBoundingClientRect` to trigger a layout event\n * in order to make the transition to the new height work.\n */\n element.getBoundingClientRect()\n\n if (isFunction(updateHeight)) {\n updateHeight(open ? childrenHeight : -childrenHeight)\n }\n })\n }, [open])\n\n return (\n <div\n className=\"overflow-hidden\"\n ref={container}\n style={{\n height,\n transition: `height ${TRANSITION_DELAY}ms ease-out`,\n }}\n >\n {children}\n </div>\n )\n}\n\nexport default Collapsible\n\n```"
}
] |
code_store-on-localhost_4afff4e2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/components/CategoryMenu.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { Query } from 'react-apollo'\nimport { loader } from 'graphql.macro'\n\nimport StyledLink from './StyledLink'\n\nconst categoryWithChildren = loader('../graphql/categoryWithChildren.graphql')\n\nconst CategoryLink: FunctionComponent<CategoryLinkProps> = ({\n href,\n titleTag,\n isTitle,\n name,\n}: CategoryLinkProps) => {\n return (\n <StyledLink title={titleTag} to={href} isTitle={isTitle}>\n {name}\n </StyledLink>\n )\n}\n\nconst CategoryMenu: FunctionComponent<CategoryMenuProps> = ({\n categoryId,\n}: CategoryMenuProps) => {\n return (\n <Query query={categoryWithChildren} variables={{ id: categoryId }}>\n {({ data, loading, error }: any) => {\n if (error || loading) {\n // TODO add loader and error message\n return null\n }\n\n const {\n category,\n category: { children },\n }: { category: Category } = data\n return (\n <>\n <CategoryLink {...category} isTitle/>\n {children && children.map((child: Category) => (\n <li key={child.id}>\n <CategoryLink {...child} />\n </li>\n ))}\n </>\n )\n }}\n </Query>\n )\n}\n\ninterface CategoryMenuProps {\n categoryId: number\n customText?: string\n}\n\ninterface Category {\n id: number\n titleTag: string\n href: string\n name: string\n children: Category[]\n}\n\ninterface CategoryLinkProps extends Category {\n isTitle?: boolean\n}\n\nexport default CategoryMenu\n\n```"
}
] |
code_store-on-localhost_5eed6419
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/__tests__/StyledLink.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { render } from '@vtex/test-tools/react'\nimport React from 'react'\n\nimport StyledLink from '../components/StyledLink'\n\n\ndescribe('Icon should appear at the left', () => {\n function renderComponent(iconPos: \"left\" | \"right\" | undefined) {\n const props = {\n active: false,\n children: \"Shop\",\n highlight: false,\n iconProps: {\n activeClassName: \"rebel-pink\",\n id: \"bnd-logo\",\n mutedClassName: \"c-action-primary\",\n size: 16,\n viewBox: \"0 0 16 16\",\n },\n iconPosition: iconPos,\n id: \"menu-item-shop\",\n params: undefined,\n query: undefined,\n title: \"Shop\",\n to: \"#\",\n treePath: \"store.home/$before_header.full/header-layout.desktop/header-row#3-desktop/vtex.menu@2.x:menu#websites/menu-item#shop\"\n }\n return render(<StyledLink {...props} />)\n }\n\n it('should be rendered', () => {\n expect(renderComponent('left')).toBeDefined()\n })\n\n it('should not have icon', () => {\n const props = {\n active: false,\n children: \"Shop\",\n highlight: false,\n iconToTheRight: false,\n id: \"menu-item-shop\",\n params: undefined,\n query: undefined,\n title: \"Shop\",\n to: \"#\",\n treePath: \"store.home/$before_header.full/header-layout.desktop/header-row#3-desktop/vtex.menu@2.x:menu#websites/menu-item#shop\"\n }\n\n const {queryByTestId} = render(<StyledLink {...props} />)\n expect(queryByTestId('icon-right')).toBeNull()\n expect(queryByTestId('icon-left')).toBeNull()\n })\n\n it('should have icon to the left', () => {\n const {getByTestId} = renderComponent('left')\n expect(getByTestId('icon-left'))\n })\n\n it('should have icon to the right', () => {\n const {getByTestId} = renderComponent('right')\n expect(getByTestId('icon-right'))\n })\n\n})\n```"
}
] |
code_store-on-localhost_a1a6a5ce
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/__tests__/Menu.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { render } from '@vtex/test-tools/react'\nimport React from 'react'\n\nimport Menu from '../Menu'\n\ndescribe('Menu Component', () => {\n function renderComponent() {\n return render(<Menu />)\n }\n\n it('should be rendered', () => {\n expect(renderComponent()).toBeDefined()\n })\n\n it('should match the snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should be editable through storefront', () => {\n expect(Menu.getSchema({})).toHaveProperty('title')\n })\n})\n\n```"
}
] |
code_store-on-localhost_9b9e3b74
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/__tests__/MenuLink.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { render } from '@vtex/test-tools/react'\nimport React from 'react'\n\nimport Menu from '../index'\n\ndescribe('MenuLink Component', () => {\n function renderComponent() {\n const props = {\n links: [\n {\n externalPage: 'externalPage',\n internalPage: 'internalPage',\n page: 'page',\n params: 'params',\n position: 'position',\n text: 'text',\n typeOfRoute: 'typeOfRoute',\n },\n ],\n }\n\n return render(<Menu {...props} />)\n }\n\n it('should be rendered', () => {\n expect(renderComponent()).toBeDefined()\n })\n\n it('should match the snapshot', () => {\n const { asFragment } = renderComponent()\n expect(asFragment()).toMatchSnapshot()\n })\n})\n\n```"
}
] |
code_store-on-localhost_5ebe6d78
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/graphql/categoryWithChildren.graphql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery categoryWithChildren($id: Int) {\n category(id: $id) {\n cacheId\n id\n href\n name\n titleTag\n children {\n id\n href\n name\n titleTag\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_c1d6e17c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/graphql/category.graphql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery category($id: Int) {\n category(id: $id) {\n cacheId\n id\n href\n name\n titleTag\n }\n}\n```"
}
] |
code_store-on-localhost_b1b46379
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Menu/hooks/useSubmenuImplementation.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useRuntime, useTreePath } from '../../../../../vtex.render-runtime'\n\n/** This is a throwaway function, while useChildBlock doesn't return\n * the \"implements\" block info, or which specialization of the block\n * is being used (i.e. whether its `submenu` or `submenu.accordion`)\n */\nconst useSubmenuImplementation = () => {\n const runtime = useRuntime()\n const treePathContext = useTreePath()\n\n const { treePath } = treePathContext\n const { extensions } = runtime\n\n if (!extensions || !treePath) {\n return null\n }\n\n const submenuTreePath = `${treePath}/submenu`\n\n const extension = extensions[submenuTreePath]\n\n if (!extension) {\n return null\n }\n\n const { component } = extension\n\n if (typeof component === 'string' && component.indexOf('SubmenuAccordion') > -1) {\n return 'submenu.accordion'\n }\n return 'submenu'\n}\n\nexport default useSubmenuImplementation\n\n```"
}
] |
code_store-on-localhost_e1c14683
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/typings/splunk-events.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'splunk-events' {\n interface Constructable<T> {\n new (): T\n }\n const Splunk: Constructable<any>\n export default Splunk\n}\n\n```"
}
] |
code_store-on-localhost_74b6966c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/typings/graphql.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_store-on-localhost_bbe5c0c0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/utils/logger.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport SplunkEvents from 'splunk-events'\n\nconst splunkEvents = new SplunkEvents()\n\nsplunkEvents.config({\n endpoint: 'https://splunk-heavyforwarder-public.vtex.com:8088',\n token: '50fe94b0-30b6-442a-9cb1-a476c97ba917',\n})\n\ninterface Runtime {\n workspace: string\n account: string\n}\n\ninterface LogConfig {\n level: 'Critical' | 'Important' | 'Debug'\n type: 'Error' | 'Warn' | 'Info'\n workflowType: string\n workflowInstance: string\n event: any\n}\n\ndeclare let window: {\n __RUNTIME__: Runtime\n}\n\nconst isMasterWorkspace = () => window?.__RUNTIME__?.workspace === 'master'\nconst getAccount = () => window?.__RUNTIME__?.account\n\nexport const logSplunk = (config: LogConfig) => {\n const { level, type, workflowType, workflowInstance, event } = config\n\n if (isMasterWorkspace()) {\n splunkEvents.logEvent(\n level,\n type,\n workflowType,\n workflowInstance,\n event,\n getAccount()\n )\n }\n}\n\n```"
}
] |
code_store-on-localhost_659ecefa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/utils/dummyOrderForm.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype Item = any\ntype OrderForm = any\n\nconst dummyItem = (id: string): Item => ({\n additionalInfo: {\n brandName: '',\n },\n id,\n detailUrl: '',\n imageUrls: null,\n listPrice: 0,\n measurementUnit: '',\n name: '',\n price: 0,\n productId: '',\n quantity: 0,\n sellingPrice: 0,\n skuName: '',\n skuSpecifications: [],\n uniqueId: id,\n availability: 'available',\n})\n\nexport const emptyOrderForm: OrderForm = {\n canEditData: false,\n id: '',\n items: [],\n shipping: {\n countries: [],\n deliveryOptions: [],\n selectedAddress: {\n addressId: '',\n addressType: null,\n city: '',\n complement: '',\n country: '',\n neighborhood: '',\n number: '',\n postalCode: '',\n receiverName: '',\n reference: '',\n state: '',\n street: '',\n geoCoordinates: [],\n },\n },\n marketingData: {\n coupon: '',\n },\n paymentData: {\n installmentOptions: [],\n paymentSystems: [],\n },\n messages: {\n couponMessages: [],\n generalMessages: [],\n },\n totalizers: [{ id: '', value: 0, name: '' }],\n value: 0,\n}\n\nexport const dummyOrderForm: OrderForm = {\n ...emptyOrderForm,\n items: [dummyItem('id1'), dummyItem('id2')],\n}\n\n```"
}
] |
code_store-on-localhost_46bd5885
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/__tests__/OrderForm.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { fireEvent, render, wait } from '@vtex/test-tools/react'\nimport { MockedProvider } from '@apollo/react-testing'\nimport { Item } from 'vtex.checkout-graphql'\n\nimport { mockOrderForm } from '../__mocks__/mockOrderForm'\nimport { Queries } from '../__mocks__/vtex.checkout-resources'\nimport { OrderFormProvider, useOrderForm } from '../OrderForm'\n\nconst { orderForm: OrderForm } = Queries\n\nconst mockQuery = {\n request: {\n query: OrderForm,\n },\n result: {\n data: {\n orderForm: mockOrderForm,\n },\n },\n}\n\ndescribe('OrderForm', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n it('should throw when useOrderForm is called outside a OrderFormProvider', () => {\n const oldConsoleError = console.error\n console.error = () => {}\n\n const Component: FunctionComponent = () => {\n useOrderForm()\n return <div>foo</div>\n }\n\n expect(() =>\n render(<Component />, {\n graphql: { mocks: [mockQuery] },\n MockedProvider,\n })\n ).toThrow('useOrderForm must be used within a OrderFormProvider')\n\n console.error = oldConsoleError\n })\n\n it('should set loading=true when fetching the order form', async () => {\n const Component: FunctionComponent = () => {\n const { loading } = useOrderForm()\n return <div>{loading ? 'Loading' : 'Not loading'}</div>\n }\n\n const { getByText } = render(\n <OrderFormProvider>\n <Component />\n </OrderFormProvider>,\n { graphql: { mocks: [mockQuery] }, MockedProvider }\n )\n\n expect(getByText('Loading')).toBeTruthy()\n await wait(() => jest.runAllTimers())\n })\n\n it('should correctly load the order form', async () => {\n const Component: FunctionComponent = () => {\n const { loading, orderForm } = useOrderForm()\n if (loading) {\n return <div>Loading</div>\n }\n return (\n <div>\n {orderForm &&\n orderForm.items.map((item: Item) => (\n <div key={item.id}>{item.name}</div>\n ))}\n </div>\n )\n }\n\n const { getByText } = render(\n <OrderFormProvider>\n <Component />\n </OrderFormProvider>,\n { graphql: { mocks: [mockQuery] }, MockedProvider }\n )\n\n await wait(() => jest.runAllTimers())\n expect(getByText(mockOrderForm.items[0].name)).toBeTruthy()\n expect(getByText(mockOrderForm.items[1].name)).toBeTruthy()\n expect(getByText(mockOrderForm.items[2].name)).toBeTruthy()\n })\n\n it('should correctly update the order form', async () => {\n const Component: FunctionComponent = () => {\n const { loading, orderForm, setOrderForm } = useOrderForm()\n if (loading || !orderForm) {\n return <div>Loading</div>\n }\n const handleClick = () => {\n const newItem = orderForm && {\n ...orderForm.items[1],\n name: 'Mirai zura!',\n }\n setOrderForm({ items: [newItem] })\n }\n return (\n <div>\n <div>\n {orderForm &&\n orderForm.items.map((item: Item) => (\n <div key={item.id}>{item.name}</div>\n ))}\n </div>\n <button onClick={handleClick}>update</button>\n </div>\n )\n }\n\n const { getByText } = render(\n <OrderFormProvider>\n <Component />\n </OrderFormProvider>,\n { graphql: { mocks: [mockQuery] }, MockedProvider }\n )\n\n await wait(() => {\n jest.runAllTimers()\n const button = getByText('update')\n fireEvent.click(button)\n })\n expect(getByText('Mirai zura!')).toBeTruthy()\n })\n})\n\n```"
}
] |
code_store-on-localhost_b35b4973
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/__tests__/OrderQueue.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useEffect } from 'react'\nimport { act, fireEvent, render } from '@vtex/test-tools/react'\n\nimport { QueueStatus } from '../constants'\nimport {\n OrderQueueProvider,\n useOrderQueue,\n useQueueStatus,\n} from '../OrderQueue'\n\nconst createScheduledTask = (task: () => any, time: number) => () =>\n new Promise(resolve => {\n setTimeout(() => resolve(task()), time)\n })\n\ndescribe('OrderQueue', () => {\n it('should throw when useOrderQueue is called outside a OrderQueueProvider', () => {\n const oldConsoleError = console.error\n console.error = () => {}\n\n const Component: FunctionComponent = () => {\n useOrderQueue()\n return <div>foo</div>\n }\n\n expect(() => render(<Component />)).toThrow(\n 'useOrderQueue must be used within a OrderQueueProvider'\n )\n\n console.error = oldConsoleError\n })\n\n it('should run tasks in order', async () => {\n const results: string[] = []\n const tasks: PromiseLike<any>[] = []\n\n const InnerComponent: FunctionComponent = () => {\n const { enqueue } = useOrderQueue()\n useEffect(() => {\n tasks.push(enqueue(createScheduledTask(() => results.push('1'), 10)))\n tasks.push(enqueue(createScheduledTask(() => results.push('2'), 5)))\n tasks.push(enqueue(createScheduledTask(() => results.push('3'), 5)))\n }, [enqueue])\n return <div>foo</div>\n }\n\n const OuterComponent: FunctionComponent = () => (\n <OrderQueueProvider>\n <InnerComponent />\n </OrderQueueProvider>\n )\n\n render(<OuterComponent />)\n\n await Promise.all(tasks)\n expect(results).toEqual(['1', '2', '3'])\n })\n\n it('should keep the ref returned by useQueueStatus updated', async () => {\n let queueStatusRef: any = null\n let task = null\n\n const Component: FunctionComponent = () => {\n const { enqueue, listen } = useOrderQueue()\n queueStatusRef = useQueueStatus(listen)\n\n const handleClick = () => {\n task = enqueue(createScheduledTask(() => {}, 10))\n }\n\n return <button onClick={handleClick}>enqueue</button>\n }\n\n const { getByText } = render(\n <OrderQueueProvider>\n <Component />\n </OrderQueueProvider>\n )\n\n expect(queueStatusRef).toBeDefined()\n expect(queueStatusRef.current).toEqual(QueueStatus.FULFILLED)\n\n const button = getByText('enqueue')\n act(() => {\n fireEvent.click(button)\n })\n expect(queueStatusRef.current).toEqual(QueueStatus.PENDING)\n\n await task\n expect(queueStatusRef.current).toEqual(QueueStatus.FULFILLED)\n })\n})\n\n```"
}
] |
code_store-on-localhost_3875f660
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/modules/SequentialTaskQueue.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// Adapted from https://github.com/BalassaMarton/sequential-task-queue/blob/master/src/sequential-task-queue.ts\n\n/**\n * Represents an object that schedules a function for asynchronous execution.\n * The default implementation used by {@link SequentialTaskQueue} calls {@link setImmediate} when available,\n * and {@link setTimeout} otherwise.\n * @see {@link SequentialTaskQueue.defaultScheduler}\n * @see {@link TaskQueueOptions.scheduler}\n */\nexport interface Scheduler {\n /**\n * Schedules a callback for asynchronous execution.\n */\n schedule(callback: Function): void\n}\n\n/**\n * Object used for passing configuration options to the {@link SequentialTaskQueue} constructor.\n */\nexport interface SequentialTaskQueueOptions {\n /**\n * Assigns a name to the task queue for diagnostic purposes. The name does not need to be unique.\n */\n name?: string\n /**\n * Default timeout (in milliseconds) for tasks pushed to the queue. Default is 0 (no timeout).\n * */\n timeout?: number\n /**\n * Scheduler used by the queue. Defaults to {@link SequentialTaskQueue.defaultScheduler}.\n */\n scheduler?: Scheduler\n}\n\n/**\n * Options object for individual tasks.\n */\nexport interface TaskOptions {\n /**\n * Timeout for the task, in milliseconds.\n * */\n timeout?: number\n\n /**\n * Arguments to pass to the task. Useful for minimalising the number of Function objects and closures created\n * when pushing the same task multiple times, with different arguments.\n *\n * @example\n * // The following code creates a single Function object and no closures:\n * for (let i = 0; i < 100; i++)\n * queue.push(process, {args: [i]});\n * function process(n) {\n * console.log(n);\n * }\n */\n args?: any\n}\n\n/**\n * Provides the API for querying and invoking task cancellation.\n */\nexport interface CancellationToken {\n /**\n * When `true`, indicates that the task has been cancelled.\n */\n cancelled?: boolean\n /**\n * An arbitrary object representing the reason of the cancellation. Can be a member of the {@link cancellationTokenReasons} object or an `Error`, etc.\n */\n reason?: any\n /**\n * Cancels the task for which the cancellation token was created.\n * @param reason - The reason of the cancellation, see {@link CancellationToken.reason}\n */\n cancel?: (reason?: any) => void\n}\n\n/**\n * Standard cancellation reasons. {@link SequentialTaskQueue} sets {@link CancellationToken.reason}\n * to one of these values when cancelling a task for a reason other than the user code calling\n * {@link CancellationToken.cancel}.\n */\nexport const cancellationTokenReasons = {\n /** Used when the task was cancelled in response to a call to {@link SequentialTaskQueue.cancel} */\n cancel: Object.create(null),\n /** Used when the task was cancelled after its timeout has passed */\n timeout: Object.create(null),\n}\n\n/**\n * Standard event names used by {@link SequentialTaskQueue}\n */\nexport const sequentialTaskQueueEvents = {\n drained: 'drained',\n error: 'error',\n timeout: 'timeout',\n}\n\n/**\n * Promise interface with the ability to cancel.\n */\nexport interface CancellablePromiseLike<T> extends PromiseLike<T> {\n /**\n * Cancels (and consequently, rejects) the task associated with the Promise.\n * @param reason - Reason of the cancellation. This value will be passed when rejecting this Promise.\n */\n cancel(reason?: any): void\n}\n\nfunction isPromise(obj: any): obj is PromiseLike<any> {\n return obj && typeof obj.then === 'function'\n}\n\nfunction noop() {}\n\n/**\n * FIFO task queue to run tasks in predictable order, without concurrency.\n */\nexport class SequentialTaskQueue {\n static defaultScheduler: Scheduler = {\n schedule: callback => setTimeout(callback as any, 0),\n }\n\n private queue: TaskEntry[] = []\n private _isClosed = false\n private waiters: Function[] = []\n private defaultTimeout?: number\n private currentTask?: TaskEntry\n private scheduler: Scheduler\n private events?: { [key: string]: Function[] }\n\n name: string\n\n /** Indicates if the queue has been closed. Calling {@link SequentialTaskQueue.push} on a closed queue will result in an exception. */\n get isClosed() {\n return this._isClosed\n }\n\n /**\n * Creates a new instance of {@link SequentialTaskQueue}\n * @param options - Configuration options for the task queue.\n */\n constructor(options?: SequentialTaskQueueOptions) {\n if (!options) options = {}\n this.defaultTimeout = options.timeout\n this.name = options.name || 'SequentialTaskQueue'\n this.scheduler = options.scheduler || SequentialTaskQueue.defaultScheduler\n }\n\n /**\n * Adds a new task to the queue.\n * @param {Function} task - The function to call when the task is run\n * @param {TaskOptions} options - An object containing arguments and options for the task.\n * @returns {CancellablePromiseLike<any>} A promise that can be used to await or cancel the task.\n */\n push(task: Function, options?: TaskOptions): CancellablePromiseLike<any> {\n if (this._isClosed)\n throw new Error(`${this.name} has been previously closed`)\n const taskEntry: TaskEntry = {\n callback: task,\n args:\n options && options.args\n ? Array.isArray(options.args)\n ? options.args.slice()\n : [options.args]\n : [],\n timeout:\n options && options.timeout !== undefined\n ? options.timeout\n : this.defaultTimeout,\n cancellationToken: {\n cancel: (reason?) => this.cancelTask(taskEntry, reason),\n },\n resolve: undefined,\n reject: undefined,\n }\n taskEntry.args.push(taskEntry.cancellationToken)\n this.queue.push(taskEntry)\n this.scheduler.schedule(() => this.next())\n const result = (new Promise((resolve, reject) => {\n taskEntry.resolve = resolve\n taskEntry.reject = reject\n }) as any) as CancellablePromiseLike<any>\n result.cancel = (reason?: any) =>\n taskEntry.cancellationToken.cancel!(reason)\n return result\n }\n\n /**\n * Cancels the currently running task (if any), and clears the queue.\n * @returns {Promise} A Promise that is fulfilled when the queue is empty and the current task has been cancelled.\n */\n cancel(): PromiseLike<any> {\n if (this.currentTask)\n this.cancelTask(this.currentTask, cancellationTokenReasons.cancel)\n const queue = this.queue.splice(0)\n // Cancel all and emit a drained event if there were tasks waiting in the queue\n if (queue.length) {\n queue.forEach(task =>\n this.cancelTask(task, cancellationTokenReasons.cancel)\n )\n this.emit(sequentialTaskQueueEvents.drained)\n }\n return this.wait()\n }\n\n /**\n * Closes the queue, preventing new tasks to be added.\n * Any calls to {@link SequentialTaskQueue.push} after closing the queue will result in an exception.\n * @param {boolean} cancel - Indicates that the queue should also be cancelled.\n * @returns {Promise} A Promise that is fulfilled when the queue has finished executing remaining tasks.\n */\n close(cancel?: boolean): PromiseLike<any> {\n if (!this._isClosed) {\n this._isClosed = true\n if (cancel) return this.cancel()\n }\n return this.wait()\n }\n\n /**\n * Returns a promise that is fulfilled when the queue is empty.\n * @returns {Promise}\n */\n wait(): PromiseLike<any> {\n if (!this.currentTask && this.queue.length === 0) return Promise.resolve()\n return new Promise(resolve => {\n this.waiters.push(resolve)\n })\n }\n\n /**\n * Adds an event handler for a named event.\n * @param {string} evt - Event name. See the readme for a list of valid events.\n * @param {Function} handler - Event handler. When invoking the handler, the queue will set itself as the `this` argument of the call.\n */\n on(evt: string, handler: Function) {\n this.events = this.events || {}\n ;(this.events[evt] || (this.events[evt] = [])).push(handler)\n }\n\n /**\n * Adds a single-shot event handler for a named event.\n * @param {string} evt - Event name. See the readme for a list of valid events.\n * @param {Function} handler - Event handler. When invoking the handler, the queue will set itself as the `this` argument of the call.\n */\n once(evt: string, handler: Function) {\n const cb = (...args: any[]) => {\n this.removeListener(evt, cb)\n handler.apply(this, args)\n }\n this.on(evt, cb)\n }\n\n /**\n * Removes an event handler.\n * @param {string} evt - Event name\n * @param {Function} handler - Event handler to be removed\n */\n removeListener(evt: string, handler: Function) {\n if (this.events) {\n const list = this.events[evt]\n if (list) {\n let i = 0\n while (i < list.length) {\n if (list[i] === handler) list.splice(i, 1)\n else i++\n }\n }\n }\n }\n\n /** @see {@link SequentialTaskQueue.removeListener} */\n off(evt: string, handler: Function) {\n return this.removeListener(evt, handler)\n }\n\n protected emit(evt: string, ...args: any[]) {\n if (this.events && this.events[evt])\n try {\n this.events[evt].forEach(fn => fn.apply(this, args))\n } catch (e) {\n console.error(`${this.name}: Exception in '${evt}' event handler`, e)\n }\n }\n\n protected next() {\n // Try running the next task, if not currently running one\n if (!this.currentTask) {\n let task = this.queue.shift()\n // skip cancelled tasks\n while (task && task.cancellationToken.cancelled) task = this.queue.shift()\n if (task) {\n try {\n this.currentTask = task\n if (task.timeout) {\n task.timeoutHandle = setTimeout(() => {\n this.emit(sequentialTaskQueueEvents.timeout)\n this.cancelTask(task!, cancellationTokenReasons.timeout)\n }, task.timeout)\n }\n const res = task.callback.apply(undefined, task.args)\n if (res && isPromise(res)) {\n res.then(\n result => {\n task!.result = result\n this.doneTask(task!)\n },\n err => {\n this.doneTask(task!, err)\n }\n )\n } else {\n task.result = res\n this.doneTask(task)\n }\n } catch (e) {\n this.doneTask(task, e)\n }\n } else {\n // queue is empty, call waiters\n this.callWaiters()\n }\n }\n }\n\n private cancelTask(task: TaskEntry, reason?: any) {\n task.cancellationToken.cancelled = true\n task.cancellationToken.reason = reason\n this.doneTask(task)\n }\n\n private doneTask(task: TaskEntry, error?: any) {\n if (task.timeoutHandle) clearTimeout(task.timeoutHandle)\n task.cancellationToken.cancel = noop\n if (error) {\n this.emit(sequentialTaskQueueEvents.error, error)\n task.reject!.call(undefined, error)\n } else if (task.cancellationToken.cancelled)\n task.reject!.call(undefined, task.cancellationToken.reason)\n else task.resolve!.call(undefined, task.result)\n\n if (this.currentTask === task) {\n this.currentTask = undefined\n if (!this.queue.length) {\n this.emit(sequentialTaskQueueEvents.drained)\n this.callWaiters()\n } else this.scheduler.schedule(() => this.next())\n }\n }\n\n private callWaiters() {\n const waiters = this.waiters.splice(0)\n waiters.forEach(waiter => waiter())\n }\n}\n\ninterface TaskEntry {\n args: any[]\n callback: Function\n timeout?: number\n timeoutHandle?: any\n cancellationToken: CancellationToken\n result?: any\n resolve?: (value: any | PromiseLike<any>) => void\n reject?: (reason?: any) => void\n}\n\nSequentialTaskQueue.defaultScheduler = {\n schedule:\n typeof setImmediate === 'function'\n ? callback => setImmediate(callback as (...args: any[]) => void)\n : callback => setTimeout(callback as (...args: any[]) => void, 0),\n}\n\n```"
}
] |
code_store-on-localhost_700a14b5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/modules/TaskQueue.test.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { TaskQueue, TASK_CANCELLED_CODE } from './TaskQueue'\nimport { QueueStatus } from '../constants'\n\nconst createScheduledTask = (task: () => any, time: number) => () =>\n new Promise(resolve => {\n setTimeout(() => resolve(task()), time)\n })\n\ndescribe('TaskQueue', () => {\n it('should execute a task', async () => {\n const queue = new TaskQueue()\n const result = await queue.enqueue(createScheduledTask(() => 42, 10))\n\n expect(result).toEqual(42)\n })\n\n it('should execute tasks in order', async () => {\n const queue = new TaskQueue()\n const results: string[] = []\n\n await Promise.all([\n queue.enqueue(createScheduledTask(() => results.push('1'), 20)),\n queue.enqueue(createScheduledTask(() => results.push('2'), 10)),\n queue.enqueue(async () => results.push('3')),\n ])\n\n expect(results).toEqual(['1', '2', '3'])\n })\n\n it('should not execute a task if a newer one with same id was enqueued', async () => {\n const queue = new TaskQueue()\n const results: string[] = []\n\n const task1 = queue.enqueue(\n createScheduledTask(() => results.push('1'), 20),\n 'foo'\n )\n const task2 = queue.enqueue(\n createScheduledTask(() => results.push('2'), 5),\n 'bar'\n )\n const task3 = queue.enqueue(\n createScheduledTask(() => results.push('3'), 5),\n 'baz'\n )\n const task4 = queue.enqueue(\n createScheduledTask(() => results.push('4'), 5),\n 'bar'\n )\n\n expect(task2).rejects.toEqual({\n code: TASK_CANCELLED_CODE,\n })\n\n await Promise.all([task1, task3, task4])\n\n expect(results).toEqual(['1', '3', '4'])\n })\n\n it('should not cancel a running task if a newer one with same id is pushed to the queue', async () => {\n const queue = new TaskQueue()\n const tasks: PromiseLike<any>[] = []\n\n const innerTask = createScheduledTask(() => 'bar', 5)\n\n const outerTask = async () => {\n tasks.push(queue.enqueue(innerTask, 'someId'))\n await createScheduledTask(() => {}, 10)\n return 'foo'\n }\n\n tasks.push(queue.enqueue(outerTask, 'someId'))\n\n await expect(tasks[0]).resolves.toEqual('foo')\n await expect(tasks[1]).resolves.toEqual('bar')\n })\n\n it('should emit a Fulfilled event only when the queue becomes empty', async () => {\n const queue = new TaskQueue()\n const mockFulfilledCb = jest.fn()\n queue.listen(QueueStatus.FULFILLED, mockFulfilledCb)\n\n const task1 = queue.enqueue(createScheduledTask(() => {}, 5))\n const task2 = queue.enqueue(createScheduledTask(() => {}, 5))\n const task3 = queue.enqueue(createScheduledTask(() => {}, 5))\n\n expect(mockFulfilledCb).toHaveBeenCalledTimes(0)\n await task1\n expect(mockFulfilledCb).toHaveBeenCalledTimes(0)\n await task2\n expect(mockFulfilledCb).toHaveBeenCalledTimes(0)\n await task3\n expect(mockFulfilledCb).toHaveBeenCalledTimes(1)\n })\n\n it('should emit a Pending event only when the queue is free and receives a task', async () => {\n const queue = new TaskQueue()\n const mockPendingCb = jest.fn()\n queue.listen(QueueStatus.PENDING, mockPendingCb)\n\n expect(mockPendingCb).toHaveBeenCalledTimes(0)\n const task1 = queue.enqueue(createScheduledTask(() => {}, 5))\n expect(mockPendingCb).toHaveBeenCalledTimes(1)\n const task2 = queue.enqueue(createScheduledTask(() => {}, 5))\n const task3 = queue.enqueue(createScheduledTask(() => {}, 5))\n expect(mockPendingCb).toHaveBeenCalledTimes(1)\n\n await Promise.all([task1, task2, task3])\n\n expect(mockPendingCb).toHaveBeenCalledTimes(1)\n queue.enqueue(createScheduledTask(() => {}, 5))\n expect(mockPendingCb).toHaveBeenCalledTimes(2)\n queue.enqueue(createScheduledTask(() => {}, 5))\n expect(mockPendingCb).toHaveBeenCalledTimes(2)\n })\n\n it('should not call listener callback after unlisten is called', async () => {\n const queue = new TaskQueue()\n const mockPendingCb = jest.fn()\n const unlisten = queue.listen(QueueStatus.PENDING, mockPendingCb)\n\n const task = queue.enqueue(async () => {})\n expect(mockPendingCb).toHaveBeenCalledTimes(1)\n await task\n\n unlisten()\n queue.enqueue(async () => {})\n expect(mockPendingCb).toHaveBeenCalledTimes(1)\n })\n\n it('should remove a single listener callback when unlisten is called', async () => {\n const queue = new TaskQueue()\n const mockPendingCb = jest.fn()\n queue.listen(QueueStatus.PENDING, mockPendingCb)\n const unlisten = queue.listen(QueueStatus.PENDING, mockPendingCb)\n queue.listen(QueueStatus.PENDING, mockPendingCb)\n\n const task = queue.enqueue(async () => {})\n expect(mockPendingCb).toHaveBeenCalledTimes(3)\n await task\n\n unlisten()\n queue.enqueue(async () => {})\n expect(mockPendingCb).toHaveBeenCalledTimes(5)\n })\n\n it('should return correct values when isWaiting is called', async () => {\n const queue = new TaskQueue()\n queue.enqueue(createScheduledTask(() => {}, 20))\n const secondTaskStarts = new Promise((resolve: any) =>\n queue.enqueue(async () => {\n resolve()\n await createScheduledTask(() => {}, 5)\n }, 'TaskID')\n )\n\n expect(queue.isWaiting('TaskID')).toEqual(true)\n await secondTaskStarts\n expect(queue.isWaiting('TaskID')).toEqual(false)\n })\n})\n\n```"
}
] |
code_store-on-localhost_f4bdd30e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderManager/modules/TaskQueue.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n CancellablePromiseLike,\n SequentialTaskQueue,\n} from './SequentialTaskQueue'\nimport { QueueStatus } from '../constants'\n\nexport const TASK_CANCELLED_CODE = 'TASK_CANCELLED'\n\ninterface EnqueuedTask {\n task: () => Promise<any>\n promise: CancellablePromiseLike<any>\n}\n\nexport class TaskQueue {\n private queue: SequentialTaskQueue\n private taskIdMap: Record<string, EnqueuedTask>\n private listeners: Record<QueueStatus, (() => any)[]>\n private isEmpty: boolean\n\n public constructor() {\n this.queue = new SequentialTaskQueue()\n this.taskIdMap = {}\n this.listeners = {} as any\n this.isEmpty = true\n\n this.queue.on('drained', () => {\n this.isEmpty = true\n this.emit(QueueStatus.FULFILLED)\n })\n }\n\n public isWaiting(id: string) {\n return !!this.taskIdMap[id]\n }\n\n public enqueue(task: () => Promise<any>, id?: string) {\n if (this.isEmpty) {\n this.isEmpty = false\n this.emit(QueueStatus.PENDING)\n }\n\n if (id && this.taskIdMap[id]) {\n this.taskIdMap[id].promise.cancel()\n }\n\n const wrappedTask = () => {\n if (id && this.taskIdMap[id]) {\n delete this.taskIdMap[id]\n }\n return task()\n }\n\n const promise = this.queue.push(wrappedTask)\n const cancelPromise = promise.cancel\n promise.cancel = () =>\n cancelPromise({\n code: TASK_CANCELLED_CODE,\n })\n\n if (id) {\n this.taskIdMap[id] = {\n task,\n promise,\n }\n }\n\n return promise\n }\n\n public listen(event: QueueStatus, cb: () => any) {\n if (!this.listeners[event]) {\n this.listeners[event] = []\n }\n\n this.listeners[event].push(cb)\n\n const unlisten = () => {\n const index = this.listeners[event].indexOf(cb)\n if (index !== -1) {\n this.listeners[event].splice(index, 1)\n }\n }\n\n return unlisten\n }\n\n private emit(event: QueueStatus) {\n if (this.listeners[event]) {\n this.listeners[event].forEach(cb => cb())\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_13e632fe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreImage/typings/vtex.device-detector.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.device-detector' {\n export function useDevice(): {\n device: 'desktop' | 'tablet' | 'phone'\n isMobile: boolean\n }\n}\n\n```"
}
] |
code_store-on-localhost_aa1ddcd0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreImage/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n schema?: object\n getSchema?(props?: P): object\n }\n}\n\n```"
}
] |
code_store-on-localhost_b62703d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreImage/typings/css.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: CSSHandles\n export default css\n}\n\ninterface CSSHandles {\n imageElement: string\n}\n\n```"
}
] |
code_store-on-localhost_fef9718e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreImage/__tests__/index.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\ndescribe('Orders List Scenarios', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```"
}
] |
code_store-on-localhost_e2a7ce57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.react-portal.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.react-portal' {\n import { ComponentType } from 'react'\n export const Overlay: ComponentType<{}>\n}\n\n```"
}
] |
code_store-on-localhost_fd967ccc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n type CssHandlesInput = readonly string[]\n type ValueOf<T extends readonly any[]> = T[number]\n type CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\n interface CssHandlesOptions {\n migrationFrom?: string | string[]\n }\n\n export const useCssHandles: <T extends CssHandlesInput>(\n handles: T,\n options: CssHandlesOptions = {}\n ) => CssHandles<T>\n export const applyModifiers: (\n handles: string,\n modifier: string | string[]\n ) => string\n}\n\n```"
}
] |
code_store-on-localhost_6098d6b4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.product-context.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface SelectedItem {\n itemId: string\n sellers: {\n sellerId: string\n commertialOffer: {\n AvailableQuantity: number\n }\n }[]\n}\n\ninterface Specification {\n name: string\n values: [string]\n}\n\ninterface SpecificationGroup {\n name: string\n specifications: Specification[]\n}\n\ninterface Product {\n specificationGroups?: SpecificationGroup[]\n}\n\ndeclare module 'vtex.product-context/useProduct' {\n const useProduct: () => ProductContext\n export default useProduct\n\n interface ProductContext {\n selectedQuantity: number\n product: Product | undefined\n selectedItem: SelectedItem | null\n skuSelector: {\n areAllVariationsSelected: boolean\n isVisible: boolean\n }\n }\n}\n\ndeclare module 'vtex.product-context/ProductDispatchContext' {\n type DispatchFunction = (payload: { type: string; args?: any }) => void\n export const useProductDispatch: () => DispatchFunction\n}\n\n```"
}
] |
code_store-on-localhost_b8abb302
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n interface Runtime {\n navigate: (options: NavigationOptions) => void\n culture: {\n country: string\n }\n }\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: Runtime\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = function({ id: string }): object {}\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends object>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const useRuntime: () => Runtime\n}\n\n```"
}
] |
code_store-on-localhost_a5f7c1e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.device-detector.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.device-detector' {\n interface DeviceType {\n isMobile: boolean\n }\n export const useDevice: () => DeviceType\n}\n\n```"
}
] |
code_store-on-localhost_1816f4de
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.store-icons.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-icons' {\n import { ComponentType } from 'react'\n interface Props {\n size: number\n viewBox?: string\n }\n\n export const IconLocationInput: ComponentType<Props>\n export const IconClose: ComponentType<Props & { type: string }>\n}\n\n```"
}
] |
code_store-on-localhost_21261aaa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FC, Component } from 'react'\nimport { Orientations } from '../modules/constants'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FC<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n\n interface Condition {\n visibleWhen?: string\n displayValue?: string\n }\n\n interface BaseProps extends Condition {\n specificationGroupName: string\n orientation?: Orientations\n specificationsOptions?: ConditionWithName[]\n specificationName?: string\n }\n\n type ConditionWithName = Condition & {\n specificationName: BaseProps['specificationName']\n }\n}\n\n```"
}
] |
code_store-on-localhost_c5eb0f48
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/css.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```"
}
] |
code_store-on-localhost_4cd297d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/typings/vtex.styleguide.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n export const Spinner: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n\n export const Button: ComponentType<{\n onClick: () => void\n variation?: string\n size?: string\n }>\n\n export const Modal: ComponentType<{\n onClose: () => void\n isOpen: boolean\n centered: boolean\n title?: string\n }>\n\n export const Radio: ComponentType<{\n checked: boolean\n onChange: () => void\n id: string\n label: string\n name: string\n value: string\n }>\n}\n\n```"
}
] |
code_store-on-localhost_89d18d35
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/components/BaseSpecificationBadges.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { propEq } from 'ramda'\nimport slugify from '../modules/slug'\nimport useCssHandles from '../../CssHandles/useCssHandles'\nimport applyModifiers from '../../CssHandles/applyModifiers'\n\nimport { Orientations, DisplayValues } from '../modules/constants'\n\nconst CSS_HANDLES = ['groupContainer', 'badgeContainer', 'badgeText'] as const\n\ninterface Props {\n product?: Product\n}\n\nconst checkConditionForSpecification = (condition: Condition, specification: Specification) => {\n const { displayValue, visibleWhen } = condition\n if (!displayValue) {\n return false\n }\n\n if (!visibleWhen) {\n return specification.values && specification.values[0]\n }\n\n return specification.values && visibleWhen && specification.values[0] === visibleWhen\n}\n\nconst getValidSpecificationForCondition = (condition: ConditionWithName, specifications: Specification[]) => {\n const { displayValue, specificationName } = condition\n const specification = specifications.find(propEq('name', specificationName))\n if (!specification) {\n return null\n }\n\n const isValid = checkConditionForSpecification(condition, specification)\n return isValid ? { displayValue, specification } : null\n}\n\ninterface VisibleSpecification {\n specification: Specification\n displayValue: Condition['displayValue']\n}\n\nconst getVisibleBadges = (\n product: Product | undefined,\n baseCondition: ConditionWithName,\n groupName: string,\n specificationsOptions: BaseProps['specificationsOptions']\n) => {\n if (!product) {\n return []\n }\n const { specificationGroups = [] } = product\n const group = specificationGroups.find(propEq('name', groupName))\n\n if (!group) {\n return []\n }\n\n let badges = [] as VisibleSpecification[]\n\n if (baseCondition.visibleWhen && baseCondition.displayValue) {\n const { specificationName } = baseCondition\n const specifications =\n specificationName ? group.specifications.filter(propEq('name', specificationName)) : group.specifications\n\n badges = specifications.map(spec => {\n if (checkConditionForSpecification(baseCondition, spec as any)) {\n return { specification: spec, displayValue: baseCondition.displayValue }\n }\n return null\n }).filter(Boolean) as VisibleSpecification[]\n }\n\n if (specificationsOptions) {\n const optionsBadges = specificationsOptions.map(option =>\n getValidSpecificationForCondition(option, group.specifications as any))\n .filter(Boolean) as VisibleSpecification[]\n badges = badges.concat(optionsBadges)\n }\n\n return badges\n}\n\nconst getMarginToken = (isVertical: boolean, isFirst: boolean, isLast: boolean) => {\n let marginTokens = \"\"\n\n if (isVertical) {\n if (!isFirst) {\n marginTokens += \"mt2 \"\n }\n if (!isLast) {\n marginTokens += \"mb2 \"\n }\n }\n\n if (!isVertical) {\n if (!isFirst) {\n marginTokens += \"ml2 \"\n }\n if (!isLast) {\n marginTokens += \"mr2 \"\n }\n }\n\n return marginTokens.trim()\n}\n\nconst BaseSpecificationBadges: StorefrontFunctionComponent<Props & BaseProps> = ({\n product,\n specificationGroupName,\n visibleWhen,\n specificationsOptions,\n specificationName,\n displayValue,\n orientation = Orientations.vertical\n}) => {\n const badges = getVisibleBadges(\n product,\n { specificationName, displayValue, visibleWhen },\n specificationGroupName,\n specificationsOptions\n )\n const handles = useCssHandles(CSS_HANDLES)\n\n if (!product || badges.length === 0) {\n return null\n }\n\n const isVertical = orientation === Orientations.vertical\n\n const orientationToken = isVertical ? 'inline-flex flex-column' : 'flex'\n\n return (\n <div className={`${handles.groupContainer} ${orientationToken} ma2`}>\n {badges.map((badge, idx) => {\n const { displayValue } = badge\n let valueToShow = displayValue\n if (displayValue === DisplayValues.specificationValue) {\n valueToShow = badge.specification.values[0]\n }\n\n if (displayValue === DisplayValues.specificationName) {\n valueToShow = badge.specification.name\n }\n\n if (!displayValue) {\n console.warn('You need to set a `displayValue` for the `product-specification-badges` block, either `SPECIFICATION_VALUE` or `SPECIFICATION_NAME`')\n return null\n }\n const slugifiedName = slugify(badge.specification.name)\n const marginToken = getMarginToken(isVertical, idx === 0, idx === badges.length - 1)\n return (\n <div\n key={`${badge.specification.name}-${valueToShow}`}\n className={`${applyModifiers(handles.badgeContainer, slugifiedName)} ${marginToken} bg-base flex items-center justify-center\"`}\n >\n <span className={`${handles.badgeText} ma3 t-body c-muted-1 tc`}>{valueToShow}</span>\n </div>\n )\n })}\n </div>\n )\n}\n\nBaseSpecificationBadges.schema = {\n type: 'object',\n properties: {\n specificationGroupName: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.specificationGroupName.title',\n description: 'admin/editor.product-specification-badges.specificationGroupName.description'\n },\n specificationName: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.specificationName.title',\n description: 'admin/editor.product-specification-badges.specificationName.description'\n },\n visibleWhen: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.visibleWhen.title',\n description: 'admin/editor.product-specification-badges.visibleWhen.description'\n },\n displayValue: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.displayValue.title',\n description: 'admin/editor.product-specification-badges.displayValue.description'\n },\n orientation: {\n title: 'admin/editor.product-specification-badges.orientation.title',\n description: 'admin/editor.product-specification-badges.orientation.description',\n enum: ['vertical', 'horizontal'],\n enumNames: ['admin/editor.product-specification-badges.orientation.vertical', 'admin/editor.product-specification-badges.orientation.horizontal'],\n type: 'string',\n default: 'vertical',\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n },\n specificationsOptions: {\n type: 'array',\n title: 'admin/editor.product-specification-badges.specificationsOptions.title',\n description: 'admin/editor.product-specification-badges.specificationsOptions.description',\n items: {\n title: 'admin/editor.product-specification-badges.specificationsOptions.item.title',\n type: 'object',\n properties: {\n specificationName: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.specificationName.title',\n },\n visibleWhen: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.visibleWhen.title',\n },\n displayValue: {\n type: 'string',\n title: 'admin/editor.product-specification-badges.displayValue.title',\n },\n }\n }\n }\n }\n}\n\nexport default BaseSpecificationBadges\n\n```"
}
] |
code_store-on-localhost_6f75d2e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/__tests__/index.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport Index from '../index'\n\nimport { getProduct } from '../__mocks__/productMock'\n\nimport ProductContextProvider from '../__mocks__/vtex.product-context/ProductContextProvider'\n\n\nconst renderComponent = (customProps: any = {}) => {\n\n const product = customProps.product || getProduct()\n\n return render(\n <ProductContextProvider product={product}>\n <Index\n visibleWhen={customProps.visibleWhen}\n specificationsOptions={customProps.specificationsOptions}\n specificationGroupName={customProps.specificationGroupName}\n specificationName={customProps.specificationName}\n displayValue={customProps.displayValue}\n />\n </ProductContextProvider>\n )\n}\n\ntest('show names inside group that meet condition', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n const { getByText, queryByText } = renderComponent({\n specificationGroupName: \"allSpecifications\",\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n getByText(/Demo/)\n expect(queryByText(/PromoExclusion/)).toBeFalsy()\n})\n\ntest('show names inside group that meet conditions array', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n\n const { getByText, queryByText } = renderComponent({\n specificationGroupName: \"allSpecifications\",\n specificationsOptions: [{\n specificationName: 'On Sale',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n }],\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n expect(queryByText(/Demo/)).toBeFalsy()\n expect(queryByText(/PromoExclusion/)).toBeFalsy()\n})\n\ntest('show badges of generic condition and for specific options', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['Enabled'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['Enabled'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n\n const { getByText, queryByText } = renderComponent({\n specificationGroupName: \"allSpecifications\",\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n specificationsOptions: [{\n specificationName: 'Demo',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'Enabled',\n }],\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n getByText(/Demo/)\n expect(queryByText(/PromoExclusion/)).toBeFalsy()\n})\n\ntest('test generic condition with specification Name being passed', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n\n const { getByText, queryByText } = renderComponent({\n specificationGroupName: \"allSpecifications\",\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n specificationName: 'On Sale',\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n expect(queryByText(/Demo/)).toBeFalsy()\n expect(queryByText(/PromoExclusion/)).toBeFalsy()\n})\n\ntest('test show demo, value and custom string', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['DemoValue'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['DemoValue'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n const { getByText } = renderComponent({\n // specificationsOptions: {\n // ['On Sale']: {\n // displayValue: 'SPECIFICATION_NAME',\n // visibleWhen: 'True',\n // },\n // Demo: {\n // displayValue: 'SPECIFICATION_VALUE',\n // },\n // PromoExclusion: {\n // displayValue: \"Custom String\"\n // }\n // },\n specificationsOptions: [{\n specificationName: 'On Sale',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n },\n {\n specificationName: 'Demo',\n displayValue: 'SPECIFICATION_VALUE',\n },\n {\n specificationName: 'PromoExclusion',\n displayValue: 'Custom String',\n }],\n specificationGroupName: \"allSpecifications\",\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n getByText(/DemoValue/)\n getByText(/Custom String/)\n})\n\ntest('dont break if wrong group name', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['DemoValue'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['DemoValue'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n const { queryByText } = renderComponent({\n specificationsOptions: [{\n specificationName: 'On Sale',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n },\n {\n specificationName: 'Demo',\n displayValue: 'SPECIFICATION_VALUE',\n },\n {\n specificationName: 'PromoExclusion',\n displayValue: 'Custom String',\n }],\n specificationGroupName: \"adsaadsad\",\n product: getProduct({ specificationGroups }),\n })\n\n expect(queryByText(/On Sale/)).toBeFalsy()\n})\n\ntest('dont show item with displayValue condition not provided', () => {\n\n const specificationGroups = [\n {\n name: 'Group',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n ],\n },\n {\n name: 'Group 2',\n specifications: [\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n }\n ],\n },\n {\n name: 'allSpecifications',\n specifications: [\n {\n name: 'On Sale',\n values: ['True'],\n },\n {\n name: 'Demo',\n values: ['True'],\n },\n {\n name: 'PromoExclusion',\n values: ['1'],\n },\n ],\n },\n ]\n\n const { queryByText, getByText } = renderComponent({\n specificationsOptions: [{\n specificationName: 'On Sale',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n },\n {\n specificationName: 'Demo',\n }],\n specificationGroupName: \"allSpecifications\",\n product: getProduct({ specificationGroups }),\n })\n\n getByText(/On Sale/)\n expect(queryByText(/Demo/)).toBeFalsy()\n})\n\ntest('do not break if specificationgroups is undefined', () => {\n const { queryByText } = renderComponent({\n specificationsOptions: [{\n specificationName: 'On Sale',\n displayValue: 'SPECIFICATION_NAME',\n visibleWhen: 'True',\n },\n {\n specificationName: 'Demo',\n }],\n specificationGroupName: \"allSpecifications\",\n product: getProduct({ specificationGroups: undefined }),\n })\n\n expect(queryByText(/On Sale/)).toBeFalsy()\n})\n```"
}
] |
code_store-on-localhost_c884244f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/modules/slug.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport slugify from 'slugify'\n\nexport default function slug(str: string) {\n const replaced = (str && str.replace(/[*+~.()'\"!:@&\\[\\]]/g, '')) || ''\n const slugified = slugify(replaced, { lower: true }) || ''\n return slugified\n}\n```"
}
] |
code_store-on-localhost_642ba67b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ProductSpecificationBadges/modules/constants.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport enum Orientations {\n horizontal = 'horizontal',\n vertical = 'vertical',\n}\n\nexport enum DisplayValues {\n specificationName = 'SPECIFICATION_NAME',\n specificationValue = 'SPECIFICATION_VALUE',\n}\n\n```"
}
] |
code_store-on-localhost_f869d6be
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/ListContext/__tests__/index.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\ndescribe('Orders List Scenarios', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```"
}
] |
code_store-on-localhost_ceedb290
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/storefront.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```"
}
] |
code_store-on-localhost_e0243b4b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/globals.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface OrderForm {\n items: Item[]\n marketingData: MarketingData | null\n totalizers: Totalizer[]\n value: number\n}\n\ninterface Item {\n additionalInfo: ItemAdditionalInfo\n availability: string\n detailUrl: string\n id: string\n imageUrl: string\n index?: number\n listPrice: number\n measurementUnit: string\n name: string\n price: number\n productId: string\n quantity: number\n sellingPrice: number\n skuName: string\n skuSpecifications: SKUSpecification[]\n uniqueId: string\n}\n\ninterface ItemAdditionalInfo {\n brandName: string\n}\n\ninterface MarketingData {\n coupon: string\n}\n\ninterface SKUSpecification {\n fieldName: string\n fieldValues: string[]\n}\n\ninterface Totalizer {\n id: string\n name: string\n value: number\n}\n\n```"
}
] |
code_store-on-localhost_c49ca0fb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n\n interface ChildBlockProps {\n id: string\n }\n\n export const ChildBlock: ComponentType<ChildBlockProps>\n export const useChildBlock = function({ id: string }): object {}\n\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: ReactElement\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n}\n\n```"
}
] |
code_store-on-localhost_1bfb7072
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/css.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```"
}
] |
code_store-on-localhost_6cd6a515
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/graphql.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_store-on-localhost_1ddc7604
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/typings/vtex.styleguide.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n\n export const Input: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```"
}
] |
code_store-on-localhost_7d52eb5d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/OrderItems/__tests__/OrderItems.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { adjust } from 'ramda'\nimport React, { FunctionComponent } from 'react'\nimport { MockedProvider } from '@apollo/react-testing'\nimport { act, render, fireEvent } from '@vtex/test-tools/react'\nimport { updateItems as UpdateItem } from 'vtex.checkout-resources/Mutations'\nimport { OrderFormProvider, useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { OrderQueueProvider } from 'vtex.order-manager/OrderQueue'\n\nimport { mockOrderForm } from '../__mocks__/mockOrderForm'\nimport { OrderItemsProvider, useOrderItems } from '../OrderItems'\n\nconst mockUpdateItemMutation = (\n args: Partial<Item>[],\n result: Partial<Item>[]\n) => ({\n request: {\n query: UpdateItem,\n variables: {\n orderItems: args,\n },\n },\n result: {\n data: {\n updateItems: {\n ...mockOrderForm,\n items: result,\n },\n },\n },\n})\n\ndescribe('OrderItems', () => {\n it('should throw when useOrderItems is called outside a OrderItemsProvider', () => {\n const oldConsoleError = console.error\n console.error = () => {}\n\n const Component: FunctionComponent = () => {\n useOrderItems()\n return <div>foo</div>\n }\n\n expect(() => render(<Component />)).toThrow(\n 'useOrderItems must be used within a OrderItemsProvider'\n )\n\n console.error = oldConsoleError\n })\n\n it('should optimistically update itemList when updateQuantity is called', async () => {\n const Component: FunctionComponent = () => {\n const {\n orderForm: { items },\n } = useOrderForm()\n const { updateQuantity } = useOrderItems()\n return (\n <div>\n {items.map((item: Item) => (\n <div key={item.name}>\n {item.name}: {item.quantity}\n </div>\n ))}\n <button onClick={() => updateQuantity({ index: 1, quantity: 123 })}>\n mutate\n </button>\n </div>\n )\n }\n\n const mockUpdateItem = mockUpdateItemMutation(\n [{ uniqueId: mockOrderForm.items[1].uniqueId, quantity: 123 }],\n adjust(\n 1,\n (item: Item) => ({ ...item, quantity: 42 }),\n mockOrderForm.items\n )\n )\n\n const { getByText } = render(\n <MockedProvider mocks={[mockUpdateItem]} addTypename={false}>\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderItemsProvider>\n <Component />\n </OrderItemsProvider>\n </OrderFormProvider>\n </OrderQueueProvider>\n </MockedProvider>\n )\n\n const button = getByText('mutate')\n\n act(() => {\n fireEvent.click(button)\n })\n expect(getByText(`${mockOrderForm.items[1].name}: 123`)).toBeTruthy() // optimistic response\n\n await act(() => new Promise(resolve => setTimeout(() => resolve()))) // waits for actual mutation result\n expect(getByText(`${mockOrderForm.items[1].name}: 42`)).toBeTruthy()\n })\n\n it('should optimistically update itemList when removeItem is called', async () => {\n const Component: FunctionComponent = () => {\n const {\n orderForm: { items },\n } = useOrderForm()\n const { removeItem } = useOrderItems()\n return (\n <div>\n {items.map((item: Item) => (\n <div key={item.name}>\n {item.name}: {item.quantity}\n </div>\n ))}\n <button\n onClick={() =>\n removeItem({ uniqueId: mockOrderForm.items[0].uniqueId })\n }\n >\n mutate\n </button>\n </div>\n )\n }\n\n const mockUpdateItem = mockUpdateItemMutation(\n [{ uniqueId: mockOrderForm.items[0].uniqueId, quantity: 0 }],\n adjust(0, (item: Item) => ({ ...item, quantity: 7 }), mockOrderForm.items)\n )\n\n const { getByText, queryByText } = render(\n <MockedProvider mocks={[mockUpdateItem]} addTypename={false}>\n <OrderQueueProvider>\n <OrderFormProvider>\n <OrderItemsProvider>\n <Component />\n </OrderItemsProvider>\n </OrderFormProvider>\n </OrderQueueProvider>\n </MockedProvider>\n )\n\n const button = getByText('mutate')\n\n act(() => {\n fireEvent.click(button)\n })\n expect(\n queryByText(\n (_, element) =>\n !!element.textContent &&\n element.textContent.includes(mockOrderForm.items[0].name)\n )\n ).toBeFalsy() // optimistic response\n\n await act(() => new Promise(resolve => setTimeout(() => resolve()))) // waits for actual mutation result\n expect(getByText(`${mockOrderForm.items[0].name}: 7`)).toBeTruthy()\n })\n})\n\n```"
}
] |
code_store-on-localhost_ca958c9d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/CssHandles/typings/global.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface CssHandlesOptions {\n migrationFrom?: string | string[]\n blockClass?: string\n}\ntype CssHandlesInput = readonly string[]\ntype ValueOf<T extends readonly any[]> = T[number]\ntype CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\n\n```"
}
] |
code_store-on-localhost_8a63d927
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/CssHandles/__tests__/useCssHandles.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport useCssHandles from '../useCssHandles'\nimport { useExtension } from '../hooks/useExtension'\n\njest.mock('react', () => ({\n useMemo: (callback: () => any) => callback(),\n}))\n\njest.mock('../hooks/useExtension', () => ({\n useExtension: jest.fn(() => ({\n component: 'vtex.app@2.1.0',\n props: {\n blockClass: 'blockClass',\n },\n })),\n}))\n\nconsole.error = jest.fn()\n\ndescribe('useCssHandles', () => {\n it('should apply proper classes to proper handles', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const handles = useCssHandles(CSS_HANDLES)\n\n expect(handles).toStrictEqual({\n element1: 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass',\n element2: 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass',\n })\n })\n it('should not apply blockClasses if not available', () => {\n const CSS_HANDLES = ['element1', 'element2']\n ;(useExtension as any).mockImplementationOnce(() => ({\n component: 'vtex.app@2.1.0',\n props: {},\n }))\n\n const handles = useCssHandles(CSS_HANDLES)\n\n expect(handles).toStrictEqual({\n element1: 'vtex-app-2-x-element1',\n element2: 'vtex-app-2-x-element2',\n })\n })\n describe('migration', () => {\n it('should add both the current app and the migration app', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const handles = useCssHandles(CSS_HANDLES, {\n migrationFrom: 'vtex.previous-app@3.0.0',\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n it('should add more than one migration if needed', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const handles = useCssHandles(CSS_HANDLES, {\n migrationFrom: ['vtex.previous-app@2.0.0', 'vtex.previous-app@3.0.0'],\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n\n it('doesnt repeat the migration if the current app happens to be the same as the migration one', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const handles = useCssHandles(CSS_HANDLES, {\n migrationFrom: [\n 'vtex.previous-app@2.0.0',\n 'vtex.previous-app@3.0.0',\n 'vtex.app@2.1.0',\n ],\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n })\n})\n\n```"
}
] |
code_store-on-localhost_a12013f6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/CssHandles/__tests__/applyModifiers.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport applyModifiers from '../applyModifiers'\n\nconsole.error = jest.fn()\n\ndescribe('applyModifier', () => {\n it('should apply a single modifier properly', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifier = 'test'\n\n const modified = applyModifiers(handle, modifier)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--test vtex-app-2-x-handle--blockClass--test'\n )\n })\n it('should apply multiple modifiers properly', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['test', 'test2']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--test vtex-app-2-x-handle--blockClass--test vtex-app-2-x-handle--test2 vtex-app-2-x-handle--blockClass--test2'\n )\n })\n it('should not apply modifier if its not a string', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifier = 0 as any\n\n const modified = applyModifiers(handle, modifier)\n\n expect(modified).toBe('vtex-app-2-x-handle vtex-app-2-x-handle--blockClass')\n })\n\n describe('validation', () => {\n it('should refrain from applying a modifier from an array if its not a string', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', 0, null] as any\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok'\n )\n })\n it('should not apply a modifier with spaces, should allow with dashes', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', 'test 1', 'test-2', 'test\\t3', 'test\\n4']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok vtex-app-2-x-handle--test-2 vtex-app-2-x-handle--blockClass--test-2'\n )\n })\n it('should not apply a modifier if its empty', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', '', '\\t', ' ']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok'\n )\n })\n })\n})\n\n```"
}
] |
code_store-on-localhost_4c2ea0b8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/CssHandles/__tests__/withCssHandles.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport withCssHandles from '../withCssHandles'\nimport { useExtension } from '../hooks/useExtension'\nimport { render } from '@vtex/test-tools/react'\n\ntype ValueOf<T extends readonly any[]> = T[number]\n\ntype CssHandlesInput = readonly string[]\ntype CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\ninterface CssHandlesOptions {\n migrationFrom?: string | string[]\n}\n\ninterface Props<T extends CssHandlesInput> {\n cssHandles?: CssHandles<T>\n}\n\nclass ExampleComponent<T extends CssHandlesInput> extends Component<Props<T>> {\n public render() {\n const cssHandles = this.props.cssHandles as CssHandles<T>\n\n return (\n <div\n data-testid=\"test-div\"\n className={Object.values(cssHandles).join(' ')}></div>\n )\n }\n}\n\njest.mock('../hooks/useExtension', () => ({\n useExtension: jest.fn(() => ({\n component: 'vtex.app@2.1.0',\n props: {\n blockClass: 'blockClass',\n },\n })),\n}))\n\ndescribe('withCssHandles', () => {\n const renderComponent = (\n handlesNames: CssHandlesInput,\n options?: CssHandlesOptions\n ) => {\n const EnhancedComponent = withCssHandles<\n typeof handlesNames,\n Props<typeof handlesNames>\n >(handlesNames, options)(ExampleComponent)\n\n return render(<EnhancedComponent />)\n }\n\n it('should apply proper classes to proper handles', () => {\n const CSS_HANDLES = ['element1', 'element2'] as const\n const { getByTestId } = renderComponent(CSS_HANDLES)\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass'\n )\n })\n it('should not apply blockClasses if not available', () => {\n const CSS_HANDLES = ['element1', 'element2'] as const\n ;(useExtension as any).mockImplementationOnce(() => ({\n component: 'vtex.app@2.1.0',\n props: {},\n }))\n\n const { getByTestId } = renderComponent(CSS_HANDLES)\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element2'\n )\n })\n describe('migration', () => {\n it('should add both the current app and the migration app', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: 'vtex.previous-app@3.0.0',\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n it('should add more than one migration if needed', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: ['vtex.previous-app@2.0.0', 'vtex.previous-app@3.0.0'],\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n\n it('doesnt repeat the migration if the current app happens to be the same as the migration one', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: [\n 'vtex.previous-app@2.0.0',\n 'vtex.previous-app@3.0.0',\n 'vtex.app@2.1.0',\n ],\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n })\n})\n\n```"
}
] |
code_store-on-localhost_2c7a823b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/CssHandles/hooks/useExtension.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useRuntime, useTreePath } from '../../../../../vtex.render-runtime'\n\n/** This code has been copied and adapted from vtex.render-runtime,\n * while it doesn't export this hook */\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\ninterface Extension {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n props?: Record<string, any>\n component?: string\n [key: string]: any\n}\n\nexport const useExtension = ({ children }: Options = {}): Extension | 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 as Extension) || null\n}\n\n```"
}
] |
code_store-on-localhost_ae9fb030
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/__test__/index.test.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-env jest */\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport RichText from '../index'\n\nimport { textPositionValues, textAlignmentValues } from '../typings/SchemaTypes'\n\ndescribe('Rich text component', () => {\n const defaultProps = {\n font: 't-body',\n text: '',\n textPosition: textPositionValues.LEFT,\n textAlignment: textAlignmentValues.LEFT,\n textColor: 'c-on-base',\n }\n\n it('should render with bold', () => {\n const component = render(\n <RichText {...defaultProps} text={'**be bold**'} />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render with paragraph', () => {\n const component = render(\n <RichText {...defaultProps} text={'IAM BOLD'} />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render link with title', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n '[I\\'m an inline-style link with title](https://www.google.com \"Google\\'s Homepage\")\\n**Bollllddd**\\n*this is talic*'\n }\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render and sanitize malicious text', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n \"Hi everyone! This is **how** you do XSS <script>alert('XSS')</script>\"\n }\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render and sanitize malicious text', () => {\n const component = render(\n <RichText {...defaultProps} text={'[some text](javascript:exec())'} />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render and sanitize malicious javascript', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={'<a href=\"javascript:exec()\">HEHEHE</a>'}\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render and sanitize malicious javascript', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n '<DIV STYLE=\"background-image: url(javascript:alert(\\'XSS\\'))\">'\n }\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render with image', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `Inline-style: \n `\n }\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render with image no title', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `Inline-style: \n `\n }\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render with image block class props', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `[I\\'m an inline-style link with title](https://www.google.com \"Google\\'s Homepage\")\\n**Bollllddd**\\n*this is talic*`\n }\n blockClass=\"home\"\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render an iframe', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={ // It must be preceeded by Markdown tag or any other string, otherwise the lib marked escapes the iframe HTML tag.\n \"__<iframe frameborder=\\\"0\\\" height=\\\"100%\\\" src=\\\"https://invictastores.typeform.com/to/KmycOT?typeform-embed=embed-widget&embed-hide-footer=true&embed-hide-headers=true&embed-opacity=50&typeform-embed-id=d0pe3\\\" width=\\\"100%\\\" style=\\\"border: 0px;\\\"></iframe>__\"\n }\n />\n )\n\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render a link with target', () => {\n const { asFragment } = render(\n <RichText\n {...defaultProps}\n text=\"<a href='https://google.com' target='_blank'>bc</a>\"\n />\n )\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render a link with target as query string on markdown and erase ?', () => {\n const { asFragment } = render(\n <RichText\n {...defaultProps}\n text=\"[text](https://www.google.com?target=_blank) \"\n />\n )\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render a link with target as query string on markdown and keep others params', () => {\n const { asFragment } = render(\n <RichText\n {...defaultProps}\n text=\"[text](https://www.google.com?target=_blank&foo=tree\\&bar=lala)\"\n />\n )\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render a link with target as query string on markdown and keep others params, remove trailing &', () => {\n const { asFragment } = render(\n <RichText\n {...defaultProps}\n text=\"[text](https://www.google.com?foo=tree\\&bar=lala&target=_blank)\"\n />\n )\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render a table', () => {\n const { asFragment } = render(\n <RichText\n {...defaultProps}\n text={`\nfoo|bar\n---|---\nteste|abc\n `}\n />\n )\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should render with two different heading levels', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `# Heading 1 # \\n ### Heading level 3 ##`\n }\n blockClass=\"home\"\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should render list', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `Teste \\n * Item 1\\n * Item 2\\n * Item 3`\n }\n blockClass=\"home\"\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n\n it('should render ordered list', () => {\n const component = render(\n <RichText\n {...defaultProps}\n text={\n `Teste \\n 1. Item 1\\n 2. Item 2\\n 3. Item 3`\n }\n blockClass=\"home\"\n />\n )\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should sanitize the font prop', () => {\n const typography = 't-heading-1'\n const { container } = render(<RichText {...defaultProps} text=\"foo\" font={`${typography} foo`} />)\n\n const element = container.querySelector(`.${typography}`)\n const notFound = container.querySelector('.foo')\n\n expect(element).toBeTruthy()\n expect(notFound).toBeFalsy()\n })\n\n it('should sanitize the textColor prop', () => {\n const color = 'c-muted-1'\n const { container } = render(<RichText {...defaultProps} text=\"foo\" textColor={`${color} foo`} />)\n\n const element = container.querySelector(`.${color}`)\n const notFound = container.querySelector('.foo')\n\n expect(element).toBeTruthy()\n expect(notFound).toBeFalsy()\n })\n\n it('should allow tel scheme on link', () => {\n const component = render(<RichText {...defaultProps} text=\"[Telefone](tel:+18882165252)\" />)\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should allow mailto scheme on link', () => {\n const component = render(<RichText {...defaultProps} text=\"[Mail me](mailto:test@vtex.com.br)\" />)\n expect(component).toBeDefined()\n expect(component.asFragment()).toMatchSnapshot()\n })\n})\n\n\n```"
}
] |
code_store-on-localhost_24e668c9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n type CssHandlesInput = readonly string[]\n type ValueOf<T extends readonly any[]> = T[number]\n export type CssHandles<T extends CssHandlesInput> = Record<ValueOf<T>, string>\n interface CssHandlesOptions {\n migrationFrom?: string | string[]\n }\n\n export const useCssHandles: <T extends CssHandlesInput>(\n handles: T,\n options: CssHandlesOptions = {}\n ) => CssHandles<T>\n export const applyModifiers: (\n handles: string,\n modifier: string | string[]\n ) => string\n}\n\n```"
}
] |
code_store-on-localhost_0e0dbaac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/typings/SchemaTypes.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport enum textPositionValues {\n CENTER = 'CENTER',\n LEFT = 'LEFT',\n RIGHT = 'RIGHT',\n}\n\nexport enum textAlignmentValues {\n CENTER = 'CENTER',\n LEFT = 'LEFT',\n RIGHT = 'RIGHT',\n}\n\nexport const textPositionTypes: Record<\n string,\n { name: string; value: textPositionValues }\n> = {\n TEXT_POSITION_CENTER: {\n name: 'admin/editor.rich-text.textPosition.center',\n value: textPositionValues.CENTER,\n },\n TEXT_POSITION_LEFT: {\n name: 'admin/editor.rich-text.textPosition.left',\n value: textPositionValues.LEFT,\n },\n TEXT_POSITION_RIGHT: {\n name: 'admin/editor.rich-text.textPosition.right',\n value: textPositionValues.RIGHT,\n },\n}\n\nexport const textAlignmentTypes: Record<\n string,\n { name: string; value: textAlignmentValues }\n> = {\n TEXT_ALIGNMENT_CENTER: {\n name: 'admin/editor.rich-text.textAlignment.center',\n value: textAlignmentValues.CENTER,\n },\n TEXT_ALIGNMENT_LEFT: {\n name: 'admin/editor.rich-text.textAlignment.left',\n value: textAlignmentValues.LEFT,\n },\n TEXT_ALIGNMENT_RIGHT: {\n name: 'admin/editor.rich-text.textAlignment.right',\n value: textAlignmentValues.RIGHT,\n },\n}\n\n```"
}
] |
code_store-on-localhost_4238db3a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/typings/insane.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// Insane is based on the sanitize-html package.\n// So its types are extremely close to it.\n\ndeclare function insane(dirty: string, options?: insane.IOptions): string\n\ndeclare namespace insane {\n interface IOptions {\n allowedTags?: string[] | boolean\n allowedAttributes?: { [index: string]: string[] } | boolean\n allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }\n allowedClasses?: { [index: string]: string[] } | boolean\n }\n}\n\ndeclare module 'insane' {\n export = insane\n}\n```"
}
] |
code_store-on-localhost_a6f6805d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/typings/vtex.native-types.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.native-types' {\n import { Component } from 'react'\n import { InjectedIntl, WrappedComponentProps } from 'react-intl'\n\n interface FormatIOMessageParams {\n id: string\n intl: InjectedIntl\n }\n\n export const formatIOMessage: (params: FormatIOMessageParams) => string\n\n interface IOMessageProps extends WrappedComponentProps {\n id: string\n }\n\n export const IOMessage: Component<IOMessageProps>\n}\n\n```"
}
] |
code_store-on-localhost_c1c0c77a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/RichText/styles/index.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.heading-level-1 {\n}\n.heading-level-2 {\n}\n.heading-level-3 {\n}\n.heading-level-4 {\n}\n.heading-level-5 {\n}\n.heading-level-6 {\n}\n\n```"
}
] |
code_store-on-localhost_2d312419
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/__test__/Shelf.test.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-env jest */\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\nimport ProductList from '../components/ProductList'\nimport { productMock } from '../__mocks__/productMock'\nimport Shelf from '../Shelf'\nimport { resolvePaginationDotsVisibility } from '../utils/resolvePaginationDots'\nconst fs = require('fs')\n\ndescribe('Shelf component', () => {\n const renderComponent = customProps => {\n const props = {\n maxItems: 1,\n itemsPerPage: 1,\n arrows: true,\n showTitle: true,\n }\n\n const titleText = 'store/shelf.title'\n const wrapper = render(<ProductList titleText={titleText} {...props} {...customProps} />)\n return wrapper\n }\n\n it('should be rendered', () => {\n const component = renderComponent()\n expect(component).toBeDefined()\n })\n\n it('should render nothing if there is no products', () => {\n const component = renderComponent({ products: [] })\n\n expect(component.container.querySelector('.title')).toBeFalsy()\n })\n\n it('should match the snapshot', () => {\n const component = renderComponent({ products: productMock })\n expect(component.asFragment()).toMatchSnapshot()\n })\n\n it('should show in Site Editor', () => {\n const { schema } = Shelf\n expect(schema).toBeDefined()\n expect(typeof schema.title).toBe('string')\n })\n})\n\ndescribe('Util functions', () => {\n it('should return the correct value for pagination dots visibility', () => {\n const MOBILE_ONLY = 'mobileOnly'\n const DESKTOP_ONLY = 'desktopOnly'\n const VISIBLE = 'visible'\n const HIDDEN = 'hidden'\n\n /** resolvePaginationDotsVisibility(visibility: string, isMobile: boolean) */\n expect(resolvePaginationDotsVisibility(MOBILE_ONLY, false)).toBeFalsy()\n expect(resolvePaginationDotsVisibility(MOBILE_ONLY, true)).toBeTruthy()\n\n expect(resolvePaginationDotsVisibility(DESKTOP_ONLY, false)).toBeTruthy()\n expect(resolvePaginationDotsVisibility(DESKTOP_ONLY, true)).toBeFalsy()\n\n expect(resolvePaginationDotsVisibility(VISIBLE, false)).toBeTruthy()\n expect(resolvePaginationDotsVisibility(VISIBLE, true)).toBeTruthy()\n\n expect(resolvePaginationDotsVisibility(HIDDEN, false)).toBeFalsy()\n expect(resolvePaginationDotsVisibility(HIDDEN, true)).toBeFalsy()\n })\n})\n\n```"
}
] |
code_store-on-localhost_fad2b1ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/typings/vtex.native-types.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.native-types' {\n import { Component } from 'react'\n import { InjectedIntl, InjectedIntlProps } from 'react-intl'\n \n interface FormatIOMessageParams {\n id: string\n intl: InjectedIntl\n }\n \n export const formatIOMessage: (params: FormatIOMessageParams) => string\n \n interface IOMessageProps extends InjectedIntlProps {\n id: string\n }\n \n export const IOMessage: Component<IOMessageProps>\n }\n \n```"
}
] |
code_store-on-localhost_536219ce
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/queries/productRecommendations.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery ProductRecommendations(\n $identifier: ProductUniqueIdentifier\n $type: CrossSelingInputEnum\n) {\n productRecommendations(identifier: $identifier, type: $type)\n @context(provider: \"vtex.search-graphql\") {\n cacheId\n productId\n productName\n description\n link\n linkText\n brand\n brandId\n categories\n priceRange {\n sellingPrice {\n highPrice\n lowPrice\n }\n listPrice {\n highPrice\n lowPrice\n }\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n items {\n name\n itemId\n measurementUnit\n unitMultiplier\n referenceId {\n Value\n }\n images {\n imageId\n imageLabel\n imageTag\n imageUrl\n imageText\n }\n sellers {\n sellerId\n sellerName\n addToCartLink\n sellerDefault\n commertialOffer {\n Price\n ListPrice\n PriceWithoutDiscount\n RewardValue\n PriceValidUntil\n AvailableQuantity\n Tax\n CacheVersionUsedToCallCheckout\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n teasers {\n name\n }\n discountHighlights {\n name\n }\n }\n }\n }\n properties {\n name\n values\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_8752a75d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/queries/productsQuery.gql from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Products(\n $category: String\n $collection: String\n $specificationFilters: [String]\n $orderBy: String\n $from: Int\n $to: Int\n $hideUnavailableItems: Boolean = false\n $skusFilter: ItemsFilter = ALL_AVAILABLE\n) {\n products(\n category: $category\n collection: $collection\n specificationFilters: $specificationFilters\n orderBy: $orderBy\n from: $from\n to: $to\n hideUnavailableItems: $hideUnavailableItems\n ) @context(provider: \"vtex.search-graphql\") {\n cacheId\n productId\n productName\n productReference\n description\n link\n linkText\n brand\n brandId\n categories\n priceRange {\n sellingPrice {\n highPrice\n lowPrice\n }\n listPrice {\n highPrice\n lowPrice\n }\n }\n specificationGroups {\n name\n specifications {\n name\n values\n }\n }\n items(filter: $skusFilter) {\n name\n itemId\n measurementUnit\n unitMultiplier\n referenceId {\n Value\n }\n images {\n imageUrl\n imageTag\n imageLabel\n }\n variations {\n name\n values\n }\n sellers {\n sellerId\n commertialOffer {\n Installments(criteria: MAX) {\n Value\n InterestRate\n TotalValuePlusInterestRate\n NumberOfInstallments\n Name\n }\n AvailableQuantity\n Price\n PriceWithoutDiscount\n ListPrice\n teasers {\n name\n }\n discountHighlights {\n name\n }\n }\n }\n }\n productClusters {\n id\n name\n }\n properties {\n name\n values\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_9499b1a0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/normalize.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nfunction getBuyableSellers(sellers) {\n return sellers && sellers.length > 0\n ? sellers.filter(seller => seller.sellerId)\n : sellers\n}\n\nexport function normalizeBuyable(product) {\n if (!product || !product.items || product.items.length === 0) {\n return product\n }\n\n const buyableItems = product.items\n .map(item => ({\n ...item,\n sellers: getBuyableSellers(item.sellers),\n }))\n .filter(item => item && item.sellers && item.sellers.length > 0)\n\n return buyableItems ? { ...product, items: buyableItems } : null\n}\n\n```"
}
] |
code_store-on-localhost_40437c7c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/paddingEnum.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { pluck, values } from 'ramda'\n\nconst gapPaddingTypes = {\n NONE: {\n name: 'admin/editor.shelf.gapType.none',\n value:'ph0',\n },\n SMALL: {\n name: 'admin/editor.shelf.gapType.small',\n value:'ph3',\n },\n MEDIUM: {\n name: 'admin/editor.shelf.gapType.medium',\n value:'ph5',\n },\n LARGE: {\n name: 'admin/editor.shelf.gapType.large',\n value:'ph7',\n },\n}\n\nexport const getGapPaddingNames = () => values(pluck('name', gapPaddingTypes))\n\nexport const getGapPaddingValues = () => values(pluck('value', gapPaddingTypes))\n\nexport default gapPaddingTypes\n```"
}
] |
code_store-on-localhost_69f24474
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/OrdenationTypes.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst ordenationTypes = {\n ORDER_BY_RELEVANCE: {\n name: 'admin/editor.shelf.orderType.relevance',\n value: '',\n },\n ORDER_BY_TOP_SALE_DESC: {\n name: 'admin/editor.shelf.orderType.sales',\n value: 'OrderByTopSaleDESC',\n },\n ORDER_BY_PRICE_DESC: {\n name: 'admin/editor.shelf.orderType.priceDesc',\n value: 'OrderByPriceDESC',\n },\n ORDER_BY_PRICE_ASC: {\n name: 'admin/editor.shelf.orderType.priceAsc',\n value: 'OrderByPriceASC',\n },\n ORDER_BY_NAME_ASC: {\n name: 'admin/editor.shelf.orderType.nameAsc',\n value: 'OrderByNameASC',\n },\n ORDER_BY_NAME_DESC: {\n name: 'admin/editor.shelf.orderType.nameDesc',\n value: 'OrderByNameDESC',\n },\n ORDER_BY_RELEASE_DATE_DESC: {\n name: 'admin/editor.shelf.orderType.releaseDate',\n value: 'OrderByReleaseDateDESC',\n },\n ORDER_BY_BEST_DISCOUNT_DESC: {\n name: 'admin/editor.shelf.orderType.discount',\n value: 'OrderByBestDiscountDESC',\n },\n}\n\nexport function getOrdenationNames() {\n const names = []\n for (const key in ordenationTypes) {\n names.push(ordenationTypes[key].name)\n }\n return names\n}\n\nexport function getOrdenationValues() {\n const values = []\n for (const key in ordenationTypes) {\n values.push(ordenationTypes[key].value)\n }\n return values\n}\n\nexport default ordenationTypes\n\n```"
}
] |
code_store-on-localhost_5c2e1f62
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/propTypes.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nimport { getScrollValues } from './ScrollTypes'\nimport { getGapPaddingValues } from './paddingEnum'\n\nexport const shelfItemPropTypes = {\n item: PropTypes.shape({\n productId: PropTypes.string.isRequired,\n productName: PropTypes.string.isRequired,\n description: PropTypes.string.isRequired,\n categories: PropTypes.array,\n link: PropTypes.string.isRequired,\n linkText: PropTypes.string.isRequired,\n brandId: PropTypes.number,\n brand: PropTypes.string.isRequired,\n items: PropTypes.arrayOf(\n PropTypes.shape({\n itemId: PropTypes.string.isRequired,\n name: PropTypes.string.isRequired,\n referenceId: PropTypes.arrayOf(\n PropTypes.shape({\n Value: PropTypes.string.isRequired,\n })\n ),\n images: PropTypes.arrayOf(\n PropTypes.shape({\n imageUrl: PropTypes.string.isRequired,\n imageTag: PropTypes.string.isRequired,\n })\n ).isRequired,\n sellers: PropTypes.arrayOf(\n PropTypes.shape({\n commertialOffer: PropTypes.shape({\n /** SKU installments */\n Installments: PropTypes.arrayOf(\n PropTypes.shape({\n /** Installment value */\n Value: PropTypes.number.isRequired,\n /** Interest rate (zero if interest-free) */\n InterestRate: PropTypes.number.isRequired,\n /** Calculated total value */\n TotalValuePlusInterestRate: PropTypes.number,\n /** Number of installments */\n NumberOfInstallments: PropTypes.number.isRequired,\n /** Installments offer name */\n Name: PropTypes.string,\n })\n ),\n Price: PropTypes.number.isRequired,\n ListPrice: PropTypes.number.isRequired,\n }).isRequired,\n })\n ).isRequired,\n })\n ).isRequired,\n }),\n summary: PropTypes.any,\n position: PropTypes.number,\n}\n\nexport const productListSchemaPropTypes = {\n /** Maximum number of items in the shelf. */\n maxItems: PropTypes.number.isRequired,\n /** Maximum number of items in a page. */\n itemsPerPage: PropTypes.number.isRequired,\n /** Minimum number of items in a page. */\n minItemsPerPage: PropTypes.number,\n /** Scroll options. */\n scroll: PropTypes.oneOf(getScrollValues()),\n /** If the arrows are showable or not. */\n arrows: PropTypes.bool.isRequired,\n /** Show value of the title. */\n showTitle: PropTypes.bool,\n /** Text value of the title. */\n titleText: PropTypes.string,\n /** Product Summary schema props */\n summary: PropTypes.any,\n}\n\nexport const shelfContentPropTypes = {\n /** List of products */\n products: PropTypes.arrayOf(shelfItemPropTypes.item),\n /** Max Items per page */\n itemsPerPage: PropTypes.number,\n /** Minimum Items per page */\n minItemsPerPage: PropTypes.number,\n /** Max items in shelf */\n maxItems: PropTypes.number.isRequired,\n /** Show Arrows */\n arrows: PropTypes.bool.isRequired,\n /** Scroll type */\n scroll: PropTypes.string.isRequired,\n /** Should display navigation dots below the Shelf */\n paginationDotsVisibility: PropTypes.oneOf([\n 'visible',\n 'hidden',\n 'desktopOnly',\n 'mobileOnly',\n ]),\n /** Container width */\n width: PropTypes.number,\n /** Props to ProductsSummary */\n summary: PropTypes.any,\n /** Is mobile */\n isMobile: PropTypes.bool,\n /** Gap between Shelf Items */\n gap: PropTypes.oneOf(getGapPaddingValues()),\n}\n\n```"
}
] |
code_store-on-localhost_d6aa948b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/ScrollTypes.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst scrollTypes = {\n BY_PAGE: {\n name: 'admin/editor.shelf.scrollType.byPage',\n value: 'BY_PAGE',\n },\n ONE_BY_ONE: {\n name: 'admin/editor.shelf.scrollType.oneByOne',\n value: 'ONE_BY_ONE',\n },\n}\n\nexport function getScrollNames() {\n const names = []\n for (const key in scrollTypes) {\n names.push(scrollTypes[key].name)\n }\n return names\n}\n\nexport function getScrollValues() {\n const values = []\n for (const key in scrollTypes) {\n values.push(scrollTypes[key].value)\n }\n return values\n}\n\nexport default scrollTypes\n\n```"
}
] |
code_store-on-localhost_8a299fca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/utils/resolvePaginationDots.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport function resolvePaginationDotsVisibility(visibility, isMobile) {\n return !!(\n visibility === 'visible' ||\n (visibility === 'mobileOnly' && isMobile) ||\n (visibility === 'desktopOnly' && !isMobile)\n )\n}\n\n```"
}
] |
code_store-on-localhost_da8d8446
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/ShelfItem.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useMemo, useCallback, useEffect } from 'react'\nimport { assocPath } from 'ramda'\nimport { useInView } from 'react-intersection-observer'\nimport ProductListContext from '../../ProductListContext/ProductListContext'\n\n\nimport {usePixel} from '../../PixelContext/PixelContext'\nimport ProductSummaryShelf from '../../ProductSummary/ProductSummaryCustom'\nimport ProductSummaryImage from '../../ProductSummary/ProductSummaryImage'\nimport ProductSummarySpecificationBadges from '../../ProductSummary/ProductSummarySpecificationBadges'\nimport ProductSummaryName from '../../ProductSummary/ProductSummaryName'\nimport ProductSummarySpacer from '../../ProductSummary/Spacer'\nimport ProductSummaryPrice from '../../ProductSummary/ProductSummaryPrice'\n// import RatingInline from '../../ReviewsRatings/RatingInline'\nimport AddToCartBtn from '../../AddToCartButton/Wrapper'\nimport StackLayout from '../../StackLayout'\n\nconst { useProductListDispatch } = ProductListContext\n/**\n * ShelfItem Component. Normalizes the item received in the props\n * to adapt to the extension point prop.\n */\nconst ShelfItem = ({ item, summary }) => {\n const { push } = usePixel()\n const newSummary = useMemo(() => assocPath(['name', 'tag'], 'h2', summary), [\n summary,\n ])\n const product = useMemo(\n () => ProductSummaryShelf.mapCatalogProductToProductSummary(item),\n [item]\n )\n\n const pushPixelProductClick = useCallback(() => {\n push({\n event: 'productClick',\n product: product,\n })\n }, [product, push])\n\n const [inViewRef, inView] = useInView({\n // Triggers the event when the element is 75% visible\n threshold: 0.75,\n triggerOnce: true,\n })\n\n const dispatch = useProductListDispatch()\n\n useEffect(() => {\n if (inView) {\n dispatch({ type: 'SEND_IMPRESSION', args: { product: product } })\n }\n }, [dispatch, inView, product])\n return (\n <ProductSummaryShelf containerRef={inViewRef} product={product} actionOnClick={pushPixelProductClick} {...newSummary}>\n <StackLayout>\n <ProductSummaryImage />\n <ProductSummarySpecificationBadges specificationGroupName=\"Group\" specificationName=\"On Sale\" visibleWhen=\"True\" displayValue=\"SPECIFICATION_NAME\" />\n </StackLayout>\n <ProductSummaryName />\n <ProductSummarySpacer />\n <ProductSummaryPrice />\n <AddToCartBtn />\n </ProductSummaryShelf>\n )\n\n // return (\n // <ExtensionPoint\n // id=\"product-summary\"\n // containerRef={inViewRef}\n // product={product}\n // actionOnClick={pushPixelProductClick}\n // {...newSummary}\n // />\n // )\n}\n\nexport default ShelfItem\n\n```"
}
] |
code_store-on-localhost_5162b805
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/shelf.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.arrow {\n top: 50%;\n transform: translate(0, -50%);\n}\n\n.dot {\n height: 0.625rem;\n width: 0.625rem;\n}\n\n```"
}
] |
code_store-on-localhost_846c4833
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/ProductList.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Fragment } from 'react'\nimport ReactResizeDetector from 'react-resize-detector'\nimport IOMessage from '../../NativeTypes/IOMessage'\nimport useCssHandles from '../../CssHandles/useCssHandles'\n\nimport {\n productListSchemaPropTypes,\n shelfItemPropTypes,\n} from '../utils/propTypes'\nimport ScrollTypes from '../utils/ScrollTypes'\nimport GapPaddingTypes from '../utils/paddingEnum'\nimport ShelfContent from './ShelfContent'\nimport ProductListEventCaller from './ProductListEventCaller'\n\nconst CSS_HANDLES = ['title']\n\nconst DEFAULT_MAX_ITEMS = 10\nconst DEFAULT_ITEMS_PER_PAGE = 5\nconst DEFAULT_MIN_ITEMS_PER_PAGE = 1\n\n/**\n * Product List Component. Shows a collection of products.\n */\nconst ProductList = ({\n gap,\n arrows,\n scroll,\n summary,\n maxItems,\n products,\n isMobile,\n autoplay,\n showTitle,\n titleText,\n itemsPerPage,\n minItemsPerPage,\n paginationDotsVisibility,\n navigationStep: navigationStepProp,\n}) => {\n const handles = useCssHandles(CSS_HANDLES)\n const navigationStep = isNaN(parseInt(navigationStepProp)) ? navigationStepProp : parseInt(navigationStepProp)\n\n return products && !products.length ? null : (\n <Fragment>\n {showTitle && (\n <div\n className={`${handles.title} t-heading-2 fw3 w-100 flex justify-center pt7 pb6 c-muted-1`}\n >\n <IOMessage id={titleText} />\n </div>\n )}\n <ReactResizeDetector handleWidth>\n {width => (\n <ShelfContent\n gap={gap}\n width={width.width}\n arrows={arrows}\n scroll={scroll}\n summary={summary}\n products={products}\n maxItems={maxItems}\n isMobile={isMobile}\n autoplay={autoplay}\n itemsPerPage={itemsPerPage}\n navigationStep={navigationStep}\n minItemsPerPage={minItemsPerPage}\n paginationDotsVisibility={paginationDotsVisibility}\n />\n )}\n </ReactResizeDetector>\n <ProductListEventCaller />\n </Fragment>\n )\n}\n\nProductList.defaultProps = {\n maxItems: DEFAULT_MAX_ITEMS,\n minItemsPerPage: DEFAULT_MIN_ITEMS_PER_PAGE,\n itemsPerPage: DEFAULT_ITEMS_PER_PAGE,\n scroll: ScrollTypes.BY_PAGE.value,\n gap: GapPaddingTypes.SMALL.value,\n arrows: true,\n showTitle: true,\n titleText: null,\n isMobile: false,\n}\n\nProductList.propTypes = {\n /** Loading status */\n loading: PropTypes.bool,\n /** Graphql data response. */\n products: PropTypes.arrayOf(shelfItemPropTypes.item),\n /** Verifies if is a mobile device. */\n isMobile: PropTypes.bool,\n /** Should display navigation dots below the Shelf */\n paginationDotsVisibility: PropTypes.oneOf([\n 'visible',\n 'hidden',\n 'desktopOnly',\n 'mobileOnly',\n ]),\n ...productListSchemaPropTypes,\n}\n\nProductList.schema = {\n title: 'admin/editor.shelf.title',\n}\n\nexport default ProductList\n\n```"
}
] |
code_store-on-localhost_bb7b9a65
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/ProductListEventCaller.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport useProductImpression from '../../ProductListContext/useProductImpression'\n\nconst ProductListEventCaller = () => {\n useProductImpression()\n return null\n}\n\nexport default ProductListEventCaller\n\n```"
}
] |
code_store-on-localhost_609a7472
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/ShelfContent.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { path } from 'ramda'\nimport React, { Component } from 'react'\nimport IconCaret from '../../StoreIcons/IconCaret'\nimport classNames from 'classnames'\nimport { NoSSR } from '../../../../../vtex.render-runtime'\nimport Dots from '../../Slider/Dots'\nimport Slide from '../../Slider/Slide'\nimport Slider from '../../Slider/Slider'\nimport SliderContainer from '../../Slider/SliderContainer'\nimport withCssHandles from '../../CssHandles/withCssHandles'\nimport { resolvePaginationDotsVisibility } from '../utils/resolvePaginationDots'\nimport ScrollTypes from '../utils/ScrollTypes'\nimport ShelfItem from './ShelfItem'\nimport { shelfContentPropTypes } from '../utils/propTypes'\nimport shelf from './shelf.css'\n\nconst CSS_HANDLES = ['arrow', 'arrowLeft', 'arrowRight', 'shelfContentContainer', 'sliderContainer', 'slide']\nconst SLIDER_WIDTH_ONE_ELEMENT = 320\nconst SLIDER_WIDTH_TWO_ELEMENTS = 500\nconst SLIDER_WIDTH_THREE_ELEMENTS = 750\nconst SLIDER_WIDTH_FOUR_ELEMENTS = 1000\nconst SLIDER_WIDTH_FIVE_ELEMENTS = 1290\nconst DEFAULT_SHELF_ITEM_WIDTH = 260\n\n/**\n * ShelfContent Component. Executes the interaction with react-slick\n * and render the properly content of the Shelf depending of edit mode state.\n */\nclass ShelfContent extends Component {\n constructor(props) {\n super(props)\n this.perPage = {\n [SLIDER_WIDTH_FIVE_ELEMENTS]: 5,\n [SLIDER_WIDTH_FOUR_ELEMENTS]: 4,\n [SLIDER_WIDTH_THREE_ELEMENTS]: 3,\n [SLIDER_WIDTH_TWO_ELEMENTS]: 2,\n [SLIDER_WIDTH_ONE_ELEMENT]: 1,\n }\n this.calcItemsPerPage()\n this.state = {\n currentSlide: 0,\n firstRender: true,\n }\n }\n\n calcItemsPerPage = () => {\n const { itemsPerPage } = this.props\n for (let key in this.perPage) {\n if (this.perPage[key] > itemsPerPage) delete this.perPage[key]\n }\n }\n\n handleChangeSlide = i => {\n this.setState({ currentSlide: i })\n }\n\n handleNextSlide = () => {\n const { currentSlide } = this.state\n const { itemsPerPage, maxItems, products, isMobile } = this.props\n const productList =\n !products || !products.length ? Array(maxItems).fill(null) : products\n const totalItems = productList.slice(0, maxItems).length\n const customPerPage = (!isMobile && itemsPerPage) || this.perPage\n const nextSlide = ((currentSlide) % totalItems) + customPerPage\n this.handleChangeSlide(nextSlide)\n }\n\n componentDidMount() {\n this.setState({\n firstRender: false,\n })\n }\n\n arrowRender = ({ orientation, onClick }) => {\n const { gap, cssHandles } = this.props\n const containerClasses = classNames(\n shelf.arrow,\n 'pointer z-1 flex absolute',\n {\n [`${cssHandles.arrowLeft} left-0 ${gap}`]: orientation === 'left',\n [`${cssHandles.arrowRight} right-0 ${gap}`]: orientation === 'right',\n }\n )\n return (\n <div className={containerClasses} onClick={onClick}>\n <IconCaret orientation={orientation} thin size={20} />\n </div>\n )\n }\n\n roundHalf = num => Math.round(num * 2) / 2\n\n render() {\n const {\n gap,\n scroll,\n arrows,\n summary,\n autoplay,\n isMobile,\n maxItems,\n products,\n cssHandles,\n itemsPerPage,\n navigationStep,\n minItemsPerPage,\n paginationDotsVisibility,\n } = this.props\n\n const { currentSlide } = this.state\n const showPaginationDots = resolvePaginationDotsVisibility(\n paginationDotsVisibility,\n isMobile\n )\n\n const isScrollByPage = scroll === ScrollTypes.BY_PAGE.value\n\n const productList =\n !products || !products.length ? Array(maxItems).fill(null) : products\n\n const roundedMinItems = this.roundHalf(minItemsPerPage)\n const customPerPage = !isMobile && itemsPerPage\n\n return (\n <div className={`${cssHandles.shelfContentContainer} flex justify-center`}>\n <SliderContainer\n autoplay={autoplay}\n onNextSlide={this.handleNextSlide}\n className={`${cssHandles.sliderContainer} w-100 mw9`}\n >\n <Slider\n loop\n easing=\"ease\"\n duration={500}\n minPerPage={roundedMinItems}\n scrollByPage={isScrollByPage}\n navigationStep={navigationStep}\n currentSlide={Math.ceil(currentSlide)}\n onChangeSlide={this.handleChangeSlide}\n perPage={customPerPage || this.perPage}\n arrowRender={arrows && this.arrowRender}\n >\n {productList.slice(0, maxItems).map((item, index) => (\n <Slide\n sliderTransitionDuration={500}\n className={classNames('justify-center h-100', gap, cssHandles.slide)}\n key={path(['productId'], item) || index}\n defaultWidth={DEFAULT_SHELF_ITEM_WIDTH}\n >\n <ShelfItem item={item} summary={summary} />\n </Slide>\n ))}\n </Slider>\n {showPaginationDots && (\n <NoSSR>\n <Dots\n loop\n showDotsPerPage={isScrollByPage}\n minPerPage={roundedMinItems}\n perPage={this.perPage}\n currentSlide={Math.ceil(currentSlide)}\n totalSlides={productList.slice(0, maxItems).length}\n onChangeSlide={this.handleChangeSlide}\n classes={{\n root: 'pt4',\n notActiveDot: 'bg-muted-3',\n dot: classNames(shelf.dot, 'mh2 mv0 pointer br-100'),\n activeDot: 'bg-emphasis',\n }}\n />\n </NoSSR>\n )}\n </SliderContainer>\n </div>\n )\n }\n}\n\nShelfContent.defaultProps = {\n itemsPerPage: 5,\n minItemsPerPage: 1,\n paginationDotsVisibility: 'visible',\n}\n\nShelfContent.propTypes = {\n /** List of products */\n products: shelfContentPropTypes.products,\n /** Max Items per page */\n itemsPerPage: shelfContentPropTypes.itemsPerPage,\n /** Minimum Items per page */\n minItemsPerPage: shelfContentPropTypes.minItemsPerPage,\n /** Max items in shelf */\n maxItems: shelfContentPropTypes.maxItems,\n /** Show Arrows */\n arrows: shelfContentPropTypes.arrows,\n /** Scroll type */\n scroll: shelfContentPropTypes.scroll,\n /** Should display navigation dots below the Shelf */\n paginationDotsVisibility: shelfContentPropTypes.paginationDotsVisibility,\n /** Container width */\n width: shelfContentPropTypes.width,\n /** Props to ProductsSummary */\n summary: shelfContentPropTypes.summary,\n /** Is mobile */\n isMobile: shelfContentPropTypes.isMobile,\n /** Gap between Shelf Items */\n gap: shelfContentPropTypes.gap,\n}\n\nexport default withCssHandles(CSS_HANDLES)(ShelfContent)\n\n```"
}
] |
code_store-on-localhost_0829ccbd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/TabbedShelf/Tabs.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport classNames from 'classnames'\nimport useCssHandles from '../CssHandles/useCssHandles'\n\nconst CSS_HANDLES = ['itemContainer', 'itemContainerSelected', 'itemContainerUnselected', 'tabsContainer', 'tabsNamesContainer', 'shelfContainer', 'tabButton']\n\nclass Tabs extends Component {\n\n state = {\n selectedIndex: 0\n }\n\n handleClick = (index) => this.setState({ selectedIndex: index })\n\n render() {\n const { panes, cssHandles } = this.props\n const { selectedIndex } = this.state\n if (!panes || panes.length === 0) {\n return null\n }\n\n return (\n <div className=\"flex justify-center items-center\">\n <div className={`${cssHandles.tabsContainer} flex-ns pa6-ns justify-between-ns w-100-s`}>\n <div className={`${cssHandles.tabsNamesContainer} flex flex-column mh6`}>\n {panes.map((pane, index) => {\n const isSelected = index === selectedIndex\n const isLast = index === panes.length - 1\n const itemContainer = classNames(`t-body pa4 tl bb b--muted-4 ${cssHandles.itemContainer}`, {\n [`bg-base--inverted c-on-muted-1 ${cssHandles.itemContainerSelected}`]: isSelected,\n [cssHandles.itemContainerUnselected]: !isSelected,\n 'bw0': isLast,\n })\n return (\n <button \n type=\"button\"\n onClick={() => this.handleClick(index)}\n className={`${cssHandles.tabButton} bn outline-0 bg-transparent pa0`}\n >\n <div className={itemContainer} key={pane.menuItem} >{pane.menuItem}</div>\n </button>\n )\n })}\n </div>\n <div className={`${cssHandles.shelfContainer} mh6-s mw-100 overflow-hidden`}>\n {panes[selectedIndex].render()}\n </div>\n </div>\n </div>\n )\n }\n}\n\nexport default withCssHandles(CSS_HANDLES)(Tabs)\n\n```"
}
] |
code_store-on-localhost_f7804b86
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/TabbedShelf/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\nimport React, { Fragment, Component } from 'react'\nimport Button from '../../../Styleguide/Button'\nimport { withRuntimeContext } from '../../../../../../vtex.render-runtime'\nimport Tabs from './Tabs'\nimport Shelf from '../../Shelf'\nimport withCssHandles from '../../../CssHandles/withCssHandles'\nimport tabbedShelf from './tabbedShelf.css'\n\nconst MAX_NUMBER_OF_MENUS = 6\nconst CSS_HANDLES = ['headline'] \n\n/**\n * Tabbed Shelf Module\n */\nclass TabbedShelf extends Component {\n\n /**\n * The prop types for this component\n * Used for type checking\n */\n static propTypes = {\n isEnabled: PropTypes.bool,\n headline: PropTypes.string,\n bottomText: PropTypes.string,\n tabs: PropTypes.PropTypes.arrayOf(PropTypes.shape({\n id: PropTypes.number,\n __editorItemTitle: PropTypes.string,\n })),\n shelf: PropTypes.object,\n };\n\n /**\n * Default prop types for this component\n */\n static defaultProps = {\n isEnabled: false,\n headline: '',\n bottomText: '',\n tabs: [],\n shelf: {},\n };\n\n /**\n * Handle primary call to action button click\n */\n handleButtonClick(url) {\n if(url != undefined && url != '') {\n window.open(url.buttunUrl,\"_self\");\n }\n }\n\n /**\n * Return the component\n *\n * @returns {*}\n */\n render() {\n const {\n isEnabled,\n headline,\n bottomText,\n buttunUrl,\n buttonText,\n tabs,\n cssHandles\n } = this.props\n\n const panes = (tabs.length > 0 ? tabs.map(tab => (\n { menuItem: tab.__editorItemTitle, render: () => (\n <Shelf\n {...{ ...this.props.shelf }}\n category={tab.id}\n />\n )\n }\n )) : '');\n\n return (\n <Fragment>\n {isEnabled ? (\n <div className={`${tabbedShelf.container}`}>\n <h3 className={`${cssHandles.headline}`}>{headline}</h3>\n <Tabs panes={panes} />\n <div className={`${tabbedShelf.blockContainer}`}>\n <p className={`${tabbedShelf.blockText}`}>{bottomText}</p>\n {buttonText ? (\n <div className={`${tabbedShelf.buttonContainer}`}>\n <Button onClick={() => this.handleButtonClick({buttunUrl})}>{buttonText}</Button>\n </div>\n ) : ('')}\n </div>\n </div>\n ) : null\n }\n </Fragment>\n );\n }\n}\n\n/**\n * Schema for component to allow configuration of props from admin configuration\n */\nTabbedShelf.getSchema = props => ({\n title: 'admin/editor.tabbed-shelf.title',\n description: 'admin/editor.tabbed-shelf.description',\n type: 'object',\n properties: {\n isEnabled: {\n title: 'admin/editor.tabbed-shelf.isEnabled.title',\n type: 'boolean',\n default: false,\n },\n headline: {\n title: 'admin/editor.tabbed-shelf.headline',\n type: 'string',\n },\n bottomText: {\n title: 'admin/editor.tabbed-shelf.bottomText',\n type: 'string',\n widget: {\n 'ui:widget': 'textarea',\n },\n },\n buttonText: {\n title: 'admin/editor.tabbed-shelf.buttonText',\n type: 'string',\n },\n buttunUrl: {\n title: 'admin/editor.tabbed-shelf.buttonUrl',\n type: 'string',\n },\n tabs: {\n title:'admin/editor.tabbed-shelf.tabs',\n type: 'array',\n minItems: 0,\n maxItems: MAX_NUMBER_OF_MENUS,\n items: {\n title: 'admin/editor.tabbed-shelf.tabs.items',\n type: 'object',\n properties: {\n id: {\n title: 'admin/editor.tabbed-shelf.tabs.items.id',\n type: 'number',\n },\n },\n },\n },\n shelf: {\n title: 'admin/editor.tabbed-shelf.shelf.title',\n type: 'object',\n properties: Shelf.getSchema(props).properties,\n },\n },\n});\n\nexport default withRuntimeContext(injectIntl(withCssHandles(CSS_HANDLES)(TabbedShelf)))\n\n```"
}
] |
code_store-on-localhost_7c564ff4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Shelf/components/TabbedShelf/tabbedShelf.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container {\n display:block;\n}\n\n.container .mh7-ns,\n.container .pv4,\n.container .pb7 {\n margin:0 0 0 25px;\n padding:0;\n}\n\n.blockContainer {\n font-size: .625em;\n width: 15%;\n position: absolute;\n margin-top: -320px;\n color: #45474a;\n line-height: 17px;\n}\n\n.blockContainer:after {\n clear:both;\n}\n\n.blockText {\n margin:0 0 19px;\n}\n\n.buttonContainer {\n margin: 0 !important;\n padding: 8px 20px !important;\n text-transform: inherit;\n font-size: 16px !important;\n}\n\n@media only screen and (max-width: 1047px) {\n .blockContainer {\n margin-top: -300px;\n }\n}\n\n@media only screen and (max-width: 854px) {\n .blockContainer {\n margin-top: -280px;\n }\n}\n\n@media only screen and (max-width: 821px) {\n .blockContainer {\n margin-top: -320px;\n }\n}\n\n@media only screen and (max-width: 639px) {\n .blockContainer {\n margin-top: -220px;\n width:25%;\n }\n}\n\n/* Switch to mobile tabs */\n@media only screen and (max-width: 570px) {\n .blockContainer {\n margin-top: 45px;\n width: 100%;\n position: relative;\n }\n}\n\n```"
}
] |
code_store-on-localhost_7a856c32
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/storefront.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent, ReactElement } from 'react'\n\ndeclare global {\n interface StorefrontFC<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```"
}
] |
code_store-on-localhost_c89539ba
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/jsx.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport 'react'\n\ndeclare module 'react' {\n interface ImgHTMLAttributes<T> extends HTMLAttributes<T> {\n loading?: 'lazy' | 'eager' | 'auto';\n }\n}\n```"
}
] |
code_store-on-localhost_7fe86a96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.css-handles.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n const useCssHandles: any\n}\n```"
}
] |
code_store-on-localhost_f753dd13
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.responsive-values.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.responsive-values' {\n const useResponsiveValues: (input: any) => any\n const useResponsiveValue: <T>(input: MaybeResponsiveInput<T>) => T\n\n enum InputDevices {\n mobile = 'mobile',\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n }\n\n enum OutputDevices {\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n }\n\n type ResponsiveInput<T> = { [P in keyof typeof InputDevices]?: T }\n type MaybeResponsiveInput<T> = T | ResponsiveInput<T>\n\n type ResponsiveOutput<T> = { [P in keyof typeof OutputDevices]: T }\n}\n\n```"
}
] |
code_store-on-localhost_bab8fb1f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.product-context.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Seller {\n commertialOffer: {\n AvailableQuantity: number\n }\n}\n\ninterface ProductItem {\n itemId: string\n name: string\n images: Image[]\n variations: {\n name: string\n values: string[]\n }[]\n sellers: {\n commertialOffer: {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n }\n }[]\n}\n\ninterface Product {\n itemMetadata: ItemMetadata\n items: ProductItem[]\n skuSpecifications: SkuSpecification[]\n}\n\ninterface SkuSpecification {\n field: SkuSpecificationField\n values: SkuSpecificationValues[]\n}\n\ninterface SkuSpecificationField {\n name: string\n}\n\ninterface SkuSpecificationValues {\n name: string\n}\n\ndeclare module 'vtex.product-context/useProduct' {\n type GroupId = string\n\n interface AssemblyOptionItem {\n id: string\n quantity: number\n seller: string\n initialQuantity: number\n choiceType: string\n name: string\n price: number\n children: Record<string, AssemblyOptionItem[]> | null\n }\n\n type InputValues = Record<string, string>\n\n export interface ProductContext {\n product?: Product,\n selectedItem: ProductItem | null,\n selectedQuantity: number\n skuSelector: {\n isVisible: boolean\n areAllVariationsSelected: boolean\n }\n buyButton: {\n clicked: boolean\n }\n assemblyOptions: {\n items: Record<GroupId, AssemblyOptionItem[]>\n inputValues: Record<GroupId, InputValues>\n areGroupsValid: Record<GroupId, boolean>\n }\n }\n\n const useProduct: () => ProductContext\n export default useProduct\n}\n\ndeclare module 'vtex.product-context/ProductDispatchContext' {\n type DispatchFunction = (payload: { type: string; args?: any }) => void\n export const useProductDispatch: () => DispatchFunction\n}\n\ndeclare module 'vtex.product-context' {\n export const ProductContext\n}\n```"
}
] |
code_store-on-localhost_7553cb72
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.render-runtime.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n interface Runtime {\n setQuery: (vars: { skuId: string }, options?: { replace?: boolean } ) => void\n query?: { skuId?: string }\n }\n export const useRuntime: () => Runtime\n}\n\n```"
}
] |
code_store-on-localhost_a47ac298
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.native-types.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// import { ComponentType } from 'react'\n\ndeclare module 'vtex.native-types' {\n import { ComponentType } from 'react'\n export const IOMessage: ComponentType<{\n id: string\n values: Record<string, any>\n ['data-testid']: string\n }>\n}\n\n```"
}
] |
code_store-on-localhost_544e9854
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/css.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```"
}
] |
code_store-on-localhost_ac8110f9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/product.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface Product {\n linkText: string\n productName: string\n brand: string\n categoryId: string\n categoryTree: Category[]\n productId: string\n titleTag: string\n metaTagDescription: string\n items: SKU[]\n skuSpecifications: SkuSpecification[]\n}\n\nexport interface Category {\n id: string\n name: string\n}\n\nexport interface SKU {\n itemId: string\n ean: string\n referenceId: [{ Value: string }]\n sellers: Seller[]\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n}\n\ninterface CommertialOffer {\n ListPrice: number\n Price: number\n}\n\ninterface Seller {\n commertialOffer: CommertialOffer\n}\n\ninterface CommertialOffer {\n AvailableQuantity: number\n}\n\ninterface SkuSpecification {\n field: SkuSpecificationField\n values: SkuSpecificationValues[]\n}\n\ninterface SkuSpecificationField {\n name: string\n}\n\ninterface SkuSpecificationValues {\n name: string\n}\n```"
}
] |
code_store-on-localhost_ee049ced
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/graphql.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n const graphql: any\n export default graphql\n}\n\n```"
}
] |
code_store-on-localhost_8c450176
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.store-resources.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-resources/OrderFormContext' {\n export const orderFormConsumer\n}\n```"
}
] |
code_store-on-localhost_63ba4dfa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/typings/vtex.styleguide.d.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const Checkbox: any\n export const Radio: any\n export const NumericStepper: any\n export const Button: any\n export const Modal: any\n export const withToast: any\n export const Tooltip: any\n export const EXPERIMENTAL_Select: any\n export const Dropdown: any\n}\n\n```"
}
] |
code_store-on-localhost_d9478d3c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SearchBar/styles.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.searchBarContainer :global(.vtex-input-prefix__group) {\n height: 38px;\n}\n\n.searchBarContainer input {\n color: #727273;\n border-radius: 1px;\n}\n\n.compactMode input {\n border-top-style: none !important;\n border-left-style: none !important;\n border-right-style: none !important;\n border-bottom: 2px solid !important;\n}\n\n.paddingInput input {\n -webkit-appearance: none;\n padding-left: 40px !important;\n}\n\n.searchMobile .vtex-button {\n padding: 0.9rem;\n font-weight: 400;\n font-size: 0.875rem;\n}\n\n.searchMobile input {\n border: none;\n}\n\n@media only screen and (max-width: 49rem) {\n .searchBarContainer input {\n box-shadow: none;\n }\n}\n\n```"
}
] |
code_store-on-localhost_443dee9f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SearchBar/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { injectIntl } from 'react-intl'\n\nimport SearchBar from './components/SearchBar'\n\n/** Canonical search bar that uses the autocomplete endpoint to search for a specific product*/\nclass SearchBarContainer extends Component {\n state = {\n inputValue: '',\n }\n\n handleClearInput = () => {\n this.setState({ inputValue: '' })\n }\n\n handleGoToSearchPage = () => {\n const search = this.state.inputValue\n const { customSearchPageUrl } = this.props\n\n if (this.props.attemptPageTypeSearch) {\n window.location.href = `/${search}`\n return\n }\n\n if (customSearchPageUrl) {\n this.context.navigate({\n to: customSearchPageUrl.replace(/\\$\\{term\\}/g, search),\n })\n\n return\n }\n\n // This param is only useful to track terms searched\n // See: https://support.google.com/analytics/answer/1012264\n const paramForSearchTracking = '&_q=' + search\n\n this.setState({ inputValue: '' })\n this.context.navigate({\n page: 'store.search',\n params: { term: search },\n query: 'map=ft' + paramForSearchTracking,\n fallbackToWindowLocation: false,\n })\n }\n\n handleInputChange = event => {\n this.setState({ inputValue: event.target.value })\n }\n\n render() {\n const {\n intl,\n compactMode,\n hasIconLeft,\n iconClasses,\n autoFocus,\n maxWidth,\n attemptPageTypeSearch,\n customSearchPageUrl,\n placeholder = intl.formatMessage({\n id: 'store/search.placeholder',\n }),\n autocompleteAlignment = 'right',\n openAutocompleteOnFocus = false,\n blurOnSubmit = false,\n submitOnIconClick = false,\n minSearchTermLength,\n autocompleteFullWidth = false,\n } = this.props\n\n const { inputValue } = this.state\n\n return (\n <SearchBar\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={autoFocus}\n placeholder={placeholder}\n inputValue={inputValue}\n onClearInput={this.handleClearInput}\n onGoToSearchPage={this.handleGoToSearchPage}\n onInputChange={this.handleInputChange}\n compactMode={compactMode}\n hasIconLeft={hasIconLeft}\n iconClasses={iconClasses}\n maxWidth={maxWidth}\n attemptPageTypeSearch={attemptPageTypeSearch}\n customSearchPageUrl={customSearchPageUrl}\n autocompleteAlignment={autocompleteAlignment}\n openAutocompleteOnFocus={openAutocompleteOnFocus}\n blurOnSubmit={blurOnSubmit}\n submitOnIconClick={submitOnIconClick}\n minSearchTermLength={minSearchTermLength}\n autocompleteFullWidth={autocompleteFullWidth}\n intl={intl}\n />\n )\n }\n}\n\nSearchBarContainer.contextTypes = {\n navigate: PropTypes.func,\n}\n\nSearchBarContainer.schema = {\n title: 'admin/editor.search-bar.title',\n}\n\nSearchBarContainer.propTypes = {\n /** Indentify when use the compact version of the component */\n compactMode: PropTypes.bool,\n /** Identify if the search icon is on left or right position */\n hasIconLeft: PropTypes.bool,\n /** Custom classes for the search icon */\n iconClasses: PropTypes.string,\n /** Identify if the search input should autofocus or not */\n autoFocus: PropTypes.bool,\n /** Max width of the search bar */\n maxWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /** Uses the term the user has inputed to try to navigate to the proper\n * page type (e.g. a department, a brand, a category)\n */\n attemptPageTypeSearch: PropTypes.bool,\n /** A template for a custom url. It can have a substring ${term} used as placeholder to interpolate the searched term. (e.g. `/search?query=${term}`) */\n customSearchPageUrl: PropTypes.string,\n placeholder: PropTypes.string,\n /* Autocomplete Horizontal alignment */\n autocompleteAlignment: PropTypes.string,\n /** Identify if autocomplete should be open on input focus or not */\n openAutocompleteOnFocus: PropTypes.bool,\n /** Identify if input should blur on submit */\n blurOnSubmit: PropTypes.bool,\n /** Identify if icon should submit on click */\n submitOnIconClick: PropTypes.bool,\n /** Minimum search term length allowed */\n minSearchTermLength: PropTypes.number,\n /** If true, the autocomplete will fill the whole window horizontally */\n autocompleteFullWidth: PropTypes.bool,\n}\n\nexport default injectIntl(SearchBarContainer)\n\n```"
}
] |
code_store-on-localhost_a03bcc1c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/SearchBar/setupTests.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { configure } from 'enzyme'\nimport Adapter from 'enzyme-adapter-react-16'\n\nconfigure({ adapter: new Adapter() })\n\n```"
}
] |
code_store-on-localhost_e9c7e9eb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/assemblyUtils.test.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n transformAssemblyOptions,\n ItemOption,\n InputValuesOption,\n} from './assemblyUtils'\nimport { customBell, comboPizza, starColor } from './__mocks__/assemblyOptions'\n\ntest('should transform assemblyOptions', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultBell = transformAssemblyOptions(\n customBell.items,\n {},\n parentPrice,\n parentQuantity\n )\n\n expect(resultBell.options).toHaveLength(5)\n const addonOption = resultBell.options[0] as ItemOption\n expect(addonOption.assemblyId).toBe('add-on_Add-on')\n expect(addonOption.id).toBe('2000588')\n expect(addonOption.quantity).toBe(1)\n expect(addonOption.seller).toBe('1')\n\n const resultPizza = transformAssemblyOptions(\n comboPizza.items,\n {},\n parentPrice,\n parentQuantity\n )\n\n expect(resultPizza.options).toHaveLength(2)\n const pizzaOption = resultPizza.options[0] as ItemOption\n expect(pizzaOption.assemblyId).toBe('pizza_composition_Pizza flavor')\n expect(pizzaOption.id).toBe('5101')\n expect(pizzaOption.quantity).toBe(1)\n expect(pizzaOption.seller).toBe('1')\n expect(pizzaOption.options).toHaveLength(3)\n\n const drinksOptions = resultPizza.options[1] as ItemOption\n expect(drinksOptions.options).toBeUndefined()\n})\n\ntest('input values', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultStar = transformAssemblyOptions(\n starColor.items,\n starColor.inputValues,\n parentPrice,\n parentQuantity\n )\n\n expect(resultStar.options).toHaveLength(1)\n const customization = resultStar.options[0] as InputValuesOption\n expect(customization.assemblyId).toBe('Customization')\n expect(customization.inputValues).toMatchObject({\n Font: 'Sans serif',\n 'Front text': 'Frente',\n 'Back text': 'Verso',\n 'Glossy print': true,\n })\n})\n\ntest('empty input values should result in empty options', () => {\n const parentPrice = 450\n const parentQuantity = 1\n\n const resultStar = transformAssemblyOptions(\n starColor.items,\n {\n Customization: {},\n },\n parentPrice,\n parentQuantity\n )\n expect(resultStar.options.length).toBe(0)\n})\n\n```"
}
] |
code_store-on-localhost_930ad747
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/StoreComponents/components/BuyButton/assemblyUtils.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype GroupId = string\ntype GroupTypes = 'SINGLE' | 'TOGGLE' | 'MULTIPLE'\n\nexport const sumAssembliesPrice = (\n assemblyOptions: Record<GroupId, AssemblyOptionItem[]>\n) => {\n const cleanAssemblies = assemblyOptions || {}\n const assembliesGroupItems = Object.values(cleanAssemblies)\n return assembliesGroupItems.reduce<number>(\n (sum: number, groupItems: AssemblyOptionItem[]) => {\n const groupPrice = groupItems.reduce<number>((groupSum, item) => {\n const childrenPrice: number = item.children\n ? sumAssembliesPrice(item.children)\n : 0\n const itemCost = item.price * item.quantity\n return groupSum + itemCost + childrenPrice * item.quantity\n }, 0)\n return groupPrice + sum\n },\n 0\n )\n}\n\ninterface AssemblyOptionItem {\n price: number\n choiceType: GroupTypes\n children: Record<GroupId, AssemblyOptionItem[]> | null\n name: string\n id: string\n initialQuantity: number\n quantity: number\n seller: string\n}\n\ntype InputValue = Record<string, string | boolean>\n\nexport interface AssemblyOptions {\n items: Record<GroupId, AssemblyOptionItem[]>\n inputValues: Record<GroupId, InputValue>\n areGroupsValid: Record<string, boolean>\n}\n\ntype Option = ItemOption | InputValuesOption\n\nexport interface ItemOption {\n assemblyId: string\n id: string\n quantity: number\n seller: string\n options?: Option[]\n}\n\nexport interface InputValuesOption {\n assemblyId: string\n inputValues: InputValue\n}\n\ninterface AddedItem {\n id: string\n name: string\n quantity: number\n sellingPrice: number\n sellingPriceWithAssemblies: number\n assemblyOptions?: ParsedAssemblyOptionsMeta\n}\n\ninterface CartAddedOption {\n normalizedQuantity: number\n extraQuantity: number\n choiceType: GroupTypes\n item: AddedItem\n}\n\ninterface CartRemovedOption {\n name: string\n initialQuantity: number\n removedQuantity: number\n}\n\ninterface ParsedAssemblyOptionsMeta {\n added: CartAddedOption[]\n removed: CartRemovedOption[]\n parentPrice: number\n}\n\ninterface ParsedAssemblyOptions {\n options: Option[]\n assemblyOptions: ParsedAssemblyOptionsMeta\n}\n\nexport const transformAssemblyOptions = (\n assemblyOptionsItems: Record<GroupId, AssemblyOptionItem[]> = {},\n inputValues: Record<GroupId, InputValue> = {},\n parentPrice: number,\n parentQuantity: number\n): ParsedAssemblyOptions => {\n // contains options sent as arguments to graphql mutation\n const options: Option[] = []\n\n // array with added assemblies data to show in minicart optimistic preview\n const added: CartAddedOption[] = []\n\n // array with removed assemblies data to show in minicart optimistic preview\n const removed: CartRemovedOption[] = []\n\n const assemblyItemsKeys: GroupId[] = Object.keys(assemblyOptionsItems)\n\n for (const groupId of assemblyItemsKeys) {\n const items = assemblyOptionsItems[groupId]\n for (const item of items) {\n const childrenAddedData = item.children\n ? transformAssemblyOptions(\n item.children,\n {},\n item.price,\n item.quantity * parentQuantity\n )\n : null\n\n const {\n options: childrenOptions,\n assemblyOptions: childrenAssemblyOptions,\n } = childrenAddedData || {\n options: undefined,\n assemblyOptions: undefined,\n }\n\n const { quantity, initialQuantity } = item\n\n if (quantity >= initialQuantity && quantity > 0) {\n added.push({\n normalizedQuantity: quantity,\n extraQuantity: quantity - initialQuantity,\n choiceType: item.choiceType,\n item: {\n name: item.name,\n sellingPrice: item.price,\n quantity,\n sellingPriceWithAssemblies:\n item.price + sumAssembliesPrice(item.children || {}),\n id: item.id,\n ...(childrenAssemblyOptions\n ? { assemblyOptions: childrenAssemblyOptions }\n : {}),\n },\n })\n }\n\n if (quantity < initialQuantity && item.choiceType === 'TOGGLE') {\n removed.push({\n name: item.name,\n initialQuantity,\n removedQuantity: initialQuantity - quantity,\n })\n }\n\n const addedChildrenCount = childrenAddedData\n ? childrenAddedData.options.length\n : 0\n\n if (quantity !== initialQuantity || addedChildrenCount > 0) {\n options.push({\n assemblyId: groupId,\n id: item.id,\n quantity: quantity * parentQuantity,\n seller: item.seller,\n ...(childrenOptions && childrenOptions.length > 0\n ? { options: childrenOptions }\n : {}),\n })\n }\n }\n }\n\n const assemblyInputValuesKeys: GroupId[] = Object.keys(inputValues)\n\n for (const groupId of assemblyInputValuesKeys) {\n const inputValuesObject = inputValues[groupId] || {}\n if (Object.keys(inputValuesObject).length > 0) {\n options.push({\n assemblyId: groupId,\n inputValues: inputValues[groupId],\n })\n }\n }\n\n return {\n options,\n assemblyOptions: {\n added,\n removed,\n parentPrice,\n },\n }\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.