id
stringlengths
12
53
messages
listlengths
3
3
code_admin-pages_0cdce7a9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { withApollo, WithApolloClient } from 'react-apollo'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { CSSTransition } from 'react-transition-group'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport { ANIMATION_TIMEOUT } from '../../consts'\nimport { useEditorContext } from '../../EditorContext'\nimport Modal from '../../Modal'\nimport SaveContentMutation from '../mutations/SaveContent'\nimport AbsoluteLoader from './AbsoluteLoader'\nimport BlockEditor from './BlockEditor'\nimport BlockSelector from './BlockSelector'\nimport useInitialEditingState from './hooks'\nimport { useModalContext } from './ModalContext'\nimport styles from './styles.css'\nimport Transitions from './Transitions'\nimport SendEventToAuditMutation from '../mutations/SendEventToAudit'\n\ninterface CustomProps {\n highlightHandler: (treePath: string | null) => void\n iframeRuntime: RenderContext\n updateHighlightTitleByTreePath: (\n titleByTreePath?: Record<string, { title?: string; isEditable: boolean }>\n ) => void\n}\n\ntype Props = WithApolloClient<\n CustomProps & InjectedIntlProps & Pick<ToastConsumerFunctions, 'showToast'>\n>\n\nconst Sidebar: React.FunctionComponent<Props> = ({\n client,\n highlightHandler,\n iframeRuntime,\n intl,\n showToast,\n updateHighlightTitleByTreePath,\n}) => {\n const [scrollState, setScrollState] = React.useState('overflow-y-auto')\n const adminSidebar = React.createRef<HTMLElement>()\n const initialEditingState = useInitialEditingState({\n client,\n iframeRuntime,\n intl,\n showToast,\n })\n\n const {\n actionHandler: handleModalAction,\n cancelHandler: handleModalCancel,\n close: handleModalClose,\n getIsOpen: getIsModalOpen,\n getTextButtonAction,\n getTextButtonCancel,\n getTextMessage,\n getTitle,\n isActionDanger,\n } = useModalContext()\n\n const editor = useEditorContext()\n\n React.useEffect(() => {\n adminSidebar.current?.scroll(0, 0)\n\n if (editor.editTreePath && adminSidebar.current?.scrollTop === 0) {\n setScrollState('overflow-y-hidden vh-100')\n } else {\n setScrollState('overflow-x-auto')\n }\n }, [editor.editTreePath])\n\n return (\n <div\n id=\"sidebar-vtex-editor\"\n className={'z-1 h-100 w-100 flex flex-row-reverse ' + scrollState}\n >\n <nav\n ref={adminSidebar}\n id=\"admin-sidebar\"\n className={\n `transition animated fadeIn b--light-silver bw1 z-2 h-100 pt8 pt0-ns ` +\n `overflow-x-hidden w-100 font-display bg-white shadow-solid-x w-18em-ns ${styles['admin-sidebar']} ` +\n scrollState\n }\n >\n <div className=\"relative h-100 flex flex-column dark-gray overflow-y-auto\">\n <Modal\n isActionDanger={isActionDanger}\n isActionLoading={editor.getIsLoading()}\n isOpen={getIsModalOpen()}\n onClickAction={handleModalAction}\n onClickCancel={handleModalCancel}\n onClose={handleModalClose}\n textButtonAction={getTextButtonAction()}\n textButtonCancel={getTextButtonCancel()}\n textMessage={getTextMessage()}\n title={getTitle()}\n />\n <div className=\"flex\">\n <AbsoluteLoader\n containerClassName={`w-100 h-100 absolute top-0 ${\n !editor.getIsLoading() ? 'dn' : ''\n }`}\n />\n\n <CSSTransition\n classNames={{\n enter: styles['transition-selector-enter'],\n enterActive: styles['transition-selector-enter-active'],\n enterDone: styles['transition-selector-enter-done'],\n exit: styles['transition-selector-exit'],\n exitActive: styles['transition-selector-exit-active'],\n exitDone: styles['transition-selector-exit-done'],\n }}\n in={!!initialEditingState}\n timeout={ANIMATION_TIMEOUT}\n >\n <BlockSelector\n highlightHandler={highlightHandler}\n iframeRuntime={iframeRuntime}\n updateHighlightTitleByTreePath={updateHighlightTitleByTreePath}\n />\n </CSSTransition>\n\n <Transitions.Exit condition={!initialEditingState} to=\"right\">\n <Transitions.Enter condition={!!initialEditingState} from=\"right\">\n <SaveContentMutation>\n {saveContent => (\n <SendEventToAuditMutation>\n {sendEventToAudit => (\n <BlockEditor\n iframeRuntime={iframeRuntime}\n initialEditingState={initialEditingState}\n saveContent={saveContent}\n sendEventToAudit={sendEventToAudit}\n showToast={showToast}\n />\n )}\n </SendEventToAuditMutation>\n )}\n </SaveContentMutation>\n </Transitions.Enter>\n </Transitions.Exit>\n </div>\n </div>\n </nav>\n </div>\n )\n}\n\nexport default injectIntl(withApollo(Sidebar))\n\n```" } ]
code_admin-pages_5fb12008
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/FormMetaContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component, createContext, useContext } from 'react'\n\nimport { FormMetaContext as FormMetaContextT } from './typings'\n\nconst defaultExternalState: FormMetaContextT = {\n getWasModified: () => {\n return false\n },\n setWasModified: () => {\n return\n },\n}\n\nconst FormMetaContext = createContext(defaultExternalState)\n\nexport const useFormMetaContext = () => useContext(FormMetaContext)\n\nexport const FormMetaConsumer = FormMetaContext.Consumer\n\ninterface State extends FormMetaContextT {\n isLoading: boolean\n wasModified: boolean\n}\n\nexport class FormMetaProvider extends Component<{}, State> {\n public constructor(props: {}) {\n super(props)\n\n this.state = {\n ...defaultExternalState,\n getWasModified: this.getWasModified,\n isLoading: false,\n setWasModified: this.setWasModified,\n wasModified: false,\n }\n }\n\n public render() {\n return (\n <FormMetaContext.Provider value={this.state}>\n {this.props.children}\n </FormMetaContext.Provider>\n )\n }\n\n private getWasModified: State['getWasModified'] = () => this.state.wasModified\n\n private setWasModified: State['setWasModified'] = (newValue, callback) => {\n this.setState({ wasModified: newValue }, () => {\n if (callback) {\n callback()\n }\n })\n }\n}\n\n```" } ]
code_admin-pages_0c51f14d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/utils.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport EXTENSIONS from './__fixtures__/extensions'\nimport { getIsSitewide } from './utils'\n\ndescribe('getIsSitewide', () => {\n it('should return true for AFTER', () => {\n const mockEditTreePath = 'store.home/$after_footer'\n\n expect(getIsSitewide(EXTENSIONS, mockEditTreePath)).toBe(true)\n })\n\n it('should return true for AROUND', () => {\n const mockEditTreePath = 'store.home/$around_homeWrapper'\n\n expect(getIsSitewide(EXTENSIONS, mockEditTreePath)).toBe(true)\n })\n\n it('should return true for BEFORE', () => {\n const mockEditTreePath = 'store.home/$before_header.full'\n\n expect(getIsSitewide(EXTENSIONS, mockEditTreePath)).toBe(true)\n })\n\n it('should return false for blocks without role', () => {\n const mockEditTreePath = 'store.home/carousel#home'\n\n expect(getIsSitewide(EXTENSIONS, mockEditTreePath)).toBe(false)\n })\n})\n\n```" } ]
code_admin-pages_fe07f493
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.transition-editor-enter {\n transform: translateX(18em);\n}\n\n.transition-editor-enter-active {\n transition: transform 250ms ease-in;\n transform: translateX(0);\n}\n\n.transition-editor-enter-done {\n transform: translateX(0);\n}\n\n.transition-editor-exit {\n transform: translateX(0);\n}\n\n.transition-editor-exit-active {\n transition: transform 250ms ease-in;\n transform: translateX(18em);\n}\n\n.transition-editor-exit-done {\n transform: translateX(18em);\n}\n\n.transition-selector-enter {\n transform: translateX(0);\n}\n\n.transition-selector-enter-active {\n transition: transform 250ms ease-in;\n transform: translateX(-18em);\n}\n\n.transition-selector-enter-done {\n transform: translateX(-18em);\n}\n\n.transition-selector-exit {\n transform: translateX(-18em);\n}\n\n.transition-selector-exit-active {\n transition: transform 250ms ease-in;\n transform: translateX(0);\n}\n\n.transition-selector-exit-done {\n transform: translateX(0);\n}\n\n/* Non small */\n@media screen and (min-width: 30em) {\n .admin-sidebar {\n border-left: 2px solid #f2f4f5;\n }\n\n .admin-sidebar::-webkit-scrollbar,\n .admin-sidebar::-webkit-scrollbar-track {\n width: 2px;\n background: #f2f4f5;\n }\n\n .admin-sidebar::-webkit-scrollbar-thumb {\n width: 2px;\n background: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n }\n}\n\n```" } ]
code_admin-pages_902da437
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/AbsoluteLoader.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 { Spinner } from 'vtex.styleguide'\n\nimport { useEditorContext } from '../../EditorContext'\n\ninterface Props {\n containerClassName?: string\n}\n\nconst AbsoluteLoader: React.FunctionComponent<Props> = ({\n children,\n containerClassName,\n}) => {\n const editor = useEditorContext()\n\n const isLoading = editor.getIsLoading()\n\n return (\n <>\n {isLoading ? (\n <div className=\"absolute bg-white-70 flex items-center h-100 justify-center w-100 z-2\">\n <Spinner />\n </div>\n ) : null}\n\n <div className={classnames('relative', containerClassName)}>\n {children}\n </div>\n </>\n )\n}\n\nexport default React.memo(AbsoluteLoader)\n\n```" } ]
code_admin-pages_c85248c0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { formatIOMessage } from 'vtex.native-types'\n\nimport { getBlockPath } from '../../../utils/blocks'\nimport {\n getActiveContentId,\n getComponentSchema,\n getExtension,\n getIframeImplementation,\n getSchemaPropsOrContentFromRuntime,\n} from '../../../utils/components'\nimport {\n GetDefaultCondition,\n GetFormData,\n GetInitialEditingState,\n UpdateEditorBlockData,\n} from './typings'\n\nexport const isUnidentifiedPageContext = (\n pageContext: RenderRuntime['route']['pageContext']\n) => pageContext.type !== '*' && pageContext.id === '*'\n\nexport const getIsSitewide = (\n extensions: Extensions,\n editTreePath: EditorContextType['editTreePath']\n) => {\n const blockPath = getBlockPath(extensions, editTreePath)\n\n return (\n (blockPath.length > 0 &&\n ['AFTER', 'AROUND', 'BEFORE'].includes(blockPath[1].role)) ||\n false\n )\n}\n\nexport const getDefaultCondition: GetDefaultCondition = ({\n iframeRuntime,\n isSitewide,\n}) => {\n const iframePageContext = iframeRuntime.route.pageContext\n\n const pageContext: ExtensionConfiguration['condition']['pageContext'] = isSitewide\n ? {\n id: '*',\n type: '*',\n }\n : {\n id: isUnidentifiedPageContext(iframePageContext)\n ? '*'\n : iframePageContext.id,\n type: iframePageContext.type,\n }\n\n return {\n allMatches: true,\n id: '',\n pageContext,\n statements: [],\n }\n}\n\nexport const getFormData: GetFormData = ({\n componentImplementation,\n content,\n contentSchema,\n iframeRuntime,\n}) =>\n getSchemaPropsOrContentFromRuntime({\n component: componentImplementation,\n contentSchema,\n isContent: true,\n messages: iframeRuntime.messages,\n propsOrContent: content,\n runtime: iframeRuntime,\n }) || {}\n\nexport const getInitialEditingState: GetInitialEditingState = ({\n data,\n editor,\n iframeRuntime,\n}) => {\n const treePath = editor.editTreePath || ''\n\n const extension = getExtension(treePath, iframeRuntime.extensions)\n\n const componentImplementation = getIframeImplementation(extension.component)\n\n const listContent = data && data.listContentWithSchema\n\n const contentSchema = listContent && JSON.parse(listContent.schemaJSON)\n\n const configurations = listContent && listContent.content\n\n const activeContentId = getActiveContentId({\n extensions: iframeRuntime.extensions,\n treePath: editor.editTreePath,\n })\n\n const activeContent =\n configurations &&\n configurations.find(\n configuration => configuration.contentId === activeContentId\n )\n\n const content =\n (activeContent &&\n activeContent.contentJSON &&\n JSON.parse(activeContent.contentJSON)) ||\n {}\n\n const condition = activeContent\n ? activeContent.condition\n : getDefaultCondition({\n iframeRuntime,\n isSitewide: editor.blockData.isSitewide,\n })\n\n const label = activeContent && activeContent.label\n\n const formData = getFormData({\n componentImplementation,\n content,\n contentSchema,\n iframeRuntime,\n })\n\n return {\n condition,\n contentId: activeContentId,\n content,\n formData,\n label,\n origin: (activeContent && activeContent.origin) || null,\n }\n}\n\nexport const updateEditorBlockData: UpdateEditorBlockData = ({\n data,\n editor,\n id,\n iframeRuntime,\n intl,\n serverTreePath,\n template,\n}) => {\n const treePath = editor.editTreePath || ''\n\n const extension = getExtension(treePath, iframeRuntime.extensions)\n\n const listContent = data && data.listContentWithSchema\n\n const componentImplementation = getIframeImplementation(extension.component)\n\n const contentSchema = listContent && JSON.parse(listContent.schemaJSON)\n\n const componentSchema = getComponentSchema({\n component: componentImplementation,\n contentSchema: contentSchema,\n isContent: true,\n propsOrContent: extension.content,\n runtime: iframeRuntime,\n })\n\n const title = formatIOMessage({ id: componentSchema.title || '', intl })\n\n const configurations = listContent && listContent.content\n\n const blockData = {\n componentImplementation,\n componentSchema,\n configurations,\n contentSchema,\n id,\n serverTreePath,\n template,\n title,\n }\n\n editor.setBlockData(blockData)\n}\n\n```" } ]
code_admin-pages_ab54997d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { InjectedIntl } from 'react-intl'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport { GetSchemaPropsOrContentFromRuntimeParams } from '../../../utils/components/typings'\nimport { ListContentData } from '../queries/ListContent'\n\nexport interface FormMetaContext {\n getWasModified: () => boolean\n setWasModified: (newValue: boolean, callback?: () => void) => void\n}\n\nexport interface ModalContext {\n actionHandler?: () => void\n cancelHandler?: () => void\n close: () => void\n getIsOpen: () => boolean\n getTextButtonAction: () => string\n getTextButtonCancel: () => string\n getTextMessage: () => string\n getTitle: () => string\n isActionDanger: boolean\n open: (handlers?: {\n actionHandler?: ModalContext['actionHandler']\n cancelHandler?: ModalContext['cancelHandler']\n closeCallbackHandler?: () => void\n isActionDanger?: ModalContext['isActionDanger']\n textButtonAction?: ModalContext['textButtonAction']\n textButtonCancel?: ModalContext['textButtonCancel']\n textMessage?: ModalContext['textMessage']\n title?: ModalContext['title']\n }) => void\n textButtonAction: string\n textButtonCancel: string\n textMessage: string\n title: string\n}\n\nexport interface SidebarComponent {\n name: string\n isEditable: boolean\n treePath: string\n}\n\nexport interface ModifiedSidebarComponent extends SidebarComponent {\n modifiedTreePath: string\n}\n\nexport interface EditingState\n extends Partial<Omit<ExtensionConfiguration, 'contentJSON'>> {\n content?: Extension['content']\n formData?: Extension['content']\n}\n\n// eslint-disable-next-line @typescript-eslint/prefer-interface\nexport type FormDataContainer = {\n formData: object\n}\n\ninterface GetInitialEditingStateParams {\n data: ListContentData\n editor: EditorContextType\n iframeRuntime: RenderContext\n}\n\nexport type GetInitialEditingState = (\n params: GetInitialEditingStateParams\n) => EditingState\n\nexport type GetDefaultCondition = ({\n iframeRuntime,\n isSitewide,\n}) => ExtensionConfiguration['condition']\n\ninterface GetFormDataParams {\n componentImplementation: GetSchemaPropsOrContentFromRuntimeParams['component']\n content: GetSchemaPropsOrContentFromRuntimeParams['propsOrContent']\n contentSchema: GetSchemaPropsOrContentFromRuntimeParams['contentSchema']\n iframeRuntime: GetSchemaPropsOrContentFromRuntimeParams['runtime']\n}\n\nexport type GetFormData = (params: GetFormDataParams) => Extension['content']\n\nexport type UpdateEditorBlockData = (\n params: Pick<BlockData, 'id' | 'serverTreePath' | 'template'> & {\n data?: ListContentData\n editor: EditorContextType\n iframeRuntime: RenderContext\n intl: InjectedIntl\n isSitewide: boolean\n }\n) => void\n\ninterface UseInitialEditingStateParams {\n client: ApolloClient\n iframeRuntime: RenderContext\n intl: InjectedIntl\n showToast: ToastConsumerFunctions['showToast']\n}\n\nexport type UseInitialEditingState = (\n params: UseInitialEditingStateParams\n) => EditingState | undefined\n\n```" } ]
code_admin-pages_cb709b8e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/ModalContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component, createContext, useContext } from 'react'\n\nimport { ModalContext as ModalContextT } from './typings'\n\nconst defaultExternalState: ModalContextT = {\n close: () => {\n return\n },\n getIsOpen: () => false,\n getTextButtonAction: () => '',\n getTextButtonCancel: () => '',\n getTextMessage: () => '',\n getTitle: () => '',\n isActionDanger: false,\n open: () => {\n return\n },\n textButtonAction: '',\n textButtonCancel: '',\n textMessage: '',\n title: '',\n}\n\nconst ModalContext = createContext(defaultExternalState)\n\nexport const useModalContext = () => useContext(ModalContext)\n\nexport const ModalConsumer = ModalContext.Consumer\n\ninterface State extends ModalContextT {\n closeCallbackHandler?: () => void\n isOpen: boolean\n}\n\nexport class ModalProvider extends Component<{}, State> {\n public constructor(props: {}) {\n super(props)\n\n this.state = {\n close: this.close,\n getIsOpen: this.getIsOpen,\n getTextButtonAction: this.getTextButtonAction,\n getTextButtonCancel: this.getTextButtonCancel,\n getTextMessage: this.getTextMessage,\n getTitle: this.getTitle,\n isActionDanger: false,\n isOpen: false,\n open: this.open,\n textButtonAction: '',\n textButtonCancel: '',\n textMessage: '',\n title: '',\n }\n }\n\n public render() {\n return (\n <ModalContext.Provider value={this.state}>\n {this.props.children}\n </ModalContext.Provider>\n )\n }\n\n private close: State['close'] = () => {\n this.setState(\n {\n isOpen: false,\n },\n () => {\n if (this.state.closeCallbackHandler) {\n this.state.closeCallbackHandler()\n }\n\n this.setState({\n actionHandler: undefined,\n cancelHandler: undefined,\n closeCallbackHandler: undefined,\n })\n }\n )\n }\n\n private getIsOpen: State['getIsOpen'] = () => this.state.isOpen\n\n private getTextButtonAction: State['getTextButtonAction'] = () =>\n this.state.textButtonAction\n\n private getTextButtonCancel: State['getTextButtonCancel'] = () =>\n this.state.textButtonCancel\n\n private getTextMessage: State['getTextMessage'] = () => this.state.textMessage\n\n private getTitle: State['getTitle'] = () => this.state.title\n\n private open: State['open'] = params => {\n this.setState(prevState => ({\n ...prevState,\n ...params,\n isActionDanger: (params && params.isActionDanger) || false,\n isOpen: true,\n textButtonAction: (params && params.textButtonAction) || '',\n textButtonCancel: (params && params.textButtonCancel) || '',\n textMessage: (params && params.textMessage) || '',\n title: (params && params.title) || '',\n }))\n }\n}\n\n```" } ]
code_admin-pages_e935552f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/hooks.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { getSitewideTreePath } from '../../../utils/blocks'\nimport { useEditorContext } from '../../EditorContext'\nimport ListContent from '../graphql/ListContent.graphql'\nimport { ListContentData, ListContentVariables } from '../queries/ListContent'\nimport { EditingState, UseInitialEditingState } from './typings'\nimport {\n getInitialEditingState,\n getIsSitewide,\n updateEditorBlockData,\n} from './utils'\n\nconst useInitialEditingState: UseInitialEditingState = ({\n client,\n iframeRuntime,\n intl,\n showToast,\n}) => {\n const editor = useEditorContext()\n\n const treePath = editor.editTreePath || ''\n\n const isSitewide = getIsSitewide(iframeRuntime.extensions, treePath)\n\n const blockId =\n iframeRuntime.extensions[treePath] &&\n iframeRuntime.extensions[treePath].blockId\n\n const template =\n isSitewide || !iframeRuntime.page\n ? '*'\n : iframeRuntime.pages[iframeRuntime.page].blockId\n\n const serverTreePath = isSitewide ? getSitewideTreePath(treePath) : treePath\n\n const isEditing = editor.editTreePath !== null\n\n const [initialEditingState, setInitialEditingState] = useState<EditingState>()\n\n const fetchAndSetData = useCallback(async () => {\n try {\n const { data } = await client.query<\n ListContentData,\n ListContentVariables\n >({\n fetchPolicy: 'network-only',\n query: ListContent,\n variables: {\n bindingId: iframeRuntime.binding?.id,\n blockId,\n pageContext: iframeRuntime.route.pageContext,\n template,\n treePath: serverTreePath,\n },\n })\n\n setInitialEditingState(\n getInitialEditingState({\n data,\n editor,\n iframeRuntime,\n })\n )\n\n updateEditorBlockData({\n data,\n editor,\n id: blockId,\n iframeRuntime,\n intl,\n isSitewide,\n serverTreePath,\n template,\n })\n } catch (e) {\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage({\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.components.open.error',\n }),\n })\n\n editor.editExtensionPoint(null)\n } finally {\n editor.setIsLoading(false)\n }\n }, [\n blockId,\n client,\n editor,\n iframeRuntime,\n intl,\n isSitewide,\n serverTreePath,\n showToast,\n template,\n ])\n\n useEffect(() => {\n if (isEditing && !initialEditingState) {\n fetchAndSetData()\n }\n }, [isEditing, fetchAndSetData, initialEditingState])\n\n useEffect(() => {\n if (!isEditing && initialEditingState) {\n setInitialEditingState(undefined)\n }\n }, [isEditing, initialEditingState])\n\n return initialEditingState\n}\n\nexport default useInitialEditingState\n\n```" } ]
code_admin-pages_a14aea9f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/DeleteContent.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Mutation, MutationFn, MutationResult } from 'react-apollo'\nimport DeleteContent from '../graphql/DeleteContent.graphql'\n\nexport interface DeleteContentData {\n deleteContent: string\n}\n\ninterface DeleteContentVariables {\n pageContext: PageContext\n contentId: string | null\n template: string\n treePath: string\n}\n\nexport type DeleteContentMutationFn = MutationFn<\n DeleteContentData,\n DeleteContentVariables\n>\n\nexport interface MutationRenderProps extends MutationResult<DeleteContentData> {\n deleteContent: DeleteContentMutationFn\n}\n\nclass DeleteContentMutation extends Mutation<\n DeleteContentData,\n DeleteContentVariables\n> {\n public static defaultProps = {\n mutation: DeleteContent,\n }\n}\n\nexport default DeleteContentMutation\n\n```" } ]
code_admin-pages_469db3f6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/SendEventToAudit.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Mutation, MutationFn, MutationResult } from 'react-apollo'\n\nimport SendEventToAudit from '../graphql/SendEventToAudit.graphql'\n\ninterface SendEventToAuditData {\n sendEventToAudit: any\n}\n\ninterface MetaData {\n entityName: string\n entityBeforeAction: string\n entityAfterAction: string\n remoteIpAddress: string\n forwardFromVtexUserAgent: string\n}\n\ninterface SendEventToAuditInput {\n id: string\n date: string\n mainAccountName: string\n accountName: string\n subjectId: string\n application: string\n workspace: string\n operation: string\n meta: MetaData\n}\n\ninterface SendEventToAuditVariables {\n input: SendEventToAuditInput\n}\n\nexport type SendEventToAuditMutationFn = MutationFn<\n SendEventToAuditData,\n SendEventToAuditVariables\n>\n\nexport interface MutationRenderProps\n extends MutationResult<SendEventToAuditData> {\n sendEventToAudit: SendEventToAuditMutationFn\n}\n\nclass SendEventToAuditMutation extends Mutation<\n SendEventToAuditData,\n SendEventToAuditVariables\n> {\n public static defaultProps = {\n mutation: SendEventToAudit,\n }\n}\n\nexport default SendEventToAuditMutation\n\n```" } ]
code_admin-pages_3e201258
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/SaveContent.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Mutation, MutationFn, MutationResult } from 'react-apollo'\nimport SaveContent from '../graphql/SaveContent.graphql'\n\ninterface SaveContentData {\n saveContent: Pick<ExtensionConfiguration, 'contentId'>\n}\n\ninterface SaveContentVariables {\n bindingId?: string\n blockId?: string\n configuration: Omit<ExtensionConfiguration, 'contentId'> & {\n contentId: string | null\n }\n lang: RenderContext['culture']['locale']\n template: string\n treePath: string\n}\n\nexport type SaveContentMutationFn = MutationFn<\n SaveContentData,\n SaveContentVariables\n>\n\nexport interface MutationRenderProps extends MutationResult<SaveContentData> {\n SaveContent: SaveContentMutationFn\n}\n\nclass SaveContentMutation extends Mutation<\n SaveContentData,\n SaveContentVariables\n> {\n public static defaultProps = {\n mutation: SaveContent,\n }\n}\n\nexport default SaveContentMutation\n\n```" } ]
code_admin-pages_6c48ab6a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/queries/ListContent.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { Query, QueryResult } from 'react-apollo'\nimport ListContent from '../graphql/ListContent.graphql'\n\nexport const ListContentGraphqlDocument = ListContent\n\nexport interface ListContentVariables {\n bindingId?: string\n blockId: string\n pageContext: { id: string; type: string }\n template: string\n treePath: string\n}\n\nexport interface ListContentData {\n listContentWithSchema?: {\n content?: ExtensionConfiguration[]\n schemaJSON: string\n }\n}\n\nexport type ListContentQueryResult = QueryResult<\n ListContentData,\n ListContentVariables\n>\n\nclass ListContentQuery extends Query<ListContentData, ListContentVariables> {\n public static defaultProps = {\n fetchPolicy: 'network-only',\n query: ListContent,\n }\n}\n\nexport default ListContentQuery\n\n```" } ]
code_admin-pages_69392b8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\n\nimport { useEditorContext } from '../../EditorContext'\n\nimport StyleEditor from './StyleEditor'\nimport StyleList from './StyleList'\n\nconst SELECTED_STYLE_TAG_ID = 'style_link'\nconst PATH_STYLE_TAG_ID = 'style_path'\nconst SHEET_STYLE_TAG_ID = 'style_sheet'\n\ntype EditingState = Style | undefined\n\nconst setStyleAsset = (window?: Window) => (asset: StyleAssetInfo) => {\n if (!window) {\n return\n }\n\n if (asset.type === 'path') {\n const pathStyleTag = window.document.getElementById(PATH_STYLE_TAG_ID)\n if (pathStyleTag) {\n pathStyleTag.setAttribute('href', asset.value)\n }\n if (!asset.keepSheet) {\n const sheetStyleTag = window.document.getElementById(SHEET_STYLE_TAG_ID)\n if (sheetStyleTag) {\n sheetStyleTag.innerHTML = ''\n }\n }\n if (asset.selected) {\n const selectedStyleTag = window.document.getElementById(\n SELECTED_STYLE_TAG_ID\n )\n if (selectedStyleTag) {\n selectedStyleTag.setAttribute('href', asset.value)\n }\n }\n } else {\n const sheetStyleTag = window.document.getElementById(SHEET_STYLE_TAG_ID)\n if (sheetStyleTag) {\n sheetStyleTag.innerHTML = asset.value\n }\n }\n}\n\nconst createStyleTag = (id: string, window?: Window) => {\n if (!window || window.document.getElementById(id)) {\n return\n }\n const styleTag = window.document.createElement('style')\n styleTag.setAttribute('id', id)\n const tachyonsTag = window.document.getElementById('style_link')\n if (tachyonsTag) {\n tachyonsTag.after(styleTag)\n }\n}\n\nconst removeStyleTag = (id: string, window?: Window) => {\n if (!window) {\n return\n }\n\n const styleTag = window.document.getElementById(id)\n if (styleTag && window.document.head) {\n try {\n window.document.head.removeChild(styleTag)\n } catch (err) {\n console.error(err)\n }\n }\n}\n\nconst Styles = () => {\n const [editing, setEditing] = useState<EditingState>(undefined)\n\n const { iframeWindow } = useEditorContext()\n\n useEffect(() => {\n createStyleTag(PATH_STYLE_TAG_ID, iframeWindow)\n createStyleTag(SHEET_STYLE_TAG_ID, iframeWindow)\n\n return () => {\n removeStyleTag(PATH_STYLE_TAG_ID, iframeWindow)\n removeStyleTag(SHEET_STYLE_TAG_ID, iframeWindow)\n }\n }, [editing, iframeWindow])\n\n return (\n <div\n className=\"h-100 mr5 bg-base ba b--muted-4 br3\"\n style={{\n minWidth: '31rem',\n width: '31rem',\n }}\n >\n {editing ? (\n <StyleEditor\n style={editing}\n stopEditing={() => setEditing(undefined)}\n setStyleAsset={setStyleAsset(iframeWindow)}\n />\n ) : (\n <StyleList\n startEditing={setEditing}\n setStyleAsset={setStyleAsset(iframeWindow)}\n />\n )}\n </div>\n )\n}\n\nexport default Styles\n\n```" } ]
code_admin-pages_a65b9917
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/SaveContent.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation saveContent(\n $bindingId: String\n $blockId: String\n $configuration: ContentConfigurationInput\n $template: String\n $treePath: String\n $lang: String\n) {\n saveContent(\n bindingId: $bindingId\n blockId: $blockId\n configuration: $configuration\n template: $template\n treePath: $treePath\n lang: $lang\n ) {\n # Available fields:\n # condition {\n # allMatches\n # id\n # pageContext {\n # id\n # type\n # }\n # statements {\n # objectJSON\n # subject\n # verb\n # }\n # }\n # contentJSON\n # contentId\n # label\n contentId\n }\n}\n\n```" } ]
code_admin-pages_98eaf1ef
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/SendEventToAudit.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SendEventToAudit($input: SendToAuditInput!) {\n sendEventToAudit(input: $input) {\n id\n mainAccountName\n date\n application\n accountName\n subjectId\n workspace\n operation\n meta {\n entityName\n entityBeforeAction\n entityAfterAction\n remoteIpAddress\n forwardFromVtexUserAgent\n }\n }\n}\n\n```" } ]
code_admin-pages_f2c5a69d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/DeleteContent.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation DeleteContent(\n $template: String\n $treePath: String\n $pageContext: PageContextInput\n $contentId: String\n) {\n deleteContent(\n template: $template\n treePath: $treePath\n pageContext: $pageContext\n contentId: $contentId\n )\n}\n\n```" } ]
code_admin-pages_7116f211
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/ListContent.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery ListContent(\n $bindingId: String\n $blockId: String\n $pageContext: PageContextInput\n $template: String\n $treePath: String\n) {\n listContentWithSchema(\n bindingId: $bindingId\n blockId: $blockId\n pageContext: $pageContext\n template: $template\n treePath: $treePath\n ) {\n content {\n condition {\n allMatches\n id\n pageContext {\n id\n type\n }\n statements {\n objectJSON\n subject\n verb\n }\n }\n contentId\n contentJSON\n label\n origin\n }\n schemaJSON\n }\n}\n\n```" } ]
code_admin-pages_2d827db9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditableText/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { IconEdit } from 'vtex.styleguide'\n\nimport styles from './styles.css'\n\ninterface Props {\n baseClassName: string\n onChange?: React.ChangeEventHandler<HTMLInputElement>\n onBlur?: React.FocusEventHandler<HTMLInputElement>\n onKeyPress?: React.KeyboardEventHandler<HTMLInputElement>\n disabled?: boolean\n placeholder?: string\n value?: string\n}\n\nconst EditableText: React.FC<Props> = ({\n baseClassName,\n onChange,\n onBlur,\n onKeyPress,\n disabled,\n placeholder,\n value,\n}) => {\n const [isEditing, setIsEditing] = React.useState(false)\n\n const inputRef = React.useRef<HTMLInputElement | null>(null)\n\n const startEditing = React.useCallback(() => {\n inputRef && inputRef.current && inputRef.current.focus()\n }, [inputRef])\n\n const handleOnFocus = React.useCallback(() => {\n setIsEditing(true)\n }, [setIsEditing])\n\n const handleOnBlur = React.useCallback(\n e => {\n setIsEditing(false)\n onBlur && onBlur(e)\n },\n [setIsEditing, onBlur]\n )\n\n return (\n <div\n role=\"presentation\"\n className={`flex items-baseline bb b--light-gray ${\n isEditing ? 'hover-b--action-primary' : ''\n } pb2 ${isEditing ? 'b--action-primary' : ''} ${\n styles.editableTextInputWrapper\n }`}\n style={{ cursor: 'text' }}\n onClick={startEditing}\n >\n <input\n className={`flex-grow-1 w-100 truncate outline-0 c-on-base bn font-body input-reset ${baseClassName} ${styles.input}`}\n onChange={onChange}\n onFocus={handleOnFocus}\n onBlur={handleOnBlur}\n disabled={disabled}\n onKeyPress={onKeyPress}\n placeholder={placeholder || ''}\n ref={inputRef}\n type=\"text\"\n value={value || ''}\n />\n <span\n className={`${styles.editableTextInputWrapper__input} ${\n isEditing ? 'dn' : ''\n }`}\n >\n <IconEdit />\n </span>\n </div>\n )\n}\n\nexport default EditableText\n\n```" } ]
code_admin-pages_281d0698
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/EditableText/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.input::placeholder {\n color: #979899;\n font-style: normal;\n font-weight: 400;\n}\n\n.editableTextInputWrapper .editableTextInputWrapper__input {\n opacity: 0;\n}\n\n.editableTextInputWrapper:hover .editableTextInputWrapper__input {\n opacity: 1;\n}\n\n```" } ]
code_admin-pages_babb82b1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Topbar/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ToastConsumer } from 'vtex.styleguide'\n\nimport BlockPicker from './BlockPicker'\nimport ContextSelectors from './ContextSelectors'\nimport DeviceSwitcher from './DeviceSwitcher'\nimport SidebarVisibilityToggle from './SidebarVisibilityToggle'\nimport UrlInput from './UrlInput'\n\nimport styles from '../EditorContainer.css'\n\ninterface Props {\n iframeRuntime: RenderContext\n}\n\nconst Topbar: React.FunctionComponent<Props> = ({ iframeRuntime }) => (\n <div\n className={`ph5 pv7 f6 ${styles['h-3em']} w-100 bg-muted-5 flex justify-center items-center`}\n >\n <ToastConsumer>\n {({ showToast }) => (\n <ContextSelectors iframeRuntime={iframeRuntime} showToast={showToast} />\n )}\n </ToastConsumer>\n\n <div className=\"ml6 flex flex-grow-1\">\n <UrlInput />\n </div>\n\n <div className=\"ml6\">\n <BlockPicker />\n </div>\n\n <div className=\"ml8\">\n <DeviceSwitcher device={iframeRuntime.device} />\n </div>\n\n <div className=\"ml6\">\n <SidebarVisibilityToggle />\n </div>\n </div>\n)\n\nexport default Topbar\n\n```" } ]
code_admin-pages_4fdd8e84
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Topbar/BlockPicker.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Tooltip } from 'vtex.styleguide'\n\nimport { useEditorContext } from '../../EditorContext'\nimport { useHover } from './hooks'\nimport IconPicker from './icons/IconPicker'\n\nconst BlockPicker: React.FC<InjectedIntlProps> = ({ intl }) => {\n const editor = useEditorContext()\n\n const { handleMouseEnter, handleMouseLeave, hover } = useHover()\n\n const handleEditModeToggle = editor.toggleEditMode\n\n const handleKeyPress = useKeydownFromClick(handleEditModeToggle)\n\n return (\n <Tooltip\n label={intl.formatMessage({\n defaultMessage: 'Select a block',\n id: 'admin/pages.editor.topbar.button.block-picker.tooltip',\n })}\n position=\"bottom\"\n >\n <button\n style={editor.mode === 'disabled' ? { cursor: 'wait' } : {}}\n className={`w2 h2 bg-white br2 b--transparent outline-0 pointer flex justify-center items-center ${\n editor.editMode || (hover && editor.mode !== 'disabled')\n ? 'c-action-primary'\n : 'c-on-disabled'\n }`}\n onClick={handleEditModeToggle}\n onKeyPress={handleKeyPress}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n disabled={editor.mode === 'disabled'}\n >\n <IconPicker />\n </button>\n </Tooltip>\n )\n}\n\nexport default injectIntl(BlockPicker)\n\n```" } ]
code_admin-pages_236865b7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Topbar/SidebarVisibilityToggle.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 from 'react'\nimport { InjectedIntlProps, injectIntl } from 'react-intl'\nimport { Tooltip } from 'vtex.styleguide'\n\nimport { useEditorContext } from '../../EditorContext'\n\nimport { useHover } from './hooks'\nimport IconView from './icons/IconView'\n\nconst SidebarVisibilityToggle: React.FC<InjectedIntlProps> = ({ intl }) => {\n const editor = useEditorContext()\n\n const { handleMouseEnter, handleMouseLeave, hover } = useHover()\n\n const handleSidebarVisibilityToggle = editor.toggleSidebarVisibility\n\n const handleSidebarVisibilityToggleKeyDown = createKeydownFromClick(\n handleSidebarVisibilityToggle\n )\n\n return (\n <Tooltip\n label={intl.formatMessage({\n defaultMessage: 'Preview',\n id: 'admin/pages.editor.topbar.button.preview.tooltip',\n })}\n position=\"bottom\"\n >\n <button\n className={`w2 h2 bg-white br2 b--transparent outline-0 pointer flex justify-center items-center ${\n editor.isSidebarVisible && !hover\n ? 'c-on-disabled'\n : 'c-action-primary'\n }`}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onClick={handleSidebarVisibilityToggle}\n onKeyDown={handleSidebarVisibilityToggleKeyDown}\n >\n <IconView />\n </button>\n </Tooltip>\n )\n}\n\nexport default injectIntl(SidebarVisibilityToggle)\n\n```" } ]
code_admin-pages_e3137372
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Topbar/UrlInput.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 { useEditorContext } from '../../EditorContext'\n\nconst UrlInput = () => {\n const [urlInputDisabled, setUrlInputDisabled] = React.useState(false)\n\n const editor = useEditorContext()\n\n const resolveUrlPath = (pathname: string, searchQueries: string) => {\n const searchParams = new URLSearchParams(searchQueries)\n const SEARCH_QUERIES_TO_HIDE = [\n '__siteEditor',\n '__bindingAddress',\n '__locale',\n ]\n\n SEARCH_QUERIES_TO_HIDE.forEach(query => {\n searchParams.delete(query)\n })\n\n if (searchParams.toString().length) {\n return pathname + decodeURIComponent(`?${searchParams.toString()}`)\n }\n\n return pathname\n }\n\n const urlPath = editor.iframeWindow\n ? resolveUrlPath(\n editor.iframeWindow.location.pathname,\n editor.iframeWindow.location.search\n )\n : ''\n\n const [url, setUrl] = React.useState(urlPath)\n\n React.useEffect(() => {\n setUrl(urlPath)\n }, [urlPath])\n\n const onEnter = (\n event: React.KeyboardEvent<HTMLInputElement>,\n callback: () => void\n ) => event.key === 'Enter' && callback()\n\n const handleNavigateToUrl = () => {\n if (url === urlPath) {\n return\n }\n\n setUrlInputDisabled(true)\n\n editor.onChangeIframeUrl(url)\n }\n\n const handleUrlKeyPress = (\n e: React.KeyboardEvent<HTMLInputElement>\n ): void => {\n onEnter(e, handleNavigateToUrl)\n }\n\n const handleChangeUrl = (e: React.ChangeEvent<HTMLInputElement>) => {\n const targetUrl = e.target.value\n if (targetUrl === url) {\n return\n }\n setUrl(targetUrl)\n }\n\n return (\n <div className=\"w-100 h2 pl5 bg-white ba bw1 br2 b--muted-4 hover-b--muted-3 flex items-center\">\n <FormattedMessage\n defaultMessage=\"URL\"\n id=\"admin/pages.editor.container.editpath.label\"\n >\n {message => (\n <label\n className=\"c-muted-2\"\n htmlFor=\"topbar-url-input\"\n style={{ userSelect: 'none' }}\n >\n {message}\n </label>\n )}\n </FormattedMessage>\n\n <input\n className=\"w-100 pl3 bn outline-0\"\n disabled={urlInputDisabled}\n id=\"topbar-url-input\"\n onBlur={handleNavigateToUrl}\n onChange={handleChangeUrl}\n onKeyPress={handleUrlKeyPress}\n value={url}\n />\n </div>\n )\n}\n\nexport default UrlInput\n\n```" } ]
code_admin-pages_b4612cdb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Topbar/hooks.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useCallback, useState } from 'react'\n\nexport const useHover = () => {\n const [hover, setHover] = useState(false)\n\n const handleMouseEnter = useCallback(() => {\n setHover(true)\n }, [])\n\n const handleMouseLeave = useCallback(() => {\n setHover(false)\n }, [])\n\n return { handleMouseEnter, handleMouseLeave, hover }\n}\n\n```" } ]
code_admin-pages_a48ddf64
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { injectIntl } from 'react-intl'\nimport { CSSTransition } from 'react-transition-group'\n\nimport { ANIMATION_TIMEOUT } from '../../../consts'\nimport { useEditorContext } from '../../../EditorContext'\nimport DeleteContentMutation from '../../mutations/DeleteContent'\nimport Transitions from '../Transitions'\nimport { EditingState, FormDataContainer } from '../typings'\nimport BlockConfigurationEditor from './BlockConfigurationEditor'\nimport BlockConfigurationList from './BlockConfigurationList'\nimport { useFormHandlers } from './hooks'\nimport { UseFormHandlersParams } from './typings'\nimport { getActiveContentId } from '../../../../utils/components/index'\n\ntype Props = Omit<UseFormHandlersParams, 'setState' | 'state'> & {\n initialEditingState?: EditingState\n}\n\nexport enum ConfigurationStatus {\n ACTIVE = 'ACTIVE',\n INACTIVE = 'INACTIVE',\n SCHEDULED = 'SCHEDULED',\n}\n\nexport interface State extends EditingState {\n mode: 'editingActive' | 'editingInactive' | 'list'\n prevMode?: State['mode']\n status?: ConfigurationStatus\n}\n\nconst BlockEditor = ({\n iframeRuntime,\n initialEditingState,\n intl,\n saveContent,\n sendEventToAudit,\n showToast,\n}: Props) => {\n const [state, setState] = React.useReducer<\n React.Reducer<State, Partial<State>>\n >(\n (prevState, nextState) => ({\n ...prevState,\n ...nextState,\n prevMode:\n nextState.mode && nextState.mode !== prevState.mode\n ? prevState.mode\n : prevState.prevMode,\n }),\n { ...initialEditingState, mode: 'editingActive' }\n )\n\n const isFirstState = !state.prevMode\n\n const stateTransitions = React.useMemo(\n () => ({\n editingActiveToList:\n state.prevMode === 'editingActive' && state.mode === 'list',\n editingToList:\n state.prevMode &&\n state.prevMode.startsWith('editing') &&\n state.mode === 'list',\n listToEditingActive:\n state.prevMode === 'list' && state.mode === 'editingActive',\n listToEditing:\n state.prevMode === 'list' && state.mode.startsWith('editing'),\n }),\n [state.mode, state.prevMode]\n )\n\n const editor = useEditorContext()\n\n const activeContentId = getActiveContentId({\n extensions: iframeRuntime.extensions,\n treePath: editor.editTreePath,\n })\n\n const currentContent = editor.blockData?.configurations?.find(\n config => state.contentId === config.contentId\n )\n\n const statusFromRuntime =\n currentContent?.contentId === activeContentId\n ? ConfigurationStatus.ACTIVE\n : ConfigurationStatus.INACTIVE\n\n const {\n handleStatusChange,\n handleConditionChange,\n handleConfigurationCreate,\n handleConfigurationOpen,\n handleConfigurationActivate,\n handleFormBack,\n handleFormChange,\n handleFormSave,\n handleLabelChange,\n handleListClose,\n handleListOpen,\n } = useFormHandlers({\n iframeRuntime,\n intl,\n saveContent,\n sendEventToAudit,\n setState,\n showToast,\n state,\n statusFromRuntime,\n })\n\n return (\n <>\n <CSSTransition\n in={isFirstState || stateTransitions.listToEditing}\n mountOnEnter\n timeout={ANIMATION_TIMEOUT}\n unmountOnExit\n >\n <BlockConfigurationEditor\n state={state}\n statusFromRuntime={statusFromRuntime}\n condition={\n (state\n ? state.condition\n : {}) as ExtensionConfiguration['condition']\n }\n isNew={!currentContent}\n contentSchema={editor.blockData.contentSchema}\n editingContentId={state.contentId}\n data={state.formData as FormDataContainer}\n iframeRuntime={iframeRuntime}\n isSitewide={editor.blockData.isSitewide}\n label={state.label}\n onBack={handleFormBack}\n onChange={handleFormChange}\n onConditionChange={handleConditionChange}\n onStatusChange={handleStatusChange}\n onLabelChange={handleLabelChange}\n onListOpen={handleListOpen}\n onSave={handleFormSave}\n showToast={showToast}\n title={editor.blockData.title}\n />\n </CSSTransition>\n\n <Transitions.Exit condition={stateTransitions.listToEditing} to=\"right\">\n <Transitions.Enter\n condition={stateTransitions.editingToList}\n from=\"right\"\n >\n <DeleteContentMutation>\n {deleteContent => (\n <BlockConfigurationList\n deleteContent={deleteContent}\n sendEventToAudit={sendEventToAudit}\n onConfigurationActivate={handleConfigurationActivate}\n editingContentId={state.contentId}\n iframeRuntime={iframeRuntime}\n onConfigurationCreate={handleConfigurationCreate}\n onConfigurationOpen={handleConfigurationOpen}\n onListClose={handleListClose}\n showToast={showToast}\n />\n )}\n </DeleteContentMutation>\n </Transitions.Enter>\n </Transitions.Exit>\n </>\n )\n}\n\nexport default injectIntl(BlockEditor)\n\n```" } ]
code_admin-pages_63cd2846
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/EditorHeader.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { injectIntl, InjectedIntlProps } from 'react-intl'\nimport { IconArrowBack, IconClose } from 'vtex.styleguide'\n\ninterface CustomProps {\n isTitleEditable?: boolean\n onBack?: () => void\n onListClose?: () => void\n onListOpen?: () => void\n onTitleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void\n title?: string\n}\n\ntype Props = CustomProps & InjectedIntlProps\n\nconst noOp = () => {\n return\n}\n\nconst EditorHeader: React.FC<Props> = ({\n intl,\n onBack,\n onListClose,\n onListOpen,\n title,\n}) => {\n const handleBackKeyDown = useKeydownFromClick(onBack || noOp)\n const handleCloseListKeyDown = useKeydownFromClick(onListClose || noOp)\n const handleOpenListKeyDown = useKeydownFromClick(onListOpen || noOp)\n\n return (\n <div className=\"ph5 pt4\">\n <div className=\"w-100 flex justify-between\">\n <div\n className=\"flex items-center c-action-primary hover-c-action-primary pointer\"\n role=\"button\"\n tabIndex={0}\n onKeyDown={handleBackKeyDown}\n onClick={onBack}\n >\n {onBack && (\n <React.Fragment>\n <span className=\"outline-0\">\n <IconArrowBack />\n </span>\n <span className=\"ml3 fw5 f7 ttu\">\n {intl.formatMessage({\n defaultMessage: 'Back',\n id: 'admin/pages.editor.component-list.back',\n })}\n </span>\n </React.Fragment>\n )}\n </div>\n <div>\n {onListClose && (\n <span\n className=\"pointer outline-0 c-on-base hover-c-action-primary\"\n onClick={onListClose}\n onKeyDown={handleCloseListKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <IconClose />\n </span>\n )}\n\n {onListOpen && (\n <span\n className=\"pointer outline-0 c-action-primary hover-c-action-primary ttu f7 fw5\"\n role=\"button\"\n tabIndex={0}\n onClick={onListOpen}\n onKeyDown={handleOpenListKeyDown}\n >\n {intl.formatMessage({\n defaultMessage: 'Configurations',\n id: 'admin/pages.editor.component-list.title',\n })}\n </span>\n )}\n </div>\n </div>\n\n <div className=\"w-100 flex flex-grow-1 justify-between items-center\">\n <h4 className=\"w-100 ma0 lh-copy f4 fw4 near-black ba b--transparent\">\n {title}\n </h4>\n </div>\n </div>\n )\n}\n\nexport default injectIntl(EditorHeader)\n\n```" } ]
code_admin-pages_8bb2fe54
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/utils.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getIsDefaultContent } from './utils'\n\ndescribe('getIsDefaultContent', () => {\n it('should return true when origin is declared (comes from app)', () => {\n expect(getIsDefaultContent({ origin: 'comes from block' })).toBe(true)\n })\n\n it('should return false when origin is null (declared by user)', () => {\n expect(getIsDefaultContent({ origin: null })).toBe(false)\n })\n})\n\n```" } ]
code_admin-pages_25f2f6a5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport throttle from 'lodash/throttle'\n\nimport { updateExtensionFromForm } from '../../../../utils/components'\nimport { NEW_CONFIGURATION_ID } from '../consts'\nimport { getDefaultCondition } from '../utils'\nimport { GetDefaultConfiguration, GetConfigurationType } from './typings'\n\nexport const getDefaultConfiguration: GetDefaultConfiguration = ({\n iframeRuntime,\n isSitewide,\n}) => ({\n condition: getDefaultCondition({ iframeRuntime, isSitewide }),\n contentId: NEW_CONFIGURATION_ID,\n contentJSON: '{}',\n label: null,\n origin: null,\n})\n\nexport const getIsDefaultContent: (\n configuration: Pick<ExtensionConfiguration, 'origin'>\n) => boolean = configuration => configuration.origin !== null\n\nexport const omitUndefined = (obj: Extension['content']) =>\n Object.entries(obj).reduce((acc, [currKey, currValue]) => {\n if (typeof currValue === 'undefined') {\n return acc\n }\n\n return { ...acc, [currKey]: currValue }\n }, {})\n\nexport const getConfigurationType: GetConfigurationType = ({\n configuration,\n activeContentId,\n}) => {\n if (getIsDefaultContent(configuration)) {\n return 'app'\n }\n\n if (activeContentId === configuration.contentId) {\n return 'active'\n }\n\n return 'inactive'\n}\n\nexport const throttledUpdateExtensionFromForm = throttle(\n data => updateExtensionFromForm(data),\n 200\n)\n\n```" } ]
code_admin-pages_bb6c98b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MutationFn } from 'react-apollo'\nimport { InjectedIntl } from 'react-intl'\nimport { FormProps } from 'react-jsonschema-form'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport { GetDefaultConditionParams } from '../typings'\nimport { ConfigurationStatus, State as FormState } from './index'\nimport { SendEventToAuditMutationFn } from '../../mutations/SendEventToAudit'\n\nexport type GetDefaultConfiguration = (\n params: GetDefaultConditionParams\n) => ExtensionConfiguration\n\nexport interface GetDefaultConditionParams {\n iframeRuntime: RenderContext\n isSitewide: boolean\n}\n\ninterface GetConfigurationTypeParams {\n configuration: ExtensionConfiguration\n activeContentId: ExtensionConfiguration['contentId']\n}\n\ntype ConfigurationType = 'active' | 'inactive' | 'app'\n\ntype GetConfigurationType = (\n params: GetConfigurationTypeParams\n) => ConfigurationType\n\nexport interface UseFormHandlersParams {\n iframeRuntime: RenderContext\n intl: InjectedIntl\n saveContent: MutationFn<SaveContentData, SaveContentVariables>\n sendEventToAudit: SendEventToAuditMutationFn\n setState: React.Dispatch<Partial<FormState>>\n showToast: ToastConsumerFunctions['showToast']\n state: FormState\n statusFromRuntime?: ConfigurationStatus\n}\n\nexport type UseFormHandlers = (\n params: UseFormHandlersParams\n) => {\n handleStatusChange: () => void\n handleConfigurationActivate: (\n configuration: ExtensionConfiguration\n ) => Promise<void>\n handleConditionChange: (changes: Partial<FormState['condition']>) => void\n handleConfigurationCreate: () => ReturnType<\n ReturnType<UseFormHandlers>['handleInactiveConfigurationOpen']\n >\n handleConfigurationOpen: (\n configuration: ExtensionConfiguration\n ) => Promise<void>\n handleFormBack: () => void\n handleFormChange: FormProps<FormDataContainer>['onChange']\n handleFormSave: () => Promise<void>\n handleLabelChange: React.ChangeEventHandler<HTMLInputElement>\n handleListClose: () => void\n handleListOpen: () => void\n}\n\n```" } ]
code_admin-pages_3befeb08
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/hooks.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { equals, path } from 'ramda'\nimport { useCallback } from 'react'\nimport { defineMessages } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport { ConfigurationStatus } from '.'\nimport {\n getActiveContentId,\n getSchemaPropsOrContent,\n updateExtensionFromForm,\n} from '../../../../utils/components'\nimport { useEditorContext } from '../../../EditorContext'\nimport { NEW_CONFIGURATION_ID } from '../consts'\nimport { useFormMetaContext } from '../FormMetaContext'\nimport { useModalContext } from '../ModalContext'\nimport { getFormData } from '../utils'\nimport { UseFormHandlers } from './typings'\nimport {\n getDefaultConfiguration,\n omitUndefined,\n throttledUpdateExtensionFromForm,\n} from './utils'\nimport { createEventObject } from '../../../../utils/auditEvents'\n\nconst messages = defineMessages({\n cancel: {\n defaultMessage: 'Cancel',\n id: 'admin/pages.editor.components.modal.form.button.cancel',\n },\n discard: {\n defaultMessage: 'Discard',\n id: 'admin/pages.editor.components.modal.back.button.discard',\n },\n save: {\n defaultMessage: 'Save',\n id: 'admin/pages.editor.components.modal.back.button.save',\n },\n saveError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.components.toast.save.error',\n },\n saveSuccess: {\n defaultMessage: 'Content saved successfully.',\n id: 'admin/pages.editor.components.toast.save.success',\n },\n unsavedBackText: {\n defaultMessage:\n 'Your unsaved changes will be lost. Do you want to save them?',\n id: 'admin/pages.editor.components.modal.back.text',\n },\n unsavedListText: {\n defaultMessage:\n 'You have unsaved changes. Are you sure you want to continue and discard your modifications? This action cannot be undone.',\n id: 'admin/pages.editor.components.modal.form.text',\n },\n unsavedListTitle: {\n defaultMessage: 'Unsaved changes',\n id: 'admin/pages.editor.components.modal.form.title',\n },\n})\n\nexport const useFormHandlers: UseFormHandlers = ({\n iframeRuntime,\n intl,\n saveContent,\n sendEventToAudit,\n setState,\n showToast,\n state,\n statusFromRuntime,\n}) => {\n const editor = useEditorContext()\n const formMeta = useFormMetaContext()\n const modal = useModalContext()\n const { account, workspace } = useRuntime()\n\n const handleStatusChange = () => {\n const status = state.status ?? statusFromRuntime\n\n setState({\n ...state,\n status:\n status === ConfigurationStatus.ACTIVE\n ? ConfigurationStatus.INACTIVE\n : ConfigurationStatus.ACTIVE,\n })\n\n if (!formMeta.getWasModified()) {\n formMeta.setWasModified(true)\n }\n }\n\n const handleConditionChange = useCallback(\n (changes: Partial<typeof state['condition']>) => {\n setState({\n condition: {\n ...(state.condition as ExtensionConfiguration['condition']),\n ...changes,\n },\n })\n\n if (!formMeta.getWasModified()) {\n formMeta.setWasModified(true)\n }\n },\n [formMeta, setState, state]\n )\n\n const handleFormChange = useCallback(\n event => {\n if (\n state.formData &&\n !formMeta.getWasModified() &&\n !equals(omitUndefined(state.formData), omitUndefined(event.formData))\n ) {\n formMeta.setWasModified(true)\n }\n\n if (event.formData) {\n setState({ formData: event.formData })\n\n throttledUpdateExtensionFromForm({\n data: event.formData,\n isContent: true,\n runtime: iframeRuntime,\n treePath: editor.editTreePath,\n })\n }\n },\n [editor.editTreePath, formMeta, iframeRuntime, setState, state]\n )\n\n const handleFormClose = useCallback(async () => {\n if (!editor.getIsLoading()) {\n editor.setIsLoading(true)\n }\n\n await iframeRuntime.updateRuntime()\n\n editor.editExtensionPoint(null)\n\n editor.setIsLoading(false)\n }, [editor, iframeRuntime])\n\n const handleFormSave = useCallback(async () => {\n if (editor.getIsLoading()) {\n return\n }\n\n const content = getSchemaPropsOrContent({\n propsOrContent: state.formData,\n schema: editor.blockData.componentSchema,\n })\n const contentId =\n state.contentId === NEW_CONFIGURATION_ID ? null : state.contentId\n const contentStatus = state.status ?? statusFromRuntime\n\n const hasOnlyEndDate = state.condition?.statements?.some(\n statement => statement.verb === 'to'\n )\n const isScheduled = state.condition?.statements.length\n const isActive = contentStatus === ConfigurationStatus.ACTIVE\n const isDefault = state.origin\n\n let newStatus\n\n if (isActive || hasOnlyEndDate || isDefault) {\n newStatus = ConfigurationStatus.ACTIVE\n } else if (isScheduled) {\n newStatus = ConfigurationStatus.SCHEDULED\n } else {\n newStatus = ConfigurationStatus.INACTIVE\n }\n\n const newConfiguration = {\n status: newStatus,\n condition: state.condition,\n contentId,\n contentJSON: JSON.stringify(content),\n label: state.label || null,\n origin: isDefault || null,\n }\n\n const blockId = path<string>(\n ['extensions', editor.editTreePath || '', 'blockId'],\n iframeRuntime\n )\n\n let error: Error | undefined\n\n try {\n editor.setIsLoading(true)\n\n await saveContent({\n variables: {\n bindingId: iframeRuntime.binding?.id,\n blockId,\n configuration: newConfiguration,\n lang: iframeRuntime.culture.locale,\n template: editor.blockData.template,\n treePath: editor.blockData.serverTreePath,\n },\n })\n\n formMeta.setWasModified(false)\n\n if (newConfiguration.status === ConfigurationStatus.SCHEDULED) {\n const event = createEventObject(\n 'Schedule change',\n 'content',\n account,\n workspace,\n contentId\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n }\n\n const event = createEventObject(\n 'Edit content block',\n 'content',\n account,\n workspace,\n contentId\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n\n handleFormClose()\n } catch (err) {\n console.error(err)\n\n error = err\n\n editor.setIsLoading(false)\n } finally {\n if (modal.getIsOpen()) {\n modal.close()\n }\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(\n error ? messages.saveError : messages.saveSuccess\n ),\n })\n }\n }, [\n editor,\n state.formData,\n state.contentId,\n state.status,\n state.condition,\n state.origin,\n state.label,\n statusFromRuntime,\n iframeRuntime,\n saveContent,\n sendEventToAudit,\n formMeta,\n handleFormClose,\n modal,\n showToast,\n intl,\n ])\n\n const handleFormBack = useCallback(() => {\n if (formMeta.getWasModified()) {\n modal.open({\n actionHandler: async () => {\n await handleFormSave()\n },\n cancelHandler: () => {\n if (state.content) {\n updateExtensionFromForm({\n data: state.content,\n isContent: true,\n runtime: iframeRuntime,\n treePath: editor.editTreePath,\n })\n }\n\n formMeta.setWasModified(false, () => {\n handleFormBack()\n })\n },\n textButtonAction: intl.formatMessage(messages.save),\n textButtonCancel: intl.formatMessage(messages.discard),\n textMessage: intl.formatMessage(messages.unsavedBackText),\n title: intl.formatMessage(messages.unsavedListTitle),\n })\n } else {\n if (modal.getIsOpen()) {\n modal.close()\n }\n\n handleFormClose()\n }\n }, [\n editor,\n formMeta,\n handleFormClose,\n handleFormSave,\n iframeRuntime,\n intl,\n modal,\n state.content,\n ])\n\n const handleConfigurationActivate = async (\n configuration: ExtensionConfiguration\n ) => {\n const blockId = path<string>(\n ['extensions', editor.editTreePath || '', 'blockId'],\n iframeRuntime\n )\n\n let error: Error | undefined\n\n try {\n editor.setIsLoading(true)\n\n await saveContent({\n variables: {\n bindingId: iframeRuntime.binding?.id,\n blockId,\n configuration: {\n ...configuration,\n condition: {\n ...configuration.condition,\n statements: [],\n },\n status: ConfigurationStatus.ACTIVE,\n },\n lang: iframeRuntime.culture.locale,\n template: editor.blockData.template,\n treePath: editor.blockData.serverTreePath,\n },\n })\n\n const event = createEventObject(\n 'Activate content block version',\n 'content',\n account,\n workspace,\n blockId\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n } catch (err) {\n console.error(err)\n\n error = err\n\n editor.setIsLoading(false)\n } finally {\n if (modal.getIsOpen()) {\n modal.close()\n }\n\n await iframeRuntime.updateRuntime()\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(\n error ? messages.saveError : messages.saveSuccess\n ),\n })\n\n editor.setIsLoading(false)\n }\n }\n\n const handleConfigurationOpen = useCallback(\n async (configuration: ExtensionConfiguration) => {\n if (!editor.editTreePath) {\n return\n }\n\n if (\n configuration.contentId &&\n state.contentId === configuration.contentId\n ) {\n setState({\n mode: state.prevMode,\n })\n } else {\n const baseContent =\n configuration.contentId !== NEW_CONFIGURATION_ID\n ? (JSON.parse(configuration.contentJSON) as Extension['content'])\n : {}\n\n const formData = getFormData({\n componentImplementation: editor.blockData.componentImplementation,\n content: baseContent,\n contentSchema: editor.blockData.contentSchema,\n iframeRuntime,\n })\n\n await iframeRuntime.updateExtension(editor.editTreePath, {\n ...iframeRuntime.extensions[editor.editTreePath],\n content: formData,\n })\n\n const activeContentId = getActiveContentId({\n extensions: iframeRuntime.extensions,\n treePath: editor.editTreePath,\n })\n\n const newMode =\n configuration.contentId && configuration.contentId === activeContentId\n ? 'editingActive'\n : 'editingInactive'\n\n setState({\n condition: configuration.condition,\n content: baseContent,\n contentId: configuration.contentId,\n formData,\n label: configuration.label,\n mode: newMode,\n origin: configuration.origin,\n })\n }\n },\n [\n editor.blockData.componentImplementation,\n editor.blockData.contentSchema,\n editor.editTreePath,\n iframeRuntime,\n setState,\n state.contentId,\n state.prevMode,\n ]\n )\n\n const handleConfigurationCreate = useCallback(\n () =>\n handleConfigurationOpen(\n getDefaultConfiguration({\n iframeRuntime,\n isSitewide: editor.blockData.isSitewide || false,\n })\n ),\n [editor.blockData.isSitewide, handleConfigurationOpen, iframeRuntime]\n )\n\n const handleLabelChange = useCallback(\n (event: React.ChangeEvent<HTMLInputElement>) => {\n setState({ label: event.target.value })\n\n if (!formMeta.getWasModified()) {\n formMeta.setWasModified(true)\n }\n },\n [formMeta, setState]\n )\n\n const handleListClose = useCallback(() => {\n setState({ mode: state.prevMode })\n }, [setState, state.prevMode])\n\n const handleListOpen = useCallback(() => {\n if (formMeta.getWasModified()) {\n modal.open({\n actionHandler: async () => {\n editor.setIsLoading(true)\n\n if (state.content) {\n setState({\n formData: getFormData({\n componentImplementation:\n editor.blockData.componentImplementation,\n content: state.content,\n contentSchema: editor.blockData.contentSchema,\n iframeRuntime,\n }),\n })\n }\n\n await iframeRuntime.updateRuntime()\n\n editor.setIsLoading(false)\n\n formMeta.setWasModified(false, () => {\n handleListOpen()\n })\n },\n cancelHandler: () => {\n modal.close()\n },\n isActionDanger: true,\n textButtonAction: intl.formatMessage(messages.discard),\n textButtonCancel: intl.formatMessage(messages.cancel),\n textMessage: intl.formatMessage(messages.unsavedListText),\n title: intl.formatMessage(messages.unsavedListTitle),\n })\n } else {\n if (modal.getIsOpen()) {\n modal.close()\n }\n\n setState({ mode: 'list' })\n }\n }, [editor, formMeta, iframeRuntime, intl, modal, setState, state.content])\n\n return {\n handleStatusChange,\n handleConditionChange,\n handleConfigurationCreate,\n handleConfigurationOpen,\n handleConfigurationActivate,\n handleFormBack,\n handleFormChange,\n handleFormSave,\n handleLabelChange,\n handleListClose,\n handleListOpen,\n }\n}\n\n```" } ]
code_admin-pages_7bc8a623
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport Enter from './Enter'\nimport Exit from './Exit'\n\nconst Transitions = {\n Enter,\n Exit,\n}\n\nexport default Transitions\n\n```" } ]
code_admin-pages_022f09a7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Transition } from 'react-transition-group'\n\ntype Direction = 'left' | 'right'\n\ntype TransitionProps = React.ComponentPropsWithoutRef<typeof Transition>\n\ninterface Props {\n children: React.ReactElement\n condition: TransitionProps['in']\n}\n\nexport interface EnterProps extends Props {\n from: Direction\n}\n\nexport interface ExitProps extends Props {\n to: Direction\n}\n\n```" } ]
code_admin-pages_cc392b3e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/consts.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ANIMATION_TIMEOUT } from '../../../consts'\n\nexport const COMMON_PROPS = {\n timeout: ANIMATION_TIMEOUT,\n}\n\n```" } ]
code_admin-pages_738d679a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { InjectedIntlProps } from 'react-intl'\nimport { FormattedMessage, injectIntl } from 'react-intl'\n\nimport { getIframeRenderComponents } from '../../../../utils/components'\nimport { useEditorContext } from '../../../EditorContext'\nimport {\n getComponents,\n getNormalizedBlocks,\n getTitleByTreePathMap,\n} from './utils'\nimport BlockList from './BlockList'\nimport styles from '../../EditorContainer.css'\n\ninterface Props {\n highlightHandler: (treePath: string | null) => void\n iframeRuntime: RenderContextProps['runtime']\n updateHighlightTitleByTreePath: (\n titleByTreePath?: Record<string, { title?: string; isEditable: boolean }>\n ) => void\n}\n\nconst BlockSelector: React.FunctionComponent<Props & InjectedIntlProps> = ({\n highlightHandler,\n iframeRuntime,\n intl,\n updateHighlightTitleByTreePath,\n}) => {\n const [blocks, setBlocks] = React.useState(() =>\n getNormalizedBlocks({\n extensions: iframeRuntime.extensions,\n page: iframeRuntime.page,\n })\n )\n\n const editor = useEditorContext()\n\n const path = React.useRef('')\n const binding = React.useRef('')\n\n React.useEffect(() => {\n if (\n path.current === iframeRuntime.route.path &&\n binding.current === iframeRuntime.binding?.id\n ) {\n return\n }\n\n const nextComponents = getComponents(\n iframeRuntime.extensions,\n getIframeRenderComponents(),\n iframeRuntime.page\n )\n\n const nextBlocks = getNormalizedBlocks(nextComponents)\n\n setBlocks(nextBlocks)\n\n updateHighlightTitleByTreePath(getTitleByTreePathMap(nextComponents, intl))\n\n editor.setIsLoading(false)\n path.current = iframeRuntime.route.path\n binding.current = iframeRuntime.binding.id\n }, [\n editor,\n iframeRuntime.extensions,\n iframeRuntime.page,\n iframeRuntime.route.path,\n iframeRuntime.binding?.id,\n intl,\n updateHighlightTitleByTreePath,\n ])\n\n const handleMouseEnter = React.useCallback(\n (event: React.MouseEvent<HTMLDivElement | HTMLLIElement>) => {\n const treePath = event.currentTarget.getAttribute('data-tree-path')\n\n highlightHandler(treePath)\n },\n [highlightHandler]\n )\n\n const handleMouseLeave = React.useCallback(() => {\n highlightHandler(null)\n }, [highlightHandler])\n\n return (\n <div className={`w-100 absolute ${styles['h-3em']}`}>\n <h3 className=\"fw5 ph5 pv4 ma0 lh-copy f5 near-black\">\n <FormattedMessage id=\"admin/pages.editor.components.title\" />\n </h3>\n\n <div className=\"bb bw1 b--light-silver\" />\n\n <BlockList\n blocks={blocks}\n highlightHandler={highlightHandler}\n onMouseEnterBlock={handleMouseEnter}\n onMouseLeaveBlock={handleMouseLeave}\n iframeRuntime={iframeRuntime}\n />\n </div>\n )\n}\n\nexport default React.memo(injectIntl(BlockSelector))\n\n```" } ]
code_admin-pages_a15c32a9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/utils.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport EXTENSIONS from '../__fixtures__/extensions'\nimport { SidebarComponent } from '../typings'\nimport COMPONENTS from './__fixtures__/components'\nimport { NormalizedBlock } from './typings'\nimport {\n generateWarningMessage,\n getComponents,\n getParentTreePath,\n hasContentPropsInSchema,\n isRootComponent,\n normalize,\n} from './utils'\n\nconst DEFAULT_EXTENSIONS_COMPONENTS = [\n {\n isEditable: true,\n name: 'admin/editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n isEditable: true,\n name: 'admin/editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n isEditable: true,\n name: 'admin/editor.productSummary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n]\n\ndescribe('getComponents', () => {\n let spiedConsoleWarn: jest.MockInstance<\n ReturnType<Console['warn']>,\n Parameters<Console['warn']>\n >\n\n beforeEach(() => {\n spiedConsoleWarn = jest\n .spyOn(console, 'warn')\n .mockImplementation(() => undefined)\n })\n\n afterEach(() => {\n spiedConsoleWarn.mockRestore()\n })\n\n it('should filter out components without either a schema or a title', () => {\n expect(getComponents(EXTENSIONS, COMPONENTS, 'store.home')).toEqual(\n DEFAULT_EXTENSIONS_COMPONENTS\n )\n })\n\n it('should use blocks from extension to determine order', () => {\n const swap = <T>(indexA: number, indexB: number, arr: T[]) => {\n const clonedArr = Array.from(arr)\n\n const temp = clonedArr[indexA]\n\n clonedArr[indexA] = clonedArr[indexB]\n\n clonedArr[indexB] = temp\n\n return clonedArr\n }\n\n const homeBlocks = EXTENSIONS['store.home'].blocks || []\n\n const shelfExtensionsIndex = homeBlocks.findIndex(item =>\n item.blockId.endsWith('shelf#home')\n )\n\n const carouselExtensionsIndex = homeBlocks.findIndex(item =>\n item.blockId.endsWith('carousel#home')\n )\n\n const reorderedHomeBlocks = swap(\n shelfExtensionsIndex,\n carouselExtensionsIndex,\n homeBlocks\n )\n\n const shelfComponentsIndex = DEFAULT_EXTENSIONS_COMPONENTS.findIndex(item =>\n item.treePath.endsWith('shelf#home')\n )\n\n const carouselComponentsIndex = DEFAULT_EXTENSIONS_COMPONENTS.findIndex(\n item => item.treePath.endsWith('carousel#home')\n )\n\n const reorderedDefaultComponentBlocks = swap(\n shelfComponentsIndex,\n carouselComponentsIndex,\n DEFAULT_EXTENSIONS_COMPONENTS\n )\n\n const extensions = {\n ...EXTENSIONS,\n 'store.home': {\n ...EXTENSIONS['store.home'],\n blocks: reorderedHomeBlocks,\n },\n }\n\n expect(getComponents(extensions, COMPONENTS, 'store.home')).toEqual(\n reorderedDefaultComponentBlocks\n )\n })\n\n describe('schema with no titles', () => {\n it('should show extension that have only title in the blocks (extensions) and no schema', () => {\n const extensions: RenderRuntime['extensions'] = {\n ...EXTENSIONS,\n 'store.home/title-in-blocks': {\n after: [],\n around: [],\n before: [],\n blockId: 'vtex.title-in-blocks@0.x:title-in-blocks',\n blocks: [],\n component: 'vtex.title-in-blocks@0.0.1/TitleInBlocks',\n composition: 'blocks',\n content: {},\n hasContentSchema: false,\n preview: null,\n props: {},\n render: 'server',\n title: 'admin/title-in-blocks.title',\n track: [],\n },\n }\n\n expect(getComponents(extensions, {}, 'store.home')).toEqual([\n {\n isEditable: false,\n name: 'admin/title-in-blocks.title',\n treePath: 'store.home/title-in-blocks',\n },\n ])\n })\n\n it('should filter out components whose extensions have falsy titles', () => {\n const extensions: RenderRuntime['extensions'] = {\n ...EXTENSIONS,\n 'store.home/empty-string-title': {\n after: [],\n around: [],\n before: [],\n blockId: 'vtex.empty-string-title@0.x:empty-string-title',\n blocks: [],\n component: 'vtex.empty-string-title@0.0.1/EmptyStringTitle',\n composition: 'blocks',\n content: {},\n hasContentSchema: false,\n preview: null,\n props: {},\n render: 'server',\n track: [],\n },\n 'store.home/null-title': {\n after: [],\n around: [],\n before: [],\n blockId: 'vtex.null-title@0.x:null-title',\n blocks: [],\n component: 'vtex.null-title@0.0.1/NullTitle',\n composition: 'blocks',\n content: {},\n hasContentSchema: false,\n preview: null,\n props: {},\n render: 'server',\n track: [],\n },\n 'store.home/undefined-title': {\n after: [],\n around: [],\n before: [],\n blockId: 'vtex.undefined-title@0.x:undefined-title',\n blocks: [],\n component: 'vtex.undefined-title@0.0.1/UndefinedTitle',\n composition: 'blocks',\n content: {},\n hasContentSchema: false,\n preview: null,\n props: {},\n render: 'server',\n track: [],\n },\n }\n\n const components = {\n ...COMPONENTS,\n 'vtex.empty-string-title@0.0.1/EmptyStringTitle': {\n schema: {\n title: '',\n },\n },\n 'vtex.null-title@0.0.1/NullTitle': {\n schema: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n title: null as any,\n },\n },\n 'vtex.undefined-title@0.0.1/UndefinedTitle': {\n schema: {\n title: undefined,\n },\n },\n }\n\n expect(getComponents(extensions, components, 'store.home')).toEqual(\n DEFAULT_EXTENSIONS_COMPONENTS\n )\n })\n })\n\n it('should use getSchema as fallback for schema', () => {\n const components = {\n 'vtex.shelf@1.25.0/Shelf': {\n getSchema: () => ({\n properties: { mock: {} },\n title: 'admin/editor.shelf.title',\n type: 'object',\n }),\n schema: undefined,\n },\n }\n\n expect(getComponents(EXTENSIONS, components, 'store.home')).toEqual([\n {\n isEditable: true,\n name: 'admin/editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n ])\n })\n\n describe('Warnings for schemas without title', () => {\n it('should call console.warn when component has a schema with no title', () => {\n const EXTENSION_ID = 'store.home/shelf#home/product-summary'\n\n const extensions = {\n [EXTENSION_ID]: EXTENSIONS[EXTENSION_ID],\n }\n\n const COMPONENT_ID = 'vtex.product-summary@2.31.0/ProductSummaryCustom'\n\n const components = {\n [COMPONENT_ID]: {\n schema: {},\n },\n }\n\n expect(getComponents(extensions, components, 'store.home')).toEqual([])\n\n expect(spiedConsoleWarn).toHaveBeenCalledTimes(1)\n expect(spiedConsoleWarn).toHaveBeenCalledWith(\n generateWarningMessage(COMPONENT_ID)\n )\n })\n\n it('should call console.warn when component returns a schema from getSchema with no title', () => {\n const COMPONENT_ID = 'vtex.shelf@1.25.0/Shelf'\n\n const components = {\n ...COMPONENTS,\n [COMPONENT_ID]: {\n getSchema: () => ({}),\n },\n }\n\n expect(getComponents(EXTENSIONS, components, 'store.home')).toEqual(\n DEFAULT_EXTENSIONS_COMPONENTS.filter(\n item => item.treePath !== 'store.home/shelf#home'\n )\n )\n\n expect(spiedConsoleWarn).toHaveBeenCalledTimes(1)\n expect(spiedConsoleWarn).toHaveBeenCalledWith(\n generateWarningMessage(COMPONENT_ID)\n )\n })\n })\n})\n\ndescribe('getParentTreePath', () => {\n it('returns parent treePath', () => {\n expect(getParentTreePath('store.home/shelf#home')).toBe('store.home')\n })\n\n it('handles strings with no delimiter', () => {\n expect(getParentTreePath('store')).toBe('store')\n })\n})\n\ndescribe('hasContentPropsInSchema', () => {\n it(`should return false when schema isn't type object`, () => {\n expect(hasContentPropsInSchema({ title: 'Test' })).toBe(false)\n expect(hasContentPropsInSchema({ type: 'number' })).toBe(false)\n })\n\n it(`should return true if there are properties with isLayout falsy`, () => {\n expect(\n hasContentPropsInSchema({\n properties: { test: { isLayout: false } },\n type: 'object',\n })\n ).toBe(true)\n expect(\n hasContentPropsInSchema({ type: 'object', properties: { test: {} } })\n ).toBe(true)\n })\n\n it(`should return true if there are nested properties with isLayout falsy`, () => {\n expect(\n hasContentPropsInSchema({\n properties: { test: { isLayout: false } },\n type: 'object',\n })\n ).toBe(true)\n expect(\n hasContentPropsInSchema({\n properties: { test: { type: 'object', properties: { lala: {} } } },\n type: 'object',\n })\n ).toBe(true)\n })\n})\n\ndescribe('isRootComponent', () => {\n it(`returns true when called with 'store.home/header.full'`, () => {\n const input: SidebarComponent = {\n isEditable: true,\n name: 'header',\n treePath: 'store.home/header.full',\n }\n\n const expectedOutput = true\n\n expect(isRootComponent(2)(input)).toBe(expectedOutput)\n })\n\n it(`returns true when called with 'store.home/footer'`, () => {\n const input: SidebarComponent = {\n isEditable: true,\n name: 'footer',\n treePath: 'store.home/footer',\n }\n\n const expectedOutput = true\n\n expect(isRootComponent(2)(input)).toBe(expectedOutput)\n })\n\n it(`returns true when called with 'store.home/test'`, () => {\n const input: SidebarComponent = {\n isEditable: true,\n name: 'test',\n treePath: 'store.home/test',\n }\n\n const expectedOutput = true\n\n expect(isRootComponent(2)(input)).toBe(expectedOutput)\n })\n\n it(`returns false when called with 'store.home/header/login'`, () => {\n const input: SidebarComponent = {\n isEditable: true,\n name: 'login',\n treePath: 'store.home/header.full/login',\n }\n\n const expectedOutput = false\n\n expect(isRootComponent(2)(input)).toBe(expectedOutput)\n })\n\n it(`returns false when called with 'store.home/shelf/product-summary'`, () => {\n const input: SidebarComponent = {\n isEditable: true,\n name: 'product-summary',\n treePath: 'store.home/shelf/product-summary',\n }\n\n const expectedOutput = false\n\n expect(isRootComponent(2)(input)).toBe(expectedOutput)\n })\n})\n\ndescribe('normalize', () => {\n it('handles empty array inputs', () => {\n const input: SidebarComponent[] = []\n\n const expectedOutput: NormalizedBlock[] = []\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n\n it('nests store.home/ level components', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n {\n isEditable: true,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n isEditable: true,\n name: 'editor.category-menu.title',\n treePath: 'store.home/$before_0/category-menu',\n },\n {\n isEditable: true,\n name: 'editor.login.title',\n treePath: 'store.home/$before_0/login',\n },\n {\n isEditable: true,\n name: 'editor.menu',\n treePath: 'store.home/$before_0/menu-link',\n },\n {\n isEditable: true,\n name: 'editor.minicart.title',\n treePath: 'store.home/$before_0/minicart',\n },\n {\n isEditable: true,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n isEditable: true,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.category-menu.title',\n treePath: 'store.home/$before_0/category-menu',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.login.title',\n treePath: 'store.home/$before_0/login',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.menu',\n treePath: 'store.home/$before_0/menu-link',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.minicart.title',\n treePath: 'store.home/$before_0/minicart',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n // Don't consider order here\n expect(normalize(input)).toEqual(expect.arrayContaining(expectedOutput))\n })\n\n it('preserves multilevel structures', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n isEditable: true,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0/menu',\n },\n {\n isEditable: true,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n isEditable: true,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n {\n isEditable: true,\n name: 'editor.product-rating.title',\n treePath: 'store.home/shelf#home/product-summary/product-rating',\n },\n {\n isEditable: true,\n name: 'editor.product-rating.start.title',\n treePath: 'store.home/shelf#home/product-summary/product-rating/start',\n },\n {\n isEditable: true,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0/menu',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n components: [\n {\n components: [\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-rating.start.title',\n treePath:\n 'store.home/shelf#home/product-summary/product-rating/start',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-rating.title',\n treePath:\n 'store.home/shelf#home/product-summary/product-rating',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n\n it('should treat \"closest\" node as next root', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath:\n 'store.home/shelf#home/spacer/placeholder/flex/product-summary',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.star.title',\n treePath:\n 'store.home/shelf#home/spacer/placeholder/flex/product-summary/star',\n },\n {\n isEditable: true,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.star.title',\n treePath:\n 'store.home/shelf#home/spacer/placeholder/flex/product-summary/star',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath:\n 'store.home/shelf#home/spacer/placeholder/flex/product-summary',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n ]\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n\n it('handles unordered components', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n {\n isEditable: true,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n isEditable: true,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n isEditable: true,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n\n it(`handles components with 'around' blocks`, () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n isEditable: true,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n {\n isEditable: true,\n name: 'editor.around-shelf.title',\n treePath: 'store.home/shelf#home/$around_0',\n },\n {\n isEditable: true,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n isEditable: true,\n name: 'editor.around-carousel.title',\n treePath: 'store.home/carousel#home/$around_0',\n },\n {\n isEditable: true,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.header.title',\n treePath: 'store.home/$before_0',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.around-carousel.title',\n treePath: 'store.home/carousel#home/$around_0',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.carousel.title',\n treePath: 'store.home/carousel#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.around-shelf.title',\n treePath: 'store.home/shelf#home/$around_0',\n },\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath: 'store.home/shelf#home/product-summary',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.shelf.title',\n treePath: 'store.home/shelf#home',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.footer.title',\n treePath: 'store.home/$after_0',\n },\n ]\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n\n it('should handle treePaths with same beginning but that are different blocks', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.carousel.title',\n treePath: 'store.home/layout#home',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath: 'store.home/layout#homeCollection',\n },\n {\n isEditable: true,\n name: 'editor.product-summary.title',\n treePath: 'store.home/layout#homeCollection/button',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.carousel.title',\n treePath: 'store.home/layout#home',\n },\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath: 'store.home/layout#homeCollection/button',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.product-summary.title',\n treePath: 'store.home/layout#homeCollection',\n },\n ]\n const output = normalize(input)\n\n expect(output).toEqual(expectedOutput)\n })\n\n it('should put components in closest ancestor', () => {\n const input: SidebarComponent[] = [\n {\n isEditable: true,\n name: 'editor.row.title',\n treePath: 'store.home/flex-layout.row#homeCollections',\n },\n {\n isEditable: true,\n name: 'admin/editor.rich-text.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#leftCollection/rich-text#homeCollectionsTitle',\n },\n {\n isEditable: true,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsBottom/info-card#homeBannerDCComics',\n },\n {\n isEditable: true,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsBottom/info-card#homeBannerMarvel',\n },\n {\n isEditable: true,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsTop/info-card#homeBannerAngel',\n },\n {\n isEditable: true,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsTop/info-card#homeBannerSeaHunter',\n },\n {\n isEditable: true,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#rightCollection/info-card#homeCollectionsDisney',\n },\n ]\n\n const expectedOutput: NormalizedBlock[] = [\n {\n components: [\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.rich-text.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#leftCollection/rich-text#homeCollectionsTitle',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsBottom/info-card#homeBannerDCComics',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsBottom/info-card#homeBannerMarvel',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsTop/info-card#homeBannerAngel',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#middleCollection/flex-layout.row#homeCollectionsTop/info-card#homeBannerSeaHunter',\n },\n {\n components: [],\n isEditable: true,\n isSortable: false,\n name: 'admin/editor.info-card.title',\n treePath:\n 'store.home/flex-layout.row#homeCollections/flex-layout.col#rightCollection/info-card#homeCollectionsDisney',\n },\n ],\n isEditable: true,\n isSortable: false,\n name: 'editor.row.title',\n treePath: 'store.home/flex-layout.row#homeCollections',\n },\n ]\n\n expect(normalize(input)).toEqual(expectedOutput)\n })\n})\n\n```" } ]
code_admin-pages_5828a7ad
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { flatten, path, pathOr } from 'ramda'\nimport { IntlShape } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\nimport { ComponentsRegistry } from 'vtex.render-runtime'\n\nimport { getBlockRole } from '../../../../utils/blocks'\nimport { getIframeRenderComponents } from '../../../../utils/components'\nimport { ModifiedSidebarComponent, SidebarComponent } from '../typings'\nimport { BlocksByRole, NormalizedBlock } from './typings'\n\nexport const generateWarningMessage = (name: string) =>\n `[Site Editor] Component \"${name}\" exports schema but doesn't have a \"title\" property, because of that, it won't appear in the lateral list. If this is intended, ignore this message.`\n\nconst getParentContainerBlocksGetter = (extensions: Extensions) => (\n parentPath: string\n) => {\n const children = pathOr<InnerBlock[], InnerBlock[]>(\n [],\n [parentPath, 'children'],\n extensions\n )\n return pathOr<InnerBlock[], InnerBlock[]>(\n children,\n [parentPath, 'blocks'],\n extensions\n )\n}\n\nconst getComponentNameGetterFromExtensions = (extensions: Extensions) => (\n treePath: string\n) => (extensions[treePath] && extensions[treePath].component) || ''\n\nconst getComponentSchemaGetter = (\n components: ComponentsRegistry | null,\n extensions: Extensions\n) => (treePath: string) => {\n const getComponentName = getComponentNameGetterFromExtensions(extensions)\n\n const extensionProps = pathOr({}, [treePath, 'props'], extensions)\n\n const component = getComponentName(treePath)\n\n const getSchema = path([component, 'getSchema'], { ...components })\n\n return (\n path([component, 'schema'], { ...components }) ||\n (typeof getSchema === 'function' && getSchema(extensionProps))\n )\n}\n\nexport const isRootComponent = (minimumTreePathSize: number) => (\n component: Pick<ModifiedSidebarComponent, 'treePath'>\n) => {\n const splitTreePath = component.treePath.split('/')\n\n return (\n splitTreePath.length === minimumTreePathSize ||\n (splitTreePath.length === minimumTreePathSize + 1 &&\n splitTreePath[minimumTreePathSize].startsWith('$'))\n )\n}\n\nexport const hasContentPropsInSchema = (schema: ComponentSchema): boolean => {\n return (\n schema.type === 'object' &&\n Object.values(schema.properties || {}).some(\n property =>\n !property.isLayout ||\n (property.type === 'object' && hasContentPropsInSchema(property))\n )\n )\n}\n\nconst isSamePage = (page: string, treePath: string) => {\n const pageHead = page && page.split('/')[0]\n const treePathHead = treePath && treePath.split('/')[0]\n\n return pageHead && treePathHead && treePathHead === pageHead\n}\n\nexport const getComponents = (\n extensions: Extensions,\n components: ComponentsRegistry | null,\n page: string\n) => {\n const getParentContainerProps = getParentContainerBlocksGetter(extensions)\n\n const getComponentName = getComponentNameGetterFromExtensions(extensions)\n const getComponentSchema = getComponentSchemaGetter(components, extensions)\n\n const sidebarComponentMap: Record<string, SidebarComponent> = {}\n const isComponentEditableMap: Record<string, boolean> = {}\n\n return Object.keys(extensions)\n .filter(treePath => {\n const schema = getComponentSchema(treePath)\n const componentName = getComponentName(treePath)\n const hasTitleInSchema = schema && !!schema.title\n\n if (schema && !hasTitleInSchema) {\n console.warn(generateWarningMessage(componentName))\n }\n\n const extension = pathOr<Partial<Extension>, Extension>(\n {},\n [treePath],\n extensions\n )\n\n const hasTitleInBlock = !!extension.title\n\n const isRoot = isRootComponent(2)({ treePath })\n\n const isEditable =\n isComponentEditableMap[componentName] !== undefined\n ? isComponentEditableMap[componentName]\n : (isComponentEditableMap[componentName] =\n extension.hasContentSchema || hasContentPropsInSchema(schema))\n\n const shouldShow =\n isSamePage(page, treePath) &&\n (hasTitleInBlock || (hasTitleInSchema && (isRoot || isEditable)))\n\n if (shouldShow) {\n sidebarComponentMap[treePath] = {\n isEditable,\n name: extension.title || schema.title,\n treePath,\n }\n }\n\n return shouldShow\n })\n .sort((treePathA, treePathB) => {\n const splitTreePathA = treePathA.split('/')\n const parentPathA = splitTreePathA\n .slice(0, splitTreePathA.length - 1)\n .join('/')\n\n const splitTreePathB = treePathB.split('/')\n const parentPathB = splitTreePathB\n .slice(0, splitTreePathB.length - 1)\n .join('/')\n\n const nameA = splitTreePathA[splitTreePathA.length - 1]\n const nameB = splitTreePathB[splitTreePathB.length - 1]\n\n if (parentPathA !== parentPathB) {\n return 0\n }\n\n const parentContainerProps = getParentContainerProps(parentPathA)\n\n const firstElementPosition = parentContainerProps.findIndex(\n ({ extensionPointId }) => {\n return nameA === extensionPointId\n }\n )\n const secondElementPosition = parentContainerProps.findIndex(\n ({ extensionPointId }) => {\n return nameB === extensionPointId\n }\n )\n\n const areBothElementsInProps =\n firstElementPosition !== -1 && secondElementPosition !== -1\n\n if (\n areBothElementsInProps &&\n firstElementPosition > secondElementPosition\n ) {\n return 1\n }\n\n if (\n areBothElementsInProps &&\n firstElementPosition < secondElementPosition\n ) {\n return -1\n }\n\n return treePathA > treePathB ? 1 : -1\n })\n .map<SidebarComponent>(treePath => sidebarComponentMap[treePath])\n}\n\nconst hideNonExistentNodesInTreePath = (\n components: SidebarComponent[]\n): ModifiedSidebarComponent[] => {\n const allTreePaths = components.reduce((acc, component) => {\n return acc.add(component.treePath)\n }, new Set())\n\n return components.map(component => {\n const paths = component.treePath.split('/')\n\n let prefix: string | null = null\n const existingPaths = paths.filter(path => {\n prefix = prefix === null ? path : [prefix, path].join('/')\n return allTreePaths.has(prefix)\n })\n\n return {\n ...component,\n modifiedTreePath: existingPaths.join('/'),\n }\n })\n}\n\nconst modifiedPathLength = (component: ModifiedSidebarComponent) =>\n component.modifiedTreePath.split('/').length\n\nconst getComponentRole = (component: SidebarComponent): keyof BlocksByRole => {\n const splitTreePath = component.treePath.split('/')\n const treePathTail = splitTreePath[splitTreePath.length - 1]\n return getBlockRole(treePathTail)\n}\n\nexport const getParentTreePath = (treePath: string): string => {\n const splitTreePath = treePath.split('/')\n\n if (splitTreePath.length === 1) {\n return splitTreePath.join('')\n }\n\n return splitTreePath.slice(0, splitTreePath.length - 1).join('/')\n}\n\nconst buildTree = (orderedNodes: ModifiedSidebarComponent[]) => {\n const nodes: Record<string, NormalizedBlock> = {}\n orderedNodes.forEach(({ modifiedTreePath, ...component }) => {\n const normalized = {\n ...component,\n components: [],\n isSortable: false,\n }\n const parentId = modifiedTreePath\n .split('/')\n .slice(0, -1)\n .join('/')\n\n nodes[modifiedTreePath] = normalized\n\n if (nodes[parentId] != null) {\n const parent = nodes[parentId]\n parent.components.push(normalized)\n }\n })\n return nodes\n}\n\nconst partitionNodesChildrenByRole = (\n nodes: Record<string, NormalizedBlock>\n) => {\n const partitionChildrenByRole = ({ components }: NormalizedBlock) =>\n components.reduce(\n (componentsByRole: BlocksByRole, component) => {\n componentsByRole[getComponentRole(component)].push(component)\n return componentsByRole\n },\n { around: [], after: [], before: [], blocks: [] }\n )\n\n return Object.values(nodes).reduce(\n (childrenByRole: Record<string, BlocksByRole>, node) => {\n childrenByRole[node.treePath] = partitionChildrenByRole(node)\n return childrenByRole\n },\n {}\n )\n}\nconst hoistSubtrees = (\n component: NormalizedBlock,\n pathToChildrenByRole: Record<string, BlocksByRole>,\n isRoot = false\n): NormalizedBlock[] => {\n const { treePath, components } = component\n const childrenByRole = pathToChildrenByRole[treePath]\n const blockChildren = components.filter(\n child => getComponentRole(child) === 'blocks'\n )\n const hoistedComponents = flatten(\n blockChildren.map(child => hoistSubtrees(child, pathToChildrenByRole))\n )\n const current = isRoot\n ? hoistedComponents\n : [{ ...component, components: hoistedComponents }]\n\n if (childrenByRole) {\n return [\n ...childrenByRole.around,\n ...childrenByRole.before,\n ...current,\n ...childrenByRole.after,\n ]\n }\n\n return [...current]\n}\n\nconst hoistSurroundingBlocks = (\n nodes: Record<string, NormalizedBlock>,\n rootId: string\n) => {\n const childrenByRole = partitionNodesChildrenByRole(nodes)\n\n return hoistSubtrees(nodes[rootId], childrenByRole, true)\n}\n\nexport const normalize = (components: SidebarComponent[]) => {\n if (components.length === 0) {\n return []\n }\n const rootId = components[0].treePath.split('/')[0]\n const root = { treePath: rootId, name: 'root', isEditable: false }\n const allComponents = [root, ...components]\n\n const modifiedComponents = hideNonExistentNodesInTreePath(allComponents).sort(\n (cmp1: ModifiedSidebarComponent, cmp2: ModifiedSidebarComponent) =>\n modifiedPathLength(cmp1) - modifiedPathLength(cmp2)\n )\n\n const nodes = buildTree(modifiedComponents)\n\n return hoistSurroundingBlocks(nodes, rootId)\n}\n\nexport const getNormalizedBlocks = (\n partialContextOrComponents:\n | Pick<RenderContext, 'extensions' | 'page'>\n | ReturnType<typeof getComponents>\n) => {\n if (\n 'extensions' in partialContextOrComponents &&\n 'page' in partialContextOrComponents\n ) {\n const partialContext = partialContextOrComponents as Pick<\n RenderContext,\n 'extensions' | 'page'\n >\n return normalize(\n getComponents(\n partialContext.extensions,\n getIframeRenderComponents(),\n partialContext.page\n )\n )\n }\n\n const components = partialContextOrComponents as ReturnType<\n typeof getComponents\n >\n return normalize(components)\n}\n\nexport const getTitleByTreePathMap = (\n components: SidebarComponent[],\n intl: IntlShape\n) => {\n return components.reduce<\n Record<string, { title?: string; isEditable: boolean }>\n >((acc, { isEditable, name, treePath }) => {\n const title = formatIOMessage({ id: name, intl })\n acc[treePath] = { title, isEditable }\n\n return acc\n }, {})\n}\n\n```" } ]
code_admin-pages_35691e8e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SidebarComponent } from '../typings'\n\nexport interface NormalizedBlock extends SidebarComponent {\n components: NormalizedBlock[]\n isEditable: boolean\n isSortable: boolean\n}\n\nexport interface BlocksByRole {\n after: NormalizedBlock[]\n around: NormalizedBlock[]\n before: NormalizedBlock[]\n blocks: NormalizedBlock[]\n}\n\n```" } ]
code_admin-pages_2c3d95d3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, injectIntl } from 'react-intl'\n\nimport { getActiveContentId } from '../../../../../utils/components'\nimport { useEditorContext } from '../../../../EditorContext'\nimport { EditingState } from '../../typings'\nimport EditorHeader from '../EditorHeader'\nimport { getIsDefaultContent } from '../utils'\nimport Card from './Card'\nimport CreateButton from './CreateButton'\nimport { useListHandlers } from './hooks'\nimport { UseListHandlersParams } from './typings'\nimport { getConfigurationSort } from './utils'\n\ninterface Props extends Omit<UseListHandlersParams, 'activeContentId'> {\n editingContentId: EditingState['contentId']\n onConfigurationCreate: () => void\n onConfigurationOpen: (configuration: ExtensionConfiguration) => void\n onListClose?: () => void\n onConfigurationActivate: (\n configuration: ExtensionConfiguration\n ) => Promise<void>\n onListOpen?: () => void\n}\n\nconst messages = defineMessages({\n contentCards: {\n defaultMessage: 'Configurations',\n id: 'admin/pages.editor.component-list.title',\n },\n})\n\nconst BlockConfigurationList: React.FC<Props> = ({\n deleteContent,\n sendEventToAudit,\n editingContentId,\n iframeRuntime,\n intl,\n onConfigurationCreate,\n onConfigurationOpen,\n onConfigurationActivate,\n onListClose,\n onListOpen,\n showToast,\n}) => {\n const editor = useEditorContext()\n\n const activeContentId = React.useMemo(\n () =>\n getActiveContentId({\n extensions: iframeRuntime.extensions,\n treePath: editor.editTreePath,\n }),\n [editor.editTreePath, iframeRuntime.extensions]\n )\n\n const { handleConfirmConfigurationDelete } = useListHandlers({\n activeContentId,\n deleteContent,\n sendEventToAudit,\n iframeRuntime,\n intl,\n showToast,\n })\n\n if (!editor.blockData.configurations) {\n return null\n }\n\n const configurations = editor.blockData.configurations.sort(\n getConfigurationSort(activeContentId)\n )\n\n return (\n <div\n className=\"w-100 min-h-100 absolute bg-white\"\n style={{ boxShadow: '-3px 0px 23px 0px rgba(0,0,0,0.14)' }}\n >\n <EditorHeader\n onListClose={onListClose}\n onListOpen={onListOpen}\n title={intl.formatMessage(messages.contentCards)}\n />\n\n <CreateButton onClick={onConfigurationCreate} />\n\n {configurations.map((configuration: ExtensionConfiguration, index) => (\n <Card\n configuration={configuration}\n isActive={configuration.contentId === activeContentId}\n isDefaultContent={getIsDefaultContent(configuration)}\n isEditing={editingContentId === configuration.contentId}\n key={configuration.contentId || index}\n onConfigurationOpen={onConfigurationOpen}\n onConfigurationActivate={onConfigurationActivate}\n onDelete={handleConfirmConfigurationDelete}\n />\n ))}\n </div>\n )\n}\n\nexport default injectIntl(BlockConfigurationList)\n\n```" } ]
code_admin-pages_8ef552b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport ListContent from '../../../graphql/ListContent.graphql'\nimport { ListContentData } from '../../../queries/ListContent'\nimport { GetDeleteStoreUpdater } from './typings'\n\nexport const isConfigurationExpired = (\n configuration: ExtensionConfiguration\n) => {\n const endDateStatement = configuration.condition.statements.find(\n (statement: ExtensionConfigurationConditionStatement) =>\n statement &&\n statement.subject === 'date' &&\n JSON.parse(statement.objectJSON).to\n )\n\n const getEndDate = (statement: ExtensionConfigurationConditionStatement) => {\n return new Date(JSON.parse(statement.objectJSON).to)\n }\n\n if (endDateStatement && getEndDate(endDateStatement) < new Date()) {\n return true\n }\n\n return false\n}\n\nexport const getConfigurationSort = (activeContentId: string) => (\n current: ExtensionConfiguration,\n previous: ExtensionConfiguration\n) => {\n const isActiveConfiguration = (configuration: ExtensionConfiguration) =>\n configuration.contentId === activeContentId\n\n const isAppConfiguration = (configuration: ExtensionConfiguration) =>\n configuration.origin\n\n if (isActiveConfiguration(current)) {\n return -1\n }\n\n if (isAppConfiguration(current)) {\n return 1\n }\n\n if (isAppConfiguration(previous)) {\n return -1\n }\n\n if (isConfigurationExpired(previous)) {\n return -1\n }\n\n if (isConfigurationExpired(current)) {\n return 1\n }\n\n return 0\n}\n\nexport const isConfigurationScheduled = (\n configuration: ExtensionConfiguration\n) => configuration.condition.statements.length > 0\n\nexport const getDeleteStoreUpdater: GetDeleteStoreUpdater = ({\n action,\n blockId,\n iframeRuntime,\n serverTreePath,\n setBlockData,\n template,\n}) => (store, { data }) => {\n if (action === 'reset') {\n return\n }\n\n const cacheAccessParameters = {\n query: ListContent,\n variables: {\n bindingId: iframeRuntime.binding?.id,\n blockId,\n pageContext: iframeRuntime.route.pageContext,\n template,\n treePath: serverTreePath,\n },\n }\n\n const deletedContentId = data && data.deleteContent\n\n try {\n const queryData = store.readQuery<ListContentData>(cacheAccessParameters)\n\n if (queryData) {\n const content =\n queryData.listContentWithSchema &&\n queryData.listContentWithSchema.content\n\n const newContent =\n content &&\n content.filter(({ contentId }) => contentId !== deletedContentId)\n\n const newData = {\n ...queryData,\n listContentWithSchema: {\n ...queryData.listContentWithSchema,\n content: newContent,\n },\n }\n\n store.writeQuery({\n data: newData,\n ...cacheAccessParameters,\n })\n\n setBlockData({ configurations: newContent })\n }\n } catch (err) {\n console.warn('No cache found for \"ListContent\".')\n }\n}\n\n```" } ]
code_admin-pages_40825e19
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MutationUpdaterFn } from 'react-apollo'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport {\n DeleteContentData,\n DeleteContentMutationFn,\n} from '../../../mutations/DeleteContent'\nimport { SendEventToAuditMutationFn } from '../../../mutations/SendEventToAudit'\n\ninterface GetDeleteStoreUpdaterParams\n extends Pick<BlockData, 'serverTreePath' | 'template'> {\n action: 'reset' | 'delete'\n blockId: EditorContextType['blockData']['id']\n iframeRuntime: RenderContext\n setBlockData: EditorContextType['setBlockData']\n}\n\nexport type GetDeleteStoreUpdater = (\n params: GetDeleteStoreUpdaterParams\n) => MutationUpdaterFn<DeleteContentData>\n\nexport interface UseListHandlersParams {\n activeContentId: ExtensionConfiguration['contentId']\n deleteContent: DeleteContentMutationFn\n sendEventToAudit: SendEventToAuditMutationFn\n iframeRuntime: RenderContext\n intl: ReactIntl.InjectedIntl\n showToast: ToastConsumerFunctions['showToast']\n}\n\nexport type UseListHandlers = (\n params: UseListHandlersParams\n) => {\n handleConfirmConfigurationDelete: (\n configuration: ExtensionConfiguration\n ) => void\n handleConfigurationDelete: (\n configuration: ExtensionConfiguration\n ) => Promise<void>\n}\n\n```" } ]
code_admin-pages_058bef9f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/hooks.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useCallback } from 'react'\nimport { defineMessages } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport { useEditorContext } from '../../../../EditorContext'\nimport { useModalContext } from '../../ModalContext'\nimport { getConfigurationType, getIsDefaultContent } from '../utils'\nimport { ConfigurationType } from '../typings'\nimport { UseListHandlers } from './typings'\nimport { getDeleteStoreUpdater } from './utils'\nimport { createEventObject } from '../../../../../utils/auditEvents'\n\nconst messages = defineMessages({\n cancel: {\n defaultMessage: 'Cancel',\n id: 'admin/pages.editor.components.modal.list.delete.button.cancel',\n },\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.editor.components.modal.list.delete.button.delete',\n },\n deleteActiveText: {\n defaultMessage:\n 'You are trying to delete the active content. The next available content will take its place. Are you sure you want to continue? This action cannot be undone.',\n id: 'admin/pages.editor.components.modal.list.delete.active.text',\n },\n deleteActiveTitle: {\n defaultMessage: 'Delete active content',\n id: 'admin/pages.editor.components.modal.list.delete.active.title',\n },\n deleteError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.components.toast.delete.error',\n },\n deleteInactiveText: {\n defaultMessage:\n 'Are you sure you want to delete this content? This action cannot be undone.',\n id: 'admin/pages.editor.components.modal.list.delete.inactive.text',\n },\n deleteInactiveTitle: {\n defaultMessage: 'Delete content',\n id: 'admin/pages.editor.components.modal.list.delete.inactive.title',\n },\n reset: {\n defaultMessage: 'Reset',\n id: 'admin/pages.editor.components.modal.list.reset.button.reset',\n },\n deleteSuccess: {\n defaultMessage: 'Content deleted successfully.',\n id: 'admin/pages.editor.components.toast.delete.success',\n },\n resetError: {\n defaultMessage: 'Something went wrong. Please try again.',\n id: 'admin/pages.editor.components.toast.reset.error',\n },\n resetSuccess: {\n defaultMessage: 'Content reset successfully.',\n id: 'admin/pages.editor.components.toast.reset.success',\n },\n resetTitle: {\n defaultMessage: 'Reset content from an app',\n id: 'admin/pages.editor.components.modal.list.reset.title',\n },\n resetText: {\n defaultMessage:\n \"You are trying to reset content created by an application. This action will discard any changes you've made. Are you sure you want to continue? This action cannot be undone.\",\n id: 'admin/pages.editor.components.modal.list.reset.text',\n },\n})\n\nexport const useListHandlers: UseListHandlers = ({\n activeContentId,\n deleteContent,\n sendEventToAudit,\n iframeRuntime,\n intl,\n showToast,\n}) => {\n const editor = useEditorContext()\n\n const modal = useModalContext()\n const { account, workspace } = useRuntime()\n\n const handleConfigurationDelete = useCallback(\n async (configuration: ExtensionConfiguration) => {\n editor.setIsLoading(true)\n\n const action = getIsDefaultContent(configuration) ? 'reset' : 'delete'\n\n const {\n blockData: { id: blockId, serverTreePath, template },\n setBlockData,\n } = editor\n\n if (blockId && serverTreePath && template) {\n const { contentId } = configuration\n\n let wasSuccessful = true\n\n try {\n await deleteContent({\n update: getDeleteStoreUpdater({\n action,\n blockId,\n iframeRuntime,\n serverTreePath,\n setBlockData,\n template,\n }),\n variables: {\n contentId,\n pageContext: iframeRuntime.route.pageContext,\n template,\n treePath: serverTreePath,\n },\n })\n\n await iframeRuntime.updateRuntime()\n\n const event = createEventObject(\n action === 'reset'\n ? 'Reset content block version'\n : 'Delete content block version',\n 'content',\n account,\n workspace,\n contentId\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n\n editor.editExtensionPoint(null)\n } catch (error) {\n wasSuccessful = false\n\n console.error(error)\n } finally {\n const messageKey = action + (wasSuccessful ? 'Success' : 'Error')\n\n editor.setIsLoading(false)\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(\n messages[messageKey as keyof typeof messages]\n ),\n })\n }\n }\n },\n [deleteContent, editor, iframeRuntime, intl, showToast]\n )\n\n const handleConfirmConfigurationDelete = useCallback(\n (configuration: ExtensionConfiguration) => {\n const textMessageByType: Record<\n ConfigurationType,\n ReturnType<typeof defineMessages>\n > = {\n active: messages.deleteActiveText,\n inactive: messages.deleteInactiveText,\n app: messages.resetText,\n }\n\n const titleByType: Record<\n ConfigurationType,\n ReturnType<typeof defineMessages>\n > = {\n active: messages.deleteActiveTitle,\n inactive: messages.deleteInactiveTitle,\n app: messages.resetTitle,\n }\n\n const buttonMessageByType: Record<\n ConfigurationType,\n ReturnType<typeof defineMessages>\n > = {\n active: messages.delete,\n inactive: messages.delete,\n app: messages.reset,\n }\n\n const configurationType = getConfigurationType({\n configuration,\n activeContentId,\n })\n\n modal.open({\n isActionDanger: true,\n title: intl.formatMessage(titleByType[configurationType]),\n textButtonAction: intl.formatMessage(\n buttonMessageByType[configurationType]\n ),\n textButtonCancel: intl.formatMessage(messages.cancel),\n textMessage: intl.formatMessage(textMessageByType[configurationType]),\n actionHandler: async () => {\n await handleConfigurationDelete(configuration)\n modal.close()\n },\n cancelHandler: () => {\n modal.close()\n },\n })\n },\n [modal, handleConfigurationDelete, activeContentId, intl]\n )\n\n return {\n handleConfirmConfigurationDelete,\n handleConfigurationDelete,\n }\n}\n\n```" } ]
code_admin-pages_fb892256
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/CreateButton.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 CreateButton = ({ onClick }: Props) => (\n <div className=\"mh5 ba b--muted-4 br2\">\n <ButtonWithIcon\n block\n icon={<AddIcon />}\n onClick={onClick}\n variation=\"tertiary\"\n >\n <FormattedMessage\n defaultMessage=\"New content\"\n id=\"admin/pages.editor.configuration.button.create\"\n />\n </ButtonWithIcon>\n </div>\n)\n\nexport default React.memo(CreateButton)\n\n```" } ]
code_admin-pages_7a53a7ba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/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, { useMemo } from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { FormProps } from 'react-jsonschema-form'\n// The styleguide is not exporting the warning icon\nimport {\n Button,\n ToastConsumerFunctions,\n // eslint-disable-next-line @typescript-eslint/ban-ts-ignore\n // @ts-ignore\n IconWarning,\n Checkbox,\n} from 'vtex.styleguide'\n\nimport { useEditorContext } from '../../../../EditorContext'\nimport EditableText from '../../../EditableText'\nimport { useFormMetaContext } from '../../FormMetaContext'\nimport { EditingState, FormDataContainer } from '../../typings'\nimport { isUnidentifiedPageContext } from '../../utils'\nimport EditorHeader from '../EditorHeader'\nimport { getIsDefaultContent } from '../utils'\nimport ConditionControls from './ConditionControls'\nimport Form from './Form'\nimport { useComponentFormStateStack } from './hooks'\nimport styles from './styles.css'\nimport { getSchemas } from './utils'\n\nexport enum ConfigurationStatus {\n ACTIVE = 'ACTIVE',\n INACTIVE = 'INACTIVE',\n SCHEDULED = 'SCHEDULED',\n}\n\ninterface Props {\n state?: EditingState\n condition?: ExtensionConfiguration['condition']\n contentSchema?: JSONSchema6\n data: FormDataContainer\n editingContentId: EditingState['contentId']\n iframeRuntime: RenderContext\n isNew?: boolean\n isSitewide?: boolean\n label?: string | null\n onBack: () => void\n onChange: FormProps<FormDataContainer>['onChange']\n onStatusChange: () => void\n onConditionChange?: (\n changes: Partial<ExtensionConfiguration['condition']>\n ) => void\n onLabelChange?: (e: React.ChangeEvent<HTMLInputElement>) => void\n onListClose?: () => void\n onListOpen?: () => void\n onSave: () => void\n showToast: ToastConsumerFunctions['showToast']\n title: ComponentSchema['title']\n statusFromRuntime: ConfigurationStatus\n}\n\nconst messages = defineMessages({\n pageContextError: {\n defaultMessage:\n 'Could not identify {entity}. The configuration will be set to \"{template}\".',\n id: 'admin/pages.editor.components.condition.toast.error.page-context',\n },\n activationLabel: {\n id: 'admin/pages.editor.components.condition.visibility.activation',\n },\n activationDisabledLabel: {\n id:\n 'admin/pages.editor.components.condition.visibility.activation.disabled',\n },\n activationWarningLabel: {\n id: 'admin/pages.editor.components.condition.visibility.activation.warning',\n },\n})\n\nconst BlockConfigurationEditor: React.FunctionComponent<Props> = ({\n state,\n condition,\n contentSchema,\n data,\n editingContentId,\n iframeRuntime,\n isNew,\n isSitewide = false,\n label,\n onBack,\n onChange,\n onStatusChange,\n onConditionChange,\n onLabelChange,\n onListOpen,\n onSave,\n showToast,\n title,\n statusFromRuntime,\n}) => {\n const intl = useIntl()\n\n React.useEffect(() => {\n const { pageContext } = iframeRuntime.route\n\n if (isUnidentifiedPageContext(pageContext)) {\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(\n {\n id: messages.pageContextError.id,\n },\n {\n entity: intl.formatMessage({\n id: `admin/pages.editor.components.condition.scope.entity.${\n pageContext.type.startsWith('$') ? 'custom' : pageContext.type\n }`,\n }),\n template: intl.formatMessage({\n id: 'admin/pages.editor.components.condition.scope.template',\n }),\n }\n ),\n })\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n const editor = useEditorContext()\n const formMeta = useFormMetaContext()\n const {\n currentDepth,\n componentFormState,\n popComponentFormState,\n pushComponentFormState,\n } = useComponentFormStateStack()\n\n const isContent = useMemo(() => editor.mode === 'content', [editor.mode])\n\n const { componentSchema, uiSchema } = useMemo(\n () =>\n getSchemas({\n contentSchema,\n editTreePath: editor.editTreePath,\n iframeRuntime,\n isContent,\n }),\n [contentSchema, editor.editTreePath, iframeRuntime, isContent]\n )\n\n const schema = useMemo(\n () => ({\n ...componentSchema,\n properties: {\n ...componentSchema.properties,\n },\n title: undefined,\n }),\n [componentSchema]\n )\n\n const isLoading = editor.getIsLoading()\n\n const shouldDisableSaveButton =\n isLoading || (!formMeta.getWasModified() && !isNew)\n\n const isArrayFieldOpen = Boolean(componentFormState)\n\n const isRootLevel = componentFormState === undefined\n\n const isDefaultContent = React.useMemo(() => {\n if (!editor.blockData || !editor.blockData.configurations) {\n return false\n }\n\n const defaultContent = editor.blockData.configurations.find(\n getIsDefaultContent\n )\n\n return defaultContent && defaultContent.contentId === editingContentId\n }, [editor.blockData, editingContentId])\n\n const status = state?.status ?? statusFromRuntime\n\n const hasOnlyEndDate = state?.condition?.statements?.some(\n statement => statement.verb === 'to'\n )\n\n const isSubcategoryPage = !!(\n iframeRuntime.route.pageContext?.id === 'search' &&\n iframeRuntime.route.pageContext?.type === 'subcategory'\n )\n\n const getStatusWarningText = () => {\n if (statusFromRuntime === ConfigurationStatus.ACTIVE) {\n return intl.formatMessage(messages.activationDisabledLabel)\n } else if (state?.status === ConfigurationStatus.ACTIVE) {\n return intl.formatMessage(messages.activationWarningLabel)\n }\n\n return\n }\n\n const statusWarningText = getStatusWarningText()\n\n return (\n <div className=\"w-100 h-100 absolute flex flex-column\">\n <div\n className=\"flex-grow-1 overflow-y-auto overflow-x-hidden\"\n id=\"component-editor-container\"\n >\n <EditorHeader\n onBack={componentFormState ? componentFormState.onClose : onBack}\n onListOpen={onListOpen && isRootLevel ? onListOpen : undefined}\n title={componentFormState ? componentFormState.title : title}\n />\n\n <div className=\"ma4 mb5\">\n {!isNew && statusFromRuntime !== ConfigurationStatus.ACTIVE && (\n <p className=\"pt4 pb4 pl4 pr2 bg-warning--faded lh-copy\">\n <FormattedMessage\n id=\"admin/pages.editor.components.status.alert\"\n defaultMessage=\"This version of the content is not being shown in the preview and to visitors.\"\n />\n </p>\n )}\n\n {isSubcategoryPage && (\n <p className=\"pt4 pb4 pl4 pr2 bg-warning--faded lh-copy\">\n <FormattedMessage\n id=\"admin/pages.editor.components.editable.alert\"\n defaultMessage=\"Editing this page will reflect on every subcategory page. If you want to have the content inherited from its parent(category) level, reset it.\"\n />\n </p>\n )}\n </div>\n\n <div\n className={classnames(\n 'relative bg-white flex flex-column justify-between w-100 pb3 ph5',\n styles['size-editor'],\n styles['form'],\n { [styles['form--leave']]: isArrayFieldOpen }\n )}\n >\n <FormattedMessage\n defaultMessage=\"Untitled content\"\n id=\"admin/pages.editor.configuration.defaultTitle\"\n >\n {placeholder => (\n <EditableText\n baseClassName=\"lh-copy f5 fw5 near-black\"\n onChange={onLabelChange}\n placeholder={placeholder as string}\n value={label || ''}\n />\n )}\n </FormattedMessage>\n\n <Form\n formContext={{\n currentDepth,\n componentFormState,\n popComponentFormState,\n pushComponentFormState,\n }}\n formData={data}\n onChange={onChange}\n onSubmit={onSave}\n schema={schema as JSONSchema6}\n uiSchema={uiSchema}\n />\n\n <div id=\"form__error-list-template___alert\" />\n </div>\n\n {isContent && !isDefaultContent && !isArrayFieldOpen && (\n <>\n <FormattedMessage id=\"admin/pages.editor.components.condition.title\">\n {message => (\n <div className=\"mb5 ph5 pt7 bt bw1 b--light-silver flex items-center f4\">\n {message}\n </div>\n )}\n </FormattedMessage>\n\n <div className=\"ph5 pt5 mb6\">\n <>\n <Checkbox\n checked={\n status === ConfigurationStatus.ACTIVE || hasOnlyEndDate\n }\n id=\"status\"\n label={intl.formatMessage(messages.activationLabel)}\n disabled={\n statusFromRuntime === ConfigurationStatus.ACTIVE ||\n condition?.statements.length\n }\n name=\"status\"\n onChange={onStatusChange}\n value=\"status\"\n />\n\n {statusWarningText && (\n <div className=\"mt3 dib\">\n <span>{statusWarningText}</span>\n </div>\n )}\n </>\n </div>\n </>\n )}\n\n {isContent &&\n !isDefaultContent &&\n condition &&\n onConditionChange &&\n !isArrayFieldOpen && (\n <ConditionControls\n condition={condition}\n isSitewide={isSitewide}\n onConditionChange={onConditionChange}\n pageContext={iframeRuntime.route.pageContext}\n status={status}\n statusFromRuntime={statusFromRuntime}\n />\n )}\n </div>\n\n <div\n className={classnames(\n 'pr4 pv4 flex-row-reverse w-100 bt bw1 b--light-silver',\n {\n dn: isArrayFieldOpen,\n flex: !isArrayFieldOpen,\n }\n )}\n >\n <Button\n disabled={shouldDisableSaveButton}\n onClick={onSave}\n size=\"small\"\n variation=\"primary\"\n >\n <FormattedMessage\n defaultMessage=\"Save\"\n id=\"admin/pages.editor.components.button.save\"\n />\n </Button>\n\n <div className=\"mr5\">\n <Button\n disabled={isLoading}\n onClick={onBack}\n size=\"small\"\n variation=\"tertiary\"\n >\n <FormattedMessage\n defaultMessage=\"Cancel\"\n id=\"admin/pages.editor.components.button.cancel\"\n />\n </Button>\n </div>\n </div>\n </div>\n )\n}\n\nexport default BlockConfigurationEditor\n\n```" } ]
code_admin-pages_01c13a1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/utils.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getUiSchema } from './utils'\n\ndescribe('getUiSchema', () => {\n const mockComponents = {\n 'vtex.no-schema': {\n schema: {},\n },\n 'vtex.schema-with-dependencies': {\n schema: {\n dependencies: {\n foo: {\n oneOf: [\n {\n properties: {\n bar: { type: 'string', widget: { 'ui:widget': 'textarea' } },\n foo: {\n enum: ['0'],\n },\n },\n required: ['bar'],\n },\n {\n properties: {\n bar: {},\n baz: { type: 'string', widget: { 'ui:widget': 'IOMessage' } },\n foo: {\n enum: ['1'],\n },\n },\n },\n ],\n },\n },\n properties: {\n foo: {\n enum: ['0', '1'],\n },\n },\n required: ['foo'],\n },\n },\n 'vtex.schema-with-nested-dependencies': {\n schema: {\n dependencies: {\n foo: {\n oneOf: [\n {\n dependencies: {\n bar: {\n oneOf: [\n {\n properties: {\n baar: {\n type: 'string',\n widget: { 'ui:widget': 'textarea' },\n },\n bar: { enum: ['0'] },\n },\n },\n ],\n },\n },\n properties: {\n bar: { enum: ['0'] },\n foo: {\n enum: ['0'],\n },\n },\n required: ['bar'],\n },\n {\n properties: {\n bar: {},\n baz: { type: 'string', widget: { 'ui:widget': 'IOMessage' } },\n foo: {\n enum: ['1'],\n },\n },\n },\n ],\n },\n },\n properties: {\n foo: {\n enum: ['0', '1'],\n },\n },\n required: ['foo'],\n },\n },\n 'vtex.simple-schema': {\n schema: {\n properties: {\n foo: {\n properties: {\n bar: {\n widget: { 'ui:widget': 'textarea' },\n },\n },\n type: 'object',\n },\n },\n },\n },\n }\n\n it('should get ui schema for dependencies', () => {\n const uiSchema = {\n bar: { 'ui:widget': 'textarea' },\n baz: { 'ui:widget': 'IOMessage' },\n }\n const result = getUiSchema({}, mockComponents[\n 'vtex.schema-with-dependencies'\n ].schema as ComponentSchema)\n expect(result).toEqual(uiSchema)\n })\n\n it('should get ui schema for nested dependencies', () => {\n const uiSchema = {\n baar: { 'ui:widget': 'textarea' },\n baz: { 'ui:widget': 'IOMessage' },\n }\n const result = getUiSchema({}, mockComponents[\n 'vtex.schema-with-nested-dependencies'\n ].schema as ComponentSchema)\n expect(result).toEqual(uiSchema)\n })\n\n it('should deal with empty schemas', () => {\n const result = getUiSchema({}, mockComponents['vtex.no-schema']\n .schema as ComponentSchema)\n expect(result).toEqual({})\n })\n\n it('should get ui schema for simple schemas', () => {\n const uiSchema = { foo: { bar: { 'ui:widget': 'textarea' } } }\n const result = getUiSchema({}, mockComponents['vtex.simple-schema']\n .schema as ComponentSchema)\n expect(result).toEqual(uiSchema)\n })\n})\n\n```" } ]
code_admin-pages_f65b10e1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.form {\n transition: transform 250ms ease-in-out;\n transform: translateX(0rem);\n}\n\n.form--leave {\n transition: transform 250ms ease-in-out;\n transform: translateX(-18rem);\n}\n\n.form--leave > :global(.rjsf) {\n height: 0;\n overflow: hidden;\n}\n\n@media only screen and (max-width: 40em) {\n .size-editor {\n bottom: 0;\n height: 100%;\n }\n}\n\n@media only screen and (min-width: 40em) {\n .size-editor {\n max-width: 450px;\n }\n}\n\n```" } ]
code_admin-pages_6db09e68
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JSONSchema6 } from 'json-schema'\nimport traverse from 'json-schema-traverse'\nimport { assocPath, mergeDeepLeft } from 'ramda'\nimport { UiSchema, Widget } from 'react-jsonschema-form'\n\nimport {\n getComponentSchema,\n getExtension,\n getIframeImplementation,\n} from '../../../../../utils/components'\nimport { GetSchemasArgs } from './typings'\n\n/**\n * Generates an `UiSchema` following the `Component Schema` definition of `widgets`.\n * Each schema property can define an widget especifying how to display it.\n * @param {object} componentUiSchema The default static `UiSchema` definition\n * @param {object} componentSchema The full `Component Schema` (already\n * applyed the `getSchema`, if its the case)\n * @return {object} A object defining the complete `UiSchema` that matches all the schema\n * properties.\n */\nexport const getUiSchema = (\n componentUiSchema: UiSchema,\n componentSchema: ComponentSchema\n): UiSchema => {\n /**\n * It goes deep into the schema tree to find widget definitions, generating\n * the correct path to the property.\n * e.g:\n * {\n * banner1: {\n * numberOfLines: {\n * value: {\n * 'ui:widget': 'range'\n * }\n * }\n * }\n * }\n *\n * @param {object} properties The schema properties to be analysed.\n */\n\n const arrayAttrs = /(anyOf|oneOf|allOf|dependencies)(\\/\\d+|\\/\\w+)?/g\n const noUISchemaProp = [\n 'definitions',\n 'properties',\n 'patternProperties',\n 'additionalProperties',\n ]\n let uiSchema = {}\n\n const getWidget = (\n schema: JSONSchema6 & { widget: Widget },\n JSONPointer: string\n ) => {\n if (schema.widget) {\n const widgetPath = JSONPointer.replace(arrayAttrs, '')\n .split('/')\n .filter(\n (pointer: string) => pointer && !noUISchemaProp.includes(pointer)\n )\n uiSchema = assocPath(widgetPath, schema.widget, uiSchema)\n }\n }\n\n traverse(componentSchema, getWidget)\n\n return mergeDeepLeft(uiSchema, componentUiSchema)\n}\n\nexport const getSchemas = ({\n contentSchema,\n editTreePath,\n iframeRuntime,\n isContent,\n}: GetSchemasArgs) => {\n const extension = getExtension(editTreePath, iframeRuntime.extensions)\n const componentImplementation = getIframeImplementation(extension.component)\n\n const componentSchema = getComponentSchema({\n component: componentImplementation,\n contentSchema,\n isContent: true,\n propsOrContent: extension[isContent ? 'content' : 'props'],\n runtime: iframeRuntime,\n })\n\n const componentUiSchema =\n componentImplementation && componentImplementation.uiSchema\n ? componentImplementation.uiSchema\n : {}\n\n const uiSchemaFromComponent = getUiSchema(componentUiSchema, componentSchema)\n\n return {\n componentSchema,\n uiSchema: uiSchemaFromComponent,\n }\n}\n\n```" } ]
code_admin-pages_5e820c2a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { JSONSchema6 } from 'json-schema'\n\nexport interface ComponentFormState {\n depth: number\n onClose: () => void\n onTitleChange?: () => void\n title: string\n}\n\nexport interface GetSchemasArgs {\n contentSchema?: JSONSchema6\n editTreePath: string | null\n iframeRuntime: RenderContext\n isContent?: boolean\n}\n\n```" } ]
code_admin-pages_a182bcb4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/hooks.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useRef, useState } from 'react'\n\nimport { ComponentFormState } from './typings'\n\nexport function useComponentFormStateStack() {\n const [componentFormState, setComponentFormState] = useState<\n ComponentFormState | undefined\n >()\n const stack = useRef<ComponentFormState[]>([])\n\n function popComponentFormState() {\n stack.current.pop()\n\n setComponentFormState(stack.current[stack.current.length - 1])\n }\n\n function pushComponentFormState(state: ComponentFormState) {\n const stateWithDepth = { ...state, depth: stack.current.length + 1 }\n\n stack.current.push(stateWithDepth)\n setComponentFormState(stateWithDepth)\n }\n\n return {\n currentDepth: stack.current.length,\n componentFormState,\n popComponentFormState,\n pushComponentFormState,\n }\n}\n\n```" } ]
code_admin-pages_05cad5d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/Form.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { equals } from 'ramda'\nimport React from 'react'\nimport JsonSchemaForm, { FormProps, Widget } from 'react-jsonschema-form'\n\nimport ArrayFieldTemplate from '../../../../form/ArrayFieldTemplate'\nimport BaseInput from '../../../../form/BaseInput'\nimport Dropdown from '../../../../form/Dropdown'\nimport ErrorListTemplate from '../../../../form/ErrorListTemplate'\nimport FieldTemplate from '../../../../form/FieldTemplate'\nimport I18nInput from '../../../../form/I18nInput'\nimport ObjectFieldTemplate from '../../../../form/ObjectFieldTemplate'\nimport Radio from '../../../../form/Radio'\nimport RichText from '../../../../form/RichText'\nimport TextArea from '../../../../form/TextArea'\nimport Toggle from '../../../../form/Toggle'\nimport MediaGalleryWidget from '../../../../MediaGalleryWidget'\nimport { FormDataContainer } from '../../typings'\n\nexport const widgets: Record<string, Widget> = {\n BaseInput,\n CheckboxWidget: Toggle,\n IOMessage: I18nInput,\n RadioWidget: Radio,\n RichText,\n SelectWidget: Dropdown as Widget,\n TextareaWidget: TextArea,\n 'image-uploader': (MediaGalleryWidget as unknown) as Widget,\n}\n\ntype Props = FormProps<FormDataContainer>\nexport default class Form extends React.Component<Props> {\n public shouldComponentUpdate(nextProps: Props) {\n return (\n !equals(this.props.formContext, nextProps.formContext) ||\n !equals(this.props.formData, nextProps.formData)\n )\n }\n\n public render() {\n return (\n <JsonSchemaForm\n schema={this.props.schema}\n formData={this.props.formData}\n onChange={this.props.onChange}\n onSubmit={this.props.onSubmit}\n FieldTemplate={FieldTemplate}\n ArrayFieldTemplate={ArrayFieldTemplate}\n ObjectFieldTemplate={ObjectFieldTemplate}\n uiSchema={this.props.uiSchema}\n widgets={widgets}\n showErrorList\n ErrorList={ErrorListTemplate}\n formContext={this.props.formContext}\n >\n <button className=\"dn\" type=\"submit\" />\n </JsonSchemaForm>\n )\n }\n}\n\n```" } ]
code_admin-pages_53b4c87f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { Tag } from 'vtex.styleguide'\n\nimport ActionMenu from '../../../../../ActionMenu'\nimport { useEditorContext } from '../../../../../EditorContext'\nimport EarthIcon from '../../../../../icons/EarthIcon'\nimport TemplateIcon from '../../../../../icons/TemplateIcon'\nimport { isConfigurationExpired, isConfigurationScheduled } from '../utils'\nimport ConditionTags from './ConditionTags'\nimport StatusLabel from './StatusLabel'\nimport { getGenericContext } from './utils'\nimport styles from './styles.css'\n\ninterface Props {\n configuration: ExtensionConfiguration\n isActive: boolean\n isDefaultContent?: boolean\n isDisabled?: boolean\n isEditing: boolean\n onConfigurationOpen: (configuration: ExtensionConfiguration) => void\n onDelete: (configuration: ExtensionConfiguration) => void\n onConfigurationActivate: (\n configuration: ExtensionConfiguration\n ) => Promise<void>\n}\n\nfunction stopPropagation(e: Pick<Event, 'preventDefault' | 'stopPropagation'>) {\n e.preventDefault()\n e.stopPropagation()\n}\n\nconst messages = defineMessages({\n defaultTitle: {\n defaultMessage: 'Untitled content',\n id: 'admin/pages.editor.configuration.defaultTitle',\n },\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.editor.component-list.action-menu.delete',\n },\n activate: {\n defaultMessage: 'Activate',\n id: 'admin/pages.editor.component-list.action-menu.activate',\n },\n reset: {\n defaultMessage: 'Reset',\n id: 'admin/pages.editor.component-list.action-menu.reset',\n },\n sitewideContext: {\n defaultMessage: 'entire site',\n id: 'admin/pages.editor.configuration.scope.sitewide.context',\n },\n sitewideSaved: {\n defaultMessage: 'Saved on',\n id: 'admin/pages.editor.configuration.scope.sitewide.saved',\n },\n tag: {\n defaultMessage: 'Editing',\n id: 'admin/pages.editor.configuration.tag.editing',\n },\n templateContext: {\n defaultMessage: 'template',\n id: 'admin/pages.editor.configuration.scope.template.context',\n },\n templateSaved: {\n defaultMessage: 'Saved in',\n id: 'admin/pages.editor.configuration.scope.template.saved',\n },\n tooltip: {\n defaultMessage: 'This card is currently being edited.',\n id: 'admin/pages.editor.component-list.action-menu.tooltip',\n },\n})\n\nconst Card = ({\n configuration,\n isActive = false,\n isDefaultContent = false,\n isDisabled = false,\n isEditing = false,\n onConfigurationOpen,\n onDelete,\n onConfigurationActivate,\n}: Props) => {\n const intl = useIntl()\n const editor = useEditorContext()\n\n const handleMainClick = React.useCallback(() => {\n onConfigurationOpen(configuration)\n }, [configuration, onConfigurationOpen])\n\n const handleMainKeyDown = useKeydownFromClick(handleMainClick)\n\n const stopPropagationByKeyDown = useKeydownFromClick(stopPropagation)\n\n const appName = React.useMemo(() => {\n if (!isDefaultContent) {\n return null\n }\n\n const splitOrigin = configuration.origin && configuration.origin.split('@')\n\n return splitOrigin && splitOrigin[0]\n }, [configuration.origin, isDefaultContent])\n\n const conditionPageContext = configuration.condition.pageContext\n\n const conditions = configuration.condition.statements\n\n const scope = React.useMemo(\n () =>\n getGenericContext({\n context: conditionPageContext,\n isSitewide: editor.blockData.isSitewide || false,\n }),\n [conditionPageContext, editor.blockData.isSitewide]\n )\n\n const iconByScope: Record<\n 'sitewide' | 'template',\n JSX.Element\n > = React.useMemo(\n () => ({\n sitewide: <EarthIcon />,\n template: <TemplateIcon />,\n }),\n []\n )\n\n const status = React.useMemo(() => {\n if (isActive) {\n return 'active'\n }\n\n if (\n isConfigurationScheduled(configuration) &&\n !isConfigurationExpired(configuration)\n ) {\n return 'scheduled'\n }\n\n return 'inactive'\n }, [configuration, isActive])\n\n const menuOptions = React.useMemo(\n () => [\n {\n label: intl.formatMessage(messages.activate),\n onClick: async () => {\n await onConfigurationActivate(configuration)\n },\n disabled: isActive,\n },\n {\n isDangerous: true,\n label: intl.formatMessage(\n isDefaultContent ? messages.reset : messages.delete\n ),\n onClick: () => onDelete(configuration),\n },\n ],\n [\n configuration,\n intl,\n isActive,\n isDefaultContent,\n onConfigurationActivate,\n onDelete,\n ]\n )\n\n return (\n <div\n className={`relative mh5 mv5 pa5 br3 bg-action-secondary hover-bg-action-secondary outline-0 ${\n !isDisabled ? 'pointer' : ''\n }`}\n onClick={handleMainClick}\n onKeyDown={handleMainKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <StatusLabel type={status} />\n\n <div className=\"c-on-base\">\n {configuration.label ||\n intl.formatMessage({\n id: 'admin/pages.editor.configuration.defaultTitle',\n })}\n </div>\n\n {conditions.length > 0 && <ConditionTags conditions={conditions} />}\n\n {scope !== 'page' && (\n <div className=\"mt5\">\n <FormattedMessage\n id={`admin/pages.editor.configuration.scope.${scope}.saved`}\n >\n {message => (\n <div className=\"flex items-center\">\n {iconByScope[scope]}\n\n <span className=\"ml2 f6\">\n {message}{' '}\n <FormattedMessage\n id={`admin/pages.editor.configuration.scope.${scope}.context`}\n >\n {message => <span className=\"fw5\">{message}</span>}\n </FormattedMessage>\n </span>\n </div>\n )}\n </FormattedMessage>\n </div>\n )}\n\n {appName && (\n <div className=\"mt5\">\n <FormattedMessage\n defaultMessage=\"Created by {name}\"\n id=\"admin/pages.editor.configuration.createdBy\"\n values={{ name: appName }}\n >\n {message => <div className=\"mt3 f7 c-muted-2\">{message}</div>}\n </FormattedMessage>\n </div>\n )}\n\n <div\n className=\"absolute top-0 right-0 mt1\"\n id=\"action-menu-parent\"\n onClick={stopPropagation}\n onKeyDown={stopPropagationByKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <ActionMenu options={menuOptions} />\n </div>\n\n {isEditing && (\n <div\n className={\n 'absolute bottom-1 right-1 ' +\n styles['editor-configuration-card-tag-editing']\n }\n >\n <Tag size=\"small\">{intl.formatMessage(messages.tag)}</Tag>\n </div>\n )}\n </div>\n )\n}\n\nexport default Card\n\n```" } ]
code_admin-pages_4ba68404
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/StatusLabel.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\n\nimport ContentActiveIcon from '../../../../../icons/ContentActiveIcon'\nimport ContentInactiveIcon from '../../../../../icons/ContentInactiveIcon'\nimport ContentScheduledIcon from '../../../../../icons/ContentScheduledIcon'\n\ninterface Props {\n type: 'active' | 'inactive' | 'scheduled'\n}\n\nconst messages = defineMessages({\n active: {\n defaultMessage: 'Active',\n id: 'admin/pages.editor.component-list.status.active',\n },\n inactive: {\n defaultMessage: 'Inactive',\n id: 'admin/pages.editor.component-list.status.inactive',\n },\n scheduled: {\n defaultMessage: 'Scheduled',\n id: 'admin/pages.editor.component-list.status.scheduled',\n },\n})\n\nconst ICON_BY_STATUS = {\n active: <ContentActiveIcon />,\n inactive: <ContentInactiveIcon />,\n scheduled: <ContentScheduledIcon />,\n}\n\nconst StatusLabel: React.FC<Props> = ({ type }) => {\n const intl = useIntl()\n\n return (\n <div className=\"flex items-center mb3\">\n {ICON_BY_STATUS[type]}\n <div className=\"ml2 ttu f7 fw7\">{intl.formatMessage(messages[type])}</div>\n </div>\n )\n}\n\nexport default StatusLabel\n\n```" } ]
code_admin-pages_07a5a2c9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* This is a temporary hack to remove the hover background from the\nActionMenu */\n#action-menu-parent > div > div > div > button:active,\n#action-menu-parent > div > div > div > button:hover {\n background-color: transparent !important;\n}\n\n.editor-configuration-card-tag-editing > div {\n background: rgba(0, 0, 0, 0.5);\n}\n\n```" } ]
code_admin-pages_e8281d88
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { GetGenericContextArgs } from './typings'\n\nexport const getGenericContext = ({\n context,\n isSitewide,\n}: GetGenericContextArgs) => {\n if (isSitewide) {\n return 'sitewide'\n }\n\n if (context.id === '*') {\n return 'template'\n }\n\n return 'page'\n}\n\n```" } ]
code_admin-pages_cde227c2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface GetGenericContextArgs {\n context: PageContext\n isSitewide: boolean\n}\n\n```" } ]
code_admin-pages_d36674dd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/ConditionTags/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\n\nimport Tag from './Tag'\n\nconst messages = defineMessages({\n from: {\n defaultMessage: 'Start:',\n id: 'admin/pages.editor.configuration.condition.date.from',\n },\n to: {\n defaultMessage: 'End:',\n id: 'admin/pages.editor.configuration.condition.date.to',\n },\n})\n\ninterface Props {\n conditions: ExtensionConfiguration['condition']['statements']\n}\n\nconst ConditionTags: React.FC<Props> = ({ conditions }) => {\n const intl = useIntl()\n\n const format = React.useCallback(\n ({ kind, value }: { kind: ConditionSubject; value: string }) => {\n const textByKind: Record<ConditionSubject, string> = {\n date: `${intl.formatDate(value, {\n day: '2-digit',\n month: '2-digit',\n year: '2-digit',\n })} ${intl.formatTime(value)}`,\n // TODO\n utm: '',\n }\n\n return textByKind[kind]\n },\n [intl]\n )\n\n return (\n <div className=\"mt5\">\n {conditions.map(item => {\n const parsedConditionObj: Record<string, string> = JSON.parse(\n item.objectJSON\n )\n\n if (!parsedConditionObj) {\n return null\n }\n\n return Object.entries(parsedConditionObj).reduce<JSX.Element[]>(\n (acc, [key, value]) => {\n const tagTitle = messages[key as keyof typeof messages]\n\n if (!tagTitle) {\n return acc\n }\n\n return [\n ...acc,\n <div className=\"mt3\" key={key}>\n <Tag\n kind={item.subject}\n text={format({ kind: item.subject, value })}\n title={intl.formatMessage({\n id: tagTitle.id,\n })}\n />\n </div>,\n ]\n },\n []\n )\n })}\n </div>\n )\n}\n\nexport default ConditionTags\n\n```" } ]
code_admin-pages_fafaaf67
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationList/Card/ConditionTags/Tag.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Tag as StyleguideTag } from 'vtex.styleguide'\n\nimport CalendarIcon from '../../../../../../icons/CalendarIcon'\nimport PersonIcon from '../../../../../../icons/PersonIcon'\n\ninterface Props {\n kind: ConditionSubject\n text: string\n title: string\n}\n\nconst iconByKind = {\n date: <CalendarIcon />,\n utm: <PersonIcon />,\n}\n\nconst Tag: React.FunctionComponent<Props> = ({ kind, text, title }) => (\n <StyleguideTag bgColor=\"#FFFFFF\" color=\"#727273\">\n <div className=\"flex items-center\">\n {iconByKind[kind]}\n\n <span className=\"mh2 fw5\">{title}</span>\n\n <span className=\"fw4\">{text}</span>\n </div>\n </StyleguideTag>\n)\n\nexport default React.memo(Tag)\n\n```" } ]
code_admin-pages_626db5df
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { PureComponent } from 'react'\n\nimport { ConfigurationStatus } from '../..'\nimport { formatStatements } from '../../../../../../utils/conditions'\nimport { isUnidentifiedPageContext } from '../../../utils'\nimport Scheduler from './Scheduler'\nimport ScopeSelector from './ScopeSelector'\nimport Separator from './Separator'\nimport Typings from './typings'\n\ninterface Props {\n condition: ExtensionConfiguration['condition']\n isSitewide: boolean\n onConditionChange: (\n changes: Partial<ExtensionConfiguration['condition']>\n ) => void\n pageContext: RenderRuntime['route']['pageContext']\n statusFromRuntime: ConfigurationStatus\n status: ConfigurationStatus\n}\n\nclass ConditionControls extends PureComponent<Props> {\n private isScopeDisabled =\n this.props.isSitewide || isUnidentifiedPageContext(this.props.pageContext)\n\n public render() {\n const { condition, isSitewide, pageContext, status } = this.props\n\n const scope = isSitewide\n ? 'sitewide'\n : condition.pageContext.id === '*'\n ? 'template'\n : 'entity'\n\n return (\n <div className=\"ph5\">\n <Scheduler\n status={status}\n onConditionUpdate={this.handleDateChange}\n initialValues={this.getDatesInitialValues()}\n />\n\n <div className=\"mv7\">\n <ScopeSelector\n isDisabled={this.isScopeDisabled}\n isSitewide={isSitewide}\n onChange={this.handleScopeChange}\n pageContext={pageContext}\n scope={scope}\n />\n\n <Separator />\n </div>\n </div>\n )\n }\n\n private getDatesInitialValues = () => {\n const { condition } = this.props\n\n const statement = condition.statements[0]\n\n const object = statement && JSON.parse(statement.objectJSON)\n\n const initialValues = object && {\n from: object.from && new Date(object.from),\n to: object.to && new Date(object.to),\n }\n\n return initialValues\n }\n\n private getPageContextFromScope(scope: ConfigurationScope): PageContext {\n const { pageContext } = this.props\n\n if (['sitewide', 'template'].includes(scope)) {\n return { id: '*', type: '*' }\n }\n\n return pageContext\n }\n\n private handleDateChange = (dates: Typings.DateRange) => {\n const object =\n dates.from || dates.to\n ? {\n ...(dates.from && dates.to\n ? dates\n : { date: dates.from || dates.to }),\n }\n : null\n\n const verb = object\n ? (dates.from && dates.to && 'between') || (dates.from && 'from') || 'to'\n : null\n\n const statements =\n object && verb\n ? formatStatements([\n {\n error: null,\n object,\n subject: 'date',\n verb,\n },\n ])\n : []\n\n this.props.onConditionChange({\n statements,\n })\n }\n\n private handleScopeChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n const { condition, onConditionChange } = this.props\n\n const newPageContext = this.getPageContextFromScope(\n event.target.value as ConfigurationScope\n )\n\n if (\n newPageContext.id !== condition.pageContext.id ||\n newPageContext.type !== condition.pageContext.type\n ) {\n onConditionChange({\n pageContext: newPageContext,\n })\n }\n }\n}\n\nexport default ConditionControls\n\n```" } ]
code_admin-pages_8ed9e909
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface DateRange {\n from?: Date\n to?: Date\n}\n\n```" } ]
code_admin-pages_32fe4cff
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/Scheduler.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { defineMessages, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport { Checkbox, DatePicker } from 'vtex.styleguide'\n\nimport { ConfigurationStatus } from '../..'\nimport {\n getFirstTime,\n getLastTime,\n getNextDay,\n getNextTime,\n getPreviousTime,\n isLastTime,\n isSameDay,\n} from '../../../../../../utils/date'\nimport Typings from './typings'\n\ninterface CustomProps {\n initialValues?: Typings.DateRange\n onConditionUpdate: (dates: Typings.DateRange) => void\n status: ConfigurationStatus\n}\n\ntype Props = CustomProps & InjectedIntlProps & RenderContextProps\n\ninterface State extends Typings.DateRange {\n fromMinTime: Date\n shouldDisplayFrom: boolean\n shouldDisplayTo: boolean\n toMinTime: Date\n}\n\nconst messages = defineMessages({\n dateTitle: {\n defaultMessage: 'Custom date',\n id: 'admin/pages.editor.components.condition.date.title',\n },\n toggleEnd: {\n defaultMessage: 'Set an end date',\n id: 'admin/pages.editor.components.condition.date.toggle.end',\n },\n toggleStart: {\n defaultMessage: 'Set a start date',\n id: 'admin/pages.editor.components.condition.date.toggle.start',\n },\n})\n\nclass Scheduler extends Component<Props, State> {\n private currDate: Date\n private defaultMaxTime: Date\n private defaultMinTime: Date\n private minDate: Date\n\n private initialState: State\n\n public constructor(props: Props) {\n super(props)\n\n this.currDate = new Date()\n\n this.defaultMaxTime = getLastTime(this.currDate)\n this.defaultMinTime = getFirstTime(this.currDate)\n\n const initialTimeLimit = this.currDate\n\n this.minDate = isLastTime(initialTimeLimit)\n ? getNextDay(this.currDate)\n : this.currDate\n\n const fromMinTime = getNextTime(initialTimeLimit)\n const toMinTime = getNextTime(fromMinTime)\n\n const from = props.initialValues && props.initialValues.from\n const to = props.initialValues && props.initialValues.to\n\n this.initialState = {\n from,\n fromMinTime,\n shouldDisplayFrom: !!from,\n shouldDisplayTo: !!to,\n to,\n toMinTime,\n }\n\n this.state = this.initialState\n }\n\n public render() {\n const { intl, runtime: iframeRuntime, status } = this.props\n\n return (\n <>\n <Checkbox\n checked={this.state.shouldDisplayFrom}\n disabled={status === ConfigurationStatus.ACTIVE}\n label={intl.formatMessage(messages.toggleStart)}\n onChange={this.handleFromVisibilityToggle}\n />\n\n {this.state.shouldDisplayFrom && (\n <div className=\"flex mt4\">\n <DatePicker\n align=\"right\"\n dateRangeStart={this.state.from}\n dateRangeEnd={this.state.to}\n direction=\"up\"\n isRangeStart\n locale={iframeRuntime.culture.locale}\n maxTime={this.defaultMaxTime}\n minDate={this.minDate}\n minTime={this.state.fromMinTime}\n onChange={this.handleFromChange}\n positionFixed\n useTime\n value={this.state.from}\n />\n </div>\n )}\n\n <div className=\"mt6\" />\n\n <Checkbox\n checked={this.state.shouldDisplayTo}\n label={intl.formatMessage(messages.toggleEnd)}\n onChange={this.handleToVisibilityToggle}\n />\n\n {this.state.shouldDisplayTo && (\n <div className=\"flex mt4\">\n <DatePicker\n align=\"right\"\n dateRangeStart={this.state.from}\n dateRangeEnd={this.state.to}\n direction=\"up\"\n isRangeEnd\n locale={iframeRuntime.culture.locale}\n maxTime={this.defaultMaxTime}\n minDate={this.minDate}\n minTime={this.state.toMinTime}\n onChange={this.handleToChange}\n positionFixed\n useTime\n value={this.state.to}\n />\n </div>\n )}\n </>\n )\n }\n\n private getConditionUpdater = (dates: Typings.DateRange) => () => {\n this.props.onConditionUpdate({\n from: dates.from || this.state.from,\n to: dates.to || this.state.to,\n })\n }\n\n private handleFromChange = (from: Date) => {\n if (from < this.initialState.fromMinTime) {\n from.setTime(this.initialState.fromMinTime.getTime())\n }\n\n const to =\n this.state.to && from > this.state.to ? getNextTime(from) : this.state.to\n\n this.setState(\n {\n from,\n fromMinTime: isSameDay(from, this.currDate)\n ? this.initialState.fromMinTime\n : this.defaultMinTime,\n to,\n },\n this.getConditionUpdater({ from, to })\n )\n }\n\n private handleToChange = (to: Date) => {\n const isToToday = isSameDay(to, this.currDate)\n\n if (to < this.initialState.toMinTime) {\n to.setTime(this.initialState.toMinTime.getTime())\n }\n\n const from =\n this.state.from && to < this.state.from\n ? getPreviousTime(to)\n : this.state.from\n\n this.setState(\n {\n from,\n fromMinTime: isSameDay(from, this.currDate)\n ? this.initialState.fromMinTime\n : this.defaultMinTime,\n to,\n toMinTime: isToToday\n ? this.initialState.toMinTime\n : this.defaultMinTime,\n },\n this.getConditionUpdater({ from, to })\n )\n }\n\n private handleFromVisibilityToggle = () => {\n if (this.state.from) {\n const from = undefined\n\n this.setState(\n {\n from,\n shouldDisplayFrom: false,\n },\n this.getConditionUpdater({ from })\n )\n } else {\n this.handleFromChange(this.initialState.fromMinTime)\n\n this.setState({ shouldDisplayFrom: true })\n }\n }\n\n private handleToVisibilityToggle = () => {\n if (this.state.to) {\n const to = undefined\n\n this.setState(\n {\n shouldDisplayTo: false,\n to,\n },\n this.getConditionUpdater({ to })\n )\n } else {\n const initialValue = this.state.from\n ? getNextTime(this.state.from)\n : this.initialState.toMinTime\n\n this.handleToChange(initialValue)\n\n this.setState({ shouldDisplayTo: true })\n }\n }\n}\n\nexport default injectIntl(withRuntimeContext(Scheduler))\n\n```" } ]
code_admin-pages_c948f4f9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/Separator.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst Separator: React.FunctionComponent = () => <div className=\"mv7\" />\n\nexport default Separator\n\n```" } ]
code_admin-pages_62800790
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/ConditionTitle.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\ninterface Props {\n labelId: string\n}\n\nconst ConditionTitle: React.FunctionComponent<Props> = ({ labelId }) => (\n <FormattedMessage id={labelId}>\n {message => <div className=\"mb6\">{message}</div>}\n </FormattedMessage>\n)\n\nexport default React.memo(ConditionTitle)\n\n```" } ]
code_admin-pages_4d735bbb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/ScopeSelector/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment, useMemo } from 'react'\nimport { FormattedMessage, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { RadioGroup } from 'vtex.styleguide'\n\nimport { getScopeStandardOptions } from './utils'\n\ninterface CustomProps {\n isDisabled: boolean\n isSitewide: boolean\n onChange: (event: React.ChangeEvent<HTMLInputElement>) => void\n pageContext: PageContext\n scope: ConfigurationScope\n}\n\ntype Props = CustomProps & InjectedIntlProps\n\nconst ScopeSelector: React.FunctionComponent<Props> = ({\n intl,\n isDisabled,\n isSitewide,\n onChange,\n pageContext,\n scope,\n}) => {\n const standardOptions = getScopeStandardOptions(intl, pageContext)\n const options = useMemo(\n () =>\n isSitewide\n ? [\n {\n label: intl.formatMessage({\n id: 'admin/pages.editor.components.condition.scope.sitewide',\n }),\n value: 'sitewide',\n },\n ]\n : standardOptions,\n [intl, isSitewide, standardOptions]\n )\n\n return (\n <Fragment>\n <FormattedMessage id=\"admin/pages.editor.components.condition.scope.title\">\n {message => <div className=\"mb5\">{message}</div>}\n </FormattedMessage>\n <RadioGroup\n hideBorder\n disabled={isDisabled}\n name=\"scopes\"\n onChange={onChange}\n options={options}\n value={scope}\n />\n </Fragment>\n )\n}\n\nexport default React.memo(injectIntl(ScopeSelector))\n\n```" } ]
code_admin-pages_49f2fc2f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/ScopeSelector/ScopeSelector.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 { RadioGroup } from 'vtex.styleguide'\n\nimport ConditionTitle from '../ConditionTitle'\nimport { getScopeStandardOptions } from './utils'\n\ninterface CustomProps {\n onChange: (event: React.ChangeEvent<HTMLInputElement>) => void\n pageContext: PageContext\n scope: ConfigurationScope\n isSitewide: boolean\n}\n\ntype Props = CustomProps & InjectedIntlProps\n\nconst ScopeSelector: React.FunctionComponent<Props> = ({\n intl,\n isSitewide,\n onChange,\n pageContext,\n scope,\n}) => {\n const standardOptions = getScopeStandardOptions(intl, pageContext)\n\n return (\n <Fragment>\n <ConditionTitle labelId=\"admin/pages.editor.components.condition.scope.title\" />\n\n <RadioGroup\n disabled={isSitewide}\n name=\"scopes\"\n onChange={onChange}\n options={\n isSitewide\n ? [\n {\n label: intl.formatMessage({\n id:\n 'admin/pages.editor.components.condition.scope.sitewide',\n }),\n value: 'sitewide',\n },\n ]\n : standardOptions\n }\n value={scope}\n hideBorder\n />\n </Fragment>\n )\n}\n\nexport default injectIntl(ScopeSelector)\n\n```" } ]
code_admin-pages_33c372e5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockEditor/BlockConfigurationEditor/ConditionControls/ScopeSelector/utils.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { defineMessages, IntlShape } from 'react-intl'\n\n// Messages used in getScopeStandardOptions\ndefineMessages({\n brand: {\n defaultMessage: 'this brand',\n id: 'admin/pages.editor.components.condition.scope.entity.brand',\n },\n category: {\n defaultMessage: 'this category',\n id: 'admin/pages.editor.components.condition.scope.entity.category',\n },\n department: {\n defaultMessage: 'this department',\n id: 'admin/pages.editor.components.condition.scope.entity.department',\n },\n product: {\n defaultMessage: 'this product',\n id: 'admin/pages.editor.components.condition.scope.entity.product',\n },\n route: {\n defaultMessage: 'this URL',\n id: 'admin/pages.editor.components.condition.scope.entity.route',\n },\n search: {\n defaultMessage: 'this search',\n id: 'admin/pages.editor.components.condition.scope.entity.search',\n },\n sitewide: {\n defaultMessage: 'the entire site',\n id: 'admin/pages.editor.components.condition.scope.sitewide',\n },\n subcategory: {\n defaultMessage: 'this subcategory',\n id: 'admin/pages.editor.components.condition.scope.entity.subcategory',\n },\n template: {\n defaultMessage: 'this template',\n id: 'admin/pages.editor.components.condition.scope.template',\n },\n title: {\n defaultMessage: 'Apply to',\n id: 'admin/pages.editor.components.condition.scope.title',\n },\n})\n\nexport const getScopeStandardOptions = (\n intl: IntlShape,\n pageContext: PageContext\n) => [\n {\n label: intl.formatMessage({\n id: `admin/pages.editor.components.condition.scope.entity.${\n pageContext.type.startsWith('$') ? 'custom' : pageContext.type\n }`,\n }),\n value: 'entity',\n },\n {\n label: intl.formatMessage({\n id: 'admin/pages.editor.components.condition.scope.template',\n }),\n value: 'template',\n },\n]\n\n```" } ]
code_admin-pages_6dd30f2a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/Enter/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { CSSTransition } from 'react-transition-group'\n\nimport { COMMON_PROPS } from '../consts'\nimport { EnterProps } from '../typings'\nimport styles from './styles.css'\n\nconst Enter: React.FC<EnterProps> = ({ children, condition, from }) => (\n <CSSTransition\n {...COMMON_PROPS}\n appear\n classNames={{\n appear: styles[`transition-editor-enter-${from}`],\n appearActive: styles[`transition-editor-enter-${from}-active`],\n enter: styles[`transition-editor-enter-${from}`],\n enterActive: styles[`transition-editor-enter-${from}-active`],\n }}\n in={condition}\n mountOnEnter\n >\n {children}\n </CSSTransition>\n)\n\nexport default React.memo(Enter)\n\n```" } ]
code_admin-pages_86ae13e6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/Enter/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.transition-editor-enter-left {\n transform: translateX(-18em);\n}\n\n.transition-editor-enter-left-active {\n transition: transform 250ms ease-in;\n transform: translateX(0);\n}\n\n.transition-editor-enter-right {\n transform: translateX(18em);\n}\n\n.transition-editor-enter-right-active {\n transition: transform 250ms ease-in;\n transform: translateX(0);\n}\n\n```" } ]
code_admin-pages_1940d9de
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/Exit/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { CSSTransition } from 'react-transition-group'\n\nimport { COMMON_PROPS } from '../consts'\nimport { ExitProps } from '../typings'\nimport styles from './styles.css'\n\nconst Exit: React.FC<ExitProps> = ({ children, condition, to }) => (\n <CSSTransition\n {...COMMON_PROPS}\n classNames={{\n exit: styles[`transition-editor-exit-${to}`],\n exitActive: styles[`transition-editor-exit-${to}-active`],\n exitDone: styles[`transition-editor-exit-${to}-done`],\n }}\n in={!condition}\n unmountOnExit\n >\n {children}\n </CSSTransition>\n)\n\nexport default React.memo(Exit)\n\n```" } ]
code_admin-pages_2a23c8a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/Transitions/Exit/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.transition-editor-exit-left {\n transform: translateX(0);\n}\n\n.transition-editor-exit-left-active {\n transition: transform 250ms ease-in;\n transform: translateX(-18em);\n}\n\n.transition-editor-exit-left-done {\n transform: translateX(-18em);\n}\n\n.transition-editor-exit-right {\n transform: translateX(0);\n}\n\n.transition-editor-exit-right-active {\n transition: transform 250ms ease-in;\n transform: translateX(18em);\n}\n\n.transition-editor-exit-right-done {\n transform: translateX(18em);\n}\n\n```" } ]
code_admin-pages_880fe0a1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/__fixtures__/components.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ComponentsRegistry } from 'vtex.render-runtime'\n\nconst COMPONENTS: ComponentsRegistry = {\n 'vtex.carousel@2.10.2/Carousel': {\n getSchema: () => ({\n description: 'admin/editor.carousel.description',\n dependencies: {\n autoplay: {\n oneOf: [\n {\n properties: {\n autoplay: {\n enum: [true],\n },\n autoplaySpeed: {\n enum: ['2', '3', '4', '5', '6', '7', '8'],\n isLayout: false,\n title: 'admin/editor.carousel.autoplaySpeed.title',\n type: 'string',\n },\n },\n },\n ],\n },\n },\n properties: {\n banners: {\n items: {\n properties: {\n description: {\n default: '',\n title: 'admin/editor.carousel.banner.description.title',\n type: 'string',\n },\n externalRoute: {\n default: false,\n isLayout: false,\n title: 'admin/editor.carousel.banner.externalRoute.title',\n type: 'boolean',\n },\n url: {\n isLayout: false,\n title: 'admin/editor.carousel.bannerLink.url.title',\n type: 'string',\n },\n page: {\n enum: [\n 'store.lists',\n 'store.custom#about-us',\n 'store.home',\n 'store.account',\n 'store.login',\n 'store.product',\n 'store.search',\n 'store.search#brand',\n 'store.search#department',\n 'store.search#category',\n 'store.search#subcategory',\n 'store.search#subcategory-terms',\n 'store.search#custom',\n 'store.search#configurable',\n 'store.orderplaced',\n 'vtex.store@2.x:store.custom#foo',\n 'vtex.store@2.x:store.custom#renato',\n ],\n isLayout: false,\n title: 'admin/editor.carousel.bannerLink.page.title',\n type: 'string',\n },\n params: {\n description:\n 'admin/editor.carousel.bannerLink.params.description',\n isLayout: false,\n title: 'admin/editor.carousel.bannerLink.params.title',\n type: 'string',\n },\n image: {\n default: '',\n title: 'admin/editor.carousel.banner.image.title',\n type: 'string',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n mobileImage: {\n default: '',\n title: 'admin/editor.carousel.banner.mobileImage.title',\n type: 'string',\n widget: {\n 'ui:widget': 'image-uploader',\n },\n },\n },\n title: 'admin/editor.carousel.banner.title',\n type: 'object',\n },\n minItems: 1,\n title: 'admin/editor.carousel.banners.title',\n type: 'array',\n },\n height: {\n default: 420,\n enum: [420, 440],\n isLayout: true,\n title: 'admin/editor.carousel.height.title',\n type: 'number',\n },\n showArrows: {\n default: true,\n isLayout: true,\n title: 'admin/editor.carousel.showArrows.title',\n type: 'boolean',\n },\n showDots: {\n default: true,\n isLayout: true,\n title: 'admin/editor.carousel.showDots.title',\n type: 'boolean',\n },\n autoplay: {\n default: true,\n isLayout: false,\n title: 'admin/editor.carousel.autoplay.title',\n type: 'boolean',\n },\n },\n title: 'admin/editor.carousel.title',\n type: 'object',\n }),\n },\n 'vtex.product-summary@2.31.0/ProductSummaryCustom': {\n getSchema: () => ({\n title: 'admin/editor.productSummary.title',\n description: 'admin/editor.productSummary.description',\n }),\n },\n 'vtex.shelf@1.25.0/Shelf': {\n getSchema: () => ({\n title: 'admin/editor.shelf.title',\n description: 'admin/editor.shelf.description',\n type: 'object',\n properties: {\n category: {\n title: 'admin/editor.shelf.category.title',\n description: 'admin/editor.shelf.category.description',\n type: 'string',\n isLayout: false,\n },\n specificationFilters: {\n title: 'admin/editor.shelf.specificationFilters.title',\n type: 'array',\n items: {\n title: 'admin/editor.shelf.specificationFilters.item.title',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n title: 'admin/editor.shelf.specificationFilters.item.id.title',\n },\n value: {\n type: 'string',\n title:\n 'admin/editor.shelf.specificationFilters.item.value.title',\n },\n },\n },\n },\n collection: {\n title: 'admin/editor.shelf.collection.title',\n type: 'number',\n isLayout: false,\n },\n orderBy: {\n title: 'admin/editor.shelf.orderBy.title',\n type: 'string',\n enum: [\n '',\n 'OrderByTopSaleDESC',\n 'OrderByPriceDESC',\n 'OrderByPriceASC',\n 'OrderByNameASC',\n 'OrderByNameDESC',\n 'OrderByReleaseDateDESC',\n 'OrderByBestDiscountDESC',\n ],\n enumNames: [\n 'admin/editor.shelf.orderType.relevance',\n 'admin/editor.shelf.orderType.sales',\n 'admin/editor.shelf.orderType.priceDesc',\n 'admin/editor.shelf.orderType.priceAsc',\n 'admin/editor.shelf.orderType.nameAsc',\n 'admin/editor.shelf.orderType.nameDesc',\n 'admin/editor.shelf.orderType.releaseDate',\n 'admin/editor.shelf.orderType.discount',\n ],\n default: '',\n isLayout: false,\n },\n productList: {\n title: 'admin/editor.shelf.title',\n description: 'admin/editor.shelf.description',\n type: 'object',\n properties: {\n maxItems: {\n title: 'admin/editor.shelf.maxItems.title',\n type: 'number',\n default: 10,\n isLayout: true,\n },\n gap: {\n title: 'admin/editor.shelf.gap.title',\n type: 'string',\n enum: ['ph0', 'ph3', 'ph5', 'ph7'],\n enumNames: [\n 'admin/editor.shelf.gapType.none',\n 'admin/editor.shelf.gapType.small',\n 'admin/editor.shelf.gapType.medium',\n 'admin/editor.shelf.gapType.large',\n ],\n default: 'ph3',\n isLayout: true,\n },\n itemsPerPage: {\n title: 'admin/editor.shelf.itemsPerPage.title',\n type: 'number',\n enum: [3, 4, 5],\n default: 5,\n isLayout: true,\n },\n scroll: {\n title: 'admin/editor.shelf.scrollType.title',\n type: 'string',\n enum: ['BY_PAGE', 'ONE_BY_ONE'],\n enumNames: [\n 'admin/editor.shelf.scrollType.byPage',\n 'admin/editor.shelf.scrollType.oneByOne',\n ],\n default: 'BY_PAGE',\n isLayout: true,\n },\n arrows: {\n title: 'admin/editor.shelf.arrows.title',\n type: 'boolean',\n default: true,\n isLayout: true,\n },\n showTitle: {\n title: 'admin/editor.shelf.titleText.showTitle',\n type: 'boolean',\n default: true,\n isLayout: true,\n },\n },\n },\n hideUnavailableItems: {\n title: 'admin/editor.shelf.hideUnavailableItems',\n type: 'boolean',\n default: false,\n isLayout: false,\n },\n },\n }),\n },\n}\n\nexport default COMPONENTS\n\n```" } ]
code_admin-pages_20b52a33
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/BlockList/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { useEditorContext } from '../../../../EditorContext'\nimport { NormalizedBlock } from '../typings'\nimport BlockListItem from './BlockListItem'\n\ninterface Props {\n blocks: NormalizedBlock[]\n highlightHandler: (treePath: string | null) => void\n iframeRuntime: RenderContextProps['runtime']\n onMouseEnterBlock: (\n event: React.MouseEvent<HTMLDivElement | HTMLLIElement>\n ) => void\n onMouseLeaveBlock: () => void\n}\n\nconst BlockList: React.FC<Props> = ({\n blocks,\n highlightHandler,\n onMouseEnterBlock,\n onMouseLeaveBlock,\n}) => {\n const editor = useEditorContext()\n\n const handleEdit = React.useCallback(\n (block: NormalizedBlock) => {\n if (block.isEditable) {\n editor.editExtensionPoint(block.treePath)\n\n editor.setIsLoading(true)\n\n highlightHandler(null)\n }\n },\n [editor, highlightHandler]\n )\n\n return (\n <ul className=\"mv0 pl0 overflow-y-auto\">\n {blocks.map((block, index) => (\n <BlockListItem\n block={block}\n key={`${block.treePath}-${index}`}\n onEdit={handleEdit}\n onMouseEnter={onMouseEnterBlock}\n onMouseLeave={onMouseLeaveBlock}\n />\n ))}\n </ul>\n )\n}\n\nexport default BlockList\n\n```" } ]
code_admin-pages_0790e448
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/BlockList/BlockListItem/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { NormalizedBlock } from '../../typings'\nimport ExpandArrow from './ExpandArrow'\nimport Item from './Item'\n\ninterface Props {\n block: NormalizedBlock\n onEdit: (block: NormalizedBlock) => void\n onMouseEnter: (\n event: React.MouseEvent<HTMLDivElement | HTMLLIElement>\n ) => void\n onMouseLeave: () => void\n}\n\nconst BlockListItem: React.FC<Props> = ({\n block,\n onEdit,\n onMouseEnter,\n onMouseLeave,\n}) => {\n const [isExpanded, setIsExpanded] = React.useState(false)\n\n const handleClick = React.useCallback(() => {\n onEdit(block)\n }, [block, onEdit])\n\n const handleExpansionToggle = React.useCallback(() => {\n setIsExpanded(!isExpanded)\n }, [isExpanded])\n\n const subitems = block.components || []\n const hasSubitems = subitems.length > 0\n\n return (\n <>\n <div\n className=\"flex items-center bb bg-white b--light-silver\"\n data-tree-path={block.treePath}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n >\n {hasSubitems && (\n <ExpandArrow\n isExpanded={isExpanded}\n onClick={handleExpansionToggle}\n />\n )}\n\n <Item\n hasSubitems={hasSubitems}\n isEditable={block.isEditable}\n onEdit={handleClick}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n title={block.name}\n treePath={block.treePath}\n />\n </div>\n {isExpanded && subitems && (\n <div className=\"mv0 pl0\">\n {subitems.map((item, index) => (\n <div\n className=\"flex bg-white hover-bg-light-silver list\"\n data-tree-path={item.treePath}\n key={item.treePath}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n >\n <div className=\"bl bw2 b--light-blue\" />\n\n <div\n className={`w-100 ${\n index !== subitems.length - 1 ? 'bb b--light-silver ' : ''\n }`}\n >\n <BlockListItem\n block={item}\n onEdit={onEdit}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n />\n </div>\n </div>\n ))}\n\n <div className=\"bb b--light-silver\" />\n </div>\n )}\n </>\n )\n}\n\nexport default BlockListItem\n\n```" } ]
code_admin-pages_0246476e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/BlockList/BlockListItem/Item.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { formatIOMessage } from 'vtex.native-types'\n\nimport styles from './Item.css'\n\ninterface Props {\n hasSubitems?: boolean\n isEditable: boolean\n onEdit: () => void\n onMouseEnter: (event: React.MouseEvent<HTMLDivElement>) => void\n onMouseLeave: (event: React.MouseEvent<HTMLDivElement>) => void\n title: string\n treePath: string\n}\n\nconst messages = defineMessages({\n untitledBlock: {\n defaultMessage: 'Untitled Block',\n id: 'admin/pages.editor.component-list.untitled',\n },\n})\n\nconst Item: React.FunctionComponent<Props> = ({\n hasSubitems,\n isEditable,\n onEdit,\n onMouseEnter,\n onMouseLeave,\n title,\n treePath,\n}) => {\n const intl = useIntl()\n const handleKeyDown = useKeydownFromClick(onEdit)\n\n const leftPaddingClassName = hasSubitems ? 'pl2' : 'pl8'\n\n return (\n <div\n className={classnames(\n 'w-100 pv5 pr0 dark-gray bg-inherit tl outline-0',\n leftPaddingClassName,\n {\n 'hover-bg-light-silver': isEditable,\n }\n )}\n data-tree-path={treePath}\n key={treePath}\n onClick={onEdit}\n onKeyDown={handleKeyDown}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n role=\"treeitem\"\n style={{\n ...{ animationDuration: '0.2s' },\n ...(!hasSubitems ? { marginLeft: 1 } : null),\n ...{ cursor: isEditable ? 'pointer' : 'default' },\n }}\n tabIndex={0}\n >\n <span className={`f6 fw4 ${styles['track-1']} pl2`}>\n {typeof title === 'string' ? (\n formatIOMessage({ id: title, intl })\n ) : (\n <i>{intl.formatMessage(messages.untitledBlock)}</i>\n )}\n </span>\n </div>\n )\n}\n\nexport default Item\n\n```" } ]
code_admin-pages_74c3d91a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/BlockList/BlockListItem/ExpandArrow/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\n\nimport ArrowIcon from '../../../../../../icons/ArrowIcon'\nimport styles from './styles.css'\n\ninterface Props {\n isExpanded: boolean\n onClick: () => void\n}\n\nconst ExpandArrow: React.FC<Props> = ({ isExpanded, onClick }) => {\n const handleKeyDown = useKeydownFromClick(onClick)\n\n return (\n <div\n className=\"flex items-center ph3 pv5 bg-inherit c-muted-3 hover-bg-light-silver hover-black-90 outline-0 pointer\"\n onClick={onClick}\n onKeyDown={handleKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <div className=\"flex items-center ph4 color-inherit\">\n <div\n className={classnames('color-inherit', styles.transition, {\n 'rotate-90': isExpanded,\n })}\n >\n <ArrowIcon />\n </div>\n </div>\n </div>\n )\n}\n\nexport default ExpandArrow\n\n```" } ]
code_admin-pages_15a77fe6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Sidebar/BlockSelector/BlockList/BlockListItem/ExpandArrow/styles.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.transition {\n transition-property: transform, color;\n transition-duration: 200ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n```" } ]
code_admin-pages_11e23f8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { find, zip } from 'ramda'\nimport React, { useState } from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { ButtonWithIcon, Spinner, ToastConsumer } from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport Operations from './Operations'\nimport CreateNewIcon from './icons/CreateNewIcon'\nimport StyleCard from './StyleCard'\nimport { createEventObject } from '../../../../utils/auditEvents'\nimport SendEventToAuditMutation from '../../mutations/SendEventToAudit'\n\ninterface Props {\n startEditing: (style: Style) => void\n setStyleAsset: (asset: StyleAssetInfo) => void\n}\n\nconst compareStyles = (a: Style, b: Style) => {\n const toArray = ({ selected, editable, app, name, id }: Style) => {\n return [selected ? 0 : 1, editable ? 0 : 1, app, name, id]\n }\n return zip(toArray(a), toArray(b)).reduce((acc, [value1, value2]) => {\n if (acc !== 0) {\n return acc\n }\n if (value1 < value2) {\n return -1\n }\n if (value1 > value2) {\n return 1\n }\n return acc\n }, 0)\n}\n\nconst messages = defineMessages({\n defaultName: {\n defaultMessage: 'Untitled',\n id: 'admin/pages.editor.styles.new.defaultName',\n },\n deleteFail: {\n defaultMessage: 'Failed to delete style.',\n id: 'admin/pages.editor.styles.card.menu.delete.fail',\n },\n deleteSuccess: {\n defaultMessage: `Style '{name}' was deleted.`,\n id: 'admin/pages.editor.styles.select.delete-success',\n },\n duplicateDefaultName: {\n defaultMessage: 'Copy of {name}',\n id: 'admin/pages.editor.styles.duplicate.defaultName',\n },\n duplicateFail: {\n defaultMessage: `Failed to duplicate style '{name}'.`,\n id: 'admin/pages.editor.styles.card.menu.duplicate.fail',\n },\n duplicateSuccess: {\n defaultMessage: `Style '{name}' was duplicated.`,\n id: 'admin/pages.editor.styles.card.menu.duplicate.success',\n },\n newFail: {\n defaultMessage: 'Failed to create new style.',\n id: 'admin/pages.editor.styles.new.fail',\n },\n newSuccess: {\n defaultMessage: 'New style created.',\n id: 'admin/pages.editor.styles.new.success',\n },\n saveFail: {\n defaultMessage: `Failed to select style '{name}'.`,\n id: 'admin/pages.editor.styles.select.save-fail',\n },\n saveSuccess: {\n defaultMessage: `Style '{name}' was selected.`,\n id: 'admin/pages.editor.styles.select.save-success',\n },\n undo: {\n defaultMessage: 'Undo',\n id: 'admin/pages.editor.styles.select.delete.toast.undo',\n },\n})\n\nconst StyleList: React.FunctionComponent<Props> = ({\n startEditing,\n setStyleAsset,\n}) => {\n const intl = useIntl()\n const [isCreatingStyle, setIsCreatingStyle] = useState(false)\n const { account, workspace } = useRuntime()\n\n return (\n <Operations>\n {({\n listStyles: { data, loading },\n saveSelectedStyle,\n createStyle,\n deleteStyle,\n }) => {\n const unsortedStyles = data && data.listStyles\n const listStyles = unsortedStyles && unsortedStyles.sort(compareStyles)\n\n const selected = listStyles && find(style => style.selected, listStyles)\n if (selected && !loading) {\n setStyleAsset({ type: 'path', selected: true, value: selected.path })\n }\n\n return loading ? (\n <div className=\"pt7 flex justify-around\">\n <Spinner />\n </div>\n ) : (\n <SendEventToAuditMutation>\n {sendEventToAudit => (\n <ToastConsumer>\n {({ showToast }) => (\n <section className=\"flex flex-column ph3 h-100 overflow-x-hidden\">\n <header className=\"flex justify-between pv5 pl5 items-center flex-shrink-0 bg-white z-1\">\n <h1 className=\"f3 fw4\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.header.title\"\n defaultMessage=\"Styles\"\n />\n </h1>\n <ButtonWithIcon\n icon={<CreateNewIcon />}\n variation=\"tertiary\"\n isLoading={isCreatingStyle}\n onClick={() => {\n setIsCreatingStyle(true)\n createStyle({\n variables: {\n name: intl.formatMessage(messages.defaultName),\n },\n })\n .then(() => {\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.newSuccess\n ),\n })\n const event = createEventObject(\n 'Create new style',\n 'style',\n account,\n workspace\n )\n sendEventToAudit({\n variables: { input: event },\n })\n })\n .catch(e => {\n console.error(e)\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(messages.newFail),\n })\n })\n .finally(() => setIsCreatingStyle(false))\n }}\n >\n <FormattedMessage\n id=\"admin/pages.editor.styles.new-button.text\"\n defaultMessage=\"new\"\n />\n </ButtonWithIcon>\n </header>\n <div className=\"flex flex-column flex-grow-1 overflow-y-auto\">\n {listStyles &&\n listStyles.map(style => (\n <StyleCard\n key={style.id}\n style={style}\n selectStyle={({ id, name }: Style) =>\n saveSelectedStyle({ variables: { id } })\n .then(async () => {\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.saveSuccess,\n { name }\n ),\n })\n const event = createEventObject(\n 'Select main style',\n 'style',\n account,\n workspace,\n id\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n })\n .catch(e => {\n console.error(e)\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.saveFail,\n {\n name,\n }\n ),\n })\n })\n }\n deleteStyle={({ config, name, id }: Style) =>\n deleteStyle({ variables: { id } })\n .then(async () => {\n showToast({\n action: {\n label: intl.formatMessage(messages.undo),\n onClick: () => {\n createStyle({\n variables: { name, config },\n })\n },\n },\n duration: Infinity,\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.deleteSuccess,\n { name }\n ),\n })\n const event = createEventObject(\n 'Delete style',\n 'style',\n account,\n workspace,\n id\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n })\n .catch(e => {\n console.error(e)\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.deleteFail\n ),\n })\n throw e\n })\n }\n duplicateStyle={({ name, config }: Style) =>\n createStyle({\n variables: {\n config,\n name: intl.formatMessage(\n messages.duplicateDefaultName,\n { name }\n ),\n },\n })\n .then(async () => {\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.duplicateSuccess,\n { name }\n ),\n })\n const event = createEventObject(\n 'Create new style',\n 'style',\n account,\n workspace\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n })\n .catch(e => {\n console.error(e)\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage(\n messages.duplicateFail,\n { name }\n ),\n })\n })\n }\n startEditing={startEditing}\n />\n ))}\n </div>\n </section>\n )}\n </ToastConsumer>\n )}\n </SendEventToAuditMutation>\n )\n }}\n </Operations>\n )\n}\n\nexport default StyleList\n\n```" } ]
code_admin-pages_0d7f4be3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/Operations.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport ListStyles from './graphql/ListStyles.graphql'\nimport CreateStyleMutation, {\n CreateStyleMutationFn,\n} from './mutations/CreateStyle'\nimport DeleteStyleMutation, {\n DeleteStyleMutationFn,\n} from './mutations/DeleteStyle'\nimport SaveSelectedStyleMutation, {\n SaveSelectedStyleMutationFn,\n} from './mutations/SaveSelectedStyle'\nimport ListStylesQuery, { ListStylesQueryResult } from './queries/ListStyles'\n\ninterface Props {\n children: (mutations: OperationsObj) => React.ReactNode\n}\n\ninterface OperationsObj {\n listStyles: ListStylesQueryResult\n saveSelectedStyle: SaveSelectedStyleMutationFn\n createStyle: CreateStyleMutationFn\n deleteStyle: DeleteStyleMutationFn\n}\n\nconst Operations = (props: Props) => (\n <ListStylesQuery fetchPolicy={'network-only'}>\n {listStyles => (\n <SaveSelectedStyleMutation\n refetchQueries={() => [{ query: ListStyles }]}\n awaitRefetchQueries\n >\n {saveSelectedStyle => (\n <CreateStyleMutation\n refetchQueries={() => [{ query: ListStyles }]}\n awaitRefetchQueries\n >\n {createStyle => (\n <DeleteStyleMutation\n refetchQueries={() => [{ query: ListStyles }]}\n awaitRefetchQueries\n >\n {deleteStyle =>\n props.children({\n createStyle,\n deleteStyle,\n listStyles,\n saveSelectedStyle,\n })\n }\n </DeleteStyleMutation>\n )}\n </CreateStyleMutation>\n )}\n </SaveSelectedStyleMutation>\n )}\n </ListStylesQuery>\n)\n\nexport default Operations\n\n```" } ]
code_admin-pages_5ccc8670
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { createMemoryHistory } from 'history'\nimport { injectIntl, IntlShape } from 'react-intl'\nimport { Router } from 'react-router-dom'\nimport { ToastConsumer } from 'vtex.styleguide'\n\nimport RenameStyleMutation from './mutations/RenameStyle'\nimport UpdateStyleMutation from './mutations/UpdateStyle'\nimport StyleEditorHooks from './StyleEditorHooks'\n\ninterface Props {\n intl: IntlShape\n setStyleAsset: (asset: StyleAssetInfo) => void\n stopEditing: () => void\n style: Style\n}\n\nconst StyleEditor: React.FunctionComponent<Props> = props => {\n return (\n <Router history={createMemoryHistory()}>\n <RenameStyleMutation>\n {renameStyle => (\n <UpdateStyleMutation>\n {updateStyle => (\n <ToastConsumer>\n {({ showToast }) => (\n <StyleEditorHooks\n {...{\n ...props,\n renameStyle,\n showToast,\n updateStyle,\n }}\n />\n )}\n </ToastConsumer>\n )}\n </UpdateStyleMutation>\n )}\n </RenameStyleMutation>\n </Router>\n )\n}\n\nexport default injectIntl(StyleEditor)\n\n```" } ]
code_admin-pages_005d096e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/StyleEditorHooks.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { mergeDeepRight } from 'ramda'\nimport React, { useCallback, useReducer, useState } from 'react'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { ShowToastFunction } from 'vtex.styleguide'\n\nimport { RenameStyleFunction } from './mutations/RenameStyle'\nimport { UpdateStyleFunction } from './mutations/UpdateStyle'\nimport GenerateStyleSheetQuery from './queries/GenerateStyleSheet'\nimport StyleEditorRouter from './StyleEditorRouter'\n\ninterface Props {\n style: Style\n renameStyle: RenameStyleFunction\n updateStyle: UpdateStyleFunction\n setStyleAsset: (asset: StyleAssetInfo) => void\n showToast: ShowToastFunction\n stopEditing: () => void\n}\n\ntype ConfigReducer = (\n config: TachyonsConfig,\n partialConfig: DeepPartial<TachyonsConfig>\n) => TachyonsConfig\n\ndefineMessages({\n saveFailed: {\n defaultMessage: 'An error occurred while saving your style.',\n id: 'admin/pages.editor.styles.edit.save.failed',\n },\n saveSuccessful: {\n defaultMessage: 'Style saved successfully.',\n id: 'admin/pages.editor.styles.edit.save.successful',\n },\n})\n\nconst StyleEditorStates: React.FunctionComponent<Props> = ({\n style,\n renameStyle,\n setStyleAsset,\n updateStyle,\n showToast,\n stopEditing,\n}) => {\n const intl = useIntl()\n const nameState = useState<string>(style.name)\n const [name] = nameState\n const configReducer = useReducer<ConfigReducer>(\n mergeDeepRight as ConfigReducer,\n style.config\n )\n const [config] = configReducer\n\n const editingState = useState(false)\n const setEditing = editingState[1]\n\n const hooks = {\n config: configReducer,\n editing: editingState,\n name: nameState,\n }\n\n const saveStyle = useCallback(async () => {\n await renameStyle({ variables: { id: style.id, name } })\n const result = await updateStyle({\n variables: { id: style.id, config },\n })\n const styleInfo = result && result.data && result.data.updateStyle\n if (styleInfo) {\n const { path, selected } = styleInfo\n setStyleAsset({\n keepSheet: true,\n selected,\n type: 'path',\n value: path,\n })\n\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage({\n id: 'admin/pages.editor.styles.edit.save.successful',\n }),\n })\n } else {\n showToast({\n horizontalPosition: 'left',\n message: intl.formatMessage({\n id: 'admin/pages.editor.styles.edit.save.failed',\n }),\n })\n }\n }, [\n renameStyle,\n style.id,\n name,\n updateStyle,\n config,\n setStyleAsset,\n showToast,\n intl,\n ])\n\n const onSave = useCallback(() => {\n setEditing(false)\n saveStyle()\n }, [saveStyle, setEditing])\n\n return (\n <GenerateStyleSheetQuery\n variables={{ config }}\n fetchPolicy={'network-only'}\n >\n {({ data }) => (\n <StyleEditorRouter\n data={data || null}\n hooks={hooks}\n onSave={onSave}\n setStyleAsset={setStyleAsset}\n stopEditing={stopEditing}\n style={style}\n />\n )}\n </GenerateStyleSheetQuery>\n )\n}\n\nexport default StyleEditorStates\n\n```" } ]
code_admin-pages_e4d494a6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/EditorSelector.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { defineMessages, FormattedMessage } from 'react-intl'\n\nimport Colors from '../components/Colors'\nimport AvailableEditor from './AvailableEditor'\nimport StyleEditorHeader from './StyleEditorHeader'\nimport { EditorPath, IdParam } from './StyleEditorRouter'\n\ninterface Props {\n config: TachyonsConfig\n name: string\n onSave: () => void\n stopEditing: () => void\n}\n\ndefineMessages({\n colorsTitle: {\n defaultMessage: 'Colors',\n id: 'admin/pages.editor.styles.edit.colors.title',\n },\n typographyTitle: {\n defaultMessage: 'Typography',\n id: 'admin/pages.editor.styles.edit.typography.title',\n },\n})\n\nconst EditorSelector: React.FunctionComponent<Props> = ({\n config,\n name,\n onSave,\n stopEditing,\n}) => {\n const {\n semanticColors: {\n background: { action_primary: actionPrimary, emphasis },\n },\n } = config\n\n const colorEditorProps = {\n path: EditorPath.colors.replace(IdParam, ''),\n titleId: 'admin/pages.editor.styles.edit.colors.title',\n widget: <Colors colors={[emphasis, actionPrimary]} />,\n }\n\n const typographyEditorProps = {\n path: EditorPath.typography,\n titleId: 'admin/pages.editor.styles.edit.typography.title',\n widget: <div className=\"t-heading-2\">Aa</div>,\n }\n\n const saveButtonLabel = (\n <FormattedMessage\n id=\"admin/pages.editor.components.button.save\"\n defaultMessage=\"Save\"\n />\n )\n\n return (\n <>\n <StyleEditorHeader\n onButtonClick={onSave}\n buttonLabel={saveButtonLabel}\n afterOnBack={stopEditing}\n title={name}\n />\n <div className=\"ph6\">\n <AvailableEditor {...colorEditorProps} />\n <AvailableEditor {...typographyEditorProps} />\n </div>\n </>\n )\n}\n\nexport default EditorSelector\n\n```" } ]
code_admin-pages_ecb480b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/StyleEditorHeader.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React, { useCallback } from 'react'\nimport { RouteComponentProps, withRouter } from 'react-router'\nimport { Button, IconArrowBack } from 'vtex.styleguide'\n\ninterface Props extends RouteComponentProps {\n buttonLabel?: string | React.ReactNode\n onButtonClick?: () => void\n afterOnBack?: () => void\n title: string | React.ReactNode\n}\n\nconst StyleEditorHeader: React.FunctionComponent<Props> = ({\n afterOnBack,\n buttonLabel,\n children,\n history,\n onButtonClick,\n title,\n}) => {\n const onBack = useCallback(() => {\n history.goBack()\n if (afterOnBack) {\n afterOnBack()\n }\n }, [history, afterOnBack])\n\n const onBackByKeyDown = useKeydownFromClick(onBack)\n\n return (\n <div className=\"mh6 mt6\">\n <div className=\"flex justify-between items-center mv4\">\n <div className=\"flex items-center\">\n <div\n className=\"pointer f3 ph4 outline-0\"\n onClick={onBack}\n onKeyDown={onBackByKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <IconArrowBack />\n </div>\n <span className=\"f3\">{title}</span>\n </div>\n {buttonLabel && (\n <Button\n variation=\"tertiary\"\n size=\"small\"\n onClick={onButtonClick}\n disabled={!onButtonClick}\n >\n {buttonLabel}\n </Button>\n )}\n {children}\n </div>\n </div>\n )\n}\n\nexport default withRouter(StyleEditorHeader)\n\n```" } ]
code_admin-pages_413bd704
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/AvailableEditor.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { RouteComponentProps, withRouter } from 'react-router-dom'\n\ninterface Props extends RouteComponentProps {\n path: string\n titleId: string\n widget?: React.ReactNode\n}\n\nconst AvailableEditor: React.FunctionComponent<Props> = ({\n history,\n path,\n titleId,\n widget,\n}) => {\n const redirect = React.useCallback(() => history.push(path), [history, path])\n\n const redirectByKeyDown = useKeydownFromClick(redirect)\n\n return (\n <div\n className=\"pointer flex justify-between items-center pv6 bb b--muted-4 outline-0\"\n onClick={redirect}\n onKeyDown={redirectByKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <span className=\"f4\">\n <FormattedMessage id={titleId} />\n </span>\n {widget}\n </div>\n )\n}\n\nexport default withRouter(AvailableEditor)\n\n```" } ]
code_admin-pages_61569d39
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/StyleEditorRouter.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect } from 'react'\nimport { Route, RouteComponentProps, Switch } from 'react-router'\n\nimport ColorsEditor from './ColorsEditor'\nimport EditorSelector from './EditorSelector'\nimport FontFamilyList from './typography/FontFamilyList'\nimport TypographyEditor from './typography/TypographyEditor'\n\nimport { GenerateStyleSheetData } from './queries/GenerateStyleSheet'\nimport CustomFont from './typography/FontEditor'\nimport TypeToken from './typography/TypeToken'\nimport TypeTokensList from './typography/TypeTokensList'\n\nexport const IdParam = ':id'\n\nexport enum EditorPath {\n selector = '/',\n colors = '/colors/:id',\n typography = '/typography',\n fontFamily = '/font-family',\n typeToken = '/type-token/:id',\n typeTokens = '/type-tokens',\n customFont = '/custom-font/:id',\n customFontFile = '/custom-font/file/:id',\n customFontLink = '/custom-font/link/:id',\n}\n\ninterface Props {\n data: GenerateStyleSheetData | null\n hooks: {\n config: [TachyonsConfig, React.Dispatch<DeepPartial<TachyonsConfig>>]\n editing: [boolean, React.Dispatch<React.SetStateAction<boolean>>]\n name: [string, React.Dispatch<React.SetStateAction<string>>]\n }\n onSave: () => void\n setStyleAsset: (asset: StyleAssetInfo) => void\n stopEditing: () => void\n style: Style\n}\n\nconst StyleEditorRouter: React.FunctionComponent<Props> = ({\n data,\n hooks: {\n config: [config, updateConfig],\n name: [name],\n },\n onSave,\n setStyleAsset,\n stopEditing,\n style,\n}) => {\n const stylesheet = data && data.generateStyleSheet\n\n useEffect(() => {\n if (stylesheet) {\n setStyleAsset({ type: 'stylesheet', value: stylesheet })\n }\n }, [setStyleAsset, stylesheet])\n\n const renderEditorSelector = () => (\n <EditorSelector {...{ config, name, onSave, stopEditing }} />\n )\n\n const colorsPaths = [\n EditorPath.colors,\n EditorPath.colors.replace(IdParam, ''),\n ]\n const renderColorsEditor = (props: RouteComponentProps<ColorRouteParams>) => (\n <ColorsEditor\n {...{ ...props, updateStyle: updateConfig, config, onSave }}\n />\n )\n\n const customFontPaths = [\n EditorPath.customFont,\n EditorPath.customFont.replace(IdParam, ''),\n ]\n\n const renderTypeTokensList = (props: RouteComponentProps) => (\n <TypeTokensList {...props} style={style} />\n )\n\n const renderTypeToken = (props: RouteComponentProps<TypeTokenParams>) => (\n <TypeToken\n {...props}\n config={config}\n updateConfig={updateConfig}\n onSave={onSave}\n />\n )\n\n return (\n <div className=\"h-100 flex flex-column flex-grow-1 overflow-y-auto overflow-x-hidden\">\n <Switch>\n <Route exact path={EditorPath.selector} render={renderEditorSelector} />\n <Route exact path={colorsPaths} render={renderColorsEditor} />\n <Route\n exact\n path={EditorPath.typography}\n component={TypographyEditor}\n />\n <Route exact path={EditorPath.fontFamily} component={FontFamilyList} />\n\n <Route path={customFontPaths} component={CustomFont} />\n <Route\n exact\n path={EditorPath.typeTokens}\n render={renderTypeTokensList}\n />\n <Route exact path={EditorPath.typeToken} render={renderTypeToken} />\n </Switch>\n </div>\n )\n}\n\nexport default StyleEditorRouter\n\n```" } ]
code_admin-pages_3a539166
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype DeepPartial<T> = T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T\n\ninterface ButtonInfo {\n action?: () => void\n text: string\n}\n\ninterface RouteInfo {\n backButton: ButtonInfo\n auxButton?: ButtonInfo\n title: string\n}\n\ninterface NavigationUpdate {\n type: 'push' | 'pop' | 'update'\n route: EditorRoute\n}\n\ninterface ColorRouteParams {\n id: string\n}\n\ninterface CustomFontParams {\n id: string\n}\n\ninterface TypeTokenParams {\n id: string\n}\n\n```" } ]
code_admin-pages_bbd0c5b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/colors.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface ColorInfo {\n path: string\n color: string\n configField: string\n}\n\ntype Colors = Record<string, ColorInfo[]>\n\n```" } ]
code_admin-pages_ff295af2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/typings/config.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport {\n FontFamilyProperty,\n FontSizeProperty,\n FontWeightProperty,\n LetterSpacingProperty,\n TextTransformProperty,\n} from 'csstype'\n\ndeclare global {\n interface Font {\n fontFamily: FontFamilyProperty\n fontWeight: FontWeightProperty\n fontSize: FontSizeProperty\n textTransform: TextTransformProperty\n letterSpacing: LetterSpacingProperty\n }\n\n interface Tokens {\n [token: string]: string\n }\n\n interface SemanticColors {\n [field: string]: Tokens\n }\n\n interface TypographyStyles {\n heading_1: Font\n heading_2: Font\n heading_3: Font\n heading_4: Font\n heading_5: Font\n heading_6: Font\n body: Font\n small: Font\n mini: Font\n action: Font\n action__small: Font\n action__large: Font\n code: Font\n }\n\n interface TachyonsConfig {\n semanticColors: SemanticColors\n typography: {\n styles: TypographyStyles\n }\n }\n}\n\n```" } ]
code_admin-pages_c84276f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/typings/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface BasicStyle {\n id: string\n app: string\n name: string\n}\n\ninterface Style extends BasicStyle {\n editable: boolean\n selected: boolean\n path: string\n config: TachyonsConfig\n}\n\ninterface ActionMenuOption {\n label: string\n onClick: (style: Style) => void\n}\n\ninterface StyleAssetInfo {\n type: 'path' | 'stylesheet'\n keepSheet?: boolean\n selected?: boolean\n value: string\n}\n\n```" } ]
code_admin-pages_7edf77c3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/components/Colors.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 colors: string[]\n}\n\nconst Colors: React.FunctionComponent<Props> = ({ colors }) => (\n <div className=\"flex ba br2 b--muted-5 bg-muted-5 overflow-hidden\">\n {colors.map((color, index) => (\n <div\n key={index}\n className={`w2 h2`}\n style={{\n backgroundColor: color,\n }}\n />\n ))}\n </div>\n)\n\nexport default Colors\n\n```" } ]
code_admin-pages_2684e61e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/components/Typography.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 typography: Font\n textColor?: string\n}\n\nconst Typography: React.FunctionComponent<Props> = ({\n typography: {\n fontFamily,\n fontSize,\n fontWeight,\n letterSpacing,\n textTransform,\n },\n textColor,\n}) => {\n return (\n <div\n style={{\n color: textColor || 'black',\n fontFamily,\n fontSize,\n fontWeight,\n letterSpacing,\n textTransform,\n }}\n >\n Aa\n </div>\n )\n}\n\nexport default Typography\n\n```" } ]
code_admin-pages_8d229c3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/mutations/CreateStyle.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Mutation, MutationFn } from 'react-apollo'\nimport CreateStyle from '../graphql/CreateStyle.graphql'\n\ninterface CreateStyleData {\n createStyle: {\n id: string\n app: string\n name: string\n }\n}\n\ninterface CreateStyleVariables {\n name: string\n config?: TachyonsConfig\n}\n\nexport type CreateStyleMutationFn = MutationFn<\n CreateStyleData,\n CreateStyleVariables\n>\n\nclass CreateStyleMutation extends Mutation<\n CreateStyleData,\n CreateStyleVariables\n> {\n public static defaultProps = {\n mutation: CreateStyle,\n }\n}\n\nexport default CreateStyleMutation\n\n```" } ]
code_admin-pages_8bc340cd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/mutations/DeleteStyle.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Mutation, MutationFn } from 'react-apollo'\nimport DeleteStyle from '../graphql/DeleteStyle.graphql'\n\ninterface DeleteStyleData {\n deleteStyle: {\n id: string\n app: string\n name: string\n }\n}\n\ninterface DeleteStyleVariables {\n id: string\n}\n\nexport type DeleteStyleMutationFn = MutationFn<\n DeleteStyleData,\n DeleteStyleVariables\n>\n\nclass DeleteStyleMutation extends Mutation<\n DeleteStyleData,\n DeleteStyleVariables\n> {\n public static defaultProps = {\n mutation: DeleteStyle,\n }\n}\n\nexport default DeleteStyleMutation\n\n```" } ]
code_admin-pages_e0fb2a00
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/mutations/SaveSelectedStyle.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Mutation, MutationFn } from 'react-apollo'\nimport SaveSelectedStyle from '../graphql/SaveSelectedStyle.graphql'\n\ninterface SaveSelectedStyleData {\n saveSelectedStyle: {\n id: string\n app: string\n name: string\n }\n}\n\ninterface SaveSelectedStyleVariables {\n id: string\n}\n\nexport type SaveSelectedStyleMutationFn = MutationFn<\n SaveSelectedStyleData,\n SaveSelectedStyleVariables\n>\n\nclass SaveSelectedStyleMutation extends Mutation<\n SaveSelectedStyleData,\n SaveSelectedStyleVariables\n> {\n public static defaultProps = {\n mutation: SaveSelectedStyle,\n }\n}\n\nexport default SaveSelectedStyleMutation\n\n```" } ]
code_admin-pages_483d0f35
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/queries/ListStyles.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Query, QueryResult } from 'react-apollo'\nimport ListStyles from '../graphql/ListStyles.graphql'\n\nexport interface ListStylesData {\n listStyles: Style[]\n}\n\nexport type ListStylesQueryResult = QueryResult<ListStylesData>\n\nclass ListStylesQuery extends Query<ListStylesData, {}> {\n public static defaultProps = {\n query: ListStyles,\n }\n}\n\nexport default ListStylesQuery\n\n```" } ]
code_admin-pages_c39617a9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/StyleCard/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { ActionMenu, Card, IconOptionsDots, Tag } from 'vtex.styleguide'\n\nimport Colors from '../../components/Colors'\nimport Typography from '../../components/Typography'\n\ntype StyleFunction = (style: Style) => void\ntype StyleMutation = (style: Style) => Promise<unknown>\n\ninterface Props {\n deleteStyle: StyleMutation\n duplicateStyle: StyleMutation\n selectStyle: StyleMutation\n startEditing: StyleFunction\n style: Style\n}\n\nconst messages = defineMessages({\n delete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.editor.styles.card.menu.delete',\n },\n duplicate: {\n defaultMessage: 'Duplicate',\n id: 'admin/pages.editor.styles.card.menu.duplicate',\n },\n edit: {\n defaultMessage: 'Edit',\n id: 'admin/pages.editor.styles.card.menu.edit',\n },\n select: {\n defaultMessage: 'Select as store style',\n id: 'admin/pages.editor.styles.card.menu.select',\n },\n})\n\nconst StyleCard: React.FunctionComponent<Props> = ({\n deleteStyle,\n duplicateStyle,\n selectStyle,\n startEditing,\n style,\n style: { app: appId, name, selected, editable, config },\n}) => {\n const [isLoading, setIsLoading] = useState(false)\n const intl = useIntl()\n\n const setIsLoadingWrapper = (fn: () => Promise<unknown>) => async () => {\n setIsLoading(true)\n await fn()\n setIsLoading(false)\n }\n\n const {\n background: {\n action_primary: actionPrimary,\n action_secondary: actionSecondary,\n base,\n emphasis,\n },\n } = config.semanticColors\n\n const typography = config.typography.styles.heading_2\n\n const createMenuOptions = () => {\n const options = [\n editable && {\n label: intl.formatMessage(messages.edit),\n onClick: () => startEditing(style),\n },\n !selected && {\n label: intl.formatMessage(messages.select),\n onClick: setIsLoadingWrapper(() => selectStyle(style)),\n },\n {\n label: intl.formatMessage(messages.duplicate),\n onClick: setIsLoadingWrapper(() => duplicateStyle(style)),\n },\n !selected &&\n editable && {\n label: intl.formatMessage(messages.delete),\n onClick: async () => {\n setIsLoading(true)\n try {\n await deleteStyle(style)\n } catch (e) {\n setIsLoading(false)\n }\n },\n },\n ]\n return options.filter(option => option)\n }\n\n return (\n <div className=\"mh3 mb3\">\n <Card noPadding>\n <div className=\"ph5 pt5 pb2\">\n <div className=\"flex justify-between items-center mb4\">\n <div className=\"flex items-center h2 w-80\">\n <span className=\"mr5 truncate\">{name}</span>\n {!editable && (\n <span className=\"f7 c-muted-2 truncate\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.card.name.app-subtitle\"\n defaultMessage=\"created by {app}\"\n values={{ app: appId.split('@')[0] }}\n />\n </span>\n )}\n </div>\n <ActionMenu\n hideCaretIcon\n buttonProps={{\n icon: <IconOptionsDots />,\n iconPosition: 'right',\n isLoading,\n variation: 'tertiary',\n }}\n options={createMenuOptions()}\n />\n </div>\n <div className=\"flex justify-between items-center mb5\">\n <div className=\"flex items-center\">\n <Typography typography={typography} />\n <div className=\"pl5\">\n <Colors\n colors={[emphasis, actionPrimary, actionSecondary, base]}\n />\n </div>\n </div>\n {selected && (\n <Tag bgColor=\"#F71963\" color=\"#FFFFFF\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.card.current\"\n defaultMessage=\"Current\"\n />\n </Tag>\n )}\n </div>\n </div>\n </Card>\n </div>\n )\n}\n\nexport default StyleCard\n\n```" } ]
code_admin-pages_d5dc9a7f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/graphql/DeleteStyle.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation DeleteStyle($id: String) {\n deleteStyle(id: $id) {\n id\n app\n name\n }\n}\n\n```" } ]
code_admin-pages_d328f658
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/graphql/SaveSelectedStyle.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveSelectedStyle($id: String) {\n saveSelectedStyle(id: $id) {\n id\n app\n name\n }\n}\n\n```" } ]
code_admin-pages_a6b713f7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/graphql/CreateStyle.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation CreateStyle($name: String, $config: ConfigInput) {\n createStyle(name: $name, config: $config) {\n id\n app\n name\n }\n}\n\n```" } ]
code_admin-pages_95d8658d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/graphql/ListStyles.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery ListStyles {\n listStyles {\n id\n app\n name\n path\n editable\n selected\n config {\n semanticColors {\n background {\n base\n base__inverted\n action_primary\n action_secondary\n emphasis\n disabled\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n hover_background {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n active_background {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n text {\n action_primary\n action_secondary\n link\n emphasis\n disabled\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n visited_text {\n link\n }\n hover_text {\n action_primary\n action_secondary\n link\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n }\n active_text {\n link\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n }\n border {\n action_primary\n action_secondary\n emphasis\n disabled\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n hover_border {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n active_border {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n on {\n base\n base__inverted\n action_primary\n action_secondary\n emphasis\n disabled\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n muted_1\n muted_2\n muted_3\n muted_4\n muted_5\n }\n hover_on {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n }\n active_on {\n action_primary\n action_secondary\n emphasis\n success\n success__faded\n danger\n danger__faded\n warning\n warning__faded\n }\n }\n typography {\n styles {\n heading_1 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n heading_2 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n heading_3 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n heading_4 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n heading_5 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n heading_6 {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n body {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n small {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n mini {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n action {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n action__small {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n action__large {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n code {\n fontFamily\n fontWeight\n fontSize\n textTransform\n letterSpacing\n }\n }\n }\n }\n }\n}\n\n```" } ]
code_admin-pages_794c57aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleList/icons/CreateNewIcon.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\n// TODO: Use tachyons on stroke color\nconst CreateNewIcon: React.FunctionComponent = () => (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 14 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M7 4.42773V9.57059\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M4.42969 7H9.57254\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M12.1429 13H1.85714C1.384 13 1 12.616 1 12.1429V1.85714C1 1.384 1.384 1 1.85714 1H12.1429C12.616 1 13 1.384 13 1.85714V12.1429C13 12.616 12.616 13 12.1429 13Z\"\n stroke=\"#134CD8\"\n strokeWidth=\"1.4\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n)\n\nexport default CreateNewIcon\n\n```" } ]
code_admin-pages_af1160d8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/Styles/StyleEditor/ColorsEditor/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useCallback, useMemo } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { RouteComponentProps } from 'react-router'\n\nimport startCase from 'lodash/startCase'\nimport { fromPairs, groupBy, toPairs } from 'ramda'\n\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport { EditorPath, IdParam } from '../StyleEditorRouter'\nimport fromTachyonsConfig from '../utils/colors'\nimport ColorEditor from './ColorEditor'\nimport ColorGroup from './ColorGroup'\n\ninterface Props extends RouteComponentProps<ColorRouteParams> {\n updateStyle: (partialConfig: Partial<TachyonsConfig>) => void\n config: TachyonsConfig\n onSave: () => void\n}\n\nconst updateColor = (updateStyle: Props['updateStyle']) => (\n token: string,\n colorInfo: ColorInfo\n) => {\n const { configField, color } = colorInfo\n const partialConfig = {\n semanticColors: {\n [configField]: {\n [token]: color,\n },\n },\n }\n updateStyle(partialConfig)\n}\n\nconst ColorsEditor: React.FunctionComponent<Props> = ({\n config: {\n semanticColors,\n typography: {\n styles: { heading_6: font },\n },\n },\n match,\n updateStyle,\n history,\n onSave,\n}) => {\n const {\n params: { id },\n } = match\n const info = fromTachyonsConfig(semanticColors)\n\n const colorsLabel = (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.colors.title\"\n defaultMessage=\"Colors\"\n />\n )\n\n const saveButtonLabel = (\n <FormattedMessage\n id=\"admin/pages.editor.components.button.save\"\n defaultMessage=\"Save\"\n />\n )\n\n const MemoizedHeader = useMemo(() => {\n const Header = ({ name }: { name: string | React.ReactNode }) => (\n <StyleEditorHeader\n onButtonClick={onSave}\n buttonLabel={saveButtonLabel}\n title={name}\n />\n )\n\n return Header\n }, [onSave, saveButtonLabel])\n\n const startEditing = useCallback(\n (token: string) => history.push(EditorPath.colors.replace(IdParam, token)),\n [history]\n )\n\n const groups = useMemo(\n () =>\n groupBy(([token]) => {\n if (token === 'emphasis') {\n return 'emphasis'\n } else if (token.startsWith('base')) {\n return 'base'\n } else if (token.startsWith('muted')) {\n return 'muted'\n } else if (\n token.startsWith('action') ||\n token === 'link' ||\n token === 'disabled'\n ) {\n return 'action'\n } else {\n return 'feedback'\n }\n }, toPairs(info)),\n [info]\n )\n\n const colourGroups = useMemo(\n () =>\n toPairs(groups).map(([groupName, group]) => (\n <ColorGroup\n colorsInfo={fromPairs(group)}\n font={font}\n groupName={startCase(groupName as string)}\n key={groupName}\n semanticColors={semanticColors}\n startEditing={startEditing}\n />\n )),\n [font, groups, semanticColors, startEditing]\n )\n\n if (id) {\n return (\n <>\n <MemoizedHeader name={startCase(id)} />\n <div className=\"flex-grow-1 overflow-y-auto overflow-x-hidden\">\n <ColorEditor\n updateColor={updateColor(updateStyle)}\n token={id}\n colorInfo={info[id]}\n />\n </div>\n </>\n )\n }\n\n return (\n <>\n <MemoizedHeader name={colorsLabel} />\n <div className=\"flex-grow-1\">{colourGroups}</div>\n </>\n )\n}\n\nexport default ColorsEditor\n\n```" } ]