id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_admin-pages_d5cfb193
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/SectionTitle.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\ninterface Props {\n textId: string\n}\n\nconst SectionTitle: React.FunctionComponent<Props> = ({ textId }) => (\n <FormattedMessage id={textId}>\n {text => <h2 className=\"mv7 f5 normal\">{text}</h2>}\n </FormattedMessage>\n)\n\nexport default SectionTitle\n\n```"
}
] |
code_admin-pages_e777ae8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/messages.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { defineMessages } from 'react-intl'\n\nexport const messages = defineMessages({\n addCondition: {\n defaultMessage: 'Add new condition',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.add-button',\n },\n dateEquals: {\n defaultMessage: 'is',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.date.equals',\n },\n dateFrom: {\n defaultMessage: 'starts on',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.date.from',\n },\n dateLabel: {\n defaultMessage: 'Date',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.date',\n },\n dateRange: {\n defaultMessage: 'is between',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.date.range',\n },\n dateTo: {\n defaultMessage: 'ends on',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.date.to',\n },\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.admin.pages.form.button.delete',\n },\n headerPrefix: {\n defaultMessage: 'Matching',\n id:\n 'admin/pages.admin.pages.form.templates.simple.conditions.header-prefix',\n },\n headerSuffix: {\n defaultMessage: 'following conditions',\n id:\n 'admin/pages.admin.pages.form.templates.simple.conditions.header-suffix',\n },\n noConditions: {\n defaultMessage: 'No conditions selected',\n id:\n 'admin/pages.admin.pages.form.templates.simple.conditions.no-conditions',\n },\n operatorAll: {\n defaultMessage: 'all',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.operator-all',\n },\n operatorAnd: {\n defaultMessage: 'and',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.operator-and',\n },\n operatorAny: {\n defaultMessage: 'any',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.operator-any',\n },\n operatorOr: {\n defaultMessage: 'or',\n id: 'admin/pages.admin.pages.form.templates.simple.conditions.operator-or',\n },\n subjectPlaceholder: {\n defaultMessage: 'Select condition type',\n id:\n 'admin/pages.admin.pages.form.templates.simple.conditions.category-placeholder',\n },\n emptyConditionsOptions: {\n defaultMessage: 'No options',\n id:\n 'admin/pages.admin.pages.form.templates.simple.conditions.empty-conditions-options',\n },\n})\n\n```"
}
] |
code_admin-pages_aee15798
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/Form.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo } from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport {\n Button,\n Checkbox,\n Dropdown,\n EXPERIMENTAL_Select as Select,\n Input,\n Textarea,\n} from 'vtex.styleguide'\nimport { Binding } from 'vtex.tenant-graphql'\nimport { KeywordsFormData, RouteFormData } from 'pages'\n\nimport FormFieldSeparator from '../../FormFieldSeparator'\nimport SeparatorWithLine from '../SeparatorWithLine'\nimport SectionTitle from './SectionTitle'\nimport { FormErrors } from './typings'\nimport {\n ConditionalTemplateSection,\n ConditionalTemplateSectionProps,\n} from './ConditionalTemplateSection'\nimport { isNewRoute } from '../utils'\nimport { DropdownChangeInput } from '../../../../utils/bindings/typings'\nimport { getBindingSelectorOptions } from '../../../../utils/bindings'\n\ntype TemplateSectionProps = Omit<\n ConditionalTemplateSectionProps,\n 'pages' | 'blockId'\n>\ninterface Props extends TemplateSectionProps {\n data: RouteFormData\n detailChangeHandlerGetter: (\n detailName: keyof RouteFormData\n ) => (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => void\n formErrors: FormErrors\n isCustomPage: boolean\n isDeletable: boolean\n isInfoEditable: boolean\n isLoading: boolean\n onDelete: () => void\n onExit: () => void\n onLoginToggle: () => void\n onSave: (event: React.FormEvent) => void\n onAddConditionalTemplate: () => void\n onChangeTemplateConditionalTemplate: (\n uniqueId: number,\n template: string\n ) => void\n onRemoveConditionalTemplate: (uniqueId: number) => void\n templates: Template[]\n onChangeKeywords: (values: KeywordsFormData[]) => void\n storeBindings: Binding[]\n onChangeBinding: (input: DropdownChangeInput) => void\n}\n\ninterface BindingSelectorWrapper {\n visible: boolean\n}\n\nconst messages = defineMessages({\n createKeywordsMessage: {\n defaultMessage: 'Create keyword \"{keyword}\"',\n id: 'admin/pages.admin.pages.form.field.meta.keywords.create',\n },\n detailsTitle: {\n defaultMessage: 'Page details',\n id: 'admin/pages.admin.pages.form.details.title',\n },\n fieldLogin: {\n defaultMessage: 'Requires authentication',\n id: 'admin/pages.admin.pages.form.field.login',\n },\n fieldPath: {\n defaultMessage: 'URL',\n id: 'admin/pages.admin.pages.form.field.path',\n },\n fieldTitle: {\n defaultMessage: 'Title',\n id: 'admin/pages.admin.pages.form.field.title',\n },\n noOptionsKeywordsMessage: {\n defaultMessage: 'Type your keyword and press ENTER to add it.',\n id: 'admin/pages.admin.pages.form.field.meta.description.no-options',\n },\n pathHint: {\n defaultMessage: '/my-custom-page',\n id: 'admin/pages.admin.pages.form.details.path-hint',\n },\n seoDescription: {\n defaultMessage: 'Description',\n id: 'admin/pages.admin.pages.form.field.meta.description',\n },\n seoKeywords: {\n defaultMessage: 'Keywords',\n id: 'admin/pages.admin.pages.form.field.meta.keywords',\n },\n seoRobots: {\n defaultMessage: 'Robots',\n id: 'admin/store.metaTagRobots.title',\n },\n seoRobotsHelp: {\n defaultMessage: 'Robots',\n id: 'admin/store.metaTagRobots.description',\n },\n bindingSelectorTitle: {\n defaultMessage: 'Binding',\n id: 'admin/pages.admin.pages.form.binding-selector.title',\n },\n})\n\nconst BindingSelectorWrapper: React.FunctionComponent<BindingSelectorWrapper> = props => {\n const { children, visible } = props\n return visible ? (\n <div>\n <FormFieldSeparator />\n {children}\n <div className=\"mb7 pb7 bb bw1 b--light-silver f3 normal\" />\n <FormFieldSeparator />\n </div>\n ) : null\n}\n\nconst Form: React.FunctionComponent<Props> = ({\n data,\n detailChangeHandlerGetter,\n formErrors,\n isCustomPage,\n isDeletable,\n isInfoEditable,\n isLoading,\n onAddConditionalTemplate,\n onChangeKeywords,\n onChangeOperatorConditionalTemplate,\n onChangeStatementsConditionalTemplate,\n onChangeTemplateConditionalTemplate,\n onDelete,\n onExit,\n onLoginToggle,\n onRemoveConditionalTemplate,\n onSave,\n templates,\n storeBindings,\n onChangeBinding,\n}) => {\n const intl = useIntl()\n const path = data.path || ''\n const shouldDisablePathChange = !isNewRoute(data)\n\n const bindingOptions = useMemo(\n () => getBindingSelectorOptions(storeBindings),\n [storeBindings]\n )\n\n return (\n <form onSubmit={onSave}>\n <BindingSelectorWrapper visible={storeBindings.length > 1}>\n <Dropdown\n label={intl.formatMessage(messages.bindingSelectorTitle)}\n disabled={storeBindings.length === 1}\n onChange={onChangeBinding}\n options={bindingOptions}\n value={data.binding || storeBindings[0]}\n />\n </BindingSelectorWrapper>\n <SectionTitle textId=\"admin/pages.admin.pages.form.details.title\" />\n <Input\n disabled={!!data.context}\n label={intl.formatMessage(messages.fieldTitle)}\n onChange={detailChangeHandlerGetter('title')}\n required\n value={data.title}\n errorMessage={\n formErrors.title &&\n intl.formatMessage({\n id: formErrors.title,\n })\n }\n />\n <FormFieldSeparator />\n <Input\n disabled={shouldDisablePathChange}\n label={intl.formatMessage(messages.fieldPath)}\n onChange={detailChangeHandlerGetter('path')}\n placeholder={intl.formatMessage(messages.pathHint)}\n required\n value={path}\n errorMessage={\n formErrors.path &&\n intl.formatMessage({\n id: formErrors.path,\n })\n }\n />\n <FormFieldSeparator />\n <Checkbox\n checked={!!data.auth}\n disabled={!isInfoEditable}\n label={intl.formatMessage(messages.fieldLogin)}\n name=\"checkbox-login\"\n onChange={onLoginToggle}\n value=\"option-0\"\n />\n {isCustomPage && (\n <>\n <FormFieldSeparator />\n <Textarea\n disabled={!!data.context}\n label={intl.formatMessage(messages.seoDescription)}\n onChange={detailChangeHandlerGetter('metaTagDescription')}\n resize=\"vertical\"\n value={data.metaTagDescription}\n />\n <FormFieldSeparator />\n <Select\n creatable\n disabled={!!data.context}\n formatCreateLabel={(keyword: string) =>\n intl.formatMessage(messages.createKeywordsMessage, { keyword })\n }\n label={intl.formatMessage(messages.seoKeywords)}\n noOptionsMessage={() =>\n intl.formatMessage(messages.noOptionsKeywordsMessage)\n }\n onChange={onChangeKeywords}\n placeholder=\"\"\n value={data.metaTagKeywords}\n />\n <FormFieldSeparator />\n <Input\n disabled={!!data.context}\n label={intl.formatMessage(messages.seoRobots)}\n onChange={detailChangeHandlerGetter('metaTagRobots')}\n value={data.metaTagRobots}\n helpText={intl.formatMessage(messages.seoRobotsHelp)}\n />\n </>\n )}\n <SeparatorWithLine />\n <ConditionalTemplateSection\n intl={intl}\n detailChangeHandlerGetter={detailChangeHandlerGetter}\n pages={data.pages}\n templates={templates}\n blockId={data.blockId}\n onAddConditionalTemplate={onAddConditionalTemplate}\n onRemoveConditionalTemplate={onRemoveConditionalTemplate}\n onChangeTemplateConditionalTemplate={\n onChangeTemplateConditionalTemplate\n }\n onChangeOperatorConditionalTemplate={\n onChangeOperatorConditionalTemplate\n }\n onChangeStatementsConditionalTemplate={\n onChangeStatementsConditionalTemplate\n }\n formErrors={formErrors}\n />\n <SeparatorWithLine />\n <FormFieldSeparator />\n <div className={isDeletable ? 'flex justify-between' : ''}>\n {isDeletable && (\n <Button\n disabled={isLoading}\n onClick={onDelete}\n size=\"small\"\n variation=\"danger\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.delete\"\n defaultMessage=\"Delete\"\n />\n </Button>\n )}\n <div className=\"flex justify-end\">\n <div className=\"mr6\">\n <Button\n disabled={isLoading}\n onClick={onExit}\n size=\"small\"\n variation=\"tertiary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.cancel\"\n defaultMessage=\"Cancel\"\n />\n </Button>\n </div>\n <Button\n disabled={isLoading}\n isLoading={isLoading}\n onClick={onSave}\n size=\"small\"\n variation=\"primary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.save\"\n defaultMessage=\"Save\"\n />\n </Button>\n </div>\n </div>\n </form>\n )\n}\n\nexport default Form\n\n```"
}
] |
code_admin-pages_01671e43
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/index.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { defineMessages } from 'react-intl'\n\nimport Section from './Section'\nimport SectionSeparator from './SectionSeparator'\nimport { CategorizedRoutes } from './typings'\nimport { sortRoutes } from './utils'\n\ninterface Props {\n categorizedRoutes: CategorizedRoutes\n}\n\ndefineMessages({\n product: {\n defaultMessage: 'Product',\n id: 'admin/pages.admin.pages.list.section.product',\n },\n productCollections: {\n defaultMessage: 'Product collections',\n id: 'admin/pages.admin.pages.list.section.productCollections',\n },\n standard: {\n defaultMessage: 'Standard',\n id: 'admin/pages.admin.pages.list.section.standard',\n },\n})\n\nconst List: React.FunctionComponent<Props> = ({ categorizedRoutes }) => (\n <Fragment>\n <Section\n hasCreateButton\n routes={sortRoutes(categorizedRoutes.noProducts)}\n titleId=\"admin/pages.admin.pages.list.section.standard\"\n />\n <SectionSeparator />\n <Section\n routes={sortRoutes(categorizedRoutes.singleProduct)}\n titleId=\"admin/pages.admin.pages.list.section.product\"\n />\n <SectionSeparator />\n <Section\n routes={sortRoutes(categorizedRoutes.multipleProducts)}\n titleId=\"admin/pages.admin.pages.list.section.productCollections\"\n />\n <SectionSeparator />\n <Section\n routes={sortRoutes(categorizedRoutes.notFoundSection)}\n titleId=\"admin/pages.admin.pages.list.section.notFound\"\n />\n </Fragment>\n)\n\nexport default List\n\n```"
}
] |
code_admin-pages_60fc777d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/SectionSeparator.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst SectionSeparator = () => <div className=\"mt7\" />\n\nexport default SectionSeparator\n\n```"
}
] |
code_admin-pages_f11c37a4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/Section.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport { Box, Button } from 'vtex.styleguide'\n\nimport { NEW_ROUTE_ID, ROUTES_FORM } from '../consts'\nimport SeparatorWithLine from '../SeparatorWithLine'\n\nimport Entry from './Entry'\n\ninterface Props {\n hasCreateButton?: boolean\n routes: Route[]\n runtime: RenderContext\n titleId: string\n}\n\nconst Section = ({ hasCreateButton, routes, runtime, titleId }: Props) => (\n <Box>\n <div className=\"relative flex items-center\">\n <FormattedMessage id={titleId}>\n {title => <div className=\"b\">{title}</div>}\n </FormattedMessage>\n {hasCreateButton && (\n <div className=\"absolute right-0\">\n <Button\n onClick={() => {\n runtime.navigate({\n page: ROUTES_FORM,\n params: { id: NEW_ROUTE_ID },\n })\n }}\n size=\"small\"\n variation=\"primary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.list.button.create\"\n defaultMessage=\"Create New\"\n />\n </Button>\n </div>\n )}\n </div>\n {routes.map(route => (\n <Fragment key={route.path}>\n <SeparatorWithLine />\n <Entry route={route} />\n </Fragment>\n ))}\n </Box>\n)\n\nexport default withRuntimeContext(Section)\n\n```"
}
] |
code_admin-pages_4ccce781
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/utils.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const sortRoutes = (routes: Route[]) =>\n routes.sort((a, b) => a.interfaceId.localeCompare(b.interfaceId))\n\n```"
}
] |
code_admin-pages_4483aed3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/typings.d.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface CategorizedRoutes {\n multipleProducts: Route[]\n noProducts: Route[]\n singleProduct: Route[]\n notFoundSection: Route[]\n}\n\n```"
}
] |
code_admin-pages_88737610
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/List/Entry.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport { IconEdit } from 'vtex.styleguide'\n\nimport { ROUTES_FORM } from '../consts'\nimport { getRouteTitle } from '../utils'\n\ninterface Props {\n route: Route\n runtime: RenderContext\n}\n\nconst Entry = ({ route, runtime }: Props) => {\n const handleClick = React.useCallback(() => {\n runtime.navigate({\n page: ROUTES_FORM,\n params: { id: encodeURIComponent(route.routeId) },\n })\n }, [route.routeId, runtime])\n\n const handleKeyDown = useKeydownFromClick(handleClick)\n\n return (\n <div className=\"flex justify-between items-center\">\n <div className=\"f6\">{getRouteTitle(route)}</div>\n <div\n className=\"flex pointer outline-0\"\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <IconEdit color=\"silver\" />\n </div>\n </div>\n )\n}\n\nexport default withRuntimeContext(Entry)\n\n```"
}
] |
code_admin-pages_2877d4e2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getLoginToggleState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { State } from '../index'\n\nexport const getLoginToggleState = (prevState: State) => ({\n ...prevState,\n data: {\n ...prevState.data,\n auth: !!prevState.data && !prevState.data.auth,\n },\n})\n\n```"
}
] |
code_admin-pages_840de5f2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeTemplateConditionalTemplateState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { State } from '../index'\n\nexport const getChangeTemplateConditionalTemplateState = (\n uniqueId: number,\n template: string\n) => (prevState: State) => {\n const newPages = prevState.data.pages.map(page => {\n if (page.uniqueId === uniqueId) {\n return {\n ...page,\n template,\n }\n }\n return page\n })\n\n return {\n ...prevState,\n data: {\n ...prevState.data,\n pages: newPages,\n },\n formErrors: {},\n }\n}\n\n```"
}
] |
code_admin-pages_e98ffd1b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeStatementsConditionalTemplate.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Statements } from 'pages'\n\nimport { State } from '../index'\n\nexport const getChangeStatementsConditionalTemplate = (\n uniqueId: number,\n statements: Statements[]\n) => (prevState: State) => {\n const newPages = prevState.data.pages.map(page => {\n if (page.uniqueId === uniqueId) {\n return {\n ...page,\n condition: {\n ...page.condition,\n statements,\n },\n }\n }\n return page\n })\n\n return {\n ...prevState,\n data: {\n ...prevState.data,\n pages: newPages,\n },\n formErrors: {},\n }\n}\n\n```"
}
] |
code_admin-pages_55b7b5c5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeOperatorConditionalTemplateState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ConditionsProps } from 'vtex.styleguide'\n\nimport { State } from '../index'\n\nexport const getChangeOperatorConditionalTemplateState = (\n uniqueId: number,\n operator: NonNullable<ConditionsProps['operator']>\n) => (prevState: State) => {\n const newPages = prevState.data.pages.map(page => {\n if (page.uniqueId === uniqueId) {\n return {\n ...page,\n condition: {\n ...page.condition,\n allMatches: operator === 'all',\n },\n operator,\n }\n }\n return page\n })\n\n return {\n ...prevState,\n data: {\n ...prevState.data,\n pages: newPages,\n },\n formErrors: {},\n }\n}\n\n```"
}
] |
code_admin-pages_442402bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeOperatorConditionalTemplateState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport NEW_PAGE from './__fixtures__/newPage'\nimport setupDate from './__fixtures__/setupDate'\nimport BASE_STATE from './__fixtures__/state'\nimport { getChangeOperatorConditionalTemplateState } from './getChangeOperatorConditionalTemplateState'\n\ndescribe('getChangeOperatorConditionalTemplateState', () => {\n setupDate()\n\n it('should modify operator given a unique ID', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n isInfoEditable: false,\n }\n\n expect(\n getChangeOperatorConditionalTemplateState(3, 'all')(mockState)\n ).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n operator: 'all',\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n\n it('should set allMatches boolean to true given \"all\" as operator', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n isInfoEditable: false,\n }\n\n expect(\n getChangeOperatorConditionalTemplateState(3, 'all')(mockState)\n ).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n condition: expect.objectContaining({\n allMatches: true,\n }),\n operator: 'all',\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n\n it('should set allMatches boolean to false given \"any\" as operator', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n isInfoEditable: false,\n }\n\n expect(\n getChangeOperatorConditionalTemplateState(3, 'any')(mockState)\n ).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n condition: expect.objectContaining({\n allMatches: false,\n }),\n operator: 'any',\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n\n it('should clear formError', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n formErrors: {\n title: 'oi',\n },\n isInfoEditable: false,\n }\n\n expect(\n getChangeOperatorConditionalTemplateState(3, 'all')(mockState)\n ).toEqual(\n expect.objectContaining({\n formErrors: {},\n })\n )\n })\n})\n\n```"
}
] |
code_admin-pages_1d621de8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getValidateFormState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { RouteFormData } from 'pages'\n\nimport { State } from '../index'\n\nconst REQUIRED_MESSAGE = 'admin/pages.admin.pages.form.templates.field.required'\n\nconst validateFalsyPath = (path: keyof RouteFormData) => (\n data: RouteFormData\n) => !data[path] && { [path]: REQUIRED_MESSAGE }\n\nconst validateUrlBeginning = (path: string) => {\n if (path.startsWith('/')) {\n return {}\n }\n return {\n path: 'admin/pages.admin.pages.form.templates.path.validation-error',\n }\n}\n\nconst validateConditionalTemplates: (data: RouteFormData) => { pages?: {} } = (\n data: RouteFormData\n) => {\n return data.pages.reduce<Record<string, any>>(\n (acc, { uniqueId, condition, template }) => {\n const templateError = !template && { template: REQUIRED_MESSAGE }\n const conditionError = !condition.statements.length && {\n condition: REQUIRED_MESSAGE,\n }\n\n if (templateError || conditionError) {\n acc.pages = {\n ...acc.pages,\n [uniqueId]: {\n ...templateError,\n ...conditionError,\n },\n }\n }\n return acc\n },\n {}\n )\n}\n\nexport const getValidateFormState = (prevState: State) => {\n return {\n ...prevState,\n formErrors: {\n ...prevState.formErrors,\n ...(validateUrlBeginning(prevState.data.path) as Record<string, string>),\n ...validateFalsyPath('path')(prevState.data),\n ...validateFalsyPath('blockId')(prevState.data),\n ...(prevState.isInfoEditable\n ? validateFalsyPath('title')(prevState.data)\n : {}),\n ...validateConditionalTemplates(prevState.data),\n },\n }\n}\n\n```"
}
] |
code_admin-pages_34974ef8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getAddConditionalTemplateState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport NEW_PAGE from './__fixtures__/newPage'\nimport setupDate from './__fixtures__/setupDate'\nimport BASE_STATE from './__fixtures__/state'\nimport { getAddConditionalTemplateState } from './getAddConditionalTemplateState'\n\ndescribe('getAddConditionalTemplateState', () => {\n setupDate()\n\n it(`should add empty page with uniqueId if data.pages is empty`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [],\n },\n }\n\n expect(getAddConditionalTemplateState(mockState)).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 0,\n },\n ],\n },\n })\n })\n\n it(`should add empty page with uniqueId === highest uniqueId + 1`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n }\n\n expect(getAddConditionalTemplateState(mockState)).toMatchObject({\n data: {\n pages: [\n ...mockState.data.pages,\n {\n ...NEW_PAGE,\n uniqueId: 11,\n },\n ],\n },\n })\n })\n\n it(`should clear form errors`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [],\n },\n formErrors: {\n title: 'oi',\n },\n }\n\n expect(getAddConditionalTemplateState(mockState)).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 0,\n },\n ],\n },\n formErrors: {},\n })\n })\n})\n\n```"
}
] |
code_admin-pages_d83ab2f0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getLoginToggleState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport BASE_STATE from './__fixtures__/state'\nimport { getLoginToggleState } from './getLoginToggleState'\n\ndescribe('getLoginToggleState', () => {\n it('should negate data.login value', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n auth: true,\n },\n }\n\n expect(getLoginToggleState(mockState)).toMatchObject({\n data: { auth: false },\n })\n })\n})\n\n```"
}
] |
code_admin-pages_31ff4cbc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getAddConditionalTemplateState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { PagesFormData } from 'pages'\n\nimport { State } from '../index'\n\nconst getMaxUniqueId: (pages: PagesFormData[]) => number = pages => {\n return pages.reduce((acc, { uniqueId: currentValue }) => {\n if (acc < currentValue) {\n return currentValue\n }\n return acc\n }, -1)\n}\n\nexport const getAddConditionalTemplateState = (prevState: State) => {\n const maxUniqueId = getMaxUniqueId(prevState.data.pages)\n const now = new Date()\n const newPage: PagesFormData = {\n condition: {\n allMatches: true,\n id: '',\n statements: [\n {\n error: '',\n object: { date: now },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'all',\n pageId: '',\n template: '',\n uniqueId: maxUniqueId + 1,\n }\n\n return {\n ...prevState,\n data: { ...prevState.data, pages: prevState.data.pages.concat(newPage) },\n formErrors: {},\n }\n}\n\n```"
}
] |
code_admin-pages_4c5ffe76
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getRemoveConditionalTemplateState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport NEW_PAGE from './__fixtures__/newPage'\nimport BASE_STATE from './__fixtures__/state'\nimport { getRemoveConditionalTemplateState } from './getRemoveConditionalTemplateState'\n\ndescribe('getRemoveConditionalTemplateState', () => {\n it('should remove the given page with the given uniqueId from \"data.pages\"', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n }\n\n expect(getRemoveConditionalTemplateState(10)(mockState)).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n\n it(`should clear form errors`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n formErrors: {\n title: 'oi',\n },\n }\n\n expect(getRemoveConditionalTemplateState(10)(mockState)).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n formErrors: {},\n })\n })\n})\n\n```"
}
] |
code_admin-pages_19473fa0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/index.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport {\n getAddConditionalTemplateState,\n} from './getAddConditionalTemplateState'\nexport {\n getChangeOperatorConditionalTemplateState,\n} from './getChangeOperatorConditionalTemplateState'\nexport {\n getChangeStatementsConditionalTemplate,\n} from './getChangeStatementsConditionalTemplate'\nexport {\n getChangeTemplateConditionalTemplateState,\n} from './getChangeTemplateConditionalTemplateState'\nexport { getLoginToggleState } from './getLoginToggleState'\nexport {\n getRemoveConditionalTemplateState,\n} from './getRemoveConditionalTemplateState'\nexport { getValidateFormState } from './getValidateFormState'\n\n```"
}
] |
code_admin-pages_b4e12fd3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeStatementsConditionalTemplate.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport NEW_PAGE from './__fixtures__/newPage'\nimport BASE_STATE from './__fixtures__/state'\nimport { getChangeStatementsConditionalTemplate } from './getChangeStatementsConditionalTemplate'\n\ndescribe('getChangeStatementsConditionalTemplate', () => {\n it('should change statement inside condition given a page uniqueId', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n condition: {\n allMatches: false,\n statements: [],\n },\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n }\n\n expect(\n getChangeStatementsConditionalTemplate(3, [\n { error: '', object: {}, subject: 'Date', verb: '=' },\n ])(mockState)\n ).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n condition: {\n allMatches: false,\n statements: [{ subject: 'Date', verb: '=' }],\n },\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n})\n\n```"
}
] |
code_admin-pages_47d3cd12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getRemoveConditionalTemplateState.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { State } from '../index'\n\nexport const getRemoveConditionalTemplateState = (uniqueId: number) => (\n prevState: State\n) => {\n const newPages = prevState.data.pages.filter(\n page => page.uniqueId !== uniqueId\n )\n\n return {\n ...prevState,\n data: { ...prevState.data, pages: newPages },\n formErrors: {},\n }\n}\n\n```"
}
] |
code_admin-pages_6f2a218e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getChangeTemplateConditionalTemplateState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport NEW_PAGE from './__fixtures__/newPage'\nimport BASE_STATE from './__fixtures__/state'\nimport { getChangeTemplateConditionalTemplateState } from './getChangeTemplateConditionalTemplateState'\n\ndescribe('getChangeTemplateConditionalTemplateState', () => {\n it('should modify template given a unique ID', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n }\n\n expect(\n getChangeTemplateConditionalTemplateState(3, 'store/test')(mockState)\n ).toMatchObject({\n data: {\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n template: 'store/test',\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n })\n })\n\n it('should clear formError', () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n ...NEW_PAGE,\n uniqueId: 10,\n },\n {\n ...NEW_PAGE,\n uniqueId: 3,\n },\n {\n ...NEW_PAGE,\n uniqueId: 5,\n },\n ],\n },\n formErrors: {\n title: 'oi',\n },\n }\n\n expect(\n getChangeTemplateConditionalTemplateState(3, 'store/test')(mockState)\n ).toEqual(\n expect.objectContaining({\n formErrors: {},\n })\n )\n })\n})\n\n```"
}
] |
code_admin-pages_450b339b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/getValidateFormState.test.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { State } from '../index'\n\nimport { getValidateFormState } from './getValidateFormState'\nimport BASE_STATE from './__fixtures__/state'\n\ndescribe('getValidateFormState', () => {\n it('should return empty object if there are no errors', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n condition: {\n allMatches: true,\n id: '1',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate2',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: 'test',\n },\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({ formErrors: {} })\n )\n })\n\n it('should return error if path is falsy', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n blockId: '',\n pages: [\n {\n condition: {\n allMatches: true,\n id: '1',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '',\n title: 'test',\n },\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({\n formErrors: expect.objectContaining({\n path: 'admin/pages.admin.pages.form.templates.field.required',\n }),\n })\n )\n })\n\n it(`should return error if path doesn't begin with '/'`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n path: 'lalala',\n title: 'test',\n },\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({\n formErrors: expect.objectContaining({\n path: 'admin/pages.admin.pages.form.templates.path.validation-error',\n }),\n })\n )\n })\n\n it('should return error if pageId is falsy', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n blockId: '',\n pages: [\n {\n condition: {\n allMatches: true,\n id: '1',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: 'test',\n },\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({\n formErrors: expect.objectContaining({\n blockId: 'admin/pages.admin.pages.form.templates.field.required',\n }),\n })\n )\n })\n\n it('should return error if title is falsy', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n condition: {\n allMatches: true,\n id: '1',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: '',\n },\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({\n formErrors: expect.objectContaining({\n title: 'admin/pages.admin.pages.form.templates.field.required',\n }),\n })\n )\n })\n\n it(`shouldn't return error if title is falsy and field isn't editable`, () => {\n const mockState = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n path: '/test',\n template: 'defaultTemplate',\n title: '',\n },\n isInfoEditable: false,\n }\n\n expect(getValidateFormState(mockState)).toEqual(\n expect.objectContaining({\n formErrors: {},\n })\n )\n })\n\n describe('pages[] field errors', () => {\n it('should return error with if template of conditional template is falsy', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n condition: {\n allMatches: true,\n id: '1',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: '',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: 'defaultTemplate',\n },\n }\n\n expect(getValidateFormState(mockState)).toMatchObject({\n formErrors: expect.objectContaining({\n pages: {\n 5: {\n template: 'admin/pages.admin.pages.form.templates.field.required',\n },\n },\n }),\n })\n })\n\n it('should return error with if template of conditional template is falsy', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n condition: {\n allMatches: true,\n statements: [],\n },\n operator: 'any',\n pageId: 'page1',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n id: '34',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-02'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'any',\n pageId: 'page2',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: 'defaultTemplate',\n },\n }\n\n expect(getValidateFormState(mockState)).toMatchObject({\n formErrors: expect.objectContaining({\n pages: {\n 10: {\n condition:\n 'admin/pages.admin.pages.form.templates.field.required',\n },\n },\n }),\n })\n })\n\n it('should return error for more than one page and field', () => {\n const mockState: State = {\n ...BASE_STATE,\n data: {\n ...BASE_STATE.data,\n pages: [\n {\n condition: {\n allMatches: true,\n statements: [],\n },\n operator: 'any',\n template: 'myTemplate1',\n uniqueId: 10,\n },\n {\n condition: {\n allMatches: true,\n statements: [],\n },\n operator: 'any',\n template: 'myTemplate2',\n uniqueId: 5,\n },\n ],\n path: '/test',\n title: 'defaultTemplate',\n },\n }\n\n expect(getValidateFormState(mockState)).toMatchObject({\n formErrors: {\n pages: {\n 5: {\n condition:\n 'admin/pages.admin.pages.form.templates.field.required',\n },\n 10: {\n condition:\n 'admin/pages.admin.pages.form.templates.field.required',\n },\n },\n },\n })\n })\n })\n})\n\n```"
}
] |
code_admin-pages_5ff150d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/__fixtures__/newPage.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ConditionsOperator } from 'vtex.styleguide'\n\nconst newPage = {\n condition: {\n allMatches: true,\n id: '',\n statements: [\n {\n error: '',\n object: {\n date: new Date('2019-02-01'),\n },\n subject: 'date',\n verb: 'is',\n },\n ],\n },\n operator: 'all' as ConditionsOperator,\n pageId: '',\n template: '',\n}\n\nexport default newPage\n\n```"
}
] |
code_admin-pages_3aa784c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/__fixtures__/state.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport default {\n data: {\n auth: false,\n blockId: 'test.app@1.x:store.home#cool-home',\n context: null,\n declarer: 'user',\n domain: 'store',\n interfaceId: 'test.app@1.x:store.home',\n pages: [],\n path: '/',\n routeId: 'store.home#cool-home',\n title: null,\n uuid: undefined,\n },\n formErrors: {},\n isDeletable: false,\n isInfoEditable: true,\n isLoading: false,\n}\n\n```"
}
] |
code_admin-pages_d6cc886c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/stateHandlers/__fixtures__/setupDate.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport MockDate from 'mockdate'\n\nconst setupDate = () => {\n beforeEach(() => {\n MockDate.set('2019-02-01')\n })\n\n afterEach(() => {\n MockDate.reset()\n })\n}\n\nexport default setupDate\n\n```"
}
] |
code_admin-pages_6056f953
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/utils/utils.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { QueryResult } from 'react-apollo'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport { Button, EmptyState, Spinner } from 'vtex.styleguide'\n\nconst isRefetching = (status: number): boolean => status === 4\n\nconst Loading = (): React.ReactElement => (\n <div className=\"flex justify-center items-center h5\">\n <Spinner />\n </div>\n)\n\ninterface ErrorMessageProps {\n title: string\n description: string\n refetch: () => unknown\n refetching: boolean\n}\n\nconst ErrorMessage: React.FunctionComponent<ErrorMessageProps> = ({\n title,\n description,\n refetch,\n refetching,\n}) => {\n const intl = useIntl()\n return (\n <div className=\"flex flex-column justify-center\">\n <EmptyState\n title={intl.formatMessage({\n id: title,\n })}\n >\n <FormattedMessage id={description} />\n </EmptyState>\n <Button\n size=\"small\"\n variation=\"tertiary\"\n onClick={() => refetch()}\n isLoading={refetching}\n >\n <FormattedMessage id=\"admin/pages.editor.store.settings.refetch\" />\n </Button>\n </div>\n )\n}\n\nexport function handleCornerCases<TData, TVariables>(\n options: { error: { title: string; description: string } },\n fn: (\n x: Omit<QueryResult<TData, TVariables>, 'loading' | 'error'> & {\n data: TData // be sure data is not undefined\n }\n ) => JSX.Element\n) {\n return ({\n loading,\n error,\n data,\n refetch,\n networkStatus,\n ...rest\n }: QueryResult<TData, TVariables>) => {\n if (loading) {\n return <Loading />\n }\n if (error || !data) {\n const { error: errorMessage } = options\n console.error('Error', error)\n return (\n <ErrorMessage\n {...errorMessage}\n refetch={refetch}\n refetching={isRefetching(networkStatus)}\n />\n )\n }\n\n return fn({ data, refetch, networkStatus, ...rest })\n }\n}\n\n```"
}
] |
code_admin-pages_1761af11
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/index.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { JSONSchema6 } from 'json-schema'\nimport { assoc } from 'ramda'\nimport React, { useContext, useEffect, useState } from 'react'\nimport { ChildMutateProps, withMutation } from 'react-apollo'\nimport { FormattedMessage, useIntl, IntlShape } from 'react-intl'\nimport Form, { UiSchema } from 'react-jsonschema-form'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Button, ToastContext } from 'vtex.styleguide'\n\nimport ArrayFieldTemplate from '../../../form/ArrayFieldTemplate'\nimport BaseInput from '../../../form/BaseInput'\nimport Toggle from '../../../form/Toggle'\nimport FieldTemplate from '../../../form/FieldTemplate'\nimport ObjectFieldTemplate from '../../../form/ObjectFieldTemplate'\nimport withStoreSettings, { FormProps } from './components/withStoreSettings'\nimport SaveAppSettings from './mutations/SaveAppSettings.graphql'\nimport { formatSchema, tryParseJson, removeObjectProperties } from './utils'\nimport { CustomWidgetProps } from '../../../form/typings'\n\ninterface MutationData {\n message: string\n}\n\ninterface MutationVariables {\n app: string\n version: string\n settings: string\n}\n\ntype Props = ChildMutateProps<FormProps, MutationData, MutationVariables>\n\nconst CheckboxWidget = (props: CustomWidgetProps) => (\n <div className=\"pv4\">\n <Toggle {...props} />\n {props.schema.description && (\n <span className=\"t-small c-muted-1 pv3 relative\">\n {props.schema.description}\n </span>\n )}\n </div>\n)\n\nconst widgets = {\n BaseInput,\n CheckboxWidget,\n}\n\nfunction resolveSchemaForCurrentTab(\n tab: string | undefined,\n schema: JSONSchema6,\n intl: IntlShape\n) {\n const advancedSettingsSchema = (schema.properties\n ?.advancedSettings as JSONSchema6) ?? {\n properties: {},\n }\n\n switch (tab) {\n case 'general':\n return assoc<JSONSchema6>(\n 'properties',\n formatSchema({\n schema: schema.properties || {},\n intl,\n ignore: ['title', 'advancedSettings'],\n }),\n schema\n )\n case 'advanced':\n return assoc<JSONSchema6>(\n 'properties',\n formatSchema({\n schema: advancedSettingsSchema.properties || {},\n intl,\n ignore: ['title'],\n }),\n advancedSettingsSchema\n )\n default:\n return assoc<JSONSchema6>(\n 'properties',\n formatSchema({\n schema: removeObjectProperties(schema, ['title']).properties || {},\n intl,\n }),\n schema\n )\n }\n}\n\nconst StoreForm: React.FunctionComponent<Props> = ({ store, mutate, tab }) => {\n const intl = useIntl()\n const [formData, setFormData] = useState(tryParseJson(store.settings))\n\n const [submitting, setSubmitting] = useState(false)\n\n const { showToast } = useContext(ToastContext)\n\n useEffect(() => {\n if (submitting) {\n const { slug: app, version } = store\n\n mutate({\n variables: { app, version, settings: JSON.stringify(formData) },\n })\n .then(() =>\n showToast(\n intl.formatMessage({\n id: 'admin/pages.admin.pages.form.save.success',\n })\n )\n )\n .catch(() =>\n showToast(\n intl.formatMessage({\n id: 'admin/pages.admin.pages.form.save.error',\n })\n )\n )\n .finally(() => setSubmitting(false))\n }\n }, [formData, intl, mutate, showToast, store, submitting])\n\n const shouldDisplayWarning = tab === 'advanced'\n const { settingsSchema, settingsUiSchema } = store\n\n const schema = tryParseJson<JSONSchema6>(settingsSchema)\n const uiSchema = tryParseJson<UiSchema>(settingsUiSchema)\n\n const schemas = {\n schema: resolveSchemaForCurrentTab(tab, schema, intl),\n title: formatIOMessage({ id: schema.title || '', intl }),\n ...(uiSchema && { uiSchema }),\n }\n\n return (\n <div className=\"flex flex-column justify-center\">\n {shouldDisplayWarning && (\n <div className=\"pv3\">\n <span className=\"c-emphasis\">\n <FormattedMessage id=\"admin/pages.editor.store.settings.advanced.disclaimer\" />\n </span>\n </div>\n )}\n <Form\n {...schemas}\n formData={formData}\n onSubmit={() => setSubmitting(true)}\n onError={e => console.error('Bad input numbers: ', e.length)}\n onChange={({ formData: newFormData }) => setFormData(newFormData)}\n showErrorList={false}\n FieldTemplate={FieldTemplate}\n ArrayFieldTemplate={ArrayFieldTemplate}\n ObjectFieldTemplate={ObjectFieldTemplate}\n widgets={widgets}\n >\n <div className=\"w-100 tr\">\n <Button\n size=\"small\"\n type=\"submit\"\n variation=\"primary\"\n onClick={() => setSubmitting(true)}\n isLoading={submitting}\n >\n <FormattedMessage id=\"admin/pages.admin.pages.form.button.save\" />\n </Button>\n </div>\n </Form>\n </div>\n )\n}\n\nexport default withMutation<{ tab?: string }, MutationData, MutationVariables>(\n SaveAppSettings\n)(\n withStoreSettings<ChildMutateProps<{}, MutationData, MutationVariables>>(\n StoreForm\n )\n)\n\n```"
}
] |
code_admin-pages_142311f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/utils.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { JSONSchema6, JSONSchema6Definition } from 'json-schema'\nimport { IntlShape } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\n\ninterface FormatSchemaArgs {\n schema: JSONSchema6Definition\n intl: IntlShape\n ignore?: string[]\n}\n\n/**\n * Returns the original object without the received properties\n * @param object\n * @param properties\n */\nexport const removeObjectProperties = (\n object: Record<string, any>,\n properties: string[]\n) => {\n let newObject = object\n\n properties.forEach(property => {\n const { [property]: deletedProperty, ...otherProperties } = newObject\n newObject = otherProperties\n })\n\n return newObject\n}\n\nexport const formatSchema = ({\n schema,\n intl,\n ignore,\n}: FormatSchemaArgs): JSONSchema6Definition => {\n if (typeof schema === 'boolean') {\n return schema\n }\n const filteredSchema = ignore\n ? removeObjectProperties(schema, ignore)\n : schema\n\n return Object.entries(filteredSchema).reduce<JSONSchema6>(\n (acc, [currKey, currValue]) => {\n let formattedValue: unknown\n\n if (\n typeof currValue === 'object' &&\n currValue !== null &&\n !Array.isArray(currValue)\n ) {\n formattedValue = formatSchema({ schema: currValue, intl })\n } else if (typeof currValue === 'string') {\n formattedValue = formatIOMessage({ id: currValue, intl })\n } else {\n formattedValue = currValue\n }\n\n return {\n ...acc,\n [currKey]: formattedValue,\n }\n },\n filteredSchema\n )\n}\n\nexport const tryParseJson = <T>(str: string): T => {\n let parsed = null\n\n try {\n if (str) {\n parsed = JSON.parse(str)\n }\n } catch (e) {\n console.error(e)\n }\n\n return parsed\n}\n\n```"
}
] |
code_admin-pages_60182fc8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/index.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport { equals, last, path, pick } from 'ramda'\nimport React, { useContext, useState } from 'react'\nimport { FormattedMessage, injectIntl, WrappedComponentProps } from 'react-intl'\nimport {\n Button,\n ColorPicker,\n Dropdown,\n IconCaretDown,\n IconCaretUp,\n Input,\n ToastContext,\n Toggle,\n Spinner,\n} from 'vtex.styleguide'\n\nimport ImageUploader from '../../../form/ImageUploader'\nimport withPWAMutations, {\n ManifestMutationData,\n PWAMutationProps,\n} from './components/withPWAMutations'\nimport withPWASettings, {\n Manifest,\n PWAImage,\n PWASettingsProps,\n} from './components/withPWASettings'\nimport { messages } from './messages'\nimport {\n DISPLAY_OPTIONS,\n ORIENTATION_OPTIONS,\n TOAST_DURATION,\n INSTALL_PROMPT_OPTIONS,\n} from './utils/constants'\n\nconst fillManifest = (manifest: Manifest): Manifest => ({\n ...manifest,\n display: manifest.display || 'standalone',\n orientation: manifest.orientation || 'portrait',\n ['start_url']: manifest.start_url || '/',\n})\n\nconst isManifestValid = (manifest: Manifest): boolean =>\n Boolean(\n manifest.start_url &&\n manifest.background_color &&\n manifest.display &&\n manifest.orientation &&\n manifest.theme_color\n )\n\ntype Props = WrappedComponentProps & PWAMutationProps & PWASettingsProps\n\nconst PWAForm: React.FunctionComponent<Props> = ({\n manifest: pwaManifest,\n splashes,\n iOSIcons,\n pwaSettings,\n updateManifest,\n updateManifestIcon,\n updatePWASettings,\n intl,\n refetch,\n}) => {\n const [manifest, setManifest] = useState(fillManifest(pwaManifest))\n const [settings, setSettings] = useState(pwaSettings)\n const [colorHistory, setColorHistory] = useState([\n pwaManifest.theme_color,\n pwaManifest.background_color,\n ])\n const [submitting, setSubmitting] = useState(false)\n const [showSpecific, setShowSpecific] = useState(false)\n const [splashLoading, setSplashLoading] = useState(true)\n\n const toggleSpecific = React.useCallback(\n () => setShowSpecific(!showSpecific),\n [showSpecific]\n )\n\n const toggleSpecificByKeyDown = useKeydownFromClick(toggleSpecific)\n\n const { showToast } = useContext(ToastContext)\n\n const [splash = null] = splashes || []\n const androidIcon = manifest.icons && last(manifest.icons)\n const iOSIcon = last(iOSIcons)\n\n async function uploadIcon({\n icon,\n iOS = false,\n }: {\n icon: File\n iOS?: boolean\n }): Promise<void> {\n setSubmitting(true)\n try {\n const result = await updateManifestIcon.mutate({\n variables: { icon, iOS },\n })\n // If the iOS icon changed, show the new iOS splash screen\n if (iOS) {\n await refetch()\n } else {\n const icons: PWAImage[] | undefined = path(\n ['data', 'updateManifestIcon', 'icons'],\n result || {}\n )\n setManifest({ ...manifest, icons })\n }\n showToast({\n duration: TOAST_DURATION,\n message: intl.formatMessage(messages.updateManifestIconSuccess),\n })\n } catch (err) {\n console.error('Error updating manifest icon: ', err)\n showToast({\n duration: Infinity,\n message: intl.formatMessage(messages.updateManifestIconError),\n })\n } finally {\n setSubmitting(false)\n }\n }\n\n async function saveSettings(): Promise<void> {\n await updatePWASettings.mutate({ variables: { settings } })\n }\n\n async function saveManifest(): Promise<ManifestMutationData | undefined> {\n const manifestData = pick(\n [\n 'start_url',\n 'theme_color',\n 'background_color',\n 'display',\n 'orientation',\n ],\n manifest\n ) as ManifestMutationData\n const result = await updateManifest.mutate({\n variables: { manifest: manifestData },\n })\n return path(['data', 'updateManifest'], result || {})\n }\n\n async function handleSubmit() {\n setSubmitting(true)\n try {\n const mutations: Promise<ManifestMutationData | void>[] = [saveManifest()]\n if (!equals(settings, pwaSettings)) {\n mutations.push(saveSettings())\n }\n const [newManifest] = await Promise.all(mutations)\n // If background color changed, show the new iOS splash screen\n if (\n newManifest &&\n pwaManifest.background_color !== newManifest.background_color\n ) {\n await refetch()\n }\n showToast({\n duration: TOAST_DURATION,\n message: intl.formatMessage({\n id: 'admin/pages.admin.pages.form.save.success',\n }),\n })\n } catch (err) {\n console.error(err)\n showToast({\n duration: Infinity,\n message: intl.formatMessage({\n id: 'admin/pages.admin.pages.form.save.error',\n }),\n })\n } finally {\n setSubmitting(false)\n }\n }\n\n return (\n <div className=\"flex flex-column justify-center\">\n <div className=\"flex flex-row items-center\">\n <div className=\"t-heading-7 w-40\">\n <FormattedMessage id=\"admin/pages.editor.store.settings.pwa.theme_color\" />\n </div>\n <div className=\"w-100\">\n <ColorPicker\n disabled={submitting}\n color={{ hex: manifest.theme_color }}\n colorHistory={colorHistory}\n label={intl.formatMessage({\n id: 'admin/pages.admin.pages.form.templates.field.default',\n })}\n onChange={(color: { hex: string }) => {\n setManifest({ ...manifest, ['theme_color']: color.hex })\n setColorHistory([...colorHistory, color.hex])\n }}\n />\n </div>\n </div>\n <div className=\"pt2\">\n <div className=\"flex flex-row items-center\">\n <div className=\"t-heading-7 w-40\">\n <FormattedMessage id=\"admin/pages.editor.store.settings.pwa.background_color\" />\n </div>\n <div className=\"w-100\">\n <ColorPicker\n disabled={submitting}\n color={{ hex: manifest.background_color }}\n colorHistory={colorHistory}\n label={intl.formatMessage({\n id: 'admin/pages.admin.pages.form.templates.field.default',\n })}\n onChange={(color: { hex: string }) => {\n setManifest({ ...manifest, ['background_color']: color.hex })\n setColorHistory([...colorHistory, color.hex])\n }}\n />\n </div>\n </div>\n </div>\n <div className=\"flex flex-column items-center justify-center\">\n <div className=\"w-100 pt4\">\n <ImageUploader\n disabled={submitting}\n value={\n androidIcon\n ? new URL(`https://${location.hostname}/${androidIcon.src}`)\n .href\n : ''\n }\n schema={{\n title: 'admin/pages.editor.store.settings.pwa.android-logo-icon',\n }}\n onFileDrop={(icon: File) => uploadIcon({ icon })}\n />\n </div>\n <div className=\"w-100 pt4\">\n <ImageUploader\n disabled={submitting}\n value={\n iOSIcon\n ? new URL(`https://${location.hostname}/${iOSIcon.src}`).href\n : ''\n }\n schema={{\n title: 'admin/pages.editor.store.settings.pwa.ios-logo-icon',\n }}\n onFileDrop={(icon: File) => uploadIcon({ icon, iOS: true })}\n />\n </div>\n </div>\n {splash && (\n <div className=\"pt6\">\n <div className=\"t-heading-7 mb4\">\n <FormattedMessage id=\"admin/pages.editor.store.settings.pwa.splash-screen\" />\n </div>\n <div className=\"w-100 flex justify-center items-center\">\n {splashLoading && <Spinner />}\n <img\n alt={intl.formatMessage({\n id: 'admin/pages.editor.store.settings.pwa.splash-screen',\n })}\n className=\"h5 shadow-1 mb3\"\n src={`${splash.src}?v=${Date.now()}`}\n onLoad={() => setSplashLoading(false)}\n style={{ display: splashLoading ? 'none' : 'block' }}\n />\n </div>\n </div>\n )}\n <div className=\"pv7\">\n <div className=\"w-100 bb b--muted-4\" />\n </div>\n <div\n aria-checked={showSpecific}\n className=\"pb3 link pointer c-muted-1 outline-0\"\n onClick={toggleSpecific}\n onKeyDown={toggleSpecificByKeyDown}\n role=\"switch\"\n tabIndex={0}\n >\n <span className=\"pr4\">\n <FormattedMessage id=\"admin/pages.editor.store.settings.pwa.app-settings\" />\n </span>\n {showSpecific ? <IconCaretUp /> : <IconCaretDown />}\n </div>\n {showSpecific && (\n <>\n <div className=\"pt4 w-100\">\n <Input\n disabled={submitting}\n size=\"small\"\n label={intl.formatMessage(messages.startUrl)}\n value={manifest.start_url}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setManifest({ ...manifest, ['start_url']: e.target.value })\n }\n />\n </div>\n <div className=\"pt4 w-100\">\n <Dropdown\n disabled={submitting}\n value={manifest.orientation}\n label={intl.formatMessage(messages.screenOrientation)}\n options={ORIENTATION_OPTIONS.map(option => ({\n ...option,\n label: intl.formatMessage({ id: option.label }),\n }))}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n setManifest({\n ...manifest,\n orientation: e.target.value,\n })\n }\n />\n </div>\n <div className=\"pt4\">\n <Dropdown\n disabled={submitting}\n value={manifest.display}\n label={intl.formatMessage(messages.pwaDisplay)}\n options={DISPLAY_OPTIONS.map(option => ({\n ...option,\n label: intl.formatMessage({ id: option.label }),\n }))}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n setManifest({\n ...manifest,\n display: e.target.value,\n })\n }\n />\n </div>\n <div className=\"pt6\">\n <Toggle\n label={intl.formatMessage(messages.disablePrompt)}\n checked={!settings.disablePrompt}\n disabled={submitting}\n onChange={() =>\n setSettings({\n ...settings,\n disablePrompt: !settings.disablePrompt,\n })\n }\n />\n </div>\n {!settings.disablePrompt && (\n <div className=\"pt4\">\n <Dropdown\n disabled={submitting}\n value={settings.promptOnCustomEvent}\n label={intl.formatMessage(messages.pwaPrompt)}\n options={INSTALL_PROMPT_OPTIONS.map(option => ({\n ...option,\n label: intl.formatMessage({ id: option.label }),\n }))}\n onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>\n setSettings({\n ...settings,\n promptOnCustomEvent: e.target.value,\n })\n }\n />\n </div>\n )}\n </>\n )}\n <div className=\"w-100 mt7 tr\">\n <Button\n size=\"small\"\n type=\"submit\"\n variation=\"primary\"\n onClick={handleSubmit}\n disabled={!isManifestValid(manifest)}\n isLoading={submitting}\n >\n <FormattedMessage id=\"admin/pages.admin.pages.form.button.save\" />\n </Button>\n </div>\n </div>\n )\n}\n\nexport default injectIntl(\n withPWASettings<WrappedComponentProps>(\n withPWAMutations<WrappedComponentProps & PWASettingsProps>(PWAForm)\n )\n)\n\n```"
}
] |
code_admin-pages_67382125
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/messages.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { defineMessages } from 'react-intl'\n\nexport const messages = defineMessages({\n androidLogoIcon: {\n defaultMessage: 'Android Logo Icon (512x512)',\n id: 'admin/pages.editor.store.settings.pwa.android-logo-icon',\n },\n disablePrompt: {\n defaultMessage: 'Add to Home Screen',\n id: 'admin/pages.editor.store.settings.pwa.disable-prompt',\n },\n iosLogoIcon: {\n defaultMessage: 'iOS Logo Icon (512x512)',\n id: 'admin/pages.editor.store.settings.pwa.ios-logo-icon',\n },\n // ORIENTATION_OPTIONS messages\n orientationAny: {\n defaultMessage: 'Any',\n id: 'admin/pages.editor.store.settings.pwa.orientation.any',\n },\n orientationLandscape: {\n defaultMessage: 'Landscape',\n id: 'admin/pages.editor.store.settings.pwa.orientation.landscape',\n },\n orientationLandscapePrimary: {\n defaultMessage: 'Landscape (Primary)',\n id: 'admin/pages.editor.store.settings.pwa.orientation.landscape-primary',\n },\n orientationLandscapeSecondary: {\n defaultMessage: 'Landscape (Secondary)',\n id: 'admin/pages.editor.store.settings.pwa.orientation.landscape-secondary',\n },\n orientationNatural: {\n defaultMessage: 'Natural',\n id: 'admin/pages.editor.store.settings.pwa.orientation.natural',\n },\n orientationPortrait: {\n defaultMessage: 'Portrait',\n id: 'admin/pages.editor.store.settings.pwa.orientation.portrait',\n },\n orientationPortraitPrimary: {\n defaultMessage: 'Portrait (Primary)',\n id: 'admin/pages.editor.store.settings.pwa.orientation.portrait-primary',\n },\n orientationPortraitSecondary: {\n defaultMessage: 'Portrait (Secondary)',\n id: 'admin/pages.editor.store.settings.pwa.orientation.portrait-secondary',\n },\n\n // DISPLAY_OPTIONS messages\n pwaDisplay: {\n defaultMessage: 'Display',\n id: 'admin/pages.editor.store.settings.pwa.display',\n },\n pwaDisplayBrowser: {\n defaultMessage: 'Browser',\n id: 'admin/pages.editor.store.settings.pwa.display.browser',\n },\n pwaDisplayFullscreen: {\n defaultMessage: 'Fullscreen',\n id: 'admin/pages.editor.store.settings.pwa.display.fullscreen',\n },\n pwaDisplayMinimalUi: {\n defaultMessage: 'Minimal-UI (Not supported by Chrome)',\n id: 'admin/pages.editor.store.settings.pwa.display.minimal-ui',\n },\n pwaDisplayStandalone: {\n defaultMessage: 'Standalone (Add to Home Screen)',\n id: 'admin/pages.editor.store.settings.pwa.display.standalone',\n },\n\n screenOrientation: {\n defaultMessage: 'Screen Orientation',\n id: 'admin/pages.editor.store.settings.pwa.screen-orientation',\n },\n startUrl: {\n defaultMessage: 'Start URL',\n id: 'admin/pages.editor.store.settings.pwa.start_url',\n },\n updateManifestIconError: {\n defaultMessage: 'Something wrong occurred while updating the App icon…',\n id: 'admin/pages.editor.store.settings.pwa.update-manifest-icon.error',\n },\n updateManifestIconSuccess: {\n defaultMessage: 'App icon successfuly updated!',\n id: 'admin/pages.editor.store.settings.pwa.update-manifest-icon.success',\n },\n\n // Install prompt\n pwaPrompt: {\n defaultMessage: 'Prompt \"Add to Home Screen\"',\n id: 'admin/pages.editor.store.settings.pwa.prompt-custom-event',\n },\n addToCartPrompt: {\n defaultMessage: 'On the first item added to cart',\n id: 'admin/pages.editor.store.settings.pwa.prompt-custom-event.addToCart',\n },\n customEventDefault: {\n defaultMessage: 'On the first visit',\n id: 'admin/pages.editor.store.settings.pwa.prompt-custom-event.default',\n },\n})\n\n```"
}
] |
code_admin-pages_ac519bcd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/mutations/SaveAppSettings.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation saveAppSettings($app: String, $version: String, $settings: String) {\n saveAppSettings(app: $app, version: $version, settings: $settings) {\n message\n }\n}\n\n```"
}
] |
code_admin-pages_c644508d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/queries/InstalledApp.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery installedApp($slug: String!) {\n installedApp(slug: $slug) {\n slug\n name\n vendor\n version\n settings\n }\n}\n\n```"
}
] |
code_admin-pages_b96fce00
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/queries/AvailableApp.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery availableApp($id: String!) {\n availableApp(id: $id) {\n id\n title\n installed\n linked\n installedVersion\n settingsSchema\n settingsUiSchema\n }\n}\n\n```"
}
] |
code_admin-pages_56770642
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/StoreForm/components/withStoreSettings.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Query } from 'react-apollo'\nimport { defineMessages } from 'react-intl'\n\nimport { handleCornerCases } from '../../utils/utils'\nimport AvailableApp from '../queries/AvailableApp.graphql'\nimport InstalledApp from '../queries/InstalledApp.graphql'\n\nexport interface InstalledApp {\n slug: string\n name: string\n vendor: string\n version: string\n settings: string\n}\n\ninterface InstalledAppData {\n installedApp: InstalledApp\n}\n\ninterface InstalledAppVariables {\n slug: string\n}\n\nclass InstalledAppQuery extends Query<\n InstalledAppData,\n InstalledAppVariables\n> {}\n\nexport interface AvailableApp {\n id: string\n title: string\n installed: boolean\n linked: boolean\n installedVersion: string\n settingsSchema: string\n settingsUiSchema: string\n}\n\ninterface AvailableAppData {\n availableApp: AvailableApp\n}\n\ninterface AvailableAppVariables {\n id: string\n}\n\nclass AvailableAppQuery extends Query<\n AvailableAppData,\n AvailableAppVariables\n> {}\n\nexport interface FormProps {\n store: AvailableApp &\n InstalledApp & {\n settings: string\n }\n tab?: 'advanced' | 'general'\n}\n\ndefineMessages({\n description: {\n defaultMessage: `Couldn't load store settings.`,\n id: 'admin/pages.editor.store.settings.error',\n },\n title: {\n defaultMessage: 'Something went wrong',\n id: 'admin/pages.editor.store.settings.error.title',\n },\n})\n\nconst options = {\n error: {\n description: 'admin/pages.editor.store.settings.error',\n title: 'admin/pages.editor.store.settings.error.title',\n },\n}\n\nfunction withStoreSettings<T>(\n WrappedComponent: React.ComponentType<T & FormProps>\n) {\n const ComponentWithStoreSettings = (props: T) => (\n <InstalledAppQuery query={InstalledApp} variables={{ slug: 'vtex.store' }}>\n {handleCornerCases<InstalledAppData, InstalledAppVariables>(\n options,\n ({ data: storeData }) => {\n const { installedApp: store } = storeData\n const { slug, version } = store\n return (\n <AvailableAppQuery\n query={AvailableApp}\n variables={{ id: `${slug}@${version}` }}\n >\n {handleCornerCases<AvailableAppData, AvailableAppVariables>(\n options,\n ({ data: { availableApp: schemasData } }) => (\n <WrappedComponent\n {...props}\n store={{\n ...store,\n ...schemasData,\n }}\n />\n )\n )}\n </AvailableAppQuery>\n )\n }\n )}\n </InstalledAppQuery>\n )\n\n return ComponentWithStoreSettings\n}\n\nexport default withStoreSettings\n\n```"
}
] |
code_admin-pages_37a71d57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/mutations/UpdateManifest.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateManifest($manifest: ManifestInput) {\n updateManifest(manifest: $manifest) {\n start_url\n theme_color\n background_color\n display\n orientation\n }\n}\n\n```"
}
] |
code_admin-pages_16ccaef4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/mutations/UpdatePWASettings.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updatePWASettings($settings: PWASettingsInput) {\n updatePWASettings(settings: $settings) {\n disablePrompt\n }\n}\n\n```"
}
] |
code_admin-pages_04389907
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/mutations/UpdateManifestIcon.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateManifest($icon: Upload!, $iOS: Boolean) {\n updateManifestIcon(icon: $icon, iOS: $iOS) {\n icons {\n src\n type\n sizes\n }\n }\n}\n\n```"
}
] |
code_admin-pages_55116b0e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/queries/PWA.graphql from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery PWA {\n # Manifest\n manifest {\n start_url\n theme_color\n background_color\n display\n orientation\n icons {\n src\n type\n sizes\n }\n }\n iOSIcons {\n src\n type\n sizes\n }\n splashes {\n src\n type\n sizes\n }\n pwaSettings {\n disablePrompt\n promptOnCustomEvent\n }\n\n # Styles\n selectedStyle {\n config {\n semanticColors {\n background {\n base\n }\n }\n }\n }\n}\n\n```"
}
] |
code_admin-pages_8fbdd0bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/utils/constants.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface DropdownOption {\n value: string\n label: string\n}\n\nexport const ORIENTATION_OPTIONS: DropdownOption[] = [\n {\n value: 'any',\n label: 'admin/pages.editor.store.settings.pwa.orientation.any',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.orientation.natural',\n value: 'natural',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.orientation.landscape',\n value: 'landscape',\n },\n {\n label:\n 'admin/pages.editor.store.settings.pwa.orientation.landscape-primary',\n value: 'landscape-primary',\n },\n {\n label:\n 'admin/pages.editor.store.settings.pwa.orientation.landscape-secondary',\n value: 'landscape-secondary',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.orientation.portrait',\n value: 'portrait',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.orientation.portrait-primary',\n value: 'portrait-primary',\n },\n {\n label:\n 'admin/pages.editor.store.settings.pwa.orientation.portrait-secondary',\n value: 'portrait-secondary',\n },\n]\n\nexport const DISPLAY_OPTIONS: DropdownOption[] = [\n {\n label: 'admin/pages.editor.store.settings.pwa.display.fullscreen',\n value: 'fullscreen',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.display.standalone',\n value: 'standalone',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.display.minimal-ui',\n value: 'minimal-ui',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.display.browser',\n value: 'browser',\n },\n]\n\n\nexport const INSTALL_PROMPT_OPTIONS: DropdownOption[] = [\n {\n label: 'admin/pages.editor.store.settings.pwa.prompt-custom-event.default',\n value: 'default',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.prompt-custom-event.addToCart',\n value: 'addToCart',\n },\n {\n label: 'admin/pages.editor.store.settings.pwa.prompt-custom-event.checkout',\n value: 'checkout',\n }\n]\n\nexport const TOAST_DURATION = 4000\n\n```"
}
] |
code_admin-pages_7df32d63
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/components/withPWASettings.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { pathOr } from 'ramda'\nimport React from 'react'\nimport { Query, QueryResult } from 'react-apollo'\nimport { defineMessages } from 'react-intl'\n\nimport { handleCornerCases } from '../../utils/utils'\nimport PWA from '../queries/PWA.graphql'\n\nexport interface PWAImage {\n src: string\n type: string\n sizes: string\n}\n\nexport interface PWASettings {\n disablePrompt: boolean\n promptOnCustomEvent: string\n}\n\nexport interface Manifest {\n icons?: PWAImage[]\n background_color: string\n theme_color: string\n orientation?: string\n start_url?: string\n display?: string\n}\n\ninterface PWAData {\n manifest: Manifest\n iOSIcons: PWAImage[]\n splashes: PWAImage[]\n pwaSettings: PWASettings\n selectedStyle: {\n config: {\n semanticColors: {\n background: {\n base: string\n }\n }\n }\n }\n}\n\nexport type PWASettingsProps = PWAData & Pick<QueryResult<PWAData>, 'refetch'>\n\nclass PWAQuery extends Query<PWAData, {}> {}\n\ndefineMessages({\n description: {\n defaultMessage: `Couldn't load store settings.`,\n id: 'admin/pages.editor.store.settings.error',\n },\n title: {\n defaultMessage: `Couldn't load PWA settings.`,\n id: 'admin/pages.editor.store.settings.pwa.error',\n },\n})\n\nconst options = {\n error: {\n description: 'admin/pages.editor.store.settings.error.title',\n title: 'admin/pages.editor.store.settings.pwa.error',\n },\n}\n\nfunction withPWASettings<T>(\n WrappedComponent: React.ComponentType<T & PWASettingsProps>\n) {\n const ComponentWithPWASettings = (props: T) => (\n <PWAQuery query={PWA}>\n {handleCornerCases<PWAData, {}>(options, ({ data, refetch }) => {\n if (\n !data.manifest ||\n !data.manifest.background_color ||\n !data.manifest.theme_color\n ) {\n const color: string = pathOr(\n '',\n ['selectedStyle', 'config', 'semanticColors', 'background', 'base'],\n data\n )\n\n return (\n <WrappedComponent\n {...props}\n {...data}\n manifest={{\n ...(data.manifest || {}),\n ['background_color']: color,\n ['theme_color']: color,\n }}\n refetch={refetch}\n />\n )\n }\n return <WrappedComponent {...props} {...data} refetch={refetch} />\n })}\n </PWAQuery>\n )\n\n return ComponentWithPWASettings\n}\n\nexport default withPWASettings\n\n```"
}
] |
code_admin-pages_7deee22a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/admin/store/PWAForm/components/withPWAMutations.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Mutation, MutationFn, MutationResult } from 'react-apollo'\n\nimport UpdateManifest from '../mutations/UpdateManifest.graphql'\nimport UpdateManifestIcon from '../mutations/UpdateManifestIcon.graphql'\nimport UpdatePWASettings from '../mutations/UpdatePWASettings.graphql'\n\nimport { PWASettings } from './withPWASettings'\n\nexport interface ManifestMutationData {\n start_url: string\n theme_color: string\n background_color: string\n display: string\n orientation: string\n}\n\ninterface UpdateManifestData {\n manifest: ManifestMutationData\n}\n\ninterface UpdateManifestVariables {\n manifest: ManifestMutationData\n}\n\nclass UpdateManifestMutation extends Mutation<\n UpdateManifestData,\n UpdateManifestVariables\n> {}\n\ninterface UpdateManifestIconVariables {\n icon: File\n iOS: boolean\n}\n\nclass UpdateManifestIconMutation extends Mutation<\n UpdateManifestData,\n UpdateManifestIconVariables\n> {}\n\ninterface UpdatePWASettingsData {\n settings: PWASettings\n}\n\nclass UpdatePWASettingsMutation extends Mutation<\n PWASettings,\n UpdatePWASettingsData\n> {}\n\nexport interface PWAMutationProps {\n updateManifest: {\n mutate: MutationFn<UpdateManifestData, UpdateManifestVariables>\n } & MutationResult<UpdateManifestData>\n updateManifestIcon: {\n mutate: MutationFn<UpdateManifestData, UpdateManifestIconVariables>\n } & MutationResult<UpdateManifestData>\n updatePWASettings: {\n mutate: MutationFn<PWASettings, UpdatePWASettingsData>\n } & MutationResult<PWASettings>\n}\n\nconst withPWAMutations = <T extends {}>(\n WrappedComponent: React.ComponentType<T & PWAMutationProps>\n) => {\n const ComponentWithPWAMutations = (props: T) => (\n <UpdateManifestMutation mutation={UpdateManifest}>\n {(updateManifestMutate, updateManifestRest) => (\n <UpdateManifestIconMutation mutation={UpdateManifestIcon}>\n {(updateManifestIconMutate, updateManifestIconRest) => (\n <UpdatePWASettingsMutation mutation={UpdatePWASettings}>\n {(updatePWASettingsMutate, updatePWASettingsRest) => (\n <WrappedComponent\n {...props}\n updateManifest={{\n mutate: updateManifestMutate,\n ...updateManifestRest,\n }}\n updateManifestIcon={{\n mutate: updateManifestIconMutate,\n ...updateManifestIconRest,\n }}\n updatePWASettings={{\n mutate: updatePWASettingsMutate,\n ...updatePWASettingsRest,\n }}\n />\n )}\n </UpdatePWASettingsMutation>\n )}\n </UpdateManifestIconMutation>\n )}\n </UpdateManifestMutation>\n )\n\n return ComponentWithPWAMutations\n}\n\nexport default withPWAMutations\n\n```"
}
] |
code_admin-pages_c8cd9f27
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/MediaGalleryWidget/icons/IconImage.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconImage: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"23\"\n height=\"20\"\n viewBox=\"0 0 23 20\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M3.50146 1.75C2.81068 1.75 2.25146 2.30921 2.25146 3V17C2.25146 17.5802 2.64596 18.0676 3.18156 18.2088L7.29428 13.2729C7.90488 12.5399 8.98838 12.4313 9.73207 13.0263L11.5996 14.5209C11.7085 14.6077 11.866 14.5897 11.952 14.4823L15.288 10.3123C15.8917 9.55808 16.9937 9.43542 17.7482 10.0394L20.7455 12.4371V3C20.7455 2.30921 20.1863 1.75 19.4955 1.75H3.50146ZM22.2455 13.9319V3C22.2455 1.48079 21.0147 0.25 19.4955 0.25H3.50146C1.98225 0.25 0.751465 1.48079 0.751465 3V17C0.751465 18.5192 1.98225 19.75 3.50146 19.75H19.4955C21.0134 19.75 22.2455 18.5195 22.2455 17V14.0689C22.2496 14.0232 22.2496 13.9774 22.2455 13.9319ZM20.7455 14.358L16.8111 11.2106C16.7037 11.1247 16.5455 11.1418 16.4592 11.2495L13.1232 15.4195C12.5193 16.174 11.4186 16.296 10.6635 15.693L8.79503 14.1976C8.68873 14.1127 8.5342 14.1281 8.44683 14.2329L5.09967 18.25H19.4955C20.1855 18.25 20.7455 17.6905 20.7455 17V14.358ZM8.38242 6.11612C7.89427 5.62796 7.10281 5.62796 6.61465 6.11612C6.1265 6.60427 6.1265 7.39573 6.61465 7.88389C7.10281 8.37204 7.89427 8.37204 8.38242 7.88389C8.87058 7.39573 8.87058 6.60427 8.38242 6.11612ZM9.44222 5.0546C8.36821 3.98151 6.62765 3.9818 5.55399 5.05546C4.48005 6.1294 4.48005 7.8706 5.55399 8.94455C6.62794 10.0185 8.36914 10.0185 9.44308 8.94455C10.517 7.8706 10.517 6.1294 9.44308 5.05546L9.44222 5.0546Z\"\n fill={color}\n />\n </svg>\n)\n\nexport default IconImage\n\n```"
}
] |
code_admin-pages_e69cd73d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/OverlayMask/index.tsx from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { CSSTransition } from 'react-transition-group'\nimport styles from './OverlayMask.css'\n\ninterface Props {\n isActive: boolean\n style?: React.CSSProperties\n}\n\nconst classNames = {\n enter: styles['overlay-mask-enter'],\n enterActive: styles['overlay-mask-enter-active'],\n enterDone: styles['overlay-mask-enter-done'],\n exit: styles['overlay-mask-exit'],\n exitActive: styles['overlay-mask-exit-active'],\n exitDone: styles['overlay-mask-exit-done'],\n}\n\nconst timeout = {\n enter: 300,\n exit: 150,\n}\n\nexport default function OverlayMask({ style, isActive }: Props) {\n const overlayMaskStyle: React.CSSProperties = isActive\n ? {}\n : { pointerEvents: 'none' }\n\n return (\n <CSSTransition\n mountOnEnter\n in={isActive}\n timeout={timeout}\n classNames={classNames}\n >\n <div\n className=\"absolute bg-base h-100 w-100\"\n style={{ ...overlayMaskStyle, ...style }}\n />\n </CSSTransition>\n )\n}\n\n```"
}
] |
code_admin-pages_c35a87dc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/OverlayMask/OverlayMask.css from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.overlay-mask-enter {\n opacity: 0;\n}\n\n.overlay-mask-enter-active {\n opacity: 0.8;\n transition: opacity 300ms cubic-bezier(0.19, 1, 0.22, 1);\n}\n\n.overlay-mask-enter-done {\n opacity: 0.8;\n}\n\n.overlay-mask-exit {\n opacity: 0.8;\n}\n\n.overlay-mask-exit-active {\n opacity: 0;\n transition: opacity 150ms cubic-bezier(0.215, 0.61, 0.355, 1);\n}\n\n.overlay-mask-exit-done {\n opacity: 0;\n}\n\n```"
}
] |
code_admin-pages_5ba011f4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/usePortal.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useEffect, useRef } from 'react'\nimport { ObserverReturnType } from './useResizeObserver'\n\nexport default function usePortal({\n subscribeToResize,\n unsubscribeToResize,\n}: ObserverReturnType) {\n const portalContainerRef = useRef<HTMLDivElement>(\n document.createElement<'div'>('div')\n )\n\n useEffect(() => {\n const portalContainer = portalContainerRef.current\n portalContainer.setAttribute('class', 'absolute z-9999')\n const portalRoot = document.querySelector<HTMLDivElement>(\n '.render-provider'\n )\n\n const rootComputedStyle = (portalRoot &&\n window.getComputedStyle(portalRoot)) || { height: 0, width: 0 }\n\n portalContainer.setAttribute(\n 'style',\n `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`\n )\n\n if (portalRoot) {\n portalRoot.prepend(portalContainer)\n }\n\n function resizeCallback() {\n if (portalRoot) {\n const rootComputedStyle = window.getComputedStyle(portalRoot)\n portalContainer.setAttribute(\n 'style',\n `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`\n )\n }\n }\n\n subscribeToResize(resizeCallback)\n\n function resizeOnLoad() {\n const rootComputedStyle = (portalRoot &&\n window.getComputedStyle(portalRoot)) || { height: 0, width: 0 }\n\n portalContainer.setAttribute(\n 'style',\n `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`\n )\n }\n\n window.addEventListener('load', resizeOnLoad)\n\n return () => {\n unsubscribeToResize(resizeCallback)\n\n if (portalRoot) {\n portalRoot.removeChild(portalContainer)\n }\n window.removeEventListener('load', resizeOnLoad)\n }\n }, [subscribeToResize, unsubscribeToResize])\n\n return portalContainerRef.current\n}\n\n```"
}
] |
code_admin-pages_0e93f8f8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useHighlightOnHover.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useCallback, useEffect, useRef } from 'react'\nimport { State } from '../typings'\n\nconst HIGHLIGHT_REMOVAL_TIMEOUT_MS = 300\n\nexport default function useHighlightOnHover({\n editMode,\n editExtensionPoint,\n highlightHandler,\n highlightTreePath,\n sidebarBlocksMap,\n}: State) {\n const highlightRemovalTimeout = useRef<number | undefined>()\n const handleMouseOverHighlight = useCallback<EventListener>(\n e => {\n if (!e.currentTarget || !(e.currentTarget instanceof HTMLElement)) {\n return\n }\n\n const treePath = e.currentTarget.getAttribute('data-extension-point')\n const isEditable =\n treePath &&\n sidebarBlocksMap[treePath] &&\n sidebarBlocksMap[treePath].isEditable\n\n if (isEditable) {\n highlightHandler(treePath)\n }\n\n clearTimeout(highlightRemovalTimeout.current)\n e.stopPropagation()\n },\n [highlightHandler, sidebarBlocksMap]\n )\n\n const handleMouseLeaveHighlight = useCallback<EventListener>(() => {\n if (highlightRemovalTimeout.current) {\n clearTimeout(highlightRemovalTimeout.current)\n }\n\n highlightRemovalTimeout.current = window.setTimeout(() => {\n highlightHandler(null)\n }, HIGHLIGHT_REMOVAL_TIMEOUT_MS)\n }, [highlightHandler])\n\n const handleClickHighlight = useCallback<EventListener>(\n e => {\n if (!e.currentTarget) {\n return\n }\n\n e.preventDefault()\n e.stopPropagation()\n editExtensionPoint(highlightTreePath)\n highlightHandler(null)\n },\n [editExtensionPoint, highlightHandler, highlightTreePath]\n )\n\n useEffect(() => {\n const elements = Array.from(\n document.querySelectorAll(`[data-extension-point]`)\n )\n if (editMode) {\n elements.forEach((e: Element) => {\n const element = e as HTMLElement\n\n if (editMode) {\n element.addEventListener('mouseover', handleMouseOverHighlight)\n element.addEventListener('mouseleave', handleMouseLeaveHighlight)\n element.addEventListener('click', handleClickHighlight)\n element.style.cursor = 'pointer'\n }\n })\n }\n\n return () => {\n if (editMode) {\n elements.forEach((e: Element) => {\n const element = e as HTMLElement\n element.removeEventListener('mouseover', handleMouseOverHighlight)\n element.removeEventListener('mouseleave', handleMouseLeaveHighlight)\n element.removeEventListener('click', handleClickHighlight)\n element.style.cursor = 'default'\n })\n }\n }\n }, [\n handleMouseOverHighlight,\n editMode,\n handleMouseLeaveHighlight,\n handleClickHighlight,\n ])\n}\n\n```"
}
] |
code_admin-pages_6516f4f6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useResizeObserver.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useEffect, useCallback, useRef } from 'react'\nimport observeResize from 'simple-element-resize-detector'\nimport { isArray } from 'util'\n\ntype ResizeFn = (el: Element) => void\n\nexport default function useResizeObserver() {\n const callbacksRef = useRef<Set<ResizeFn>>(new Set())\n\n const subscribeToResize = useCallback((callbacks: ResizeFn | ResizeFn[]) => {\n const fns = isArray(callbacks) ? callbacks : [callbacks]\n fns.forEach(fn => {\n callbacksRef.current.add(fn)\n })\n }, [])\n\n const unsubscribeToResize = useCallback(\n (callbacks: ResizeFn | ResizeFn[]) => {\n const fns = isArray(callbacks) ? callbacks : [callbacks]\n fns.forEach(fn => {\n callbacksRef.current.delete(fn)\n })\n },\n []\n )\n\n useEffect(() => {\n const root = document.querySelector<HTMLBodyElement>('body')\n\n if (root) {\n const currentStyle = root.getAttribute('style') || ''\n const newStyle = currentStyle + 'position: relative;'\n root.setAttribute('style', newStyle)\n }\n\n const resizeDetector =\n root &&\n observeResize(root, element => {\n callbacksRef.current.forEach(fn => {\n fn(element)\n })\n })\n\n return () => {\n if (resizeDetector && resizeDetector.parentNode) {\n resizeDetector.parentNode.removeChild(resizeDetector)\n }\n\n if (root) {\n const currentStyle = root.getAttribute('style') || ''\n const newStyle = currentStyle.replace('position: relative;', '')\n\n if (!newStyle) {\n root.removeAttribute('style')\n } else {\n root.setAttribute('style', newStyle)\n }\n }\n }\n }, [])\n\n return { subscribeToResize, unsubscribeToResize }\n}\n\nexport type ObserverReturnType = ReturnType<typeof useResizeObserver>\n\n```"
}
] |
code_admin-pages_7fb8f41f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useHighlightedElementInfo.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useMemo } from 'react'\nimport { State } from '../typings'\n\nfunction isElementInHorizontalAxis(el: Element) {\n const rect = el.getBoundingClientRect()\n\n return (\n rect.left >= 0 &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth)\n )\n}\n\nfunction getElementInfo(\n highlightTreePath: string,\n sidebarBlocksMap: State['sidebarBlocksMap']\n) {\n const elements = document.querySelectorAll(\n `[data-extension-point=\"${highlightTreePath}\"]`\n )\n\n const provider = document.querySelector<HTMLDivElement>('.render-provider')\n const elementsArray: Element[] = Array.prototype.slice.call(elements)\n\n const viewportMiddle =\n (window.innerWidth || document.documentElement.clientWidth) / 2\n\n const visibleElementsClosestToMiddle = elementsArray\n .filter(currElement => {\n const currRect = currElement.getBoundingClientRect()\n\n return (\n currRect.width > 0 &&\n currRect.height > 0 &&\n isElementInHorizontalAxis(currElement)\n )\n })\n .sort((elemA, elemB) => {\n const rectA = elemA.getBoundingClientRect()\n const rectB = elemB.getBoundingClientRect()\n const middleA = rectA.left || 0 + rectA.width\n const middleB = rectB.left || 0 + rectB.width\n\n const differenceA =\n viewportMiddle - middleA < 0\n ? middleA - viewportMiddle\n : viewportMiddle - middleA\n const differenceB =\n viewportMiddle - middleB < 0\n ? middleB - viewportMiddle\n : viewportMiddle - middleB\n\n if (differenceA < differenceB) {\n return -1\n } else if (differenceA > differenceB) {\n return 1\n }\n return 0\n })\n\n const visibleElement = visibleElementsClosestToMiddle[0]\n\n const isEditable =\n sidebarBlocksMap[highlightTreePath] &&\n sidebarBlocksMap[highlightTreePath].isEditable\n\n const hasValidElement = !(\n !highlightTreePath ||\n elements.length === 0 ||\n !visibleElement ||\n !isEditable ||\n !provider\n )\n\n return { visibleElement, hasValidElement }\n}\n\nexport default function useHighlightedElementInfo(\n highlightTreePath: State['highlightTreePath'],\n sidebarBlocksMap: State['sidebarBlocksMap'],\n elementHeight: State['elementHeight']\n) {\n return useMemo<Partial<ReturnType<typeof getElementInfo>>>(() => {\n return (\n (highlightTreePath &&\n getElementInfo(highlightTreePath, sidebarBlocksMap)) ||\n {}\n )\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [highlightTreePath, sidebarBlocksMap, elementHeight])\n}\n\n```"
}
] |
code_admin-pages_f947e4ee
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useAutoScroll.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport debounce from 'lodash/debounce'\nimport { useEffect } from 'react'\nimport { State } from '../typings'\n\ninterface UseAutoScrollArgs {\n highlightTreePath: State['highlightTreePath']\n editMode: State['editMode']\n visibleElement?: Element\n}\n\nfunction isElementInViewport(el: Element) {\n const rect = el.getBoundingClientRect()\n\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth)\n )\n}\n\nconst scrollToElement = debounce((element: Element) => {\n if (!isElementInViewport(element)) {\n element.scrollIntoView({\n behavior: 'smooth',\n block: 'center',\n inline: 'center',\n })\n }\n}, 75)\n\nexport default function useAutoScroll({\n highlightTreePath,\n editMode,\n visibleElement,\n}: UseAutoScrollArgs) {\n useEffect(() => {\n if (visibleElement && !editMode) {\n scrollToElement(visibleElement)\n }\n }, [visibleElement, editMode])\n\n useEffect(() => {\n if (highlightTreePath === null) {\n scrollToElement.cancel()\n }\n }, [highlightTreePath])\n}\n\n```"
}
] |
code_admin-pages_526cdb49
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useStyles/utils.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CSSProperties } from 'react'\n\nimport { GetStyles } from './typings'\n\nlet defaultHighlightRect = { x: 0, y: 0, width: 0, height: 0 }\n\nconst INITIAL_HIGHLIGHT_RECT = {\n height: 0,\n width: 0,\n x: 0,\n y: 0,\n}\n\nconst BLUE = '#134CD8'\n\nfunction getHighlightRect(visibleElement?: Element) {\n const provider = document.querySelector<HTMLDivElement>('.render-provider')\n\n const iframeBody = document.querySelector('body')\n\n const paddingFromIframeBody = iframeBody\n ? {\n left: parseInt(\n window.getComputedStyle(iframeBody, null).paddingLeft || '0',\n 10\n ),\n right: parseInt(\n window.getComputedStyle(iframeBody, null).paddingRight || '0',\n 10\n ),\n }\n : {\n left: 0,\n right: 0,\n }\n\n const providerRect = (provider &&\n (provider.getBoundingClientRect() as DOMRect)) || { x: 0, y: 0 }\n\n const rect = visibleElement\n ? (visibleElement.getBoundingClientRect() as DOMRect)\n : INITIAL_HIGHLIGHT_RECT\n\n // Add offset from render provider main div\n rect.y += -providerRect.y\n rect.x +=\n -providerRect.x +\n (paddingFromIframeBody.left + paddingFromIframeBody.right) / 2\n\n defaultHighlightRect = rect\n\n return rect\n}\n\nexport const getStyles: GetStyles = ({\n hasValidElement,\n highlightTreePath,\n visibleElement,\n}) => {\n const highlight =\n highlightTreePath && hasValidElement && getHighlightRect(visibleElement)\n\n const { x: left, y: top, width, height } = highlight || defaultHighlightRect\n\n const isBlockWidthSmaller = width < 98 * 1.25\n const isBlockHeightSmaller = height < 26\n\n const highlightDimensions = {\n height: !isBlockHeightSmaller && top - 4 < 0 ? height : height + 8,\n left:\n !isBlockWidthSmaller && width >= document.body.scrollWidth\n ? left\n : left - 4,\n top: !isBlockHeightSmaller && top - 4 < 0 ? top : top - 4,\n width:\n !isBlockWidthSmaller && width >= document.body.scrollWidth\n ? document.body.scrollWidth\n : width + 8,\n }\n\n const highlightWidthRatio =\n highlightDimensions.width / document.body.scrollWidth\n\n const highlightStyle: CSSProperties = {\n ...highlightDimensions,\n boxShadow: `rgb(0, 0, 0) 0px ${60 * highlightWidthRatio}px ${66 *\n highlightWidthRatio}px -${78 * highlightWidthRatio}px`,\n pointerEvents: 'none',\n zIndex: 9999,\n }\n\n const startX = `${highlightDimensions.left}px`\n const endX = `${highlightDimensions.left + highlightDimensions.width}px`\n\n const startY = `${highlightDimensions.top}px`\n const endY = `${highlightDimensions.top + highlightDimensions.height}px`\n\n const maskStyle = {\n clipPath:\n `polygon(0% 0%, 0% 100%, ${startX} 100%, ${startX} ${startY}, ${endX} ${startY}, ` +\n `${endX} ${endY}, ${startX} ${endY}, ${startX} 100%, 100% 100%, 100% 0%)`,\n }\n\n const labelStyle = {\n backgroundColor: BLUE,\n width: 90,\n height: 20,\n transform: `${\n isBlockHeightSmaller || isBlockWidthSmaller ? 'translate(4px, -24px)' : ''\n }`,\n }\n\n return { highlightStyle, labelStyle, maskStyle }\n}\n\n```"
}
] |
code_admin-pages_789457ca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useStyles/typings.d.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CSSProperties } from 'react'\n\nimport { ObserverReturnType } from '../useResizeObserver'\nimport { State } from '../../typings'\n\ninterface GetStylesParams {\n hasValidElement?: boolean\n highlightTreePath: State['highlightTreePath']\n visibleElement?: Element\n}\n\nexport type GetStyles = (\n params: GetStylesParams\n) => {\n highlightStyle: CSSProperties\n labelStyle: CSSProperties\n maskStyle: CSSProperties\n}\n\ninterface UseStylesParams extends GetStylesParams, ObserverReturnType {\n isOverlayMaskActive: boolean\n setState: React.Dispatch<React.SetStateAction<State>>\n}\n\nexport type UseStyles = (params: UseStylesParams) => void\n\n```"
}
] |
code_admin-pages_863933ba
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of admin-pages/react/components/HighlightOverlay/hooks/useStyles/index.ts from the admin-pages VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useCallback, useEffect } from 'react'\n\nimport { UseStyles } from './typings'\nimport { getStyles } from './utils'\n\n/*\n * The \"data-extension-point\" attribute is re-added to the element every\n * time it's edited. By observing it, we can consistently check if the\n * block's automatic height has changed and adapt the HighlightOverlay's\n * height accordingly.\n */\n\nconst useStyles: UseStyles = ({\n hasValidElement,\n highlightTreePath,\n isOverlayMaskActive,\n setState,\n subscribeToResize,\n unsubscribeToResize,\n visibleElement,\n}) => {\n const updateStyles = useCallback(\n (clientHeight?) => {\n const elementHeight: HTMLElement['clientHeight'] = clientHeight\n\n const styles = getStyles({\n hasValidElement,\n highlightTreePath,\n visibleElement,\n })\n\n setState(state => ({\n ...state,\n ...styles,\n elementHeight: elementHeight || state.elementHeight,\n }))\n },\n [hasValidElement, highlightTreePath, setState, visibleElement]\n )\n\n useEffect(() => {\n function resizeCallback(element: Element) {\n updateStyles(element.clientHeight)\n }\n\n subscribeToResize(resizeCallback)\n updateStyles()\n\n return () => {\n unsubscribeToResize(resizeCallback)\n }\n }, [\n isOverlayMaskActive,\n subscribeToResize,\n unsubscribeToResize,\n updateStyles,\n visibleElement,\n ])\n}\n\nexport default useStyles\n\n```"
}
] |
code_similar-products-variants_69064e9e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/docs/README.md from the similar-products-variants VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Similar Products Variants\n\nThe Similar Products Variants app returns similar products related to an SKU so users can select other colors or types of the same product.\n\n\n\n\n## Before you start\n1. Set up similar products in your store’s **Products and SKU.** Access your store’s Admin and go to **Products > Catalog > Products and SKU**.\n2. In **Products and SKU**, in the column **SKU**, click on the desired SKU.\n3. In the field **Similar (Alternative Products)**, type the product name you desire\n\n\n\n4. Then, In **Products and SKU**, in the column **SKU**, click on the one you have added in the last step.\n5. Go to the `Images` tab, and on the field `Label`, type a name to identify the image displayed in the thumbnail through the `imageLabel` prop of the `Similar Products` Variants app.\n\nNow, follow the [app’s configuration below](#configuration) to show the similar products you have set up.\n\n\n## Configuration\n\n1. Using [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference), install the app by running the following:\n\n```bash\nvtex install vtex.similar-products-variants\n```\n2. Add the `vtex.similar-products-variants` app to your theme's dependencies in the `manifest.json`\n\n```json\n\"dependencies\": {\n \"vtex.similar-products-variants\": “0.x”\n}\n```\n\n3. Add the `similar-products-variants` block to the product template you desire, such as `store.product`, to display a similar product list. \n\n\n```json\n...\n \"flex-layout.col#right-col\": {\n \"props\": {\n \"preventVerticalStretch\": true,\n \"rowGap\": 0\n },\n \"children\": [\n \"flex-layout.row#product-name\",\n \"product-rating-summary\",\n \"flex-layout.row#list-price-savings\",\n \"flex-layout.row#selling-price\",\n \"product-installments\",\n \"product-separator\",\n \"product-identifier.product\",\n \"sku-selector\",\n + \"similar-products-variants\",\n \"product-quantity\",\n \"link-seller\",\n \"product-availability\",\n \"product-assembly-options\",\n \"product-gifts\",\n \"flex-layout.row#buy-button\",\n \"availability-subscriber\",\n \"shipping-simulator\",\n \"share#default\"\n ]\n },\n \"similar-products-variants\": {\n \"props\": {\n \"imageLabel\": \"swatch\"\n }\n },\n...\n```\n\n| Prop name | Type | Description | Default value |\n|--------------|--------|------------------------------------| ------------- |\n| `imageLabel` | String | The identifier of the image thumbnail displayed for each variant. The identifier is set in the Admin’s Catalog. If the label does not exist or is not defined, the first image is used. | `null` |\n\n\n## Customization\n\nTo apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\n| CSS Handles |\n| ----------- |\n| `variants` |\n| `title` |\n| `var-wrap` |\n| `img_wrap` |\n| `img_wrap--is-active` |\n| `img` |\n\n```"
}
] |
code_similar-products-variants_8ce07666
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/react/Index.tsx from the similar-products-variants VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { ProductTypes } from 'vtex.product-context'\nimport { useProduct } from 'vtex.product-context'\nimport { useQuery } from 'react-apollo'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useIntl } from 'react-intl'\nimport { Link } from 'vtex.render-runtime'\n\nimport productRecommendationsQuery from './queries/productRecommendations.gql'\n\ninterface SimilarProductsVariantsProps {\n productQuery: {\n product: {\n productId: string\n }\n },\n imageLabel: string\n}\n\nconst CSS_HANDLES = [\n 'variants',\n 'title',\n 'var-wrap',\n 'img_wrap',\n 'img',\n] as const\n\nfunction SimilarProductsVariants({\n productQuery,\n imageLabel\n}: SimilarProductsVariantsProps) {\n const handles = useCssHandles(CSS_HANDLES)\n const intl = useIntl()\n const productContext = useProduct()\n const { route } = useRuntime()\n const productId =\n productQuery?.product?.productId ?? productContext?.product?.productId\n\n const { data, loading, error } = useQuery(productRecommendationsQuery, {\n variables: {\n identifier: { field: 'id', value: productId },\n type: `similars`,\n },\n skip: !productId,\n })\n\n if (loading || error) return null\n\n const { productRecommendations } = data\n\n const { products } = {\n products: productRecommendations || [],\n }\n\n const unique = [\n ...new Set<string>(\n products.map((item: ProductTypes.Product) => item.productId)\n ),\n ]\n\n const items: ProductTypes.Product[] = []\n\n unique.forEach(id => {\n const item = products.find(\n (element: ProductTypes.Product) => element.productId === id\n )\n\n if (item) items.push(item)\n })\n\n if( items.length == 0 ){\n return <></>\n }\n\n return (\n <div className={`${handles.variants}`}>\n <p className={`${handles.title}`}>{intl.formatMessage({ id: \"store/title.label\" })}</p>\n <div className={handles['var-wrap']}>\n {items.map((element: ProductTypes.Product) => {\n const imageIndex = imageLabel === undefined\n ? 0\n : element.items[0].images.findIndex(image => image.imageLabel === imageLabel) === -1\n ? 0\n : element.items[0].images.findIndex(image => image.imageLabel === imageLabel)\n\n const srcImage = element.items[0].images[imageIndex].imageUrl\n return (\n <Link \n key={element.productId}\n className={`${handles.img_wrap}${route?.params?.slug === element.linkText ? '--is-active' : ''}`}\n {...{\n page: 'store.product',\n params: {\n slug: element?.linkText,\n id: element?.productId,\n },\n }}>\n <img\n src={srcImage}\n alt={element.productName}\n height=\"50px\"\n className={`${handles.img} mr3 ${route?.params?.slug === element.linkText ? 'o-50' : ''\n }`\n }\n />\n </Link>\n )\n })}\n </div>\n </div>\n )\n}\n\nSimilarProductsVariants.schema = {\n title: 'SimilarProducts Variants',\n description: 'SimilarProducts Variants',\n type: 'object',\n properties: {},\n}\n\nexport default SimilarProductsVariants\n\n```"
}
] |
code_similar-products-variants_098043ee
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/react/package.json from the similar-products-variants VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^5.21.2\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.order-items\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.1/public/@types/vtex.order-items\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.11.1/public/@types/vtex.order-manager\",\n \"vtex.product-context\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime\",\n \"vtex.search-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.47.2/public/@types/vtex.search-graphql\",\n \"vtex.similar-products-variants\": \"https://roo--paragonsports.myvtex.com/_v/private/typings/linked/v1/vtex.similar-products-variants@0.0.7+build1637602189/public/@types/vtex.similar-products-variants\",\n \"vtex.store-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.85.0/public/@types/vtex.store-resources\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.2/public/@types/vtex.styleguide\"\n },\n \"version\": \"0.1.1\"\n}\n\n```"
}
] |
code_similar-products-variants_fff52b78
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/store/interfaces.json from the similar-products-variants VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"similar-products-variants\": {\n \"component\": \"Index\"\n }\n}\n```"
}
] |
code_similar-products-variants_28a0ad52
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/react/typings/gql.d.ts from the similar-products-variants VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import type { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import type { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```"
}
] |
code_similar-products-variants_c90050c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/react/typings/css.d.ts from the similar-products-variants 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_similar-products-variants_6c232387
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of similar-products-variants/react/queries/productRecommendations.gql from the similar-products-variants 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 productId\n linkText\n specificationGroups {\n name\n originalName\n specifications {\n name\n originalName\n values\n }\n }\n items {\n images {\n imageLabel\n imageUrl\n }\n variations {\n name\n values\n }\n }\n }\n}\n```"
}
] |
code_speedsize_e87d3775
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/docs/README.md from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/CHANGEME) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# APP NAME\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nUnder the app's name, you should explain the topic, giving a **brief description** of the **app's functionality** (what is it for?) in a store.\n\nNext, you can **add media** (either an image of a GIF) if possible, so that users can better understand how the app works in practice. \n\n\n\n## Configuration\n\nIt is possible to install in your store either by using App Store or the VTEX IO Toolbelt.\n\n### Using VTEX App Store\n\n1. Access the **Apps** section in your account's admin page and look for the Icommkt box;\n2. Then, click on the **Install** button;\n3. You'll see a warning message about needing to enter the necessary configurations. Scroll down and type in your **NAME OF A SETTINGS FIELD** in the `NAME OF THE APP` field.\n4. Click on **Save**.\n\n### Using VTEX IO Toolbelt\n\n1. [Install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.icommkt@0.x` app. You can confirm that the app has now been installed by running `vtex ls` again. \n2. Access the **Apps** section in your account's admin page and look for the NAME OF THE APP box. Once you find it, click on the box.\n3. Fill in the `NAME OF THE APP` field with your **NAME OF THE SETTINGS FIELD**.\n4. Click on **Save**.\n\n<!-- Remember to also **showcase any necessary disclaimer** related to the app in this section, such as the different behavior it may display during its configuration. -->\n\n## Modus Operandi *(not mandatory)*\n\nThere are scenarios in which an app can behave differently in a store, according to its configuration. It's crucial then to go through these **behavioral changes** in this section, allowing users to fully understand the **practical application** of the app in their store.\n\nIf you feel compelled to give further details, such as the app's **relationship with others**, don't hesitate to use this section. \n\n<!-- DOCS-IGNORE:start -->\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n<!-- DOCS-IGNORE:end -->\n\n```"
}
] |
code_speedsize_c6431939
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/service-workers/header.js from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nfunction fetchSpeedSizeSW() {\n // eslint-disable-next-line no-console\n console.log('[SpeedSize SW] Fetch of SpeedSizeSW')\n const today = new Date()\n // eslint-disable-next-line no-undef\n importScripts(\"https://di6367dava8ow.cloudfront.net\"+\"/\"+\"8310be04-0308-4646-a73c-13c37508ae99\"+\"/\"+today.getDate()+\"-\"+ (today.getMonth() + 1) +\"-\"+today.getFullYear()+\"/sw.js\");\n}\n\nexport default fetchSpeedSizeSW\n\n```"
}
] |
code_speedsize_52bd26a2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/react/index.tsx from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'vtex.render-runtime'\n\nimport type { PixelMessage } from './typings/events'\n\nexport function handleEvents(e: PixelMessage) {\n switch (e.data.eventName) {\n case 'vtex:pageView': {\n break\n }\n\n default: {\n break\n }\n }\n}\n\nif (canUseDOM) {\n window.addEventListener('message', handleEvents)\n}\n\n```"
}
] |
code_speedsize_d4de26ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/react/package.json from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^25.1.5\",\n \"@types/node\": \"^13.11.0\",\n \"@types/react\": \"^16.9.31\",\n \"@types/react-intl\": \"^3.0.0\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.6.8\",\n \"graphql\": \"^14.5.4\",\n \"react-intl\": \"^3.11.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime\"\n }\n}\n\n```"
}
] |
code_speedsize_db1cc2d3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/store/interfaces.json from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"pixel.speedsize\": {\n \"component\": \"index\"\n }\n}\n\n```"
}
] |
code_speedsize_41bc792b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/public/metadata/messages/es-AR.json from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_speedsize_8eceed92
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/public/metadata/messages/pt-BR.json from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_speedsize_68ff9322
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/public/metadata/messages/en-US.json from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_speedsize_1e2140be
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/react/typings/events.d.ts from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CartChangedData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n | CartIdData\n | PromoViewData\n | PromotionClickData\n | NewsletterSubscriptionData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface UserData extends PageInfoData {\n eventType: 'userData'\n eventName: 'vtex:userData'\n firstName?: string\n lastName?: string\n document?: string\n id?: string\n email?: string\n phone?: string\n isAuthenticated: boolean\n}\n\nexport interface CartIdData extends PageInfoData {\n eventType: 'cartId'\n eventName: 'vtex:cartId'\n cartId: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productPageInfo'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface CartChangedData extends EventData {\n event: 'cartChanged'\n eventName: 'vtex:cartChanged'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n list?: string\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\nexport interface CartData extends EventData {\n event: 'cart'\n eventName: 'vtex:cart'\n orderForm: OrderForm\n}\n\nexport interface PromoViewData extends EventData {\n event: 'promoView'\n eventName: 'vtex:promoView'\n promotions: Promotion[]\n}\n\nexport interface PromotionClickData extends EventData {\n event: 'promotionClick'\n eventName: 'vtex:promotionClick'\n promotions: Promotion[]\n}\n\nexport interface NewsletterSubscriptionData extends EventData {\n event: 'newsletterSubscription'\n eventName: 'vtex:newsletterSubscription'\n name: string\n email: string\n phone: string\n}\n\ninterface Promotion {\n id?: string\n name?: string\n creative?: string\n position?: string\n}\n\ninterface CartItem {\n brand: string\n ean: string\n category: string\n detailUrl: string\n imageUrl: string\n name: string\n price: number\n productId: string\n productRefId: string\n quantity: number\n seller: string\n sellerName: string\n skuId: string\n variant: string\n}\n\nexport interface OrderForm {\n id: string\n items: CartItem[]\n}\n\nexport interface Order {\n accountName: string\n corporateName: string\n coupon: string\n currency: string\n openTextField: string\n orderGroup: string\n salesChannel: string\n visitorAddressCity: string\n visitorAddressComplement: string\n visitorAddressCountry: string\n visitorAddressNeighborhood: string\n visitorAddressNumber: string\n visitorAddressPostalCode: string\n visitorAddressState: string\n visitorAddressStreet: string\n visitorContactInfo: string[]\n visitorContactPhone: string\n visitorType: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionLatestShippingEstimate: Date\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\nexport interface Product {\n brand: string\n brandId: string\n categories: string[]\n categoryId: string\n categoryTree: Array<{ id: string; name: string }>\n detailUrl: string\n items: Item[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean: string\n referenceId: { Key: string; Value: string }\n imageUrl: string\n sellers: Seller[]\n}\n\nexport interface ProductSummary {\n brand: string\n brandId: string\n categories: string[]\n items: ItemSummary[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n sku: ItemSummary\n}\n\ninterface ItemSummary {\n itemId: string\n ean: string\n name: string\n referenceId: { Key: string; Value: string }\n seller: Seller\n sellers: Seller[]\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n sellerName: string\n}\n\nexport interface CommertialOffer {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n}\n\n```"
}
] |
code_speedsize_9d0cf24d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of speedsize/react/typings/global.d.ts from the speedsize VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dataLayer: any[]\n}\n\n```"
}
] |
code_giftcard-protocol-example_b41517b0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/docs/README.md from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n\n\n# Gift Card Protocol Example\n\nA reference app implementing a VTEX IO Gift Card integration service. This app is an example to be followed in order to develop a gift card service integration with VTEX. \n\n## Testing the app\nAt first, once you link this application, it's important to know that so as to test it in a store to place an order, for example, it's necessary to register the external provider on the account. By doing that, Gift Card Hub will know how to compose the routes which it's going to send the requests to. This step can be found in the [GraphQL section](#graphql-queries-and-mutations).\n\nHaving the app linked, it will have the routes mentioned before exposed. At first, you can test all your routes on Postman, to make sure that they work as you expect it to. After doing that, you can trigger the communication between the Gift Card Hub and your application by simulating a purchase on a store. You'll have to configure your provider on an account so you can use it on your simulation.\n\n> **NOTE**: Some endpoints are only used when the order status changes, such as settlement and cancellation, which means that you need to have permission to use the admin panel to change orders' status.\n\n\n## Clients\nIn this example, there are a few clients implemented for you to use.\n- `GiftCardHub`: used to connect to the Gift Card Hub to configure or delete a provider on an account;\n- `GiftCardProvider`: used to connect to the provider's external API, where it must have methods implemented to handle all the request that the Gift Card Hub might make;\n- `VtexCommerce`: basic external client that can be used as the class that can be inherited to develop other clients that connectes to VTEX API. \n\n## Routes\nGift Card Hub expects the provider's API to be able to handle some endpoints that are related to gift card, transactions, cancellations, settlements, etc. In this example, all the routes are defined on the `service.json` and have their handlers implemented. \n> The base URL that is used is defined when configuring the provider on an account.\n\n## Parsers\nAs a way to simplify the logic behind the handlers that are implemented in this example, all the code logic that can be necessary to parse the payloads to a specific format is expected to be implemented inside `parsers` directory. This is necessary because both the external provider API and VTEX API expect specific payload formats. Inside the folder, there are two files, `providerToVtex.ts` and `vtexToProvider.ts`.\n\n### VTEX to Provider\nIn this file, you can define parsers to convert request body formats to the formar that the provider's API expects. In this example, there are some functions implemented, feel free to use them to help developing the integration.\n\n### Provider to VTEX\nIt's not always that the provider's API have response or request bodies that are aligned with the format that VTEX expects. In this file, you can define parsers to convert them.\n\n## GraphQL queries and mutations\n\n### Getting list of providers configured on an account\nThere is a GraphQL query that can be used on GraphiQL to check the providers that are configured on the account you're running this application.\n\nTo do that, you can use the route that is available to GraphiQL when linking this app and write a query similar to the following one:\n\n```graphql\nquery {\n getGiftCardProviders{\n serviceUrl\n oauthProvider\n preAuthEnabled\n cancelEnabled\n }\n}\n```\n\nAfter doing that, you will receive a response similar to this one:\n```json\n{\n \"data\": {\n \"getGiftCardProviders\": [\n {\n \"serviceUrl\": \"http://api.vtex.com/appliancetheme\",\n \"oauthProvider\": \"vtex\",\n \"preAuthEnabled\": true,\n \"cancelEnabled\": true\n },\n {\n \"serviceUrl\": \"https://fabiana--appliancetheme.myvtex.com/my-provider\",\n \"oauthProvider\": \"vtex\",\n \"preAuthEnabled\": true,\n \"cancelEnabled\": true\n }\n ]\n }\n}\n```\n\n> **Note**: There will always be a VTEX Gift Card provider configured on any account, because this is the native provider offered by VTEX.\n\n### Using GraphiQL to configure the gift card provider on an account\n\nIn this example app, there are also two mutations configured, which are related to adding or deleting a provider from an account.\n\n- Setting a provider\n ```graphql\n mutation ($id: String, $giftCardProvInput: GiftCardProviderInput) {\n setGiftCardProvider (id: $id, giftCardProvInput: $giftCardProvInput){\n serviceUrl\n oauthProvider\n preAuthEnabled\n cancelEnabled\n }\n }\n ```\n\n Query variables:\n ```json\n {\n \"id\": \"FabianaTest2\",\n \"giftCardProvInput\": {\n \"serviceUrl\": \"https://fabiana--appliancetheme.myvtex.com/my-provider\",\n \"oauthProvider\": \"vtex\",\n \"preAuthEnabled\": true,\n \"cancelEnabled\": true\n }\n }\n ```\n\n- Deleting a provider\n ```graphql\n mutation ($id: String) {\n deleteGiftCardProvider (id: $id){\n serviceUrl\n oauthProvider\n preAuthEnabled\n cancelEnabled\n }\n }\n ```\n\n Query variables:\n ```json\n {\n \"id\": \"FabianaTest2\",\n }\n ```\n\n```"
}
] |
code_giftcard-protocol-example_3cc58b5f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/graphql/schema.graphql from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n getGiftCardProviders: [GiftCardProvider]\n}\n\ntype Mutation {\n setGiftCardProvider(\n id: String\n giftCardProvInput: GiftCardProviderInput\n ): GiftCardProviderResponse\n deleteGiftCardProvider(id: String): GiftCardProviderResponse\n}\n\ntype GiftCardProvider {\n serviceUrl: String\n oauthProvider: String\n preAuthEnabled: Boolean\n cancelEnabled: Boolean\n}\n\ninput GiftCardProviderInput {\n serviceUrl: String\n oauthProvider: String\n preAuthEnabled: Boolean\n cancelEnabled: Boolean\n}\n\ntype GiftCardProviderResponse {\n serviceUrl: String\n oauthProvider: String\n preAuthEnabled: Boolean\n cancelEnabled: Boolean\n id: String\n caption: String\n _self: Self\n}\n\ninput SelfInput {\n href: String\n}\n\ntype Self {\n href: String\n}\n\n```"
}
] |
code_giftcard-protocol-example_f2d9207a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/service.json from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 512,\n \"ttl\": 43200,\n \"timeout\": 300,\n \"routes\": {\n \"list\": {\n \"path\": \"/my-provider/giftcards/_search\",\n \"public\": true\n },\n \"create\": {\n \"path\": \"/my-provider/giftcards\",\n \"public\": true\n },\n \"get\": {\n \"path\": \"/my-provider/giftcards/:id/\",\n \"public\": true\n },\n \"transactions\": {\n \"path\": \"/my-provider/giftcards/:giftCardId/transactions\",\n \"public\": true\n },\n \"getTransaction\": {\n \"path\": \"/my-provider/giftcards/:giftCardId/transactions/:id/\",\n \"public\": true\n },\n \"authorization\": {\n \"path\": \"/my-provider/giftcards/:giftCardId/transactions/:id/authorization\",\n \"public\": true\n },\n \"cancellation\": {\n \"path\": \"/my-provider/giftcards/:giftCardId/transactions/:id/cancellations\",\n \"public\": true\n },\n \"settlement\": {\n \"path\": \"/my-provider/giftcards/:giftCardId/transactions/:id/settlements\",\n \"public\": true\n }\n }\n}\n\n```"
}
] |
code_giftcard-protocol-example_3d35d4a8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/package.json from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@vtex/api\": \"6.36.2\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"tslint\": \"^5.14.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.8.3\"\n },\n \"resolutions\": {\n \"**/**/acorn\": \"^6.4.1\",\n \"**/**/minimist\": \"^0.2.1\",\n \"**/**/kind-of\": \"^6.0.3\",\n \"**/**/handlebars\": \"^4.3.0\",\n \"**/**/js-yaml\": \"^3.13.1\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"1.0.0\"\n}\n\n```"
}
] |
code_giftcard-protocol-example_ec703552
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/index.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ClientsConfig,\n method,\n ParamsContext,\n RecorderState,\n Service,\n ServiceContext,\n} from '@vtex/api'\n\nimport { Clients } from './clients/index'\nimport {\n createCancellation,\n listAllCancellations,\n} from './handlers/cancellations'\nimport { getOrCreateGiftCard, listGiftCards } from './handlers/giftcards'\nimport { createSettlement, listAllSettlements } from './handlers/settlements'\nimport {\n createTransaction,\n getTransactionAuthorization,\n getTransactionById,\n listTransactions,\n} from './handlers/transactions'\nimport { deleteGiftCardProvider } from './resolvers/deleteGiftCardProvider'\nimport { getGiftCardProviders } from './resolvers/getProviders'\nimport { setGiftCardProvider } from './resolvers/setGiftCardProvider'\nimport { validateCredentials } from './handlers/credentials'\n\nconst TIMEOUT_MS = 800\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients>\n}\n\n// It's possible to check the implementation of each handler in the handlers folder\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n graphql: {\n resolvers: {\n Mutation: {\n deleteGiftCardProvider,\n setGiftCardProvider,\n },\n Query: {\n getGiftCardProviders,\n },\n },\n },\n routes: {\n authorization: method({\n GET: [validateCredentials, getTransactionAuthorization],\n }),\n cancellation: method({\n GET: [validateCredentials, listAllCancellations],\n POST: [validateCredentials, createCancellation],\n }),\n create: method({\n POST: [validateCredentials, getOrCreateGiftCard],\n }),\n get: method({\n GET: [validateCredentials, getOrCreateGiftCard],\n }),\n getTransaction: method({\n GET: [validateCredentials, getTransactionById],\n }),\n list: method({\n POST: [validateCredentials, listGiftCards],\n }),\n settlement: method({\n GET: [validateCredentials, listAllSettlements],\n POST: [validateCredentials, createSettlement],\n }),\n transactions: method({\n GET: [validateCredentials, listTransactions],\n POST: [validateCredentials, createTransaction],\n }),\n },\n})\n\n```"
}
] |
code_giftcard-protocol-example_2e73f068
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/clients/vtexCommerce.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport default class VtexCommerce extends ExternalClient {\n constructor(ctx: IOContext, baseRoute: string, options?: InstanceOptions) {\n super(`http://api.vtex.com/api/${baseRoute}`, ctx, {\n ...options,\n headers: {\n VtexIdclientAutCookie: ctx.authToken,\n ...options?.headers,\n },\n params: {\n an: ctx.account,\n ...options?.params,\n },\n })\n }\n}\n\n```"
}
] |
code_giftcard-protocol-example_e11f1de1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/clients/giftCardHub.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { InstanceOptions, IOContext, RequestTracingConfig } from '@vtex/api'\n\nimport { createTracing } from '../utils/tracing'\nimport VtexCommerce from './vtexCommerce'\n\nexport class GiftCardHub extends VtexCommerce {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, 'giftcardproviders', {\n ...options,\n headers: {\n ...(ctx.adminUserAuthToken\n ? {\n VtexIdclientAutCookie: ctx.adminUserAuthToken,\n }\n : {}),\n },\n })\n }\n\n public getProviders(userToken: string, tracingConfig?: RequestTracingConfig) {\n const metric = 'giftcardprovider-getProviders'\n\n return this.http.get<GiftCardProvider[]>('', {\n headers: {\n VtexIdclientAutCookie: userToken,\n },\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n\n // eslint-disable-next-line max-params\n public createOrUpdateGiftCardProvider(\n id: string,\n body: GiftCardProvider,\n userToken: string,\n tracingConfig?: RequestTracingConfig\n ) {\n const metric = 'giftcardprovider-createOrUpdate'\n return this.http.put<GiftCardProviderResponse>(id, body, {\n headers: {\n VtexIdclientAutCookie: userToken,\n },\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n\n public deleteGiftCardById(\n id: string,\n userToken: string,\n tracingConfig?: RequestTracingConfig\n ) {\n const metric = 'giftcardprovider-Delete'\n return this.http.delete<any>(id, {\n headers: {\n VtexIdclientAutCookie: userToken,\n },\n metric,\n tracing: createTracing(metric, tracingConfig),\n })\n }\n}\n\ninterface GiftCardProvider {\n serviceUrl: string\n oauthProvider: string\n preAuthEnabled: boolean\n cancelEnabled: boolean\n}\n\ninterface GiftCardProviderResponse extends GiftCardProvider {\n id: string\n caption: string\n _self: {\n href: string\n }\n}\n\n```"
}
] |
code_giftcard-protocol-example_97e36d52
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/clients/index.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { GiftCardHub } from './giftCardHub'\nimport { GiftCardProvider } from './giftCardProvider'\n\nexport class Clients extends IOClients {\n public get giftCardHub() {\n return this.getOrSet('giftCardHub', GiftCardHub)\n }\n\n public get giftCardProvider() {\n return this.getOrSet('giftCardProvider', GiftCardProvider)\n }\n}\n\n```"
}
] |
code_giftcard-protocol-example_cabc309a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/clients/giftCardProvider.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport class GiftCardProvider extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n // The first argument is the base URl of your provider API endpoint\n super('baseURL', ctx, options)\n }\n\n public getGiftCardById(_: string) {\n /*\n This is the method that will be used to connect to the provider API\n and get a specific gift card by its id.\n For instance, it's returning a mocked object that it's already in the format\n that VTEX expects.\n It receives a string, which is the id. For now, it returns a mocked gift card,\n but it's here where the connection with the external API will happen.\n */\n\n return {\n balance: 100000,\n caption: 'gift card by id',\n emissionDate: '2020-07-05T14:48:00.000Z',\n expiringDate: '2030-10-10T14:48:00.000Z',\n id: 'xpto1',\n provider: 'FabianaTest',\n transaction: {\n href: 'appliancetheme/giftcardproviders/FabianaTest',\n },\n }\n }\n\n public getListOfGiftCards(_: GiftCardListRequest) {\n /*\n This is the method that will be used to connect to the provider API\n and get a list of available gift cards.\n For instance, it's returning a mocked object that it's already in the format\n that VTEX expects.\n It receives a well defined body, which is the format that the hub uses. For now,\n it's returning a mocked list that contains only one gift card that is already\n in the format that the Hub expects.\n */\n\n return [\n {\n balance: 100000,\n caption: 'gift card by id',\n emissionDate: '2020-07-05T14:48:00.000Z',\n expiringDate: '2030-10-10T14:48:00.000Z',\n id: 'xpto1',\n provider: 'FabianaTest',\n transaction: {\n href: 'appliancetheme/giftcardproviders/FabianaTest',\n },\n },\n ]\n }\n\n public createGiftCard(body: GiftCardRequest) {\n /*\n This is the method that will be used to connect to the provider API\n and create a gift card. It needs to create the gift card and return a body\n response in the format that VTEX expects.\n */\n return body\n }\n\n public createTransaction(_: string, __: TransactionRequest) {\n /*\n This is the method that will be used to connect to the provider API\n and create a gift card. It needs to create the gift card and return a body\n response in the format that VTEX expects.\n */\n return {\n cardId: 'xpto1',\n id: '01010101',\n _self: {\n href: 'appliancetheme/giftcardproviders/FabianaTest',\n },\n }\n }\n\n public listTransactions(_: string) {\n /*\n This is the method that will be used to connect to the provider API\n and create a gift card. It needs to create the gift card and return a body\n response in the format that VTEX expects.\n */\n return []\n }\n\n public getTransactionById(_: string, __: string) {\n /*\n Method that handlers the case of getting a transaction by its id.\n The parameter is the id.\n */\n return {}\n }\n\n public getTransactionAuthorization(_: string, __: string) {\n /*\n Method that handlers the case of getting a transaction authorization by its id.\n The parameters are the transaction id and the gift card id.\n */\n return {}\n }\n\n public createCancellation(\n _: string,\n __: string,\n ___: CreateCancellationBody\n ) {\n /*\n Method that handlers the case of creating a transaction cancellation.\n */\n return {}\n }\n\n public listAllCancellations(_: string, __: string) {\n /*\n Method that handlers the case of getting a transaction authorization by its id.\n The parameter is the id.\n */\n return {}\n }\n\n public createSettlement(_: string, __: string, ___: CreateSettlementBody) {\n /*\n Method that handlers the case of creating a transaction settlement.\n */\n return {}\n }\n\n public listAllSettlements(_: string, __: string) {\n /*\n Method that handlers the case of getting a transaction authorization by its id.\n The parameter is the id.\n */\n return {}\n }\n}\n\n```"
}
] |
code_giftcard-protocol-example_1f683663
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/parsers/vtexToProvider.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const parseGiftCardToProvider = (giftCardRequest: GiftCardRequest) => {\n // Parse here the checkout request to the expected format\n return giftCardRequest\n}\n\nexport const parseTransactionToProvider = (\n transactionRequest: TransactionRequest\n) => {\n // Parse here the checkout request to the expected format\n return transactionRequest\n}\n\n```"
}
] |
code_giftcard-protocol-example_c0bdc87c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/parsers/providerToVtex.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const parseGiftCardToVtex = (\n providerResponse: unknown // replace unknown with the typing of your provider\n): GiftCardResponse => {\n // Parse here your response to the expected format\n return providerResponse as GiftCardResponse\n}\n\nexport const parseTransactionToVtex = (\n providerResponse: unknown // replace unknown with the typing of your provider\n): TransactionResponse => {\n // Parse here your response to the expected format\n return providerResponse as TransactionResponse\n}\n\n```"
}
] |
code_giftcard-protocol-example_a49c4701
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/typings/orderForm.d.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface OrderFormConfiguration {\n paymentConfiguration: PaymentConfiguration\n taxConfiguration: TaxConfiguration | null\n minimumQuantityAccumulatedForItems: number\n decimalDigitsPrecision: number\n minimumValueAccumulated: number\n apps: App[]\n allowMultipleDeliveries: boolean\n allowManualPrice: boolean\n maxNumberOfWhiteLabelSellers: number\n maskFirstPurchaseData: boolean\n recaptchaValidation: boolean\n}\n\ninterface PaymentConfiguration {\n requiresAuthenticationForPreAuthorizedPaymentOption: boolean\n allowInstallmentsMerge: boolean\n blockPaymentSession: boolean\n paymentSystemToCheckFirstInstallment: boolean\n}\n\ninterface TaxConfiguration {\n allowExecutionAfterErrors: boolean\n authorizationHeader: string\n integratedAuthentication: boolean\n url: string | null\n}\n\ninterface App {\n fields: string[]\n id: string\n major: number\n}\n\n```"
}
] |
code_giftcard-protocol-example_12aeca0c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/typings/transaction.d.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface TransactionRequest {\n operation: string\n value: number\n descrption: string\n redemptionToken: string\n redemptionCode: string\n requestId: string\n orderInfo: OrderInfo\n paymentRelatedSellerInfo: PaymentRelatedSellerInfo\n}\n\ninterface TransactionResponse {\n cardId: string\n id: string\n _self: {\n href: string\n }\n}\n\ninterface Transaction {\n value: number\n description: string\n redemptionCode: string\n date: string\n requestId: string\n orderInfo: OrderInfo\n settlement: {\n _href: string\n }\n cancellation: {\n _href: string\n }\n authorization: {\n _href: string\n }\n operation: string\n}\n\ninterface PaymentRelatedSellerInfo {\n seller: string\n sellerOrderId: string\n sellerOrderId: string\n sellerSequence: string\n value: number\n}\n\ninterface OrderInfo {\n orderId: string\n sequence: string\n cart: Cart\n clientProfile: Client\n shipping: string\n}\n\ninterface AuthorizationInfo {\n oid: string\n value: number\n date: string\n}\n\ninterface CancellationInfo {\n oid: string\n value: number\n date: string\n}\n\ninterface SettlementInfo {\n oid: string\n value: number\n date: string\n}\n\n```"
}
] |
code_giftcard-protocol-example_fc7e316b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/typings/cancellation.d.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface CreateCancellationBody {\n value: Float32Array\n requestId: string\n}\n\n```"
}
] |
code_giftcard-protocol-example_57be0ff2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/typings/settlement.d.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface CreateSettlementBody {\n value: Float32Array\n requestId: string\n}\n\n```"
}
] |
code_giftcard-protocol-example_e3b180db
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/typings/giftCard.d.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface GiftCardListResponse {\n id: string\n provider: string\n balance: number\n totalBalance?: number\n relationName?: string\n caption?: string\n groupName: string\n _self: {\n href: string\n }\n}\n\ninterface GiftCardResponse {\n id: string\n redemptionToken?: string\n balance: number\n relationname?: string\n emissionDate: string\n expiringDate: string\n caption?: string\n provider: string\n discount?: boolean\n groupName?: string\n transaction: {\n _href: string\n }\n}\n\ninterface GiftCardRequest {\n relationName: string\n expiringDate: string\n caption: string\n redemptionCode: string\n profileId: string\n multipleRedemptions?: boolean\n restrictedToOwner?: boolean\n multipleCredits?: boolean\n}\n\ninterface GiftCardListRequest {\n client: Client\n cart: Cart\n}\n\ninterface Client {\n id: string\n email: string\n document: string\n}\n\ninterface Cart {\n grandTotal: number\n relationName: string | null\n redemptionCode: string\n discount: number\n shipping: number\n taxes: number\n items: Item[]\n itemsTotal: number\n}\n\ninterface Item {\n productId: string\n id: string\n refId: string\n name: string | null\n price: number\n quantity: number\n}\n\n```"
}
] |
code_giftcard-protocol-example_fba41858
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/utils/tracing.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { RequestTracingConfig } from '@vtex/api'\n\nexport const createTracing = (\n metric: string,\n tracingConfig?: RequestTracingConfig\n) => ({\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n})\n\n```"
}
] |
code_giftcard-protocol-example_7dba0ff8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/resolvers/setGiftCardProvider.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nexport async function setGiftCardProvider(\n _: unknown,\n { id, giftCardProvInput }: SetInput,\n ctx: Context\n) {\n /*\n This resolver is responsible for configuring a gift card\n provider on an account by using GraphQL\n */\n\n const {\n clients: { giftCardHub },\n vtex: { adminUserAuthToken: userToken },\n } = ctx\n\n if (!userToken) {\n throw new AuthenticationError('No authorization provided')\n }\n\n return giftCardHub.createOrUpdateGiftCardProvider(\n id,\n giftCardProvInput,\n userToken\n )\n}\n\ninterface SetInput {\n id: string\n giftCardProvInput: GiftCardProvider\n}\n\ninterface GiftCardProvider {\n serviceUrl: string\n oauthProvider: string\n preAuthEnabled: boolean\n cancelEnabled: boolean\n}\n\n```"
}
] |
code_giftcard-protocol-example_fc6a24f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/resolvers/deleteGiftCardProvider.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nexport async function deleteGiftCardProvider(\n _: unknown,\n { id }: DeleteInput,\n ctx: Context\n) {\n /*\n This resolver is responsible for deleting a gift card provider\n on an account by using GraphQL\n */\n\n const {\n clients: { giftCardHub },\n vtex: { adminUserAuthToken: userToken },\n } = ctx\n\n if (!userToken) {\n throw new AuthenticationError('No authorization provided')\n }\n\n return giftCardHub.deleteGiftCardById(id, userToken)\n}\n\ninterface DeleteInput {\n id: string\n}\n\n```"
}
] |
code_giftcard-protocol-example_35fb8248
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/resolvers/getProviders.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nexport async function getGiftCardProviders(\n _: unknown,\n __: unknown,\n ctx: Context\n) {\n const {\n clients: { giftCardHub },\n vtex: { adminUserAuthToken: userToken },\n } = ctx\n\n if (!userToken) {\n throw new AuthenticationError('No authorization provided')\n }\n\n return giftCardHub.getProviders(userToken)\n}\n\n```"
}
] |
code_giftcard-protocol-example_fe4df1df
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/handlers/cancellations.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function listAllCancellations(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.listAllCancellations(\n id as string,\n giftCardId as string\n )\n}\n\nexport async function createCancellation(ctx: Context) {\n const body: CreateCancellationBody = await json(ctx.req)\n\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.createCancellation(\n id as string,\n giftCardId as string,\n body\n )\n}\n\n```"
}
] |
code_giftcard-protocol-example_b1d69c2e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/handlers/giftcards.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function getOrCreateGiftCard(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { id },\n },\n },\n } = ctx\n\n if (id) {\n ctx.body = giftCardProvider.getGiftCardById(id as string)\n } else {\n const body = await json(ctx.req)\n ctx.body = giftCardProvider.createGiftCard(body)\n }\n\n ctx.status = 200\n ctx.set('Cache-Control', 'no-cache,no-store')\n}\n\nexport async function listGiftCards(ctx: Context) {\n const body = await json(ctx.req)\n\n const {\n clients: { giftCardProvider },\n } = ctx\n\n ctx.status = 200\n ctx.set('Cache-Control', 'no-cache,no-store')\n ctx.body = giftCardProvider.getListOfGiftCards(body)\n}\n\n```"
}
] |
code_giftcard-protocol-example_08117d36
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/handlers/transactions.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function listTransactions(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.listTransactions(giftCardId as string)\n}\n\nexport async function createTransaction(ctx: Context) {\n const body = await json(ctx.req)\n\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.createTransaction(giftCardId as string, body)\n}\n\nexport async function getTransactionById(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.getTransactionById(\n id as string,\n giftCardId as string\n )\n}\n\nexport async function getTransactionAuthorization(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.getTransactionAuthorization(\n id as string,\n giftCardId as string\n )\n}\n\n```"
}
] |
code_giftcard-protocol-example_ba00b5d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/handlers/credentials.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function validateCredentials(ctx: Context, next: () => Promise<any>) {\n if (!ctx.headers['x-provider-api-appkey'] || !ctx.headers['x-provider-api-apptoken']) {\n ctx.status = 401\n ctx.body = {\n message: 'Unauthorized request',\n status: 401\n }\n return\n }\n\n let appSettings: Record<string, unknown>;\n\n try {\n const appId = process.env.VTEX_APP_ID || ctx.vtex\n\n appSettings = await ctx.clients.apps.getAppSettings(appId)\n\n if (!appSettings) {\n ctx.status = 400;\n ctx.body = {\n message: 'Empty app settings giftcard protocol configuration',\n status: 400\n }\n return\n }\n } catch (error) {\n ctx.status = 500;\n ctx.body = {\n message: 'error loading app settings',\n status: 500\n }\n return\n }\n\n const { giftCardHubAppKey, giftCardHubAppToken } = appSettings\n\n if (ctx.headers['x-provider-api-appkey'] !== giftCardHubAppKey ||\n ctx.headers['x-provider-api-apptoken'] !== giftCardHubAppToken\n ) {\n ctx.status = 403\n ctx.body = {\n message: 'Forbidden request',\n status: 403\n }\n return\n }\n\n return await next()\n}\n\n```"
}
] |
code_giftcard-protocol-example_1ca4de9b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of giftcard-protocol-example/node/handlers/settlements.ts from the giftcard-protocol-example VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nexport async function listAllSettlements(ctx: Context) {\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.listAllSettlements(\n id as string,\n giftCardId as string\n )\n}\n\nexport async function createSettlement(ctx: Context) {\n const body: CreateSettlementBody = await json(ctx.req)\n\n const {\n clients: { giftCardProvider },\n vtex: {\n route: {\n params: { giftCardId, id },\n },\n },\n } = ctx\n\n ctx.status = 200\n ctx.body = giftCardProvider.createSettlement(\n id as string,\n giftCardId as string,\n body\n )\n}\n\n```"
}
] |
code_search-page-context_550d3f6c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of search-page-context/docs/README.md from the search-page-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# VTEX Search Page Context app\n\nThis app is the search page context, contains three contexts.\n\n1 - `SearchPageContext`: pass down variables set by user in blocks (SearchPageContext). This way, the children in flex search-result can access it.\n\n2 - `SearchPageStateContext`: holds variable state in search page, like if the search is loading, what mobile layout is selected, etc. (SearchPageStateContext)\n\n3 - `SearchPageDispatchContext`: holds the dispatch function for the search page state context.\n\n## Usage\n\n```jsx\nimport {\n useSearchPageState,\n useSearchPage,\n useSearchPageStateDispatch,\n} from 'vtex.search-page-context/SearchPageContext'\n\n...\n\nconst { pagination, searchQuery } = useSearchPage()\nconst { isFetchingMore } = useSearchPageState()\nconst dispatch = useSearchPageStateDispatch()\n```\n\n```"
}
] |
code_search-page-context_a015ae96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of search-page-context/react/package.json from the search-page-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"devDependencies\": {\n \"@types/node\": \"^11.13.4\",\n \"@types/react\": \"^16.8.13\",\n \"typescript\": \"3.9.7\"\n },\n \"dependencies\": {\n \"react\": \"^16.8.3\",\n \"react-dom\": \"^16.8.3\"\n },\n \"version\": \"0.2.0\"\n}\n\n```"
}
] |
code_search-page-context_cb8395d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of search-page-context/react/SearchPageContext.ts from the search-page-context VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createContext, useContext, useReducer } from 'react'\nimport type { MaybeResponsiveInput } from 'vtex.responsive-values'\n\nconst SearchPageContext = createContext({})\n\nconst useSearchPage = () => useContext(SearchPageContext)\n\nconst SearchPageStateContext = createContext({} as State)\n\nconst useSearchPageState = () => useContext(SearchPageStateContext)\n\nconst SearchPageStateDispatch = createContext((_: ReducerActions) => {})\n\nconst useSearchPageStateDispatch = () => useContext(SearchPageStateDispatch)\n\ninterface LayoutOption {\n name: string\n component: string\n itemsPerRow: MaybeResponsiveInput<number>\n}\n\ninterface State {\n mobileLayout?: string\n showContentLoader?: boolean\n isFetchingMore?: boolean\n galleryLayouts?: LayoutOption[]\n selectedGalleryLayout?: string\n /** For accessibility purposes */\n focusedGalleryLayout?: string\n}\n\ninterface InitialArgs {\n mobileLayout: string\n showContentLoader: boolean\n selectedGalleryLayout?: string\n}\n\ntype ReducerActions =\n | { type: 'SWITCH_LAYOUT'; args: { mobileLayout: string } }\n | { type: 'HIDE_CONTENT_LOADER' }\n | { type: 'SET_FETCHING_MORE'; args: { isFetchingMore: boolean } }\n | { type: 'SET_GALLERY_LAYOUTS'; args: { galleryLayouts: LayoutOption[] } }\n | {\n type: 'SWITCH_GALLERY_LAYOUT'\n args: { selectedGalleryLayout: string; focus?: boolean }\n }\n | { type: 'SET_FOCUS_GALLERY_LAYOUT'; args: { focusedGalleryLayout: string } }\n\nfunction reducer(state: State, action: ReducerActions): State {\n switch (action.type) {\n case 'SWITCH_LAYOUT': {\n const { mobileLayout } = action.args\n\n return { ...state, mobileLayout }\n }\n\n case 'HIDE_CONTENT_LOADER': {\n return { ...state, showContentLoader: false }\n }\n\n case 'SET_FETCHING_MORE': {\n const { isFetchingMore } = action.args\n\n return { ...state, isFetchingMore }\n }\n\n case 'SET_GALLERY_LAYOUTS': {\n const { galleryLayouts } = action.args\n\n return { ...state, galleryLayouts }\n }\n\n case 'SWITCH_GALLERY_LAYOUT': {\n const { selectedGalleryLayout, focus = true } = action.args\n\n const newState = {\n ...state,\n selectedGalleryLayout,\n }\n\n if (focus) {\n newState.focusedGalleryLayout = selectedGalleryLayout\n }\n\n return newState\n }\n\n case 'SET_FOCUS_GALLERY_LAYOUT': {\n const { focusedGalleryLayout } = action.args\n\n return { ...state, focusedGalleryLayout }\n }\n\n default:\n return state\n }\n}\n\nconst useSearchPageStateReducer = (initialState: InitialArgs) => {\n return useReducer(reducer, {\n mobileLayout: initialState.mobileLayout,\n showContentLoader: initialState.showContentLoader,\n selectedGalleryLayout: initialState.selectedGalleryLayout,\n isFetchingMore: false,\n })\n}\n\nexport default {\n SearchPageContext,\n useSearchPage,\n SearchPageStateContext,\n useSearchPageState,\n SearchPageStateDispatch,\n useSearchPageStateDispatch,\n useSearchPageStateReducer,\n}\n\n```"
}
] |
code_search-page-context_cb971d41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of search-page-context/react/typings/vtex.responsive-values.d.ts from the search-page-context 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 // eslint-disable-next-line no-restricted-syntax\n enum InputDevices {\n Mobile = 'mobile',\n Phone = 'phone',\n Tablet = 'tablet',\n Desktop = 'desktop',\n }\n\n // eslint-disable-next-line no-restricted-syntax\n enum InputDevices {\n MOBILE = 'mobile',\n PHONE = 'phone',\n TABLET = 'tablet',\n DESKTOP = 'desktop',\n }\n\n // eslint-disable-next-line no-restricted-syntax\n enum InputDevices {\n mobile = 'mobile',\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n }\n\n // eslint-disable-next-line no-restricted-syntax\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 export type MaybeResponsiveInput<T> = T | ResponsiveInput<T>\n\n type ResponsiveOutput<T> = { [P in keyof typeof OutputDevices]: T }\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.