id
stringlengths
12
53
messages
listlengths
3
3
code_admin-pages_d90e0511
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/queries/UploadFile.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation UploadFile($file: Upload!) {\n uploadFile(file: $file) {\n fileUrl\n }\n}\n\n```" } ]
code_admin-pages_f2289fcc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/queries/AvailableTemplates.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AvailableTemplates($interfaceId: String) {\n availableTemplates(interfaceId: $interfaceId) {\n id\n }\n}\n\n```" } ]
code_admin-pages_5384b971
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/AdminLoadingContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useContext } from 'react'\n\nconst adminLoadingDefaultValue = {\n startLoading: () => {\n window.top.postMessage({ action: { type: 'START_LOADING' } }, '*')\n },\n stopLoading: () => {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n },\n}\n\nconst AdminLoadingContext = React.createContext(adminLoadingDefaultValue)\n\nconst useAdminLoadingContext = () => useContext(AdminLoadingContext)\n\nconst AdminLoadingContextProvider: FunctionComponent = ({ children }) => (\n <AdminLoadingContext.Provider value={adminLoadingDefaultValue}>\n {children}\n </AdminLoadingContext.Provider>\n)\n\nexport { AdminLoadingContextProvider, useAdminLoadingContext }\n\n```" } ]
code_admin-pages_524c83ae
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Loader.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\nconst Loader = () => (\n <FormattedMessage id=\"admin/pages.admin.loading\">\n {text => (\n <span>\n {text}\n &hellip;\n </span>\n )}\n </FormattedMessage>\n)\n\nexport default Loader\n\n```" } ]
code_admin-pages_cf8db433
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorProvider.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport ApolloClient from 'apollo-client'\nimport { difference, equals, path, pathOr, uniq } from 'ramda'\nimport React, { Component } from 'react'\nimport { withApollo } from 'react-apollo'\nimport { canUseDOM, withRuntimeContext } from 'vtex.render-runtime'\nimport { ToastProvider } from 'vtex.styleguide'\nimport {\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\n\nimport { State as HighlightOverlayState } from '../HighlightOverlay'\nimport {\n editorMessagesFromRuntime,\n getAvailableCultures,\n LabelledLocale,\n} from './DomainMessages'\nimport EditorContainer, { APP_CONTENT_ELEMENT_ID } from './EditorContainer'\nimport { EditorContext } from './EditorContext'\n\ntype Props = RenderContextProps &\n ComponentWithIntlProps & {\n client: ApolloClient<unknown>\n isSiteEditor: boolean\n children?: React.ReactNode\n }\n\nexport interface State {\n activeConditions: string[]\n allMatches: boolean\n availableCultures: LabelledLocale[]\n blockData: BlockData\n editMode: boolean\n editTreePath: string | null\n iframeRuntime: RenderContext | null\n iframeWindow?: Window\n isLoading: boolean\n isSidebarVisible: boolean\n messages: RenderRuntime['messages']\n mode: EditorMode\n viewport: Viewport\n}\n\nconst noop = () => {\n return undefined\n}\n\nconst getUrlProperties = (href: string) => {\n const match = href.match(\n /^(https?:)\\/\\/(([^:/?#]*)(?::([0-9]+))?)([/]{0,1}[^?#]*)(\\?[^#]*|)(#.*|)$/\n )\n\n return (\n match && {\n hash: match[7],\n host: match[2],\n hostname: match[3],\n href,\n pathname: match[5],\n port: match[4],\n protocol: match[1],\n search: match[6],\n }\n )\n}\n\nclass EditorProvider extends Component<Props, State> {\n private unlisten?: (() => void) | void\n\n public constructor(props: Props) {\n super(props)\n\n this.state = {\n activeConditions: [],\n allMatches: true,\n availableCultures: [],\n blockData: {},\n editMode: false,\n editTreePath: null,\n iframeRuntime: null,\n iframeWindow: window.self,\n isLoading: false,\n isSidebarVisible: true,\n messages: {},\n mode: 'content',\n viewport: 'desktop',\n }\n\n if (canUseDOM) {\n window.top.__provideRuntime = window.self.__provideRuntime = async (\n runtime,\n messages,\n shouldUpdateRuntime\n ) => {\n const { client, intl } = this.props\n const stateIframeRuntime = this.state.iframeRuntime\n\n let formattedEditorMessages = {}\n\n try {\n formattedEditorMessages = await editorMessagesFromRuntime({\n client,\n domain: 'admin',\n runtime,\n })\n } catch (e) {\n console.error(e)\n }\n\n const newMessages = {\n ...this.state.messages,\n ...messages,\n ...formattedEditorMessages,\n }\n\n this.updateRenderRuntimeMessage(newMessages)\n\n if (shouldUpdateRuntime) {\n await this.props.runtime.updateRuntime()\n }\n\n if (!this.state.iframeRuntime) {\n runtime.updateComponentAssets(this.props.runtime.components)\n this.props.runtime.updateComponentAssets({})\n }\n\n const availableCultures = await getAvailableCultures({ client, intl })\n\n const newState = {\n availableCultures,\n iframeRuntime: runtime,\n ...(stateIframeRuntime\n ? {}\n : {\n iframeWindow: (window.self.document.getElementById(\n 'store-iframe'\n ) as HTMLIFrameElement).contentWindow as Window,\n }),\n messages: newMessages,\n }\n\n await new Promise(resolve => {\n this.setState(newState, resolve)\n })\n\n if (\n stateIframeRuntime &&\n stateIframeRuntime.history &&\n !this.unlisten\n ) {\n this.unlisten = stateIframeRuntime.history.listen(\n (location, action) => {\n const pathFromCurrentPage = stateIframeRuntime.route.path\n const isRootPath =\n pathFromCurrentPage === '/' || location.pathname === '/'\n const hasParamsChanged =\n !location.state ||\n !equals(\n location.state.navigationRoute.params,\n stateIframeRuntime.route.params\n )\n\n const isDifferentPath = isRootPath\n ? pathFromCurrentPage !== location.pathname\n : !pathFromCurrentPage.startsWith(location.pathname) ||\n hasParamsChanged // to consider canonicals\n\n const hasNavigated =\n ['PUSH', 'REPLACE', 'POP'].includes(action) && isDifferentPath\n\n if (hasNavigated) {\n this.handleSetIsLoading(true)\n this.editExtensionPoint(null)\n }\n }\n )\n }\n }\n }\n }\n\n public componentDidMount() {\n const {\n runtime: { production, emitter },\n } = this.props\n\n if (window.top) {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }\n\n const appContentElement = document.getElementById(APP_CONTENT_ELEMENT_ID)\n emitter.addListener('localesChanged', this.emitLocaleEventToIframe)\n\n if (!production) {\n emitter.addListener('localesUpdated', this.emitLocaleEventToIframe)\n }\n\n // Forward scroll events to window so code doesn't have to hook into #app-content\n if (appContentElement) {\n appContentElement.addEventListener(\n 'scroll',\n e => {\n setTimeout(() => window.self.dispatchEvent(e), 0)\n },\n { passive: true }\n )\n }\n }\n\n public componentWillUnmount() {\n const {\n runtime: { production, emitter },\n } = this.props\n\n emitter.removeListener('localesChanged', this.emitLocaleEventToIframe)\n\n if (!production) {\n emitter.removeListener('localesUpdated', this.emitLocaleEventToIframe)\n }\n\n if (this.unlisten) {\n this.unlisten()\n }\n }\n\n public emitLocaleEventToIframe = (event: string) => {\n const emitToIframe: RenderRuntime['emitter'] = pathOr({ emit: noop }, [\n 'state',\n 'iframeRuntime',\n 'emitter',\n ])(this)\n emitToIframe.emit('localesChanged', event)\n }\n\n public editExtensionPoint = (treePath: string | null) => {\n const iframe = document.getElementById('store-iframe') || {}\n const setHighlightTreePath = path<\n (value: Partial<HighlightOverlayState>) => void\n >(['contentWindow', '__setHighlightTreePath'], iframe)\n if (setHighlightTreePath) {\n setHighlightTreePath({\n openBlockTreePath: treePath,\n })\n }\n\n this.setState({ editTreePath: treePath, editMode: false })\n }\n\n public handleToggleEditMode = () => {\n const editMode = !this.state.editMode\n\n this.setState({ editMode }, () => {\n if (window.top) {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }\n })\n }\n\n public toggleSidebarVisibility = () => {\n this.setState(prevState => ({\n ...prevState,\n isSidebarVisible: !prevState.isSidebarVisible,\n }))\n }\n\n public handleAddCondition = (conditionId: string) => {\n this.setState(\n {\n activeConditions: uniq(this.state.activeConditions.concat(conditionId)),\n },\n () => {\n this.props.runtime.updateRuntime({\n conditions: this.state.activeConditions,\n device: this.props.runtime.device,\n })\n }\n )\n }\n\n public handleRemoveCondition = (conditionId: string) => {\n const activeConditions = difference(this.state.activeConditions, [\n conditionId,\n ])\n\n this.setState({ activeConditions }, () => {\n this.props.runtime.updateRuntime({\n conditions: this.state.activeConditions,\n device: this.props.runtime.device,\n })\n })\n }\n\n public handleSetDevice = (device: ConfigurationDevice) => {\n this.props.runtime.setDevice(device)\n\n this.handleSetViewport(device === 'any' ? 'desktop' : device)\n\n this.props.runtime.updateRuntime({\n conditions: this.state.activeConditions,\n device,\n })\n }\n\n public handleSetViewport = (viewport: Viewport) => {\n this.setState({ viewport })\n }\n\n public handleSetMode = (mode: EditorMode) => {\n this.setState({ mode, editMode: mode === 'content' ? false : true })\n }\n\n public handleChangeIframeUrl = (url: string) => {\n window.top.postMessage({ action: { type: 'START_LOADING' } }, '*')\n\n const convertedUrl = getUrlProperties(url)\n const storePath = convertedUrl\n ? `${convertedUrl.pathname}${convertedUrl.search ?? ''}`\n : url\n const pathname = /^\\//.test(storePath) ? storePath : `/${storePath}`\n\n window.top.location.assign(`/admin/cms/site-editor${pathname}`)\n }\n\n public handleSetBlockData = (newBlockData: State['blockData']) => {\n this.setState(prevState => ({\n ...prevState,\n blockData: { ...prevState.blockData, ...newBlockData },\n }))\n }\n\n public render() {\n const { children, isSiteEditor } = this.props\n\n const {\n activeConditions,\n allMatches,\n availableCultures,\n blockData,\n editMode,\n editTreePath,\n iframeRuntime,\n iframeWindow,\n isSidebarVisible,\n messages,\n mode,\n viewport,\n } = this.state\n\n const editor: EditorContextType = {\n activeConditions,\n addCondition: this.handleAddCondition,\n allMatches,\n availableCultures,\n blockData,\n editExtensionPoint: this.editExtensionPoint,\n editMode,\n editTreePath,\n getIsLoading: this.getIsLoading,\n iframeWindow,\n isSidebarVisible,\n messages,\n mode,\n onChangeIframeUrl: this.handleChangeIframeUrl,\n removeCondition: this.handleRemoveCondition,\n setBlockData: this.handleSetBlockData,\n setDevice: this.handleSetDevice,\n setIsLoading: this.handleSetIsLoading,\n setMode: this.handleSetMode,\n setViewport: this.handleSetViewport,\n toggleEditMode: this.handleToggleEditMode,\n toggleSidebarVisibility: this.toggleSidebarVisibility,\n viewport,\n }\n\n return (\n <ToastProvider positioning=\"parent\">\n <EditorContext.Provider value={editor}>\n <EditorContainer\n editor={editor}\n iframeRuntime={iframeRuntime}\n isSiteEditor={isSiteEditor}\n >\n {children}\n </EditorContainer>\n </EditorContext.Provider>\n </ToastProvider>\n )\n }\n\n private getIsLoading = () => this.state.isLoading\n\n private updateRenderRuntimeMessage = (messages: Record<string, string>) => {\n this.props.runtime.addMessages(messages)\n }\n\n private handleSetIsLoading = (isLoading: boolean) => {\n this.setState({ isLoading })\n }\n}\n\nconst EditorWithApolloAndRuntime = withRuntimeContext(\n withApollo<Omit<React.ComponentProps<typeof EditorProvider>, 'client'>>(\n EditorProvider\n )\n)\n\nexport default injectIntl(EditorWithApolloAndRuntime)\n\n```" } ]
code_admin-pages_b9163577
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { createContext, useContext } from 'react'\n\nexport const initialEditorContextState: EditorContextType = {\n activeConditions: [],\n addCondition: () => {},\n allMatches: true,\n availableCultures: [],\n blockData: {},\n editExtensionPoint: () => {},\n editMode: false,\n editTreePath: null,\n getIsLoading: () => false,\n iframeWindow: window.self,\n isSidebarVisible: true,\n messages: {},\n mode: 'content',\n onChangeIframeUrl: () => {},\n setDevice: () => {},\n setIsLoading: () => {},\n setMode: () => {},\n setBlockData: () => {},\n setViewport: () => {},\n toggleEditMode: () => {},\n toggleSidebarVisibility: () => {},\n viewport: 'desktop',\n}\n\nexport const EditorContext = createContext(initialEditorContextState)\n\nEditorContext.displayName = 'EditorContext'\n\nexport const useEditorContext = () => useContext(EditorContext)\n\n```" } ]
code_admin-pages_0e377b0b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Modal.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Button, Modal as StyleguideModal } from 'vtex.styleguide'\n\ninterface Props {\n isActionDanger?: boolean\n isActionLoading: boolean\n isOpen: boolean\n onClickAction?: (event: Event) => void\n onClickCancel?: (event: Event) => void\n onClose: (event?: Event) => void\n textButtonAction: string\n textButtonCancel: string\n textMessage: string | React.ReactNode\n title?: string\n}\n\nconst Modal = ({\n isActionDanger = false,\n isActionLoading,\n isOpen,\n onClickAction,\n onClickCancel,\n onClose,\n textButtonAction,\n textButtonCancel,\n textMessage,\n title,\n}: Props) => (\n <StyleguideModal centered isOpen={isOpen} onClose={onClose} title={title}>\n <p className=\"mt6 lh-copy\">{textMessage}</p>\n\n <div className=\"mt6 flex justify-end\">\n <div className=\"mr3\">\n <Button\n disabled={isActionLoading}\n onClick={onClickCancel}\n size=\"small\"\n variation=\"tertiary\"\n >\n {textButtonCancel}\n </Button>\n </div>\n\n <Button\n isLoading={isActionLoading}\n onClick={onClickAction}\n size=\"small\"\n variation={isActionDanger ? 'danger' : 'primary'}\n >\n {textButtonAction}\n </Button>\n </div>\n </StyleguideModal>\n)\n\nexport default Modal\n\n```" } ]
code_admin-pages_d158aef4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Select.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport ReactSelect, { Option } from 'react-select'\nimport { IconCaretDown, IconCaretUp } from 'vtex.styleguide'\n\ninterface SelectProps {\n errorMessage?: string\n onChange: (options: string[]) => void\n options: Option[]\n value: string[]\n}\n\ntype Props = SelectProps & InjectedIntlProps\n\nconst Select: React.FunctionComponent<Props> = ({\n errorMessage,\n onChange,\n options,\n intl,\n value,\n}) => (\n <Fragment>\n <ReactSelect\n className={`f6 ${errorMessage ? 'b--danger bw1' : ''}`}\n arrowRenderer={(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n { onMouseDown, isOpen }: any // ArrowRendererProps isn't defining isOpen.\n ) => (\n <div\n className=\"outline-0\"\n onMouseDown={onMouseDown}\n role=\"listbox\"\n tabIndex={0}\n >\n {isOpen ? (\n <IconCaretUp color=\"#134cd8\" size={8} />\n ) : (\n <IconCaretDown color=\"#134cd8\" size={8} />\n )}\n </div>\n )}\n multi\n onChange={optionValues => {\n const formattedValue = (optionValues as Option[]).map(\n (item: Option) => item.value as string\n )\n onChange(formattedValue)\n }}\n options={options}\n style={\n errorMessage\n ? {\n borderColor: '#ff4c4c',\n borderWidth: '.125rem',\n }\n : {}\n }\n placeholder={\n <span className=\"ml2\">\n {intl.formatMessage({\n id: 'admin/pages.editor.components.conditions.custom.placeholder',\n })}\n </span>\n }\n value={value}\n />\n {!!errorMessage && (\n <span className=\"c-danger f6 mt3 lh-title\">\n {intl.formatMessage({\n id: errorMessage,\n })}\n </span>\n )}\n </Fragment>\n)\n\nexport default injectIntl(Select)\n\n```" } ]
code_admin-pages_c59a4a98
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/SeoPreview.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\n\ninterface Props {\n title?: string | null\n description?: string | null\n url?: string | null\n}\n\nconst messages = defineMessages({\n seoDescription: {\n defaultMessage: '<Page description>',\n id: 'admin/pages.admin.content.general.seo.description',\n },\n seoTitle: {\n defaultMessage: '<Page title>',\n id: 'admin/pages.admin.content.general.seo.page-title',\n },\n})\n\nconst styles = {\n button: {\n borderRadius: '100%',\n display: 'inline-block',\n height: '10px',\n marginRight: '5px',\n width: '10px',\n },\n buttonClose: {\n backgroundColor: '#ff3d44',\n },\n buttonMaximize: {\n backgroundColor: '#ffa721',\n },\n buttonMinimize: {\n backgroundColor: '#7ed321',\n },\n description: {\n color: '#545454',\n },\n title: {\n color: '#1a0dab',\n },\n url: {\n color: '#006621',\n },\n}\n\nconst SeoPreview = ({ title, description, url }: Props) => {\n const intl = useIntl()\n\n return (\n <div className=\"pl5 pt4 ba br2 bw1 b--muted-4 h-100 pb4\">\n <div>\n <span style={{ ...styles.button, ...styles.buttonClose }} />\n <span style={{ ...styles.button, ...styles.buttonMaximize }} />\n <span style={{ ...styles.button, ...styles.buttonMinimize }} />\n </div>\n <div className=\"pt5\">\n <span\n className={`db f4 pb1 word-break ${!title && 'o-30'}`}\n style={styles.title}\n >\n {title || intl.formatMessage(messages.seoTitle)}\n </span>\n <span\n className={`db f6 pb1 word-break ${!url && 'o-30'}`}\n style={styles.url}\n >\n {`${window.location.origin}${url || '/<url>'}`}\n </span>\n <span\n className={`db pt2 f6 fw3 word-break ${!description && 'o-30'}`}\n style={styles.description}\n >\n {description || intl.formatMessage(messages.seoDescription)}\n </span>\n </div>\n </div>\n )\n}\n\nexport default SeoPreview\n\n```" } ]
code_admin-pages_fdb0e6b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/blocks/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type BlockRole = 'after' | 'around' | 'before'\n\nexport type BlockRolesForTree = BlockRole | 'blocks'\n\nexport interface RelativeBlocks {\n [role: string]: string[] | undefined\n}\n\n```" } ]
code_admin-pages_cf57d93c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/blocks/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { BlockRole, BlockRolesForTree, RelativeBlocks } from './typings'\n\nexport const getBlockRole = (treePathTail: string): BlockRolesForTree => {\n const blockRoleMatch = treePathTail.match(/\\$(after|around|before)_/)\n\n if (!blockRoleMatch) {\n return 'blocks'\n }\n\n return blockRoleMatch[1] as BlockRolesForTree\n}\n\nexport const getBlockPath = (\n extensions: RenderContext['extensions'],\n treePath: string | null\n): BlockPath => {\n if (!treePath) {\n return []\n }\n\n const splitTreePath = treePath.split('/')\n\n const blockId = extensions[treePath].blockId\n const blockRole = getBlockRole(splitTreePath[splitTreePath.length - 1])\n\n if (!blockId) {\n return []\n }\n\n const parentTreePath = splitTreePath\n .slice(0, splitTreePath.length - 1)\n .join('/')\n\n const formattedBlock: FormattedBlock = {\n id: blockId,\n role: blockRole\n ? (blockRole.toUpperCase() as FormattedBlock['role'])\n : 'BLOCK',\n }\n\n if (parentTreePath.length === 0) {\n const formattedTemplateBlock: FormattedBlock = {\n ...formattedBlock,\n role: 'TEMPLATE',\n }\n\n return [formattedTemplateBlock]\n }\n\n const parentBlockPath = getBlockPath(extensions, parentTreePath)\n\n if (!parentBlockPath) {\n return []\n }\n\n return [...parentBlockPath, formattedBlock]\n}\n\nexport const getParentBlockId = (\n extensions: RenderContext['extensions'],\n splitTreePath: string[]\n) => {\n const treePathTail = splitTreePath[splitTreePath.length - 1]\n\n const maybeBlockInfo = treePathTail.match(/\\$(after|around|before)_(\\d+)/)\n\n if (!maybeBlockInfo) {\n return null\n }\n\n const blockRole = maybeBlockInfo[1] as BlockRole\n const blockIndex = parseInt(maybeBlockInfo[2], 10)\n\n const parentTreePath = splitTreePath\n .slice(0, splitTreePath.length - 1)\n .join('/')\n\n const parentBlock = extensions[parentTreePath]\n\n const parentBlockRoleArray = parentBlock && parentBlock[blockRole]\n\n const blockId = parentBlockRoleArray && parentBlockRoleArray[blockIndex]\n\n return blockId\n}\n\nexport const getRelativeBlocksIds = (\n treePath: string | null,\n extensions: RenderContext['extensions'],\n targetObj: RelativeBlocks\n) => {\n if (!treePath) {\n return {}\n }\n\n return Object.entries(targetObj).reduce<RelativeBlocks>(\n (acc, [currKey, currValue]) =>\n currValue\n ? {\n ...acc,\n [currKey]: currValue.map(\n block => extensions[`${treePath}/${block}`].blockId as string\n ),\n }\n : acc,\n {}\n )\n}\n\nexport const getSitewideTreePath = (treePath: string) =>\n ['*', ...treePath.split('/').slice(1)].join('/')\n\n```" } ]
code_admin-pages_d57ced61
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/date/index.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getNextDay, getNextTime, getPreviousTime } from './index'\n\ndescribe('getNextDay', () => {\n it('returns the day after a given day', () => {\n const input = new Date('2019-04-01T12:07:21.000')\n\n const expectedOutput = new Date('2019-04-02T00:00:00.000')\n\n expect(getNextDay(input)).toEqual(expectedOutput)\n })\n})\n\ndescribe('getNextTime', () => {\n it('works with minutes = 0', () => {\n const input = new Date('2019-04-01T12:00:00.000')\n\n const expectedOutput = new Date('2019-04-01T12:30:00.000')\n\n expect(getNextTime(input)).toEqual(expectedOutput)\n })\n\n it('works with 0 < minutes < 30', () => {\n const input = new Date('2019-04-01T12:23:16.000')\n\n const expectedOutput = new Date('2019-04-01T12:30:00.000')\n\n expect(getNextTime(input)).toEqual(expectedOutput)\n })\n\n it('works with minutes = 30', () => {\n const input = new Date('2019-04-01T15:30:00.000')\n\n const expectedOutput = new Date('2019-04-01T16:00:00.000')\n\n expect(getNextTime(input)).toEqual(expectedOutput)\n })\n\n it('works with 30 < minutes <= 59', () => {\n const input = new Date('2019-04-01T12:43:51.000')\n\n const expectedOutput = new Date('2019-04-01T13:00:00.000')\n\n expect(getNextTime(input)).toEqual(expectedOutput)\n })\n\n it('works with time > 23:30', () => {\n const input = new Date('2019-04-01T23:45:34.000')\n\n const expectedOutput = new Date('2019-04-02T00:00:00.000')\n\n expect(getNextTime(input)).toEqual(expectedOutput)\n })\n})\n\ndescribe('getPreviousTime', () => {\n it('works with minutes = 0', () => {\n const input = new Date('2019-04-01T12:00:00.000')\n\n const expectedOutput = new Date('2019-04-01T11:30:00.000')\n\n expect(getPreviousTime(input)).toEqual(expectedOutput)\n })\n\n it('works with 0 < minutes < 30', () => {\n const input = new Date('2019-04-01T12:23:16.000')\n\n const expectedOutput = new Date('2019-04-01T12:00:00.000')\n\n expect(getPreviousTime(input)).toEqual(expectedOutput)\n })\n\n it('works with minutes = 30', () => {\n const input = new Date('2019-04-01T15:30:00.000')\n\n const expectedOutput = new Date('2019-04-01T15:00:00.000')\n\n expect(getPreviousTime(input)).toEqual(expectedOutput)\n })\n\n it('works with 30 < minutes <= 59', () => {\n const input = new Date('2019-04-01T12:43:51.000')\n\n const expectedOutput = new Date('2019-04-01T12:30:00.000')\n\n expect(getPreviousTime(input)).toEqual(expectedOutput)\n })\n\n it('works with time = 00:00', () => {\n const input = new Date('2019-04-01T00:00:00.000')\n\n const expectedOutput = new Date('2019-03-31T23:30:00.000')\n\n expect(getPreviousTime(input)).toEqual(expectedOutput)\n })\n})\n\n```" } ]
code_admin-pages_7fb195f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/date/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport moment from 'moment'\n\nexport const getFirstTime = (date: Date) =>\n moment(date)\n .startOf('day')\n .toDate()\n\nexport const getFormattedLocalizedDate = (date: string, locale: string) =>\n moment(date)\n .locale(locale)\n .format(\"lll\")\n\nexport const getLastTime = (date: Date) => {\n const dateClone = new Date(date)\n\n dateClone.setHours(23, 30, 0, 0)\n\n return dateClone\n}\n\nexport const getNextDay = (date: Date) => {\n const dateClone = new Date(date)\n\n dateClone.setDate(date.getDate() + 1)\n dateClone.setHours(0, 0, 0, 0)\n\n return dateClone\n}\n\nexport const getNextTime = (date: Date) => {\n const dateClone = new Date(date)\n\n const hours = dateClone.getHours()\n const minutes = dateClone.getMinutes()\n\n if (minutes >= 0 && minutes < 30) {\n dateClone.setHours(hours, 30, 0, 0)\n } else {\n dateClone.setHours(hours, 0, 0, 0)\n\n dateClone.setTime(dateClone.getTime() + 60 * 60 * 1000)\n }\n\n return dateClone\n}\n\nexport const getPreviousTime = (date: Date) => {\n const dateClone = new Date(date)\n\n const hours = dateClone.getHours()\n const minutes = dateClone.getMinutes()\n\n if (minutes > 0 && minutes <= 30) {\n dateClone.setHours(hours, 0, 0, 0)\n } else {\n dateClone.setHours(hours, 30, 0, 0)\n\n if (minutes === 0) {\n dateClone.setTime(dateClone.getTime() - 60 * 60 * 1000)\n }\n }\n\n return dateClone\n}\n\nexport const isLastTime = (time: Date) =>\n time.getHours() === 23 && time.getMinutes() >= 30\n\nexport const isSameDay = (dateA?: Date, dateB?: Date) => {\n if (!dateA || !dateB) {\n return false\n }\n\n return moment(dateA).isSame(dateB, 'day')\n}\n\n```" } ]
code_admin-pages_0fa937b5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/auditEvents/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { v4 as uuidv4 } from 'uuid'\n\nexport const createEventObject = (\n operation: string,\n entityName: string,\n account: string,\n workspace: string,\n subjectId?: any\n) => {\n const event = {\n id: uuidv4(),\n date: new Date().toISOString(),\n mainAccountName: account,\n accountName: account,\n subjectId: subjectId ? subjectId : '',\n application: 'site-editor',\n workspace: workspace,\n operation,\n meta: {\n entityName,\n entityBeforeAction: '',\n entityAfterAction: '',\n remoteIpAddress: '0.0.0.0',\n forwardFromVtexUserAgent: 'cms',\n },\n }\n\n return event\n}\n\n```" } ]
code_admin-pages_6fce1237
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/components/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JSONSchema6 } from 'json-schema'\nimport { RenderComponent } from 'vtex.render-runtime'\n\nexport type PropsOrContent = Extension['content'] | Extension['props']\n\nexport interface GetActiveContentIdParams {\n extensions: RenderContext['extensions']\n treePath: EditorContextType['editTreePath']\n}\n\nexport interface GetComponentSchemaParams {\n component: RenderComponent | null\n contentSchema?: JSONSchema6\n propsOrContent: PropsOrContent\n runtime: RenderContext\n isContent: boolean\n}\n\nexport interface GetSchemaPropsOrContentParams {\n messages?: RenderContext['messages']\n schema?: JSONSchema6Definition\n propsOrContent?: Record<string, unknown>\n}\n\nexport interface GetSchemaPropsOrContentFromRuntimeParams {\n component: RenderComponent | null\n contentSchema?: JSONSchema6\n isContent?: boolean\n messages?: RenderContext['messages']\n propsOrContent: PropsOrContent\n runtime: RenderContext\n}\n\nexport interface TranslateMessageParams {\n dictionary: Record<string, string>\n id?: string\n}\n\nexport interface UpdateExtensionFromFormParams {\n data: object\n isContent?: boolean\n runtime: RenderContext\n treePath: string | null\n}\n\n```" } ]
code_admin-pages_b8256e1e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/components/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { assocPath, merge, mergeDeepRight, reduce, toPairs } from 'ramda'\nimport Ajv from 'vtex.ajv'\nimport { global, Window } from 'vtex.render-runtime'\n\nimport {\n GetActiveContentIdParams,\n GetComponentSchemaParams,\n GetSchemaPropsOrContentFromRuntimeParams,\n GetSchemaPropsOrContentParams,\n PropsOrContent,\n TranslateMessageParams,\n UpdateExtensionFromFormParams,\n} from './typings'\n\nexport const IOMESSAGE_FORMAT_TYPE = 'IOMessage'\nexport const RICHTEXT_FORMAT_TYPE = 'RichText'\nexport const IO_MESSAGE_FORMATS = [IOMESSAGE_FORMAT_TYPE, RICHTEXT_FORMAT_TYPE]\n\nconst INVISIBLE_CHARACTER = '\\u200b'\nconst INVISIBLE_CHARACTERS_REGEX = new RegExp(INVISIBLE_CHARACTER, 'g')\n\nconst reduceProperties = (isContent: boolean) => (\n acc: ComponentSchemaProperties,\n [propertyName, property]: [string, ComponentSchema]\n) => {\n if (property.type === 'object') {\n property.properties = reduce(\n reduceProperties(isContent),\n {},\n toPairs(property.properties)\n )\n }\n if (Boolean(property.isLayout) !== isContent) {\n acc[propertyName] = property\n }\n\n return acc\n}\n\nconst hideLayoutOrContentFromSchema = (\n schema: ComponentSchema | ComponentSchema[],\n isContent: boolean\n) => {\n if (Array.isArray(schema) || Boolean(schema.isLayout) === isContent) {\n return {}\n }\n\n if (schema.type === 'object' && schema.properties) {\n const newSchema = {\n ...schema,\n properties: reduce(\n reduceProperties(isContent),\n {},\n toPairs(schema.properties)\n ),\n }\n return newSchema\n }\n\n return schema\n}\n\nconst setArraySchemaDefaultsDeep: (\n schema: ComponentSchema | ComponentSchema['items']\n) => ComponentSchema | ComponentSchema[] = schema => {\n if (!schema || Array.isArray(schema) || schema.type !== 'array') {\n return typeof schema === 'undefined' ? {} : schema\n }\n\n schema.items = setArraySchemaDefaultsDeep(schema.items)\n\n if (!schema.minItems || schema.minItems < 1) {\n schema.minItems = 1\n }\n\n if (schema.items && !Array.isArray(schema.items)) {\n schema.items.properties = {\n __editorItemTitle: {\n default: schema.items.title,\n title: 'Item title',\n type: 'string',\n },\n ...schema.items.properties,\n }\n }\n\n return schema\n}\n\nexport const getComponentSchema = ({\n component,\n contentSchema,\n isContent,\n propsOrContent,\n runtime,\n}: GetComponentSchemaParams): ComponentSchema => {\n const componentSchema: ComponentSchema = (component &&\n (component.schema ||\n (component.getSchema &&\n component.getSchema(propsOrContent, { routes: runtime.pages })))) || {\n properties: {},\n type: 'object',\n }\n\n const adaptedComponentSchema = hideLayoutOrContentFromSchema(\n setArraySchemaDefaultsDeep(componentSchema),\n isContent\n )\n\n if (!contentSchema) {\n return adaptedComponentSchema\n }\n\n return mergeDeepRight(adaptedComponentSchema, contentSchema) as any\n}\n\nexport const getExtension = (\n editTreePath: EditorContextType['editTreePath'],\n extensions: RenderContext['extensions']\n): Required<Extension> => {\n const {\n after = [],\n around = [],\n before = [],\n blockId = '',\n blocks = [],\n component = null,\n composition = 'blocks',\n configurationsIds = [],\n content = {},\n contentIds = [],\n contentMapId = '',\n hasContentSchema = false,\n implementationIndex = 0,\n implements: extensionImplements = [],\n preview = null,\n props = {},\n render = 'server',\n shouldRender = false,\n track = [],\n title = '',\n } = (editTreePath && extensions[editTreePath]) || {}\n\n return {\n after,\n around,\n before,\n blockId,\n blocks,\n component,\n composition,\n configurationsIds,\n content,\n contentIds,\n contentMapId,\n hasContentSchema,\n implementationIndex,\n implements: extensionImplements,\n preview,\n props: props || {},\n render,\n shouldRender,\n track,\n title,\n }\n}\n\nexport const getIframeRenderComponents = () => {\n const iframe = document.getElementById('store-iframe') as HTMLIFrameElement\n if (!iframe) {\n return null\n }\n const window = iframe.contentWindow as Window | null\n if (!window) {\n return null\n }\n return window.__RENDER_8_COMPONENTS__\n}\n\nexport const getIframeImplementation = (component: string | null) => {\n if (component === null) {\n return null\n }\n\n const iframeRenderComponents = getIframeRenderComponents()\n\n return iframeRenderComponents && iframeRenderComponents[component]\n}\n\nconst translateMessage = ({\n dictionary,\n id,\n}: TranslateMessageParams): string => {\n if (!id) {\n return ''\n }\n\n const translatedMessage = dictionary[id]\n\n if (translatedMessage) {\n return translatedMessage\n }\n\n if (translatedMessage === '') {\n return ''\n }\n\n return id\n}\n\nexport const updateExtensionFromForm = ({\n data,\n isContent = false,\n runtime,\n treePath,\n}: UpdateExtensionFromFormParams) => {\n if (!treePath) {\n return\n }\n\n return runtime.updateExtension(treePath, {\n ...runtime.extensions[treePath],\n [isContent ? 'content' : 'props']: data,\n })\n}\n\nconst getIOMessageAjv = () => {\n const opts = {\n allErrors: true,\n nullable: true,\n shouldStoreValidSchema: true,\n useDefaults: true,\n }\n\n const ajv = new Ajv(opts)\n const validationFunction = (value: string) => {\n return value.length >= 0\n }\n\n IO_MESSAGE_FORMATS.forEach(format => {\n ajv.addFormat(format, {\n type: 'string',\n validate: validationFunction,\n })\n })\n\n return ajv\n}\n\nconst emptyFields: Record<string, unknown> = {\n any: {},\n array: [],\n boolean: false,\n integer: null,\n number: null,\n object: {},\n string: '',\n}\n\nconst getSchemaEmptyObj = (schema: ComponentSchema, prop: string) => {\n const type =\n schema &&\n schema.properties &&\n schema.properties[prop] &&\n schema.properties[prop].type\n return type ? emptyFields[type] : null\n}\n\nconst keepTheBlanks = (\n validData: object,\n formData: Record<string, unknown> | undefined,\n schema: Record<string, ComponentSchema>\n): Record<string, unknown> => {\n if (!formData) {\n return validData as Record<string, unknown>\n }\n\n return merge(\n validData,\n toPairs(formData).reduce((acc, [prop, value]) => {\n if (!(prop in validData)) {\n return {\n ...acc,\n [prop]: value == null ? getSchemaEmptyObj(schema, prop) : value,\n }\n }\n return acc\n }, {})\n )\n}\n\nexport const appendInvisibleCharacter = (text: string) =>\n text + INVISIBLE_CHARACTER\n\nconst removeInvisibleCharacters = (text: string) =>\n text.replace(INVISIBLE_CHARACTERS_REGEX, '')\n\nexport const getImplementation = (component: string) => {\n return global.__RENDER_8_COMPONENTS__[component]\n}\n\nexport const getSchemaPropsOrContent = ({\n messages,\n schema,\n propsOrContent,\n}: GetSchemaPropsOrContentParams): PropsOrContent => {\n const validate = getIOMessageAjv().compile(schema)\n validate(propsOrContent)\n\n if (!validate.validatedData) {\n return {}\n }\n\n const dataFromSchema = validate.validatedData.reduce(\n (acc, { value, format, dataPath, isLayout }) => {\n if (isLayout) {\n return acc\n }\n\n if (IO_MESSAGE_FORMATS.includes(format)) {\n let adaptedValue\n\n if (messages) {\n adaptedValue = translateMessage({\n dictionary: messages,\n id: value,\n })\n } else {\n // Removes invisible characters from i18n fields. For more\n // information, please check the I18nInput widget.\n adaptedValue = removeInvisibleCharacters(value)\n }\n\n return { ...acc, ...assocPath(dataPath, adaptedValue, acc) }\n }\n\n return { ...acc, ...assocPath(dataPath, value, acc) }\n },\n {}\n )\n\n return keepTheBlanks(dataFromSchema, propsOrContent, schema)\n}\n\nexport const getSchemaPropsOrContentFromRuntime = ({\n component,\n contentSchema,\n isContent = false,\n messages,\n propsOrContent,\n runtime,\n}: GetSchemaPropsOrContentFromRuntimeParams) => {\n if (!component) {\n return null\n }\n\n const componentSchema = getComponentSchema({\n component,\n contentSchema,\n isContent,\n propsOrContent,\n runtime,\n })\n\n return getSchemaPropsOrContent({\n messages,\n propsOrContent,\n schema: componentSchema,\n })\n}\n\nexport const getActiveContentId = ({\n extensions,\n treePath,\n}: GetActiveContentIdParams) => {\n const extension = getExtension(treePath, extensions)\n\n return extension.contentIds[extension.contentIds.length - 1] || ''\n}\n\n```" } ]
code_admin-pages_eb98ac57
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/conditions/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface DateInfo {\n date?: Date\n from?: Date\n to?: Date\n}\n\nexport type DateVerbOptions = 'between' | 'from' | 'is' | 'to'\n\n```" } ]
code_admin-pages_eca1219a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/conditions/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ConditionsStatement } from 'vtex.styleguide'\n\nimport { DateInfo, DateVerbOptions } from './typings'\n\nconst formatDateInfo = (dateInfo: DateInfo, verb: DateVerbOptions) =>\n ({\n between: {\n from: dateInfo.from,\n to: dateInfo.to,\n },\n from: {\n from: dateInfo.date,\n },\n is: {\n from: dateInfo.date,\n },\n to: {\n to: dateInfo.date,\n },\n }[verb])\n\nexport const formatStatements = (statements: ConditionsStatement[]) =>\n statements.map(({ object, subject, verb }) => ({\n objectJSON: JSON.stringify(\n formatDateInfo(object as DateInfo, verb as DateVerbOptions)\n ),\n subject: subject as ConditionSubject,\n verb,\n }))\n\n```" } ]
code_admin-pages_f79ce3d1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/bindings/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface DropdownChangeInput {\n target: {\n value: string\n }\n}\n\n```" } ]
code_admin-pages_cfaa07bb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/bindings/index.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport React, { useMemo } from 'react'\nimport { Binding, Tenant } from 'vtex.tenant-graphql'\n\nconst STORE_PRODUCT = 'vtex-storefront'\nconst LAST_BINDING_KEY = 'vtex.cms-pages.lastBinding'\n\nexport const getStoreBindings = (tenant: Tenant) => {\n return tenant.bindings.filter(\n binding => binding.targetProduct === STORE_PRODUCT\n )\n}\n\nexport const getBindingSelectorOptions = (bindings: Binding[]) =>\n bindings.map(binding => ({\n label: binding.canonicalBaseAddress,\n value: binding.id,\n }))\n\nexport const useBinding = (): [\n Binding | undefined,\n React.Dispatch<Binding | undefined>\n] => {\n const [binding, setBinding] = React.useState<Binding | undefined>(() => {\n const lastBinding = window.localStorage.getItem(LAST_BINDING_KEY)\n return lastBinding ? (JSON.parse(lastBinding) as Binding) : undefined\n })\n\n return [\n binding,\n useMemo(() => {\n return (value: Binding | undefined) => {\n if (value) {\n window.localStorage.setItem(LAST_BINDING_KEY, JSON.stringify(value))\n } else {\n window.localStorage.removeItem(LAST_BINDING_KEY)\n }\n setBinding(value)\n }\n }, [setBinding]),\n ]\n}\n\n```" } ]
code_admin-pages_e1a48374
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ErrorListTemplate.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport { createPortal } from 'react-dom'\nimport { AjvError, ErrorListProps } from 'react-jsonschema-form'\nimport { Alert } from 'vtex.styleguide'\n\ninterface State {\n isVisible: boolean\n}\n\nclass ErrorListTemplate extends Component<ErrorListProps, State> {\n public static defaultProps = {\n errors: [],\n }\n\n public static propTypes = {\n errors: PropTypes.arrayOf(PropTypes.object),\n }\n\n public constructor(props: ErrorListProps) {\n super(props)\n\n this.state = {\n isVisible: true,\n }\n }\n\n public componentDidUpdate(prevProps: ErrorListProps) {\n const { errors: prevErrors } = prevProps\n const { errors: currErrors } = this.props\n const { isVisible } = this.state\n\n const haveErrorsChanged =\n currErrors.length !== prevErrors.length ||\n (currErrors.length > 0 &&\n currErrors.reduce<boolean>(\n (acc, error, index) => error.stack !== prevErrors[index].stack || acc,\n false\n ))\n\n if (!isVisible && haveErrorsChanged) {\n this.setState({ isVisible: true })\n }\n }\n\n public render() {\n const { errors } = this.props\n const { isVisible } = this.state\n\n const container = document.getElementById(\n 'form__error-list-template___alert'\n )\n\n return (\n container &&\n createPortal(\n errors.length > 0 && isVisible && (\n <div className=\"w-100 z-max\">\n <Alert onClose={this.handleHide} type=\"error\">\n {errors.length > 1\n ? `There are ${errors.length} invalid inputs.`\n : this.getErrorMessage(errors[0])}\n </Alert>\n </div>\n ),\n container\n )\n )\n }\n\n private getErrorMessage(error: AjvError) {\n const { message, property } = error\n\n return `${this.getFormattedFieldName(property)} ${message}`\n }\n\n private getFormattedFieldName(fieldName: string) {\n return (\n fieldName.charAt(1).toUpperCase() +\n fieldName.slice(2).replace(/([a-z])([A-Z])/g, '$1 $2')\n )\n }\n\n private handleHide = () => {\n this.setState({ isVisible: false })\n }\n}\n\nconst StatelessErrorListTemplate: React.FunctionComponent<\n ErrorListProps\n> = props => <ErrorListTemplate {...props} />\n\nexport default StatelessErrorListTemplate\n\n```" } ]
code_admin-pages_433e98ab
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/Radio.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { JSONSchema6Type } from 'json-schema'\nimport React, { Component, Fragment } from 'react'\nimport {\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { WidgetProps } from 'react-jsonschema-form'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Radio as StyleguideRadio } from 'vtex.styleguide'\n\ninterface Props extends ComponentWithIntlProps {\n label?: string\n name?: string\n schema: {\n enumNames?: string[]\n }\n}\n\ninterface State {\n value?: JSONSchema6Type\n}\n\ntype RadioProps = Props & WidgetProps\n\nclass Radio extends Component<RadioProps, State> {\n public constructor(props: RadioProps) {\n super(props)\n\n this.state = {\n value: props.value,\n }\n }\n\n public render() {\n const { id, intl, label, name, schema } = this.props\n\n return (\n <Fragment>\n <span className=\"dib mb3 w-100\">\n {formatIOMessage({ id: label, intl })}\n </span>\n {schema.enum &&\n schema.enum.map((item, index) => (\n <StyleguideRadio\n checked={this.props.value === item}\n id={`${id}-${index}`}\n key={`${id}-${index}`}\n label={this.getLabel(item, index)}\n name={name || `${id}-group`}\n onChange={(event: React.ChangeEvent) =>\n this.handleSelection(event, item)\n }\n value={item}\n />\n ))}\n </Fragment>\n )\n }\n\n private getLabel = (item: JSONSchema6Type, index: number) => {\n const {\n intl,\n schema: { enumNames },\n } = this.props\n\n return enumNames && enumNames.length >= index\n ? formatIOMessage({ id: enumNames[index], intl })\n : item && item.toString()\n }\n\n private handleSelection = (\n event: React.ChangeEvent,\n value: JSONSchema6Type\n ) => {\n event.stopPropagation()\n\n this.setState({ value })\n\n this.props.onChange(value)\n }\n}\n\nexport default injectIntl(Radio)\n\n```" } ]
code_admin-pages_64f3acd0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/FieldTemplate.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { JSONSchema6 } from 'json-schema'\nimport React from 'react'\nimport { FieldTemplateProps } from 'react-jsonschema-form'\n\ninterface Props {\n children?: React.ReactNode\n classNames: string\n hidden?: boolean\n schema: JSONSchema6\n}\n\nconst FieldTemplate: React.FunctionComponent<Props & FieldTemplateProps> = ({\n children,\n classNames,\n hidden,\n schema,\n}) => {\n const isHidden =\n hidden || (schema.type !== 'object' && (schema as ComponentSchema).isLayout)\n\n if (isHidden) {\n return null\n }\n\n return <div className={`${classNames} w-100`}>{children}</div>\n}\n\nFieldTemplate.defaultProps = {\n classNames: '',\n hidden: false,\n}\n\nexport default FieldTemplate\n\n```" } ]
code_admin-pages_b631b447
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ObjectFieldTemplate.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { ObjectFieldTemplateProps } from 'react-jsonschema-form'\n\nconst hasFieldToBeDisplayed = (field: ComponentSchema): boolean => {\n if (field.type !== 'object') {\n return !field.isLayout\n }\n\n return Object.values(field.properties || {}).reduce<boolean>(\n (acc, currValue) => acc || hasFieldToBeDisplayed(currValue),\n false\n )\n}\n\nconst ObjectFieldTemplate: React.FunctionComponent<\n ObjectFieldTemplateProps\n> = ({ properties, schema }) =>\n hasFieldToBeDisplayed(schema as ComponentSchema) ? (\n <Fragment>{properties.map(property => property.content)}</Fragment>\n ) : null\n\nObjectFieldTemplate.defaultProps = {\n properties: [],\n}\n\nexport default ObjectFieldTemplate\n\n```" } ]
code_admin-pages_a7879def
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/RichText.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport I18nInput from './I18nInput'\nimport { CustomWidgetProps } from './typings'\n\nconst RichText: React.FunctionComponent<CustomWidgetProps> = props => (\n <I18nInput {...props} isTextarea />\n)\n\nexport default RichText\n\n```" } ]
code_admin-pages_e1c5da07
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { WidgetProps } from 'react-jsonschema-form'\n\nexport interface CustomWidgetProps extends WidgetProps {\n formContext: {\n messages: RenderContext['messages']\n }\n onChange: (value: unknown) => void\n rawErrors?: string[]\n schema: WidgetProps['schema'] & {\n disabled?: boolean\n }\n}\n\n```" } ]
code_admin-pages_261faec9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/BaseInput.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Input } from 'vtex.styleguide'\n\nimport { CustomWidgetProps } from './typings'\n\ninterface Props extends CustomWidgetProps {\n isI18n?: boolean\n label: string\n max?: number\n min?: number\n rawErrors?: string[]\n type?: string\n schema: CustomWidgetProps['schema'] & {\n readonly?: boolean\n }\n}\n\nconst ReadOnlyText = (props: CustomWidgetProps) => {\n const intl = useIntl()\n\n if (!props.schema.title) {\n return null\n }\n\n return (\n <div className=\"pv3 c-on-base t-small mb3\">\n {formatIOMessage({ id: props.schema.title || '', intl })}\n </div>\n )\n}\n\nconst BaseInput: React.FunctionComponent<Props> = props => {\n const {\n disabled,\n id,\n isI18n,\n label,\n max,\n min,\n onBlur,\n onChange,\n onFocus,\n options,\n placeholder,\n rawErrors,\n readonly,\n required,\n schema,\n value,\n } = props\n\n const intl = useIntl()\n\n const schemaType = schema.type === 'number' ? 'number' : 'text'\n\n const type = options.inputType || props.type || schemaType\n\n const currentError = rawErrors && rawErrors[0]\n\n const handleChange = React.useCallback(\n ({ target }: React.ChangeEvent<HTMLInputElement>) => {\n if (isI18n) {\n onChange({ target, value: target.value || '' })\n } else {\n onChange(target.value)\n }\n },\n [isI18n, onChange]\n )\n\n if (schemaType === 'text' && schema.format === 'read-only') {\n return <ReadOnlyText {...props}></ReadOnlyText>\n }\n\n return (\n <Input\n disabled={disabled || schema.disabled}\n error={!!currentError}\n errorMessage={currentError}\n helpText={\n schema.description\n ? formatIOMessage({ id: schema.description, intl })\n : ''\n }\n label={formatIOMessage({ id: label, intl })}\n max={max ? `${max}` : undefined}\n min={min ? `${min}` : undefined}\n onBlur={\n onBlur &&\n ((event: React.ChangeEvent<HTMLInputElement>) =>\n onBlur(id, event.target.value))\n }\n onChange={handleChange}\n onFocus={\n onFocus &&\n ((event: React.ChangeEvent<HTMLInputElement>) =>\n onFocus(id, event.target.value))\n }\n placeholder={placeholder}\n readOnly={readonly || schema.readonly}\n required={required}\n type={type}\n value={value ? `${value}` : ''}\n />\n )\n}\n\nBaseInput.defaultProps = {\n disabled: false,\n placeholder: '',\n rawErrors: [],\n readonly: false,\n required: false,\n}\n\nexport default BaseInput\n\n```" } ]
code_admin-pages_34baee74
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/Dropdown.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Dropdown as StyleguideDropdown } from 'vtex.styleguide'\n\nimport { CustomWidgetProps } from './typings'\n\ninterface Props extends CustomWidgetProps {\n onClose?: () => void\n onOpen?: () => void\n options: { [key: string]: boolean | number | string | object | null }\n}\n\nconst Dropdown: React.FunctionComponent<Props> = ({\n disabled,\n id,\n label,\n onChange,\n onClose,\n onOpen,\n options,\n placeholder,\n readonly,\n schema,\n value,\n}) => {\n const intl = useIntl()\n const handleChange = React.useCallback(\n ({\n target: { value: optionValue },\n }: React.ChangeEvent<HTMLSelectElement>) =>\n onChange(!optionValue ? options.emptyValue : optionValue),\n [onChange, options.emptyValue]\n )\n\n const dropdownOptions = React.useMemo(\n () =>\n Array.isArray(options.enumOptions)\n ? options.enumOptions.map(option => ({\n ...option,\n label: formatIOMessage({ id: `${option.label}`, intl }),\n }))\n : [],\n [intl, options.enumOptions]\n )\n\n return (\n <StyleguideDropdown\n disabled={disabled || (schema && schema.disabled)}\n id={id}\n label={formatIOMessage({ id: label, intl })}\n onChange={handleChange}\n onClose={onClose}\n onOpen={onOpen}\n options={dropdownOptions}\n placeholder={\n placeholder ? formatIOMessage({ id: placeholder, intl }) : ''\n }\n readOnly={readonly}\n value={value}\n />\n )\n}\n\nDropdown.defaultProps = {\n disabled: false,\n readonly: false,\n required: false,\n value: '',\n}\n\nexport default Dropdown\n\n```" } ]
code_admin-pages_2cc7588a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/Toggle.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Toggle as StyleguideToggle } from 'vtex.styleguide'\n\nimport { CustomWidgetProps } from './typings'\n\nconst Toggle: React.FunctionComponent<CustomWidgetProps> = ({\n disabled,\n id,\n label,\n onChange,\n readonly,\n schema: { disabled: disabledBySchema },\n value,\n}) => {\n const intl = useIntl()\n\n return (\n <StyleguideToggle\n checked={value}\n disabled={disabled || disabledBySchema || readonly}\n id={id}\n label={formatIOMessage({ id: label, intl })}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) =>\n onChange(event.target.checked)\n }\n />\n )\n}\n\nToggle.defaultProps = {\n disabled: false,\n readonly: false,\n}\n\nexport default Toggle\n\n```" } ]
code_admin-pages_8e0f0013
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/MultiSelect.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport ReactSelect, { Option } from 'react-select'\n\ninterface Props {\n disabled?: boolean\n id?: string\n label?: string\n onChange: (newValue: string[]) => void\n options: {\n enumOptions: Option[]\n }\n placeholder: string\n schema?: {\n disabled?: boolean\n title: string\n }\n value: string[]\n}\n\nconst MultiSelect: React.FunctionComponent<Props> = ({\n disabled,\n id,\n label,\n onChange,\n options: { enumOptions },\n placeholder,\n schema,\n value,\n}) => (\n <Fragment>\n {(label || (schema && schema.title)) && (\n <label htmlFor={id}>\n <span className=\"dib mb3 w-100\">\n <span>{label || (schema && schema.title)}</span>\n </span>\n </label>\n )}\n <ReactSelect\n disabled={\n disabled || (schema && schema.disabled) || enumOptions.length === 0\n }\n id={id}\n multi\n onChange={optionValues => {\n const formattedValue = (optionValues as Option[]).map(\n (item: Option) => item.value as string\n )\n onChange(formattedValue)\n }}\n options={enumOptions}\n placeholder={placeholder}\n value={value}\n />\n </Fragment>\n)\n\nMultiSelect.defaultProps = {\n disabled: false,\n placeholder: '',\n value: [],\n}\n\nexport default MultiSelect\n\n```" } ]
code_admin-pages_efb2a79c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/TextArea.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { Textarea } from 'vtex.styleguide'\n\nimport { CustomWidgetProps } from './typings'\n\ninterface Props extends CustomWidgetProps {\n isI18n?: boolean\n}\n\nconst TextArea: React.FunctionComponent<Props> = ({\n disabled,\n id,\n isI18n,\n label,\n onBlur,\n onChange,\n onFocus,\n placeholder,\n rawErrors,\n readonly,\n schema,\n value,\n}) => {\n const intl = useIntl()\n const handleBlur = React.useCallback(\n (event: React.FocusEvent<HTMLTextAreaElement>) => {\n if (onBlur) {\n onBlur(id, event.target.value)\n }\n },\n [id, onBlur]\n )\n\n const handleChange = React.useCallback(\n ({ target }: React.ChangeEvent<HTMLTextAreaElement>) => {\n if (isI18n) {\n onChange({ target, value: target.value || '' })\n } else {\n onChange(target.value)\n }\n },\n [isI18n, onChange]\n )\n\n const handleFocus = React.useCallback(\n (event: React.FocusEvent<HTMLTextAreaElement>) => {\n if (onFocus) {\n onFocus(id, event.target.value)\n }\n },\n [id, onFocus]\n )\n\n const [currentError] = Array.isArray(rawErrors) ? rawErrors : ['']\n\n return (\n <Textarea\n disabled={disabled}\n error={!!currentError}\n errorMessage={currentError}\n helpText={\n schema.description\n ? formatIOMessage({ id: schema.description, intl })\n : ''\n }\n label={formatIOMessage({ id: label, intl })}\n onBlur={handleBlur}\n onChange={handleChange}\n onFocus={handleFocus}\n placeholder={\n placeholder ? formatIOMessage({ id: placeholder, intl }) : ''\n }\n readOnly={readonly}\n resize=\"vertical\"\n value={value ? `${value}` : ''}\n />\n )\n}\n\nexport default TextArea\n\n```" } ]
code_admin-pages_bf188f12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport {\n AtomicBlockUtils,\n CompositeDecorator,\n Editor,\n EditorState,\n RichUtils,\n Modifier,\n SelectionState,\n} from 'draft-js'\nimport * as React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\nimport {\n IconBold,\n IconItalic,\n IconOrderedList,\n IconUnderline,\n IconUnorderedList,\n} from 'vtex.styleguide'\n\nimport styles from './style.css'\n\nimport ImageInput from './ImageInput'\nimport Link from './Link'\nimport LinkInput from './LinkInput'\nimport HeadingInput from './HeadingInput'\nimport StyleButton from './StyleButton'\n\nimport {\n convertToEditorState,\n convertToMarkdown,\n findLinkEntities,\n mediaBlockRenderer,\n styleBlockRenderer,\n} from './utils'\n\nconst INLINE_STYLES = [\n {\n label: <IconBold />,\n style: 'BOLD',\n title: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.bold.title\"\n defaultMessage=\"Bold\"\n />\n ),\n },\n {\n label: <IconItalic />,\n style: 'ITALIC',\n title: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.italic.title\"\n defaultMessage=\"Italic\"\n />\n ),\n },\n {\n label: <IconUnderline />,\n style: 'UNDERLINE',\n title: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.underline.title\"\n defaultMessage=\"Underline\"\n />\n ),\n },\n]\n\nconst BLOCK_TYPES = [\n {\n label: <IconUnorderedList />,\n style: 'unordered-list-item',\n title: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.unordered-list.title\"\n defaultMessage=\"Unordered list\"\n />\n ),\n },\n {\n label: <IconOrderedList />,\n style: 'ordered-list-item',\n title: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.ordered-list.title\"\n defaultMessage=\"Ordered list\"\n />\n ),\n },\n]\n\ninterface BlockStyleControlsProps {\n editorState: EditorState\n onToggle: (blockType: string | null) => void\n}\nconst BlockStyleControls = (props: BlockStyleControlsProps) => {\n const { editorState } = props\n const selection = editorState.getSelection()\n const blockType = editorState\n .getCurrentContent()\n .getBlockForKey(selection.getStartKey())\n .getType()\n\n return (\n <>\n {BLOCK_TYPES.map((type, i) => (\n <StyleButton\n key={i}\n title={type.title}\n active={type.style === blockType}\n label={type.label}\n onToggle={props.onToggle}\n style={type.style}\n />\n ))}\n </>\n )\n}\n\ninterface InlineStyleControlsProps {\n editorState: EditorState\n onToggle: (inlineStyle: string | null) => void\n}\nconst InlineStyleControls = (props: InlineStyleControlsProps) => {\n const { editorState } = props\n const currentStyle = editorState.getCurrentInlineStyle()\n\n return (\n <>\n {INLINE_STYLES.map((type, i) => (\n <StyleButton\n key={i}\n title={type.title}\n active={currentStyle.has(type.style)}\n label={type.label}\n onToggle={props.onToggle}\n style={type.style}\n />\n ))}\n </>\n )\n}\n\ninterface Props {\n onChange?: (value: string) => void\n initialState?: string\n}\n\nconst RichTextEditor = ({ onChange, initialState = '' }: Props) => {\n const decorator = new CompositeDecorator([\n { strategy: findLinkEntities, component: Link },\n ])\n const [editorState, setEditorState] = React.useState(\n EditorState.createWithContent(convertToEditorState(initialState), decorator)\n )\n\n let className = `${styles.RichEditor_editor}`\n const contentState = editorState.getCurrentContent()\n if (!contentState.hasText()) {\n if (\n contentState\n .getBlockMap()\n .first()\n .getType() !== 'unstyled'\n ) {\n className += ` ${styles.RichEditor_hidePlaceholder}`\n }\n }\n\n const getContentBlockType = () => {\n const selection = editorState.getSelection()\n return editorState\n .getCurrentContent()\n .getBlockForKey(selection.getStartKey())\n .getType()\n }\n\n const getCurrentSelectionText = () => {\n const selectionState = editorState.getSelection()\n const anchorKey = selectionState.getAnchorKey()\n const currentContent = editorState.getCurrentContent()\n const currentContentBlock = currentContent.getBlockForKey(anchorKey)\n const start = selectionState.getStartOffset()\n const end = selectionState.getEndOffset()\n\n return currentContentBlock.getText().slice(start, end)\n }\n\n const handleAddImage = (imageUrl: string) => {\n const currentOffset = editorState\n .getCurrentContent()\n .getBlockMap()\n .keySeq()\n .findIndex(key => key === editorState.getSelection().getStartKey())\n\n // TODO: find out a better way to handle it\n // if editor is out of focus we force the image to be appended, not prepended\n const defEditorState =\n currentOffset === 0\n ? EditorState.moveFocusToEnd(editorState)\n : editorState\n\n const currentContentState = defEditorState.getCurrentContent()\n const contentStateWithEntity = currentContentState.createEntity(\n 'IMAGE',\n 'IMMUTABLE',\n { src: imageUrl }\n )\n const entityKey = contentStateWithEntity.getLastCreatedEntityKey()\n const newEditorState = EditorState.set(defEditorState, {\n currentContent: contentStateWithEntity,\n })\n return setEditorState(\n AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ')\n )\n }\n\n const handleAddLink = (linkText: string, linkUrl: string) => {\n const selection = editorState.getSelection()\n let currentContentState = editorState.getCurrentContent()\n\n if (!getCurrentSelectionText()) {\n currentContentState = Modifier.insertText(\n currentContentState,\n selection,\n linkText\n )\n\n const newContentWithEntity = currentContentState.createEntity(\n 'LINK',\n 'MUTABLE',\n { url: linkUrl }\n )\n\n const entityKey = newContentWithEntity.getLastCreatedEntityKey()\n const anchorOffset = selection.getAnchorOffset()\n const newSelection = new SelectionState({\n anchorKey: selection.getAnchorKey(),\n anchorOffset,\n focusKey: selection.getAnchorKey(),\n focusOffset: anchorOffset + linkText.length,\n })\n\n const newContentWithLink = Modifier.applyEntity(\n newContentWithEntity,\n newSelection,\n entityKey\n )\n\n const withLinkText = EditorState.push(\n editorState,\n newContentWithLink,\n 'insert-characters'\n )\n\n return setEditorState(\n EditorState.forceSelection(\n withLinkText,\n currentContentState.getSelectionAfter()\n )\n )\n }\n\n const contentStateWithEntity = currentContentState.createEntity(\n 'LINK',\n 'IMMUTABLE',\n { url: linkUrl }\n )\n const entityKey = contentStateWithEntity.getLastCreatedEntityKey()\n const newEditorState = EditorState.set(editorState, {\n currentContent: contentStateWithEntity,\n })\n return setEditorState(\n RichUtils.toggleLink(\n newEditorState,\n newEditorState.getSelection(),\n entityKey\n )\n )\n }\n\n const handleChange = (state: EditorState) => {\n if (onChange) {\n onChange(convertToMarkdown(state))\n }\n\n return setEditorState(state)\n }\n\n const toggleBlockType = (blockType: string | null) => {\n if (!blockType) return\n handleChange(RichUtils.toggleBlockType(editorState, blockType))\n }\n\n const toggleInlineStyle = (inlineStyle: string | null) => {\n if (!inlineStyle) return\n handleChange(RichUtils.toggleInlineStyle(editorState, inlineStyle))\n }\n\n return (\n <div className=\"bw1 br2 b--solid b--muted-4\">\n <div className=\"pa4 flex flex-wrap-s\">\n <HeadingInput\n onAdd={toggleBlockType}\n activeStyle={getContentBlockType()}\n />\n <InlineStyleControls\n editorState={editorState}\n onToggle={toggleInlineStyle}\n />\n <BlockStyleControls\n editorState={editorState}\n onToggle={toggleBlockType}\n />\n <LinkInput\n onAdd={handleAddLink}\n getCurrentSelection={getCurrentSelectionText}\n />\n <ImageInput onAdd={handleAddImage} />\n </div>\n <div className={className}>\n <Editor\n editorState={editorState}\n onChange={state => handleChange(state)}\n blockRendererFn={mediaBlockRenderer}\n blockStyleFn={styleBlockRenderer}\n />\n </div>\n </div>\n )\n}\n\nexport default RichTextEditor\n\n```" } ]
code_admin-pages_1c330f5e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/ImageInput.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { graphql, MutationFunc } from 'react-apollo'\nimport { useDropzone } from 'react-dropzone'\nimport { defineMessages, useIntl } from 'react-intl'\nimport {\n Button,\n IconClose,\n IconImage,\n Input,\n Spinner,\n IconCaretDown,\n} from 'vtex.styleguide'\n\nimport StyleButton from './StyleButton'\nimport { useClickOutside } from './utils'\nimport SeparatorWithLine from '../admin/pages/SeparatorWithLine'\nimport UploadFile from '../../queries/UploadFile.graphql'\n\ninterface MutationData {\n uploadFile: { fileUrl: string }\n}\n\ninterface Props {\n onAdd: (imageUrl: string) => void\n uploadFile?: MutationFunc<MutationData>\n}\n\nconst MAX_SIZE = 4 * 1024 * 1024\n\nconst messages = defineMessages({\n addBtn: {\n defaultMessage: 'Add',\n id: 'admin/pages.admin.rich-text-editor.add-button',\n },\n addTitle: {\n defaultMessage: 'Insert image',\n id: 'admin/pages.admin.rich-text-editor.add-image.title',\n },\n addLabel: {\n defaultMessage: 'Image URL',\n id: 'admin/pages.admin.rich-text-editor.add-image.label',\n },\n addPlaceholder: {\n defaultMessage: 'URL',\n id: 'admin/pages.admin.rich-text-editor.add-image.placeholder',\n },\n fileSizeError: {\n defaultMessage:\n 'File exceeds the size limit of 4MB. Please choose a smaller one.',\n id: 'admin/pages.editor.image-uploader.error.file-size',\n },\n genericError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.image-uploader.error.generic',\n },\n uploadBtn: {\n defaultMessage: 'Upload image',\n id: 'admin/pages.admin.rich-text-editor.upload-button',\n },\n uploadLabel: {\n defaultMessage: 'Choose an image to upload',\n id: 'admin/pages.admin.rich-text-editor.upload-image-label',\n },\n})\n\nconst ImageInput = ({ onAdd, uploadFile }: Props) => {\n const intl = useIntl()\n const ref = React.useRef<HTMLDivElement>(null)\n const [isLoading, setIsLoading] = React.useState(false)\n const [isOpen, setIsOpen] = React.useState(false)\n const [imageUrl, setImageUrl] = React.useState<string | undefined>()\n const [error, setError] = React.useState<string | null>()\n\n useClickOutside(ref, () => setIsOpen(false))\n\n const onDropImage = async (files: File[]) => {\n if (!uploadFile) {\n return undefined\n }\n\n setError(null)\n\n try {\n if (files && files[0]) {\n setIsLoading(true)\n\n const result = await uploadFile({ variables: { file: files[0] } })\n\n setIsLoading(false)\n setIsOpen(false)\n\n return result && result.data && onAdd(result.data.uploadFile.fileUrl)\n } else {\n return setError(intl.formatMessage(messages.fileSizeError))\n }\n } catch (err) {\n setError(intl.formatMessage(messages.genericError))\n setIsLoading(false)\n }\n }\n\n const { getInputProps, getRootProps } = useDropzone({\n accept: 'image/*',\n maxSize: MAX_SIZE,\n multiple: false,\n onDrop: onDropImage,\n })\n\n const handleAddImage = () => {\n setIsOpen(false)\n if (imageUrl) {\n return onAdd(imageUrl)\n }\n }\n\n return (\n <div className=\"relative\" ref={ref}>\n <StyleButton\n title={intl.formatMessage(messages.addTitle)}\n active={isOpen}\n onToggle={() => setIsOpen(!isOpen)}\n style={null}\n label={\n <div className=\"flex flex-row justify-between items-center w-100\">\n <IconImage />\n <IconCaretDown size={8} />\n </div>\n }\n />\n\n {isOpen && (\n <div className=\"absolute pa5 bg-white b--solid b--muted-4 bw1 br2 w5\">\n {isLoading && (\n <div className=\"absolute flex justify-center items-center top-0 left-0 h-100 w-100 br2 z-1 bg-black-05\">\n <Spinner />\n </div>\n )}\n\n <div className={`flex flex-column ${isLoading && 'o-20'}`}>\n <div className=\"mb4\">\n <Input\n label={intl.formatMessage(messages.addLabel)}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setImageUrl(e.target.value)\n }\n placeholder={intl.formatMessage(messages.addPlaceholder)}\n />\n </div>\n\n <Button onClick={handleAddImage} size=\"small\" disabled={!imageUrl}>\n {intl.formatMessage(messages.addBtn)}\n </Button>\n\n <SeparatorWithLine />\n\n <div className=\"flex flex-column\">\n <span className=\"db mb3 w-100 c-on-base t-small\">\n {intl.formatMessage(messages.uploadLabel)}\n </span>\n <div {...getRootProps()} className=\"flex flex-column\">\n <input {...getInputProps()} />\n <Button size=\"small\">\n {intl.formatMessage(messages.uploadBtn)}\n </Button>\n </div>\n </div>\n\n {error && (\n <div className=\"flex flex-row c-danger t-small justify-center items-center mt5\">\n <IconClose />\n <span>{error}</span>\n </div>\n )}\n </div>\n </div>\n )}\n </div>\n )\n}\n\nexport default graphql<Props>(UploadFile, {\n name: 'uploadFile',\n})(ImageInput)\n\n```" } ]
code_admin-pages_639474bb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/Link.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\n\nimport { Link as LinkProps } from 'draft-js'\n\nconst Link = (props: LinkProps) => {\n const { contentState, entityKey, children } = props\n const { url } = contentState.getEntity(entityKey).getData()\n\n return (\n <a href={url} className=\"blue\">\n {children}\n </a>\n )\n}\n\nexport default Link\n\n```" } ]
code_admin-pages_ea755f31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/LinkInput.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { Button, IconLink, Input } from 'vtex.styleguide'\n\nimport StyleButton from './StyleButton'\nimport { useClickOutside } from './utils'\n\ninterface Props {\n onAdd: (text: string, link: string) => void\n getCurrentSelection: () => string | null\n}\n\nconst messages = defineMessages({\n btn: {\n defaultMessage: 'Add',\n id: 'admin/pages.admin.rich-text-editor.add-button',\n },\n insertLink: {\n id: 'admin/pages.admin.rich-text-editor.link.title',\n defaultMessage: 'Insert link',\n },\n text: {\n defaultMessage: 'Text',\n id: 'admin/pages.admin.rich-text-editor.add-image.text-label',\n },\n})\n\nconst LinkInput = ({ onAdd, getCurrentSelection }: Props) => {\n const intl = useIntl()\n const ref = React.useRef<HTMLDivElement>(null)\n\n const [isOpen, setIsOpen] = React.useState(false)\n const [link, setLink] = React.useState<string | undefined>()\n const [text, setText] = React.useState<string | undefined>()\n\n useClickOutside(ref, () => setIsOpen(false))\n\n const handleAddLink = () => {\n setIsOpen(false)\n if (text && link) {\n return onAdd(text, link)\n }\n }\n\n const handleToggleDialog = () => {\n if (isOpen) {\n return setIsOpen(false)\n }\n\n setText(getCurrentSelection() || undefined)\n setIsOpen(true)\n }\n\n return (\n <div className=\"relative\" ref={ref}>\n <StyleButton\n title={intl.formatMessage(messages.insertLink)}\n active={isOpen}\n onToggle={handleToggleDialog}\n style={null}\n label={<IconLink />}\n />\n\n {isOpen && (\n <div className=\"flex flex-column absolute pa5 bg-white b--solid b--muted-4 bw1 br2 w5 z-1\">\n <div className=\"mb4\">\n <Input\n label={intl.formatMessage(messages.text)}\n value={text}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setText(e.target.value)\n }\n />\n </div>\n <div className=\"mb4\">\n <Input\n label={'URL'}\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n setLink(e.target.value)\n }\n />\n </div>\n <Button\n disabled={!text || !link}\n onClick={handleAddLink}\n size=\"small\"\n >\n {intl.formatMessage(messages.btn)}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nexport default LinkInput\n\n```" } ]
code_admin-pages_1b8c0043
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/StyleButton.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { Tooltip } from 'vtex.styleguide'\n\ninterface StyleBtnProps {\n label: string | JSX.Element\n title?: string | JSX.Element\n active: boolean\n onToggle: (style: string | null) => void\n style: string | null\n className?: string\n}\n\nconst StyleButton = ({\n active,\n onToggle,\n label,\n style,\n className,\n title,\n}: StyleBtnProps) => {\n const handleToggle = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n e.preventDefault()\n onToggle(style)\n }\n\n return (\n <Tooltip label={title} position=\"bottom\">\n <div\n className={`f6 pointer mr3 flex flex-row justify-center items-center outline-0 ph3 h2 b--muted-4 br2 ba ${\n active ? 'c-action-primary bg-muted-5' : ''\n } ${className}`}\n onMouseDown={handleToggle}\n role=\"button\"\n tabIndex={0}\n >\n {label}\n </div>\n </Tooltip>\n )\n}\n\nStyleButton.defaultProps = {\n title: '',\n className: '',\n}\n\nexport default StyleButton\n\n```" } ]
code_admin-pages_c4beb486
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/HeadingInput.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\nimport { IconCaretDown, IconCheck } from 'vtex.styleguide'\n\nimport StyleButton from './StyleButton'\nimport { useClickOutside } from './utils'\n\nconst BLOCK_TYPES = [\n {\n label: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.unstyled\"\n defaultMessage=\"Title\"\n />\n ),\n style: 'unstyled',\n },\n {\n label: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.header-one\"\n defaultMessage=\"Title\"\n />\n ),\n style: 'header-one',\n },\n {\n label: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.header-two\"\n defaultMessage=\"Title\"\n />\n ),\n style: 'header-two',\n },\n {\n label: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.header-three\"\n defaultMessage=\"Title\"\n />\n ),\n style: 'header-three',\n },\n {\n label: (\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.header-four\"\n defaultMessage=\"Title\"\n />\n ),\n style: 'header-four',\n },\n]\n\nconst hasActiveStyle = (style: string) => {\n return !!BLOCK_TYPES.find(block => block.style === style)\n}\n\ninterface Props {\n onAdd: (link: string) => void\n activeStyle: string\n}\n\nconst HeadingInput = ({ onAdd, activeStyle }: Props) => {\n const ref = React.useRef<HTMLDivElement>(null)\n const [isOpen, setIsOpen] = React.useState(false)\n\n useClickOutside(ref, () => setIsOpen(false))\n\n const handleClick = (\n e: React.MouseEvent<HTMLDivElement, MouseEvent>,\n style: string\n ) => {\n e.preventDefault()\n setIsOpen(false)\n onAdd(style)\n }\n\n return (\n <div className=\"relative\" ref={ref}>\n <StyleButton\n title={\n <FormattedMessage\n id=\"admin/pages.admin.rich-text-editor.heading.title\"\n defaultMessage=\"Styles\"\n />\n }\n className=\"justify-between w4\"\n active={isOpen}\n onToggle={() => setIsOpen(!isOpen)}\n style={null}\n label={\n <div className=\"flex flex-row justify-between items-center w-100\">\n <FormattedMessage\n id={\n hasActiveStyle(activeStyle)\n ? `admin/pages.admin.rich-text-editor.heading.${activeStyle}`\n : `admin/pages.admin.rich-text-editor.heading.unstyled`\n }\n defaultMessage=\"Regular text\"\n />\n <IconCaretDown size={8} />\n </div>\n }\n />\n\n {isOpen && (\n <div className=\"flex flex-column absolute bg-white b--solid b--muted-4 bw1 br2 w5\">\n {BLOCK_TYPES.map(({ label, style }, index: number) => (\n <div\n key={index}\n className={`flex justify-between items-center pointer pa5 f${index} ${\n index > 0 ? 'b bt b--muted-4' : ''\n }`}\n role=\"presentation\"\n onMouseDown={(e: React.MouseEvent<HTMLDivElement, MouseEvent>) =>\n handleClick(e, style)\n }\n >\n {label}\n {style === activeStyle && <IconCheck />}\n </div>\n ))}\n </div>\n )}\n </div>\n )\n}\n\nexport default React.memo(HeadingInput)\n\n```" } ]
code_admin-pages_db51b157
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/style.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.RichEditor_root {\n background: #fff;\n border: 1px solid #ddd;\n font-size: 14px;\n padding: 15px;\n}\n\n.RichEditor_editor {\n border-top: 1px solid #ddd;\n cursor: text;\n font-size: 16px;\n min-height: 20rem;\n padding: 10px;\n}\n\n.RichEditor_editor div[data-contents='true'] {\n min-height: 20em;\n}\n\n.RichEditor_editor .public-DraftEditorPlaceholder-root,\n.RichEditor_editor .public-DraftEditor-content {\n margin: 0 -15px -15px;\n padding: 15px;\n}\n\n.RichEditor_hidePlaceholder .public-DraftEditorPlaceholder-root {\n display: none;\n}\n\n.RichEditor_editor .RichEditor_blockquote {\n border-left: 5px solid #eee;\n color: #666;\n font-family: 'Hoefler Text', 'Georgia', serif;\n font-style: italic;\n margin: 16px 0;\n padding: 10px 20px;\n}\n\n.RichEditor_editor .public-DraftStyleDefault-pre {\n background-color: rgba(0, 0, 0, 0.05);\n font-family: 'Inconsolata', 'Menlo', 'Consolas', monospace;\n font-size: 16px;\n padding: 20px;\n}\n\n```" } ]
code_admin-pages_883b0a4c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/utils.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport {\n ContentBlock,\n ContentState,\n convertFromRaw,\n convertToRaw,\n EditorState,\n} from 'draft-js'\nimport { draftjsToMd, mdToDraftjs } from 'draftjs-md-converter'\n\nimport Media from './Media'\n\nexport function mediaBlockRenderer(block: ContentBlock) {\n if (block.getType() === 'atomic') {\n return {\n component: Media,\n editable: false,\n }\n }\n\n return null\n}\n\nexport function styleBlockRenderer(block: ContentBlock) {\n const blockType = block.getType()\n if (blockType === 'left') return 'align-left'\n if (blockType === 'center') return 'align-center'\n if (blockType === 'right') return 'align-right'\n return ''\n}\n\nexport function findLinkEntities(\n contentBlock: ContentBlock,\n callback: (start: number, end: number) => void,\n contentState: ContentState\n) {\n return contentBlock.findEntityRanges(character => {\n const entityKey = character.getEntity()\n return (\n entityKey !== null &&\n contentState.getEntity(entityKey).getType() === 'LINK'\n )\n }, callback)\n}\n\nexport function convertToMarkdown(editorState: EditorState) {\n const rawContentState = convertToRaw(editorState.getCurrentContent())\n return draftjsToMd(rawContentState)\n}\n\nexport function convertToEditorState(markdownText: string) {\n const rawMarkdown = mdToDraftjs(markdownText)\n return convertFromRaw(rawMarkdown)\n}\n\nexport function useClickOutside(\n ref: React.RefObject<HTMLDivElement>,\n callback: () => void\n) {\n function handleClickOutside(event: MouseEvent) {\n if (ref && ref.current && !ref.current.contains(event.target as Node)) {\n callback()\n }\n }\n\n React.useEffect(() => {\n document.addEventListener('mousedown', handleClickOutside)\n return () => document.removeEventListener('mousedown', handleClickOutside)\n })\n}\n\n```" } ]
code_admin-pages_12336913
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/RichTextEditor/Media.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\n\nimport { Media as MediaProps } from 'draft-js'\n\nconst Media = (props: MediaProps) => {\n const { contentState, block } = props\n const blockEntity = block.getEntityAt(0)\n\n if (!blockEntity) {\n return null\n }\n\n const entity = contentState.getEntity(blockEntity)\n const { src } = entity.getData()\n const type = entity.getType()\n\n if (type === 'IMAGE') {\n return <img alt={src} src={src} />\n }\n\n return null\n}\n\nexport default Media\n\n```" } ]
code_admin-pages_5e6be28b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorContainer/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport debounce from 'lodash/debounce'\nimport { path } from 'ramda'\nimport React, { useCallback, useEffect, useMemo } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Alert, Spinner, ToastConsumer } from 'vtex.styleguide'\n\nimport { State as HighlightOverlayState } from '../HighlightOverlay/typings'\nimport Sidebar from './Sidebar'\nimport { FormMetaProvider } from './Sidebar/FormMetaContext'\nimport { ModalProvider } from './Sidebar/ModalContext'\nimport IframeNavigationController from './IframeNavigationController'\nimport Styles from './Styles'\nimport Topbar from './Topbar'\nimport styles from './EditorContainer.css'\n\nimport '../../styles.global.css'\n\nexport const APP_CONTENT_ELEMENT_ID = 'app-content-editor'\n\nconst getContainerProps = (layout: Viewport) => {\n switch (layout) {\n case 'mobile':\n return {\n className: `${styles['mobile-preview']} center`,\n style: {\n animationDuration: '0.2s',\n transition: `width 660ms`,\n },\n }\n case 'tablet':\n return {\n className: `${styles['tablet-preview']} center`,\n style: {\n animationDuration: '0.2s',\n transition: `width 660ms`,\n },\n }\n default:\n return {\n className: 'w-100 h-100 center',\n style: {\n animationDuration: '0.2s',\n transition: `width 660ms`,\n },\n }\n }\n}\n\ninterface Props {\n editor: EditorContextType\n iframeRuntime: RenderContext | null\n isSiteEditor: boolean\n}\n\nconst EditorContainer: React.FC<Props> = ({\n children,\n editor,\n iframeRuntime,\n isSiteEditor,\n}) => {\n const { editMode, editExtensionPoint, viewport } = editor\n\n const highlightExtensionPoint = useCallback(\n debounce((highlightTreePath: string | null) => {\n const iframe = document.getElementById('store-iframe') || {}\n const setHighlightTreePath = path<\n (value: Partial<HighlightOverlayState>) => void\n >(['contentWindow', '__setHighlightTreePath'], iframe)\n if (setHighlightTreePath) {\n setHighlightTreePath({\n editExtensionPoint,\n editMode,\n highlightHandler: highlightExtensionPoint,\n highlightTreePath,\n })\n }\n }, 100),\n [editMode, editExtensionPoint]\n )\n\n const updateHighlightTitleByTreePath = useCallback(\n (\n sidebarBlocksMap?: Record<string, { title?: string; isEditable: boolean }>\n ) => {\n const iframe = document.getElementById('store-iframe') || {}\n const setHighlightTreePath = path<\n (value: Partial<HighlightOverlayState>) => void\n >(['contentWindow', '__setHighlightTreePath'], iframe)\n if (setHighlightTreePath) {\n setHighlightTreePath({\n sidebarBlocksMap: sidebarBlocksMap || {},\n })\n }\n },\n []\n )\n\n useEffect(() => {\n highlightExtensionPoint(null)\n }, [editMode, highlightExtensionPoint])\n\n const containerProps = useMemo(() => getContainerProps(viewport), [viewport])\n const isDevelopment = iframeRuntime && iframeRuntime.production === false\n const isMasterWorkspace =\n iframeRuntime && iframeRuntime.workspace === 'master'\n const hasAlert = isMasterWorkspace || isDevelopment\n\n return (\n <FormMetaProvider>\n <ModalProvider>\n <IframeNavigationController iframeRuntime={iframeRuntime} />\n <div className=\"vtex-admin-pages-4-x h-100 min-vh-100 flex flex-row-reverse bg-base bb bw1 b--muted-5\">\n <div\n className={\n editor.isSidebarVisible && isSiteEditor ? 'w-18em-ns' : 'dn'\n }\n >\n {isSiteEditor && iframeRuntime ? (\n <ToastConsumer>\n {({ showToast }) => (\n <Sidebar\n highlightHandler={highlightExtensionPoint}\n iframeRuntime={iframeRuntime}\n showToast={showToast}\n updateHighlightTitleByTreePath={\n updateHighlightTitleByTreePath\n }\n />\n )}\n </ToastConsumer>\n ) : (\n <div className=\"bg-white-70 flex items-center w-18em-ns h-100 justify-center z-2\">\n <Spinner />\n </div>\n )}\n </div>\n\n <div className=\"w-100 dn flex-ns flex-column\">\n <div style={{ minHeight: '64px' }} className=\"bg-muted-5\">\n {isSiteEditor && iframeRuntime && (\n <Topbar iframeRuntime={iframeRuntime} />\n )}\n </div>\n\n {isDevelopment && (\n <div className=\"pa5 bg-muted-5\">\n <Alert type=\"warning\">\n <FormattedMessage\n id=\"admin/pages.editor.container.dev-mode-warning.text\"\n defaultMessage=\"You are in development mode. Changes to the content will not go to production.\"\n />\n </Alert>\n </div>\n )}\n\n {isMasterWorkspace && (\n <div className=\"pa5 bg-muted-5\">\n <Alert type=\"warning\">\n <FormattedMessage\n id=\"admin/pages.editor.container.master-workspace-warning.text\"\n defaultMessage=\"You are editing the live store. Changes will have immediate effect.\"\n />\n </Alert>\n </div>\n )}\n\n <div\n className={`pa5 bg-muted-5 flex items-start z-0 center-m left-0-m overflow-x-auto-m ${\n isSiteEditor && iframeRuntime\n ? styles[`calc--height-relative${hasAlert ? '--dev' : ''}`]\n : 'top-0 w-100 h-100'\n }`}\n >\n {!isSiteEditor && iframeRuntime && <Styles />}\n\n <div id={APP_CONTENT_ELEMENT_ID} className=\"relative w-100 h-100\">\n <main\n {...containerProps}\n role=\"main\"\n style={{\n transition: `width 250ms ease-in-out 0ms, height 250ms ease-in-out 0ms`,\n }}\n >\n {children}\n </main>\n </div>\n </div>\n </div>\n </div>\n </ModalProvider>\n </FormMetaProvider>\n )\n}\n\nexport default EditorContainer\n\n```" } ]
code_admin-pages_de9e776e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorContainer/IframeNavigationController.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect } from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\n\nimport { useEditorContext } from '../EditorContext'\nimport { useFormMetaContext } from './Sidebar/FormMetaContext'\n\ninterface Props {\n iframeRuntime: RenderContext | null\n}\n\nconst maybeCall = (fn: (() => void) | void) => {\n if (typeof fn === 'function') {\n return fn()\n }\n}\n\nconst messages = defineMessages({\n confirm: {\n defaultMessage: 'Are you sure you want to leave?',\n id: 'admin/pages.editor.iframe.confirm-prompt',\n },\n})\n\nconst IframeNavigationController: React.FunctionComponent<Props> = ({\n iframeRuntime,\n}) => {\n const intl = useIntl()\n const { getWasModified, setWasModified } = useFormMetaContext()\n const { editExtensionPoint } = useEditorContext()\n\n const wasModified = getWasModified()\n\n useEffect(() => {\n let unblock: (() => void) | void\n let unlisten: (() => void) | void\n\n if (wasModified && iframeRuntime && iframeRuntime.history) {\n unblock = iframeRuntime.history.block(\n intl.formatMessage(messages.confirm)\n )\n unlisten = iframeRuntime.history.listen((_, action) => {\n const hasNavigated = ['PUSH', 'REPLACE', 'POP'].includes(action)\n if (hasNavigated) {\n unblock = maybeCall(unblock)\n unlisten = maybeCall(unlisten)\n setWasModified(false)\n editExtensionPoint(null)\n }\n })\n }\n\n return () => {\n unblock = maybeCall(unblock)\n unlisten = maybeCall(unlisten)\n }\n }, [editExtensionPoint, iframeRuntime, setWasModified, wasModified, intl])\n\n return null\n}\n\nexport default IframeNavigationController\n\n```" } ]
code_admin-pages_278d16db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorContainer/EditorContainer.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.h-3em {\n height: 48px;\n}\n\n.calc--height-relative {\n height: calc(100% - 3em);\n}\n\n.calc--height-relative--dev {\n height: calc(100% - 8.5em);\n}\n\n.mobile-preview {\n width: 360px;\n height: 640px;\n max-height: 100%;\n box-shadow: 1px 4px 8px rgba(0, 0, 0, 0.2);\n overflow: hidden;\n}\n\n.tablet-preview {\n width: 768px;\n height: 1024px;\n max-height: 100%;\n box-shadow: 1px 4px 8px rgba(0, 0, 0, 0.2);\n overflow: hidden;\n}\n\n```" } ]
code_admin-pages_04cc77c3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditorContainer/StoreIframe.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useRef } from 'react'\n\nimport { useBinding } from './Topbar/ContextSelectors/hooks/useBinding'\n\ninterface Props {\n path?: string\n}\n\nconst StoreIframe: React.FunctionComponent<Props> = ({ path }) => {\n const [binding] = useBinding()\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n if (iframeRef && iframeRef.current && iframeRef.current.contentWindow) {\n /* eslint-disable prefer-rest-params */\n const oldLog = (iframeRef.current.contentWindow as any).console.log\n const oldError = (iframeRef.current.contentWindow as any).console.error\n ;(iframeRef.current\n .contentWindow as any).console.log = function newLog() {\n Array.prototype.unshift.call(arguments, `[Iframe]: `)\n oldLog.apply(this, arguments)\n }\n ;(iframeRef.current\n .contentWindow as any).console.error = function newError() {\n Array.prototype.unshift.call(arguments, `[Iframe]: `)\n oldError.apply(this, arguments)\n }\n }\n }, [])\n\n const getJoiner = (src: string) => (src.includes('?') ? '&' : '?')\n\n let src = path ? `/${path}` : '/'\n\n if (binding && !src.includes('__bindingAddress')) {\n src += `${getJoiner(src)}__bindingAddress=${binding.canonicalBaseAddress}`\n }\n\n if (!src.includes('__siteEditor')) {\n src += `${getJoiner(src)}__siteEditor=true`\n }\n\n return (\n <iframe\n className=\"w-100 h-100\"\n frameBorder=\"0\"\n id=\"store-iframe\"\n ref={iframeRef}\n src={src}\n title=\"store-iframe\"\n />\n )\n}\n\nexport default React.memo(StoreIframe)\n\n```" } ]
code_admin-pages_db710f77
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/TargetPathContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ComponentType, useContext } from 'react'\n\nexport interface TargetPathContextProps {\n targetPath: string\n setTargetPath: (s: string) => void\n}\n\nconst TargetPathContext = React.createContext<TargetPathContextProps>({\n setTargetPath: () => undefined,\n targetPath: '',\n})\nconst useTargetPathContext = () => useContext(TargetPathContext)\n\nconst withTargetPath = <TOriginalProps extends {} = {}>(\n Component: ComponentType<TOriginalProps & TargetPathContextProps>\n): ComponentType<TOriginalProps> => {\n const extendedComponent = (props: TOriginalProps) => (\n <TargetPathContext.Consumer>\n {({ setTargetPath, targetPath }) => {\n return (\n <Component\n {...props}\n setTargetPath={setTargetPath}\n targetPath={targetPath}\n />\n )\n }}\n </TargetPathContext.Consumer>\n )\n return extendedComponent\n}\n\nexport { useTargetPathContext, withTargetPath }\nexport default TargetPathContext\n\n```" } ]
code_admin-pages_c85fe466
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/FormFieldSeparator.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst FormFieldSeparator = () => <div className=\"mt7\" />\n\nexport default FormFieldSeparator\n\n```" } ]
code_admin-pages_89b1becf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const slugify = (text: string) => {\n const specialChars: { [key: string]: string } = {\n à: 'a',\n ä: 'a',\n á: 'a',\n â: 'a',\n æ: 'a',\n å: 'a',\n ë: 'e',\n è: 'e',\n é: 'e',\n ê: 'e',\n î: 'i',\n ï: 'i',\n ì: 'i',\n í: 'i',\n ò: 'o',\n ó: 'o',\n ö: 'o',\n ô: 'o',\n ø: 'o',\n ù: 'o',\n ú: 'u',\n ü: 'u',\n û: 'u',\n ñ: 'n',\n ç: 'c',\n ß: 's',\n ÿ: 'y',\n œ: 'o',\n ŕ: 'r',\n ś: 's',\n ń: 'n',\n ṕ: 'p',\n ẃ: 'w',\n ǵ: 'g',\n ǹ: 'n',\n ḿ: 'm',\n ǘ: 'u',\n ẍ: 'x',\n ź: 'z',\n ḧ: 'h',\n '·': '-',\n '/': '-',\n _: '-',\n ',': '-',\n ':': '-',\n ';': '-',\n }\n\n return text\n .toString()\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/./g, target => specialChars[target] || target) // Replace special characters using the hash map\n .replace(/&/g, '-and-') // Replace & with 'and'\n .replace(/[^\\w-]+/g, '') // Remove all non-word chars\n .replace(/--+/g, '-') // Replace multiple - with single -\n .replace(/^-+/, '') // Trim - from start of text\n .replace(/-+$/, '') // Trim - from end of text\n}\n\n```" } ]
code_admin-pages_18b2b35c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/AdminStructure.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { PageHeader } from 'vtex.styleguide'\n\ninterface Props {\n title: string\n}\n\nconst AdminStructure: React.FC<Props> = ({ children, title }) => (\n <div className=\"h-100 min-vh-100 overflow-y-auto bg-light-silver\">\n <div className=\"center mw8\">\n <PageHeader title={title} />\n\n {children}\n </div>\n </div>\n)\n\nexport default AdminStructure\n\n```" } ]
code_admin-pages_0a1cd9b9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ActionMenu, Spinner, IconOptionsDots } from 'vtex.styleguide'\nimport MediaGallery from 'vtex.admin-cms/MediaGallery'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { JSONSchema6 } from 'json-schema'\nimport { useDropzone } from 'react-dropzone'\n\nimport ImagePreview from '../form/ImageUploader/ImagePreview'\nimport EmptyState from '../form/ImageUploader/EmptyState'\n\ninterface MediaGalleryWidgetProps {\n disabled?: boolean\n onChange?: (pathname: string | null) => void\n schema: JSONSchema6\n value: string\n}\n\nconst messages = defineMessages({\n remove: {\n id: 'admin/pages.admin.redirects.form.button.remove',\n },\n replace: {\n id: 'admin/pages.admin.redirects.form.button.replace',\n },\n fileSizeError: {\n defaultMessage:\n 'File exceeds the size limit of 4MB. Please choose a smaller one.',\n id: 'admin/pages.editor.image-uploader.error.file-size',\n },\n genericError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.image-uploader.error.generic',\n },\n})\nfunction Widget(props: MediaGalleryWidgetProps) {\n const intl = useIntl()\n const { onChange, value } = props\n const [isImageUploading, setIsImageUploading] = React.useState(false)\n const modalState = MediaGallery.useModalState({ animated: true })\n const [previewUrl, setPreviewUrl] = React.useState('')\n const { createMedia } = MediaGallery.useCreateMedia({\n onImageSelected: handleImageSelected,\n onImagePreview: setPreviewUrl,\n onImageUploading: handleUploading,\n onError: handleError,\n modalState,\n })\n const { getRootProps, getInputProps, isDragActive } = useDropzone({\n accept: 'image/*',\n maxSize: 4 * 10 ** 6,\n onDrop: acceptedFiles => {\n if (acceptedFiles?.[0]) {\n createMedia(acceptedFiles[0])\n } else {\n setError(intl.formatMessage(messages.fileSizeError))\n }\n },\n })\n const [error, setError] = React.useState<string | null>(null)\n\n const options: ActionMenuOption[] = [\n {\n label: intl.formatMessage(messages.replace),\n onClick: () => {\n modalState.setVisible(true)\n\n setError(null)\n },\n },\n {\n label: intl.formatMessage(messages.remove),\n onClick: () => {\n onChange?.(null)\n },\n },\n ]\n\n function handleUploading(isUploading: boolean) {\n setIsImageUploading(isUploading)\n }\n\n function handleImageSelected(imageUrl: string) {\n onChange?.(imageUrl)\n }\n\n const backgroundImagePreviewStyle = React.useMemo(\n () => ({\n backgroundImage: `url(\"${previewUrl}\")`,\n height: '8rem',\n }),\n [previewUrl]\n )\n\n function handleError() {\n setError(intl.formatMessage(messages.genericError))\n }\n\n return (\n <>\n <FormattedMessage id={props.schema?.title ?? 'Image'}>\n {text => <span className=\"w-100 db mb3\">{text}</span>}\n </FormattedMessage>\n\n <div className=\"w-100\">\n <>\n {isImageUploading ? (\n <div\n className=\"w-100 h-100 relative bg-center contain\"\n style={backgroundImagePreviewStyle}\n >\n <div className=\"absolute top-0 left-0 right-0 bottom-0 bg-white-70 z-2 flex items-center justify-center\">\n <Spinner />\n </div>\n </div>\n ) : value && !isDragActive ? (\n <div\n {...getRootProps({\n onClick: e => {\n e.stopPropagation()\n modalState.setVisible(true)\n },\n })}\n >\n <input {...getInputProps()} />\n <div style={{ height: '8rem' }}>\n <ImagePreview imageUrl={value}>\n <ActionMenu\n variation=\"primary\"\n menuWidth={200}\n options={options}\n buttonSize=\"small\"\n buttonProps={{\n size: 'small',\n variation: 'primary',\n icon: <IconOptionsDots color=\"currentColor\" />,\n }}\n />\n </ImagePreview>\n </div>\n\n {error && <p className=\"lh-copy f7 mt3 c-danger\">{error}</p>}\n </div>\n ) : (\n <>\n <div\n {...getRootProps({\n onClick: e => {\n e.stopPropagation()\n modalState.setVisible(true)\n },\n })}\n >\n <input {...getInputProps()} />\n <EmptyState\n style={\n isDragActive\n ? {\n borderColor: '#134cd8',\n color: '#134cd8',\n width: '14.25rem',\n height: '112px',\n }\n : {}\n }\n />\n </div>\n {error && <p className=\"lh-copy f7 mt3 c-danger\">{error}</p>}\n </>\n )}\n </>\n\n {modalState.visible && (\n <MediaGallery.Modal\n state={modalState}\n onImageSelected={handleImageSelected}\n onImageUploading={handleUploading}\n onImagePreview={setPreviewUrl}\n onError={handleError}\n />\n )}\n </div>\n </>\n )\n}\n\nexport default function MediaGalleryWidget(props: MediaGalleryWidgetProps) {\n return (\n <MediaGallery.MediaGalleryProvider>\n <Widget {...props} />\n </MediaGallery.MediaGalleryProvider>\n )\n}\n\n```" } ]
code_admin-pages_cb08f368
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/GearIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst GearIcon: React.FunctionComponent = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <g clipPath=\"url(#clip0)\">\n <path\n d=\"M13.0667 4.81733L14.6 3.28533L12.7147 1.4L11.1827 2.93333C10.6146 2.57238 9.98923 2.31086 9.33333 2.16V0H6.66667V2.16C6.01077 2.31086 5.38537 2.57238 4.81733 2.93333L3.28533 1.4L1.4 3.28533L2.93333 4.81733C2.57238 5.38537 2.31086 6.01077 2.16 6.66667H0V9.33333H2.16C2.31086 9.98923 2.57238 10.6146 2.93333 11.1827L1.4 12.7147L3.28533 14.6L4.81733 13.0667C5.38537 13.4276 6.01077 13.6891 6.66667 13.84V16H9.33333V13.84C9.98923 13.6891 10.6146 13.4276 11.1827 13.0667L12.7147 14.6L14.6 12.7147L13.0667 11.1827C13.4276 10.6146 13.6891 9.98923 13.84 9.33333H16V6.66667H13.84C13.6891 6.01077 13.4276 5.38537 13.0667 4.81733V4.81733ZM8 10.6667C7.47258 10.6667 6.95701 10.5103 6.51848 10.2173C6.07995 9.92424 5.73815 9.50776 5.53632 9.02049C5.33449 8.53322 5.28168 7.99704 5.38457 7.47976C5.48747 6.96248 5.74144 6.48732 6.11438 6.11438C6.48732 5.74144 6.96248 5.48747 7.47976 5.38457C7.99704 5.28168 8.53322 5.33449 9.02049 5.53632C9.50776 5.73815 9.92424 6.07995 10.2173 6.51848C10.5103 6.95701 10.6667 7.47258 10.6667 8C10.6667 8.70724 10.3857 9.38552 9.88562 9.88562C9.38552 10.3857 8.70724 10.6667 8 10.6667Z\"\n fill=\"#727273\"\n />\n </g>\n <defs>\n <clipPath id=\"clip0\">\n <rect width=\"16\" height=\"16\" fill=\"white\" />\n </clipPath>\n </defs>\n </svg>\n)\n\nexport default GearIcon\n\n```" } ]
code_admin-pages_50e7943f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/EarthIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst EarthIcon: React.FC = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path\n d=\"M8 1C4.15 1 1 4.15 1 8C1 11.85 4.15 15 8 15C11.85 15 15 11.85 15 8C15 4.15 11.85 1 8 1ZM8 13.25C6.6875 13.25 5.55 12.8125 4.5875 12.025C5.1125 11.325 5.2 10.45 4.675 9.75C4.2375 9.1375 3.5375 8.525 3.5375 8C3.5375 7.3 5.2 7.0375 5.725 6.3375C6.3375 5.6375 5.725 4.325 5.1125 3.625C5.8125 3.1875 6.6 2.8375 7.5625 2.75C7.7375 3.1875 8.35 3.7125 8.6125 4.0625C9.05 4.7625 9.1375 5.2 9.75 5.2C9.925 5.2 11.5 5.2 12.375 4.9375C12.9 5.8125 13.25 6.8625 13.25 8C13.25 10.8875 10.8875 13.25 8 13.25Z\"\n fill=\"#727273\"\n />\n\n <path\n d=\"M9.92468 6.8623C8.87468 6.8623 7.91218 7.56231 7.99968 8.5248C8.26218 10.7123 7.56218 11.4998 8.52468 11.9373C9.66218 12.3748 11.9372 10.2748 11.8497 8.5248C11.8497 7.56231 11.0622 6.8623 9.92468 6.8623Z\"\n fill=\"#727273\"\n />\n </svg>\n)\n\nexport default EarthIcon\n\n```" } ]
code_admin-pages_b3b2bf9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ComponentDragHandleIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst ComponentDragHandleIcon: React.FunctionComponent = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <circle cx=\"10\" cy=\"3\" r=\"1\" fill=\"#CACBCC\" />\n <circle cx=\"10\" cy=\"8\" r=\"1\" fill=\"#CACBCC\" />\n <circle cx=\"10\" cy=\"13\" r=\"1\" fill=\"#CACBCC\" />\n <circle cx=\"6\" cy=\"3\" r=\"1\" fill=\"#CACBCC\" />\n <circle cx=\"6\" cy=\"8\" r=\"1\" fill=\"#CACBCC\" />\n <circle cx=\"6\" cy=\"13\" r=\"1\" fill=\"#CACBCC\" />\n </svg>\n)\n\nexport default ComponentDragHandleIcon\n\n```" } ]
code_admin-pages_047660f4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ArrowIcon.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 ArrowIcon: React.FunctionComponent<Props> = ({ color }) => (\n <svg\n width=\"5\"\n height=\"9\"\n viewBox=\"0 0 5 9\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M0 8.5L5 4.5L0 0.5V8.5Z\" fill={color} />\n </svg>\n)\n\nArrowIcon.defaultProps = {\n color: 'currentColor',\n}\n\nexport default ArrowIcon\n\n```" } ]
code_admin-pages_44b1d0ce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/PageIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst PageIcon: React.FC = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <g clipPath=\"url(#clip0)\">\n <path\n d=\"M12.8623 13.75H3.3623V2.25H9.69564L12.8623 5.38636V13.75Z\"\n stroke=\"#727273\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"1.4\"\n />\n\n <path d=\"M9 6V2L13 6H9Z\" fill=\"#727273\" />\n </g>\n\n <defs>\n <clipPath id=\"clip0\">\n <rect width=\"16\" height=\"16\" fill=\"none\" />\n </clipPath>\n </defs>\n </svg>\n)\n\nexport default PageIcon\n\n```" } ]
code_admin-pages_f22bb95c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/PersonIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst PersonIcon: React.FC = () => (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\">\n <path\n d=\"M7 6.5C8.38071 6.5 9.5 5.38071 9.5 4C9.5 2.61929 8.38071 1.5 7 1.5C5.61929 1.5 4.5 2.61929 4.5 4C4.5 5.38071 5.61929 6.5 7 6.5Z\"\n fill=\"#CACBCC\"\n />\n\n <path\n d=\"M7 7.5C6.34339 7.5 5.69321 7.62933 5.08658 7.8806C4.47995 8.13188 3.92876 8.50017 3.46447 8.96447C2.52678 9.90215 2 11.1739 2 12.5H12C12 11.1739 11.4732 9.90215 10.5355 8.96447C9.59785 8.02678 8.32608 7.5 7 7.5V7.5Z\"\n fill=\"#CACBCC\"\n />\n </svg>\n)\n\nexport default PersonIcon\n\n```" } ]
code_admin-pages_9582eebe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ContentScheduledIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst ContentScheduledIcon: React.FC = () => (\n <svg\n width=\"13\"\n height=\"13\"\n viewBox=\"0 0 10 10\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M5.38477 3.07693L5.38477 5.38463\"\n stroke=\"#134CD8\"\n strokeWidth=\"1\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n ></path>\n\n <path\n d=\"M3.8457 5.38461H5.38416\"\n stroke=\"#134CD8\"\n strokeWidth=\"1\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n ></path>\n\n <circle cx=\"5\" cy=\"5\" r=\"4.25\" stroke=\"#134CD8\" strokeWidth=\"1.5\"></circle>\n </svg>\n)\n\nexport default ContentScheduledIcon\n\n```" } ]
code_admin-pages_9b16d328
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ContentActiveIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst ContentActiveIcon: React.FC = () => (\n <svg\n width=\"10\"\n height=\"10\"\n viewBox=\"0 0 10 10\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"5\" cy=\"5\" r=\"5\" fill=\"#8BC34A\" />\n </svg>\n)\n\nexport default ContentActiveIcon\n\n```" } ]
code_admin-pages_9ebb323b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/AddIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst AddIcon: React.FunctionComponent = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path\n d=\"M8 5.42773V10.5706\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M5.42969 8H10.5725\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M13.1429 14H2.85714C2.384 14 2 13.616 2 13.1429V2.85714C2 2.384 2.384 2 2.85714 2H13.1429C13.616 2 14 2.384 14 2.85714V13.1429C14 13.616 13.616 14 13.1429 14Z\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n)\n\nexport default AddIcon\n\n```" } ]
code_admin-pages_5b3a4a51
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/DangerIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst DangerIcon = () => (\n <svg\n width=\"17\"\n height=\"17\"\n viewBox=\"0 0 17 17\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"8.5\" cy=\"8.5\" r=\"8.5\" fill=\"#FF4C4C\" />\n <rect x=\"3\" y=\"7\" width=\"11\" height=\"2\" fill=\"white\" />\n </svg>\n)\n\nexport default React.memo(DangerIcon)\n\n```" } ]
code_admin-pages_ee395c27
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/DragHandle.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { calcIconSize } from './utils'\n\nimport styles from './DragHandle.css'\n\ninterface Props {\n className?: string\n size?: number\n}\n\nconst iconBase = {\n height: 12,\n width: 6,\n}\n\nconst DragHandle: React.FunctionComponent<Props> = ({\n size,\n className,\n ...props\n}) => {\n const newSize = calcIconSize(iconBase, size as number) // TS doesn't detect defaultProps\n\n return (\n <svg\n className={`${styles['editor-icon--fill']} ${className}`}\n width={newSize.width}\n height={newSize.height}\n viewBox=\"0 0 6 12\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n {...props}\n >\n <circle cx=\"1\" cy=\"1\" r=\"1\" transform=\"translate(4)\" />\n <circle cx=\"1\" cy=\"1\" r=\"1\" transform=\"translate(4 5)\" />\n <circle cx=\"1\" cy=\"1\" r=\"1\" transform=\"translate(4 10)\" />\n <circle cx=\"1\" cy=\"1\" r=\"1\" />\n <circle cx=\"1\" cy=\"1\" r=\"1\" transform=\"translate(0 5)\" />\n <circle cx=\"1\" cy=\"1\" r=\"1\" transform=\"translate(0 10)\" />\n </svg>\n )\n}\n\nDragHandle.defaultProps = {\n size: 20,\n}\n\nexport default React.memo(DragHandle)\n\n```" } ]
code_admin-pages_ccd36c21
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ContentInactiveIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst ContentInactiveIcon: React.FC = () => (\n <svg\n width=\"10\"\n height=\"10\"\n viewBox=\"0 0 10 10\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"5\" cy=\"5\" r=\"5\" fill=\"#CACBCC\" />\n </svg>\n)\n\nexport default ContentInactiveIcon\n\n```" } ]
code_admin-pages_66bfd079
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/PaperErrorIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst PaperErrorIcon: React.FunctionComponent = () => (\n <svg\n width=\"82\"\n height=\"95\"\n viewBox=\"0 0 82 95\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M69 64.5269V1H1V84.4433C1 89.2916 4.72084 93.589 9.46342 93.9989C9.73012 94.0219 68.7273 93.68 69 93.68\"\n fill=\"#DBE9FD\"\n />\n <path\n d=\"M69 64.5269V1H1V84.4433C1 89.2916 4.72084 93.589 9.46342 93.9989C9.73012 94.0219 68.7273 93.68 69 93.68\"\n stroke=\"#3D5980\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <path\n d=\"M19.3193 84.2844C19.3193 89.4911 15.1102 94 10 94L71.7479 93.7111C76.8581 93.7111 81 89.4911 81 84.2844V78H19.3193V84.2844Z\"\n fill=\"#DBE9FD\"\n stroke=\"#3D5980\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <path\n d=\"M16 23H54\"\n stroke=\"#3D5980\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <path\n d=\"M16 40H54\"\n stroke=\"#3D5980\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <path\n d=\"M16 57H54\"\n stroke=\"#3D5980\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <ellipse cx=\"70\" cy=\"57.5\" rx=\"12\" ry=\"11.5\" fill=\"#FF4C4C\" />\n <rect x=\"62\" y=\"56\" width=\"16\" height=\"2\" fill=\"white\" />\n </svg>\n)\n\nexport default React.memo(PaperErrorIcon)\n\n```" } ]
code_admin-pages_400f4eae
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/DragHandle.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.editor-icon--fill path,\n.editor-icon--fill circle {\n fill: #727273;\n}\n\n```" } ]
code_admin-pages_c55eb001
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/CalendarIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst CalendarIcon: React.FC = () => (\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\">\n <path\n d=\"M5.25 6.4H4.08333V7.6H5.25V6.4ZM7.58333 6.4H6.41667V7.6H7.58333V6.4ZM9.91667 6.4H8.75V7.6H9.91667V6.4ZM11.0833 2.2H10.5V1H9.33333V2.2H4.66667V1H3.5V2.2H2.91667C2.26917 2.2 1.75583 2.74 1.75583 3.4L1.75 11.8C1.75 12.46 2.26917 13 2.91667 13H11.0833C11.725 13 12.25 12.46 12.25 11.8V3.4C12.25 2.74 11.725 2.2 11.0833 2.2ZM11.0833 11.8H2.91667V5.2H11.0833V11.8Z\"\n fill=\"#CACBCC\"\n />\n </svg>\n)\n\nexport default CalendarIcon\n\n```" } ]
code_admin-pages_8c4b1e84
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/utils.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nexport interface Dimensions {\n width: number\n height: number\n}\n\nexport interface IconProps {\n color?: string\n size?: number\n block?: boolean\n}\n\nexport const calcIconSize: (d: Dimensions, s: number) => Dimensions = (\n iconBase,\n newSize\n) => {\n const isHorizontal = iconBase.width >= iconBase.height\n\n const width = isHorizontal\n ? newSize\n : (newSize * iconBase.width) / iconBase.height\n\n const height = !isHorizontal\n ? newSize\n : (newSize * iconBase.height) / iconBase.width\n\n return { width, height }\n}\n\n```" } ]
code_admin-pages_c47a1723
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/UploadTable.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst UploadTableIcon: React.FunctionComponent = () => (\n <svg\n width=\"120\"\n height=\"120\"\n viewBox=\"0 0 120 120\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"60\" cy=\"60\" r=\"60\" fill=\"#F7F9FA\" />\n <path\n d=\"M38 66H82V77C82 77.5523 81.5523 78 81 78H39C38.4477 78 38 77.5523 38 77V66Z\"\n fill=\"#E3E4E6\"\n />\n <rect x=\"42\" y=\"71\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"56\" y=\"71\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"74\" y=\"71\" width=\"4\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <path\n d=\"M82 54L38 54L38 43C38 42.4477 38.4477 42 39 42L81 42C81.5523 42 82 42.4477 82 43L82 54Z\"\n fill=\"#F71963\"\n />\n <rect\n x=\"78\"\n y=\"49\"\n width=\"4\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 78 49)\"\n fill=\"white\"\n />\n <rect\n x=\"64\"\n y=\"49\"\n width=\"8\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 64 49)\"\n fill=\"white\"\n />\n <rect\n x=\"50\"\n y=\"49\"\n width=\"8\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 50 49)\"\n fill=\"white\"\n />\n <path d=\"M38 54H82V66H38V54Z\" fill=\"#CACBCC\" />\n <rect x=\"42\" y=\"59\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"56\" y=\"59\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"74\" y=\"59\" width=\"4\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n </svg>\n)\n\nexport default React.memo(UploadTableIcon)\n\n```" } ]
code_admin-pages_09016201
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/TemplateIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst TemplateIcon: React.FC = () => (\n // <div> is used for making sure that the icon isn't vertically centered\n <div>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path\n d=\"M14.25 15.25H4.75V3.75H11.0833L14.25 6.88636V15.25Z\"\n stroke=\"#727273\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"1.4\"\n />\n\n <path\n d=\"M1.75 12.25V0.75H8.08333\"\n stroke=\"#727273\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"1.4\"\n />\n\n <path d=\"M10.6377 7.25V3.25L14.6377 7.25H10.6377Z\" fill=\"#727273\" />\n </svg>\n </div>\n)\n\nexport default TemplateIcon\n\n```" } ]
code_admin-pages_008fe568
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/ContentLibraryIcon.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 ContentLibraryIcon: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <mask id=\"path-1-inside-1\" fill=\"white\">\n <rect width=\"13\" height=\"13\" rx=\"1\" />\n </mask>\n\n <rect\n width=\"13\"\n height=\"13\"\n rx=\"1\"\n stroke={color}\n strokeWidth=\"2.8\"\n mask=\"url(#path-1-inside-1)\"\n />\n\n <rect\n x=\"3.25\"\n y=\"6.25\"\n width=\"6.5\"\n height=\"0.5\"\n rx=\"0.25\"\n fill={color}\n stroke={color}\n strokeWidth=\"0.5\"\n />\n\n <rect\n x=\"6.75\"\n y=\"3.25\"\n width=\"6.5\"\n height=\"0.5\"\n rx=\"0.25\"\n transform=\"rotate(90 6.75 3.25)\"\n fill={color}\n stroke={color}\n strokeWidth=\"0.5\"\n />\n\n <mask id=\"path-4-inside-2\" fill=\"white\">\n <path d=\"M15 3.5C15 3.22386 15.2239 3 15.5 3V3C15.7761 3 16 3.22386 16 3.5V15C16 15.5523 15.5523 16 15 16V16V3.5Z\" />\n </mask>\n\n <path\n d=\"M15 3.5C15 3.22386 15.2239 3 15.5 3V3C15.7761 3 16 3.22386 16 3.5V15C16 15.5523 15.5523 16 15 16V16V3.5Z\"\n fill={color}\n />\n\n <path\n d=\"M15 3.5V15H17V3.5H15ZM16 16V3.5H14V16H16ZM15 15V15V17C16.1046 17 17 16.1046 17 15H15ZM15.5 4C15.2239 4 15 3.77614 15 3.5H17C17 2.67157 16.3284 2 15.5 2V4ZM15.5 2C14.6716 2 14 2.67157 14 3.5H16C16 3.77614 15.7761 4 15.5 4V2Z\"\n fill={color}\n mask=\"url(#path-4-inside-2)\"\n />\n\n <mask id=\"path-6-inside-3\" fill=\"white\">\n <path d=\"M15 16L15 15L2.5 15C2.22386 15 2 15.2239 2 15.5V15.5C2 15.7761 2.22386 16 2.5 16L15 16Z\" />\n </mask>\n\n <path\n d=\"M15 16L15 15L2.5 15C2.22386 15 2 15.2239 2 15.5V15.5C2 15.7761 2.22386 16 2.5 16L15 16Z\"\n fill={color}\n />\n\n <path\n d=\"M15 16L16 16L16 17L15 17L15 16ZM15 15L15 14L16 14L16 15L15 15ZM14 16L14 15L16 15L16 16L14 16ZM15 16L2.5 16L2.5 14L15 14L15 16ZM2.5 15L15 15L15 17L2.5 17L2.5 15ZM3 15.5C3 15.2239 2.77614 15 2.5 15L2.5 17C1.67157 17 1 16.3284 1 15.5L3 15.5ZM2.5 16C2.77614 16 3 15.7761 3 15.5L1 15.5C1 14.6716 1.67157 14 2.5 14L2.5 16Z\"\n fill=\"#3F3F40\"\n mask=\"url(#path-6-inside-3)\"\n />\n </svg>\n)\n\nexport default ContentLibraryIcon\n\n```" } ]
code_admin-pages_440fdb0b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DomainMessages/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n// This file is .tsx because otherwise the babel plugin for messages doesn't work.\nimport { concat } from 'ramda'\nimport languagesQuery from '../../queries/Languages.graphql'\nimport messages from './cultureMessages'\nimport {\n AvailableCulturesProps,\n LabelledLocale,\n Languages,\n Variables,\n} from './typings'\n\n// TODO: Remove this when messages solve this case\nconst DEFAULT_LANGUAGES = ['en-US', 'pt-BR', 'es-AR']\n\nfunction isValidLang(key: string): key is keyof typeof messages {\n return Object.prototype.hasOwnProperty.call(messages, key)\n}\n\nexport const getAvailableCultures = async ({\n client,\n intl,\n}: AvailableCulturesProps) => {\n const {\n data: { languages },\n } = await client.query<Languages, Variables>({\n query: languagesQuery,\n })\n\n let { supported } = languages\n supported = Array.from(new Set(concat(supported, DEFAULT_LANGUAGES)))\n\n return supported\n .reduce(\n (acc, locale) => {\n const [lang, country] = locale.split('-')\n if (!lang || !country) {\n return acc\n }\n const i18nId = isValidLang(lang)\n ? messages[lang] && messages[lang].id\n : `admin/pages.editor.locale.${lang}`\n\n return [\n ...acc,\n {\n label: `${intl.formatMessage({ id: i18nId })} (${locale})`,\n value: locale,\n },\n ]\n },\n [] as LabelledLocale[]\n )\n .sort((a: LabelledLocale, b: LabelledLocale) =>\n a.label.localeCompare(b.label)\n )\n}\n\nexport { LabelledLocale }\nexport { editorMessagesFromRuntime } from './editorMessagesFromRuntime'\n\n```" } ]
code_admin-pages_c74767fc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DomainMessages/editorMessagesFromRuntime.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { keys, map, splitEvery } from 'ramda'\n\nimport { Data, Message, Props, Variables } from './typings'\n\nimport messagesForDomainQuery from '../../queries/MessagesForDomain.graphql'\n\nconst MAX_COMPONENTS_PER_QUERY = 15\n\nconst messagesToReactIntlFormat = (messages: Message[]) =>\n messages.reduce((acc, { key, message }) => ({ ...acc, [key]: message }), {})\n\nconst reduceP = async <T, K>(\n fn: (acc: K, item: T) => Promise<K>,\n initialValue: K,\n list: T[]\n) => {\n let acc = initialValue\n for (const item of list) {\n acc = await fn(acc, item)\n }\n return acc\n}\n\nlet cachedResult: Record<string, string> = {}\nconst fetchedKeys = new Set()\n\nexport const editorMessagesFromRuntime = async (\n { client, domain, runtime }: Props,\n { isRetry, componentsPerQuery } = {\n isRetry: false,\n componentsPerQuery: MAX_COMPONENTS_PER_QUERY,\n }\n) => {\n const { components, renderMajor } = runtime\n const allComponentNames = keys(components)\n let shouldRetry = false\n\n const componentNamesToFetch = allComponentNames.filter(componentName => {\n const shouldFetchComponent = !fetchedKeys.has(componentName)\n\n return shouldFetchComponent\n })\n\n if (componentNamesToFetch.length === 0) {\n return cachedResult\n }\n\n const componentsBatch = splitEvery(componentsPerQuery, componentNamesToFetch)\n\n const responses = map(\n batch =>\n client\n .query<Data, Variables>({\n fetchPolicy: 'network-only',\n query: messagesForDomainQuery,\n variables: {\n components: batch,\n domain,\n renderMajor,\n },\n })\n .then(res => {\n batch.forEach(componentName => {\n fetchedKeys.add(componentName)\n })\n\n return res\n }),\n componentsBatch\n )\n const messages = await reduceP(\n async (acc, response) => {\n try {\n const {\n data: { messages: batchMessages },\n } = await response\n return [...acc, ...batchMessages]\n } catch (e) {\n shouldRetry = true\n return acc\n }\n },\n [] as Message[],\n responses\n )\n\n const messagesInReactIntlFormat = messagesToReactIntlFormat(messages)\n cachedResult = { ...cachedResult, ...messagesInReactIntlFormat }\n\n let retriedMessages\n if (shouldRetry && !isRetry) {\n retriedMessages = await new Promise<Record<string, string>>(res =>\n setTimeout(async () => {\n res(\n await editorMessagesFromRuntime(\n { client, domain, runtime },\n {\n isRetry: true,\n componentsPerQuery: Math.round(MAX_COMPONENTS_PER_QUERY / 2),\n }\n )\n )\n }, 700)\n )\n }\n\n return { ...messagesInReactIntlFormat, ...retriedMessages }\n}\n\n```" } ]
code_admin-pages_cea8b438
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DomainMessages/cultureMessages.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { defineMessages } from 'react-intl'\n\nconst messages = defineMessages({\n aa: { defaultMessage: 'Afar', id: 'admin/pages.editor.locale.aa' },\n ab: { defaultMessage: 'Abkhazian', id: 'admin/pages.editor.locale.ab' },\n ae: { defaultMessage: 'Avestan', id: 'admin/pages.editor.locale.ae' },\n af: { defaultMessage: 'Afrikaans', id: 'admin/pages.editor.locale.af' },\n ak: { defaultMessage: 'Akan', id: 'admin/pages.editor.locale.ak' },\n am: { defaultMessage: 'Amharic', id: 'admin/pages.editor.locale.am' },\n an: { defaultMessage: 'Aragonese', id: 'admin/pages.editor.locale.an' },\n ar: { defaultMessage: 'Arabic', id: 'admin/pages.editor.locale.ar' },\n as: { defaultMessage: 'Assamese', id: 'admin/pages.editor.locale.as' },\n av: { defaultMessage: 'Avaric', id: 'admin/pages.editor.locale.av' },\n ay: { defaultMessage: 'Aymara', id: 'admin/pages.editor.locale.ay' },\n az: { defaultMessage: 'Azerbaijani', id: 'admin/pages.editor.locale.az' },\n ba: { defaultMessage: 'Bashkir', id: 'admin/pages.editor.locale.ba' },\n be: { defaultMessage: 'Belarusian', id: 'admin/pages.editor.locale.be' },\n bg: { defaultMessage: 'Bulgarian', id: 'admin/pages.editor.locale.bg' },\n bh: { defaultMessage: 'Bihari', id: 'admin/pages.editor.locale.bh' },\n bi: { defaultMessage: 'Bislama', id: 'admin/pages.editor.locale.bi' },\n bm: { defaultMessage: 'Bambara', id: 'admin/pages.editor.locale.bm' },\n bn: { defaultMessage: 'Bangla', id: 'admin/pages.editor.locale.bn' },\n bo: { defaultMessage: 'Tibetan', id: 'admin/pages.editor.locale.bo' },\n br: { defaultMessage: 'Breton', id: 'admin/pages.editor.locale.br' },\n bs: { defaultMessage: 'Bosnian', id: 'admin/pages.editor.locale.bs' },\n ca: { defaultMessage: 'Catalan', id: 'admin/pages.editor.locale.ca' },\n ce: { defaultMessage: 'Chechen', id: 'admin/pages.editor.locale.ce' },\n ch: { defaultMessage: 'Chamorro', id: 'admin/pages.editor.locale.ch' },\n co: { defaultMessage: 'Corsican', id: 'admin/pages.editor.locale.co' },\n cr: { defaultMessage: 'Cree', id: 'admin/pages.editor.locale.cr' },\n cs: { defaultMessage: 'Czech', id: 'admin/pages.editor.locale.cs' },\n cu: { defaultMessage: 'Church Slavic', id: 'admin/pages.editor.locale.cu' },\n cv: { defaultMessage: 'Chuvash', id: 'admin/pages.editor.locale.cv' },\n cy: { defaultMessage: 'Welsh', id: 'admin/pages.editor.locale.cy' },\n da: { defaultMessage: 'Danish', id: 'admin/pages.editor.locale.da' },\n de: { defaultMessage: 'German', id: 'admin/pages.editor.locale.de' },\n dv: { defaultMessage: 'Divehi', id: 'admin/pages.editor.locale.dv' },\n dz: { defaultMessage: 'Dzongkha', id: 'admin/pages.editor.locale.dz' },\n ee: { defaultMessage: 'Ewe', id: 'admin/pages.editor.locale.ee' },\n el: { defaultMessage: 'Greek', id: 'admin/pages.editor.locale.el' },\n en: { defaultMessage: 'English', id: 'admin/pages.editor.locale.en' },\n eo: { defaultMessage: 'Esperanto', id: 'admin/pages.editor.locale.eo' },\n es: { defaultMessage: 'Spanish', id: 'admin/pages.editor.locale.es' },\n et: { defaultMessage: 'Estonian', id: 'admin/pages.editor.locale.et' },\n eu: { defaultMessage: 'Basque', id: 'admin/pages.editor.locale.eu' },\n fa: { defaultMessage: 'Persian', id: 'admin/pages.editor.locale.fa' },\n ff: { defaultMessage: 'Fulah', id: 'admin/pages.editor.locale.ff' },\n fi: { defaultMessage: 'Finnish', id: 'admin/pages.editor.locale.fi' },\n fj: { defaultMessage: 'Fijian', id: 'admin/pages.editor.locale.fj' },\n fo: { defaultMessage: 'Faroese', id: 'admin/pages.editor.locale.fo' },\n fr: { defaultMessage: 'French', id: 'admin/pages.editor.locale.fr' },\n fy: { defaultMessage: 'Western Frisian', id: 'admin/pages.editor.locale.fy' },\n ga: { defaultMessage: 'Irish', id: 'admin/pages.editor.locale.ga' },\n gd: { defaultMessage: 'Scottish Gaelic', id: 'admin/pages.editor.locale.gd' },\n gl: { defaultMessage: 'Galician', id: 'admin/pages.editor.locale.gl' },\n gn: { defaultMessage: 'Guarani', id: 'admin/pages.editor.locale.gn' },\n gu: { defaultMessage: 'Gujarati', id: 'admin/pages.editor.locale.gu' },\n gv: { defaultMessage: 'Manx', id: 'admin/pages.editor.locale.gv' },\n ha: { defaultMessage: 'Hausa', id: 'admin/pages.editor.locale.ha' },\n he: { defaultMessage: 'Hebrew', id: 'admin/pages.editor.locale.he' },\n hi: { defaultMessage: 'Hindi', id: 'admin/pages.editor.locale.hi' },\n ho: { defaultMessage: 'Hiri Motu', id: 'admin/pages.editor.locale.ho' },\n hr: { defaultMessage: 'Croatian', id: 'admin/pages.editor.locale.hr' },\n ht: { defaultMessage: 'Haitian Creole', id: 'admin/pages.editor.locale.ht' },\n hu: { defaultMessage: 'Hungarian', id: 'admin/pages.editor.locale.hu' },\n hy: { defaultMessage: 'Armenian', id: 'admin/pages.editor.locale.hy' },\n hz: { defaultMessage: 'Herero', id: 'admin/pages.editor.locale.hz' },\n ia: { defaultMessage: 'Interlingua', id: 'admin/pages.editor.locale.ia' },\n id: { defaultMessage: 'Indonesian', id: 'admin/pages.editor.locale.id' },\n ie: { defaultMessage: 'Interlingue', id: 'admin/pages.editor.locale.ie' },\n ig: { defaultMessage: 'Igbo', id: 'admin/pages.editor.locale.ig' },\n ii: { defaultMessage: 'Sichuan Yi', id: 'admin/pages.editor.locale.ii' },\n ik: { defaultMessage: 'Inupiaq', id: 'admin/pages.editor.locale.ik' },\n io: { defaultMessage: 'Ido', id: 'admin/pages.editor.locale.io' },\n is: { defaultMessage: 'Icelandic', id: 'admin/pages.editor.locale.is' },\n it: { defaultMessage: 'Italian', id: 'admin/pages.editor.locale.it' },\n iu: { defaultMessage: 'Inuktitut', id: 'admin/pages.editor.locale.iu' },\n ja: { defaultMessage: 'Japanese', id: 'admin/pages.editor.locale.ja' },\n jv: { defaultMessage: 'Javanese', id: 'admin/pages.editor.locale.jv' },\n ka: { defaultMessage: 'Georgian', id: 'admin/pages.editor.locale.ka' },\n kg: { defaultMessage: 'Kongo', id: 'admin/pages.editor.locale.kg' },\n ki: { defaultMessage: 'Kikuyu', id: 'admin/pages.editor.locale.ki' },\n kj: { defaultMessage: 'Kuanyama', id: 'admin/pages.editor.locale.kj' },\n kk: { defaultMessage: 'Kazakh', id: 'admin/pages.editor.locale.kk' },\n kl: { defaultMessage: 'Kalaallisut', id: 'admin/pages.editor.locale.kl' },\n km: { defaultMessage: 'Khmer', id: 'admin/pages.editor.locale.km' },\n kn: { defaultMessage: 'Kannada', id: 'admin/pages.editor.locale.kn' },\n ko: { defaultMessage: 'Korean', id: 'admin/pages.editor.locale.ko' },\n kr: { defaultMessage: 'Kanuri', id: 'admin/pages.editor.locale.kr' },\n ks: { defaultMessage: 'Kashmiri', id: 'admin/pages.editor.locale.ks' },\n ku: { defaultMessage: 'Kurdish', id: 'admin/pages.editor.locale.ku' },\n kv: { defaultMessage: 'Komi', id: 'admin/pages.editor.locale.kv' },\n kw: { defaultMessage: 'Cornish', id: 'admin/pages.editor.locale.kw' },\n ky: { defaultMessage: 'Kyrgyz', id: 'admin/pages.editor.locale.ky' },\n la: { defaultMessage: 'Latin', id: 'admin/pages.editor.locale.la' },\n lb: { defaultMessage: 'Luxembourgish', id: 'admin/pages.editor.locale.lb' },\n lg: { defaultMessage: 'Ganda', id: 'admin/pages.editor.locale.lg' },\n li: { defaultMessage: 'Limburgish', id: 'admin/pages.editor.locale.li' },\n ln: { defaultMessage: 'Lingala', id: 'admin/pages.editor.locale.ln' },\n lo: { defaultMessage: 'Lao', id: 'admin/pages.editor.locale.lo' },\n lt: { defaultMessage: 'Lithuanian', id: 'admin/pages.editor.locale.lt' },\n lu: { defaultMessage: 'Luba-Katanga', id: 'admin/pages.editor.locale.lu' },\n lv: { defaultMessage: 'Latvian', id: 'admin/pages.editor.locale.lv' },\n mg: { defaultMessage: 'Malagasy', id: 'admin/pages.editor.locale.mg' },\n mh: { defaultMessage: 'Marshallese', id: 'admin/pages.editor.locale.mh' },\n mi: { defaultMessage: 'Maori', id: 'admin/pages.editor.locale.mi' },\n mk: { defaultMessage: 'Macedonian', id: 'admin/pages.editor.locale.mk' },\n ml: { defaultMessage: 'Malayalam', id: 'admin/pages.editor.locale.ml' },\n mn: { defaultMessage: 'Mongolian', id: 'admin/pages.editor.locale.mn' },\n mr: { defaultMessage: 'Marathi', id: 'admin/pages.editor.locale.mr' },\n ms: { defaultMessage: 'Malay', id: 'admin/pages.editor.locale.ms' },\n mt: { defaultMessage: 'Maltese', id: 'admin/pages.editor.locale.mt' },\n my: { defaultMessage: 'Burmese', id: 'admin/pages.editor.locale.my' },\n na: { defaultMessage: 'Nauru', id: 'admin/pages.editor.locale.na' },\n nb: {\n defaultMessage: 'Norwegian Bokmål',\n id: 'admin/pages.editor.locale.nb',\n },\n nd: { defaultMessage: 'North Ndebele', id: 'admin/pages.editor.locale.nd' },\n ne: { defaultMessage: 'Nepali', id: 'admin/pages.editor.locale.ne' },\n ng: { defaultMessage: 'Ndonga', id: 'admin/pages.editor.locale.ng' },\n nl: { defaultMessage: 'Dutch', id: 'admin/pages.editor.locale.nl' },\n nn: {\n defaultMessage: 'Norwegian Nynorsk',\n id: 'admin/pages.editor.locale.nn',\n },\n no: { defaultMessage: 'Norwegian', id: 'admin/pages.editor.locale.no' },\n nr: { defaultMessage: 'South Ndebele', id: 'admin/pages.editor.locale.nr' },\n nv: { defaultMessage: 'Navajo', id: 'admin/pages.editor.locale.nv' },\n ny: { defaultMessage: 'Nyanja', id: 'admin/pages.editor.locale.ny' },\n oc: { defaultMessage: 'Occitan', id: 'admin/pages.editor.locale.oc' },\n oj: { defaultMessage: 'Ojibwa', id: 'admin/pages.editor.locale.oj' },\n om: { defaultMessage: 'Oromo', id: 'admin/pages.editor.locale.om' },\n or: { defaultMessage: 'Odia', id: 'admin/pages.editor.locale.or' },\n os: { defaultMessage: 'Ossetic', id: 'admin/pages.editor.locale.os' },\n pa: { defaultMessage: 'Punjabi', id: 'admin/pages.editor.locale.pa' },\n pi: { defaultMessage: 'Pali', id: 'admin/pages.editor.locale.pi' },\n pl: { defaultMessage: 'Polish', id: 'admin/pages.editor.locale.pl' },\n ps: { defaultMessage: 'Pashto', id: 'admin/pages.editor.locale.ps' },\n pt: { defaultMessage: 'Portuguese', id: 'admin/pages.editor.locale.pt' },\n qu: { defaultMessage: 'Quechua', id: 'admin/pages.editor.locale.qu' },\n rm: { defaultMessage: 'Romansh', id: 'admin/pages.editor.locale.rm' },\n rn: { defaultMessage: 'Rundi', id: 'admin/pages.editor.locale.rn' },\n ro: { defaultMessage: 'Romanian', id: 'admin/pages.editor.locale.ro' },\n ru: { defaultMessage: 'Russian', id: 'admin/pages.editor.locale.ru' },\n rw: { defaultMessage: 'Kinyarwanda', id: 'admin/pages.editor.locale.rw' },\n sa: { defaultMessage: 'Sanskrit', id: 'admin/pages.editor.locale.sa' },\n sc: { defaultMessage: 'Sardinian', id: 'admin/pages.editor.locale.sc' },\n sd: { defaultMessage: 'Sindhi', id: 'admin/pages.editor.locale.sd' },\n se: { defaultMessage: 'Northern Sami', id: 'admin/pages.editor.locale.se' },\n sg: { defaultMessage: 'Sango', id: 'admin/pages.editor.locale.sg' },\n si: { defaultMessage: 'Sinhala', id: 'admin/pages.editor.locale.si' },\n sk: { defaultMessage: 'Slovak', id: 'admin/pages.editor.locale.sk' },\n sl: { defaultMessage: 'Slovenian', id: 'admin/pages.editor.locale.sl' },\n sm: { defaultMessage: 'Samoan', id: 'admin/pages.editor.locale.sm' },\n sn: { defaultMessage: 'Shona', id: 'admin/pages.editor.locale.sn' },\n so: { defaultMessage: 'Somali', id: 'admin/pages.editor.locale.so' },\n sq: { defaultMessage: 'Albanian', id: 'admin/pages.editor.locale.sq' },\n sr: { defaultMessage: 'Serbian', id: 'admin/pages.editor.locale.sr' },\n ss: { defaultMessage: 'Swati', id: 'admin/pages.editor.locale.ss' },\n st: { defaultMessage: 'Southern Sotho', id: 'admin/pages.editor.locale.st' },\n su: { defaultMessage: 'Sundanese', id: 'admin/pages.editor.locale.su' },\n sv: { defaultMessage: 'Swedish', id: 'admin/pages.editor.locale.sv' },\n sw: { defaultMessage: 'Swahili', id: 'admin/pages.editor.locale.sw' },\n ta: { defaultMessage: 'Tamil', id: 'admin/pages.editor.locale.ta' },\n te: { defaultMessage: 'Telugu', id: 'admin/pages.editor.locale.te' },\n tg: { defaultMessage: 'Tajik', id: 'admin/pages.editor.locale.tg' },\n th: { defaultMessage: 'Thai', id: 'admin/pages.editor.locale.th' },\n ti: { defaultMessage: 'Tigrinya', id: 'admin/pages.editor.locale.ti' },\n tk: { defaultMessage: 'Turkmen', id: 'admin/pages.editor.locale.tk' },\n tl: { defaultMessage: 'Tagalog', id: 'admin/pages.editor.locale.tl' },\n tn: { defaultMessage: 'Tswana', id: 'admin/pages.editor.locale.tn' },\n to: { defaultMessage: 'Tongan', id: 'admin/pages.editor.locale.to' },\n tr: { defaultMessage: 'Turkish', id: 'admin/pages.editor.locale.tr' },\n ts: { defaultMessage: 'Tsonga', id: 'admin/pages.editor.locale.ts' },\n tt: { defaultMessage: 'Tatar', id: 'admin/pages.editor.locale.tt' },\n tw: { defaultMessage: 'Twi', id: 'admin/pages.editor.locale.tw' },\n ty: { defaultMessage: 'Tahitian', id: 'admin/pages.editor.locale.ty' },\n ug: { defaultMessage: 'Uyghur', id: 'admin/pages.editor.locale.ug' },\n uk: { defaultMessage: 'Ukrainian', id: 'admin/pages.editor.locale.uk' },\n ur: { defaultMessage: 'Urdu', id: 'admin/pages.editor.locale.ur' },\n uz: { defaultMessage: 'Uzbek', id: 'admin/pages.editor.locale.uz' },\n ve: { defaultMessage: 'Venda', id: 'admin/pages.editor.locale.ve' },\n vi: { defaultMessage: 'Vietnamese', id: 'admin/pages.editor.locale.vi' },\n vo: { defaultMessage: 'Volapük', id: 'admin/pages.editor.locale.vo' },\n wa: { defaultMessage: 'Walloon', id: 'admin/pages.editor.locale.wa' },\n wo: { defaultMessage: 'Wolof', id: 'admin/pages.editor.locale.wo' },\n xh: { defaultMessage: 'Xhosa', id: 'admin/pages.editor.locale.xh' },\n yi: { defaultMessage: 'Yiddish', id: 'admin/pages.editor.locale.yi' },\n yo: { defaultMessage: 'Yoruba', id: 'admin/pages.editor.locale.yo' },\n za: { defaultMessage: 'Zhuang', id: 'admin/pages.editor.locale.za' },\n zh: { defaultMessage: 'Chinese', id: 'admin/pages.editor.locale.zh' },\n zu: { defaultMessage: 'Zulu', id: 'admin/pages.editor.locale.zu' },\n})\n\nexport default messages\n\n```" } ]
code_admin-pages_40852880
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DomainMessages/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport ApolloClient from 'apollo-client'\nimport { InjectedIntl } from 'react-intl'\n\nexport interface Props {\n runtime: RenderContext\n domain: string\n client: ApolloClient<unknown>\n}\n\nexport interface Message {\n key: string\n message: string\n}\n\nexport interface Data {\n messages: Message[]\n}\n\nexport interface Variables {\n components: string[]\n domain: string\n renderMajor: number\n}\n\nexport interface AvailableCulturesProps {\n client: ApolloClient<unknown>\n intl: InjectedIntl\n}\n\nexport interface Languages {\n languages: {\n default: string\n supported: string[]\n }\n}\n\nexport interface LabelledLocale {\n label: string\n value: string\n}\n\n```" } ]
code_admin-pages_28a18228
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ActionMenu/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport {\n ActionMenu as StyleguideActionMenu,\n IconOptionsDots,\n} from 'vtex.styleguide'\n\nimport { ActionMenuOption } from './typings'\n\ninterface Props {\n buttonSize?: string\n menuWidth?: number | string\n options: ActionMenuOption[]\n variation?: string\n}\n\nconst icon = <IconOptionsDots color=\"currentColor\" />\n\nconst ActionMenu: React.FunctionComponent<Props> = ({\n buttonSize,\n menuWidth,\n options,\n variation = 'tertiary',\n}) => (\n <StyleguideActionMenu\n buttonProps={{\n icon,\n size: buttonSize,\n type: 'button',\n variation,\n }}\n hideCaretIcon\n menuWidth={menuWidth}\n options={options}\n />\n)\n\nexport default ActionMenu\n\n```" } ]
code_admin-pages_031a0026
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ActionMenu/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface ActionMenuOption {\n isDangerous?: boolean\n label: string\n onClick: (e: ActionMenuOption) => void\n}\n\n```" } ]
code_admin-pages_8ba7c8e3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { CSSTransition } from 'react-transition-group'\nimport { canUseDOM } from 'vtex.render-runtime'\n\nimport useAutoScroll from './hooks/useAutoScroll'\nimport useHighlightOnHover from './hooks/useHighlightOnHover'\nimport useHighlightedElementInfo from './hooks/useHighlightedElementInfo'\nimport usePortal from './hooks/usePortal'\nimport useResizeObserver from './hooks/useResizeObserver'\nimport useStyles from './hooks/useStyles'\nimport OverlayMask from './OverlayMask'\nimport { State } from './typings'\n\nimport styles from './HighlightOverlay.css'\n\ninterface Props {\n editExtensionPoint: (treePath: string | null) => void\n editMode: boolean\n highlightHandler: (treePath: string | null) => void\n highlightTreePath: string | null\n}\n\nconst classNames = {\n enter: styles['highlight-enter'],\n enterActive: styles['highlight-enter-active'],\n enterDone: styles['highlight-enter-done'],\n exit: styles['highlight-exit'],\n exitActive: styles['highlight-exit-active'],\n exitDone: styles['highlight-exit-done'],\n}\n\nconst HighlightOverlay: React.FC<Props> = props => {\n const [state, setState] = React.useState<State>(() => ({\n editExtensionPoint: props.editExtensionPoint,\n editMode: props.editMode,\n highlightHandler: props.highlightHandler,\n highlightTreePath: props.highlightTreePath,\n openBlockTreePath: null,\n sidebarBlocksMap: {},\n }))\n\n const {\n editMode,\n highlightTreePath,\n openBlockTreePath,\n sidebarBlocksMap,\n } = state\n\n const { subscribeToResize, unsubscribeToResize } = useResizeObserver()\n\n const portalContainer = usePortal({ subscribeToResize, unsubscribeToResize })\n\n useHighlightOnHover(state)\n\n React.useEffect(() => {\n const highlightableWindow = window\n\n if (canUseDOM) {\n highlightableWindow.__setHighlightTreePath = (\n newState: Partial<State>\n ) => {\n setState(prevState => {\n return {\n ...prevState,\n ...newState,\n sidebarBlocksMap: {\n ...prevState.sidebarBlocksMap,\n ...newState.sidebarBlocksMap,\n },\n }\n })\n }\n }\n }, [setState])\n\n const titleTreePath = highlightTreePath || openBlockTreePath\n\n const { visibleElement, hasValidElement } = useHighlightedElementInfo(\n titleTreePath,\n sidebarBlocksMap,\n state.elementHeight\n ) || { visibleElement: undefined, hasValidElement: false }\n\n useAutoScroll({ editMode, highlightTreePath, visibleElement })\n\n const isOverlayMaskActive = Boolean(\n hasValidElement && openBlockTreePath && portalContainer\n )\n\n useStyles({\n hasValidElement,\n highlightTreePath: titleTreePath,\n isOverlayMaskActive,\n setState,\n subscribeToResize,\n unsubscribeToResize,\n visibleElement,\n })\n\n const hasHighlight = highlightTreePath && hasValidElement\n\n const title =\n titleTreePath &&\n sidebarBlocksMap[titleTreePath] &&\n sidebarBlocksMap[titleTreePath].title\n\n return (\n <>\n <CSSTransition\n in={\n Boolean(hasValidElement && hasHighlight) ||\n Boolean(hasValidElement && openBlockTreePath)\n }\n classNames={classNames}\n mountOnEnter\n timeout={150}\n >\n <div\n data-testid=\"editor-provider-overlay\"\n id=\"editor-provider-overlay\"\n style={state.highlightStyle}\n className=\"absolute bw2 ba\"\n >\n {title && (\n <p\n className=\"absolute white f7 ma0 right-0 ph2 pb2 pt1 truncate tc\"\n style={state.labelStyle}\n title={title}\n >\n {title}\n </p>\n )}\n </div>\n </CSSTransition>\n {ReactDOM.createPortal(\n <OverlayMask style={state.maskStyle} isActive={isOverlayMaskActive} />,\n portalContainer\n )}\n </>\n )\n}\n\nexport default HighlightOverlay\n\n```" } ]
code_admin-pages_534c4d37
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { CSSProperties } from 'react'\n\nexport interface State {\n editExtensionPoint: (treePath: string | null) => void\n editMode: boolean\n elementHeight?: HTMLElement['clientHeight']\n highlightStyle?: CSSProperties\n labelStyle?: CSSProperties\n maskStyle?: CSSProperties\n openBlockTreePath: string | null\n highlightHandler: (treePath: string | null) => void\n highlightTreePath: string | null\n sidebarBlocksMap: Record<string, { title?: string; isEditable: boolean }>\n}\n\n```" } ]
code_admin-pages_f45a3f88
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/index.test.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { act } from '@testing-library/react'\nimport { fireEvent, render } from '@vtex/test-tools/react'\n\nimport { State } from './typings'\nimport HighlightOverlay from './index'\n\nconst extensionPointName = 'welcome'\n\nfunction createMockDiv(width: number, height: number) {\n const renderProviderDiv = document.createElement('div')\n renderProviderDiv.setAttribute('class', 'render-provider')\n Object.assign(renderProviderDiv.style, {\n width: '1440px',\n height: '900px',\n })\n\n const div = document.createElement('div')\n Object.assign(div.style, {\n width: `${width}px`,\n height: `${height}px`,\n })\n\n // we have to mock this for jsdom.\n div.getBoundingClientRect = () => ({\n width,\n height,\n top: 0,\n left: 0,\n right: width,\n bottom: height,\n x: width,\n y: height,\n toJSON() {\n const { toJSON, ...rect } = this\n return rect\n },\n })\n div.textContent = 'Welcome'\n div.setAttribute('data-extension-point', extensionPointName)\n\n renderProviderDiv.getBoundingClientRect = () => ({\n width,\n height,\n top: 0,\n left: 0,\n right: width,\n bottom: height,\n x: width,\n y: height,\n toJSON() {\n const { toJSON, ...rect } = this\n return rect\n },\n })\n renderProviderDiv.appendChild(div)\n return renderProviderDiv\n}\n\nconst mockBlocks: State['sidebarBlocksMap'] = {\n welcome: {\n isEditable: true,\n title: 'Welcome Banner',\n },\n}\n\nfunction setUpDom() {\n Object.defineProperty(HTMLElement.prototype, 'scrollWidth', {\n configurable: true,\n get: function getScrollWidth() {\n return this._scrollWidth || 0\n },\n set(val) {\n this._scrollWidth = val\n },\n })\n\n // eslint-disable-next-line\n // @ts-ignore\n document.body.scrollWidth = 1440\n document.body.appendChild(createMockDiv(300, 300))\n}\n\nfunction cleanUpDOM() {\n document.body.innerHTML = '<div></div>'\n}\n\ndescribe('HighlightOverlay', () => {\n beforeEach(() => {\n setUpDom()\n })\n afterEach(() => {\n cleanUpDOM()\n })\n\n it(`should edit extension-point when its element is clicked`, () => {\n const mockEditExtensionPoint = jest.fn()\n const mockHighlightHandler = jest.fn()\n const { getByText } = render(\n <HighlightOverlay\n editExtensionPoint={mockEditExtensionPoint}\n editMode\n highlightHandler={mockHighlightHandler}\n highlightTreePath={extensionPointName}\n />\n )\n const extensionPointDiv = getByText(/welcome/i)\n act(() => {\n window.__setHighlightTreePath({ sidebarBlocksMap: mockBlocks })\n })\n\n fireEvent.click(extensionPointDiv)\n\n expect(mockEditExtensionPoint).toBeCalledTimes(1)\n expect(mockEditExtensionPoint).toHaveBeenCalledWith(extensionPointName)\n })\n\n it(`should have highlight when an element is being edited`, () => {\n const mockEditExtensionPoint = jest.fn()\n const mockHighlightHandler = jest.fn()\n const { queryByTestId } = render(\n <HighlightOverlay\n editExtensionPoint={mockEditExtensionPoint}\n editMode\n highlightHandler={mockHighlightHandler}\n highlightTreePath={null}\n />\n )\n\n expect(queryByTestId('editor-provider-overlay')).toBeFalsy()\n\n act(() => {\n window.__setHighlightTreePath({\n openBlockTreePath: extensionPointName,\n sidebarBlocksMap: mockBlocks,\n })\n })\n\n expect(queryByTestId('editor-provider-overlay')).toBeTruthy()\n })\n\n it('should set tree path when corresponding element is hovered', () => {\n const mockEditExtensionPoint = jest.fn()\n const mockHighlightHandler = jest.fn()\n\n render(\n <HighlightOverlay\n editExtensionPoint={mockEditExtensionPoint}\n editMode\n highlightHandler={mockHighlightHandler}\n highlightTreePath={null}\n />\n )\n\n act(() => {\n window.__setHighlightTreePath({ sidebarBlocksMap: mockBlocks })\n })\n\n const extensionPointDiv = document.querySelector(\n '[data-extension-point=\"welcome\"]'\n )\n\n if (extensionPointDiv) {\n fireEvent.mouseOver(extensionPointDiv)\n }\n\n expect(mockHighlightHandler).toHaveBeenCalledTimes(1)\n expect(mockHighlightHandler).toHaveBeenCalledWith('welcome')\n })\n\n it('should highlight element when it is set externally', () => {\n const mockEditExtensionPoint = jest.fn()\n const mockHighlightHandler = jest.fn()\n const { queryByTestId } = render(\n <HighlightOverlay\n editExtensionPoint={mockEditExtensionPoint}\n editMode\n highlightHandler={mockHighlightHandler}\n highlightTreePath={extensionPointName}\n />\n )\n\n expect(queryByTestId('editor-provider-overlay')).toBeFalsy()\n\n act(() => {\n window.__setHighlightTreePath({\n sidebarBlocksMap: mockBlocks,\n })\n })\n\n expect(queryByTestId('editor-provider-overlay')).toBeTruthy()\n })\n\n it(`should show extension point title when it's highlighted`, () => {\n const mockEditExtensionPoint = jest.fn()\n const mockHighlightHandler = jest.fn()\n const { queryByText } = render(\n <HighlightOverlay\n editExtensionPoint={mockEditExtensionPoint}\n editMode\n highlightHandler={mockHighlightHandler}\n highlightTreePath={extensionPointName}\n />\n )\n\n expect(queryByText(/welcome banner/i)).toBeFalsy()\n\n act(() => {\n window.__setHighlightTreePath({\n sidebarBlocksMap: mockBlocks,\n })\n })\n\n expect(queryByText(/welcome banner/i)).toBeTruthy()\n })\n})\n\n```" } ]
code_admin-pages_5793ee67
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/HighlightOverlay.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.highlight-enter {\n opacity: 0;\n border-color: rgba(19, 76, 216, 0);\n}\n\n.highlight-enter-active {\n transition: opacity 150ms cubic-bezier(0.19, 1, 0.22, 1),\n border-color 150ms cubic-bezier(0.19, 1, 0.22, 1);\n opacity: 1;\n border-color: rgba(19, 76, 216, 1);\n}\n\n.highlight-enter-done {\n opacity: 1;\n border-color: rgba(19, 76, 216, 1);\n}\n\n.highlight-exit {\n opacity: 1;\n border-color: rgba(19, 76, 216, 1);\n}\n\n.highlight-exit-active {\n transition: opacity 150ms cubic-bezier(0.215, 0.61, 0.355, 1),\n border-color 150ms cubic-bezier(0.215, 0.61, 0.355, 1);\n opacity: 0;\n border-color: rgba(19, 76, 216, 0);\n}\n\n.highlight-exit-done {\n opacity: 0;\n border-color: rgba(19, 76, 216, 0);\n}\n\n```" } ]
code_admin-pages_9f1757ae
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/TemporaryAlert/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport {\n Alert,\n ThemeProvider,\n createSystem,\n tag,\n Flex,\n IconNotifications,\n Anchor,\n} from '@vtex/admin-ui'\nimport { useIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\n\nconst system = createSystem('admin-pages')\n\nexport function TemporaryAlert() {\n const { workspace, production } = useRuntime()\n const { formatMessage } = useIntl()\n\n if (workspace !== 'newadmin' || !production) {\n return null\n }\n\n const url = window.top.location.href.replace(`${workspace}--`, '')\n\n return (\n <ThemeProvider system={system}>\n <tag.div\n csx={{\n padding: 4,\n }}\n >\n <Alert visible fluid>\n <Flex>\n <Flex align=\"center\">\n <IconNotifications\n csx={{\n color: 'blue',\n }}\n />\n </Flex>\n <Flex\n align=\"center\"\n csx={{\n marginLeft: 2,\n }}\n >\n <span>\n {formatMessage({ id: 'admin/pages.editor.newadmin.alert' })}\n <Anchor href={url} target=\"_blank\">\n {formatMessage({\n id: 'admin/pages.editor.newadmin.alert.anchor',\n })}\n </Anchor>\n </span>\n </Flex>\n </Flex>\n </Alert>\n </tag.div>\n </ThemeProvider>\n )\n}\n\n```" } ]
code_admin-pages_4340cbf1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport { JSONSchema6 } from 'json-schema'\nimport React, { Fragment, useMemo, useRef, useState } from 'react'\nimport { graphql, MutationFunc } from 'react-apollo'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { WidgetProps } from 'react-jsonschema-form'\nimport URL from 'url-parse'\nimport { Spinner } from 'vtex.styleguide'\n\nimport UploadFile from '../../../queries/UploadFile.graphql'\nimport ActionMenu from '../../ActionMenu'\nimport { ActionMenuOption } from '../../ActionMenu/typings'\nimport Dropzone from './Dropzone'\nimport EmptyState from './EmptyState'\nimport ErrorAlert from './ErrorAlert'\nimport ImagePreview from './ImagePreview'\n\ninterface Props {\n disabled?: boolean\n onChange?: (pathname: string | null) => void\n onFileDrop?: (file: File) => void\n schema: JSONSchema6\n uploadFile?: MutationFunc<MutationData>\n value: string\n}\n\ninterface State {\n error: string | null\n isLoading: boolean\n}\n\ninterface MutationData {\n uploadFile: { fileUrl: string }\n}\n\nconst messages = defineMessages({\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.admin.pages.form.field.array.item.delete',\n },\n edit: {\n defaultMessage: 'Edit',\n id: 'admin/pages.admin.pages.form.field.array.item.edit',\n },\n fileSizeError: {\n defaultMessage:\n 'File exceeds the size limit of 4MB. Please choose a smaller one.',\n id: 'admin/pages.editor.image-uploader.error.file-size',\n },\n genericError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.image-uploader.error.generic',\n },\n})\n\nconst ImageUploader: React.FC<Props> = props => {\n const [state, setState] = useState<State>({ error: null, isLoading: false })\n const dropZoneRef = useRef<HTMLDivElement>(null)\n\n const intl = useIntl()\n\n const {\n disabled,\n onChange,\n schema: { title },\n value,\n } = props\n const { error, isLoading } = state\n\n const handleImageDrop = async (acceptedFiles: File[]) => {\n const { uploadFile } = props as {\n uploadFile: MutationFunc<MutationData>\n }\n\n if (acceptedFiles && acceptedFiles[0]) {\n setState(prevState => ({ ...prevState, isLoading: true }))\n\n try {\n let url = null\n\n if (uploadFile) {\n const {\n data: {\n uploadFile: { fileUrl },\n },\n } = (await uploadFile({\n variables: { file: acceptedFiles[0] },\n })) as { data: MutationData }\n url = fileUrl\n }\n\n if (onChange) {\n const path = url && new URL(url).pathname\n onChange(path)\n }\n\n if (props.onFileDrop) {\n props.onFileDrop(acceptedFiles[0])\n }\n\n setState(prevState => ({ ...prevState, isLoading: false }))\n } catch (e) {\n setState({\n error: intl.formatMessage(messages.genericError),\n isLoading: false,\n })\n }\n } else {\n setState(prevState => ({\n ...prevState,\n error: intl.formatMessage(messages.fileSizeError),\n }))\n }\n }\n\n const handleErrorReset = () => {\n setState(prevState => ({ ...prevState, error: null }))\n }\n\n const options: ActionMenuOption[] = useMemo(\n () => [\n {\n label: intl.formatMessage(messages.edit),\n onClick: () => {\n if (dropZoneRef.current) {\n dropZoneRef.current.click()\n }\n },\n },\n {\n label: intl.formatMessage(messages.delete),\n onClick: () => {\n if (onChange) {\n onChange(null)\n }\n },\n },\n ],\n [intl, onChange, dropZoneRef]\n )\n\n return (\n <Fragment>\n <FormattedMessage id={title as string}>\n {text => <span className=\"w-100 db mb3\">{text}</span>}\n </FormattedMessage>\n <Dropzone\n disabled={disabled || isLoading}\n extraClasses={classnames({\n 'ba b--dashed bw1 b--light-gray': !value || isLoading,\n 'bg-light-gray pointer': !!value,\n 'bg-white b--solid': isLoading,\n cursor: !isLoading && !value,\n })}\n onClick={handleErrorReset}\n onDrop={handleImageDrop}\n ref={dropZoneRef}\n >\n {isLoading ? (\n <div className=\"w-100 h-100 flex justify-center items-center\">\n <Spinner />\n </div>\n ) : value ? (\n <ImagePreview imageUrl={value}>\n <ActionMenu\n variation=\"primary\"\n menuWidth={200}\n options={options}\n buttonSize=\"small\"\n />\n </ImagePreview>\n ) : (\n <EmptyState />\n )}\n </Dropzone>\n {error && <ErrorAlert message={error} />}\n </Fragment>\n )\n}\n\nImageUploader.defaultProps = {\n disabled: false,\n value: '',\n}\n\nexport default graphql<Props & (WidgetProps | {})>(UploadFile, {\n name: 'uploadFile',\n})(ImageUploader)\n\n```" } ]
code_admin-pages_4b614595
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/Dropzone.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { ReactElement } from 'react'\nimport ReactDropzone, { DropzoneOptions, useDropzone } from 'react-dropzone'\n\ninterface Props {\n children: ReactElement<unknown>\n disabled: boolean\n extraClasses?: string\n onClick: React.MouseEventHandler<HTMLElement>\n onDrop: DropzoneOptions['onDrop']\n ref?: React.Ref<HTMLDivElement>\n}\n\nconst MAX_SIZE = 4 * 1024 * 1024\n\nconst Dropzone = React.forwardRef<HTMLDivElement, Props>(\n ({ disabled, children, extraClasses, onClick, onDrop }, ref) => {\n const { isDragActive } = useDropzone()\n\n const stlye = isDragActive\n ? { borderColor: '#134cd8', width: '14.25rem', height: '7rem' }\n : {}\n\n return (\n <ReactDropzone\n accept=\"image/*\"\n disabled={disabled}\n maxSize={MAX_SIZE}\n multiple={false}\n onDrop={onDrop}\n >\n {({ getRootProps, getInputProps }) => (\n <div\n {...getRootProps({ onClick: e => onClick(e), stlye })}\n className={`w-100 h4 br2 ${extraClasses}`}\n ref={ref}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n )}\n </ReactDropzone>\n )\n }\n)\n\nDropzone.displayName = 'Dropzone'\n\nDropzone.defaultProps = {\n extraClasses: '',\n}\n\nexport default Dropzone\n\n```" } ]
code_admin-pages_e446ae4a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.emptyStateContainer {\n width: 100%;\n height: 8rem;\n}\n\n.emptyState {\n width: 100%;\n height: 100%;\n text-align: center;\n margin: auto;\n}\n\n.emptyStateContainer:hover > div {\n color: #134cd8;\n border-color: #134cd8;\n width: 12.93rem;\n height: 7rem;\n}\n\n.imageUploaderText {\n max-width: 11.3rem;\n}\n\n```" } ]
code_admin-pages_a7d09c1e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/ImagePreview.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { createKeydownFromClick } from 'keydown-from-click'\nimport React, { useMemo } from 'react'\n\nimport styles from './ImagePreview.css'\n\ninterface Props {\n imageUrl: string\n children: React.ReactElement\n}\n\nfunction stopPropagation(\n e: Pick<React.MouseEvent<HTMLDivElement>, 'stopPropagation'>\n) {\n e.stopPropagation()\n}\n\nconst stopOnKeyDownPropagation = createKeydownFromClick(stopPropagation)\n\nconst ImagePreview: React.FC<Props> = ({ children, imageUrl }) => {\n const backgroundImageStyle = useMemo(\n () => ({\n backgroundImage: `url(${imageUrl}?width=710&height=384&aspect=true)`,\n }),\n [imageUrl]\n )\n\n return (\n <div\n className=\"w-100 h-100 relative bg-center contain\"\n style={backgroundImageStyle}\n >\n <div\n className={`w-100 h-100 absolute bottom-0 br2 flex flex-column items-center justify-center ${styles.overlay}`}\n >\n <div\n style={{ top: '0.5rem', right: '0.5rem' }}\n className=\"absolute bg-action-primary br2 flex h2 items-center justify-center w2 white\"\n onClick={stopPropagation}\n onKeyDown={stopOnKeyDownPropagation}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n </div>\n </div>\n )\n}\n\nexport default React.memo(ImagePreview)\n\n```" } ]
code_admin-pages_5c52994e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/ErrorAlert.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { Alert } from 'vtex.styleguide'\n\ninterface Props {\n message: string\n}\n\nconst ErrorAlert: React.FunctionComponent<Props> = ({ message }) => {\n const [isVisible, setIsVisible] = useState(true)\n\n return isVisible ? (\n <div className=\"w-100 mt3\">\n <Alert onClose={() => setIsVisible(false)} type=\"error\">\n {message}\n </Alert>\n </div>\n ) : null\n}\n\nexport default ErrorAlert\n\n```" } ]
code_admin-pages_3cba232e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/EmptyState.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\nimport IconImage from '../../MediaGalleryWidget/icons/IconImage'\nimport styles from './styles.css'\n\nconst EmptyState = ({ style }: { style?: React.CSSProperties }) => {\n return (\n <div\n className={`flex justify-center align-center items-center ${styles.emptyStateContainer}`}\n >\n <div\n style={style}\n className={`h-100 flex flex-column justify-center items-center pointer b--mid-gray b--dashed ba br2 c-muted-1 ${styles.emptyState}`}\n >\n <div className=\"mb4\">\n <IconImage />\n </div>\n <div className={`tc ${styles.imageUploaderText}`}>\n <FormattedMessage id=\"admin/pages.editor.image-uploader.empty.button\" />\n </div>\n </div>\n </div>\n )\n}\n\nexport default React.memo(EmptyState)\n\n```" } ]
code_admin-pages_9b135187
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ImageUploader/ImagePreview.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.overlay {\n background: rgba(0, 0, 0, 0.15);\n opacity: 0;\n transition: opacity ease-in-out 100ms;\n}\n\n.overlay:hover {\n opacity: 1;\n}\n\n```" } ]
code_admin-pages_0535c9f4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/I18nInput/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { appendInvisibleCharacter } from '../../../utils/components'\nimport BaseInput from '../BaseInput'\nimport TextArea from '../TextArea'\nimport { CustomWidgetProps } from '../typings'\n\nimport { isValidData } from './utils'\n\ninterface Props extends CustomWidgetProps {\n isTextarea?: boolean\n}\n\n/*\n * While there isn't currently an efficient way to update the inner Runtime's\n * intl, this component uses the IOMessage's fallback behavior to modify i18n\n * properties.\n *\n * Since the value actually represents an i18n key, typing in the name of an\n * existing one would cause the block to render the corresponding intl string.\n *\n * In order to prevent that, this component adds an invisible character after\n * the input value, so it will (probably) never match an i18n key. The\n * invisible character is removed once the form is submitted, before being sent\n * to the server.\n */\n\nconst I18nInput: React.FunctionComponent<Props> = ({\n isTextarea,\n onChange,\n value,\n ...commonProps\n}) => {\n const [localValue, setLocalValue] = React.useState(value)\n\n const safeOnChange: CustomWidgetProps['onChange'] = React.useCallback(\n data => {\n if (!isValidData(data)) {\n return\n }\n\n const { target, value: newValue } = data\n\n let cursorPosition = target.selectionStart\n\n // Appends an invisible character to the input value. For more\n // information, please read the comment above this component.\n onChange(appendInvisibleCharacter(newValue))\n\n setLocalValue(newValue)\n\n // Prevents the cursor from jumping around\n target.selectionStart = cursorPosition\n },\n [onChange]\n )\n\n const finalProps = {\n ...commonProps,\n isI18n: true,\n onChange: safeOnChange,\n value: localValue,\n }\n\n if (isTextarea) {\n return <TextArea {...finalProps} />\n }\n\n return <BaseInput {...finalProps} />\n}\n\nexport default I18nInput\n\n```" } ]
code_admin-pages_8b3f485c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/I18nInput/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const isValidData = (\n data: unknown\n): data is {\n target: HTMLInputElement | HTMLTextAreaElement\n value: string\n} =>\n typeof data === 'object' &&\n data !== null &&\n Object.prototype.hasOwnProperty.call(data, 'target') &&\n Object.prototype.hasOwnProperty.call(data, 'value')\n\n```" } ]
code_admin-pages_db24d4d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { JSONSchema6 } from 'json-schema'\nimport React, { Component, Fragment } from 'react'\nimport {\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { ArrayFieldTemplateProps } from 'react-jsonschema-form'\nimport {\n Dimensions,\n SortableContainerProps,\n SortStart,\n} from 'react-sortable-hoc'\n\nimport AddButton from './AddButton'\nimport ArrayList from './ArrayList'\nimport styles from './styles.css'\n\ninterface Props extends ComponentWithIntlProps {\n canAdd: boolean\n items?: ArrayFieldTemplateProps['items']\n onAddClick?: (event: Event) => void\n schema: JSONSchema6\n}\n\ninterface State {\n sorting?: boolean\n openItem: number | null\n}\n\nfunction getHelperDimensions({ node }: SortStart): Dimensions {\n const label = node.querySelector(\n `.${styles['accordion-label']}`\n ) as HTMLElement\n const width = node instanceof HTMLElement ? node.offsetWidth : 0\n\n return {\n height: label && label.offsetHeight,\n width,\n }\n}\n\nclass ArrayFieldTemplate extends Component<\n Props & ArrayFieldTemplateProps,\n State\n> {\n private stackDepth: number\n\n public constructor(props: Props & ArrayFieldTemplateProps) {\n super(props)\n\n this.state = {\n openItem: null,\n }\n\n this.stackDepth =\n (this.props.formContext.componentFormState &&\n this.props.formContext.componentFormState.depth) ||\n 0\n }\n\n public render() {\n const { canAdd, intl, items, schema, title } = this.props\n const { openItem, sorting } = this.state\n\n return (\n <Fragment>\n {!openItem && title && (\n <h4 className=\"mb4 mt0\">{intl.formatMessage({ id: title })}</h4>\n )}\n <ArrayList\n formContext={this.props.formContext}\n getHelperDimensions={getHelperDimensions}\n getContainer={this.getContainer}\n helperClass={styles['accordion-item--dragged']}\n items={items}\n lockAxis=\"y\"\n lockToContainerEdges\n onClose={this.handleClose}\n onOpen={this.handleOpen}\n onSortEnd={this.handleSortEnd}\n onSortStart={this.handleSortStart}\n openItem={openItem}\n stackDepth={this.stackDepth}\n schema={schema}\n sorting={sorting}\n useDragHandle\n >\n {canAdd ? <AddButton onClick={this.handleAddItem} /> : null}\n </ArrayList>\n </Fragment>\n )\n }\n\n private getContainer() {\n return (\n document.getElementById('component-editor-container') || document.body\n )\n }\n\n private handleOpen = (index: number) => (e: React.MouseEvent | unknown) => {\n if (e instanceof Event) {\n e.stopPropagation()\n }\n\n if (typeof this.props.formContext.pushComponentFormState === 'function') {\n this.props.formContext.pushComponentFormState({\n onClose: this.handleClose,\n title: this.props.intl.formatMessage({ id: this.props.title }),\n })\n }\n\n this.setState(state => ({\n ...state,\n openItem: index,\n }))\n }\n\n private handleClose = () => {\n if (typeof this.props.formContext.popComponentFormState === 'function') {\n this.props.formContext.popComponentFormState()\n }\n\n this.setState(state => ({\n ...state,\n openItem: null,\n }))\n }\n\n private handleSortStart = () => {\n this.setState({\n sorting: true,\n })\n }\n\n private handleSortEnd: SortableContainerProps['onSortEnd'] = (\n { oldIndex, newIndex },\n e\n ) => {\n const { items } = this.props\n const { onReorderClick } = items[oldIndex]\n\n if (oldIndex !== newIndex) {\n onReorderClick(oldIndex, newIndex)(e)\n }\n\n this.setState({\n sorting: false,\n })\n }\n\n private handleAddItem = (e: Event) => {\n const { onAddClick, items } = this.props\n\n onAddClick(e)\n this.setState({\n openItem: items.length,\n })\n\n if (typeof this.props.formContext.pushComponentFormState === 'function') {\n this.props.formContext.pushComponentFormState({\n onClose: this.handleClose,\n title: this.props.intl.formatMessage({ id: this.props.title }),\n })\n }\n }\n}\n\nconst ArrayFieldTemplateWithIntl = injectIntl(ArrayFieldTemplate)\n\nconst StatelessArrayFieldTemplate: React.FunctionComponent<ArrayFieldTemplateProps> = props => {\n return <ArrayFieldTemplateWithIntl {...props} />\n}\n\nexport default StatelessArrayFieldTemplate\n\n```" } ]
code_admin-pages_d5b43197
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayList.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { JSONSchema6 } from 'json-schema'\nimport { CSSTransition } from 'react-transition-group'\nimport React, { Fragment } from 'react'\nimport { ArrayFieldTemplateProps } from 'react-jsonschema-form'\nimport { SortableContainer, SortableContainerProps } from 'react-sortable-hoc'\n\nimport { ANIMATION_TIMEOUT } from '../../consts'\nimport { ActionMenuOption } from '../../ActionMenu/typings'\n\nimport ArrayFieldTemplateItem from './ArrayFieldTemplateItem'\nimport ItemForm from './ItemForm'\n\nimport styles from './styles.css'\nimport transitionStyles from './ItemTransitions.css'\n\ninterface ArrayListProps {\n formContext: { currentDepth: number }\n items: ArrayFieldTemplateProps['items']\n onClose: () => void\n onOpen: (\n index: number\n ) => (e: Pick<React.MouseEvent, 'stopPropagation'> | ActionMenuOption) => void\n openItem: number | null\n schema: JSONSchema6\n sorting?: boolean\n stackDepth: number\n}\n\nconst transitionClassNames = {\n appear: transitionStyles['item-enter'],\n appearActive: transitionStyles['item-enter-active'],\n appearDone: transitionStyles['item-enter-done'],\n enter: transitionStyles['item-enter'],\n enterActive: transitionStyles['item-enter-active'],\n enterDone: transitionStyles['item-enter-done'],\n exit: transitionStyles['item-exit'],\n exitActive: transitionStyles['item-exit-active'],\n exitDone: transitionStyles['item-exit-done'],\n}\n\nconst ArrayList: React.FC<ArrayListProps & SortableContainerProps> = ({\n children,\n formContext,\n items,\n schema,\n openItem,\n onOpen,\n onClose,\n sorting,\n stackDepth,\n}) => (\n <div className={sorting ? styles['accordion-list-container--sorting'] : ''}>\n {children}\n {items.map(element => (\n <Fragment key={element.index}>\n <ArrayFieldTemplateItem\n schema={schema}\n onOpen={onOpen(element.index)}\n onClose={onClose}\n formIndex={element.index}\n showDragHandle={items.length > 1}\n {...element}\n />\n <CSSTransition\n appear\n in={element.index === openItem}\n mountOnEnter\n unmountOnExit\n timeout={ANIMATION_TIMEOUT}\n classNames={transitionClassNames}\n >\n <ItemForm\n currentDepth={formContext.currentDepth}\n stackDepth={stackDepth + 1}\n onClose={onClose}\n >\n {element.children}\n </ItemForm>\n </CSSTransition>\n </Fragment>\n ))}\n </div>\n)\n\nexport default SortableContainer(ArrayList)\n\n```" } ]
code_admin-pages_49e23037
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ItemForm.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { CSSTransition } from 'react-transition-group'\nimport { Button } from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport styles from './styles.css'\nimport transitionStyles from './ItemTransitions.css'\n\ninterface Props {\n children: React.ReactElement\n currentDepth: number\n onClose: () => void\n stackDepth: number\n}\n\nconst messages = defineMessages({\n apply: {\n defaultMessage: 'Apply',\n id: 'admin/pages.admin.pages.form.field.array.item.apply',\n },\n})\n\nconst ItemForm: React.FC<Props> = ({\n children,\n currentDepth,\n onClose,\n stackDepth,\n}) => {\n const intl = useIntl() \n const { route } = useRuntime()\n\n const isStoreSettingsPage = route.path.includes(\"cms/store\") \n\n return (\n <CSSTransition\n in={stackDepth < currentDepth}\n classNames={{\n enter: transitionStyles['item-depth-enter'],\n enterActive: transitionStyles['item-depth-enter-active'],\n enterDone: transitionStyles['item-depth-enter-done'],\n exit: transitionStyles['item-depth-exit'],\n exitActive: transitionStyles['item-depth-exit-active'],\n exitDone: transitionStyles['item-depth-exit-done'],\n }}\n timeout={150}\n >\n <div\n className={classnames(\n `${styles['accordion-item']} \n ${isStoreSettingsPage && styles['accordion-item-settings']} \n bg-white bb b--light-silver absolute left-0 top-0 ph6 w-100 z-1`\n )}\n >\n {children}\n <div className=\"mb5\">\n <Button type=\"button\" variation=\"primary\" onClick={onClose}>\n {intl.formatMessage(messages.apply)}\n </Button>\n </div>\n </div>\n </CSSTransition>\n )\n}\n\nexport default ItemForm\n\n```" } ]
code_admin-pages_a947efe9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.accordion-item {\n background-color: white;\n}\n\n.accordion-item-settings {\n padding: 2rem;\n transform: translateX(0rem) !important; \n}\n\n.accordion-list-container--sorting .accordion-item {\n pointer-events: none;\n}\n\n.accordion-item--dragged {\n z-index: 999;\n}\n\n.accordion-label {\n display: flex;\n position: relative;\n margin: 0 -24px 0;\n padding: 12px 16px;\n cursor: pointer;\n user-select: none;\n}\n\n.accordion-item--dragged .accordion-label {\n background-color: #fff;\n}\n\n.accordion-item--handle-hidden .accordion-label {\n padding-left: 16px;\n}\n\n.accordion-item--dragged .accordion-label {\n box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);\n}\n\n.accordion-label-title {\n color: #727273;\n font-weight: bold;\n cursor: pointer;\n}\n\n.accordion-item--dragged .accordion-handle,\n.accordion-label:hover .accordion-handle {\n display: block;\n}\n\n.drag-handle-container {\n transform: translateZ(0);\n transition: transform ease-in-out 100ms;\n}\n\n.drag-handle-container:hover,\n.accordion-item--dragged .drag-handle-container {\n transform: scale(1.1);\n}\n\n.drag-handle-container:hover circle,\n.accordion-item--dragged .drag-handle-container circle {\n fill: #368df7;\n}\n\n```" } ]
code_admin-pages_6fc44745
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/AddButton.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'\nimport { ButtonWithIcon } from 'vtex.styleguide'\n\nimport AddIcon from '../../icons/AddIcon'\n\ninterface Props {\n onClick: (event: Event) => void\n}\n\nconst icon = <AddIcon />\n\nconst AddButton: React.FC<Props> = ({ onClick }) => (\n <div className=\"ba b--muted-4 br2 mb3\">\n <ButtonWithIcon block icon={icon} onClick={onClick} variation=\"tertiary\">\n <FormattedMessage\n defaultMessage=\"Add\"\n id=\"admin/pages.editor.components.arrayTemplate.button.add\"\n >\n {text => <div className=\"mv3\">{text}</div>}\n </FormattedMessage>\n </ButtonWithIcon>\n </div>\n)\n\nexport default AddButton\n\n```" } ]
code_admin-pages_71b6cb20
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ItemTransitions.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.item-enter {\n transform: translateX(36rem);\n}\n\n.item-enter-active {\n transform: translateX(18rem);\n transition: transform 250ms ease-in-out;\n}\n\n.item-enter-done {\n transform: translateX(18rem);\n}\n\n.item-exit {\n transform: translateX(18rem);\n}\n\n.item-exit-active {\n transform: translateX(36rem);\n transition: transform 250ms ease-in-out;\n}\n\n.item-exit-done {\n transform: translateX(36rem);\n}\n\n.item-depth-enter {\n transform: translateX(18rem);\n}\n\n.item-depth-enter-active {\n transform: translateX(0rem);\n transition: transform 250ms ease-in-out;\n}\n\n.item-depth-enter-done {\n transform: translateX(0rem);\n}\n\n/* So the hidden item doesn't affect the height of the current form */\n.item-depth-enter-done > :global(.vtex-admin-pages-4-x .form-group) {\n height: 0;\n overflow: hidden;\n}\n\n.item-depth-exit {\n transform: translateX(0rem);\n}\n\n.item-depth-exit-active {\n transform: translateX(18rem);\n transition: transform 250ms ease-in-out;\n}\n\n.item-depth-exit-done {\n transform: translateX(18rem);\n}\n\n```" } ]
code_admin-pages_c54de125
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { createKeydownFromClick } from 'keydown-from-click'\nimport classnames from 'classnames'\nimport { JSONSchema6 } from 'json-schema'\nimport { path } from 'ramda'\nimport React, { useCallback, useMemo } from 'react'\nimport { defineMessages, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { ArrayFieldTemplateProps } from 'react-jsonschema-form'\nimport { SortableElement, SortableElementProps } from 'react-sortable-hoc'\n\nimport ActionMenu from '../../../ActionMenu'\nimport { ActionMenuOption } from '../../../ActionMenu/typings'\n\nimport Handle from './Handle'\nimport NoImagePlaceholder from './NoImagePlaceholder'\nimport PreviewOverlay from './PreviewOverlay'\n\nimport templateStyles from '../styles.css'\nimport itemStyles from './ArrayFieldTemplateItem.css'\n\nconst stopPropagation = (e: Pick<React.MouseEvent, 'stopPropagation'>) => {\n e.stopPropagation()\n}\n\ninterface CustomProps {\n children?: React.ReactElement<{ formData: number }> | React.ReactNode\n formIndex: number\n hasRemove: boolean\n onClose: () => void\n onOpen: (\n e: Pick<React.MouseEvent, 'stopPropagation'> | ActionMenuOption\n ) => void\n showDragHandle: boolean\n schema: JSONSchema6\n}\n\ntype PropsFromItemTemplateProps = Pick<\n ArrayFieldTemplateProps['items'][0],\n 'onDropIndexClick' | 'hasRemove' | 'children'\n>\ntype Props = CustomProps &\n SortableElementProps &\n PropsFromItemTemplateProps &\n InjectedIntlProps\n\nconst messages = defineMessages({\n defaultTitle: {\n defaultMessage: 'Item',\n id: 'admin/pages.admin.pages.form.field.array.item',\n },\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.admin.pages.form.field.array.item.delete',\n },\n edit: {\n defaultMessage: 'Edit',\n id: 'admin/pages.admin.pages.form.field.array.item.edit',\n },\n})\n\nfunction getComponentSchema(schema: JSONSchema6): ComponentSchema | null {\n if (\n schema.items &&\n !Array.isArray(schema.items) &&\n typeof schema.items === 'object' &&\n typeof schema.items.properties === 'object'\n ) {\n return schema as ComponentSchema\n }\n return null\n}\n\nconst isImageUploader = (schema: ComponentSchema) =>\n !!schema.widget && schema.widget['ui:widget'] === 'image-uploader'\n\nconst ArrayFieldTemplateItem: React.FC<Props> = props => {\n const {\n children,\n formIndex,\n hasRemove,\n intl,\n onOpen,\n onDropIndexClick,\n schema,\n showDragHandle,\n } = props\n\n const componentSchema = React.useMemo(() => getComponentSchema(schema), [\n schema,\n ])\n\n const handleItemClick = useCallback(\n (e: Pick<React.MouseEvent, 'stopPropagation'> | ActionMenuOption) => {\n onOpen(e)\n },\n [onOpen]\n )\n\n const handleItemKeyDown = createKeydownFromClick(handleItemClick)\n const itemStopPropagation = createKeydownFromClick(stopPropagation)\n\n const hasImageUploader = useMemo(\n () =>\n componentSchema &&\n componentSchema.items &&\n !Array.isArray(componentSchema.items) &&\n componentSchema.items.properties &&\n Object.values(componentSchema.items.properties).some(isImageUploader),\n [componentSchema]\n )\n\n const imagePreview = useMemo(() => {\n const properties =\n componentSchema &&\n componentSchema.items &&\n !Array.isArray(componentSchema.items) &&\n componentSchema.items.properties\n\n const imagePropertyKey =\n properties &&\n Object.keys(properties)\n .filter(property => isImageUploader(properties[property]))\n .sort((first, second) => {\n if (\n first.indexOf('mobile') !== -1 &&\n second.indexOf('mobile') === -1\n ) {\n return 1\n }\n\n if (\n first.indexOf('mobile') === -1 &&\n second.indexOf('mobile') !== -1\n ) {\n return -1\n }\n\n return 0\n })\n .find(key => {\n return !!children.props.formData[key]\n })\n\n return imagePropertyKey && children.props.formData[imagePropertyKey]\n }, [componentSchema, children.props.formData])\n\n const actionMenuOptions: ActionMenuOption[] = useMemo(() => {\n const options: ActionMenuOption[] = [\n {\n label: intl.formatMessage(messages.edit),\n onClick: e => {\n handleItemClick(e)\n },\n },\n ]\n\n if (hasRemove) {\n options.push({\n label: intl.formatMessage(messages.delete),\n onClick: () => {\n const e = new Event('click')\n onDropIndexClick(formIndex)(e)\n },\n })\n }\n\n return options\n }, [handleItemClick, onDropIndexClick, formIndex, hasRemove, intl])\n\n const title =\n children.props.formData.__editorItemTitle ||\n path(['items', 'properties', '__editorItemTitle', 'default'], schema)\n\n return (\n <div\n className={classnames(\n 'bg-white bb b--light-silver',\n {\n [templateStyles['accordion-item--handle-hidden']]: showDragHandle,\n },\n templateStyles['accordion-item']\n )}\n >\n <div\n className={`${\n templateStyles['accordion-label']\n } bg-white flex items-center justify-center overflow-hidden relative outline-0 ${\n hasImageUploader ? 'h4' : 'h3'\n }`}\n onClick={handleItemClick}\n onKeyDown={handleItemKeyDown}\n role=\"treeitem\"\n tabIndex={0}\n >\n {showDragHandle && <Handle />}\n <div\n className={classnames(\n 'relative flex items-center',\n itemStyles['preview-container'],\n {\n [`${itemStyles['multi-item']} mr3`]: showDragHandle,\n [`${itemStyles['single-item']}`]: !showDragHandle,\n [`${itemStyles['preview-text-container']} ml3`]:\n !hasImageUploader && !showDragHandle,\n }\n )}\n >\n {hasImageUploader ? (\n <>\n {imagePreview ? (\n <img\n alt=\"Preview\"\n className={`br3 bg-muted-5 h-100 w-100 ${itemStyles['preview-image']}`}\n src={imagePreview}\n />\n ) : (\n <NoImagePlaceholder />\n )}\n <PreviewOverlay />\n </>\n ) : (\n <span className={`f6 ${templateStyles['accordion-label-title']}`}>\n {intl.formatMessage(\n title ? { id: title } : messages.defaultTitle\n )}\n </span>\n )}\n <div\n className={`absolute top-0 right-0 mr3 mt3 ${itemStyles['action-menu-container']}`}\n onClick={stopPropagation}\n onKeyDown={itemStopPropagation}\n role=\"button\"\n tabIndex={0}\n >\n <ActionMenu\n variation=\"primary\"\n menuWidth={200}\n options={actionMenuOptions}\n buttonSize=\"small\"\n />\n </div>\n </div>\n </div>\n </div>\n )\n}\n\nexport default injectIntl(SortableElement<Props>(ArrayFieldTemplateItem))\n\n```" } ]
code_admin-pages_5e420fbe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/PreviewOverlay.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport styles from './ArrayFieldTemplateItem.css'\n\nconst PreviewOverlay = () => (\n <div\n className={`br3 absolute w-100 h-100 top-0 ${styles['preview-overlay']}`}\n ></div>\n)\n\nexport default React.memo(PreviewOverlay)\n\n```" } ]
code_admin-pages_8b420ba6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/Handle.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { SortableHandle } from 'react-sortable-hoc'\n\nimport DragHandle from '../../../icons/DragHandle'\nimport styles from '../styles.css'\n\nconst Handle = SortableHandle(() => (\n <div\n className={`flex flex-grow-1 h-100 items-center justify-center ${styles['drag-handle-container']}`}\n >\n <DragHandle size={12} className={styles['accordion-handle']} />\n </div>\n))\n\nexport default Handle\n\n```" } ]
code_admin-pages_6cb1f805
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/ArrayFieldTemplateItem.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.action-menu-container {\n opacity: 0;\n transition: opacity ease-in 100ms;\n}\n\n.preview-container:hover .action-menu-container {\n opacity: 1;\n}\n\n.preview-container {\n height: 100%;\n}\n\n.multi-item {\n width: calc(100% - 3rem);\n}\n\n.single-item {\n width: calc(100% - 1rem);\n}\n\n.preview-text-container {\n width: 100%;\n}\n\n.preview-image {\n object-fit: cover;\n transition: filter ease-in 100ms;\n}\n\n.preview-overlay {\n background-color: black;\n opacity: 0;\n transition: opacity ease-in 100ms;\n will-change: opacity;\n}\n\n.preview-container:hover .preview-overlay {\n opacity: 0.15;\n}\n\n```" } ]
code_admin-pages_e39c436f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/NoImagePlaceholder.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\nimport IconImage from './icons/IconImage'\n\nconst NoImagePlaceholder = () => (\n <div className=\"w-100 h-100 flex flex-column items-center justify-center bg-muted-5 br3\">\n <IconImage />\n\n <FormattedMessage\n id=\"admin/pages.editor.components.no-image\"\n defaultMessage=\"No image\"\n >\n {text => <p className=\"c-muted-1 f6 mb0 mt4\">{text}</p>}\n </FormattedMessage>\n </div>\n)\n\nexport default React.memo(NoImagePlaceholder)\n\n```" } ]
code_admin-pages_7a159b06
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/form/ArrayFieldTemplate/ArrayFieldTemplateItem/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 size?: number\n stroke?: string\n}\n\nconst ImageIcon: React.FunctionComponent<Props> = ({ size, stroke }) => (\n <svg\n width={`${size}px`}\n height={`${size}px`}\n viewBox=\"0 0 24 24\"\n version=\"1.1\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <g\n id=\"Artboard\"\n stroke=\"none\"\n strokeWidth=\"1\"\n fill=\"none\"\n fillRule=\"evenodd\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <g\n id=\"image-2\"\n transform=\"translate(0.000000, 1.000000)\"\n stroke={stroke}\n strokeWidth=\"1.4\"\n >\n <ellipse id=\"Oval\" cx=\"8.25\" cy=\"3.83426966\" rx=\"3\" ry=\"3.06741573\" />\n <polygon\n id=\"Shape\"\n points=\"0.75 22.238764 6.75 13.0365169 9.75 16.1039326 15.75 8.43539326 23.25 22.238764\"\n />\n </g>\n </g>\n </svg>\n)\n\nImageIcon.defaultProps = {\n size: 16,\n stroke: '#979899',\n}\n\nexport default React.memo(ImageIcon)\n\n```" } ]