id
stringlengths
12
53
messages
listlengths
3
3
code_admin-pages_e880dede
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ColorGroup.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport startCase from 'lodash/startCase'\nimport { find, mapObjIndexed, propEq } from 'ramda'\nimport React from 'react'\n\nimport Typography from '../../components/Typography'\n\nconst COLOR_BLOCK_SIZE = '40px'\n\ninterface Props {\n groupName: string\n colorsInfo: Colors\n font: Font\n startEditing: (token: string) => void\n semanticColors: SemanticColors\n}\n\nconst ColorGroup: React.FunctionComponent<Props> = ({\n colorsInfo,\n font,\n groupName,\n semanticColors,\n startEditing,\n}) => {\n return (\n <div className=\"bt b--muted-5\">\n <div className=\"ph6 f4 flex items-center pv5\">{groupName}</div>\n {Object.values(\n mapObjIndexed((info: ColorInfo[], token: string) => {\n return (\n <ColorPreview\n key={token}\n previewInfo={{\n backgroundColor: semanticColors.background.base,\n font,\n textColor: semanticColors.text.link,\n }}\n token={token}\n startEditing={startEditing}\n colorInfo={info}\n />\n )\n }, colorsInfo)\n )}\n </div>\n )\n}\n\ninterface ColorPreviewProps {\n colorInfo: ColorInfo[]\n previewInfo: {\n font: Font\n backgroundColor: string\n textColor: string\n }\n startEditing: (token: string) => void\n token: string\n}\n\nconst ColorPreview: React.FunctionComponent<ColorPreviewProps> = ({\n colorInfo,\n previewInfo,\n startEditing,\n token,\n}) => {\n const handleClick = React.useCallback(() => startEditing(token), [\n startEditing,\n token,\n ])\n\n const handleKeyDown = useKeydownFromClick(handleClick)\n\n const backgroundColor = find(propEq('configField', 'background'), colorInfo)\n const textColor = find(propEq('configField', 'on'), colorInfo)\n\n return (\n <div\n className=\"pv5 ph6 flex items-center hover-bg-light-silver pointer outline-0\"\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <div\n className=\"ba br2 b--muted-5 flex justify-center items-center\"\n style={{\n backgroundColor:\n (backgroundColor && backgroundColor.color) ||\n previewInfo.backgroundColor,\n height: COLOR_BLOCK_SIZE,\n width: COLOR_BLOCK_SIZE,\n }}\n >\n <Typography\n typography={previewInfo.font}\n textColor={(textColor && textColor.color) || previewInfo.textColor}\n />\n </div>\n <div className=\"ml3\">{startCase(token)}</div>\n </div>\n )\n}\n\nexport default ColorGroup\n\n```" } ]
code_admin-pages_2f1647e9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ColorEditor.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport startCase from 'lodash/startCase'\nimport { groupBy, mapObjIndexed } from 'ramda'\nimport React from 'react'\nimport { ColorPicker } from 'vtex.styleguide'\n\ninterface Props {\n updateColor: (token: string, color: ColorInfo) => void\n token: string\n colorInfo: ColorInfo[]\n}\n\ninterface ColorPickerColors {\n hex?: string\n rgba?: {\n r: number\n g: number\n b: number\n a: number\n }\n}\n\nconst getColorObject = (color: string): ColorPickerColors => {\n if (/^#[A-Fa-f0-9]{3}$/.test(color)) {\n return {\n hex: color.replace(\n /#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])/,\n '#$1$1$2$2$3$3'\n ),\n }\n }\n const rgbaGroup = color.match(/\\(.*\\)/)\n if (rgbaGroup) {\n const rgbaInfo = rgbaGroup[0].slice(1, -1).split(',')\n return {\n hex: '#ffffff',\n rgba: {\n a: parseFloat(rgbaInfo[3]),\n b: parseFloat(rgbaInfo[2]),\n g: parseFloat(rgbaInfo[1]),\n r: parseFloat(rgbaInfo[0]),\n },\n }\n }\n return { hex: color }\n}\n\nconst fieldName = (id: string) => {\n switch (id) {\n case 'background':\n return 'Background'\n case 'on':\n return 'Text on background'\n case 'text':\n return 'Text'\n case 'border':\n return 'Border'\n default:\n return ''\n }\n}\n\nconst ColorsEditor: React.FunctionComponent<Props> = ({\n colorInfo,\n updateColor,\n token,\n}) => {\n const groups = groupBy(info => {\n return fieldName(info.path.split('.')[0])\n }, colorInfo)\n return (\n <div className=\"overflow-scroll h-100\">\n {Object.values(\n mapObjIndexed((group: ColorInfo[], field: string) => {\n return (\n <div className=\"ph6 bt b--muted-5\" key={field}>\n <div className=\"f4 bb b--muted-5 pv6\">{field}</div>\n <div className=\"pv4\">\n {group.map(info => {\n const key = info.path.split('.')[1]\n\n return (\n <ColorPicker\n key={key}\n label={startCase(key)}\n color={getColorObject(info.color)}\n colorHistory={[]}\n onChange={({ rgba }: ColorPickerColors) => {\n if (rgba) {\n const { r, g, b, a } = rgba\n const newInfo = {\n ...info,\n color: `rgba(${r},${g},${b},${a})`,\n }\n updateColor(token, newInfo)\n }\n }}\n />\n )\n })}\n </div>\n </div>\n )\n }, groups)\n )}\n </div>\n )\n}\n\nexport default ColorsEditor\n\n```" } ]
code_admin-pages_f3827407
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/DeleteFontFamily.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DataProxy } from 'apollo-cache'\nimport { Mutation, MutationFn, QueryResult } from 'react-apollo'\n\nimport DeleteFontFamilyMutation from '../graphql/DeleteFontFamily.graphql'\nimport ListFonts from '../graphql/ListFonts.graphql'\nimport { ListFontsData } from '../queries/ListFontsQuery'\n\ninterface FontFamilyVariables {\n id: string\n}\n\nexport interface DeleteFontFamilyData {\n deleteFontFamily: {\n id: string\n }\n}\n\nexport type DeleteFontFamilyFn = MutationFn<\n DeleteFontFamilyData,\n FontFamilyVariables\n>\n\ntype DeleteFontFamilyResult = QueryResult<DeleteFontFamilyData>\n\nconst updateFontsAfterDelete = (\n cache: DataProxy,\n result: DeleteFontFamilyResult\n) => {\n const listData = cache.readQuery<ListFontsData>({ query: ListFonts })\n if (\n result.data == null ||\n result.data.deleteFontFamily == null ||\n listData == null\n ) {\n return\n }\n const { listFonts: families } = listData\n const { id: removedId } = result.data.deleteFontFamily\n const currentFonts = families.filter(family => family.id !== removedId)\n cache.writeQuery<ListFontsData>({\n data: { listFonts: currentFonts },\n query: ListFonts,\n })\n}\n\nclass DeleteFontFamily extends Mutation<\n DeleteFontFamilyData,\n FontFamilyVariables\n> {\n public static defaultProps = {\n mutation: DeleteFontFamilyMutation,\n update: updateFontsAfterDelete,\n }\n}\n\nexport default DeleteFontFamily\n\n```" } ]
code_admin-pages_4b68253b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/SaveFontFamily.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DataProxy } from 'apollo-cache'\nimport { Mutation, MutationFn, QueryResult } from 'react-apollo'\n\nimport ListFonts from '../graphql/ListFonts.graphql'\nimport SaveFontFamilyMutation from '../graphql/SaveFontFamily.graphql'\nimport { FontFamily, ListFontsData } from '../queries/ListFontsQuery'\n\ninterface FontFamilyVariables {\n font: FontFamilyInput\n}\n\nexport interface FontFamilyInput {\n id?: string\n fontFamily: string\n fontFiles: FontFileInput[]\n}\n\nexport type FontFileInput = FontFileUpload | FontFile\n\nexport interface FontFileUpload {\n fontFile: File\n fontWeight?: string\n fontStyle?: string\n}\n\nexport interface FontFile {\n filename: string\n fontWeight: string\n fontStyle: string\n}\n\nexport interface FontFamilyData {\n saveFontFamily: FontFamily\n}\n\ntype SaveFontFamilyResult = QueryResult<FontFamilyData>\n\nexport type SaveFontFamilyFn = MutationFn<FontFamilyData, FontFamilyVariables>\n\nconst updateFontsAfterSave = (\n cache: DataProxy,\n result: SaveFontFamilyResult\n) => {\n const listData = cache.readQuery<ListFontsData>({ query: ListFonts })\n\n if (result.data == null || listData == null) {\n return\n }\n\n const { listFonts: families } = listData\n const savedFamily = result.data.saveFontFamily\n const familyIndex = families.findIndex(({ id }) => id === savedFamily.id)\n families.splice(\n familyIndex < 0 ? families.length : familyIndex,\n 1,\n savedFamily\n )\n\n cache.writeQuery<ListFontsData>({\n data: {\n listFonts: families,\n },\n query: ListFonts,\n })\n}\n\nclass SaveFontFamily extends Mutation<FontFamilyData, FontFamilyVariables> {\n public static defaultProps = {\n mutation: SaveFontFamilyMutation,\n update: updateFontsAfterSave,\n }\n}\n\nexport default SaveFontFamily\n\n```" } ]
code_admin-pages_d5d8f0c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/RenameStyle.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Mutation, MutationFn } from 'react-apollo'\nimport RenameStyle from '../graphql/RenameStyle.graphql'\n\ninterface RenameStyleData {\n renameStyle: {\n id: string\n }\n}\n\ninterface RenameStyleVariables {\n id: string\n name: string\n}\n\nexport type RenameStyleFunction = MutationFn<\n RenameStyleData,\n RenameStyleVariables\n>\n\nclass RenameStyleMutation extends Mutation<\n RenameStyleData,\n RenameStyleVariables\n> {\n public static defaultProps = {\n mutation: RenameStyle,\n }\n}\n\nexport default RenameStyleMutation\n\n```" } ]
code_admin-pages_1288ba12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mutations/UpdateStyle.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Mutation, MutationFn } from 'react-apollo'\nimport UpdateStyle from '../graphql/UpdateStyle.graphql'\n\ninterface UpdateStyleData {\n updateStyle: {\n path: string\n selected: boolean\n }\n}\n\ninterface UpdateStyleVariables {\n id: string\n config: TachyonsConfig\n}\n\nexport type UpdateStyleFunction = MutationFn<\n UpdateStyleData,\n UpdateStyleVariables\n>\n\nclass UpdateStyleMutation extends Mutation<\n UpdateStyleData,\n UpdateStyleVariables\n> {\n public static defaultProps = {\n mutation: UpdateStyle,\n }\n}\n\nexport default UpdateStyleMutation\n\n```" } ]
code_admin-pages_336e6112
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/queries/ListFontsQuery.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Query, QueryResult } from 'react-apollo'\nimport ListFonts from '../graphql/ListFonts.graphql'\nimport { FontFile } from '../mutations/SaveFontFamily'\n\nexport interface FontFamily {\n id: string\n fontFamily: string\n fonts: FontFile[]\n}\n\nexport interface ListFontsData {\n listFonts: FontFamily[]\n}\n\nexport type ListFontsQueryResult = QueryResult<ListFontsData>\n\nclass ListFontsQuery extends Query<ListFontsData, {}> {\n public static defaultProps = {\n query: ListFonts,\n }\n}\n\nexport default ListFontsQuery\n\n```" } ]
code_admin-pages_3a1703a1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/queries/GenerateStyleSheet.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Query } from 'react-apollo'\nimport GenerateStyleSheet from '../graphql/GenerateStyleSheet.graphql'\n\nexport interface GenerateStyleSheetData {\n generateStyleSheet: string\n}\n\ninterface GenerateStyleSheetVariables {\n config: TachyonsConfig\n}\n\nclass GenerateStyleSheetQuery extends Query<\n GenerateStyleSheetData,\n GenerateStyleSheetVariables\n> {\n public static defaultProps = {\n query: GenerateStyleSheet,\n }\n}\n\nexport default GenerateStyleSheetQuery\n\n```" } ]
code_admin-pages_ccfdcb8d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/colors.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { forEachObjIndexed } from 'ramda'\n\nconst fromSemanticColors = (semanticColors: SemanticColors): Colors => {\n const getFieldPath = (name: string) => {\n let fieldPath = name.split('_')\n if (fieldPath.length === 1) {\n fieldPath = ['default'].concat(fieldPath)\n }\n return fieldPath.reverse().join('.')\n }\n\n const colors: Colors = {}\n forEachObjIndexed((tokens: Tokens, field: string) => {\n forEachObjIndexed((color: string, token: string) => {\n if (token.startsWith('__')) {\n return\n }\n const info: ColorInfo = {\n color,\n configField: field,\n path: getFieldPath(field),\n }\n colors[token] = (colors[token] || []).concat(info)\n }, tokens)\n }, semanticColors)\n\n return colors\n}\n\nexport default fromSemanticColors\n\n```" } ]
code_admin-pages_f183c187
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/utils/typography.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport startCase from 'lodash/startCase'\nimport { xprod } from 'ramda'\n\nimport { FontFileInput } from '../mutations/SaveFontFamily'\nimport { FontFamily } from '../queries/ListFontsQuery'\n\nexport type FontFlavour = [FontStyle, FontWeight]\n\nexport enum FontWeight {\n thin = 'Thin',\n 'extra-light' = 'Extra Light',\n light = 'Light',\n regular = 'Regular',\n medium = 'Medium',\n bold = 'Bold',\n 'extra-bold' = 'Extra Bold',\n black = 'Black',\n}\n\nexport enum FontStyle {\n normal = '',\n italic = 'Italic',\n}\n\n// Number representing the mega multiplier (2^20)\nexport const MEGA = 1048576\nexport const FONT_FILE_EXTENSIONS = [\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n '.svg',\n]\n\nconst WEIGHT_STYLE_SEPARATOR = ','\n\nexport function flavourToString(value: FontFlavour | undefined) {\n return value && value.join(WEIGHT_STYLE_SEPARATOR)\n}\n\nexport const STYLE_FLAVOUR_OPTIONS = xprod(\n Object.entries(FontStyle),\n Object.entries(FontWeight)\n).map(([[styleValue, styleLabel], [weightValue, weightLabel]]) => ({\n label: (weightLabel + ' ' + styleLabel).trim(),\n value: flavourToString([styleValue, weightValue] as FontFlavour),\n}))\n\nexport function stringToFlavour(value: string) {\n return value.split(WEIGHT_STYLE_SEPARATOR) as FontFlavour\n}\n\nexport function getFontFlavour({\n fontStyle,\n fontWeight,\n}: FontFileInput): FontFlavour {\n return [fontStyle, fontWeight] as FontFlavour\n}\n\ninterface DropdownOption {\n value: string\n label: string\n}\n\nexport function getTypeTokenDropdownOptions(\n key: keyof Font,\n font: Font,\n fontFamilies: FontFamily[]\n): DropdownOption[] {\n const options = (() => {\n switch (key) {\n case 'fontFamily':\n return [\n ...fontFamilies.map(({ fontFamily, id }) => ({\n label: fontFamily,\n value: id,\n })),\n { label: 'Default', value: '' },\n ]\n case 'fontWeight':\n return [\n { label: 'Thin', value: '100' },\n { label: 'Extra Light', value: '200' },\n { label: 'Light', value: '300' },\n { label: 'Normal', value: '400' },\n { label: 'Medium', value: '500' },\n { label: 'Semi Bold', value: '600' },\n { label: 'Bold', value: '700' },\n { label: 'Extra Bold', value: '800' },\n { label: 'Black', value: '900' },\n ]\n case 'fontSize':\n return [\n { label: '48px', value: '3rem' },\n { label: '36px', value: '2.25rem' },\n { label: '24px', value: '1.5rem' },\n { label: '20px', value: '1.25rem' },\n { label: '16px', value: '1rem' },\n { label: '14px', value: '0.875rem' },\n { label: '12px', value: '0.75rem' },\n ]\n case 'letterSpacing':\n return [\n { label: 'Normal', value: 'normal' },\n { label: 'Tracked', value: '.1em' },\n { label: 'Tracked Tight', value: '-.05em' },\n { label: 'Tracked Mega', value: '.25em' },\n { label: 'Zero', value: '0' },\n ]\n case 'textTransform':\n return [\n { label: 'None', value: 'none' },\n { label: 'Capitalize', value: 'capitalize' },\n { label: 'Uppercase', value: 'uppercase' },\n { label: 'Lowercase', value: 'lowercase' },\n ]\n }\n })()\n\n const equalsCurrentValue = ({ value }: DropdownOption) =>\n value === (font[key] || '')\n\n const currentIfNotInOptions =\n options.find(equalsCurrentValue) == null\n ? [{ label: startCase(font[key]), value: font[key] as string }]\n : []\n\n return [...currentIfNotInOptions, ...options]\n}\n\n```" } ]
code_admin-pages_196e2136
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/DeleteFontFamily.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation DeleteFontFamily($id: String) {\n deleteFontFamily(id: $id) {\n id\n }\n}\n\n```" } ]
code_admin-pages_bd61d0c6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/ListFonts.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery ListFonts {\n listFonts {\n id\n fontFamily\n fonts {\n id\n filename\n fontWeight\n fontStyle\n }\n }\n}\n\n```" } ]
code_admin-pages_243dbd13
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/GenerateStyleSheet.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery GenerateStyleSheet($config: ConfigInput) {\n generateStyleSheet(config: $config)\n}\n\n```" } ]
code_admin-pages_e8bc7652
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/UpdateStyle.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation UpdateStyle($id: String, $config: ConfigInput) {\n updateStyle(id: $id, config: $config) {\n path\n selected\n }\n}\n\n```" } ]
code_admin-pages_cb5b915b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/SaveFontFamily.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveFontFamily($font: SaveFontFamilyInput) {\n saveFontFamily(font: $font) {\n id\n fontFamily\n fonts {\n filename\n fontWeight\n fontStyle\n id\n }\n }\n}\n\n```" } ]
code_admin-pages_5207daed
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/RenameStyle.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation RenameStyle($id: String, $name: String) {\n renameStyle(id: $id, name: $name) {\n id\n }\n}\n\n```" } ]
code_admin-pages_b0ca0bba
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/TypeTokensEntry.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport startCase from 'lodash/startCase'\nimport React from 'react'\nimport { RouteComponentProps } from 'react-router'\n\nimport { EditorPath, IdParam } from '../StyleEditorRouter'\n\ninterface EntryProps {\n name: string\n history: RouteComponentProps['history']\n}\n\nconst TypeTokenEntry: React.FunctionComponent<EntryProps> = ({\n name,\n history,\n}) => {\n const handleClick = React.useCallback(\n () => history.push(EditorPath.typeToken.replace(IdParam, name)),\n [history, name]\n )\n\n const handleKeyDown = useKeydownFromClick(handleClick)\n\n return (\n <div\n className=\"pointer flex justify-between items-center pv6 bb b--muted-4 outline-0\"\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <span className=\"f4\">{startCase(name)}</span>\n </div>\n )\n}\n\nexport default TypeTokenEntry\n\n```" } ]
code_admin-pages_b1adf6d0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/TypographyEditor.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 AvailableEditor from '../AvailableEditor'\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport { EditorPath } from '../StyleEditorRouter'\n\ndefineMessages({\n fontFamilyTitle: {\n defaultMessage: 'Font Family',\n id: 'admin/pages.editor.styles.edit.font-family.title',\n },\n})\n\nconst TypographyEditor: React.FunctionComponent = () => {\n const title = (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.typography.title\"\n defaultMessage=\"Typography\"\n />\n )\n\n return (\n <>\n <StyleEditorHeader title={title} />\n <div className=\"ph6\">\n <AvailableEditor\n path={EditorPath.fontFamily}\n titleId=\"admin/pages.editor.styles.edit.font-family.title\"\n />\n <AvailableEditor\n path={EditorPath.typeTokens}\n titleId=\"admin/pages.editor.styles.edit.type-tokens.title\"\n />\n </div>\n </>\n )\n}\n\nexport default TypographyEditor\n\n```" } ]
code_admin-pages_585890be
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/TypeTokenDropdown.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Dispatch } from 'react'\n\nimport startCase from 'lodash/startCase'\nimport { Dropdown } from 'vtex.styleguide'\n\nimport { FontFamily } from '../queries/ListFontsQuery'\nimport { getTypeTokenDropdownOptions } from '../utils/typography'\n\nfunction getOnChange(key: keyof Font, dispatch: Dispatch<Partial<Font>>) {\n return (_: React.ChangeEvent, value: string) => {\n // Workaround since Dropdown does not work well with nil values\n dispatch({ [key]: value === '' ? null : value })\n }\n}\n\nfunction getValue(key: keyof Font, font: Font): string {\n return font[key] || ''\n}\n\ninterface EntryProps {\n font: Font\n fontFamilies: FontFamily[]\n id: keyof Font\n dispatch: Dispatch<Partial<Font>>\n}\n\nconst TypeTokenDropdown: React.FunctionComponent<EntryProps> = ({\n font,\n id,\n dispatch,\n fontFamilies,\n}) => {\n return (\n <div className=\"flex justify-between items-center pv6 bb b--muted-4\">\n <span className=\"f4\">{startCase(id)}</span>\n <Dropdown\n variation=\"inline\"\n onChange={getOnChange(id, dispatch)}\n options={getTypeTokenDropdownOptions(id, font, fontFamilies)}\n value={getValue(id, font)}\n />\n </div>\n )\n}\n\nexport default TypeTokenDropdown\n\n```" } ]
code_admin-pages_5a5bfb58
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/TypeToken.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Dispatch } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { RouteComponentProps } from 'react-router'\n\nimport startCase from 'lodash/startCase'\nimport { Spinner } from 'vtex.styleguide'\n\nimport ListFontsQuery, { ListFontsQueryResult } from '../queries/ListFontsQuery'\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport TypeTokenDropdown from './TypeTokenDropdown'\n\ninterface WrapperProps extends RouteComponentProps<TypeTokenParams> {\n config: TachyonsConfig\n onSave: () => void\n updateConfig: (config: DeepPartial<TachyonsConfig>) => void\n}\n\ninterface Props extends WrapperProps {\n result: ListFontsQueryResult\n}\n\nconst TypeTokenWrapper: React.FunctionComponent<WrapperProps> = props => {\n return (\n <ListFontsQuery>\n {result => <TypeToken {...props} result={result} />}\n </ListFontsQuery>\n )\n}\n\nconst TypeToken: React.FunctionComponent<Props> = ({\n match,\n result: { loading, data, error },\n config,\n onSave: saveStyle,\n updateConfig,\n}) => {\n const token = match.params.id as keyof TypographyStyles\n const { [token]: font } = config.typography.styles\n\n if (loading) {\n return (\n <>\n <StyleEditorHeader title={startCase(token)} />\n <div className=\"pv8 flex justify-center\">\n <Spinner />\n </div>\n </>\n )\n }\n\n if (error != null || data == null) {\n // TODO: add error state\n return <div />\n }\n\n const dispatch: Dispatch<Partial<Font>> = (fontChange: Partial<Font>) =>\n updateConfig({ typography: { styles: { [token]: fontChange } } })\n\n const saveLabel = (\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.save\"\n defaultMessage=\"Save\"\n />\n )\n\n return (\n <>\n <StyleEditorHeader\n title={startCase(token)}\n buttonLabel={saveLabel}\n onButtonClick={saveStyle}\n />\n <div className=\"ph6\">\n {Object.keys(font)\n .filter(key => !key.startsWith('__'))\n .map(key => (\n <TypeTokenDropdown\n font={font}\n dispatch={dispatch}\n fontFamilies={data.listFonts}\n key={key}\n id={key as keyof Font}\n />\n ))}\n </div>\n </>\n )\n}\n\nexport default TypeTokenWrapper\n\n```" } ]
code_admin-pages_82e78b6a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/TypeTokensList.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 { RouteComponentProps } from 'react-router'\n\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport TypeTokenEntry from './TypeTokensEntry'\n\ninterface Props extends RouteComponentProps {\n style: Style\n}\n\nconst TypeTokensList: React.FunctionComponent<Props> = ({ history, style }) => {\n const title = (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.type-tokens.title\"\n defaultMessage=\"Type Tokens\"\n />\n )\n\n const { styles } = style.config.typography\n const tokens = Object.entries(styles)\n .filter(([name]) => !name.startsWith('__'))\n .map(([name, value]) => ({ ...value, name }))\n\n return (\n <>\n <StyleEditorHeader title={title} />\n <div className=\"ph6\">\n {tokens.map(({ name }) => (\n <TypeTokenEntry name={name} key={name} history={history} />\n ))}\n </div>\n </>\n )\n}\n\nexport default TypeTokensList\n\n```" } ]
code_admin-pages_82a03934
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/FontEditor.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useContext, useReducer, useState } from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { matchPath, RouteComponentProps } from 'react-router'\nimport { Button, Spinner, Tab, Tabs, ToastContext } from 'vtex.styleguide'\nimport { ApolloError } from 'apollo-client'\n\nimport DeleteFontFamily, {\n DeleteFontFamilyFn,\n} from '../mutations/DeleteFontFamily'\nimport SaveFontFamily, {\n FontFileInput,\n SaveFontFamilyFn,\n} from '../mutations/SaveFontFamily'\nimport ListFontsQuery, { ListFontsQueryResult } from '../queries/ListFontsQuery'\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport { EditorPath, IdParam } from '../StyleEditorRouter'\nimport { FontFlavour } from '../utils/typography'\nimport FileFontEditor from './FileFontEditor'\n\ninterface FontFileAppend {\n type: 'append'\n files: FontFileInput[]\n}\n\ninterface FontFileRemove {\n type: 'remove'\n index: number\n}\n\ninterface FontFileUpdate {\n type: 'update'\n style: FontFlavour\n index: number\n}\n\nexport type FontFileAction = FontFileAppend | FontFileRemove | FontFileUpdate\n\nconst {\n addFontSuccessMessage,\n fileLinkMessage,\n fileUploadMessage,\n removeFontFailureMessage,\n removeFontSuccessMessage,\n} = defineMessages({\n addFontSuccessMessage: {\n defaultMessage: 'Font family saved succesfully.',\n id: 'admin/pages.editor.styles.edit.font-family.add-font-success',\n },\n fileLinkMessage: {\n defaultMessage: 'File link',\n id: 'admin/pages.editor.styles.edit.custom-font.file-link',\n },\n fileUploadMessage: {\n defaultMessage: 'Upload a file',\n id: 'admin/pages.editor.styles.edit.custom-font.file-upload',\n },\n removeFontFailureMessage: {\n defaultMessage: 'Cannot delete font family, because some style uses it.',\n id: 'admin/pages.editor.styles.edit.font-family.remove-font-failure',\n },\n removeFontSuccessMessage: {\n defaultMessage: 'Font family removed succesfully.',\n id: 'admin/pages.editor.styles.edit.font-family.remove-font-success',\n },\n})\n\nfunction reducer(\n prevState: FontFileInput[],\n action: FontFileAction\n): FontFileInput[] {\n switch (action.type) {\n case 'append':\n return [...prevState, ...action.files]\n case 'remove':\n prevState.splice(action.index, 1)\n return [...prevState]\n case 'update':\n prevState[action.index] = {\n ...prevState[action.index],\n fontStyle: action.style[0],\n fontWeight: action.style[1],\n }\n\n return [...prevState]\n }\n}\n\nfunction canSave(family: string, files: FontFileInput[]) {\n return (\n family &&\n files.length > 0 &&\n files.every(\n ({ fontStyle, fontWeight }) => fontStyle != null && fontWeight != null\n )\n )\n}\n\nfunction hasErrorCode(error: ApolloError | void, code: string): boolean {\n if (error == null || error.graphQLErrors == null) {\n return false\n }\n\n const errorWithCode = error.graphQLErrors.find(\n ({ extensions }) =>\n extensions && extensions.exception && extensions.exception.code === code\n )\n\n return errorWithCode !== undefined\n}\n\nfunction FontEditorTitle() {\n return (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.custom-font.title\"\n defaultMessage=\"Custom Font\"\n />\n )\n}\n\nfunction FontEditorLoading() {\n return (\n <>\n <StyleEditorHeader title={<FontEditorTitle />} />\n <div className=\"pv8 flex justify-center\">\n <Spinner />\n </div>\n </>\n )\n}\n\ninterface Props\n extends RouteComponentProps<CustomFontParams>,\n ListFontsQueryResult {\n deleteFont: DeleteFontFamilyFn\n saveFont: SaveFontFamilyFn\n mutationError: ApolloError | undefined\n loadingSave: boolean\n loadingDelete: boolean\n}\n\nconst CustomFont: React.FunctionComponent<Props> = ({\n data,\n deleteFont,\n error,\n loading,\n loadingDelete,\n loadingSave,\n history,\n saveFont,\n}) => {\n const intl = useIntl()\n const { customFontFile, customFontLink } = EditorPath\n const { pathname } = history.location\n\n const match = matchPath<CustomFontParams>(pathname, customFontFile)\n const paramId = match ? match.params.id : undefined\n\n const fonts = (data && data.listFonts) || []\n const editFamily = fonts.find(\n family => encodeURIComponent(family.id) === paramId\n ) || {\n fontFamily: '',\n fonts: [],\n id: undefined,\n }\n\n const filesReducer = useReducer(reducer, editFamily.fonts)\n const familyState = useState(editFamily.fontFamily)\n const [id] = useState<string | undefined>(editFamily.id)\n const { showToast } = useContext(ToastContext)\n\n const [fontFamily] = familyState\n const [fontFiles] = filesReducer\n\n if (loading) {\n return <FontEditorLoading />\n }\n\n if (error != null || data == null) {\n // TODO: add error state\n return <div />\n }\n\n const disableSave =\n !canSave(fontFamily, fontFiles) || loadingSave || loadingDelete\n\n const onSave = () => {\n saveFont({\n variables: { font: { fontFamily, fontFiles, id } },\n }).then(result => {\n if (result == null || result.data == null) {\n return // TODO: treat errors on delete\n }\n showToast(intl.formatMessage(addFontSuccessMessage))\n history.goBack()\n })\n }\n\n const disableDelete = loadingSave || loadingDelete\n const onDelete = () => {\n deleteFont({ variables: { id: id as string } })\n .then(() => {\n showToast(intl.formatMessage(removeFontSuccessMessage))\n history.goBack()\n })\n .catch(result => {\n if (hasErrorCode(result, 'USED_FONT_DELETE')) {\n showToast(intl.formatMessage(removeFontFailureMessage))\n }\n })\n }\n\n const fontFileTabProps = {\n active:\n matchPath(pathname, customFontFile) != null ||\n matchPath(pathname, EditorPath.customFont.replace(IdParam, '')) != null,\n key: 0,\n label: intl.formatMessage(fileUploadMessage),\n onClick: () =>\n history.replace(EditorPath.customFontFile.replace(IdParam, id || '')),\n }\n\n const fontLinkTabProps = {\n active: matchPath(pathname, customFontLink) != null,\n disabled: true,\n key: 1,\n label: intl.formatMessage(fileLinkMessage),\n onClick: () => history.replace(EditorPath.customFontLink),\n }\n\n return (\n <>\n <StyleEditorHeader title={<FontEditorTitle />}>\n <div>\n {id != null && (\n <Button\n variation=\"tertiary\"\n size=\"small\"\n isLoading={loadingDelete}\n onClick={onDelete}\n disabled={disableDelete}\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.delete\"\n defaultMessage=\"Delete\"\n />\n </Button>\n )}\n <Button\n variation=\"tertiary\"\n size=\"small\"\n isLoading={loadingSave}\n onClick={onSave}\n disabled={disableSave}\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.save\"\n defaultMessage=\"Save\"\n />\n </Button>\n </div>\n </StyleEditorHeader>\n <div className=\"pa7 h-100 overflow-y-auto flex flex-column\">\n <Tabs>\n <Tab {...fontFileTabProps}>\n <FileFontEditor {...{ familyState, filesReducer, showToast }} />\n </Tab>\n <Tab {...fontLinkTabProps} />\n </Tabs>\n </div>\n </>\n )\n}\n\ntype WrapperProps = RouteComponentProps<CustomFontParams>\n\nconst FontEditorWrapper: React.FunctionComponent<WrapperProps> = props => {\n return (\n <ListFontsQuery>\n {queryResult => (\n <DeleteFontFamily>\n {(deleteFont, { loading: deleteLoading, error: deleteError }) => (\n <SaveFontFamily>\n {(saveFont, { loading: saveLoading, error: saveError }) => (\n <CustomFont\n {...props}\n {...queryResult}\n saveFont={saveFont}\n deleteFont={deleteFont}\n loadingSave={saveLoading}\n loadingDelete={deleteLoading}\n mutationError={deleteError || saveError}\n />\n )}\n </SaveFontFamily>\n )}\n </DeleteFontFamily>\n )}\n </ListFontsQuery>\n )\n}\n\nexport default FontEditorWrapper\n\n```" } ]
code_admin-pages_8ad07456
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/FontFamilyList.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 { RouteComponentProps, withRouter } from 'react-router'\n\nimport { Button, Spinner } from 'vtex.styleguide'\nimport { ListFontsQueryResult } from '../queries/ListFontsQuery'\nimport ListFontsQuery from '../queries/ListFontsQuery'\nimport StyleEditorHeader from '../StyleEditorHeader'\nimport { EditorPath, IdParam } from '../StyleEditorRouter'\nimport FontFamilyEntry from './FontFamilyEntry'\n\ninterface Props extends RouteComponentProps, ListFontsQueryResult {}\n\nconst FontFamilyList: React.FunctionComponent<Props> = ({\n data,\n error,\n history,\n loading,\n}) => {\n const title = (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.font-family.title\"\n defaultMessage=\"Font Family\"\n />\n )\n\n if (loading) {\n return (\n <>\n <StyleEditorHeader title={title} />\n <div className=\"pv8 flex justify-center\">\n <Spinner />\n </div>\n </>\n )\n }\n\n if (error != null || data == null) {\n // TODO: add error state\n return <div />\n }\n\n const addFontLabel = (\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.font-family.add-font\"\n defaultMessage=\"Add Custom Font\"\n />\n )\n\n const addFontOnClick = () =>\n history.push(EditorPath.customFontFile.replace(IdParam, ''))\n\n const addFontButton = (\n <Button collapseLeft variation=\"tertiary\" onClick={addFontOnClick}>\n {addFontLabel}\n </Button>\n )\n\n const { listFonts } = data\n\n if (listFonts.length === 0) {\n return (\n <>\n <StyleEditorHeader title={title} />\n <div className=\"ph6 lh-copy\">\n <p>\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.font-family.add-font-description\"\n defaultMessage=\"You can add custom font families to your store, let’s add some?\"\n />\n </p>\n {addFontButton}\n </div>\n </>\n )\n }\n\n return (\n <>\n <StyleEditorHeader\n title={title}\n buttonLabel={addFontLabel}\n onButtonClick={addFontOnClick}\n />\n <div className=\"ph6\">\n {listFonts.map(fontFamily => (\n <FontFamilyEntry font={fontFamily} key={fontFamily.id} />\n ))}\n </div>\n </>\n )\n}\n\nconst FontFamilyListWithRouter = withRouter(FontFamilyList)\n\nconst FontFamilyListWrapper: React.FunctionComponent = () => {\n return (\n <ListFontsQuery>\n {queryResult => <FontFamilyListWithRouter {...queryResult} />}\n </ListFontsQuery>\n )\n}\n\nexport default FontFamilyListWrapper\n\n```" } ]
code_admin-pages_9636596b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/FileFontEditor.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Dispatch, SetStateAction, useCallback } from 'react'\nimport { DropzoneOptions, useDropzone } from 'react-dropzone'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport {\n ActionMenu,\n ButtonWithIcon,\n Dropdown,\n IconOptionsDots,\n IconUpload,\n Input,\n ToastConsumerFunctions,\n} from 'vtex.styleguide'\n\nimport { FontFileInput, FontFileUpload } from '../mutations/SaveFontFamily'\nimport {\n flavourToString,\n FONT_FILE_EXTENSIONS,\n FontFlavour,\n getFontFlavour,\n MEGA,\n stringToFlavour,\n STYLE_FLAVOUR_OPTIONS,\n} from '../utils/typography'\nimport { FontFileAction } from './FontEditor'\n\nconst { pickStylePlaceholder, removeMessage } = defineMessages({\n pickStylePlaceholder: {\n defaultMessage: 'Pick a style',\n id: 'admin/pages.editor.styles.edit.font-family.style-dropdown-placeholder',\n },\n removeMessage: {\n defaultMessage: 'Remove',\n id: 'admin/pages.admin.redirects.form.button.remove',\n },\n})\n\ninterface FileFontEditorProps {\n familyState: [string, Dispatch<SetStateAction<string>>]\n filesReducer: [FontFileInput[], Dispatch<FontFileAction>]\n showToast: ToastConsumerFunctions['showToast']\n}\n\nconst FileFontEditor: React.FunctionComponent<FileFontEditorProps> = ({\n filesReducer,\n familyState,\n showToast,\n}) => {\n const [files, dispatchFiles] = filesReducer\n const [family, setFamily] = familyState\n\n const onInputChange = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => setFamily(e.target.value),\n [setFamily]\n )\n\n const removeFile = (index: number) => dispatchFiles({ type: 'remove', index })\n\n const updateFile = (index: number, style: FontFlavour) =>\n dispatchFiles({ type: 'update', index, style })\n\n const onDrop = (acceptedFiles: File[], rejectedFiles: File[]): void => {\n if (rejectedFiles.length > 0) {\n showToast(\n 'Uploaded files must be under 2MB and have one of the extensions: ' +\n FONT_FILE_EXTENSIONS.join(' ')\n )\n }\n\n if (acceptedFiles.length > 0) {\n dispatchFiles({\n files: acceptedFiles.map(fontFile => ({ fontFile })),\n type: 'append',\n })\n }\n }\n\n const isUpload = (file: FontFileInput): file is FontFileUpload =>\n (file as FontFileUpload).fontFile != null\n\n const getFileName = (file: FontFileInput): string =>\n isUpload(file) ? file.fontFile.name : file.filename\n\n return (\n <div className=\"mv6 w-100\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.font-family.title\"\n defaultMessage=\"Font Family\"\n >\n {label => (\n <Input\n size=\"small\"\n label={label}\n value={family}\n onChange={onInputChange}\n />\n )}\n </FormattedMessage>\n {files.map((file, index) => (\n <FontFileItem\n fileName={getFileName(file)}\n key={getFileName(file)}\n onRemove={() => removeFile(index)}\n onStyleUpdate={(style: FontFlavour) => updateFile(index, style)}\n style={getFontFlavour(files[index])}\n />\n ))}\n <FontFileUploadComponent onDrop={onDrop} />\n </div>\n )\n}\n\ninterface FontFileItemProps {\n fileName: string\n onRemove: () => void\n onStyleUpdate: (style: FontFlavour) => void\n style?: FontFlavour\n}\n\nconst FontFileItem: React.FunctionComponent<FontFileItemProps> = ({\n fileName,\n onRemove,\n onStyleUpdate,\n style,\n}) => {\n const intl = useIntl()\n const actionMenuProps = {\n buttonProps: {\n icon: <IconOptionsDots color=\"currentColor\" />,\n variation: 'tertiary',\n },\n options: [\n {\n label: intl.formatMessage(removeMessage),\n onClick: onRemove,\n },\n ],\n }\n\n const dropdownProps = {\n onChange: (_: React.ChangeEvent, value: string) =>\n onStyleUpdate(stringToFlavour(value)),\n options: STYLE_FLAVOUR_OPTIONS,\n placeholder: intl.formatMessage(pickStylePlaceholder),\n value: flavourToString(style),\n variation: 'inline',\n }\n\n return (\n <div className=\"mv5\">\n <div className=\"flex items-center\">\n <div className=\"mv3\">{fileName}</div>\n <div className=\"flex-grow-1\" />\n <ActionMenu {...actionMenuProps} />\n </div>\n <div className=\"flex items-center\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.custom-font.style\"\n defaultMessage=\"Style:\"\n />\n <Dropdown {...dropdownProps} />\n </div>\n </div>\n )\n}\n\ninterface FontFileUploadProps {\n onDrop: DropzoneOptions['onDrop']\n}\n\nconst FontFileUploadComponent: React.FunctionComponent<FontFileUploadProps> = ({\n onDrop,\n}) => {\n const { getRootProps, getInputProps } = useDropzone({\n accept: FONT_FILE_EXTENSIONS,\n maxSize: 2 * MEGA,\n onDrop,\n })\n return (\n <div className=\"mv6 w-100 flex\">\n <p className=\"t-small\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.custom-font.upload-description\"\n defaultMessage=\"Upload your font family files in .ttf or .woff formats.\"\n />{' '}\n <span className=\"c-muted-2\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.custom-font.upload-description-max-size\"\n defaultMessage=\"(Maximum size 2MB)\"\n />\n </span>\n </p>\n <div {...getRootProps()}>\n <ButtonWithIcon icon={<IconUpload />} variation=\"tertiary\">\n <FormattedMessage\n id=\"admin/pages.editor.styles.edit.custom-font.upload\"\n defaultMessage=\"Upload\"\n />\n <input {...getInputProps()} />\n </ButtonWithIcon>\n </div>\n </div>\n )\n}\n\nexport default FileFontEditor\n\n```" } ]
code_admin-pages_05aa1bfe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typography/FontFamilyEntry.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 { RouteComponentProps, withRouter } from 'react-router'\n\nimport { FontFamily } from '../queries/ListFontsQuery'\nimport { EditorPath, IdParam } from '../StyleEditorRouter'\n\ninterface Props extends RouteComponentProps {\n font: FontFamily\n}\n\nconst FontFamilyEntry: React.FunctionComponent<Props> = ({ font, history }) => {\n const encodedId = React.useMemo(() => encodeURIComponent(font.id), [font.id])\n\n const isActive = React.useMemo(() => document.URL.includes(encodedId), [\n encodedId,\n ])\n\n const handleClick = React.useCallback(\n () => history.push(EditorPath.customFontFile.replace(IdParam, encodedId)),\n [encodedId, history]\n )\n\n const handleKeyDown = useKeydownFromClick(handleClick)\n\n return (\n <div\n aria-selected={isActive}\n className=\"pointer flex justify-between items-center pv6 bb b--muted-4 outline-0\"\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n role=\"option\"\n tabIndex={0}\n >\n <span className=\"f4\">{font.fontFamily}</span>\n </div>\n )\n}\n\nexport default withRouter(FontFamilyEntry)\n\n```" } ]
code_admin-pages_83776554
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/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'\n\nimport { VIEWPORTS_BY_DEVICE } from './consts'\nimport DeviceItem from './DeviceItem'\n\nimport styles from './DeviceSwitcher.css'\n\ninterface Props {\n device: RenderContext['device']\n}\n\nconst DeviceSwitcher: React.FC<Props> = ({ device }) => {\n const editor = useEditorContext()\n\n const handleClick = React.useCallback(\n ({ currentTarget }: Pick<React.MouseEvent, 'currentTarget'>) => {\n if (currentTarget && currentTarget instanceof HTMLElement) {\n editor.setViewport(currentTarget.dataset.type as Viewport)\n }\n },\n [editor]\n )\n\n const viewports = VIEWPORTS_BY_DEVICE[device === 'any' ? 'desktop' : device]\n\n return (\n <div className=\"flex\">\n {viewports.map((deviceType, index) => {\n const isLast = index === viewports.length - 1\n\n return (\n <div className={!isLast ? styles['mr05'] : ''} key={deviceType}>\n <DeviceItem\n isActive={deviceType === editor.viewport}\n onClick={handleClick}\n position={index === 0 ? 'first' : isLast ? 'last' : 'middle'}\n type={deviceType}\n />\n </div>\n )\n })}\n </div>\n )\n}\n\nexport default DeviceSwitcher\n\n```" } ]
code_admin-pages_f5c86331
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/messages.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default {\n desktop: {\n defaultMessage: 'Desktop view',\n id: 'admin/pages.editor.topbar.button.device.desktop.tooltip',\n },\n mobile: {\n defaultMessage: 'Mobile view',\n id: 'admin/pages.editor.topbar.button.device.mobile.tooltip',\n },\n tablet: {\n defaultMessage: 'Tablet view',\n id: 'admin/pages.editor.topbar.button.device.tablet.tooltip',\n },\n}\n\n```" } ]
code_admin-pages_35201802
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/consts.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport IconDesktop from './icons/IconDesktop'\nimport IconMobile from './icons/IconMobile'\nimport IconTablet from './icons/IconTablet'\n\nconst AVAILABLE_VIEWPORTS: Viewport[] = ['mobile', 'tablet', 'desktop']\n\nconst AVAILABLE_MOBILE_VIEWPORTS: Viewport[] = ['mobile', 'tablet']\n\nexport const BORDER_BY_POSITION = {\n first: 'br2 br--left b--transparent',\n last: 'br2 br--right b--transparent',\n middle: 'b--transparent',\n}\n\nexport const ICON_BY_VIEWPORT = {\n desktop: IconDesktop,\n mobile: IconMobile,\n tablet: IconTablet,\n}\n\nexport const VIEWPORTS_BY_DEVICE: Record<\n RenderContext['device'],\n Viewport[]\n> = {\n any: AVAILABLE_VIEWPORTS,\n desktop: AVAILABLE_VIEWPORTS,\n mobile: AVAILABLE_MOBILE_VIEWPORTS,\n}\n\n```" } ]
code_admin-pages_6f63c5ea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/DeviceItem.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 { useIntl } from 'react-intl'\nimport { Tooltip } from 'vtex.styleguide'\n\nimport { useHover } from '../hooks'\nimport { BORDER_BY_POSITION, ICON_BY_VIEWPORT } from './consts'\nimport messages from './messages'\n\ninterface Props {\n isActive: boolean\n onClick: (e: Pick<React.MouseEvent, 'currentTarget'>) => void\n position: keyof typeof BORDER_BY_POSITION\n type: Viewport\n}\n\nconst DeviceItem: React.FC<Props> = ({ onClick, position, isActive, type }) => {\n const handleKeyDown = createKeydownFromClick(onClick)\n\n const { handleMouseEnter, handleMouseLeave, hover } = useHover()\n const intl = useIntl()\n\n const Icon = ICON_BY_VIEWPORT[type]\n\n return (\n <Tooltip label={intl.formatMessage(messages[type])} position=\"bottom\">\n <button\n className={`w2 h2 pointer flex justify-center items-center bg-white outline-0 ${\n isActive || hover ? 'c-action-primary' : 'c-on-disabled'\n } ${BORDER_BY_POSITION[position]}`}\n data-type={type}\n onClick={onClick}\n onKeyDown={handleKeyDown}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n <Icon />\n </button>\n </Tooltip>\n )\n}\n\nexport default DeviceItem\n\n```" } ]
code_admin-pages_86a91544
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { WithApolloClient, withApollo } from 'react-apollo'\nimport { useIntl } from 'react-intl'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport { useEditorContext } from '../../../EditorContext'\nimport BindingSelector from './BindingSelector'\nimport TenantInfoQuery from './graphql/TenantInfo.graphql'\nimport LocaleSelector from './LocaleSelector'\nimport { QueryStateReducer, TenantInfoData } from './typings'\nimport { useBinding } from './hooks/useBinding'\nimport BindingCloning from './BindingCloning'\n\ninterface Props {\n iframeRuntime: RenderContext\n showToast: ToastConsumerFunctions['showToast']\n}\n\nconst ContextSelectors: React.FC<WithApolloClient<Props>> = ({\n client,\n iframeRuntime,\n showToast,\n}) => {\n const [queryState, setQueryState] = React.useReducer<QueryStateReducer>(\n (prevState, state) => ({\n ...prevState,\n ...state,\n }),\n { data: undefined, hasError: false, isLoading: true }\n )\n\n const { binding: iframeBinding, query } = iframeRuntime\n const explicitBinding = Boolean(query?.__bindingAddress)\n const [binding, setBinding] = useBinding()\n const intl = useIntl()\n\n React.useEffect(() => {\n if (iframeBinding || explicitBinding) {\n const fetchBindings = async () => {\n let data, hasError\n\n try {\n const result = await client.query<TenantInfoData>({\n fetchPolicy: 'network-only',\n query: TenantInfoQuery,\n })\n\n data = result.data\n hasError = !!result.errors\n\n setBinding(\n iframeBinding &&\n data.tenantInfo.bindings &&\n data.tenantInfo.bindings.find(\n item => item.id === iframeBinding.id\n )\n )\n } catch {\n hasError = true\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage({\n defaultMessage:\n 'The list of available bindings could not be loaded.',\n id: 'admin/pages.editor.topbar.context.binding.error',\n }),\n })\n } finally {\n setQueryState({ data, hasError, isLoading: false })\n }\n }\n\n fetchBindings()\n }\n }, [client, explicitBinding, setBinding, iframeBinding, intl, showToast])\n\n const bindings = React.useMemo(\n () =>\n queryState.data &&\n queryState.data.tenantInfo.bindings &&\n queryState.data.tenantInfo.bindings.filter(\n item => item.targetProduct === 'vtex-storefront'\n ),\n [queryState.data]\n )\n\n const editor = useEditorContext()\n\n const handleBindingChange = React.useCallback<\n React.ChangeEventHandler<HTMLSelectElement>\n >(\n ({ target: { value } }) => {\n if (bindings) {\n const newBinding = bindings.find(binding => binding.id === value)\n\n if (newBinding && editor.iframeWindow) {\n setBinding(newBinding)\n\n editor.iframeWindow.location.search = `__bindingAddress=${newBinding.canonicalBaseAddress}&__siteEditor=true`\n }\n\n editor.setMode('disabled')\n }\n },\n [bindings, setBinding, editor.iframeWindow]\n )\n\n const bindingOptions = React.useMemo(\n () =>\n bindings\n ? bindings.map(binding => ({\n label: binding.canonicalBaseAddress,\n value: binding.id,\n }))\n : [],\n [bindings]\n )\n\n const localeOptions = React.useMemo(\n () =>\n binding\n ? binding.supportedLocales.map(locale => ({\n label:\n intl.formatMessage({\n id: `admin/pages.editor.locale.${locale.split('-')[0]}`,\n }) + ` (${locale})`,\n value: locale,\n }))\n : editor.availableCultures,\n [binding, editor.availableCultures, intl]\n )\n\n const shouldShowBindingSelector = !!(\n (iframeBinding || explicitBinding) &&\n bindings &&\n bindings.length > 1 &&\n !queryState.hasError\n )\n\n return (\n <>\n {shouldShowBindingSelector && (\n <BindingSelector\n isDisabled={queryState.isLoading || !!editor.editTreePath}\n onChange={handleBindingChange}\n options={bindingOptions}\n value={binding ? binding.id : ''}\n />\n )}\n\n <LocaleSelector\n className={\n shouldShowBindingSelector\n ? 'locale-selector-with-bindings'\n : undefined\n }\n iframeRuntime={iframeRuntime}\n isDisabled={!!editor.editTreePath}\n options={localeOptions}\n />\n {shouldShowBindingSelector && bindings && binding && (\n <div className=\"mh3\">\n <BindingCloning\n bindings={bindings}\n binding={binding}\n iframeRuntime={iframeRuntime}\n />\n </div>\n )}\n </>\n )\n}\n\nexport default withApollo(ContextSelectors)\n\n```" } ]
code_admin-pages_9f8b199a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingSelector.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Dropdown, Tooltip } from 'vtex.styleguide'\nimport { useIntl } from 'react-intl'\n\nimport { useEditorContext } from '../../../EditorContext'\nimport { DropdownOptions, DropdownValue } from './typings'\n\ninterface Props {\n isDisabled: boolean\n onChange: React.ChangeEventHandler<HTMLSelectElement>\n options: DropdownOptions\n value: DropdownValue\n}\n\nconst BindingSelector: React.FC<Props> = ({\n isDisabled,\n onChange,\n options,\n value,\n}) => {\n const Selector = React.useCallback(\n () => (\n <div\n className={\n 'binding-selector' + (isDisabled ? ' binding-selector-disabled' : '')\n }\n >\n <Dropdown\n disabled={isDisabled}\n onChange={onChange}\n options={options}\n size=\"small\"\n value={value}\n />\n </div>\n ),\n [isDisabled, onChange, options, value]\n )\n\n const editor = useEditorContext()\n const intl = useIntl()\n\n return <>\n {editor.editTreePath ? (\n <Tooltip\n label={intl.formatMessage({\n defaultMessage: 'The binding cannot be changed while editing a block.',\n id: 'admin/pages.editor.topbar.context.binding.tooltip',\n })}\n position=\"bottom\"\n >\n <div className=\"flex\">\n <Selector />\n </div>\n </Tooltip>\n ) : (\n <Selector />\n )}\n </>\n}\n\nexport default BindingSelector\n\n```" } ]
code_admin-pages_92a26d98
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/LocaleSelector.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Dropdown, Tooltip } from 'vtex.styleguide'\nimport { useIntl } from 'react-intl'\n\nimport { DropdownOptions } from './typings'\nimport { useEditorContext } from '../../../EditorContext'\n\ninterface Props {\n className?: string\n iframeRuntime: RenderContext\n isDisabled: boolean\n options: DropdownOptions\n}\n\nconst LocaleSelector: React.FC<Props> = ({\n className,\n iframeRuntime,\n isDisabled,\n options,\n}) => {\n const { culture, emitter } = iframeRuntime\n\n const editor = useEditorContext()\n\n const [locale, setLocale] = React.useState(culture.locale)\n\n const handleChange = React.useCallback(\n (e: React.ChangeEvent<HTMLSelectElement>) => {\n editor.setMode('disabled')\n\n setLocale(e?.target?.value)\n\n emitter.emit(\n 'localesChanged',\n e?.target?.value,\n null,\n (locale: string) => {\n let bindingQueryString\n\n if (editor.iframeWindow) {\n const searchParams = new URLSearchParams(\n editor?.iframeWindow?.location.search\n )\n\n const bindingAddress = searchParams.get('__bindingAddress')\n\n if (bindingAddress) {\n bindingQueryString = `__bindingAddress=${decodeURIComponent(\n bindingAddress\n )}`\n }\n\n if (e?.target?.value) {\n editor.iframeWindow.location.search = `${bindingQueryString}&__locale=${e.target.value}&__siteEditor=true`\n } else {\n editor.iframeWindow.location.search = `${bindingQueryString}&__locale=${locale}&__siteEditor=true`\n }\n }\n }\n )\n },\n [emitter]\n )\n\n React.useEffect(() => {\n if (locale !== culture.locale) {\n setLocale(culture.locale)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [culture.locale])\n\n React.useEffect(() => {\n if (editor.mode !== 'content') {\n editor.setMode('content')\n }\n }, [culture.locale, culture.country])\n\n const Selector = React.useCallback(\n () => (\n <div className={className}>\n <Dropdown\n disabled={isDisabled}\n onChange={handleChange}\n options={options}\n size=\"small\"\n value={locale}\n />\n </div>\n ),\n [className, handleChange, isDisabled, locale, options]\n )\n\n const intl = useIntl()\n\n return editor.editTreePath ? (\n <Tooltip\n label={intl.formatMessage({\n defaultMessage: 'The locale cannot be changed while editing a block.',\n id: 'admin/pages.editor.topbar.context.locale.tooltip',\n })}\n position=\"bottom\"\n >\n <div className=\"flex\">\n <Selector />\n </div>\n </Tooltip>\n ) : (\n <Selector />\n )\n}\n\nexport default LocaleSelector\n\n```" } ]
code_admin-pages_69c2c9d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { QueryResult } from 'react-apollo'\n\nexport type DropdownOptions = {\n label: string\n value: string\n}[]\n\nexport type DropdownValue = string\n\ntype BaseAddress = string\n\ntype Locale = string\n\ninterface Binding {\n canonicalBaseAddress: string\n id: string\n supportedLocales: Locale[]\n targetProduct: string\n}\n\ninterface TenantInfo {\n bindings: Binding[]\n}\n\nexport interface TenantInfoData {\n tenantInfo: TenantInfo\n}\n\ninterface QueryState extends Pick<QueryResult<TenantInfoData>, 'data'> {\n hasError: boolean\n isLoading: QueryResult<TenantInfoData>['loading']\n}\n\nexport type QueryStateReducer = (\n prevState: QueryState,\n state: Partial<QueryState>\n) => QueryState\n\n```" } ]
code_admin-pages_defe1084
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/IconPicker.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconEdit: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M15 5.2L15 2.4C15 2.0287 14.8525 1.6726 14.5899 1.41005C14.3274 1.1475 13.9713 1 13.6 1L2.4 1C2.0287 1 1.6726 1.1475 1.41005 1.41005C1.1475 1.6726 0.999999 2.0287 0.999999 2.4L1 13.6C1 13.9713 1.1475 14.3274 1.41005 14.5899C1.6726 14.8525 2.0287 15 2.4 15L5.2 15\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M6 6L8.6329 15.8734L11.5549 12.9513L14.6037 16.0001L16.0001 14.6038L12.9513 11.555L15.8734 8.6329L6 6Z\"\n fill={color}\n />\n </svg>\n)\n\nexport default IconEdit\n\n```" } ]
code_admin-pages_1500bc4e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/CopyContent.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst CopyContent = ({ color = 'currentColor' }: Props) => (\n <svg\n name=\"copy\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 18 18\"\n >\n <path\n d=\"M6.4 0H9.2C10.3046 0 11.2 0.895431 11.2 2V9.2C11.2 10.3046 10.3046 11.2 9.2 11.2H2C0.89543 11.2 0 10.3046 0 9.2V6.4\"\n transform=\"translate(5.80005 12.2) rotate(-90)\"\n stroke={color}\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n <path\n d=\"M9.2 0H2C0.895431 0 0 0.89543 0 2V9.2C0 10.3046 0.89543 11.2 2 11.2H9.2C10.3046 11.2 11.2 10.3046 11.2 9.2V2C11.2 0.895431 10.3046 0 9.2 0Z\"\n transform=\"translate(1 17) rotate(-90)\"\n stroke={color}\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n </svg>\n)\n\nexport default CopyContent\n\n```" } ]
code_admin-pages_ff8a8685
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/icons/IconView.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconView: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"17\"\n height=\"14\"\n viewBox=\"0 0 17 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M1 7C1 7 4 1.5 8.5 1.5C13 1.5 16 7 16 7C16 7 13 12.5 8.5 12.5C4 12.5 1 7 1 7Z\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M8.5 9.5C9.88071 9.5 11 8.38071 11 7C11 5.61929 9.88071 4.5 8.5 4.5C7.11929 4.5 6 5.61929 6 7C6 8.38071 7.11929 9.5 8.5 9.5Z\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n)\n\nexport default IconView\n\n```" } ]
code_admin-pages_bdb24483
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/icons/IconDesktop.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconDesktop: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"16\"\n height=\"17\"\n viewBox=\"0 0 16 17\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M5 16H11\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M14 1H2C1.44772 1 1 1.44771 1 2V11C1 11.5523 1.44772 12 2 12H14C14.5523 12 15 11.5523 15 11V2C15 1.44772 14.5523 1 14 1Z\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n)\n\nexport default IconDesktop\n\n```" } ]
code_admin-pages_c94aee5c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/icons/IconMobile.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconPhone: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"10\"\n height=\"16\"\n viewBox=\"0 0 10 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M9 13L9 3C9 1.89543 8.10457 1 7 1L3 1C1.89543 1 1 1.89543 1 3L1 13C1 14.1046 1.89543 15 3 15L7 15C8.10457 15 9 14.1046 9 13Z\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <circle cx=\"5\" cy=\"12\" r=\"0.5\" fill=\"#CACBCC\" stroke={color} />\n </svg>\n)\n\nexport default IconPhone\n\n```" } ]
code_admin-pages_486108b4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/DeviceSwitcher/icons/IconTablet.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n color?: string\n}\n\nconst IconTablet: React.FC<Props> = ({ color = 'currentColor' }) => (\n <svg\n width=\"14\"\n height=\"18\"\n viewBox=\"0 0 14 18\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M13 15L13 3C13 1.89543 12.1046 1 11 1L3 1C1.89543 1 1 1.89543 1 3L1 15C1 16.1046 1.89543 17 3 17L11 17C12.1046 17 13 16.1046 13 15Z\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <circle cx=\"7\" cy=\"13\" r=\"0.5\" fill=\"#CACBCC\" stroke={color} />\n </svg>\n)\n\nexport default IconTablet\n\n```" } ]
code_admin-pages_7259d91d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/graphql/TenantInfo.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery TenantInfoQuery {\n tenantInfo {\n bindings {\n canonicalBaseAddress\n id\n supportedLocales\n targetProduct\n }\n }\n}\n\n```" } ]
code_admin-pages_a72401d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/graphql/CopyBindings.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation CopyBindingContent($from: String!, $to: String!, $template: String, $context: PageContextInput) {\n copyBindingContent(from: $from, to: $to, template: $template, context: $context) {\n added {\n contentId\n origin\n }\n removed {\n contentId\n origin\n }\n }\n}\n\n```" } ]
code_admin-pages_0f9b5141
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/graphql/SaveRoute.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveRoute($route: NewRouteInput) {\n saveRoute(route: $route) {\n auth\n blockId\n binding\n context\n declarer\n domain\n interfaceId\n path\n routeId\n uuid\n metaTags {\n description\n keywords\n robots\n }\n title\n }\n}\n\n```" } ]
code_admin-pages_2c7fdee7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/graphql/appSettings.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery AppSettings($appName: String, $version: String) {\n appSettings(app: $appName, version: $version)\n @context(provider: \"vtex.apps-graphql\") {\n message\n }\n}\n\n```" } ]
code_admin-pages_a5d2f068
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/graphql/GetRoute.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery GetRoute($routeId: String!) {\n route(routeId: $routeId, domain: \"store\") {\n auth\n blockId\n binding\n context\n declarer\n domain\n interfaceId\n conflicts {\n binding\n blockId\n interfaceId\n routeId\n }\n pages {\n pageId\n condition {\n id\n pageContext {\n id\n type\n }\n allMatches\n statements {\n subject\n verb\n objectJSON\n }\n }\n template\n }\n path\n routeId\n title\n uuid\n metaTags {\n description\n keywords\n robots\n }\n }\n}\n\n```" } ]
code_admin-pages_0762f128
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/hooks/useBinding.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport React, { useMemo } from 'react'\n\nimport { Binding } from '../typings'\n\nconst LAST_BINDING_KEY = 'vtex.site-editor.lastBinding'\n\nexport const useBinding = (): [\n Binding | undefined,\n React.Dispatch<Binding | undefined>\n] => {\n const [binding, setBinding] = React.useState<Binding | undefined>(() => {\n const lastBinding = window.localStorage.getItem(LAST_BINDING_KEY)\n return lastBinding ? (JSON.parse(lastBinding) as Binding) : undefined\n })\n\n return [\n binding,\n useMemo(() => {\n return (value: Binding | undefined) => {\n if (value) {\n window.localStorage.setItem(LAST_BINDING_KEY, JSON.stringify(value))\n } else {\n window.localStorage.removeItem(LAST_BINDING_KEY)\n }\n setBinding(value)\n }\n }, [setBinding]),\n ]\n}\n\n```" } ]
code_admin-pages_a2883a41
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FC, FunctionComponent, useState } from 'react'\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport { Tooltip } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { compose, graphql } from 'react-apollo'\n\nimport { useEditorContext } from '../../../../EditorContext'\nimport { useHover } from '../../hooks'\nimport CopyContent from '../../icons/CopyContent'\nimport { Binding } from '../typings'\nimport BindingCloningModal from './BindingCloningModal'\nimport { CloneContentProvider } from './CloneContentContext'\nimport APP_SETTINGS from '../graphql/appSettings.graphql'\n\ninterface Props {\n bindings: Binding[]\n binding: Binding\n iframeRuntime: RenderContext\n}\n\nconst withSettings = compose(\n graphql(APP_SETTINGS, {\n options: () => {\n const [appName, version] = (process.env.VTEX_APP_ID as string).split('@')\n return {\n variables: {\n appName,\n version,\n },\n }\n },\n })\n)\n\nconst FeatureFlagComponent: FC<{ data: { appSettings?: AppSettings } }> = ({\n children,\n data,\n}) => {\n const { message } = data.appSettings ?? {}\n const settingsParsed = message && (JSON.parse(message) as SettingsParsed)\n const enableFeature =\n settingsParsed && Boolean(settingsParsed.copyContentBinding)\n\n return <>{enableFeature ? children : null}</>\n}\n\nconst FeatureFlag = withSettings(FeatureFlagComponent)\n\nconst BindingCloning: FunctionComponent<Props> = ({\n bindings,\n binding,\n iframeRuntime,\n}) => {\n const [isModalOpen, setModalOpen] = useState(false)\n const editor = useEditorContext()\n const { handleMouseEnter, handleMouseLeave, hover } = useHover()\n\n const handleClick = () => {\n setModalOpen(true)\n }\n\n const handleKeyPress = useKeydownFromClick(handleClick)\n\n const { route, binding: iframeBinding } = iframeRuntime ?? {}\n const { id: routeId, pageContext } = route ?? {}\n\n return (\n <FeatureFlag>\n <Tooltip\n label={\n <FormattedMessage id=\"admin/pages.editor.topbar.button.copy-page.tooltip\" />\n }\n position=\"bottom\"\n >\n <button\n style={editor.mode === 'disabled' ? { cursor: 'wait' } : {}}\n className={`w2 h2 pa3 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 onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onClick={handleClick}\n onKeyPress={handleKeyPress}\n >\n <CopyContent />\n </button>\n </Tooltip>\n <CloneContentProvider\n routeId={routeId}\n bindings={bindings}\n currentBinding={binding}\n pageContext={pageContext}\n iframeBinding={iframeBinding}\n >\n <BindingCloningModal\n isOpen={isModalOpen}\n onClose={() => {\n setModalOpen(false)\n }}\n />\n </CloneContentProvider>\n </FeatureFlag>\n )\n}\n\nexport default BindingCloning\n\n```" } ]
code_admin-pages_bc8f6efa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/BindingSelector.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useReducer } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Checkbox, IconWarning } from 'vtex.styleguide'\n\nexport interface BindingSelectorItem {\n label: string\n id: string\n supportedLocales?: string[]\n checked: boolean\n overwrites?: boolean\n isCurrent?: boolean\n disabled?: boolean\n}\n\nexport type BindingSelectorState = BindingSelectorItem[]\n\nexport type BindingSelectorAction =\n | {\n type: 'set'\n payload: {\n id: string\n value: boolean\n }\n }\n | {\n type: 'toggle'\n payload: { id: string }\n }\n | {\n type: 'check-all' | 'uncheck-all'\n }\n | {\n type: 'set-initial'\n payload: BindingSelectorItem[]\n }\n\nconst reducer = (\n state: BindingSelectorState,\n action: BindingSelectorAction\n) => {\n switch (action.type) {\n case 'toggle': {\n const { id } = action.payload\n\n return state.map(item => {\n if (item.id === id && !item.disabled && !item.isCurrent) {\n return {\n ...item,\n checked: !item.checked,\n }\n }\n\n return item\n })\n }\n case 'set': {\n const { id, value } = action.payload\n\n return state.map(item => {\n if (item.id === id && !item.disabled && !item.isCurrent) {\n return {\n ...item,\n checked: value,\n }\n }\n return item\n })\n }\n case 'check-all':\n return state.map(item => ({\n ...item,\n checked: !item.disabled && !item.isCurrent,\n }))\n case 'uncheck-all':\n return state.map(item => ({\n ...item,\n checked: false,\n }))\n case 'set-initial': {\n return action.payload\n }\n default:\n return state\n }\n}\n\nexport const setInitialBindingState = (bindings: BindingSelectorItem[]) => ({\n type: 'set-initial' as const,\n payload: bindings,\n})\n\ntype BindingSelectorReducer = typeof reducer\n\nexport const useBindingSelectorReducer = () => {\n return useReducer<BindingSelectorReducer>(reducer, [])\n}\n\ninterface Props {\n reducer: [BindingSelectorState, React.Dispatch<BindingSelectorAction>]\n pathId: string\n}\n\nconst BindingSelector: FunctionComponent<Props> = ({ reducer, pathId }) => {\n const [state, dispatch] = reducer\n\n const areAllSelected = state.every(\n item => item.checked || item.disabled || item.isCurrent\n )\n const areSomeSelected = state.some(item => item.checked)\n\n return (\n <table className=\"w-100\">\n <thead className=\"w-100 ph4 truncate overflow-x-hidden c-muted-2 f6\">\n <tr className=\"w-100 truncate overflow-x-hidden\">\n <th className=\"v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s\">\n <Checkbox\n id=\"checkAll\"\n onChange={() => {\n dispatch({\n type: areAllSelected ? 'uncheck-all' : 'check-all',\n })\n }}\n checked={areAllSelected}\n partial={areSomeSelected}\n />\n </th>\n <th className=\"v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s\">\n Binding\n </th>\n <th className=\"v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s\">\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.table-header.supported-locales\" />\n </th>\n <th className=\"v-mid pv0 tl bb b--muted-4 normal bg-base bt ph3 z1 pv3-s\">\n <span className=\"flex items-center\">\n <IconWarning />{' '}\n <p className=\"ml3-s\">\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.table-header.warning\" />\n </p>\n </span>\n </th>\n </tr>\n </thead>\n <tbody>\n {state.map(item => (\n <tr\n className={`w-100 truncate overflow-x-hidden ${\n item.checked ? 'bg-washed-blue' : ''\n }`}\n key={item.id}\n >\n <td className=\"v-mid pv0 tl bb b--muted-4 ph3 z1 pv4-s\">\n <Checkbox\n id={item.id}\n onChange={() =>\n dispatch({\n type: 'toggle',\n payload: {\n id: item.id,\n },\n })\n }\n checked={item.checked}\n disabled={item.disabled || item.isCurrent}\n />\n </td>\n <td className=\"v-mid pv0 tl bb b--muted-4 ph3 z1 pv4-s\">\n <label htmlFor={item.id}>\n {item.label}\n <span className=\"c-muted-2\">{pathId}</span>\n </label>\n </td>\n <td className=\"v-mid pv0 tl bb b--muted-4 ph3 z1 pv4-s\">\n {item.supportedLocales && item.supportedLocales.length > 1 ? (\n <p>{item.supportedLocales.join(', ')}</p>\n ) : null}\n </td>\n <td className=\"v-mid pv0 tl bb b--muted-4 ph3 z1 pv4-s\">\n {item.overwrites && !item.isCurrent && (\n <div className=\"f6 c-muted-1 dib ml4\">\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.warning.page-exists\" />\n </div>\n )}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )\n}\n\nexport default BindingSelector\n\n```" } ]
code_admin-pages_d34e9994
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/OverwriteDialog.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useState } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Button, Modal } from 'vtex.styleguide'\n\nimport { BindingSelectorState } from './BindingSelector'\n\ninterface Props {\n isOpen?: boolean\n state: BindingSelectorState\n pathId: string\n onClose: () => void\n onConfirm?: (value: void | PromiseLike<void>) => void\n onCancel?: (reason?: unknown) => void\n}\n\nexport const useOverwriteDialogState = () => {\n const [overwriteHandlers, setOverwriteHandlers] = useState<null | {\n onConfirm: (value: void | PromiseLike<void>) => void\n onCancel: (reason?: unknown) => void\n }>(null)\n\n return {\n isOverwriteDialogOpen: Boolean(overwriteHandlers),\n showOverwriteDialog: setOverwriteHandlers,\n hideOverwriteDialog: () => {\n setOverwriteHandlers(null)\n },\n onOverwriteConfirm: overwriteHandlers?.onConfirm ?? (() => undefined),\n onOverwriteCancel: overwriteHandlers?.onCancel ?? (() => undefined),\n }\n}\n\nconst OverwriteDialog: FunctionComponent<Props> = ({\n isOpen,\n onClose,\n state,\n pathId,\n onConfirm,\n onCancel,\n}) => {\n const overwrittenContent =\n state?.filter(item => item.overwrites && item.checked) ?? []\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n bottomBar={\n <div className=\"flex justify-end\">\n <span className=\"mr4\">\n <Button\n variation=\"secondary\"\n onClick={() => {\n onCancel?.()\n onClose()\n }}\n >\n <FormattedMessage id=\"admin/pages.editor.components.button.go-back\" />\n </Button>\n </span>\n <Button\n variation=\"danger\"\n onClick={() => {\n onConfirm?.()\n onClose()\n }}\n >\n <FormattedMessage id=\"admin/pages.editor.components.button.overwrite\" />\n </Button>\n </div>\n }\n >\n <div className=\"mb6\">\n <div className=\"mb6\">\n <h2 className=\"mb4\">\n <FormattedMessage id=\"admin/pages.editor.copy-page.overwritedialog.header\" />\n </h2>\n {overwrittenContent.length > 1 ? (\n <FormattedMessage id=\"admin/pages.editor.copy-page.overwritedialog.subheader.singular\" />\n ) : (\n <FormattedMessage id=\"admin/pages.editor.copy-page.overwritedialog.subheader.plural\" />\n )}\n </div>\n <div className=\"mb6 ml6\">\n <ul>\n {overwrittenContent.map(item => (\n <li className=\"mb4\" key={item.id}>\n <div>\n {item.label}\n <span className=\"c-muted-2\">{pathId}</span>\n </div>\n {item.supportedLocales && item.supportedLocales.length > 0 && (\n <ul className=\"list pa0 ma0 mt2 ml6 f6 c-muted-1\">\n {item.supportedLocales.map((locale, i, arr) => (\n <li className=\"dib\" key={locale}>\n {locale}\n {i < arr.length - 1 && <span>, </span>}\n </li>\n ))}\n </ul>\n )}\n </li>\n ))}\n </ul>\n </div>\n <FormattedMessage id=\"admin/pages.editor.copy-page.overwritedialog.confirmation\" />\n </div>\n </Modal>\n )\n}\n\nexport default OverwriteDialog\n\n```" } ]
code_admin-pages_819c6630
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/BindingCloningModal.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useEffect, useRef } from 'react'\nimport {\n Button,\n Modal,\n ShowToastFunction,\n Spinner,\n ToastConsumer,\n EmptyState,\n} from 'vtex.styleguide'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { pick } from 'ramda'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport BindingSelector, { BindingSelectorItem } from './BindingSelector'\nimport {\n CopyBindingVariables,\n SaveRouteVariables,\n useCloneContent,\n} from './CloneContentContext'\nimport OverwriteDialog, { useOverwriteDialogState } from './OverwriteDialog'\nimport { createEventObject } from '../../../../../utils/auditEvents'\nimport SendEventToAuditMutation, {\n SendEventToAuditMutationFn,\n} from '../../../mutations/SendEventToAudit'\n\ninterface Props {\n isOpen?: boolean\n onClose: () => void\n}\n\nconst saveRouteSanityCheck = (variables: SaveRouteVariables) => {\n const route = variables?.route\n\n if (\n !route ||\n // uuid shouldn't be defined, it will be generated on route creation,\n // otherwise it might replace an existing route\n route.uuid ||\n // dataSource needs to be 'vtex.rewriter', otherwise it will be\n // treated as a \"colossus\" route, which is not what we want here\n route.dataSource !== 'vtex.rewriter' ||\n !route.bindingId\n ) {\n return false\n }\n\n return true\n}\n\nconst copyBindingsSanityCheck = (variables: CopyBindingVariables) => {\n if (\n !variables ||\n // If any of these values is empty, it might cause the\n // copyBindingContent mutation to be too broad, so we\n // are double checking them here to be a bit more safe\n !variables.from ||\n !variables.to ||\n !variables.template ||\n !variables.context ||\n !variables.context.type ||\n !variables.context.id\n ) {\n return false\n }\n\n return true\n}\n\ntype SubmitStatus = 'IDLE' | 'SUBMITTING'\n\nconst toastMessages = defineMessages({\n saving: {\n id: 'admin/pages.editor.copy-page.modal.toast.saving',\n },\n success: {\n id: 'admin/pages.editor.copy-page.modal.toast.success',\n },\n error: {\n id: 'admin/pages.editor.copy-page.modal.toast.error',\n },\n})\n\nconst BindingCloningModal: FunctionComponent<Props> = ({ isOpen, onClose }) => {\n const [submitStatus, setSubmitStatus] = React.useState<SubmitStatus>('IDLE')\n const intl = useIntl()\n\n const {\n showOverwriteDialog,\n isOverwriteDialogOpen,\n hideOverwriteDialog,\n onOverwriteCancel,\n onOverwriteConfirm,\n } = useOverwriteDialogState()\n\n const { data, actions } = useCloneContent()\n\n const {\n loading,\n error,\n routeInfo,\n bindingSelector,\n currentBinding,\n pageContext,\n } = data\n\n const {\n refetchRouteInfo,\n dispatchBindingSelector,\n saveRoute,\n copyBindings,\n } = actions\n const { account, workspace } = useRuntime()\n\n const checkOverwrites = () => {\n return new Promise<void>((resolve, reject) => {\n const checkedItems = bindingSelector.filter(item => item.checked)\n const willOverwrite = checkedItems.some(item => item.overwrites)\n\n if (!willOverwrite) {\n resolve()\n return\n }\n\n showOverwriteDialog({\n onConfirm: resolve,\n onCancel: reject,\n })\n })\n }\n\n // Refetches and cleans up selection when the modal is\n // closed and reopened\n const wasOpen = useRef(true)\n useEffect(() => {\n if (!wasOpen.current && isOpen) {\n refetchRouteInfo()\n dispatchBindingSelector({ type: 'uncheck-all' })\n wasOpen.current = false\n }\n\n if (wasOpen.current && isOpen) {\n wasOpen.current = false\n }\n }, [wasOpen, isOpen, refetchRouteInfo, dispatchBindingSelector])\n\n const saveItem = async (item: BindingSelectorItem) => {\n if (!routeInfo) return\n\n const copyBindingsVariables = {\n from: currentBinding.id,\n to: item.id,\n template: routeInfo.blockId,\n context: pageContext,\n }\n\n if (!copyBindingsSanityCheck(copyBindingsVariables)) {\n throw new Error()\n }\n\n try {\n if (!item.overwrites) {\n const saveRouteVariables = {\n route: {\n ...pick(\n [\n 'auth',\n 'blockId',\n 'context',\n 'declarer',\n 'domain',\n 'interfaceId',\n 'path',\n 'routeId',\n 'pages',\n 'title',\n 'metaTags',\n ],\n routeInfo\n ),\n dataSource: 'vtex.rewriter',\n bindingId: item.id,\n },\n }\n\n if (!saveRouteSanityCheck(saveRouteVariables)) {\n throw new Error()\n }\n\n const { error: errorSavingRoute } = await saveRoute({\n variables: saveRouteVariables,\n })\n if (errorSavingRoute) {\n throw new Error()\n }\n }\n const { error: errorCopyingBindings } = await copyBindings({\n variables: copyBindingsVariables,\n })\n if (errorCopyingBindings) {\n throw new Error()\n }\n } catch (error) {\n console.error(error)\n throw error\n }\n }\n\n const applyChanges = async () => {\n const checkedItems = bindingSelector.filter(item => item.checked)\n for (const item of checkedItems) {\n try {\n await saveItem(item)\n } catch (error) {\n console.error(error)\n throw error\n }\n }\n }\n\n const handleClose = () => {\n setSubmitStatus('IDLE')\n onClose()\n }\n\n const handleConfirmCopyContent = async ({\n showToast,\n sendEventToAudit,\n }: {\n showToast: ShowToastFunction\n sendEventToAudit: SendEventToAuditMutationFn\n }) => {\n if (submitStatus === 'SUBMITTING') {\n return\n }\n\n setSubmitStatus('SUBMITTING')\n\n try {\n // It doesn't throw an error. User just refused to overwrite\n await checkOverwrites()\n\n showToast({\n message: intl.formatMessage(toastMessages.saving),\n duration: Infinity,\n })\n try {\n await applyChanges()\n\n const event = createEventObject(\n 'Copy binding content',\n 'binding',\n account,\n workspace\n )\n await sendEventToAudit({\n variables: { input: event },\n })\n\n setTimeout(() => {\n showToast(intl.formatMessage(toastMessages.success))\n }, 500)\n } catch {\n // There is a bug with the Toast component, where\n // if you call two toasts on rapid succession,\n // the second one will be ignored. This timeout\n // gets around this issue, which happens if the error\n // is immediate\n setTimeout(() => {\n showToast(intl.formatMessage(toastMessages.error))\n }, 500)\n }\n } finally {\n handleClose()\n }\n }\n\n return (\n <>\n <ToastConsumer>\n {({ showToast }) => (\n <Modal\n isOpen={isOpen}\n onClose={handleClose}\n bottomBar={\n <div className=\"flex justify-end\">\n <span className=\"mr4\">\n <Button onClick={handleClose} variation=\"secondary\">\n <FormattedMessage id=\"admin/pages.editor.components.button.cancel\" />\n </Button>\n </span>\n <SendEventToAuditMutation>\n {sendEventToAudit => (\n <Button\n disabled={submitStatus === 'SUBMITTING'}\n onClick={() =>\n handleConfirmCopyContent({\n showToast,\n sendEventToAudit,\n })\n }\n >\n <FormattedMessage id=\"admin/pages.editor.components.button.save\" />\n </Button>\n )}\n </SendEventToAuditMutation>\n </div>\n }\n >\n <div className=\"mb6\">\n <h3>\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.header\" />\n </h3>\n {loading ? (\n <div className=\"tc min-h-large-l\">\n <Spinner color=\"currentColor\" />\n </div>\n ) : error || !routeInfo ? (\n <EmptyState\n title={\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.error.title\" />\n }\n >\n <p>\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.error.body\" />\n </p>\n </EmptyState>\n ) : (\n <>\n <div className=\"f5 mb5\">\n <FormattedMessage id=\"admin/pages.editor.copy-page.modal.subheader\" />\n </div>\n <BindingSelector\n reducer={[bindingSelector, dispatchBindingSelector]}\n pathId={routeInfo.path}\n />\n </>\n )}\n </div>\n </Modal>\n )}\n </ToastConsumer>\n <OverwriteDialog\n state={bindingSelector}\n pathId={routeInfo?.path ?? ''}\n isOpen={isOverwriteDialogOpen}\n onClose={hideOverwriteDialog}\n onConfirm={onOverwriteConfirm}\n onCancel={onOverwriteCancel}\n />\n </>\n )\n}\n\nexport default BindingCloningModal\n\n```" } ]
code_admin-pages_7e256e9b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/CloneContentContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, {\n FC,\n createContext,\n useContext,\n useEffect,\n Dispatch,\n} from 'react'\nimport { compose, graphql, QueryResult } from 'react-apollo'\nimport {\n ApolloError,\n ApolloQueryResult,\n OperationVariables,\n} from 'apollo-client'\n\nimport GetRouteQuery from '../graphql/GetRoute.graphql'\nimport {\n BindingSelectorState,\n setInitialBindingState,\n useBindingSelectorReducer,\n BindingSelectorAction,\n BindingSelectorItem,\n} from './BindingSelector'\nimport SaveRouteMutation from '../graphql/SaveRoute.graphql'\nimport CopyBindingsMutation from '../graphql/CopyBindings.graphql'\nimport { Binding } from '../typings'\nimport { createInitialCloningState } from './utils/initialReducerState'\n\nconst withBindingsQueries = compose(\n graphql<{ routeId: string }, {}>(GetRouteQuery, {\n name: 'routeInfoQuery',\n options: ({ routeId }) => ({\n notifyOnNetworkStatusChange: true,\n variables: { routeId },\n }),\n }),\n graphql(SaveRouteMutation, { name: 'saveRoute' }),\n graphql(CopyBindingsMutation, { name: 'copyBindings' })\n)\n\ninterface CloneContentContextValue {\n data: {\n loading: boolean\n error?: ApolloError\n routeInfo?: Route\n bindingSelector: BindingSelectorState\n currentBinding: Binding\n pageContext: PageContext\n }\n actions: {\n refetchRouteInfo: (\n variables?: OperationVariables\n ) => Promise<ApolloQueryResult<Route>>\n dispatchBindingSelector: Dispatch<BindingSelectorAction>\n saveRoute: (\n args: MutationArgs<SaveRouteVariables>\n ) => Promise<QueryResult<unknown>>\n copyBindings: (\n args: MutationArgs<CopyBindingVariables>\n ) => Promise<QueryResult<unknown>>\n }\n}\n\nconst CloneContentContext = createContext<CloneContentContextValue>(\n {} as CloneContentContextValue\n)\n\nexport interface SaveRouteVariables {\n route: Route\n}\n\ntype MutationArgs<T> = {\n variables: T\n}\n\nexport interface CopyBindingVariables {\n from: Binding['id']\n to: BindingSelectorItem['id']\n template: Route['blockId']\n context: PageContext\n}\n\ninterface WithBindingsQueriesProps {\n routeInfoQuery: QueryResult & { route?: Route }\n saveRoute: (\n args: MutationArgs<SaveRouteVariables>\n ) => Promise<QueryResult<unknown>>\n copyBindings: (\n args: MutationArgs<CopyBindingVariables>\n ) => Promise<QueryResult<unknown>>\n}\n\ninterface CloneContentProps {\n routeId: string\n bindings: Binding[]\n currentBinding: Binding\n pageContext: PageContext\n iframeBinding: RenderContext['binding']\n}\n\nconst CloneContentProvider: FC<CloneContentProps &\n WithBindingsQueriesProps> = ({\n children,\n routeInfoQuery,\n bindings,\n currentBinding,\n pageContext,\n saveRoute,\n copyBindings,\n iframeBinding,\n}) => {\n const [bindingSelector, dispatchBindingSelector] = useBindingSelectorReducer()\n const {\n route: routeInfo,\n loading: routeInfoLoading,\n error,\n refetch: refetchRouteInfo,\n } = routeInfoQuery\n\n useEffect(() => {\n if (routeInfo) {\n const initialState = bindings.map(binding =>\n createInitialCloningState(binding, currentBinding, routeInfo)\n )\n dispatchBindingSelector(setInitialBindingState(initialState))\n }\n }, [bindings, currentBinding, dispatchBindingSelector, routeInfo])\n\n /**\n * This check currentBinding.id !== iframeBinding?.id is needed to avoid the blinking\n * in the modal when user changes the binding.\n * The blinking is happening because there is a race condition on ContextSelectors/index.ts\n * When handleBindingChange is called, it sets the target binding as binding in the state.\n * However, when the useEffect in that file runs next time, it sets bindings to the old one,\n * coming from iframeBinding, which seems to be beeing update afterwards. Then, when iframeBinding\n * updates, the setBinding is called called, now with the target binding causing the blinking.\n */\n const loading =\n routeInfoLoading ||\n (currentBinding && currentBinding.id !== iframeBinding?.id)\n\n return (\n <CloneContentContext.Provider\n value={{\n data: {\n loading,\n error,\n routeInfo,\n bindingSelector,\n currentBinding,\n pageContext,\n },\n actions: {\n refetchRouteInfo,\n dispatchBindingSelector,\n saveRoute,\n copyBindings,\n },\n }}\n >\n {children}\n </CloneContentContext.Provider>\n )\n}\n\nconst useCloneContent = () => useContext(CloneContentContext)\n\nconst ProviderWithQueries: FC<CloneContentProps> = withBindingsQueries(\n CloneContentProvider\n)\n\nexport { ProviderWithQueries as CloneContentProvider, useCloneContent }\n\n```" } ]
code_admin-pages_846fa926
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/ContextSelectors/BindingCloning/utils/initialReducerState.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Binding } from '../../typings'\n\nconst formatBindings = (binding: Binding, currentBinding: Binding) => ({\n label: binding.canonicalBaseAddress,\n id: binding.id,\n supportedLocales: binding.supportedLocales,\n checked: false,\n overwrites: false,\n isCurrent: currentBinding.id === binding.id,\n})\n\n// Mark items as conflicting or not--that is, if saving on a\n// binding will overwrite a page present there or not\nexport const createInitialCloningState = (\n binding: Binding,\n currentBinding: Binding,\n routeInfo: Route\n) => {\n const formattedBinding = formatBindings(binding, currentBinding)\n\n if (formattedBinding.isCurrent) {\n return formattedBinding\n }\n\n // If the page has undefined binding, it is present on all bindings\n if (!routeInfo.binding) {\n return {\n ...formattedBinding,\n overwrites: true,\n }\n }\n\n if (!routeInfo.conflicts) {\n return formattedBinding\n }\n\n if (\n routeInfo.conflicts.find(\n conflict => formattedBinding.id === conflict.binding\n )\n ) {\n return {\n ...formattedBinding,\n overwrites: true,\n }\n }\n\n return formattedBinding\n}\n\n```" } ]
code_admin-pages_14e47f5e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/utils.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport {\n AvailableApp,\n InstalledApp,\n} from '../store/StoreForm/components/withStoreSettings'\n\nexport const parseStoreAppId = (\n store: InstalledApp & AvailableApp & { settings: string }\n) => {\n const appMajor = store.version.split('.')[0]\n return `${store.slug}@${appMajor}.x`\n}\n\n```" } ]
code_admin-pages_9b61996b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AlertProps } from 'vtex.styleguide'\n\nexport interface RedirectsQuery {\n redirect: {\n list: Redirect[]\n numberOfEntries: number\n }\n}\n\nexport interface AlertState {\n type: AlertProps['type']\n message: string\n meta?: {\n failedRedirects: Redirect[]\n mutation: (data: Redirect[]) => Promise<void>\n isSave: boolean\n }\n action?: {\n label: string\n }\n}\n\n```" } ]
code_admin-pages_5f72f049
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/consts.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const BASE_URL = '/admin/app/cms/redirects'\nexport const CSV_SEPARATOR = ';'\n\nexport const getCSVHeader = (hasMultipleBindings: boolean) =>\n hasMultipleBindings ? 'from;to;type;binding;endDate' : 'from;to;type;endDate'\n\nconst CSV_SINGLE_BINDING_TEMPLATE = `/temporary;/;TEMPORARY;\n/temporary-with-date;/;TEMPORARY;2025-01-01T00:00:00.000Z;\n/permanent;/;PERMANENT;\n`\nconst CSV_MULTIPLE_BINDING_TEMPLATE = `/temporary;/;TEMPORARY;\n/temporary-with-date;/;TEMPORARY;1234_binding_id;2025-01-01T00:00:00.000Z;\n/permanent;/;PERMANENT;123_binding_id;\n`\n\nexport const getCSVTemplate = (hasMultipleBindings: boolean) =>\n `${getCSVHeader(hasMultipleBindings)}\n ${\n hasMultipleBindings\n ? CSV_MULTIPLE_BINDING_TEMPLATE\n : CSV_SINGLE_BINDING_TEMPLATE\n }`\n\nexport const NEW_REDIRECT_ID = 'new'\n\nexport const PAGINATION_START = 0\nexport const PAGINATION_STEP = 10\nexport const REDIRECTS_LIMIT = 500\n\nexport const WRAPPER_PATH = 'redirects'\n\n```" } ]
code_admin-pages_5ba62927
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/bulkUploadRedirects.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MutableRefObject } from 'react'\nimport { splitEvery } from 'ramda'\n\nconst MAX_REDIRECTS_PER_REQUEST = 200\nconst NUMBER_OF_RETRIES = 3\n\ninterface BulkUploadRedirectsArgs {\n data: Redirect[]\n mutation: (data: Redirect[]) => Promise<void>\n isSave: boolean\n shouldUploadRef: MutableRefObject<boolean>\n updateProgress?: (processed: number) => void\n}\n\nexport default async function bulkUploadRedirects({\n data,\n mutation,\n shouldUploadRef,\n updateProgress = () => {\n return undefined\n },\n}: BulkUploadRedirectsArgs): Promise<{ failedRedirects: Redirect[] }> {\n let failedRedirects: Redirect[] = []\n let processedCount = 0\n\n const redirectBatches = splitEvery(MAX_REDIRECTS_PER_REQUEST, data)\n\n for (const payload of redirectBatches) {\n if (!shouldUploadRef.current) {\n break\n }\n\n for (let i = 1; i <= NUMBER_OF_RETRIES; i++) {\n try {\n await mutation(payload)\n processedCount += payload.length\n updateProgress(processedCount)\n break\n } catch (e) {\n await new Promise(res => {\n setTimeout(() => res(), i * 750)\n })\n if (i === NUMBER_OF_RETRIES) {\n failedRedirects = failedRedirects.concat(payload)\n }\n }\n }\n\n await new Promise(res => {\n setTimeout(() => res(), 750)\n })\n }\n\n return { failedRedirects }\n}\n\n```" } ]
code_admin-pages_11409d20
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport startCase from 'lodash/startCase'\n\ntype NewRouteTypeArg = Pick<Route, 'uuid' | 'declarer'>\nexport const isNewRoute = (route: NewRouteTypeArg) =>\n !route.uuid && !route.declarer\n\nexport const isUserRoute = (route: NewRouteTypeArg) => !route.declarer\n\ntype GetRouteTitleArg = Pick<Route, 'title' | 'blockId' | 'interfaceId'> &\n NewRouteTypeArg\n\nexport const getRouteTitle = (route: GetRouteTitleArg) => {\n const { blockId, declarer, interfaceId, title } = route\n\n const nameFromInterfaceOrBlock = startCase(\n blockId.split('#')[1] ||\n interfaceId.split('.')[interfaceId.split('.').length - 1]\n )\n\n if (isNewRoute(route)) {\n return title || ''\n }\n\n return declarer\n ? nameFromInterfaceOrBlock || title\n : title || nameFromInterfaceOrBlock\n}\n\nexport const isStoreRoute = (domain: Route['domain']) => domain === 'store'\n\n```" } ]
code_admin-pages_f66e3d0f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/SeparatorWithLine.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst SeparatorWithLine = () => <div className=\"mv5 bb b--light-silver\" />\n\nexport default SeparatorWithLine\n\n```" } ]
code_admin-pages_85eca181
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/consts.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const NEW_ROUTE_ID = 'new'\n\nexport const ROUTES_FORM = 'admin.app.cms.pages.page-details'\n\nexport const ROUTES_LIST = 'admin.app.cms.pages.page-list'\n\nexport const INSTITUTIONAL_ROUTES_LIST = 'admin.app.cms.content'\n\nexport const INSTITUTIONAL_ROUTES_FORM = 'admin.app.cms.content-details'\n\nexport const WRAPPER_PATH = 'pages'\n\nexport const DATA_SOURCE = 'vtex.rewriter'\n\n```" } ]
code_admin-pages_da5ca27d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/store/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, WrappedComponentProps } from 'react-intl'\nimport { Tab, Tabs } from 'vtex.styleguide'\n\nimport PWAForm from './PWAForm'\nimport StoreForm from './StoreForm'\n\nimport '../../../styles.global.css'\n\nconst messages = defineMessages({\n advanced: {\n defaultMessage: 'Advanced',\n id: 'admin/pages.editor.store.settings.tabs.advanced',\n },\n general: {\n defaultMessage: 'General',\n id: 'admin/pages.editor.store.settings.tabs.general',\n },\n pwa: {\n defaultMessage: 'PWA',\n id: 'admin/pages.editor.store.settings.tabs.pwa',\n },\n})\n\nconst Store: React.FC<WrappedComponentProps> = ({ intl }) => {\n const [activeTab, setActiveTab] = React.useState<\n 'advanced' | 'general' | 'pwa'\n >('general')\n\n const handleAdvancedOpen = React.useCallback(() => {\n setActiveTab('advanced')\n }, [])\n\n const handlePWAOpen = React.useCallback(() => {\n setActiveTab('pwa')\n }, [])\n\n const handleGeneralOpen = React.useCallback(() => {\n setActiveTab('general')\n }, [])\n\n return (\n <div className=\"mb7 ph7\">\n <Tabs>\n <Tab\n active={activeTab === 'general'}\n onClick={handleGeneralOpen}\n label={intl.formatMessage(messages.general)}\n >\n <div className=\"pv6\">\n <StoreForm tab=\"general\" />\n </div>\n </Tab>\n\n <Tab\n active={activeTab === 'advanced'}\n onClick={handleAdvancedOpen}\n label={intl.formatMessage(messages.advanced)}\n >\n <div className=\"pv6\">\n <StoreForm tab=\"advanced\" />\n </div>\n </Tab>\n\n <Tab\n active={activeTab === 'pwa'}\n onClick={handlePWAOpen}\n label={intl.formatMessage(messages.pwa)}\n >\n <div className=\"pv6\">\n <PWAForm />\n </div>\n </Tab>\n </Tabs>\n </div>\n )\n}\n\nexport default injectIntl(Store)\n\n```" } ]
code_admin-pages_642d5bef
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { RouteFormData } from 'pages'\nimport { isEmpty } from 'ramda'\nimport * as React from 'react'\nimport {\n defineMessages,\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { ToastConsumerFunctions } from 'vtex.styleguide'\n\nimport { formatStatements } from '../../../../utils/conditions'\nimport { FormErrors } from '../../pages/Form/typings'\nimport { generateNewRouteId } from '../../pages/Form/utils'\nimport { FormProps } from '../../store/StoreForm/components/withStoreSettings'\nimport Form from './Form'\nimport { getValidateFormState } from './utils'\nimport { OperationsResults } from './withContentContext'\n\ninterface ComponentProps {\n culture: RenderContext['culture']\n initialData: RouteFormData\n initialContent: {\n id: string\n text: string\n }\n onDelete: OperationsResults['deleteRoute']\n onExit: () => void\n onSave: OperationsResults['saveRoute']\n onSaveContent: OperationsResults['saveContent']\n showToast: ToastConsumerFunctions['showToast']\n hideToast: ToastConsumerFunctions['hideToast']\n}\n\nexport interface RouteContentFromData {\n pageContent?: string\n contentId: string\n}\n\ntype Props = ComponentProps & ComponentWithIntlProps & FormProps\n\nexport interface State {\n data: RouteFormData & RouteContentFromData\n isLoading: boolean\n formErrors: FormErrors\n isDeletable: boolean\n isInfoEditable: boolean\n}\n\nconst messages = defineMessages({\n deleteError: {\n defaultMessage: 'Error: route could not be deleted.',\n id: 'admin/pages.admin.pages.form.delete.error',\n },\n deleteSuccess: {\n defaultMessage: 'Success',\n id: 'admin/pages.admin.pages.form.delete.success',\n },\n saveError: {\n defaultMessage: 'Error: route could not be saved.',\n id: 'admin/pages.admin.pages.form.save.error',\n },\n saveSuccess: {\n defaultMessage: 'Success',\n id: 'admin/pages.admin.pages.form.save.success',\n },\n})\n\nclass FormContainer extends React.PureComponent<Props, State> {\n public constructor(props: Props) {\n super(props)\n\n const isNew = !props.initialData.uuid\n\n this.state = {\n data: {\n ...props.initialData,\n contentId: props.initialContent.id,\n pageContent: props.initialContent.text,\n },\n formErrors: {},\n isDeletable: !isNew,\n isInfoEditable: isNew,\n isLoading: false,\n }\n }\n\n public render() {\n const { onExit } = this.props\n const {\n data,\n isDeletable,\n isInfoEditable,\n isLoading,\n formErrors,\n } = this.state\n\n return (\n <Form\n data={data}\n errors={formErrors}\n isDeletable={isDeletable}\n isInfoEditable={isInfoEditable}\n isLoading={isLoading}\n onDelete={this.handleDelete}\n onExit={onExit}\n onFieldValueChange={this.handleChangeFieldValue}\n onSubmit={this.handleSave}\n />\n )\n }\n\n private handleChangeFieldValue = (\n field: string,\n value: string | number | null\n ) => {\n return this.setState(prevState => ({\n ...prevState,\n data: {\n ...prevState.data,\n [field]: value,\n },\n formErrors: {},\n }))\n }\n\n private handleSave = (event: React.FormEvent) => {\n const {\n intl,\n onExit,\n onSave,\n showToast,\n onSaveContent,\n culture,\n } = this.props\n event.preventDefault()\n\n const nextState = getValidateFormState(this.state)\n if (isEmpty(nextState.formErrors)) {\n const {\n auth,\n blockId,\n contentId,\n context,\n declarer,\n domain,\n interfaceId,\n metaTagDescription,\n metaTagKeywords,\n metaTagRobots,\n pageContent,\n pages,\n path,\n routeId: routeIdCandidate,\n title,\n uuid,\n } = this.state.data\n const routeId = routeIdCandidate || generateNewRouteId(interfaceId, path)\n\n this.setState({ isLoading: true }, async () => {\n try {\n await onSave({\n variables: {\n route: {\n auth,\n blockId,\n context,\n declarer,\n domain,\n interfaceId,\n metaTags: {\n description: metaTagDescription,\n keywords: (metaTagKeywords || []).map(({ value }) => value),\n robots: metaTagRobots\n },\n pages: pages.map(page => {\n return {\n condition: {\n allMatches: page.condition.allMatches,\n id: page.condition.id || undefined,\n statements: formatStatements(page.condition.statements),\n },\n pageId: page.pageId || undefined,\n template: page.template,\n }\n }),\n path,\n routeId,\n title,\n uuid,\n },\n },\n })\n\n await onSaveContent({\n variables: {\n blockId,\n configuration: {\n condition: {\n allMatches: true,\n id: 'vtex.rich-text@0.x:rich-text',\n pageContext: {\n id: '*',\n type: '*',\n },\n statements: [],\n },\n contentId,\n contentJSON: JSON.stringify({ text: pageContent }),\n label: null,\n origin: 'vtex.rich-text@0.x:rich-text',\n },\n lang: culture.locale,\n template: blockId,\n treePath: `${routeId}/flex-layout.row#content-body/rich-text`,\n },\n })\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.saveSuccess),\n })\n\n onExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.saveError),\n })\n })\n }\n })\n } else {\n this.setState(getValidateFormState)\n }\n }\n\n private handleDelete = () => {\n const { showToast, intl, onDelete, onExit } = this.props\n const { data } = this.state\n\n this.setState({ isLoading: true }, async () => {\n try {\n if (!data.uuid) {\n throw new Error('No uuid')\n }\n\n await onDelete({\n variables: {\n uuid: data.uuid,\n },\n })\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.deleteSuccess),\n })\n\n onExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.deleteError),\n })\n })\n }\n })\n }\n}\n\nexport default injectIntl(FormContainer)\n\n```" } ]
code_admin-pages_20150d29
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/Loader.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { Spinner } from 'vtex.styleguide'\n\nconst Loader = () => (\n <div className=\"vh-100 flex items-center justify-center\">\n <Spinner />\n </div>\n)\n\nexport default Loader\n\n```" } ]
code_admin-pages_b9b03b05
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/UnallowedWarning.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport * as React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Button, EmptyState } from 'vtex.styleguide'\n\nconst UnallowedWarning = () => (\n <EmptyState\n title={\n <FormattedMessage\n id=\"admin/pages.admin.content.not-supported.title\"\n defaultMessage=\"This feature is not available :/\"\n />\n }\n >\n <FormattedMessage id=\"admin/pages.admin.content.not-supported.description\">\n {message => <p>{message}</p>}\n </FormattedMessage>\n <div className=\"pt5\">\n <Button\n variation=\"secondary\"\n size=\"small\"\n href=\"https://github.com/vtex-apps/admin-pages/blob/master/docs/CONTENT_PAGE.md\"\n target=\"_blank\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.content.not-supported.action\"\n defaultMessage=\"See instructions\"\n />\n </Button>\n </div>\n </EmptyState>\n)\n\nexport default UnallowedWarning\n\n```" } ]
code_admin-pages_2cd2ce42
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/withContentContext.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { pathOr } from 'ramda'\nimport * as React from 'react'\nimport { Mutation, MutationFn, Query, QueryResult } from 'react-apollo'\n\nimport Loader from './Loader'\nimport UnallowedWarning from './UnallowedWarning'\nimport {\n DeleteMutationResult,\n DeleteRouteVariables,\n SaveMutationResult,\n SaveRouteVariables,\n} from '../../pages/Form/typings'\nimport {\n updateStoreAfterDelete,\n updateStoreAfterSave,\n} from '../../pages/Form/utils'\nimport AvailableTemplates from '../../../../queries/AvailableTemplates.graphql'\nimport ContentIOMessageQuery from '../../../../queries/ContentIOMessage.graphql'\nimport DeleteRoute from '../../../../queries/DeleteRoute.graphql'\nimport RouteQuery from '../../../../queries/Route.graphql'\nimport SaveRoute from '../../../../queries/SaveRoute.graphql'\nimport SaveContentMutation from '../../../EditorContainer/mutations/SaveContent'\nimport ListContentQuery from '../../../EditorContainer/queries/ListContent'\n\ninterface TemplateData {\n availableTemplates: {\n id: string\n }[]\n}\n\ninterface TemplateVariables {\n interfaceId: string\n}\n\ninterface RouteData {\n route: Route\n}\n\ninterface RouteVariables {\n domain: string\n routeId: string\n}\n\ninterface MessagesData {\n translate: string[]\n}\n\ninterface MessagesVariables {\n args: {\n indexedByFrom: {\n from: string\n messages: {\n content: string\n context?: string\n behavior?: 'USER_ONLY' | 'USER_AND_APP' | 'FULL'\n }[]\n }[]\n to: string\n }\n}\n\nexport interface OperationsResults {\n deleteRoute: MutationFn<unknown, DeleteRouteVariables>\n saveRoute: MutationFn<unknown, SaveRouteVariables>\n saveContent: MutationFn<unknown, unknown>\n templatesResults: QueryResult<unknown, TemplateVariables>\n}\n\nexport interface ContentContextProps {\n route: Route\n blockId: string\n interfaceId: string\n content: {\n id: string\n text: string\n }\n deleteRoute: MutationFn<unknown, DeleteRouteVariables>\n saveRoute: MutationFn<unknown, SaveRouteVariables>\n saveContent: MutationFn<unknown, unknown>\n}\n\ninterface Params {\n culture: {\n locale: string\n }\n routeId: string\n storeAppId: string\n}\n\nfunction withContentContext<T>(\n WrappedComponent: React.ComponentType<T>,\n getParams: (props: T) => Params\n) {\n const ComponentWithContent = (props: T) => {\n const { storeAppId, routeId, culture } = getParams(props)\n const interfaceId = `${storeAppId}:store.content`\n\n return (\n <Query<RouteData, RouteVariables>\n query={RouteQuery}\n variables={{ domain: 'store', routeId }}\n >\n {({ data: dataRoute, loading: loadingRoute }) => {\n if (loadingRoute) {\n return <Loader />\n }\n\n return (\n <Query<TemplateData, TemplateVariables>\n query={AvailableTemplates}\n variables={{ interfaceId }}\n >\n {({ data: dataTemplates, loading: loadingTemplates }) => {\n if (loadingTemplates) {\n return <Loader />\n }\n\n const eligibleTemplates =\n dataTemplates &&\n dataTemplates.availableTemplates.filter(\n (template: Template) => template.id !== interfaceId\n )\n\n if (!eligibleTemplates || !eligibleTemplates.length) {\n return <UnallowedWarning />\n }\n\n const blockId = eligibleTemplates[0].id\n\n return (\n <ListContentQuery\n variables={{\n blockId,\n pageContext: {\n id: '*',\n type: '*',\n },\n template: blockId,\n treePath: `${routeId}/flex-layout.row#content-body/rich-text`,\n }}\n >\n {({ data: dataContent, loading: loadingContent }) => {\n if (loadingContent) {\n return <Loader />\n }\n\n const contentJSON: string | null = pathOr(\n null,\n [\n 'listContentWithSchema',\n 'content',\n '0',\n 'contentJSON',\n ],\n dataContent || {}\n )\n const contentText: string = contentJSON\n ? JSON.parse(contentJSON).text\n : ''\n const contentId: string = pathOr(\n '',\n ['listContentWithSchema', 'content', '0', 'contentId'],\n dataContent || {}\n )\n\n return (\n <Query<MessagesData, MessagesVariables>\n query={ContentIOMessageQuery}\n variables={{\n args: {\n indexedByFrom: [\n {\n from: 'en-DV',\n messages: [\n {\n context: contentId,\n content: contentText || '',\n },\n ],\n },\n ],\n to: culture.locale,\n },\n }}\n >\n {({ data: dataMessage, loading: loadingMessage }) => {\n if (loadingMessage) {\n return <Loader />\n }\n\n const content = {\n id: contentId,\n text: pathOr(\n contentText,\n ['translate', 0],\n dataMessage || {}\n ),\n }\n\n return (\n <Mutation<\n DeleteMutationResult['data'],\n DeleteRouteVariables\n >\n mutation={DeleteRoute}\n update={updateStoreAfterDelete()}\n >\n {deleteRoute => (\n <Mutation<\n SaveMutationResult['data'],\n SaveRouteVariables\n >\n mutation={SaveRoute}\n update={updateStoreAfterSave}\n >\n {saveRoute => (\n <SaveContentMutation>\n {saveContent => (\n <WrappedComponent\n {...props}\n route={dataRoute && dataRoute.route}\n saveRoute={saveRoute}\n deleteRoute={deleteRoute}\n saveContent={saveContent}\n content={content}\n blockId={blockId}\n interfaceId={interfaceId}\n />\n )}\n </SaveContentMutation>\n )}\n </Mutation>\n )}\n </Mutation>\n )\n }}\n </Query>\n )\n }}\n </ListContentQuery>\n )\n }}\n </Query>\n )\n }}\n </Query>\n )\n }\n\n return ComponentWithContent\n}\n\nexport default withContentContext\n\n```" } ]
code_admin-pages_1cb14c86
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/utils.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { RouteFormData } from 'pages'\nimport { State } from './index'\n\nimport { slugify } from '../../utils'\n\nconst requiredMessage = 'admin/pages.admin.pages.form.templates.field.required'\n\nconst validateFalsyPath = (path: keyof RouteFormData) => (\n data: RouteFormData\n) => !data[path] && { [path]: requiredMessage }\n\nconst validatePathUrl = (path: string) => {\n if (!path) return { path: requiredMessage }\n if (!path.startsWith('/'))\n return {\n path: 'admin/pages.admin.pages.form.templates.path.validation-error',\n }\n if (slugify(path) !== path.slice(1))\n return {\n path: 'admin/pages.admin.pages.form.templates.path.invalid-format',\n }\n\n return {}\n}\n\nexport const getValidateFormState = (prevState: State) => {\n return {\n ...prevState,\n formErrors: {\n ...prevState.formErrors,\n ...(validatePathUrl(prevState.data.path) as Record<string, string>),\n ...(prevState.isInfoEditable\n ? validateFalsyPath('title')(prevState.data)\n : {}),\n },\n }\n}\n\n```" } ]
code_admin-pages_20ab8cee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/Form/Form.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { RouteFormData } from 'pages'\nimport * as React from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { Button, Input, Textarea, IconEdit } from 'vtex.styleguide'\n\nimport { RouteContentFromData } from './index'\nimport FormFieldSeparator from '../../FormFieldSeparator'\nimport { FormErrors } from '../../pages/Form/typings'\nimport SeparatorWithLine from '../../pages/SeparatorWithLine'\nimport { slugify } from '../../utils'\nimport RichTextEditor from '../../../RichTextEditor/index'\nimport SeoPreview from '../../../SeoPreview'\n\ninterface Props {\n data: RouteFormData & RouteContentFromData\n errors: FormErrors\n isLoading: boolean\n onDelete: () => void\n onExit: () => void\n onFieldValueChange: (field: string, value: string | number | null) => void\n onSubmit: (event: React.FormEvent) => void\n isDeletable: boolean\n isInfoEditable: boolean\n}\n\nconst messages = defineMessages({\n contentSection: {\n defaultMessage: 'Content',\n id: 'admin/pages.admin.content.content.section-title',\n },\n fieldPath: {\n defaultMessage: 'URL',\n id: 'admin/pages.admin.content.general.url.label',\n },\n fieldTitle: {\n defaultMessage: 'Title',\n id: 'admin/pages.admin.content.general.title.label',\n },\n generalSection: {\n defaultMessage: 'General',\n id: 'admin/pages.admin.content.general.section-title',\n },\n pathHint: {\n defaultMessage: '/my-custom-page',\n id: 'admin/pages.admin.content.general.url.placeholder',\n },\n seoDescription: {\n defaultMessage: 'Description',\n id: 'admin/pages.admin.content.general.description.label',\n },\n titleHint: {\n defaultMessage: 'e.g.: About us',\n id: 'admin/pages.admin.content.general.title.placeholder',\n },\n})\n\nconst Form = ({\n data,\n errors,\n isDeletable,\n isLoading,\n onDelete,\n onExit,\n onFieldValueChange,\n onSubmit,\n}: Props) => {\n const intl = useIntl()\n const pathRef = React.useRef<HTMLInputElement>(null)\n const [hasDefinedPath, setHasDefinedPath] = React.useState(false)\n\n const handlePathChange = (value: string | null) => {\n if (!value) return\n return onFieldValueChange('path', `/${slugify(value)}`)\n }\n\n const handleEventValue = (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => {\n const { name, value } = event.target\n\n if (name === 'title' && !hasDefinedPath) {\n handlePathChange(value)\n }\n\n return onFieldValueChange(name, value)\n }\n\n return (\n <form onSubmit={() => null}>\n <p className=\"mv7 f4 b\">Geral</p>\n <div className=\"flex-ns justify-between\">\n <div className=\"w-100 w-50-ns pr4-ns\">\n <Input\n name=\"title\"\n disabled={false}\n label={intl.formatMessage(messages.fieldTitle)}\n onChange={handleEventValue}\n placeholder={intl.formatMessage(messages.titleHint)}\n required\n value={data.title}\n errorMessage={\n errors.title && intl.formatMessage({ id: errors.title })\n }\n />\n <FormFieldSeparator />\n <Input\n ref={pathRef}\n name=\"path\"\n disabled={!hasDefinedPath}\n label={intl.formatMessage(messages.fieldPath)}\n onChange={handleEventValue}\n onBlur={() => {\n const value = data.path\n\n if (!value) {\n if (hasDefinedPath) setHasDefinedPath(false)\n return handlePathChange(data.title)\n }\n\n if (!hasDefinedPath) setHasDefinedPath(true)\n return handlePathChange(data.path)\n }}\n placeholder={intl.formatMessage(messages.pathHint)}\n required\n value={data.path || ''}\n errorMessage={\n errors.path && intl.formatMessage({ id: errors.path })\n }\n suffix={\n <div\n role=\"button\"\n tabIndex={0}\n className=\"pointer\"\n onMouseDown={() => {\n setHasDefinedPath(true)\n pathRef.current && pathRef.current.focus()\n }}\n >\n <IconEdit />\n </div>\n }\n />\n <FormFieldSeparator />\n <Textarea\n name=\"metaTagDescription\"\n disabled={false}\n label={intl.formatMessage(messages.seoDescription)}\n onChange={handleEventValue}\n resize=\"vertical\"\n value={data.metaTagDescription}\n size=\"small\"\n />\n </div>\n\n <div className=\"w-100 w-50-ns pl4-ns\">\n <SeoPreview\n title={data.title}\n url={data.path}\n description={data.metaTagDescription}\n />\n </div>\n </div>\n\n <FormFieldSeparator />\n <SeparatorWithLine />\n\n <p className=\"mv7 f4 b\">{intl.formatMessage(messages.contentSection)}</p>\n <RichTextEditor\n initialState={data.pageContent}\n onChange={(value: string) => onFieldValueChange('pageContent', value)}\n />\n\n <FormFieldSeparator />\n\n <div className={`${isDeletable && 'flex justify-between'}`}>\n {isDeletable && (\n <Button\n disabled={isLoading}\n onClick={onDelete}\n size=\"small\"\n variation=\"danger\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.delete\"\n defaultMessage=\"Delete\"\n />\n </Button>\n )}\n\n <div className=\"flex justify-end\">\n <div className=\"mr6\">\n <Button\n disabled={isLoading}\n onClick={onExit}\n size=\"small\"\n variation=\"tertiary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.cancel\"\n defaultMessage=\"Cancel\"\n />\n </Button>\n </div>\n <Button\n disabled={isLoading}\n isLoading={isLoading}\n onClick={onSubmit}\n size=\"small\"\n variation=\"primary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.button.save\"\n defaultMessage=\"Save\"\n />\n </Button>\n </div>\n </div>\n </form>\n )\n}\n\nexport default Form\n\n```" } ]
code_admin-pages_937d71d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/List/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Fragment } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport { Box, Button } from 'vtex.styleguide'\n\nimport { INSTITUTIONAL_ROUTES_FORM, NEW_ROUTE_ID } from '../../pages/consts'\nimport SeparatorWithLine from '../../pages/SeparatorWithLine'\n\nimport Entry from './Entry'\n\ninterface Props {\n hasCreateButton?: boolean\n routes: Route[]\n runtime: RenderContext\n titleId: string\n}\n\nconst Section = ({ hasCreateButton, routes, runtime, titleId }: Props) => (\n <Box>\n <div className=\"relative flex items-center\">\n <FormattedMessage id={titleId}>\n {title => <div className=\"b\">{title}</div>}\n </FormattedMessage>\n {hasCreateButton && (\n <div className=\"absolute right-0\">\n <Button\n onClick={() => {\n runtime.navigate({\n page: INSTITUTIONAL_ROUTES_FORM,\n params: { id: NEW_ROUTE_ID },\n })\n }}\n size=\"small\"\n variation=\"primary\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.pages.list.button.create\"\n defaultMessage=\"Create New\"\n />\n </Button>\n </div>\n )}\n </div>\n {routes.map(route => (\n <Fragment key={route.path}>\n <SeparatorWithLine />\n <Entry route={route} />\n </Fragment>\n ))}\n </Box>\n)\n\nexport default withRuntimeContext(Section)\n\n```" } ]
code_admin-pages_f7539afb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/institutional/List/Entry.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { useKeydownFromClick } from 'keydown-from-click'\nimport React from 'react'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport { IconEdit } from 'vtex.styleguide'\n\nimport { INSTITUTIONAL_ROUTES_FORM } from '../../pages/consts'\nimport { getRouteTitle } from '../../pages/utils'\n\ninterface Props {\n route: Route\n runtime: RenderContext\n}\n\nconst Entry = ({ route, runtime }: Props) => {\n const handleClick = React.useCallback(() => {\n runtime.navigate({\n page: INSTITUTIONAL_ROUTES_FORM,\n params: { id: encodeURIComponent(route.routeId) },\n })\n }, [route.routeId, runtime])\n\n const handleKeyDown = useKeydownFromClick(handleClick)\n\n return (\n <div className=\"flex justify-between items-center\">\n <div className=\"f6\">{getRouteTitle(route)}</div>\n <div\n className=\"flex pointer outline-0\"\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n role=\"button\"\n tabIndex={0}\n >\n <IconEdit color=\"silver\" />\n </div>\n </div>\n )\n}\n\nexport default withRuntimeContext(Entry)\n\n```" } ]
code_admin-pages_5d1fef8c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/Form/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport moment from 'moment'\nimport PropTypes from 'prop-types'\nimport React, { Component, Fragment } from 'react'\nimport {\n defineMessages,\n FormattedMessage,\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport {\n Button,\n DatePicker,\n Dropdown,\n IconClose,\n Input,\n RadioGroup,\n ToastConsumerFunctions,\n Toggle,\n} from 'vtex.styleguide'\nimport { Binding } from 'vtex.tenant-graphql'\n\nimport { getBindingSelectorOptions } from '../../../../utils/bindings'\nimport { DropdownChangeInput } from '../../../../utils/bindings/typings'\nimport Modal from '../../../Modal'\nimport FormFieldSeparator from '../../FormFieldSeparator'\nimport { BASE_URL, NEW_REDIRECT_ID } from '../consts'\nimport { DeleteRedirectMutationFn, SaveRedirectMutationFn } from './typings'\n\ninterface CustomProps {\n initialData: Redirect\n onDelete: DeleteRedirectMutationFn\n onSave: SaveRedirectMutationFn\n storeBindings: Binding[] | null\n isNew: boolean\n}\n\ntype Props = CustomProps &\n ComponentWithIntlProps &\n RenderContextProps &\n Pick<ToastConsumerFunctions, 'showToast'>\n\ninterface State {\n data: Redirect\n isLoading: boolean\n shouldShowDatePicker: boolean\n shouldShowModal: boolean\n}\n\nconst messages = defineMessages({\n buttonCancel: {\n defaultMessage: 'Cancel',\n id: 'admin/pages.admin.redirects.form.button.cancel',\n },\n buttonRemove: {\n defaultMessage: 'Remove',\n id: 'admin/pages.admin.redirects.form.button.remove',\n },\n deleteError: {\n defaultMessage: 'Error: redirect could not be deleted.',\n id: 'admin/pages.admin.redirects.form.delete.error',\n },\n from: {\n defaultMessage: 'From',\n id: 'admin/pages.admin.redirects.table.from',\n },\n modalText: {\n defaultMessage: 'Are you sure you want to remove this redirect?',\n id: 'admin/pages.admin.redirects.form.modal.text',\n },\n permanent: {\n defaultMessage: 'This redirect is permanent (Code: 301).',\n id: 'admin/pages.admin.redirects.form.toggle.permanent',\n },\n saveError: {\n defaultMessage: 'Error: redirect could not be saved.',\n id: 'admin/pages.admin.redirects.form.save.error',\n },\n temporary: {\n defaultMessage: 'This redirect is temporary (Code: 302).',\n id: 'admin/pages.admin.redirects.form.toggle.temporary',\n },\n to: {\n defaultMessage: 'To',\n id: 'admin/pages.admin.redirects.table.to',\n },\n toggleEndDate: {\n defaultMessage: 'This redirect has an end date',\n id: 'admin/pages.admin.redirects.form.toggle.endDate',\n },\n bindingSelectorTitle: {\n defaultMessage: 'Binding',\n id: 'admin/pages.admin.pages.form.binding-selector.title',\n },\n})\n\ninterface BindingSelectorWrapper {\n visible: boolean\n}\n\nconst BindingSelectorWrapper: React.FunctionComponent<BindingSelectorWrapper> = props => {\n const { children, visible } = props\n return visible ? (\n <div>\n <FormFieldSeparator />\n {children}\n <div className=\"mb7 pb7 bb bw1 b--light-silver f3 normal\" />\n <FormFieldSeparator />\n </div>\n ) : null\n}\n\nclass Form extends Component<Props, State> {\n public static contextTypes = {\n culture: PropTypes.shape({ locale: PropTypes.string.isRequired })\n .isRequired,\n }\n\n private isEditingRedirect: boolean\n private minDate = new Date()\n\n public constructor(props: Props) {\n super(props)\n\n this.isEditingRedirect = props.initialData.from !== NEW_REDIRECT_ID\n\n this.state = {\n data: props.initialData,\n isLoading: false,\n shouldShowDatePicker: !!props.initialData.endDate,\n shouldShowModal: false,\n }\n }\n\n public componentDidMount() {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }\n\n public render() {\n const { locale } = this.context.culture\n const { intl, storeBindings, isNew } = this.props\n const {\n data,\n isLoading,\n shouldShowModal,\n shouldShowDatePicker,\n } = this.state\n\n const bindingOptions =\n storeBindings && getBindingSelectorOptions(storeBindings)\n\n return (\n <Fragment>\n <Modal\n isActionDanger\n isActionLoading={isLoading}\n isOpen={shouldShowModal}\n onClickAction={this.handleDelete(data.from, data.binding)}\n onClickCancel={this.handleModalVisibilityToggle}\n onClose={this.handleModalVisibilityToggle}\n textButtonAction={intl.formatMessage(messages.buttonRemove)}\n textButtonCancel={intl.formatMessage(messages.buttonCancel)}\n textMessage={intl.formatMessage(messages.modalText)}\n />\n <h1>\n {this.isEditingRedirect ? (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.title.info\"\n defaultMessage=\"Redirect info\"\n />\n ) : (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.title.new\"\n defaultMessage=\"Create a redirect\"\n />\n )}\n </h1>\n <FormFieldSeparator />\n {storeBindings && (\n <BindingSelectorWrapper visible={storeBindings.length > 1}>\n <Dropdown\n label={intl.formatMessage(messages.bindingSelectorTitle)}\n disabled={!isNew || storeBindings.length === 1}\n onChange={this.handleBindingChange}\n options={bindingOptions}\n value={data.binding || storeBindings[0]}\n />\n </BindingSelectorWrapper>\n )}\n <form onSubmit={this.handleSave}>\n <Input\n label={intl.formatMessage(messages.from)}\n onChange={this.handleFromUpdate}\n required\n value={data.from}\n />\n <FormFieldSeparator />\n <Input\n label={intl.formatMessage(messages.to)}\n onChange={this.handleToUpdate}\n required\n value={data.to}\n />\n <FormFieldSeparator />\n <RadioGroup\n name=\"type\"\n options={[\n {\n label: intl.formatMessage(messages.permanent),\n value: 'PERMANENT',\n },\n {\n label: intl.formatMessage(messages.temporary),\n value: 'TEMPORARY',\n },\n ]}\n value={data.type}\n onChange={this.handleTypeChange}\n />\n <FormFieldSeparator />\n {data.type === 'TEMPORARY' ? (\n <>\n <div className=\"relative\">\n <Toggle\n checked={shouldShowDatePicker}\n label={intl.formatMessage(messages.toggleEndDate)}\n onChange={this.handleDatePickerVisibilityToggle}\n />\n </div>\n <FormFieldSeparator />\n {shouldShowDatePicker && (\n <Fragment>\n <FormattedMessage id=\"admin/pages.admin.redirects.form.datePicker.title\">\n {text => <div className=\"mb3 w-100 f6\">{text}</div>}\n </FormattedMessage>\n <div className=\"flex\">\n <DatePicker\n useTime\n direction=\"up\"\n locale={locale}\n onChange={this.handleEndDateUpdate}\n minDate={this.minDate}\n value={\n data.endDate ? moment(data.endDate).toDate() : undefined\n }\n />\n <button\n type=\"button\"\n className=\"flex items-center justify-center bn input-reset near-black\"\n onClick={this.handleEndDateClear}\n >\n <IconClose />\n </button>\n </div>\n <FormFieldSeparator />\n </Fragment>\n )}\n </>\n ) : null}\n <div\n className={classnames('justify-between', {\n flex: this.isEditingRedirect,\n })}\n >\n {this.isEditingRedirect ? (\n <Button\n size=\"small\"\n onClick={this.handleModalVisibilityToggle}\n variation=\"danger\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.button.remove\"\n defaultMessage=\"Remove\"\n />\n </Button>\n ) : null}\n <div className=\"flex justify-end\">\n <div className=\"mr6\">\n <Button\n disabled={isLoading}\n onClick={this.handleExit}\n size=\"small\"\n variation=\"tertiary\"\n >\n {this.isEditingRedirect ? (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.button.back\"\n defaultMessage=\"Back\"\n />\n ) : (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.button.cancel\"\n defaultMessage=\"Cancel\"\n />\n )}\n </Button>\n </div>\n <Button isLoading={isLoading} size=\"small\" type=\"submit\">\n <FormattedMessage\n id=\"admin/pages.admin.redirects.form.button.save\"\n defaultMessage=\"Save\"\n />\n </Button>\n </div>\n </div>\n </form>\n </Fragment>\n )\n }\n\n private handleExit = () => {\n this.props.runtime.navigate({ to: BASE_URL })\n }\n\n private handleDelete = (\n redirectFrom: string,\n redirectBinding: string\n ) => () => {\n const { intl, onDelete } = this.props\n\n this.setState({ isLoading: true }, async () => {\n try {\n await onDelete({\n variables: {\n path: redirectFrom,\n binding: redirectBinding,\n },\n })\n\n this.handleExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n this.props.showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.deleteError),\n })\n })\n }\n })\n }\n\n private handleInputChange = (inputData: object) => {\n this.setState(prevState => ({\n ...prevState,\n data: {\n ...prevState.data,\n ...inputData,\n },\n }))\n }\n\n private handleSave = (event: React.FormEvent) => {\n const { intl, onSave } = this.props\n const {\n data: { endDate, from, to, type, binding },\n } = this.state\n\n event.preventDefault()\n\n this.setState({ isLoading: true }, async () => {\n try {\n await onSave({\n variables: {\n endDate,\n from,\n to,\n type,\n binding,\n },\n })\n\n this.handleExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n this.props.showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.saveError),\n })\n })\n }\n })\n }\n\n private handleDatePickerVisibilityToggle = () => {\n this.setState(\n prevState => ({\n ...prevState,\n shouldShowDatePicker: !prevState.shouldShowDatePicker,\n }),\n () => {\n this.handleInputChange({\n endDate: this.state.shouldShowDatePicker\n ? moment(this.props.initialData.endDate || undefined).add(1, 'days')\n : '',\n })\n }\n )\n }\n\n private handleModalVisibilityToggle = () => {\n this.setState(prevState => ({\n ...prevState,\n shouldShowModal: !prevState.shouldShowModal,\n }))\n }\n\n private handleTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const type = e.target.value\n this.handleInputChange({\n ...(type === 'PERMANENT' ? { endDate: '' } : null),\n type,\n })\n }\n\n private handleEndDateUpdate = (value: Date) => {\n this.handleInputChange({ endDate: value })\n }\n\n private handleEndDateClear = () => {\n this.handleInputChange({ endDate: '' })\n }\n\n private handleFromUpdate = (event: Event) => {\n if (event.target instanceof HTMLInputElement) {\n this.handleInputChange({ from: event.target.value })\n }\n }\n\n private handleToUpdate = (event: Event) => {\n if (event.target instanceof HTMLInputElement) {\n this.handleInputChange({ to: event.target.value })\n }\n }\n\n private handleBindingChange = ({\n target: { value },\n }: DropdownChangeInput) => {\n const { storeBindings } = this.props\n const { data } = this.state\n if (!storeBindings) {\n return\n }\n const selectedBinding = storeBindings.find(binding => binding.id === value)\n if (!selectedBinding) {\n throw new Error(\n \"Selected binding does not exist or isn't a store binding\"\n )\n }\n data.binding = selectedBinding.id\n this.setState({ data })\n }\n}\n\nexport default withRuntimeContext(injectIntl(Form))\n\n```" } ]
code_admin-pages_633aca9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/Form/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DataProxy } from 'apollo-cache'\n\nimport Redirect from '../../../../queries/Redirect.graphql'\nimport Redirects from '../../../../queries/Redirects.graphql'\nimport { PAGINATION_START, PAGINATION_STEP } from '../consts'\nimport { RedirectsQuery } from '../typings'\nimport { QueryData, StoreUpdaterGetter } from './typings'\n\nconst cacheAccessParameters = {\n query: Redirects,\n variables: {\n from: PAGINATION_START,\n to: PAGINATION_START + PAGINATION_STEP,\n },\n}\n\nconst readRedirectsFromStore = (store: DataProxy): QueryData =>\n store.readQuery(cacheAccessParameters)\n\nconst writeRedirectsToStore = (newData: RedirectsQuery, store: DataProxy) => {\n store.writeQuery({\n data: newData,\n ...cacheAccessParameters,\n })\n}\n\nexport const getStoreUpdater: StoreUpdaterGetter = operation => (\n store,\n result\n) => {\n const deleteRedirect = result.data?.redirect?.delete\n const saveRedirect = result.data?.redirect?.save\n\n const isDelete = operation === 'delete'\n\n try {\n const queryData = readRedirectsFromStore(store)\n\n if (queryData) {\n const newRedirects =\n (isDelete\n ? deleteRedirect &&\n queryData.redirect.list.filter(\n redirect => redirect.from !== deleteRedirect.from\n )\n : saveRedirect &&\n queryData.redirect.list.reduce(\n (acc, currRedirect) =>\n currRedirect.from === saveRedirect.from &&\n currRedirect.binding === saveRedirect.binding\n ? acc\n : [...acc, currRedirect],\n [saveRedirect]\n )) || queryData.redirect.list\n\n const newData = {\n ...queryData,\n redirect: {\n ...queryData.redirect,\n list: newRedirects,\n numberOfEntries: isDelete\n ? queryData.redirect.numberOfEntries - 1\n : queryData.redirect.numberOfEntries + 1,\n },\n }\n\n writeRedirectsToStore(newData, store)\n }\n } catch (err) {\n console.warn('No cache found for \"Redirects\".')\n }\n\n try {\n const variables = isDelete\n ? deleteRedirect && {\n path: deleteRedirect.from,\n binding: deleteRedirect.binding,\n }\n : saveRedirect && {\n path: saveRedirect.from,\n binding: saveRedirect.binding,\n }\n\n store.writeQuery({\n data: { redirect: isDelete ? undefined : { save: saveRedirect } },\n query: Redirect,\n variables,\n })\n } catch (e) {\n console.error('Error writing to \"Redirect\".')\n }\n}\n\n```" } ]
code_admin-pages_c270d09c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/Form/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { MutationFn, MutationUpdaterFn } from 'react-apollo'\n\nimport { RedirectsQuery } from '../typings'\n\nexport interface MutationResult {\n data?: {\n [name: string]: Redirect\n }\n}\n\nexport type QueryData = RedirectsQuery | null\n\nexport interface RedirectQuery {\n redirect: {\n get: Redirect\n }\n}\n\nexport interface DeleteRedirectVariables {\n path: string\n binding?: string\n}\n\nexport interface SaveRedirectVariables {\n id?: string\n endDate: string | null\n from: string\n to: string\n type: RedirectTypes\n binding?: string\n}\n\ninterface Mutations {\n redirect?: {\n delete?: Redirect\n save?: Redirect\n }\n}\n\nexport type StoreUpdaterGetter = (\n operation: 'delete' | 'save'\n) => MutationUpdaterFn<Mutations>\n\nexport interface DeleteRedirectData {\n redirect: {\n delete: Redirect\n }\n}\n\nexport type DeleteRedirectMutationFn = MutationFn<\n DeleteRedirectData,\n DeleteRedirectVariables\n>\n\nexport interface SaveRedirectData {\n redirect: {\n save: Redirect\n }\n}\n\nexport type SaveRedirectMutationFn = MutationFn<\n SaveRedirectData,\n SaveRedirectVariables\n>\n\n```" } ]
code_admin-pages_64fdd3da
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/Form/Operations.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Mutation } from 'react-apollo'\n\nimport DeleteRedirect from '../../../../queries/DeleteRedirect.graphql'\nimport SaveRedirect from '../../../../queries/SaveRedirect.graphql'\n\nimport {\n DeleteRedirectData,\n DeleteRedirectMutationFn,\n DeleteRedirectVariables,\n SaveRedirectData,\n SaveRedirectMutationFn,\n SaveRedirectVariables,\n} from './typings'\nimport { getStoreUpdater } from './utils'\n\ninterface Props {\n children: (mutations: OperationsObj) => React.ReactNode\n}\n\ninterface OperationsObj {\n deleteRedirect: DeleteRedirectMutationFn\n saveRedirect: SaveRedirectMutationFn\n}\n\nconst Operations = (props: Props) => (\n <Mutation<DeleteRedirectData, DeleteRedirectVariables>\n mutation={DeleteRedirect}\n update={getStoreUpdater('delete')}\n >\n {deleteRedirect => (\n <Mutation<SaveRedirectData, SaveRedirectVariables>\n mutation={SaveRedirect}\n update={getStoreUpdater('save')}\n >\n {saveRedirect =>\n props.children({\n deleteRedirect,\n saveRedirect,\n })\n }\n </Mutation>\n )}\n </Mutation>\n)\n\nexport default Operations\n\n```" } ]
code_admin-pages_dac04d31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { Mutation } from 'react-apollo'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport { Modal } from 'vtex.styleguide'\n\nimport SaveRedirectFromFileMutation, {\n MutationRenderProps,\n UploadActionType,\n} from '../mutations/SaveRedirectFromFile'\nimport Loading from './Loading'\nimport UploadError from './UploadError'\nimport UploadPrompt from './UploadPrompt'\nimport {\n DeleteManyRedirectsProps,\n DeleteManyRedirectsFromFileResult,\n DeleteManyRedirectsFromFileVariables,\n} from '../mutations/DeleteManyRedirectsFromFile'\nimport DeleteManyRedirects from '../mutations/DeleteManyRedirectsFromFile.graphql'\nimport { ModalStates } from './typings'\nimport { getAlertState } from './UploadPrompt/getAlertState'\nimport { AlertState } from '../typings'\nimport bulkUploadRedirects from '../bulkUploadRedirects'\n\ninterface RouteLocator {\n from: string\n binding: string\n}\ninterface Props {\n hasRedirects: boolean\n isOpen: boolean\n onClose: () => void\n onDownloadTemplate: () => void\n refetchRedirects: () => void\n setAlert: (alertState: AlertState) => void\n hasMultipleBindings: boolean\n}\n\nconst INITIAL_MODAL_STATE = 'UPLOAD_FILE'\n\nconst UploadModal: React.FunctionComponent<Props &\n MutationRenderProps &\n DeleteManyRedirectsProps> = ({\n deleteManyRedirects,\n error,\n hasRedirects,\n isOpen,\n onClose,\n onDownloadTemplate,\n refetchRedirects,\n saveRedirectFromFile,\n setAlert,\n hasMultipleBindings,\n}) => {\n const intl = useIntl()\n const [currentStep, setModalStep] = useState<ModalStates>(INITIAL_MODAL_STATE)\n\n const [processedRedirect, setProcessedRedirect] = useState<number>(0)\n const [numberOfRedirects, setNumberOfRedirects] = useState<number>(-1)\n const shouldUploadRef = useRef<boolean>(false)\n\n useEffect(() => {\n shouldUploadRef.current = isOpen\n }, [isOpen])\n\n const [uploadActionType, setUploadActionType] = useState<UploadActionType>(\n 'save'\n )\n\n const resetState = useCallback(\n async (refetch = false) => {\n onClose()\n setModalStep(INITIAL_MODAL_STATE)\n setUploadActionType('save')\n setProcessedRedirect(0)\n setNumberOfRedirects(-1)\n if (refetch) {\n await refetchRedirects()\n }\n },\n [onClose, refetchRedirects]\n )\n\n const handlePromptCancel = useCallback(() => {\n resetState(false)\n }, [resetState])\n\n const saveRedirectFromFileCb = useCallback(\n async (\n parsedJsonFromCsv: Redirect[],\n fileName: string,\n hasMultipleBindings: boolean\n ) => {\n shouldUploadRef.current = true\n const isSave = uploadActionType === 'save'\n const mutation = (data: Redirect[]) => {\n if (isSave) {\n return saveRedirectFromFile({\n variables: { redirects: data as Redirect[] },\n })\n }\n const { paths, locators } = data.reduce(\n (acc, redirect) => {\n acc.paths.push(redirect.from)\n acc.locators.push({\n from: redirect.from,\n binding: redirect.binding,\n })\n return acc\n },\n {\n paths: [] as string[],\n locators: [] as RouteLocator[],\n }\n )\n const variables = hasMultipleBindings\n ? {\n paths,\n locators,\n }\n : { paths }\n return deleteManyRedirects({\n variables,\n })\n }\n\n try {\n const numberOfLines = parsedJsonFromCsv.length\n\n setNumberOfRedirects(numberOfLines)\n setModalStep('LOADING')\n\n const { failedRedirects } = await bulkUploadRedirects({\n data: parsedJsonFromCsv,\n isSave,\n mutation,\n shouldUploadRef,\n updateProgress: processed => {\n setProcessedRedirect(processed)\n },\n })\n\n if (shouldUploadRef.current) {\n setAlert(\n getAlertState({\n total: numberOfLines,\n failedRedirects,\n intl,\n fileName,\n mutation,\n isSave,\n })\n )\n resetState(true)\n }\n } catch (e) {\n setModalStep('ERROR')\n }\n },\n [\n deleteManyRedirects,\n intl,\n resetState,\n saveRedirectFromFile,\n setAlert,\n uploadActionType,\n ]\n )\n\n const CurrentComponent = useMemo(() => {\n switch (currentStep) {\n case 'UPLOAD_FILE':\n return (\n <UploadPrompt\n setUploadActionType={setUploadActionType}\n hasRedirects={hasRedirects}\n onCancel={handlePromptCancel}\n onDownloadTemplate={onDownloadTemplate}\n saveRedirectFromFile={saveRedirectFromFileCb}\n uploadActionType={uploadActionType}\n hasMultipleBindings={hasMultipleBindings}\n />\n )\n case 'LOADING':\n return (\n <Loading\n current={processedRedirect}\n total={numberOfRedirects}\n onCancel={() => {\n setModalStep('UPLOAD_FILE')\n shouldUploadRef.current = false\n }}\n />\n )\n case 'ERROR':\n return <UploadError error={error} />\n default:\n return null\n }\n }, [\n currentStep,\n error,\n handlePromptCancel,\n hasRedirects,\n numberOfRedirects,\n onDownloadTemplate,\n processedRedirect,\n saveRedirectFromFileCb,\n uploadActionType,\n hasMultipleBindings,\n ])\n\n return (\n <Modal centered isOpen={isOpen} onClose={resetState}>\n <h1 className=\"f3 fw4 mt0 mb6\">\n <FormattedMessage id=\"admin/pages.admin.redirects.upload-modal.prompt.select-action.title\" />\n </h1>\n <div\n className={classnames('flex flex-column justify-center', {\n 'justify-center': currentStep !== 'UPLOAD_FILE',\n })}\n >\n {CurrentComponent}\n </div>\n </Modal>\n )\n}\n\nconst UploadModalWithMutation: React.FC<Props> = props => (\n <SaveRedirectFromFileMutation>\n {(saveRedirectFromFile, mutationResult) => (\n <Mutation<\n DeleteManyRedirectsFromFileResult,\n DeleteManyRedirectsFromFileVariables\n >\n mutation={DeleteManyRedirects}\n >\n {deleteManyRedirects => (\n <UploadModal\n saveRedirectFromFile={saveRedirectFromFile}\n deleteManyRedirects={deleteManyRedirects}\n {...mutationResult}\n {...props}\n />\n )}\n </Mutation>\n )}\n </SaveRedirectFromFileMutation>\n)\n\nexport default React.memo(UploadModalWithMutation)\n\n```" } ]
code_admin-pages_fcd09ff4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type ModalStates = 'UPLOAD_FILE' | 'LOADING' | 'ERROR'\n\n```" } ]
code_admin-pages_004badb5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadError.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { ApolloError } from 'apollo-client'\nimport { pathOr } from 'ramda'\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\n\nimport DangerIcon from '../../../icons/DangerIcon'\nimport PaperErrorIcon from '../../../icons/PaperErrorIcon'\n\nimport styles from './UploadModal.css'\n\ninterface Props {\n error?: ApolloError\n}\n\ninterface ValidationLineError {\n lineNumber: number\n errors: string[]\n}\n\nconst UploadError: React.FunctionComponent<Props> = ({ error }) => {\n const message = pathOr<string, string>(\n '',\n ['graphQLErrors', '0', 'message'],\n error || {}\n )\n let errors: ValidationLineError[] = []\n try {\n errors = JSON.parse(message)\n } catch (e) {\n console.error(e)\n }\n\n return (\n <div className=\"flex flex-column items-center justify-center\">\n <PaperErrorIcon />\n <h2 className=\"tc fw4 mb3 mt7\">\n <FormattedMessage id=\"admin/pages.admin.redirects.upload-modal.fail.title\" />\n </h2>\n <p className=\"tc c-muted-2 mt2 mb2\">\n <FormattedMessage id=\"admin/pages.admin.redirects.upload-modal.fail.subtitle\" />\n </p>\n <p className=\"tc c-muted-2 mt2\">\n <FormattedMessage id=\"admin/pages.admin.redirects.upload-modal.fail.message\" />\n </p>\n <hr\n className={`b--muted-4 br-0 bl-0 bt-0 mh0 mv0 ${styles['full-modal-width']}`}\n />\n <div\n className={`overflow-y-auto ${styles['error-container']} ${styles['full-modal-width']}`}\n >\n {errors.map((errorObj, id) => {\n return (\n <div className=\"flex pa3 pl7\" key={`error-line-${id}`}>\n <div className=\"mt1\">\n <DangerIcon />\n </div>\n <div className=\"ml4\">\n <h2 className=\"c-danger f5 fw4 mv0\">\n <FormattedMessage id=\"admin/pages.admin.redirects.upload-modal.error.line.title\" />\n {errorObj.lineNumber}:\n </h2>\n <ul className=\"f5 fw3 list mt2 pl0\">\n {errorObj.errors.map((errorMessage, messageId) => (\n <li key={`error-line-${id}-message-${messageId}`}>\n {errorMessage}\n </li>\n ))}\n </ul>\n </div>\n </div>\n )\n })}\n </div>\n </div>\n )\n}\n\nexport default React.memo(UploadError)\n\n```" } ]
code_admin-pages_f221b53e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadModal.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.full-modal-width {\n width: calc(100% + 6rem);\n}\n\n.error-container {\n max-height: 30vh;\n margin-bottom: -3rem;\n}\n\n.error-container::-webkit-scrollbar,\n.error-container::-webkit-scrollbar-track {\n width: 2px;\n background: #f2f4f5;\n}\n\n.error-container::-webkit-scrollbar-thumb {\n width: 2px;\n background: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n}\n\n```" } ]
code_admin-pages_61a59602
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/Loading.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 { Button, Progress, Spinner } from 'vtex.styleguide'\n\ninterface Props {\n current: number\n total: number\n onCancel: () => void\n}\n\nconst Loading: React.FunctionComponent<Props> = ({\n current,\n onCancel,\n total,\n}) => {\n const percent =\n Math.round((current * 100) / total) < 100\n ? Math.round((current * 100) / total)\n : 100\n\n return (\n <div className=\"flex flex-column items-center justify-center\">\n <div className=\"absolute bg-white right-0 top-0 pa5 pa6-ns\">\n <Spinner size={30} />\n </div>\n <div className=\"w-100 flex justify-between mt3 mb4\">\n <span>{`${percent}%`}</span>\n <span>\n {current + ' '}/{' ' + total}\n </span>\n </div>\n <Progress type=\"line\" percent={percent} />\n <div className=\"flex justify-between items-center w-100 mt8\">\n <FormattedMessage\n id=\"admin/pages.admin.redirects.upload-modal.loading.warning\"\n defaultMessage=\"Please don't close this window.\"\n />\n <Button onClick={onCancel} type=\"button\" variation=\"secondary\">\n <FormattedMessage\n id=\"admin/pages.admin.redirects.upload-modal.loading.cancel\"\n defaultMessage=\"Cancel\"\n />\n </Button>\n </div>\n </div>\n )\n}\n\nexport default Loading\n\n```" } ]
code_admin-pages_64e47e29
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/mutations/DeleteManyRedirectsFromFile.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation DeleteManyRedirects($paths: [String!]!, $locators: [RouteLocator!]) {\n redirect @context(provider: \"vtex.rewriter\") {\n deleteMany(paths: $paths, locators: $locators)\n }\n}\n\n```" } ]
code_admin-pages_f6be8d8f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/mutations/SaveRedirectFromFile.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 SaveRedirectFromFile from './SaveRedirectFromFile.graphql'\n\ninterface SaveRedirectFromFileData {\n saveRedirectFromFile: boolean\n}\n\nexport type UploadActionType = 'save' | 'delete'\n\ninterface SaveRedirectFromFileVariables {\n redirects: Redirect[]\n}\n\ntype SaveRedirectFromFileMutationFn = MutationFn<\n SaveRedirectFromFileData,\n SaveRedirectFromFileVariables\n>\n\nexport interface MutationRenderProps\n extends MutationResult<SaveRedirectFromFileData> {\n saveRedirectFromFile: SaveRedirectFromFileMutationFn\n}\n\nclass SaveRedirectFromFileMutation extends Mutation<\n SaveRedirectFromFileData,\n SaveRedirectFromFileVariables\n> {\n public static defaultProps = {\n mutation: SaveRedirectFromFile,\n }\n}\n\nexport default SaveRedirectFromFileMutation\n\n```" } ]
code_admin-pages_fa1cf5d1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/mutations/DeleteManyRedirectsFromFile.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface DeleteManyRedirectsFromFileVariables {\n paths: string[]\n}\n\nexport type DeleteManyRedirectsFromFileResult = boolean\n\nexport type DeleteManyRedirectsFromFileFn = MutationFn<\n DeleteManyRedirectsFromFileVariables,\n DeleteManyRedirectsFromFileResult\n>\n\nexport interface DeleteManyRedirectsProps {\n deleteManyRedirects: DeleteManyRedirectsFromFileFn\n}\n\n```" } ]
code_admin-pages_4501827a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/mutations/SaveRedirectFromFile.graphql from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nmutation SaveManyRedirects($redirects: [RedirectInput!]!) {\n redirect @context(provider: \"vtex.rewriter\") {\n saveMany(routes: $redirects)\n }\n}\n\n```" } ]
code_admin-pages_576d125e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/List/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Query } from 'react-apollo'\nimport { Tenant } from 'vtex.tenant-graphql'\n\nimport Loader from '../../../Loader'\nimport List, { Props } from './List'\nimport TenantInfo from '../../../../queries/TenantInfo.graphql'\nimport { getStoreBindings } from '../../../../utils/bindings'\n\nconst ListWrapper: React.FC<Omit<Props, 'storeBindings'>> = props => {\n return (\n <Query<{ tenantInfo: Tenant }> query={TenantInfo}>\n {({ data, loading: isLoading }) => {\n const tenantInfo = data?.tenantInfo\n if (isLoading || !tenantInfo) {\n return <Loader />\n }\n const storeBindings = getStoreBindings(tenantInfo)\n return <List {...props} storeBindings={storeBindings} />\n }}\n </Query>\n )\n}\n\nexport default ListWrapper\n\n```" } ]
code_admin-pages_d639bfeb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/List/List.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState, useCallback } from 'react'\nimport { FormattedMessage, IntlShape, useIntl } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\nimport {\n ButtonWithIcon,\n IconUpload,\n Table,\n ToastConsumerFunctions,\n} from 'vtex.styleguide'\nimport { Binding } from 'vtex.tenant-graphql'\n\nimport { getFormattedLocalizedDate } from '../../../../utils/date'\nimport { BASE_URL, NEW_REDIRECT_ID } from '../consts'\nimport CreateButton from './CreateButton'\nimport { messages } from './messages'\n\ninterface CustomProps {\n from: number\n items: Redirect[]\n loading: boolean\n onHandleDownload: () => void\n onHandleInputSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void\n openModal: () => void\n refetch: () => void\n showToast: ToastConsumerFunctions['showToast']\n to: number\n storeBindings: Binding[]\n}\n\nexport type Props = CustomProps\n\ninterface Schema {\n properties: object\n}\n\nenum CellData {\n TEMPORARY = 'TEMPORARY',\n PERMANENT = 'PERMANENT',\n}\n\nconst getBindingAddress = (bindingId: string, storeBindings: Binding[]) =>\n storeBindings.find(({ id }) => id === bindingId)?.canonicalBaseAddress\n\nfunction getSchema(intl: IntlShape, locale: string, storeBindings: Binding[]) {\n const bindingProperty =\n storeBindings.length > 1\n ? {\n binding: {\n title: intl.formatMessage(messages.tableBinding),\n type: 'string',\n cellRenderer: function Binding(cell: { cellData: CellData }) {\n const address = getBindingAddress(cell.cellData, storeBindings)\n return <span className=\"ph4\">{address}</span>\n },\n },\n }\n : {}\n\n return {\n properties: {\n from: {\n title: intl.formatMessage(messages.tableFrom),\n type: 'string',\n },\n to: {\n title: intl.formatMessage(messages.tableTo),\n type: 'string',\n },\n type: {\n title: intl.formatMessage(messages.tableType),\n type: 'string',\n cellRenderer: function Type(cell: { cellData: CellData }) {\n return cell.cellData && cell.cellData === CellData.TEMPORARY ? (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.table.type.temporary\"\n defaultMessage=\"Temporary (302)\"\n >\n {text => <span className=\"ph4 silver\">{text}</span>}\n </FormattedMessage>\n ) : (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.table.type.permanent\"\n defaultMessage=\"Permanent (301)\"\n >\n {text => <span className=\"ph4 silver\">{text}</span>}\n </FormattedMessage>\n )\n },\n },\n ...bindingProperty,\n endDate: {\n cellRenderer: function EndDate(cell: { cellData: string }) {\n return cell.cellData ? (\n <span className=\"ph4\">\n {getFormattedLocalizedDate(cell.cellData, locale)}\n </span>\n ) : (\n <FormattedMessage\n id=\"admin/pages.admin.redirects.table.endDate.default\"\n defaultMessage=\"not set\"\n >\n {text => <span className=\"ph4 silver\">{text}</span>}\n </FormattedMessage>\n )\n },\n title: intl.formatMessage(messages.endDateTitle),\n type: 'string',\n },\n },\n }\n}\n\nconst List: React.FC<Props> = ({\n from,\n items,\n loading,\n onHandleDownload,\n onHandleInputSearchChange,\n openModal,\n storeBindings,\n}) => {\n const { culture, navigate } = useRuntime()\n const intl = useIntl()\n\n const [schema, setSchema] = useState<Schema>(() =>\n getSchema(intl, culture.locale, storeBindings)\n )\n\n useEffect(() => {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }, [])\n\n useEffect(() => {\n setSchema(getSchema(intl, culture.locale, storeBindings))\n }, [culture.locale, from, intl, loading, storeBindings])\n\n const handleItemView = useCallback(\n (event: { rowData: Redirect }) => {\n const selectedItem = event.rowData\n const bindingQS = selectedItem.from.includes('?')\n ? `&binding=${selectedItem.binding}`\n : `?binding=${selectedItem.binding}`\n navigate({\n to: `${BASE_URL}${selectedItem.from}${bindingQS}`,\n })\n },\n [navigate]\n )\n\n const handleNewItemOpen = useCallback(() => {\n navigate({ to: `${BASE_URL}/${NEW_REDIRECT_ID}` })\n }, [navigate])\n\n return (\n <Table\n fullWidth\n loading={loading}\n items={items}\n onRowClick={handleItemView}\n schema={schema}\n emptyStateLabel=\"\"\n emptyStateChildren={\n <div className=\"pt5 flex flex-column tc\">\n <div>\n <CreateButton onClick={handleNewItemOpen} />\n </div>\n <p className=\"mv2\">\n <FormattedMessage\n id=\"admin/pages.admin.redirects.or.text\"\n defaultMessage=\"or\"\n />\n </p>\n <div>\n <ButtonWithIcon\n icon={<IconUpload />}\n variation=\"secondary\"\n onClick={openModal}\n size=\"small\"\n >\n <FormattedMessage\n id=\"admin/pages.admin.redirects.emptyState.upload\"\n defaultMessage=\"Upload a CSV\"\n />\n </ButtonWithIcon>\n </div>\n </div>\n }\n toolbar={{\n inputSearch: {\n onChange: onHandleInputSearchChange,\n },\n density: {\n buttonLabel: intl.formatMessage(messages.lineDensityLabel),\n highOptionLabel: intl.formatMessage(messages.lineDensityHigh),\n lowOptionLabel: intl.formatMessage(messages.lineDensityLow),\n mediumOptionLabel: intl.formatMessage(messages.lineDensityMedium),\n },\n download: {\n disabled: items.length === 0,\n handleCallback: onHandleDownload,\n label: intl.formatMessage(messages.download),\n },\n fields: {\n hideAllLabel: intl.formatMessage(messages.hideAll),\n label: intl.formatMessage(messages.fieldsLabel),\n showAllLabel: intl.formatMessage(messages.showAll),\n },\n newLine: {\n handleCallback: handleNewItemOpen,\n label: intl.formatMessage(messages.newLine),\n },\n upload: {\n handleCallback: openModal,\n label: intl.formatMessage(messages.upload),\n },\n }}\n />\n )\n}\n\nexport default List\n\n```" } ]
code_admin-pages_0d01c1d3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/List/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { RedirectsQuery } from '../typings'\n\nexport interface FetchMoreOptions {\n updateQuery: (prevData: RedirectsQuery, newData: UpdateQueryNewData) => void\n variables: QueryVariables\n}\n\ninterface QueryVariables {\n from: number\n to: number\n}\n\ninterface UpdateQueryNewData {\n fetchMoreResult?: RedirectsQuery\n}\n\n```" } ]
code_admin-pages_bbd982ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/List/messages.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { defineMessages } from 'react-intl'\n\nexport const messages = defineMessages({\n download: {\n defaultMessage: 'Export',\n id: 'admin/pages.admin.redirects.table.toolbar.export',\n },\n emptyState: {\n defaultMessage: 'No redirects created.',\n id: 'admin/pages.admin.redirects.emptyState',\n },\n endDateTitle: {\n defaultMessage: 'End date',\n id: 'admin/pages.admin.redirects.table.endDate.title',\n },\n fieldsLabel: {\n defaultMessage: 'Toggle visible fields',\n id: 'admin/pages.admin.redirects.table.toolbar.fields.label',\n },\n hideAll: {\n defaultMessage: 'Hide all',\n id: 'admin/pages.admin.redirects.table.toolbar.fields.hide-all',\n },\n lineDensityHigh: {\n defaultMessage: 'High',\n id: 'admin/pages.admin.redirects.table.toolbar.line-density.high',\n },\n lineDensityLabel: {\n defaultMessage: 'Line density',\n id: 'admin/pages.admin.redirects.table.toolbar.line-density.label',\n },\n lineDensityLow: {\n defaultMessage: 'Low',\n id: 'admin/pages.admin.redirects.table.toolbar.line-density.low',\n },\n lineDensityMedium: {\n defaultMessage: 'Medium',\n id: 'admin/pages.admin.redirects.table.toolbar.line-density.medium',\n },\n newLine: {\n defaultMessage: 'New redirect',\n id: 'admin/pages.admin.redirects.button.create',\n },\n showAll: {\n defaultMessage: 'Show all',\n id: 'admin/pages.admin.redirects.table.toolbar.fields.show-all',\n },\n tableFrom: {\n defaultMessage: 'From',\n id: 'admin/pages.admin.redirects.table.from',\n },\n tableTo: {\n defaultMessage: 'To',\n id: 'admin/pages.admin.redirects.table.to',\n },\n tableType: {\n defaultMessage: 'Type',\n id: 'admin/pages.admin.redirects.table.type',\n },\n upload: {\n defaultMessage: 'Import',\n id: 'admin/pages.admin.redirects.table.toolbar.import',\n },\n tableBinding: {\n defaultMessage: 'Binding',\n id: 'admin/pages.admin.redirects.table.binding',\n },\n})\n\n```" } ]
code_admin-pages_0a8936ea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/List/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 { Button } from 'vtex.styleguide'\n\ninterface Props {\n onClick: () => void\n}\n\nconst CreateButton = ({ onClick }: Props) => (\n <Button onClick={onClick} size=\"small\" variation=\"primary\">\n <FormattedMessage id=\"admin/pages.admin.redirects.button.create\" />\n </Button>\n)\n\nexport default CreateButton\n\n```" } ]
code_admin-pages_cdad6d32
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/ImportErrorModal/ImportErrorModal.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.import-error-modal-scroll::-webkit-scrollbar,\n.import-error-modal-scroll::-webkit-scrollbar-track {\n width: 2px;\n background: #f2f4f5;\n}\n\n.import-error-modal-scroll::-webkit-scrollbar-thumb {\n width: 2px;\n background: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n}\n\n```" } ]
code_admin-pages_134a6197
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/ImportErrorModal/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, IntlShape } from 'react-intl'\nimport {\n Button,\n IconDownload,\n Modal,\n ModalProps,\n ButtonWithIcon,\n} from 'vtex.styleguide'\nimport streamSaver from 'streamsaver'\nimport { TextEncoder } from 'text-encoding'\nimport * as WebStreamsPolyfill from 'web-streams-polyfill/ponyfill'\n\nimport styles from './ImportErrorModal.css'\nimport { getCSVHeader } from '../consts'\nimport { AlertState } from '../typings'\nimport bulkUploadRedirects from '../bulkUploadRedirects'\n\ninterface Props extends Omit<ModalProps, 'children'> {\n isOpen: boolean\n redirects: Redirect[]\n mutation: (data: Redirect[]) => Promise<void>\n isSave: boolean\n setAlert: (alertState: AlertState) => void\n hasMultipleBindings: boolean\n}\n\ninterface GetAlertStateArgs {\n isSave: boolean\n failedRedirects: Redirect[]\n intl: IntlShape\n mutation: (data: Redirect[]) => Promise<void>\n total: number\n}\n\nstreamSaver.WritableStream = WebStreamsPolyfill.WritableStream\n\nconst messages = defineMessages({\n bulkUploadErrorButtonLabel: {\n defaultMessage: 'See errors',\n id: 'admin/pages.admin.redirects.bulk.failed.button',\n },\n buttonCancel: {\n defaultMessage: 'Cancel',\n id: 'admin/pages.admin.redirects.import-error.button.cancel',\n },\n buttonDownload: {\n defaultMessage: 'Download',\n id: 'admin/pages.admin.redirects.import-error.button.download',\n },\n buttonRetry: {\n defaultMessage: 'Retry',\n id: 'admin/pages.admin.redirects.import-error.button.retry',\n },\n retrySuccess: {\n defaultMessage: 'Retry successful.',\n id: 'admin/pages.admin.redirects.import-error.retry-success',\n },\n retryFail: {\n defaultMessage: 'Retry failed: {success} successful, {failed} failed.',\n id: 'admin/pages.admin.redirects.import-error.retry-fail',\n },\n title: {\n defaultMessage: 'Failed Redirects',\n id: 'admin/pages.admin.redirects.import-error.title',\n },\n})\n\nfunction getAlertState({\n isSave,\n total,\n failedRedirects,\n intl,\n mutation,\n}: GetAlertStateArgs): AlertState {\n if (failedRedirects.length === 0) {\n return {\n type: 'success',\n message: intl.formatMessage(messages.retrySuccess),\n }\n }\n return {\n type: failedRedirects.length === total ? 'error' : 'warning',\n message: intl.formatMessage(messages.retryFail, {\n success: intl.formatNumber(total - failedRedirects.length),\n failed: intl.formatNumber(failedRedirects.length),\n }),\n meta: {\n failedRedirects: failedRedirects,\n mutation,\n isSave,\n },\n action: {\n label: intl.formatMessage(messages.bulkUploadErrorButtonLabel),\n },\n }\n}\n\nconst ImportErrorModal: React.FC<Props> = ({\n isSave,\n redirects,\n isOpen,\n mutation,\n onClose,\n setAlert,\n hasMultipleBindings,\n}) => {\n const intl = useIntl()\n const shouldUploadRef = React.useRef<boolean>(false)\n\n React.useEffect(() => {\n shouldUploadRef.current = isOpen\n }, [isOpen])\n\n const [isRetrying, setIsRetrying] = React.useState(false)\n\n const handleDownload = React.useCallback(() => {\n const fileStream = streamSaver.createWriteStream('failed_redirects.csv')\n const writer = fileStream.getWriter()\n const textEncoder = new TextEncoder()\n writer.write(textEncoder.encode(getCSVHeader(hasMultipleBindings) + '\\n'))\n redirects.forEach(({ endDate, from, to, type }) => {\n writer.write(\n textEncoder.encode(`${from};${to};${type};${endDate || ''}\\n`)\n )\n })\n writer.close()\n }, [redirects, hasMultipleBindings])\n\n const handleRetry = React.useCallback(async () => {\n shouldUploadRef.current = true\n try {\n const numberOfLines = redirects.length\n\n setIsRetrying(true)\n\n const { failedRedirects } = await bulkUploadRedirects({\n data: redirects,\n isSave,\n mutation,\n shouldUploadRef,\n })\n\n setIsRetrying(false)\n\n if (shouldUploadRef.current) {\n setAlert(\n getAlertState({\n total: numberOfLines,\n failedRedirects,\n intl,\n mutation,\n isSave,\n })\n )\n onClose()\n }\n } catch (e) {\n console.error(e)\n }\n }, [redirects, isSave, mutation, setAlert, intl, onClose])\n\n return (\n <Modal\n centered\n isOpen={isOpen}\n onClose={onClose}\n title={<h2 className=\"mv0\">{intl.formatMessage(messages.title)}</h2>}\n bottomBar={\n <>\n <Button\n variation=\"secondary\"\n isLoading={isRetrying}\n onClick={handleRetry}\n >\n {intl.formatMessage(messages.buttonRetry)}\n </Button>\n <span className=\"mr4\">\n <Button\n disabled={isRetrying}\n variation=\"tertiary\"\n onClick={onClose}\n >\n {intl.formatMessage(messages.buttonCancel)}\n </Button>\n </span>\n <span className=\"mr-auto\">\n <ButtonWithIcon\n disabled={isRetrying}\n icon={<IconDownload />}\n variation=\"tertiary\"\n onClick={handleDownload}\n >\n {intl.formatMessage(messages.buttonDownload)}\n </ButtonWithIcon>\n </span>\n </>\n }\n >\n <ul\n className={`list pl0 b--muted-5 ba br2 f6 lh-copy pa3 ${styles['import-error-modal-scroll']}`}\n >\n <li>{getCSVHeader(hasMultipleBindings)}</li>\n {redirects.map(({ endDate, from, to, type }) => (\n <li\n key={`failed-redirect-${from}`}\n >{`${from};${to};${type};${endDate || ''}`}</li>\n ))}\n </ul>\n </Modal>\n )\n}\n\nexport default React.memo(ImportErrorModal)\n\n```" } ]
code_admin-pages_01c6e748
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadPrompt/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classnames from 'classnames'\nimport { zipObj } from 'ramda'\nimport React, { useState, useCallback } from 'react'\nimport { useDropzone } from 'react-dropzone'\nimport { defineMessages, useIntl } from 'react-intl'\nimport { Alert, AlertProps, Button, IconDelete, Radio } from 'vtex.styleguide'\n\nimport UploadTableIcon from '../../../../icons/UploadTable'\nimport { UploadActionType } from '../../mutations/SaveRedirectFromFile'\nimport { getCSVHeader, CSV_SEPARATOR } from '../../consts'\nimport { isRedirectType, validateRedirect } from './validateRedirect'\nimport styles from './UploadPrompt.css'\n\ninterface Props {\n hasRedirects: boolean\n onCancel: () => void\n onDownloadTemplate: () => void\n saveRedirectFromFile: (\n parsedJsonFromCsv: Redirect[],\n fileName: string,\n hasMultipleBindings: boolean\n ) => void\n setUploadActionType: React.Dispatch<React.SetStateAction<UploadActionType>>\n uploadActionType: UploadActionType\n hasMultipleBindings: boolean\n}\n\nconst messages = defineMessages({\n alertSeeErrors: {\n defaultMessage: 'See errors',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.alert.validation-errors.action',\n },\n body: {\n defaultMessage: 'Please use our template or an exported file as base.',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.body',\n },\n buttonCancel: {\n defaultMessage: 'Cancel',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.button.cancel',\n },\n buttonImport: {\n defaultMessage: 'Import file',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.button.import',\n },\n dropButton: {\n defaultMessage: 'choose a file',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.drop.button',\n },\n dropMessage: {\n defaultMessage: 'Drop here your CSV or ',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.drop.message',\n },\n downloadTemplate: {\n defaultMessage: 'Download template',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.body.download-template',\n },\n selectSave: {\n defaultMessage: 'Save',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.select-action.save',\n },\n selectDelete: {\n defaultMessage: 'Delete',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.select-action.delete',\n },\n selectUploadBody: {\n defaultMessage: 'Do you want to save or delete redirects?',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.select-action.body',\n },\n unsupportedFileFormat: {\n defaultMessage: 'Unsupported file type. Please upload a .csv file.',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.alert.unsupported-file',\n },\n validationErrors: {\n defaultMessage: 'Validation errors on file {name}',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.alert.validation-errors',\n },\n missingBindingData: {\n defaultMessage: 'Binding information missing from redirect {route}',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.alert.missing-binding-data',\n },\n extraBindingData: {\n defaultMessage: 'Uneccessary binding information from redirect {route}',\n id:\n 'admin/pages.admin.redirects.upload-modal.prompt.alert.extra-binding-data',\n },\n})\n\ninterface AlertState {\n message: string\n action?: AlertProps['action']\n}\n\nconst UploadPrompt: React.FC<Props> = ({\n hasRedirects,\n onCancel,\n onDownloadTemplate,\n saveRedirectFromFile,\n setUploadActionType,\n uploadActionType,\n hasMultipleBindings,\n}) => {\n const intl = useIntl()\n const [file, setFile] = useState<File | null>(null)\n const [shouldShowErrors, setShouldShowError] = useState(false)\n const [parsedJsonFromCsv, setParsedJsonFromCsv] = useState<Redirect[] | null>(\n null\n )\n\n const [alertState, setAlert] = useState<AlertState | null>(null)\n const [validationErrors, setValidationErrors] = useState<string[] | null>(\n null\n )\n\n const resetErrors = useCallback(() => {\n setShouldShowError(false)\n setValidationErrors(null)\n setAlert(null)\n }, [setShouldShowError, setValidationErrors, setAlert])\n\n const onDrop = useCallback(\n acceptedFiles => {\n const file = acceptedFiles[0]\n const fileExtension = file.name.substr(file.name.lastIndexOf('.') + 1)\n let nextValidationErrors: typeof validationErrors = null\n\n if (fileExtension !== 'csv') {\n return setAlert({\n message: intl.formatMessage(messages.unsupportedFileFormat),\n })\n }\n\n resetErrors()\n\n const reader = new FileReader()\n reader.onload = async () => {\n const redirectKeys = getCSVHeader(hasMultipleBindings).split(\n CSV_SEPARATOR\n ) as Array<keyof Redirect>\n let parsedJsonFromCsv = null\n if (typeof reader.result === 'string') {\n parsedJsonFromCsv = reader.result\n .trim()\n .split('\\n')\n .reduce<Redirect[]>((acc, line, lineNumber) => {\n if (lineNumber === 0) {\n return acc\n }\n const values = line.split(CSV_SEPARATOR)\n const redirect = zipObj(redirectKeys, values)\n const wrongNumberOfPropeties =\n redirectKeys.length != values.length\n if (hasMultipleBindings && wrongNumberOfPropeties) {\n nextValidationErrors = (nextValidationErrors || []).concat(\n intl.formatMessage(messages.missingBindingData, {\n route: redirect.from,\n })\n )\n return acc\n }\n if (!hasMultipleBindings && wrongNumberOfPropeties) {\n nextValidationErrors = (nextValidationErrors || []).concat(\n intl.formatMessage(messages.extraBindingData, {\n route: redirect.from,\n })\n )\n return acc\n }\n if (isRedirectType(redirect)) {\n const validationError = validateRedirect(\n redirect,\n lineNumber,\n intl\n )\n if (!validationError) {\n acc.push({\n ...redirect,\n endDate: redirect.endDate || null,\n type: redirect.type.toUpperCase() as Redirect['type'],\n })\n } else {\n nextValidationErrors = (nextValidationErrors || []).concat(\n validationError\n )\n }\n }\n return acc\n }, [])\n }\n\n if (nextValidationErrors && nextValidationErrors.length > 0) {\n setAlert({\n message: intl.formatMessage(messages.validationErrors, {\n name: file.name,\n }),\n action: {\n label: intl.formatMessage(messages.alertSeeErrors),\n onClick: () => setShouldShowError(value => !value),\n },\n })\n return setValidationErrors(nextValidationErrors)\n }\n\n setParsedJsonFromCsv(parsedJsonFromCsv)\n }\n reader.readAsText(file)\n setFile(file)\n },\n [intl, resetErrors, validationErrors, hasMultipleBindings]\n )\n\n const { getRootProps, getInputProps } = useDropzone({\n onDrop,\n multiple: false,\n })\n\n const handleSaveRadioChange = useCallback(() => {\n setUploadActionType('save')\n }, [setUploadActionType])\n\n const handleDeleteRadioChange = useCallback(() => {\n setUploadActionType('delete')\n }, [setUploadActionType])\n\n return (\n <>\n <p className=\"f4 fw3 mt0 mb5\">\n {intl.formatMessage(messages.selectUploadBody)}\n </p>\n <Radio\n disabled={!hasRedirects}\n id=\"merge-upload-action-type\"\n checked={uploadActionType === 'save'}\n label={intl.formatMessage(messages.selectSave)}\n name=\"upload-action-type\"\n onChange={handleSaveRadioChange}\n value=\"save\"\n />\n <Radio\n disabled={!hasRedirects}\n id=\"overwrite-upload-action-type\"\n checked={uploadActionType === 'delete'}\n label={intl.formatMessage(messages.selectDelete)}\n name=\"upload-action-type\"\n onChange={handleDeleteRadioChange}\n value=\"delete\"\n />\n <p className=\"f5 lh-copy mv5\">{intl.formatMessage(messages.body)}</p>\n\n {alertState && (\n <>\n <Alert type=\"error\" action={alertState.action}>\n {alertState.message}\n </Alert>\n {shouldShowErrors && validationErrors && validationErrors.length > 0 && (\n <ul\n className={`list pl0 b--muted-5 ba br2 f6 lh-copy overflow-y-auto pa3 ${styles['validation-errors-container']}`}\n >\n {validationErrors.map((errorMessage, id) => (\n <li key={`validation-error-${id}`}>{errorMessage}</li>\n ))}\n </ul>\n )}\n </>\n )}\n\n <div\n className={classnames(\n 'w-100 ba br3 bw1 b--dashed flex items-center mt4',\n {\n 'b--action-secondary hover-b--action-secondary bg-white justify-center': !file,\n 'b--muted-3 hover-b--muted-2 bg-muted-5 justify-between ph5': !!file,\n }\n )}\n >\n {!file ? (\n <div\n {...getRootProps({\n className:\n 'flex flex-column items-center justify-center w-100 pv8',\n })}\n >\n <input {...getInputProps()} />\n <div className=\"c-action-primary\">\n <UploadTableIcon />\n </div>\n <p className=\"tc lh-copy mb0\">\n {intl.formatMessage(messages.dropMessage)}{' '}\n <button className=\"input-reset bg-white bw0 fw5 pa0 hover-c-action-primary c-action-primary pointer\">\n {intl.formatMessage(messages.dropButton)}\n </button>\n .\n </p>\n </div>\n ) : (\n <>\n <p className=\"c-on-base\">{file.name}</p>\n <button\n className=\"input-reset pa0 bn c-action-primary pointer bg-transparent\"\n onClick={() => {\n setFile(null)\n resetErrors()\n }}\n >\n <IconDelete />\n </button>\n </>\n )}\n </div>\n\n <div className=\"flex mt5\">\n <div className=\"mr-auto\">\n <Button\n type=\"button\"\n variation=\"tertiary\"\n onClick={onDownloadTemplate}\n >\n {intl.formatMessage(messages.downloadTemplate)}\n </Button>\n </div>\n <div className=\"mr3\">\n <Button type=\"button\" variation=\"tertiary\" onClick={onCancel}>\n {intl.formatMessage(messages.buttonCancel)}\n </Button>\n </div>\n <Button\n type=\"button\"\n variation=\"primary\"\n disabled={!parsedJsonFromCsv || validationErrors}\n onClick={() =>\n parsedJsonFromCsv &&\n file &&\n saveRedirectFromFile(\n parsedJsonFromCsv,\n file.name,\n hasMultipleBindings\n )\n }\n >\n {intl.formatMessage(messages.buttonImport)}\n </Button>\n </div>\n </>\n )\n}\n\nexport default React.memo(UploadPrompt)\n\n```" } ]
code_admin-pages_5e1a609b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadPrompt/validateRedirect.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defineMessages, IntlShape } from 'react-intl'\n\nexport function isRedirectType(obj: unknown): obj is Redirect {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'endDate' in obj &&\n 'from' in obj &&\n 'to' in obj &&\n 'type' in obj &&\n typeof (obj as Record<string, string>).type === 'string'\n )\n}\n\nconst messages = defineMessages({\n invalidTypeError: {\n defaultMessage:\n '[Line {line}] Invalid value \"{type}\" for redirect type. Allowed values are \"PERMANENT\" and \"TEMPORARY\".',\n id: 'admin/pages.admin.redirects.upload-modal.prompt.validation-error.type',\n },\n})\n\nexport function validateRedirect(\n redirect: Redirect,\n line: number,\n intl: IntlShape\n): string | undefined {\n const { type } = redirect\n return type.toUpperCase() !== 'PERMANENT' &&\n type.toUpperCase() !== 'TEMPORARY'\n ? intl.formatMessage(messages.invalidTypeError, {\n line,\n type,\n })\n : undefined\n}\n\n```" } ]
code_admin-pages_3d160df7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadPrompt/UploadPrompt.css from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.validation-errors-container {\n max-height: 16rem;\n}\n\n.validation-errors-container::-webkit-scrollbar,\n.validation-errors-container::-webkit-scrollbar-track {\n width: 4px;\n background: #f2f4f5;\n}\n\n.validation-errors-container::-webkit-scrollbar-thumb {\n width: 4px;\n background: rgba(0, 0, 0, 0.2);\n border-radius: 2px;\n}\n\n```" } ]
code_admin-pages_77fa4919
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/redirects/UploadModal/UploadPrompt/getAlertState.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defineMessages, IntlShape } from 'react-intl'\n\nimport { AlertState } from '../../typings'\n\ninterface GetAlertStateArgs {\n isSave: boolean\n failedRedirects: Redirect[]\n fileName: string\n intl: IntlShape\n mutation: (data: Redirect[]) => Promise<void>\n total: number\n}\n\nconst messages = defineMessages({\n bulkUploadAllFailed: {\n defaultMessage: `We couldn't process all {lines} lines from file {fileName}. Please try again.`,\n id: 'admin/pages.admin.redirects.bulk.failed',\n },\n bulkUploadErrorButtonLabel: {\n defaultMessage: 'See errors',\n id: 'admin/pages.admin.redirects.bulk.failed.button',\n },\n bulkUploadPartial: {\n defaultMessage:\n 'Import of file {fileName} was partially successful: {success} successful, {failed} failed.',\n id: 'admin/pages.admin.redirects.bulk.partial',\n },\n bulkUploadSuccess: {\n defaultMessage:\n 'All done. {lines} lines were successfully processed from file \"{fileName}\"',\n id: 'admin/pages.admin.redirects.bulk.success',\n },\n})\n\nexport function getAlertState({\n isSave,\n total,\n failedRedirects,\n intl,\n fileName,\n mutation,\n}: GetAlertStateArgs): AlertState {\n if (failedRedirects.length > 0 && failedRedirects.length === total) {\n return {\n type: 'error',\n message: intl.formatMessage(messages.bulkUploadAllFailed, {\n fileName,\n lines: intl.formatNumber(total),\n }),\n }\n } else if (failedRedirects.length === 0) {\n return {\n type: 'success',\n message: intl.formatMessage(messages.bulkUploadSuccess, {\n fileName,\n lines: intl.formatNumber(total),\n }),\n }\n }\n return {\n type: 'warning',\n message: intl.formatMessage(messages.bulkUploadPartial, {\n fileName,\n success: intl.formatNumber(total - failedRedirects.length),\n failed: intl.formatNumber(failedRedirects.length),\n }),\n meta: {\n failedRedirects: failedRedirects,\n mutation,\n isSave,\n },\n action: {\n label: intl.formatMessage(messages.bulkUploadErrorButtonLabel),\n },\n }\n}\n\n```" } ]
code_admin-pages_88cd4273
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/index.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { diff } from 'deep-object-diff'\nimport { RouteFormData } from 'pages'\nimport { isEmpty } from 'ramda'\nimport React, { Component } from 'react'\nimport { defineMessages, InjectedIntlProps, injectIntl } from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport {\n ConditionsProps,\n ConditionsStatement,\n ToastConsumerFunctions,\n} from 'vtex.styleguide'\nimport { Binding } from 'vtex.tenant-graphql'\n\nimport { formatStatements } from '../../../../utils/conditions'\nimport { isNewRoute, isUserRoute } from '../utils'\nimport { generateNewRouteId } from './utils'\nimport Form from './Form'\nimport {\n getAddConditionalTemplateState,\n getChangeOperatorConditionalTemplateState,\n getChangeStatementsConditionalTemplate,\n getChangeTemplateConditionalTemplateState,\n getLoginToggleState,\n getRemoveConditionalTemplateState,\n getValidateFormState,\n} from './stateHandlers'\nimport { FormErrors } from './typings'\nimport { OperationsResults } from './Operations'\nimport { slugify } from '../../utils'\nimport { DropdownChangeInput } from '../../../../utils/bindings/typings'\n\ninterface ComponentProps {\n isCustomPage: boolean\n initialData: RouteFormData\n onDelete: OperationsResults['deleteRoute']\n onExit: () => void\n onSave: OperationsResults['saveRoute']\n runtime: RenderContext\n templates: Template[]\n showToast: ToastConsumerFunctions['showToast']\n hideToast: ToastConsumerFunctions['hideToast']\n storeBindings: Binding[]\n setLocalStorageBinding: (b: Binding) => void\n}\n\ntype Props = ComponentProps & InjectedIntlProps\n\nexport interface State {\n data: RouteFormData\n isDeletable: boolean\n isLoading: boolean\n isInfoEditable: boolean\n formErrors: FormErrors\n storeBindings: Binding[]\n}\n\nconst messages = defineMessages({\n deleteError: {\n defaultMessage: 'Error: route could not be deleted.',\n id: 'admin/pages.admin.pages.form.delete.error',\n },\n deleteSuccess: {\n defaultMessage: 'Success',\n id: 'admin/pages.admin.pages.form.delete.success',\n },\n saveError: {\n defaultMessage: 'Error: route could not be saved.',\n id: 'admin/pages.admin.pages.form.save.error',\n },\n saveSuccess: {\n defaultMessage: 'Success',\n id: 'admin/pages.admin.pages.form.save.success',\n },\n})\n\nclass FormContainer extends Component<Props, State> {\n private isNew: boolean\n\n public constructor(props: Props) {\n super(props)\n\n const { declarer } = props.initialData || { declarer: null }\n\n this.isNew = isNewRoute(props.initialData)\n this.state = {\n data: props.initialData,\n formErrors: {},\n isDeletable: !declarer && !this.isNew,\n isInfoEditable: !declarer || this.isNew,\n isLoading: false,\n storeBindings: props.storeBindings,\n }\n }\n\n public componentDidMount() {\n window.top.postMessage({ action: { type: 'STOP_LOADING' } }, '*')\n }\n\n public render() {\n const { isCustomPage, templates, onExit } = this.props\n const {\n data,\n formErrors,\n isDeletable,\n isInfoEditable,\n isLoading,\n storeBindings,\n } = this.state\n\n return (\n <Form\n isCustomPage={isCustomPage}\n data={data}\n detailChangeHandlerGetter={this.getDetailChangeHandler}\n isDeletable={isDeletable}\n isLoading={isLoading}\n isInfoEditable={isInfoEditable}\n onDelete={this.handleDelete}\n onExit={onExit}\n onLoginToggle={this.handleLoginToggle}\n onSave={this.handleSave}\n templates={templates}\n storeBindings={storeBindings}\n onAddConditionalTemplate={this.handleAddConditionalTemplate}\n onChangeKeywords={this.handleMetaTagKeywords}\n onRemoveConditionalTemplate={this.handleRemoveConditionalTemplate}\n onChangeTemplateConditionalTemplate={\n this.handleChangeTemplateConditionalTemplate\n }\n onChangeBinding={this.handleBindingChange}\n onChangeOperatorConditionalTemplate={\n this.handleChangeOperatorConditionalTemplate\n }\n onChangeStatementsConditionalTemplate={\n this.handleChangeStatementsConditionalTemplate\n }\n formErrors={formErrors}\n />\n )\n }\n\n private handleRemoveConditionalTemplate = (uniqueId: number) => {\n this.setState(getRemoveConditionalTemplateState(uniqueId))\n }\n\n private handleAddConditionalTemplate = () => {\n this.setState(getAddConditionalTemplateState)\n }\n\n private handleBindingChange = ({\n target: { value },\n }: DropdownChangeInput) => {\n const { setLocalStorageBinding } = this.props\n const { storeBindings, data } = this.state\n const selectedBinding = storeBindings.find(binding => binding.id === value)\n if (!selectedBinding) {\n throw new Error(\n \"Selected binding does not exist or isn't a store binding\"\n )\n }\n data.binding = selectedBinding.id\n setLocalStorageBinding(selectedBinding)\n this.setState({ data })\n }\n\n private handleChangeTemplateConditionalTemplate = (\n uniqueId: number,\n template: string\n ) => {\n this.setState(getChangeTemplateConditionalTemplateState(uniqueId, template))\n }\n\n private handleChangeOperatorConditionalTemplate = (\n uniqueId: number,\n operator: NonNullable<ConditionsProps['operator']>\n ) => {\n this.setState(getChangeOperatorConditionalTemplateState(uniqueId, operator))\n }\n\n private handleChangeStatementsConditionalTemplate = (\n uniqueId: number,\n statements: ConditionsStatement[]\n ) => {\n this.setState(getChangeStatementsConditionalTemplate(uniqueId, statements))\n }\n\n private handleMetaTagKeywords = (\n values: { label: string; value: string }[]\n ) => {\n this.setState(prevState => ({\n ...prevState,\n data: {\n ...prevState.data,\n metaTagKeywords: values,\n },\n formErrors: {},\n }))\n }\n\n private getDetailChangeHandler = (detailName: string) => (\n e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => {\n const newDetailValue = e.target.value\n const newDataPayload = {\n [detailName]: newDetailValue,\n ...(detailName === 'title' &&\n this.isNew && { path: `/${slugify(newDetailValue)}` }),\n }\n\n this.setState(prevState => ({\n ...prevState,\n data: {\n ...prevState.data,\n ...newDataPayload,\n },\n formErrors: {},\n }))\n }\n\n private handleDelete = () => {\n const { showToast, intl, onDelete, onExit } = this.props\n const { data } = this.state\n\n this.setState({ isLoading: true }, async () => {\n try {\n if (!data.uuid) {\n throw new Error('No uuid')\n }\n\n await onDelete({\n variables: {\n uuid: data.uuid,\n },\n })\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.deleteSuccess),\n })\n\n onExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.deleteError),\n })\n })\n }\n })\n }\n\n private handleLoginToggle = () => {\n this.setState(getLoginToggleState)\n }\n\n private handleSave = (event: React.FormEvent) => {\n const { intl, onExit, onSave, showToast } = this.props\n\n event.preventDefault()\n\n const nextState = getValidateFormState(this.state)\n\n if (isEmpty(nextState.formErrors)) {\n const {\n auth,\n binding: bindingId,\n blockId,\n context,\n declarer,\n domain,\n interfaceId,\n metaTagDescription,\n metaTagKeywords,\n metaTagRobots,\n pages,\n path,\n routeId,\n title,\n uuid,\n dataSource,\n } = isUserRoute(this.props.initialData)\n ? this.state.data\n : {\n ...(diff(this.props.initialData, this.state.data) as Partial<\n RouteFormData\n >),\n ...this.state.data,\n pages: this.state.data.pages || this.state.data,\n blockId: this.state.data.blockId || this.props.initialData,\n }\n\n const metaTags =\n metaTagDescription || metaTagKeywords || metaTagRobots\n ? {\n description: metaTagDescription,\n keywords: metaTagKeywords?.map(({ value }) => value),\n robots: metaTagRobots\n }\n : undefined\n\n this.setState({ isLoading: true }, async () => {\n try {\n await onSave({\n variables: {\n route: {\n auth,\n bindingId,\n blockId,\n context,\n declarer,\n domain,\n interfaceId,\n metaTags,\n pages:\n pages &&\n pages.map(page => {\n return {\n condition: {\n allMatches: page.condition.allMatches,\n id: page.condition.id || undefined,\n statements: formatStatements(page.condition.statements),\n },\n pageId: page.pageId || undefined,\n template: page.template,\n }\n }),\n path,\n routeId:\n routeId ||\n generateNewRouteId(\n interfaceId || this.state.data.interfaceId,\n path\n ),\n title,\n uuid,\n dataSource,\n },\n },\n })\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.saveSuccess),\n })\n\n onExit()\n } catch (err) {\n this.setState({ isLoading: false }, () => {\n console.error(err)\n\n showToast({\n horizontalPosition: 'right',\n message: intl.formatMessage(messages.saveError),\n })\n })\n }\n })\n } else {\n this.setState(getValidateFormState)\n }\n }\n}\n\nexport default withRuntimeContext(injectIntl(FormContainer))\n\n```" } ]
code_admin-pages_bb39f94a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/Title.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst Title: React.FunctionComponent = ({ children }) => (\n <h1 className=\"mb7 pb7 bb bw1 b--light-silver f3 normal\">{children}</h1>\n)\n\nexport default Title\n\n```" } ]
code_admin-pages_46d55291
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/ConditionalTemplatePicker.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { path } from 'ramda'\nimport React from 'react'\nimport {\n defineMessages,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport {\n ConditionsProps,\n ConditionsStatement,\n Dropdown,\n IconClose,\n} from 'vtex.styleguide'\nimport { ConditionFormsData } from 'pages'\n\nimport SelectConditions from './SelectConditions'\nimport { FormErrors } from './typings'\n\nexport interface ConditionalTemplatePickerProps {\n condition: ConditionFormsData\n formErrors: FormErrors\n onChangeOperatorConditionalTemplate: (\n uniqueId: number,\n operator: NonNullable<ConditionsProps['operator']>\n ) => void\n onChangeTemplateConditionalTemplate: (\n uniqueId: number,\n template: string\n ) => void\n onChangeStatementsConditionalTemplate: (\n uniqueId: number,\n statements: ConditionsStatement[]\n ) => void\n onRemoveConditionalTemplate: (uniqueId: number) => void\n operator: ConditionsProps['operator']\n pageId: number\n template: string\n templates: Template[]\n}\n\ntype Props = ConditionalTemplatePickerProps & ComponentWithIntlProps\n\nconst messages = defineMessages({\n errorMessage: {\n defaultMessage: 'Required',\n id: 'admin/pages.admin.pages.form.templates.field.required',\n },\n pathValidationErrorMessage: {\n defaultMessage: `URL should begin with '/'.`,\n id: 'admin/pages.admin.pages.form.templates.path.validation-error',\n },\n templateLabel: {\n defaultMessage: 'Template',\n id: 'admin/pages.admin.pages.form.templates.conditional.template.label',\n },\n})\n\nexport const ConditionalTemplatePicker: React.FunctionComponent<Props> = ({\n condition,\n formErrors,\n intl,\n onChangeOperatorConditionalTemplate,\n onChangeStatementsConditionalTemplate,\n onChangeTemplateConditionalTemplate,\n operator,\n onRemoveConditionalTemplate,\n pageId,\n template,\n templates,\n}) => {\n const hasError =\n !!path(['pages', pageId, 'condition'], formErrors) ||\n !!path(['pages', pageId, 'template'], formErrors)\n\n const closeButtonStyle = hasError\n ? {\n marginBottom: 'auto',\n marginTop: 'auto',\n }\n : undefined\n\n return (\n <div className={`flex ${!hasError ? 'items-center' : ''} mv5`}>\n <div className=\"flex flex-column flex-grow-1 mr4 ph4\">\n <Dropdown\n label={intl.formatMessage(messages.templateLabel)}\n options={templates.map(({ id }) => ({ value: id, label: id }))}\n onChange={(_: React.ChangeEvent, value: string) =>\n onChangeTemplateConditionalTemplate(pageId, value)\n }\n value={template}\n errorMessage={\n path(['pages', pageId, 'template'], formErrors) &&\n intl.formatMessage({\n id: path(['pages', pageId, 'template'], formErrors) as string,\n })\n }\n />\n <div className=\"flex flex-column w-100 mt5\">\n <SelectConditions\n onChangeOperator={({ operator: newOperator }) => {\n onChangeOperatorConditionalTemplate(pageId, newOperator)\n }}\n operator={operator}\n condition={condition}\n onChangeStatements={statements => {\n onChangeStatementsConditionalTemplate(pageId, statements)\n }}\n errorMessage={\n path(['pages', pageId, 'condition'], formErrors) &&\n intl.formatMessage({\n id: path(['pages', pageId, 'condition'], formErrors) as string,\n })\n }\n />\n </div>\n </div>\n <button\n type=\"button\"\n className=\"w1 h1 bg-silver br-100 flex items-center justify-center bn pa1 mt6\"\n style={closeButtonStyle}\n onClick={() => onRemoveConditionalTemplate(pageId)}\n >\n <IconClose color=\"white\" size={12} />\n </button>\n </div>\n )\n}\n\n```" } ]
code_admin-pages_2760ce73
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/utils.test.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { generateNewRouteId } from './utils'\n\ndescribe('#generateNewRouteId', () => {\n it('should remove trailing slash from path', () => {\n expect(\n generateNewRouteId('vtex.store@2.x:store.custom', '/path1/path2/')\n ).toBe('vtex.store@2.x:store.custom#path1-path2')\n })\n\n it('should generate a routeId without \"/\"', () => {\n expect(\n generateNewRouteId('vtex.store@2.x:store.custom', '/path1/path2')\n ).toEqual(expect.not.stringContaining('/'))\n })\n})\n\n```" } ]
code_admin-pages_6590b172
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/SelectConditions.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport {\n FormattedMessage,\n injectIntl,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { withRuntimeContext } from 'vtex.render-runtime'\nimport {\n ConditionsProps,\n ConditionsRenderFn,\n ConditionsStatement,\n DatePicker,\n EXPERIMENTAL_Conditions as Conditions,\n} from 'vtex.styleguide'\nimport { ConditionFormsData } from 'pages'\n\nimport { messages } from './messages'\n\ninterface ComponentProps {\n condition: ConditionFormsData\n errorMessage?: string\n operator: ConditionsProps['operator']\n onChangeOperator: ConditionsProps['onChangeOperator']\n onChangeStatements: (statements: ConditionsStatement[]) => void\n}\n\ntype Props = ComponentProps & RenderContextProps & ComponentWithIntlProps\n\nclass SelectConditions extends React.Component<Props> {\n private options: ConditionsProps['options']\n private labels: ConditionsProps['labels']\n\n public constructor(props: Props) {\n super(props)\n\n const intl = props.intl\n\n this.labels = {\n addConditionBtn: intl.formatMessage(messages.addCondition),\n addNewCondition: intl.formatMessage(messages.addCondition),\n delete: intl.formatMessage(messages.delete),\n headerPrefix: intl.formatMessage(messages.headerPrefix),\n headerSufix: intl.formatMessage(messages.headerSuffix),\n noConditions: intl.formatMessage(messages.noConditions),\n operatorAll: intl.formatMessage(messages.operatorAll),\n operatorAnd: intl.formatMessage(messages.operatorAnd),\n operatorAny: intl.formatMessage(messages.operatorAny),\n operatorOr: intl.formatMessage(messages.operatorOr),\n }\n\n this.options = {\n date: {\n label: intl.formatMessage(messages.dateLabel),\n unique: true,\n verbs: [\n {\n label: intl.formatMessage(messages.dateEquals),\n object: {\n extraParams: {},\n renderFn: this.complexDatePickerObject,\n },\n value: 'is',\n },\n {\n label: intl.formatMessage(messages.dateRange),\n object: {\n extraParams: {},\n renderFn: this.complexDatePickerRangeObject,\n },\n value: 'between',\n },\n {\n label: intl.formatMessage(messages.dateTo),\n object: {\n extraParams: {},\n renderFn: this.complexDatePickerObject,\n },\n value: 'to',\n },\n {\n label: intl.formatMessage(messages.dateFrom),\n object: {\n extraParams: {},\n renderFn: this.complexDatePickerObject,\n },\n value: 'from',\n },\n ],\n },\n }\n }\n\n public render() {\n return (\n <>\n <Conditions\n labels={this.labels}\n options={this.options}\n subjectPlaceholder={this.props.intl.formatMessage(\n messages.subjectPlaceholder\n )}\n noOptionsMessage={this.props.intl.formatMessage(\n messages.emptyConditionsOptions\n )}\n statements={this.props.condition.statements}\n operator={this.props.operator}\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n this.props.onChangeStatements(\n statements.map(statement => ({\n ...statement,\n objectJSON: JSON.stringify(statement.object || null),\n }))\n )\n }}\n />\n <span className=\"c-danger t-small mt3 lh-title\">\n {this.props.errorMessage}\n </span>\n </>\n )\n }\n\n private handleToggleOperator: ConditionsProps['onChangeOperator'] = operatorObj => {\n if (typeof this.props.onChangeOperator === 'function') {\n this.props.onChangeOperator(operatorObj)\n }\n }\n\n private complexDatePickerObject: ConditionsRenderFn = ({\n statements,\n values,\n statementIndex,\n }) => {\n const {\n culture: { locale },\n } = this.props.runtime\n return (\n <DatePicker\n value={values && values.date}\n onChange={(date: Date) => {\n const newStatements = statements.map((statement, index) => {\n const dateAtMidnight = new Date(date)\n dateAtMidnight.setHours(0, 0, 0, 0)\n\n return {\n ...statement,\n object:\n index === statementIndex\n ? { date: dateAtMidnight }\n : statement.object,\n }\n })\n this.props.onChangeStatements(newStatements)\n }}\n locale={locale}\n />\n )\n }\n\n private complexDatePickerRangeObject: ConditionsRenderFn = ({\n statements,\n values,\n statementIndex,\n }) => {\n const {\n culture: { locale },\n } = this.props.runtime\n return (\n <div className=\"flex\">\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n value={values && values.from}\n onChange={(date: Date) => {\n const newStatements = statements.map((statement, index) => {\n return {\n ...statement,\n object: {\n ...statement.object,\n ...(index === statementIndex ? { from: date } : null),\n },\n }\n })\n this.props.onChangeStatements(newStatements)\n }}\n locale={locale}\n />\n </div>\n\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.templates.simple.conditions.date.range.and\"\n defaultMessage=\"and\"\n >\n {message => <div className=\"mv4 mh3 c-muted-2 b\">{message}</div>}\n </FormattedMessage>\n\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n value={values && values.to}\n onChange={(date: Date) => {\n const newStatements = statements.map((statement, index) => {\n return {\n ...statement,\n object: {\n ...statement.object,\n ...(index === statementIndex ? { to: date } : null),\n },\n }\n })\n this.props.onChangeStatements(newStatements)\n }}\n locale={locale}\n />\n </div>\n </div>\n )\n }\n}\n\nexport default withRuntimeContext(injectIntl(SelectConditions))\n\n```" } ]
code_admin-pages_ebc3ab99
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/utils.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { DataProxy } from 'apollo-cache'\nimport { RouteFormData } from 'pages'\nimport { pathOr } from 'ramda'\n\nimport Routes from '../../../../queries/Routes.graphql'\nimport Route from '../../../../queries/Route.graphql'\nimport { DateVerbOptions } from '../../../../utils/conditions/typings'\nimport {\n DateInfoFormat,\n DateStatementFormat,\n DeleteMutationResult,\n QueryData,\n RoutesQuery,\n SaveMutationResult,\n} from './typings'\nimport { DATA_SOURCE } from '../consts'\n\nconst routesCacheAccessParameters = (bindingId?: string) => ({\n query: Routes,\n variables: {\n domain: 'store',\n bindingId,\n },\n})\n\nconst routeCacheAccessParameters = (routeId: string, bindingId?: string) => ({\n query: Route,\n variables: {\n domain: 'store',\n routeId,\n bindingId,\n },\n})\n\nconst logCacheError = () => {\n console.warn('No cache found for \"Routes\".')\n}\n\nconst readRoutesFromStore = (store: DataProxy, binding?: string): QueryData =>\n store.readQuery(routesCacheAccessParameters(binding))\n\nconst writeRoutesToStore = (\n newData: RoutesQuery,\n store: DataProxy,\n bindingId?: string,\n updatedRoute?: Route\n) => {\n store.writeQuery({\n data: newData,\n ...routesCacheAccessParameters(bindingId),\n })\n if (updatedRoute) {\n store.writeQuery({\n data: { route: updatedRoute },\n ...routeCacheAccessParameters(updatedRoute.routeId, bindingId),\n })\n }\n}\n\nexport const updateStoreAfterDelete = (binding?: string) => (\n store: DataProxy,\n result: DeleteMutationResult\n) => {\n const deletedPageId = result.data && result.data.deleteRoute\n\n try {\n const queryData = readRoutesFromStore(store, binding)\n\n if (queryData) {\n const routes = queryData.routes\n\n const newRoutes = routes.filter(({ uuid }) => uuid !== deletedPageId)\n\n const newData = {\n ...queryData,\n routes: newRoutes || routes,\n }\n\n writeRoutesToStore(newData, store, binding)\n }\n } catch (err) {\n logCacheError()\n }\n}\n\nexport const updateStoreAfterSave = (\n store: DataProxy,\n result: SaveMutationResult\n) => {\n const savedRoute = result.data && result.data.saveRoute\n\n try {\n const binding = savedRoute?.binding\n const queryData = readRoutesFromStore(store, binding)\n\n if (queryData && savedRoute) {\n const routes = queryData.routes\n\n const savedRouteId = savedRoute && savedRoute.uuid\n const matchedRoute = routes.find(route => route.uuid === savedRouteId)\n if (matchedRoute) {\n const idx = routes.indexOf(matchedRoute)\n routes[idx] = savedRoute\n } else {\n routes.push(savedRoute)\n }\n\n const newData = {\n ...queryData,\n routes,\n }\n\n writeRoutesToStore(newData, store, binding, savedRoute)\n }\n } catch (err) {\n logCacheError()\n }\n}\n\nconst getConditionStatementObject = (\n objectJson: string,\n verb: DateVerbOptions\n): Partial<DateStatementFormat> => {\n const dateInfoStringValues: DateInfoFormat = JSON.parse(objectJson)\n\n return {\n between: {\n from: new Date(dateInfoStringValues.from),\n to: new Date(dateInfoStringValues.to),\n },\n from: {\n date: new Date(dateInfoStringValues.from),\n },\n is: {\n date: new Date(dateInfoStringValues.from),\n },\n to: {\n date: new Date(dateInfoStringValues.to),\n },\n }[verb]\n}\n\nexport const formatToFormData = (route: Route): RouteFormData => {\n return {\n ...route,\n metaTagDescription: pathOr('', ['metaTags', 'description'], route),\n metaTagKeywords: pathOr<string[], string[]>(\n [],\n ['metaTags', 'keywords'],\n route\n ).map(keyword => ({ label: keyword, value: keyword })),\n metaTagRobots: pathOr('', ['metaTags', 'robots'], route),\n pages: route.pages.map((page, index) => ({\n ...page,\n condition: {\n ...page.condition,\n statements: page.condition.statements.map(\n ({ verb, subject, objectJSON }) => ({\n error: '',\n object: getConditionStatementObject(\n objectJSON,\n verb as DateVerbOptions\n ),\n subject,\n verb,\n })\n ),\n },\n operator: page.condition.allMatches ? 'all' : 'any',\n uniqueId: index,\n })),\n dataSource: DATA_SOURCE,\n }\n}\n\nexport const generateNewRouteId = (interfaceId: string, path: string) => {\n return `${interfaceId}#${path.replace(\n /\\//gi,\n (_, offset: number, fullString: string) => {\n return offset === 0 || offset === fullString.length - 1 ? '' : '-'\n }\n )}`\n}\n\n```" } ]
code_admin-pages_81ec1784
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/typings.d.ts from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ConditionsProps } from 'vtex.styleguide'\n\nexport interface DeleteMutationResult {\n data?: {\n deleteRoute: string\n }\n}\n\nexport interface SaveMutationResult {\n data?: {\n saveRoute: Route\n }\n}\n\nexport interface TemplateMutationResult {\n data?: {\n availableTemplates: Template[]\n }\n}\n\nexport type QueryData = RoutesQuery | null\n\nexport interface RoutesQuery {\n routes: Route[]\n}\n\nexport interface ClientSideUniqueId {\n uniqueId: number\n operator: ConditionsProps['operator']\n}\n\ninterface StatementsOnSaveRoute {\n subject: string\n verb: string\n objectJSON: string\n}\n\ninterface ConditionsOnSaveRouteVariables {\n id?: string\n allMatches: boolean\n statements: StatementsOnSaveRoute[]\n}\n\nexport interface SaveRouteVariables {\n route: Partial<Route> &\n Pick<Route, 'declarer' | 'domain' | 'path' | 'routeId' | 'binding'>\n}\n\nexport interface DeleteRouteVariables {\n uuid: string\n}\n\nexport interface DateInfoFormat {\n date: string\n to: string\n from: string\n}\n\nexport type DateStatementFormat = Record<keyof DateInfoFormat, Date>\n\nexport type FormErrors = Omit<Partial<Route>, 'pages'> & {\n pages?: {\n [key: string]: {\n template?: string\n condition?: string\n }\n }\n}\n\n```" } ]
code_admin-pages_06f893a2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/Operations.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Mutation, MutationFn, Query, QueryResult } from 'react-apollo'\n\nimport AvailableTemplates from '../../../../queries/AvailableTemplates.graphql'\nimport DeleteRoute from '../../../../queries/DeleteRoute.graphql'\nimport SaveRoute from '../../../../queries/SaveRoute.graphql'\nimport {\n DeleteMutationResult,\n DeleteRouteVariables,\n SaveMutationResult,\n SaveRouteVariables,\n TemplateMutationResult,\n} from './typings'\nimport { updateStoreAfterDelete, updateStoreAfterSave } from './utils'\n\ninterface TemplateVariables {\n interfaceId: string\n}\n\ninterface Props {\n interfaceId: string\n binding?: string\n children: (mutations: OperationsResults) => React.ReactNode\n}\n\nexport interface OperationsResults {\n deleteRoute: MutationFn<DeleteMutationResult['data'], DeleteRouteVariables>\n saveRoute: MutationFn<SaveMutationResult['data'], SaveRouteVariables>\n templatesResults: QueryResult<\n TemplateMutationResult['data'],\n TemplateVariables\n >\n}\n\nconst Operations = ({ interfaceId, children, binding }: Props) => (\n <Query<TemplateMutationResult['data'], TemplateVariables>\n query={AvailableTemplates}\n variables={{ interfaceId }}\n >\n {templatesResults => (\n <Mutation<DeleteMutationResult['data'], DeleteRouteVariables>\n mutation={DeleteRoute}\n update={updateStoreAfterDelete(binding)}\n >\n {deleteRoute => (\n <Mutation<SaveMutationResult['data'], SaveRouteVariables>\n mutation={SaveRoute}\n update={updateStoreAfterSave}\n >\n {saveRoute =>\n children({\n deleteRoute,\n saveRoute,\n templatesResults,\n })\n }\n </Mutation>\n )}\n </Mutation>\n )}\n </Query>\n)\n\nexport default Operations\n\n```" } ]
code_admin-pages_72e9854c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of admin-pages/react/components/admin/pages/Form/ConditionalTemplateSection.tsx from the admin-pages VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport {\n defineMessages,\n FormattedMessage,\n WrappedComponentProps as ComponentWithIntlProps,\n} from 'react-intl'\nimport { Dropdown } from 'vtex.styleguide'\nimport { PagesFormData, RouteFormData } from 'pages'\n\nimport {\n ConditionalTemplatePicker,\n ConditionalTemplatePickerProps,\n} from './ConditionalTemplatePicker'\nimport SectionTitle from './SectionTitle'\nimport { FormErrors } from './typings'\n\ntype TemplatePickerCallbacks = Pick<\n ConditionalTemplatePickerProps,\n | 'onChangeOperatorConditionalTemplate'\n | 'onChangeStatementsConditionalTemplate'\n | 'onChangeTemplateConditionalTemplate'\n | 'onRemoveConditionalTemplate'\n>\n\nexport interface ConditionalTemplateSectionProps\n extends TemplatePickerCallbacks {\n detailChangeHandlerGetter: (\n detailName: keyof RouteFormData\n ) => (\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n ) => void\n formErrors: FormErrors\n onAddConditionalTemplate: () => void\n pages: PagesFormData[]\n blockId: string\n templates: Template[]\n}\n\ntype Props = ConditionalTemplateSectionProps & ComponentWithIntlProps\n\nconst messages = defineMessages({\n defaultFieldLabel: {\n defaultMessage: 'Default',\n id: 'admin/pages.admin.pages.form.templates.field.default',\n },\n templateTitle: {\n defaultMessage: 'Templates',\n id: 'admin/pages.admin.pages.form.templates.title',\n },\n})\n\nexport const ConditionalTemplateSection: React.FunctionComponent<Props> = ({\n detailChangeHandlerGetter,\n formErrors,\n intl,\n onAddConditionalTemplate,\n onChangeOperatorConditionalTemplate,\n onChangeStatementsConditionalTemplate,\n onChangeTemplateConditionalTemplate,\n onRemoveConditionalTemplate,\n pages,\n blockId,\n templates,\n}) => (\n <React.Fragment>\n <SectionTitle textId=\"admin/pages.admin.pages.form.templates.title\" />\n <Dropdown\n label={intl.formatMessage(messages.defaultFieldLabel)}\n options={templates.map(({ id }) => ({ value: id, label: id }))}\n onChange={detailChangeHandlerGetter('blockId')}\n value={blockId}\n errorMessage={\n formErrors.blockId && intl.formatMessage({ id: formErrors.blockId })\n }\n />\n <h2 className=\"mt7 f5 normal\">\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.templates.conditional.title\"\n defaultMessage=\"Conditional\"\n />\n </h2>\n <p className=\"f6 c-muted-2\">\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.templates.conditional.description\"\n defaultMessage=\"Conditional template enables the use of a variant layout to your page. This layout will appear when it matches with the conditions set.\"\n />\n </p>\n {pages.map(page => (\n <ConditionalTemplatePicker\n key={page.uniqueId}\n condition={page.condition}\n intl={intl}\n onChangeTemplateConditionalTemplate={\n onChangeTemplateConditionalTemplate\n }\n onChangeOperatorConditionalTemplate={\n onChangeOperatorConditionalTemplate\n }\n onChangeStatementsConditionalTemplate={\n onChangeStatementsConditionalTemplate\n }\n operator={page.operator}\n onRemoveConditionalTemplate={onRemoveConditionalTemplate}\n pageId={page.uniqueId}\n template={page.template}\n templates={templates}\n formErrors={formErrors}\n />\n ))}\n <button\n type=\"button\"\n className=\"bg-transparent bn mt4 pl0 pointer\"\n onClick={onAddConditionalTemplate}\n >\n <span className=\"c-action-primary f4 mr2 v-mid\">+</span>\n <span className=\"f6 v-mid\">\n <FormattedMessage\n id=\"admin/pages.admin.pages.form.templates.conditional.addButton\"\n defaultMessage=\"Add conditional template\"\n />\n </span>\n </button>\n </React.Fragment>\n)\n\nexport default ConditionalTemplateSection\n\n```" } ]