id
stringlengths
12
53
messages
listlengths
3
3
code_store-on-localhost_d0aebe58
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ButtonPlain/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A low-prominence button for progressive disclosure of secondary flows.\n\n### ๐Ÿ‘ Dos\n\n- Use it for progressive disclosure purposes, such as displaying elements related to secondary actions (e.g edit buttons).\n- Use it when it's semantically a button, but the prominence is akin to a link.\n- Use it for placing low-key icons that behave as a button. Strongly consider the use of labels, though.\n- Use it for buttons with relatively long labels that canโ€™t be abbreviated.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Donโ€™t use it with other in-line elements very close to it.\n- Donโ€™t position it in-line with other types of buttons.\n- Donโ€™t use it when the use case calls for the prominence of a primary or secondary button.\n\n### Related components\n\n- [Button](#/Components/Forms/Button)\n- [ButtonGroup](#/Components/Forms/ButtonGroup)\n- [ButtonWithIcon](#/Components/Forms/ButtonWithIcon)\n\n#### Variations\n\n```js\n<div>\n <div className=\"flex w-50 center justify-between pa4\">\n <ButtonPlain>Plain</ButtonPlain>\n <ButtonPlain disabled>Plain disabled</ButtonPlain>\n </div>\n <div className=\"flex w-50 center justify-between pa4\">\n <ButtonPlain variation=\"danger\">Danger</ButtonPlain>\n <ButtonPlain variation=\"danger\" disabled>Danger disabled</ButtonPlain>\n </div>\n <div className=\"flex w-50 center justify-between bg-base--inverted pa4 mt4\">\n <ButtonPlain variation=\"inverted\">Inverted</ButtonPlain>\n <ButtonPlain variation=\"inverted\" disabled>Inverted disabled</ButtonPlain>\n </div>\n</div>\n```\n\n#### Sizes\n\n```js\n<div>\n <div className=\"flex w-50 center justify-between pa4\">\n <ButtonPlain size=\"small\">Small plain</ButtonPlain>\n <ButtonPlain variation=\"danger\" size=\"small\">Small danger</ButtonPlain>\n </div>\n <div className=\"flex w-50 center justify-between pa4\">\n <ButtonPlain>Regular plain</ButtonPlain>\n <ButtonPlain variation=\"danger\">Regular danger</ButtonPlain>\n </div>\n <div className=\"flex w-50 center justify-between pa4\">\n <ButtonPlain size=\"large\">Large plain</ButtonPlain>\n <ButtonPlain variation=\"danger\" size=\"large\">Large danger</ButtonPlain>\n </div>\n</div>\n```\n\n#### Link mode\n\n```js\n<ButtonPlain variation=\"primary\" href=\"http://vtex.com\" target=\"_blank\">Sign in</ButtonPlain>\n```\n\n#### Loading state\n\n```js\ninitialState = { isLoading: false };\n\n<ButtonPlain\n variation=\"primary\"\n onClick={\n () => {\n setState({ isLoading: true })\n setTimeout(() => { setState({ isLoading: false }) }, 2000)\n }\n }\n isLoading={state.isLoading}\n>\n Start loading\n</ButtonPlain>\n```\n\n#### Use case examples\n\n### Example 1: Click to show the content\n\n```js\ninitialState = { showShippingOptions: false, showCoupon: false };\n\n<div className=\"c-on-base\">\n <div className=\"pb4\">\n <h3 className=\"t-heading-4\">Shipping</h3>\n {\n !state.showShippingOptions\n ? (\n <div>\n <ButtonPlain onClick={() => setState({ showShippingOptions: true }) }>\n View shipping options\n </ButtonPlain>\n </div>\n ) :\n (\n <div className=\"lh-copy\">\n List of options here!\n </div>\n )\n }\n </div>\n <div>\n <h3 className=\"t-heading-4\">Coupon</h3>\n {\n !state.showCoupon\n ? (\n <div>\n <ButtonPlain onClick={() => setState({ showCoupon: true }) }>\n Add a discount coupon\n </ButtonPlain>\n </div>\n ) :\n (\n <div className=\"lh-copy\">\n Coupon code form here!\n </div>\n )\n }\n </div>\n</div>\n```\n\n### Example 2: Edit info\n\n```js\n<div className=\"c-on-base w-40\">\n <div className=\"flex justify-between\">\n <div className=\"lh-copy mr4\">\n <div className=\"mb3 fw5\">\n Shipping options for\n </div>\n <div>\n 1585 Broadway, New York, NY\n </div>\n <div>\n 10036, United States\n </div>\n </div>\n <div><ButtonPlain>Edit</ButtonPlain></div>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_44a55337
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Progress/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React from 'react'\n\nimport { ProgressSteps, ProgressStepsTypes } from './Steps'\nimport { ProgressLine, ProgressLineTypes } from './Line'\n\nconst propTypes = {\n type: PropTypes.oneOf(['line', 'steps']),\n ...ProgressLineTypes,\n ...ProgressStepsTypes,\n}\n\nconst Progress: React.FC<PropTypes.InferProps<typeof propTypes>> = props => {\n if (props.type === 'line') {\n return <ProgressLine percent={props.percent} />\n }\n\n return (\n <ProgressSteps\n steps={props.steps}\n danger={props.danger}\n slim={props.slim}\n />\n )\n}\n\nProgress.propTypes = propTypes\n\nProgress.defaultProps = {\n type: 'steps',\n}\n\nexport default Progress\n\n```" } ]
code_store-on-localhost_5bf3827e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Progress/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n## Steps\n\n### ๐Ÿ‘ Dos\n\n- The steps should be used in this order: \"Completed\", \"In Progress\" and \"To Do\". You are free to choose the quantity of steps.\n- Steps should be grouped together by their type.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't put more than one \"in progress\" step.\n- Don't put steps of a different type in between steps of the same type (e.g. [\"Completed\", \"In Progress\", \"Completed\"]). Remember that the component represents a linear progression.\n\n#### Simple ProgressBar example\n\nSecond Action in Progress\n\n```jsx\n<Progress type=\"steps\" steps={['completed', 'inProgress', 'toDo']} />\n```\n\n#### ProgressBar with all steps to do\n\nFirst Action Ready to Begin\n\n```jsx\n<Progress type=\"steps\" steps={['toDo', 'toDo', 'toDo', 'toDo']} />\n```\n\n#### Completed ProgressBar example\n\nAll completed\n\n```jsx\n<Progress type=\"steps\" steps={['completed', 'completed']} />\n```\n\n#### Slim ProgressBar example\n\nSecond Action in Progress\n\n```jsx\n<Progress type=\"steps\" slim steps={['completed', 'inProgress', 'toDo']} />\n```\n\n#### ProgressBar with a single step in progress example\n\nIn Progress\n\n```jsx\n<Progress type=\"steps\" steps={['inProgress']} />\n```\n\nSimple danger ProgressBar example\n\n```jsx\n<div>\n <Progress type=\"steps\" danger steps={['completed', 'inProgress', 'toDo']} />\n <span className=\"vtex-input__label mb3 w-100\">\n {' '}\n Late Second Action in Progress\n </span>\n</div>\n```\n\n## Line\n\n```jsx\nconst Button = require('../Button').default\nconst ProgressComponent = () => {\n const [value, setValue] = React.useState(10)\n const increment = () => {\n if (value < 100) {\n setValue(value + 10)\n }\n }\n const decrement = () => {\n if (value > 0) {\n setValue(value - 10)\n }\n }\n return (\n <div>\n <Progress type=\"line\" percent={value} />\n <div className=\"flex mt6\">\n <Button onClick={increment} size=\"small\">\n Increment\n </Button>\n <div className=\"ml3\">\n <Button onClick={decrement} size=\"small\">\n Decrement\n </Button>\n </div>\n </div>\n </div>\n )\n}\n\n;<ProgressComponent />\n```\n\n### Line Completed\n\n```jsx\n<Progress percent={100} type=\"line\" />\n```\n\n```" } ]
code_store-on-localhost_8a8c99d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Progress/Line.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport cn from 'classnames'\nimport PropTypes from 'prop-types'\nimport React from 'react'\n\nimport styles from './styles.css'\n\nexport const ProgressLineTypes = {\n percent: PropTypes.number.isRequired,\n}\n\nexport const ProgressLine: React.FC<PropTypes.InferProps<\n typeof ProgressLineTypes\n>> = props => {\n const barClasses = cn(\n styles.progressHeight,\n 'w-100 br4 overflow-hidden bg-light-silver'\n )\n const stepClasses = cn(styles.progressHeight, 'br4', {\n 'bg-action-primary': props.percent !== 100,\n 'bg-success': props.percent === 100,\n })\n return (\n <div className={barClasses}>\n <div className={stepClasses} style={{ width: `${props.percent}%` }} />\n </div>\n )\n}\n\nProgressLine.propTypes = ProgressLineTypes\n\n```" } ]
code_store-on-localhost_7b2e3e60
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/CheckboxGroup/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport some from 'lodash/some'\nimport every from 'lodash/every'\n\nimport Checkbox from '../Checkbox'\n\nclass CheckboxGroup extends Component {\n constructor(props) {\n super(props)\n this.state = { groupChecked: false }\n }\n\n isPartiallyChecked = () => {\n const { checkedMap } = this.props\n const checkedValues = Object.values(checkedMap).map(value => value.checked)\n return some(checkedValues) && !every(checkedValues)\n }\n\n isFullyChecked = () => {\n const { checkedMap } = this.props\n const checkedValues = Object.values(checkedMap).map(value => value.checked)\n return every(checkedValues)\n }\n\n handleOnChange = key => {\n const { checkedMap } = this.props\n const newCheckedMap = {\n ...checkedMap,\n [key]: { ...checkedMap[key], checked: !checkedMap[key].checked },\n }\n this.props.onGroupChange(newCheckedMap)\n }\n\n setGroupChecked = value => {\n const { checkedMap } = this.props\n const newCheckedMap = { ...checkedMap }\n Object.keys(checkedMap).forEach(key => {\n newCheckedMap[key].checked = value\n })\n return newCheckedMap\n }\n\n handleOnGroupChange = () => {\n if (this.isPartiallyChecked() || this.isFullyChecked()) {\n this.props.onGroupChange(this.setGroupChecked(false))\n } else {\n this.props.onGroupChange(this.setGroupChecked(true))\n }\n }\n\n render() {\n const { checkedMap, disabled, name, id, value, label, padded } = this.props\n return (\n <div>\n <Checkbox\n checked={this.isFullyChecked()}\n partial={this.isPartiallyChecked()}\n id={id}\n name={name}\n onChange={this.handleOnGroupChange}\n value={value}\n disabled={disabled}\n label={label}\n />\n <div className={`${padded ? 'ml7' : ''} mv5`}>\n {Object.keys(checkedMap).map(key => (\n <div key={key} className=\"mv6\">\n <Checkbox\n checked={checkedMap[key].checked}\n id={`${id}-${key}`}\n name={name}\n onChange={() => this.handleOnChange(key)}\n value={`${value}-${key}`}\n disabled={disabled}\n label={checkedMap[key].label}\n />\n </div>\n ))}\n </div>\n </div>\n )\n }\n}\n\nCheckboxGroup.defaultProps = {\n disabled: false,\n padded: true,\n}\n\nCheckboxGroup.propTypes = {\n /** Map of objects containing the label and the checked value of each checkbox of this group */\n checkedMap: PropTypes.objectOf(\n PropTypes.shape({\n label: PropTypes.string,\n checked: PropTypes.bool.isRequired,\n })\n ),\n /** (Input spec attribute) */\n disabled: PropTypes.bool,\n /** (Input spec attribute) */\n id: PropTypes.string.isRequired,\n /** Checkbox Group label (i.e. main checkbox label)*/\n label: PropTypes.string,\n /** (Input spec attribute) */\n name: PropTypes.string.isRequired,\n /** onChange event for the checkedMap object */\n onGroupChange: PropTypes.func.isRequired,\n /** (Input spec attribute) */\n value: PropTypes.string.isRequired,\n /** Setting for the padding, set it for false if want the inner checkboxes with no padding in relation to the main checkbox */\n padded: PropTypes.bool,\n}\n\nexport default CheckboxGroup\n\n```" } ]
code_store-on-localhost_137ec5d2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/CheckboxGroup/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A CheckboxGroup represents a group of related binary choices in the format of checkboxes.\n\n### ๐Ÿ‘ Dos\n\n- Initialize it with a default value that makes sense to your needs.\n- Use a text label for the checkbox groups, which should clearly inform that this checkbox checks or uncheks all the other checkboxes.\n- Use a text label for each of the inner checkboxes, which should be intuitive and provide sufficient context for the user take that decision.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't use negative labels because they are harder to interpret.\n- Don't implement an \"autosave\" behavior: checkboxes should always require the use of a button (like \"SAVE\" or \"OK\") to commit the choice.\n\n### Related components\n\n- If the inner checkboxes have no relation between them consider using single <a href=\"#/Components/Forms/Checkbox\">Checkboxes</a>.\n\nSimple Group\n\n```js\ninitialState = { checkedMap: {\n check1: {label: \"Filter 1\", checked: true}, \n check2: {label: \"Filter 2\", checked: false}, \n check3: {label: \"Filter 3\", checked: false}\n }\n}\n;<div>\n <CheckboxGroup\n name=\"simpleCheckboxGroup\"\n label=\"All Filters\"\n id=\"simple\"\n value=\"simple\"\n checkedMap={state.checkedMap}\n onGroupChange={newCheckedMap => {\n setState({ checkedMap: newCheckedMap })\n }}\n />\n</div>\n```\n\nDisabled Group\n\n```js\ninitialState = { checkedMap: {\n check1: {label: \"Filter 1\", checked: true}, \n check2: {label: \"Filter 2\", checked: false}, \n check3: {label: \"Filter 3\", checked: false}\n }\n}\n;<div>\n <CheckboxGroup\n name=\"disabledCheckboxGroup\"\n disabled\n label=\"All Filters\"\n id=\"disabled\"\n value=\"disabled\"\n checkedMap={state.checkedMap}\n onGroupChange={newCheckedMap => {\n setState({ checkedMap: newCheckedMap })\n }}\n />\n</div>\n\n```\n\nWithout Padding\n\n```js\ninitialState = { checkedMap: {\n check1: {label: \"Filter 1\", checked: true}, \n check2: {label: \"Filter 2\", checked: false}, \n check3: {label: \"Filter 3\", checked: false}\n }\n}\n;<div>\n <CheckboxGroup\n padded={false}\n name=\"withoutPaddingCheckboxGroup\"\n label=\"All Filters\"\n id=\"withoutPadding\"\n value=\"withoutPadding\"\n checkedMap={state.checkedMap}\n onGroupChange={newCheckedMap => {\n setState({ checkedMap: newCheckedMap })\n }}\n />\n</div>\n```\n\n```" } ]
code_store-on-localhost_7c397b8b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Input/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Button from '../Button'\nimport styles from './Input.css'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass Input extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n active: false,\n }\n }\n\n handleChange = event => {\n this.props.onChange && this.props.onChange(event)\n }\n\n handleKeyPress = event => {\n this.props.onKeyPress && this.props.onKeyPress(event)\n }\n\n handleKeyDown = event => {\n this.props.onKeyDown && this.props.onKeyDown(event)\n }\n\n handleKeyUp = event => {\n this.props.onKeyUp && this.props.onKeyUp(event)\n }\n\n handleFocus = event => {\n if (!this.props.readOnly) {\n this.setState({ active: true })\n this.props.onFocus && this.props.onFocus(event)\n }\n }\n\n handleBlur = event => {\n if (!this.props.readOnly) {\n this.setState({ active: false })\n this.props.onBlur && this.props.onBlur(event)\n }\n }\n\n handleMouseEnter = event => {\n this.props.onMouseEnter && this.props.onMouseEnter(event)\n }\n\n handleMouseLeave = event => {\n this.props.onMouseLeave && this.props.onMouseLeave(event)\n }\n\n componentDidMount() {\n if (this.props.size === 'x-large') {\n console.warn(\n 'Input: The value \"x-large\" for the prop \"size\" is deprecated. In the next major version, it will be equivalent to \"large\", and removed altogether in future versions'\n )\n }\n\n if (this.props.suffixIcon) {\n console.warn(\n 'The prop suffixIcon is deprecated and will be removed in the next major. Please use the prop suffix instead.'\n )\n }\n\n if (this.props.prefix && this.props.suffix) {\n console.warn(\n 'You should not use both prefix and suffix props in the same input. '\n )\n }\n }\n\n render() {\n const {\n errorMessage,\n error,\n label,\n size,\n token,\n helpText,\n dataAttributes,\n prefix,\n suffix: suffixProp,\n suffixIcon,\n button,\n isLoadingButton,\n groupBottom,\n disabled,\n readOnly,\n testId,\n } = this.props\n const { active } = this.state\n\n const suffix = suffixProp || suffixIcon\n\n const dataAttrs = {}\n for (const key of Object.keys(dataAttributes)) {\n dataAttrs[`data-${key}`] = dataAttributes[key]\n }\n\n const widthClass = 'w-100'\n const box = 'ma0 border-box'\n const borderRadiusBase = 'br2'\n const borderBase = `bw1 b--solid`\n\n const borderRadius = `${borderRadiusBase} ${\n prefix ? 'bl-0 br--right ' : ''\n } ${suffix ? 'br-0 br--left ' : ''}`\n let prefixClasses = `${borderRadiusBase} br-0 br--left `\n let suffixClasses = `${borderRadiusBase} bl-0 br--right `\n\n let classes = `${widthClass} ${box} ${styles.hideDecorators} ${styles.noAppearance} ${borderRadius} bn outline-0 `\n let labelClasses = 'vtex-input__label db mb3 w-100 c-on-base '\n let prefixAndSuffixClasses =\n 'vtex-input__prefix c-muted-2 fw5 flex items-center c-muted-2 t-body '\n let prefixSuffixGroupClasses =\n 'vtex-input-prefix__group flex flex-row items-stretch '\n prefixSuffixGroupClasses += `${borderRadiusBase} ${borderBase} ${\n groupBottom ? 'br--top ' : ''\n }`\n\n if (token) {\n classes += 'code '\n }\n\n if (disabled || readOnly || isLoadingButton) {\n classes += `bg-transparent b--disabled ${\n disabled || isLoadingButton ? 'c-disabled' : ''\n } `\n prefixSuffixGroupClasses += `bg-disabled b--disabled ${\n disabled ? 'c-disabled' : ''\n } `\n } else {\n classes += 'bg-base c-on-base '\n prefixAndSuffixClasses += 'bg-base '\n\n if (error || errorMessage) {\n classes += 'b--danger hover-b--danger '\n prefixSuffixGroupClasses += 'b--danger hover-b--danger '\n } else if (active) {\n classes += 'b--muted-2 '\n prefixSuffixGroupClasses += 'b--muted-2 '\n } else {\n classes += 'b--muted-4 '\n prefixSuffixGroupClasses += 'b--muted-4 '\n if (!readOnly) {\n classes += 'hover-b--muted-3 '\n prefixSuffixGroupClasses += 'hover-b--muted-3 '\n }\n }\n }\n\n switch (size) {\n case 'small':\n prefixSuffixGroupClasses += 'h-small '\n classes += `${!token ? 't-small' : ''} `\n classes += `${\n prefix && suffix ? '' : prefix ? 'pr5 ' : suffix ? 'pl5 ' : 'ph5 '\n }`\n labelClasses += 't-small '\n prefixClasses += 'pl5 pr3 '\n suffixClasses += 'pr5 pl3 '\n break\n case 'large':\n prefixSuffixGroupClasses += 'h-large '\n classes += `${!token ? 't-body' : ''} `\n classes += `${\n prefix && suffix ? '' : prefix ? 'pr5 ' : suffix ? 'pl5 ' : 'ph5 '\n }`\n labelClasses += 't-body '\n prefixClasses += 'pl5 pr4 '\n suffixClasses += 'pr5 pl4 '\n break\n case 'x-large':\n // DEPRECATED\n classes += `${!token ? 't-body' : ''} pv5 `\n classes += `${\n prefix && suffix ? '' : prefix ? 'pr7 ' : suffix ? 'pl7 ' : 'ph7 '\n }`\n labelClasses += 't-body '\n prefixClasses += 'pl5 pr3 '\n suffixClasses += 'pr5 pl3 '\n break\n default:\n prefixSuffixGroupClasses += 'h-regular '\n classes += `${!token ? 't-body' : ''} `\n classes += `${\n prefix && suffix ? '' : prefix ? 'pr5 ' : suffix ? 'pl5 ' : 'ph5 '\n }`\n labelClasses += 't-small '\n prefixClasses += 'pl5 pr3 '\n suffixClasses += 'pr5 pl3 '\n break\n }\n\n return (\n <label className=\"vtex-input w-100\" data-testid={testId}>\n {label && <span className={labelClasses}>{label}</span>}\n <div className={prefixSuffixGroupClasses}>\n {prefix && (\n <span className={`${prefixAndSuffixClasses} ${prefixClasses}`}>\n {prefix}\n </span>\n )}\n <input\n {...dataAttrs}\n ref={this.props.forwardedRef}\n onBlur={this.handleBlur}\n onFocus={this.handleFocus}\n onChange={this.handleChange}\n onKeyPress={this.handleKeyPress}\n onKeyDown={this.handleKeyDown}\n onKeyUp={this.handleKeyUp}\n onMouseEnter={this.handleMouseEnter}\n onMouseLeave={this.handleMouseLeave}\n className={classes}\n disabled={disabled || isLoadingButton}\n accept={this.props.accept}\n autoComplete={this.props.autoComplete}\n autoCorrect={this.props.autoCorrect}\n autoFocus={this.props.autoFocus}\n autoSave={this.props.autoSave}\n defaultValue={this.props.defaultValue}\n inputMode={this.props.inputMode}\n list={this.props.list}\n max={this.props.max}\n maxLength={this.props.maxLength}\n min={this.props.min}\n minLength={this.props.minLength}\n multiple={this.props.multiple}\n name={this.props.name}\n pattern={this.props.pattern}\n placeholder={this.props.placeholder}\n readOnly={readOnly}\n required={this.props.required}\n spellCheck={this.props.spellCheck}\n src={this.props.src}\n step={this.props.step}\n tabIndex={this.props.tabIndex}\n type={this.props.type}\n value={this.props.value}\n id={this.props.id}\n />\n {suffix && (\n <span className={`${prefixAndSuffixClasses} ${suffixClasses}`}>\n {suffix}\n </span>\n )}\n {button && size !== 'small' && (\n <span className=\"flex items-center mr1\">\n <Button\n disabled={disabled || isLoadingButton}\n isLoading={isLoadingButton}\n size={size === 'large' ? 'regular' : 'small'}\n type=\"submit\"\n variation=\"secondary\">\n {button}\n </Button>\n </span>\n )}\n </div>\n {errorMessage && (\n <div className=\"c-danger t-small mt3 lh-title\">{errorMessage}</div>\n )}\n {helpText && (\n <div className=\"c-muted-1 t-small mt3 lh-title\">{helpText}</div>\n )}\n </label>\n )\n }\n}\n\nInput.defaultProps = {\n autoFocus: false,\n token: false,\n dataAttributes: {},\n disabled: false,\n label: '',\n multiple: false,\n readOnly: false,\n error: false,\n size: 'regular',\n prefix: '',\n type: 'text',\n isLoadingButton: false,\n}\n\nInput.propTypes = {\n /** Error highlight */\n error: PropTypes.bool,\n /** Error message */\n errorMessage: PropTypes.string,\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** If the input is an API Key, App Key or App Token */\n token: PropTypes.bool,\n /** Help text */\n helpText: PropTypes.node,\n /** Input size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Label */\n label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),\n /** Prefix */\n prefix: PropTypes.node,\n /** Spec attribute */\n accept: PropTypes.string,\n /** Spec attribute */\n disabled: PropTypes.bool,\n /** Spec attribute */\n autoComplete: PropTypes.string,\n /** Spec attribute */\n autoCorrect: PropTypes.string,\n /** Spec attribute */\n autoFocus: PropTypes.bool,\n /** Spec attribute */\n autoSave: PropTypes.string,\n /** @ignore\n * Spec attribute */\n button: PropTypes.string,\n /** List of data attributes as a object like `{'locale': 'en-US'}` */\n dataAttributes: PropTypes.object,\n /** Spec attribute */\n defaultValue: PropTypes.string,\n /** Whether the border should join with an element below */\n groupBottom: PropTypes.bool,\n /** Spec attribute */\n id: PropTypes.string,\n /** Data attribute */\n testId: PropTypes.string,\n /** Spec attribute */\n inputMode: PropTypes.string,\n /** @ignore\n * Loading state */\n isLoadingButton: PropTypes.bool,\n /** Spec attribute */\n list: PropTypes.string,\n /** Spec attribute */\n max: PropTypes.string,\n /** Spec attribute */\n maxLength: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /** Spec attribute */\n min: PropTypes.string,\n /** Spec attribute */\n minLength: PropTypes.string,\n /** Spec attribute */\n multiple: PropTypes.bool,\n /** Spec attribute */\n name: PropTypes.string,\n /** Spec attribute */\n pattern: PropTypes.string,\n /** Spec attribute */\n placeholder: PropTypes.string,\n /** Spec attribute */\n readOnly: PropTypes.bool,\n /** Spec attribute */\n required: PropTypes.bool,\n /** Spec attribute */\n spellCheck: PropTypes.string,\n /** Spec attribute */\n src: PropTypes.string,\n /** Spec attribute */\n step: PropTypes.string,\n /** Suffix attribute */\n suffix: PropTypes.node,\n /** DEPRECATED: Suffix icon attribute */\n suffixIcon: PropTypes.element,\n /** Spec attribute */\n tabIndex: PropTypes.string,\n /** Spec attribute */\n type: PropTypes.string,\n /** Spec attribute */\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /** onChange event */\n onChange: PropTypes.func,\n /** onKeyDown event */\n onKeyDown: PropTypes.func,\n /** onKeyPress event */\n onKeyPress: PropTypes.func,\n /** onKeyUp event */\n onKeyUp: PropTypes.func,\n /** onFocus event */\n onFocus: PropTypes.func,\n /** onBlur event */\n onBlur: PropTypes.func,\n /** onMouseEnter event */\n onMouseEnter: PropTypes.func,\n /** onMouseLeave event */\n onMouseLeave: PropTypes.func,\n}\n\nexport default withForwardedRef(Input)\n\n```" } ]
code_store-on-localhost_e4bf7b80
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Input/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### Inputs let users type in data in a variety of ways. Take a look at the options available to see which one fits best with what you need.\n\n### ๐Ÿ‘ Dos\n\n- When possible use labels, and keep them short and descriptive. More than 3 words might start looking weird.\n- Use the placeholders only to provide complementary information and show examples of how to fill that field. But using the label text is preferred in most cases.\n- Do use the required/optional flags when necessary, but prefer using one or another.\n- Provide a Tooltip in the label to explain in more details what you couldn't with just a few words.\n- Use the Helper Text to explain in more details how the input is expected to be filled.\n\n### Related components\n\n- In some cases for numerical inputs you might want a <a href=\"#/Components/Forms/NumericStepper\">NumericStepper</a>.\n- In case of monetary input values you might want to use the <a href=\"#/Components/Forms/InputCurrency\">InputCurrency</a>.\n- If instead of a free-form entry you expect the user to enter a value from a preset of values you might want to use a <a href=\"#/Components/Forms/Dropdown\">Dropdown</a>, for a single value, or a <a href=\"#/Components/Forms/MultiSelect\">Multiselect</a> for multiple values.\n- For input with a contextual button, use <a href=\"#/Components/Forms/InputButton\">InputButton</a>.\n\nSizes\n\n```js\n;<div>\n <div className=\"mb5\">\n <Input placeholder=\"Placeholder\" size=\"small\" label=\"Small\" />\n </div>\n\n <div className=\"mb5\">\n <Input\n placeholder=\"Regular with data-attributes\"\n dataAttributes={{ 'hj-white-list': true, test: 'string' }}\n label=\"Regular\"\n />\n </div>\n\n <div className=\"mb5\">\n <Input placeholder=\"Placeholder\" size=\"large\" label=\"Large\" />\n </div>\n</div>\n```\n\nVariations\n\n```js\nconst IconHelp = require('../icon/Help').default\nconst IconSearch = require('../icon/Search').default\nclass InputExamples extends React.Component {\n constructor() {\n super()\n this.state = {\n errorValue: '404',\n helpTextValue: '',\n passwordValue: '123456',\n tokenValue: 'DUq0xuJZAD7Rvezv',\n withPrefixValue: '',\n withSuffixValue: '',\n withSuffixLargeValue: '',\n withSuffixXLargeValue: '',\n }\n }\n\n render() {\n return (\n <div className=\"w-40\">\n <div className=\"mb5\">\n <Input\n value=\"This input is read-only.\"\n readOnly={true}\n label=\"Read-only\"\n />\n </div>\n <div className=\"mb5\">\n <Input disabled value=\"This input is disabled.\" label=\"Disabled\" />\n </div>\n <div className=\"mb5\">\n <Input\n type=\"password\"\n value={this.state.passwordValue}\n onChange={e => this.setState({ passwordValue: e.target.value })}\n label=\"Type Password\"\n />\n </div>\n <div className=\"mb5\">\n <Input\n label=\"Token\"\n value={this.state.tokenValue}\n onChange={e => this.setState({ tokenValue: e.target.value })}\n token\n />\n </div>\n <div className=\"mb5\">\n <Input\n label=\"Error\"\n onChange={e => this.setState({ errorValue: e.target.value })}\n value={this.state.errorValue}\n errorMessage=\"Invalid field value\"\n />\n </div>\n <div className=\"mb5\">\n <Input\n label=\"Help text\"\n onChange={e => this.setState({ helpTextValue: e.target.value })}\n vaue={this.state.helpTextValue}\n placeholder=\"Placeholder\"\n helpText={<span>Yout help text goes here!</span>}\n />\n </div>\n <div className=\"mb5\">\n <Input\n label=\"With prefix\"\n value={this.state.withPrefixValue}\n onChange={e => this.setState({ withPrefixValue: e.target.value })}\n prefix={<IconSearch />}\n />\n </div>\n <div className=\"mb5\">\n <Input\n label=\"With suffix\"\n value={this.state.withSuffixValue}\n onChange={e => this.setState({ withSuffixValue: e.target.value })}\n suffix={<IconHelp />}\n />\n </div>\n </div>\n )\n }\n}\n;<InputExamples />\n```\n\nUsing ref\n\n```js\nconst Button = require('../Button').default\nthis.input = React.createRef()\n\nconst handleFocusClick = () => {\n this.input.current.focus()\n}\n\n;<div>\n <Input\n ref={this.input}\n placeholder=\"Placeholder\"\n label=\"Click on the button below to focus on this input\"\n />\n <div className=\"pt2\">\n <Button size=\"small\" onClick={handleFocusClick}>\n Focus on input\n </Button>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_c943ac08
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Input/Input.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/* removes edge clear button on input */\n.hideDecorators::-ms-clear {\n display: none;\n}\n\n.noAppearance {\n appearance: none;\n}\n\n/* placeholders are using c-muted-1's value */\n::-webkit-input-placeholder {\n /* Chrome/Opera/Safari */\n color: #979899;\n}\n::-moz-placeholder {\n /* Firefox 19+ */\n color: #979899;\n}\n:-ms-input-placeholder {\n /* IE 10+ */\n color: #979899;\n}\n:-moz-placeholder {\n /* Firefox 18- */\n color: #979899;\n}\n\n```" } ]
code_store-on-localhost_aa0da7fa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Alert/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport SuccessIcon from '../icon/Success'\nimport FailureIcon from '../icon/Failure'\nimport WarningIcon from '../icon/Warning'\nimport CloseIcon from '../icon/Close'\nimport Button from '../Button'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass Alert extends Component {\n componentDidMount() {\n if (this.props.autoClose && this.props.onClose) {\n this.timeout = setTimeout(this.props.onClose, this.props.autoClose)\n }\n }\n\n componentWillUnmount() {\n clearTimeout(this.timeout)\n }\n\n render() {\n const { type, onClose, action, forwardedRef } = this.props\n const innerVerticalPadding = 'pv3'\n let classes = 'ph5 pv4 br2 '\n let showIcon = false\n let Icon = 'div'\n let color = 'c-on-base'\n const handleActionClick = (action && action.onClick) || undefined\n const displayAction = action && action.onClick && action.label\n\n switch (type) {\n case 'success': {\n showIcon = true\n classes += 'bg-success--faded '\n Icon = SuccessIcon\n color = 'c-success'\n break\n }\n case 'error': {\n showIcon = true\n classes += 'bg-danger--faded '\n Icon = FailureIcon\n color = 'c-danger'\n break\n }\n default:\n case 'warning': {\n showIcon = true\n classes += 'bg-warning--faded '\n Icon = WarningIcon\n color = 'c-warning'\n break\n }\n }\n\n return (\n <div\n ref={forwardedRef}\n className={`vtex-alert flex justify-between t-body c-on-base ${classes}`}>\n <div className=\"flex-ns flex-wrap flex-grow-1 items-start\">\n <div\n className={`flex items-start flex-grow-1 ${innerVerticalPadding}`}>\n {showIcon && (\n <div className={color}>\n <Icon block color=\"currentColor\" size={18} />\n </div>\n )}\n\n <div className={`${showIcon ? 'ph5 flex' : 'pr5'}`}>\n {this.props.children}\n </div>\n </div>\n\n {displayAction && (\n <div\n className={`flex flex-grow-1 justify-end ${innerVerticalPadding}`}>\n <div className=\"nt4-ns nb4\">\n <Button variation=\"tertiary\" onClick={handleActionClick}>\n {action.label}\n </Button>\n </div>\n </div>\n )}\n </div>\n\n {onClose && (\n <div\n title=\"Close\"\n className={`vtex-alert__close-icon pointer pv2 c-on-base ph3 ${innerVerticalPadding}`}\n onClick={onClose}\n tabIndex={0}>\n <CloseIcon block color=\"currentColor\" size={16} />\n </div>\n )}\n </div>\n )\n }\n}\n\nAlert.propTypes = {\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** Style of the alert */\n type: PropTypes.oneOf(['success', 'error', 'warning']).isRequired,\n /** Content of the alert */\n children: PropTypes.node.isRequired,\n /** If this function is defined, a close icon will appear and this function will be called when alert is closed. */\n onClose: PropTypes.func,\n /** Time in ms to auto close the alert */\n autoClose: PropTypes.number,\n /** If this object is defined, an action button will appear on the right side of the alert. */\n action: PropTypes.shape({\n onClick: PropTypes.func.isRequired,\n label: PropTypes.node.isRequired,\n }),\n}\n\nexport default withForwardedRef(Alert)\n\n```" } ]
code_store-on-localhost_3564a142
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Alert/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### Alerts are notifications of mild to high priority. They may inform the user about things they should know or explain a problem and the user a solution. It may be triggered by a user action or not.\n\n### Do\n\n- Alerts should be shown at the top of the page or section they apply to, filling the full container width respecting some minimum little margins.\n- Do provide actions for users to address when it ads value to the user's workflow. Alerts are also a helping hand.\n- Do use semantic colors that have a clear and contextualized meaning in your application, but keep in mind that due to its mild to high priority, that success message may not apply here. If that's the case, you might be looking for Toasts.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Never dismiss automatically an Alert. If dismissable, a user action is required.\n\n### Related components\n\nFor low-priority notification prefer a <a href=\"#/Components/Notification/ToastProvider\">Toast</a>.\n\n```js\n<div>\n <div className=\"mb5\">\n <Alert type=\"success\" onClose={() => console.log('Closed!')}>\n Your action was complete.\n </Alert>\n </div>\n\n <div className=\"mb5\">\n <Alert type=\"warning\" onClose={() => console.log('Closed!')}>\n This action is irreversible.\n </Alert>\n </div>\n <div className=\"mb5\">\n <Alert type=\"warning\" onClose={() => console.log('Closed!')}>\n This is a large Alert. Lorem ipsum dolor sit amet, consectetur adipiscing\n elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut\n aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in\n voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur\n sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt\n mollit anim id est laborum.\n </Alert>\n </div>\n <div className=\"mb5\">\n <Alert type=\"error\" onClose={() => console.log('Closed!')}>\n You can't delete this item.\n </Alert>\n </div>\n <div>\n <Alert\n type=\"error\"\n action={{ label: 'Go back', onClick: () => console.log('Went back!') }}\n onClose={() => console.log('Closed!')}>\n You can't delete this item.\n </Alert>\n </div>\n</div>\n```\n\nUsing ref\n\n```js\nconst Button = require('../Button').default\nconst alertRef = React.createRef()\n\n;<div>\n <Alert ref={alertRef} type=\"warning\" onClose={() => console.log('Closed!')}>\n Click on the button below to focus on (scroll to) the alert\n </Alert>\n <div className=\"pt2\">\n <Button\n onClick={() =>\n alertRef.current.scrollIntoView({\n behavior: 'smooth',\n block: 'center',\n })\n }>\n Focus\n </Button>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_812fa104
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Alert/index.test.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { render, fireEvent } from 'react-testing-library'\n\nimport Alert from './index'\n\ndescribe('Alert', () => {\n describe('action button', () => {\n it('should be displayed if props are passed', () => {\n const label = 'Action'\n const onClick = jest.fn()\n\n const { getByText } = render(\n <Alert type=\"error\" action={{ label, onClick }}>\n Foo\n </Alert>\n )\n\n const actionButton = getByText(label)\n\n expect(actionButton).toBeDefined()\n\n fireEvent.click(actionButton)\n\n expect(onClick).toHaveBeenCalled()\n })\n })\n\n describe('onClose', () => {\n it('should be called on click close button', () => {\n const onClose = jest.fn()\n\n const { getByTitle } = render(\n <Alert type=\"error\" onClose={onClose}>\n Foo\n </Alert>\n )\n\n const closeButton = getByTitle('Close')\n\n fireEvent.click(closeButton)\n\n expect(onClose).toHaveBeenCalled()\n })\n\n it('should be called after autoClose time passes', () => {\n jest.useFakeTimers()\n const onClose = jest.fn()\n\n render(\n <Alert type=\"error\" autoClose={1} onClose={onClose}>\n Foo\n </Alert>\n )\n\n jest.runAllTimers()\n\n expect(onClose).toHaveBeenCalled()\n })\n\n it('should not be called if no click happens or autoClose time is not defined', () => {\n jest.useFakeTimers()\n const onClose = jest.fn()\n\n render(\n <Alert type=\"error\" onClose={onClose}>\n Foo\n </Alert>\n )\n\n jest.runAllTimers()\n\n expect(onClose).not.toHaveBeenCalled()\n })\n })\n})\n\n```" } ]
code_store-on-localhost_497ad56f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/DropdownIndicator.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport ArrowDownIcon from '../Dropdown/ArrowDownIcon'\n\nfunction paddingRightClassFromSize(size) {\n return {\n [size]: 'pr4',\n large: 'pr5',\n small: 'pr3',\n }[size]\n}\n\nconst DropdownIndicator = ({ innerProps, selectProps, size }) => {\n const arrowColorClassName = selectProps.isDisabled\n ? 'c-disabled'\n : 'c-action-primary'\n\n return (\n <div\n className={`flex items-center h-100 ${paddingRightClassFromSize(\n size\n )} pointer ${arrowColorClassName}`}\n {...innerProps}>\n <ArrowDownIcon size={18} />\n </div>\n )\n}\n\nDropdownIndicator.propTypes = {\n getStyles: PropTypes.func,\n innerProps: PropTypes.object,\n size: PropTypes.oneOf(['large', 'regular', 'small']),\n selectProps: PropTypes.object.isRequired,\n}\n\nexport default DropdownIndicator\n\n```" } ]
code_store-on-localhost_0e6a5d44
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/Control.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { components } from 'react-select'\n\nfunction heightClassFromSize(size) {\n return {\n [size]: 'min-h-regular',\n large: 'min-h-large',\n small: 'min-h-small',\n }[size]\n}\n\nconst Control = ({ size, ...props }) => {\n return (\n <div className={`pa0 ${heightClassFromSize(size)}`}>\n <components.Control {...props} />\n </div>\n )\n}\n\nControl.propTypes = {\n errorMessage: PropTypes.string,\n size: PropTypes.oneOf(['large', 'regular', 'small']),\n}\n\nexport default Control\n\n```" } ]
code_store-on-localhost_42a25cf1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/ClearIndicator.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport ClearIcon from '../icon/Clear'\n\nconst ClearIndicator = ({ innerProps }) => {\n return (\n <div\n className=\"flex items-center h-100 pr4 pointer c-muted-3 hover-gray\"\n {...innerProps}>\n <ClearIcon />\n </div>\n )\n}\n\nClearIndicator.propTypes = {\n innerProps: PropTypes.object,\n selectProps: PropTypes.object.isRequired,\n}\n\nexport default ClearIndicator\n\n```" } ]
code_store-on-localhost_c16f8c31
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/Placeholder.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nconst Placeholder = ({ innerProps, children }) => (\n <span className=\"c-muted-2\" {...innerProps}>\n {children}\n </span>\n)\n\nPlaceholder.propTypes = {\n innerProps: PropTypes.object,\n children: PropTypes.node.isRequired,\n}\n\nexport default Placeholder\n\n```" } ]
code_store-on-localhost_00253b8c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React, { Component } from 'react'\nimport uuid from 'uuid/v4'\nimport ReactSelect from 'react-select'\nimport CreatableSelect from 'react-select/lib/Creatable'\n\nimport COLORS from './colors'\nimport ClearIndicator from './ClearIndicator'\nimport DropdownIndicatorComponent from './DropdownIndicator'\nimport MultiValueRemove from './MultiValueRemove'\nimport Placeholder from './Placeholder'\nimport ControlComponent from './Control'\nimport { getFontClassNameFromSize, getTagPaddingFromSize } from './styles'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nconst getOptionValue = option => {\n return JSON.stringify(option.value)\n}\n\nclass Select extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n searchTerm: undefined,\n }\n\n this.inputId = `react-select-input-${uuid()}`\n }\n\n componentDidUpdate(prevProps, prevState) {\n const { searchTerm } = this.state\n const { searchTerm: prevSearchTerm } = prevState\n const { loading } = this.props\n const { loading: prevLoading } = prevProps\n\n if (searchTerm !== prevSearchTerm || loading !== prevLoading) {\n document.getElementById(this.inputId).focus()\n }\n }\n\n render() {\n const {\n forwardedRef,\n autoFocus,\n creatable,\n defaultValue,\n disabled,\n errorMessage,\n formatCreateLabel,\n label,\n loading,\n multi,\n noOptionsMessage,\n onChange,\n onSearchInputChange,\n options,\n placeholder,\n size,\n value,\n valuesMaxHeight,\n clearable,\n defaultMenuIsOpen,\n } = this.props\n\n const reactSelectComponentProps = {\n defaultMenuIsOpen,\n ref: forwardedRef,\n autoFocus,\n className: `pointer b--danger bw1 ${getFontClassNameFromSize(size)} ${\n errorMessage ? 'b--danger bw1' : ''\n }`,\n components: {\n ClearIndicator,\n Control: function Control(props) {\n return (\n <ControlComponent\n errorMessage={errorMessage}\n size={size}\n {...props}\n />\n )\n },\n DropdownIndicator: function DropdownIndicator(props) {\n return <DropdownIndicatorComponent size={size} {...props} />\n },\n IndicatorSeparator: () => null,\n MultiValueRemove,\n Placeholder,\n },\n defaultValue,\n formatCreateLabel,\n getOptionValue,\n isClearable: clearable,\n isDisabled: disabled,\n isLoading: loading,\n isMulti: multi,\n noOptionsMessage,\n inputId: this.inputId,\n onInputChange: (value, { action }) => {\n this.setState({\n searchTerm: value,\n })\n if (\n action === 'input-change' &&\n typeof onSearchInputChange === 'function'\n ) {\n onSearchInputChange(value)\n }\n },\n onChange,\n options,\n placeholder,\n styles: {\n control: style => {\n const errorStyle = errorMessage ? { borderColor: COLORS.red } : {}\n\n return {\n ...style,\n ...errorStyle,\n borderWidth: '.125rem',\n }\n },\n menu: style => ({ ...style, marginTop: 0 }),\n multiValue: (style, state) => ({\n ...style,\n backgroundColor: state.isDisabled\n ? COLORS['muted-4']\n : COLORS.aliceBlue,\n borderRadius: 100,\n padding: getTagPaddingFromSize(size),\n color: state.isDisabled ? COLORS.gray : COLORS.blue,\n position: 'relative',\n }),\n multiValueLabel: (style, state) => ({\n ...style,\n paddingRight: 0,\n fontWeight: 500,\n color: state.isDisabled ? COLORS.gray : COLORS.blue,\n }),\n multiValueRemove: style => ({\n ...style,\n colors: 'inherit',\n ':hover': {\n backgroundColor: 'transparent',\n color: COLORS.red,\n },\n }),\n option: style => ({ ...style, cursor: 'pointer' }),\n placeholder: style => ({ ...style, padding: 10 }),\n valueContainer: (style, state) => ({\n ...style,\n cursor: 'pointer',\n paddingLeft: '1rem',\n backgroundColor: state.isDisabled\n ? COLORS.lightGray\n : style.backgroundColor,\n maxHeight: `${valuesMaxHeight}px`,\n overflowY: 'auto',\n }),\n theme: theme => ({\n ...theme,\n colors: {\n ...theme.colors,\n primary: COLORS.gray,\n primary25: COLORS.lightGray,\n },\n }),\n },\n value,\n }\n\n return (\n <div className=\"flex flex-column\">\n {label && (\n <label className={`dib mb3 w-100 ${getFontClassNameFromSize(size)}`}>\n {label}\n </label>\n )}\n\n {creatable ? (\n <CreatableSelect {...reactSelectComponentProps} />\n ) : (\n <ReactSelect {...reactSelectComponentProps} />\n )}\n\n {errorMessage && (\n <span className=\"c-danger f6 mt3 lh-title\">{errorMessage}</span>\n )}\n </div>\n )\n }\n}\n\nSelect.defaultProps = {\n multi: true,\n placeholder: 'Select...',\n size: 'regular',\n clearable: true,\n defaultMenuIsOpen: false,\n}\n\nconst OptionShape = PropTypes.shape({\n /** Text that gets rendered for the option. */\n label: PropTypes.string.isRequired,\n /** Underlying value, e.g., an id. */\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,\n})\n\nconst OptionsShape = PropTypes.arrayOf(OptionShape)\n\nconst GroupedOptionsShape = PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string,\n options: OptionsShape,\n })\n)\n\nSelect.propTypes = {\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** Select auto focus */\n autoFocus: PropTypes.bool,\n /** Should clear button appear */\n clearable: PropTypes.bool,\n /** Creatable options. */\n creatable: PropTypes.bool,\n /** Default value */\n defaultValue: PropTypes.oneOfType([\n PropTypes.string,\n OptionShape,\n OptionsShape,\n ]),\n /** Disables Select */\n disabled: PropTypes.bool,\n /** Error message, e.g., validation error message. */\n errorMessage: PropTypes.string,\n /** Gets the label for the \"Create new...\" option in the menu. ({inputValue}) => string | null */\n formatCreateLabel: PropTypes.func,\n /** Label text. */\n label: PropTypes.string,\n /** Is the select in a state of loading (async). */\n loading: PropTypes.bool,\n /** Text to display when loading options */\n loadingMessage: PropTypes.string,\n /** Support multiple selected options. */\n multi: PropTypes.bool,\n /** Text to display when there are no options. ({inputValue}) => string | null */\n noOptionsMessage: PropTypes.func,\n /** onChange handler: (option) => void */\n onChange: PropTypes.func.isRequired,\n /** Handle events on search input */\n onSearchInputChange: PropTypes.func,\n /** Array of options. Options have the shape { label, value }. */\n options: PropTypes.oneOfType([OptionsShape, GroupedOptionsShape]),\n /** Text for the select value. */\n placeholder: PropTypes.string,\n /** Select size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Value of the select. */\n value: PropTypes.oneOfType([OptionShape, OptionsShape]),\n /** Max height (in _px_) of the selected values container */\n valuesMaxHeight: PropTypes.number,\n /** If its options are initially shown */\n defaultMenuIsOpen: PropTypes.bool,\n}\n\nexport default withForwardedRef(Select)\n\n```" } ]
code_store-on-localhost_ab2389e7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/ArrowUpIcon.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nclass ArrowUpIcon extends PureComponent {\n render() {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={this.props.size}\n height={this.props.size}\n viewBox=\"0 0 24 24\">\n <g fill={this.props.color}>\n <path\n d=\"M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z\"\n transform=\"translate(24 24) rotate(-180)\"\n />\n </g>\n </svg>\n )\n }\n}\n\nArrowUpIcon.defaultProps = {\n size: 16,\n color: 'currentColor',\n}\n\nArrowUpIcon.propTypes = {\n size: PropTypes.number.isRequired,\n color: PropTypes.string.isRequired,\n}\n\nexport default ArrowUpIcon\n\n```" } ]
code_store-on-localhost_eddb2da3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Select lets the user pick one or more options from a list.\n\n### Options\n\nThe options prop accepts the following types:\n\n```ts\ntype Options = {\n label: string\n value: string | {}\n}[]\n\ntype GroupedOptions = {\n label: string\n options: Options\n}\n```\n\n### ๐Ÿ‘ Dos\n\n- Mind the order of the options, like putting the more probable one to be selected at the top. In doubt, sort them alphanumerically (from A to Z and from 0 to 9).\n\n### ๐Ÿ‘Ž Don'ts\n\n- If there are just a few options to choose from (like 4), consider a **Radio Group** (for single select) or **Checkbox** (for multi select).\n\nSimple\n\n```js\nconst options = [\n {\n value: { id: 0, name: 'first-option' },\n label: 'First Option',\n },\n {\n value: { id: 1, name: 'second-option' },\n label: 'Second Option',\n },\n]\n\n;<div>\n <div className=\"mb5\">\n <Select\n defaultValue={options[0]}\n size=\"small\"\n multi={true}\n label=\"Small\"\n options={options}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n onSearchInputChange={value => {\n console.log('[Select] onSeachInputChange: ' + value)\n }}\n />\n </div>\n <div className=\"mb5\">\n <Select\n defaultValue={options[0]}\n multi={true}\n label=\"Regular\"\n options={options}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n </div>\n <div className=\"mb5\">\n <Select\n defaultValue={options[0]}\n size=\"large\"\n multi={true}\n label=\"Large\"\n options={options}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n </div>\n</div>\n```\n\nSingle\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n\n;<div>\n <Select\n label=\"Label\"\n options={options}\n multi={false}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n</div>\n```\n\nNo label\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First option',\n },\n {\n value: 'second-option',\n label: 'Second option',\n },\n]\n\n;<div>\n <Select\n options={options}\n multi={true}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n</div>\n```\n\nWith Error\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n\n;<div>\n <Select\n label=\"Label\"\n options={options}\n multi={true}\n errorMessage=\"Required!\"\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n</div>\n```\n\nWith creatable option\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n;<div>\n <Select\n label=\"Label\"\n options={options}\n multi={true}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n creatable\n />\n</div>\n```\n\nDisabled\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n\n;<div>\n <Select\n disabled={true}\n label=\"Label\"\n options={options}\n multi={true}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n <div className=\"mv5\">\n <Select\n disabled={true}\n label=\"Label\"\n options={options}\n multi={true}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n value={[\n {\n value: 'first-option',\n label: 'First Option',\n },\n ]}\n />\n </div>\n</div>\n```\n\nLoading state\n\n```js\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n\n;<div>\n <Select\n loading={true}\n label=\"Label\"\n options={options}\n multi={true}\n onChange={values => {\n console.log(`[Select] Selected: ${JSON.stringify(values, null, 2)}`)\n }}\n />\n</div>\n```\n\nUsing ref\n\n```js\nconst Button = require('../Button').default\n\nconst options = [\n {\n value: 'first-option',\n label: 'First Option',\n },\n {\n value: 'second-option',\n label: 'Second Option',\n },\n]\n\nconst ref = React.createRef()\n\n;<div>\n <Select\n ref={ref}\n label=\"Click in the button below to focus on this Select\"\n options={options}\n />\n <div className=\"pt2\">\n <Button size=\"small\" onClick={() => ref.current.focus()}>\n Focus on input\n </Button>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_fe1f5a53
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/colors.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport default {\n aliceBlue: '#eef3f7',\n blue: '#134cd8',\n gray: '#979899',\n lightGray: '#f2f4f5',\n 'muted-4': '#E3E4E6',\n red: '#ff4c4c',\n}\n\n```" } ]
code_store-on-localhost_fb445cf6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/MultiValueRemove.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\nimport React from 'react'\nimport { components } from 'react-select'\n\nimport Close from '../icon/Close'\n\nconst MultiValueRemove = props => {\n const multiValueProps = {\n ...props,\n innerProps: {\n ...props.innerProps,\n className: `${props.innerProps.className}`,\n },\n }\n\n const {\n innerProps: {\n onClick: handleClick,\n onTouchEnd: handleTouchEnd,\n onMouseDown: handleMouseDown,\n },\n } = props\n\n return (\n <React.Fragment>\n <div\n className=\"flex items-center\"\n onClick={handleClick}\n onTouchEnd={handleTouchEnd}\n onMouseDown={handleMouseDown}>\n <components.MultiValueRemove {...multiValueProps}>\n <Close size={14} />\n </components.MultiValueRemove>\n </div>\n </React.Fragment>\n )\n}\n\nMultiValueRemove.propTypes = {\n innerProps: PropTypes.object,\n}\n\nexport default MultiValueRemove\n\n```" } ]
code_store-on-localhost_449f28fe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EXPERIMENTAL_Select/styles.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nexport const getFontClassNameFromSize = size => {\n switch (size) {\n case 'large':\n return 't-body'\n case 'small':\n default:\n return 't-small'\n }\n}\n\nexport const getTagPaddingFromSize = size => {\n switch (size) {\n case 'large':\n return '.25rem .5rem' // pv2 ph3\n case 'small':\n return '0 .125rem' // pv0 ph1\n default:\n return '.25rem .5rem' // pv2 ph3\n }\n}\n\n```" } ]
code_store-on-localhost_7cb7ec38
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Layout/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Layout extends Component {\n render() {\n const { fullWidth, pageHeader, children } = this.props\n\n return (\n <div className=\"styleguide__layout flex justify-center pb7 bg-muted-5 min-vh-100\">\n <div className={fullWidth ? 'w-100' : 'w-100 mw8'}>\n {pageHeader}\n <div className=\"layout__container ph7-ns\">{children}</div>\n </div>\n </div>\n )\n }\n}\n\nLayout.defaultProps = {\n fullWidth: false,\n}\n\nLayout.propTypes = {\n /** Content of the Layout */\n children: PropTypes.node.isRequired,\n /** If the content fills the whole width */\n fullWidth: PropTypes.bool,\n /** A PageHeader component slot */\n pageHeader: PropTypes.node.isRequired,\n}\n\nexport default Layout\n\n```" } ]
code_store-on-localhost_3008430b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Layout/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### We built the page layout component in order to establish layout standards across VTEX admins. This standardization helps to create user patterns and impacts the user experience while using our platform. With these standards, our user became more aware of use and interaction. Thus we created this component with only two versions, centered and full.\n\n### Centered\nThe centered version has a max width. This layout version will keep the page content centered even on large screens. The designer can use this kind of layout when it is important to guide the user through the action. For example, it can be used for, forms, setups, and CRUDs, in with a specific context.\n\n### ๐Ÿ‘ Dos\n- Use to create layouts with direct content\n- Use to guide the user through an action\n- Use to draw attention to specific actions\n\n```\nconst PageHeader = require('../PageHeader').default\nconst PageBlock = require('../PageBlock').default\nconst Button = require('../Button').default\n\n;<Layout pageHeader={<PageHeader title=\"Page title centered\" />}>\n <PageBlock>\n <Button>click me</Button>\n </PageBlock>\n</Layout>\n```\n\n### Full\nThe Full version will take the whole screen width. This layout version must be used when the designer wants to show a large amount of data. For this, the full design will turn possible the possibility of building dashboards and display data sets, such as tables and so on.\n\n### ๐Ÿ‘ Dos\n- Use to show large amount of data\n- Use to create dashboards\n- Use to display interactions that must to be simultaneous\n\n\n```\nconst PageHeader = require('../PageHeader').default\nconst PageBlock = require('../PageBlock').default\nconst Button = require('../Button').default\n\n;<Layout\n fullWidth\n pageHeader={\n <PageHeader\n title=\"Page title fullwidth\"\n linkLabel=\"A link\">\n <Button variation=\"primary\">Primary</Button>\n </PageHeader>\n }>\n <PageBlock>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada ut neque id pharetra. Suspendisse tortor eros, sagittis at molestie at, semper mollis urna. Sed porta ipsum ac vulputate ultrices. Mauris sed libero quis risus rutrum efficitur in nec justo.\n </PageBlock>\n</Layout>\n```\n\n```" } ]
code_store-on-localhost_d134e46b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/DatePicker/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport ReactDatePicker, { registerLocale } from 'react-datepicker'\nimport * as locales from 'date-fns/locale/index.js'\n\nimport Input from '../Input'\nimport IconCalendar from '../icon/Calendar'\nimport './react-datepicker.global.css'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass DatePicker extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n active: false,\n }\n\n this.handleLocaleChange(props.locale)\n }\n\n get popperModifiers() {\n const { align, direction, size, useTime } = this.props\n\n const BASE_MODIFIERS = {\n hide: { enabled: false },\n preventOverflow: {\n enabled: false,\n },\n }\n\n const isRightAligned = align === 'right'\n const isUpwards = direction === 'up'\n\n if (!isRightAligned && !isUpwards) {\n return BASE_MODIFIERS\n }\n\n const offsetX = isRightAligned\n ? (size === 'large' ? -91 : -136) - (useTime ? 130 : 0)\n : 0\n\n const offsetYBySize = {\n large: -448,\n regular: -440,\n small: -432,\n }\n\n const offsetY = isUpwards ? offsetYBySize[size] - (useTime ? 18 : 0) : 0\n\n return {\n ...BASE_MODIFIERS,\n flip: {\n enabled: !isUpwards,\n },\n keepTogether: {\n enabled: false,\n },\n offset: {\n offset: `${offsetX}, ${offsetY}`,\n },\n }\n }\n\n componentDidMount() {\n if (this.props.useTime) {\n console.warn(\n 'DatePicker: The prop \"useTime\" of the \"DatePicker\" component has been deprecated, and will be removed in a future version. Please use the \"TimePicker\" component instead'\n )\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.locale !== prevProps.locale) {\n this.handleLocaleChange(this.props.locale)\n }\n }\n\n handleLocaleChange = locale => {\n // registerLocale is a function from react-datepicker component that loads\n // an imported locale object from date-fns.\n //\n // For more information visit the link below:\n // https://github.com/Hacker0x01/react-datepicker#localization\n //\n registerLocale(locale, locales[locale.replace('-', '')])\n }\n\n render() {\n const { positionFixed, useTime, useTimeOnly } = this.props\n\n const popperProps = {\n ...(positionFixed && {\n positionFixed: true,\n }),\n }\n\n const format = useTimeOnly ? 'p' : useTime ? 'Pp' : 'P'\n\n return (\n <ReactDatePicker\n ref={this.props.forwardedRef}\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={this.props.autoFocus}\n customInput={\n <Input\n error={this.props.error}\n errorMessage={this.props.errorMessage || this.state.errorMessage}\n helpText={this.props.helpText}\n label={this.props.label}\n prefix={this.props.prefix}\n size={this.props.size}\n />\n }\n dateFormat={format}\n disabled={this.props.disabled}\n disabledKeyboardNavigation\n endDate={this.props.dateRangeEnd}\n excludeDates={this.props.excludeDates}\n excludeTimes={this.props.excludeTimes}\n fixedHeight={this.props.direction === 'up'}\n id={this.props.id}\n includeDates={this.props.includeDates}\n includeTimes={this.props.includeTimes}\n locale={this.props.locale}\n maxDate={this.props.maxDate}\n maxTime={this.props.maxTime}\n minDate={this.props.minDate}\n minTime={this.props.minTime}\n name={this.props.name}\n placeholderText={this.props.placeholder}\n popperModifiers={this.popperModifiers}\n popperProps={popperProps}\n readOnly={this.props.readOnly}\n required={this.props.required}\n selected={this.props.value}\n selectsEnd={this.props.isRangeEnd}\n selectsStart={this.props.isRangeStart}\n showDisabledMonthNavigation={this.props.limitMonthNavigation}\n showTimeSelect={useTime || useTimeOnly}\n startDate={this.props.dateRangeStart}\n showTimeSelectOnly={useTimeOnly}\n tabIndex={this.props.tabIndex}\n timeFormat=\"p\"\n timeIntervals={this.props.timeIntervals}\n onBlur={this.props.onBlur}\n onFocus={this.props.onFocus}\n onChange={this.props.onChange}\n />\n )\n }\n}\n\nDatePicker.defaultProps = {\n align: 'left',\n autoFocus: false,\n direction: 'down',\n disabled: false,\n error: false,\n label: '',\n limitMonthNavigation: false,\n prefix: <IconCalendar />,\n readOnly: false,\n required: false,\n size: 'regular',\n}\n\nDatePicker.propTypes = {\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** Popper alignment in relation to the input */\n align: PropTypes.oneOf(['left', 'right']),\n /** Spec attribute */\n autoFocus: PropTypes.bool,\n /** @ignore Date range end date */\n dateRangeEnd: PropTypes.instanceOf(Date),\n /** @ignore Date range start date */\n dateRangeStart: PropTypes.instanceOf(Date),\n /** @ignore Date format */\n dateFormat: PropTypes.string,\n /** Popper position in relation to the input */\n direction: PropTypes.oneOf(['down', 'up']),\n /** Spec attribute */\n disabled: PropTypes.bool,\n /** Error highlight */\n error: PropTypes.bool,\n /** Error message */\n errorMessage: PropTypes.string,\n /** Dates to be excluded */\n excludeDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)),\n /** Times to be excluded */\n excludeTimes: PropTypes.arrayOf(PropTypes.instanceOf(Date)),\n /** Help text */\n helpText: PropTypes.node,\n /** Spec attribute */\n id: PropTypes.string,\n /** Dates to be included */\n includeDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)),\n /** Dates to be included */\n includeTimes: PropTypes.arrayOf(PropTypes.instanceOf(Date)),\n /** @ignore Indicates that the input represents the end date of a date range */\n isRangeEnd: PropTypes.bool,\n /** @ignore Indicates that the input represents the start date of a date range */\n isRangeStart: PropTypes.bool,\n /** Label */\n label: PropTypes.string,\n /** Disables out-of-bounds month navigation */\n limitMonthNavigation: PropTypes.bool,\n /** Locale string ('en-US', 'pt-BR', ...) */\n locale: PropTypes.string.isRequired,\n /** Max possible date */\n maxDate: PropTypes.instanceOf(Date),\n /** Upper time limit */\n maxTime: PropTypes.instanceOf(Date),\n /** Minimum possible date */\n minDate: PropTypes.instanceOf(Date),\n /** Lower time limit */\n minTime: PropTypes.instanceOf(Date),\n /** Spec attribute */\n name: PropTypes.string,\n /** onChange event */\n onChange: PropTypes.func.isRequired,\n /** onFocus event */\n onFocus: PropTypes.func,\n /** onBlur event */\n onBlur: PropTypes.func,\n /** Placeholder text */\n placeholder: PropTypes.string,\n /** @ignore Prefix component to be used as the prefix of the input */\n prefix: PropTypes.node,\n /** Spec attribute */\n readOnly: PropTypes.bool,\n /** Spec attribute */\n required: PropTypes.bool,\n /** DatePicker size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Spec attribute */\n tabIndex: PropTypes.string,\n /** Interval between times (in min) */\n timeIntervals: PropTypes.number,\n /** Flag used for indicating whether to use time or not */\n useTime: PropTypes.bool,\n /** @ignore Do not show calendar view */\n useTimeOnly: PropTypes.bool,\n /** Value of the selected date */\n value: PropTypes.instanceOf(Date).isRequired,\n /** Sets the popper to position fixed. Fixes issues with overflow: hidden. */\n positionFixed: PropTypes.bool,\n}\n\nexport default withForwardedRef(DatePicker)\n\n```" } ]
code_store-on-localhost_25d5cc5b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/DatePicker/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Datepicker lets the user select a single date and time by interacting with a calendar.\n\n### ๐Ÿ‘ Dos\n\n- Combine with Dropdowns or other components if you need more input from the user such as choosing a timezone.\n- Combine with the **TimePicker** component for specifing a time when choosing a date.\n- For birthdates or other dates that span far to the past or to the future do disable the calendar popover. It's not (yet) built for that, and the user might see herself forced to do a lot of clicks.\n\n### ๐Ÿ‘Ž Don'ts\n\n- For complex tasks such as selecting dates you might be tempted to design a slightly different behavior and build a customization on top of the component. Avoid doing that locally, and consider contributing to the library. More often than you think your need is the same as someone's else.\n\n### Supported locales\n\nYou can check out the list of supported locales [here](https://github.com/date-fns/date-fns/blob/master/src/locale/index.js).\n\n#### Simple DatePicker\n\n```js\nclass DatePickerExample extends React.Component {\n constructor() {\n super()\n this.state = {\n startDate: new Date(),\n }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n render() {\n return (\n <div>\n <div className=\"mb5\">\n <DatePicker\n label=\"Small\"\n size=\"small\"\n value={this.state.startDate}\n onChange={this.handleChange}\n locale=\"pt-BR\"\n />\n </div>\n\n <div className=\"mb5\">\n <DatePicker\n label=\"Regular\"\n value={this.state.startDate}\n onChange={this.handleChange}\n locale=\"pt-BR\"\n />\n </div>\n\n <div className=\"mb5\">\n <DatePicker\n label=\"Large\"\n size=\"large\"\n value={this.state.startDate}\n onChange={this.handleChange}\n locale=\"pt-BR\"\n />\n </div>\n </div>\n )\n }\n\n handleChange(date) {\n this.setState({\n startDate: date,\n })\n }\n}\n\n;<DatePickerExample />\n```\n\n#### Variations\n\n```js\nconst { subDays, addDays, setHours, setMinutes } = require('date-fns')\n\nclass DatePickerExample extends React.Component {\n constructor() {\n super()\n this.state = {\n customTimeIntervalsDate: new Date(),\n dateRangeDate: new Date(),\n disabledDate: new Date(),\n errorDate: new Date(),\n excludeDatesDate: new Date(),\n excludeTimesDate: new Date(),\n helpTextDate: new Date(),\n includeDatesDate: new Date(),\n includeTimesDate: new Date(),\n placeholderDate: null,\n readOnlyDate: new Date(),\n requiredDate: null,\n rightAlignedDate: new Date(),\n timeRangeDate: new Date(),\n upwardsDate: new Date(),\n }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(date) {\n this.setState({\n startDate: date,\n })\n }\n\n render() {\n return (\n <div>\n <div className=\"mv4\">\n <DatePicker\n label=\"Date range\"\n maxDate={addDays(new Date(), 5)}\n minDate={new Date()}\n value={this.state.dateRangeDate}\n onChange={date => this.setState({ dateRangeDate: date })}\n locale=\"pt-BR\"\n />\n </div>\n <div className=\"mv4\">\n <DatePicker\n excludeDates={[\n subDays(new Date(), 4),\n subDays(new Date(), 2),\n new Date(),\n addDays(new Date(), 2),\n addDays(new Date(), 4),\n ]}\n label=\"Exclude dates\"\n value={this.state.excludeDatesDate}\n onChange={date => this.setState({ excludeDatesDate: date })}\n locale=\"pt-BR\"\n />\n </div>\n <div className=\"mv4\">\n <DatePicker\n includeDates={[\n subDays(new Date(), 4),\n subDays(new Date(), 2),\n new Date(),\n addDays(new Date(), 2),\n addDays(new Date(), 4),\n ]}\n label=\"Include dates\"\n value={this.state.includeDatesDate}\n onChange={date => this.setState({ includeDatesDate: date })}\n locale=\"pt-BR\"\n />\n </div>\n <div className=\"mv4\">\n <DatePicker\n align=\"right\"\n label=\"Right-aligned\"\n locale=\"pt-BR\"\n onChange={date => this.setState({ rightAlignedDate: date })}\n value={this.state.rightAlignedDate}\n />\n </div>\n <div>\n <span className=\"mv4\">\n <DatePicker\n direction=\"up\"\n label=\"Upwards\"\n locale=\"pt-BR\"\n onChange={date => this.setState({ upwardsDate: date })}\n value={this.state.upwardsDate}\n />\n </span>\n </div>\n </div>\n )\n }\n}\n\n;<DatePickerExample />\n```\n\n#### Using ref\n\n```js\nconst Button = require('../Button/index.js').default\n\nclass DatePickerExample extends React.Component {\n constructor() {\n super()\n this.ref = React.createRef()\n this.state = {\n startDate: new Date(),\n }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(date) {\n this.setState({\n startDate: date,\n })\n }\n\n render() {\n return (\n <div>\n <div className=\"mb5\">\n <DatePicker\n ref={this.ref}\n label=\"Click in the button below to focus on this DatePicker\"\n value={this.state.startDate}\n onChange={this.handleChange}\n locale=\"pt-BR\"\n />\n </div>\n\n <div className=\"mb5\">\n <Button onClick={() => this.ref.current.setFocus()}>Focus!</Button>\n </div>\n </div>\n )\n }\n}\n\n;<DatePickerExample />\n```\n\n```" } ]
code_store-on-localhost_80e21008
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/DatePicker/react-datepicker.global.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n@import url('~react-datepicker/dist/react-datepicker.min.css');\n\n/* VTEX Customizations */\n.react-datepicker {\n /* Styleguide Colors */\n /* todo: replace this with actual variables from VTEX Tachyons */\n --white: #ffffff;\n --near-white: #f0f0f0;\n --near-black: #2e2e2e;\n\n --blue: #134cd8;\n --light-blue: #dbe9fd;\n --dark-blue: #0c389f;\n\n --gray: #979899;\n --light-gray: #e3e4e6;\n --dark-gray: #727273;\n\n /* Sizes */\n --calendar-width: 376px;\n --calendar-height: 346px;\n --time-width: 130px;\n --time-paddings: 24px 12px;\n --cell-size: 42px;\n --cell-margins: 0;\n\n /* Colors */\n --bg-color: var(--white);\n\n --day-color: var(--near-black);\n --day-disabled-text-color: var(--light-gray);\n --day-hover-bg-color: var(--near-white);\n --day-hover-text-color: var(--blue);\n --day-outside-month-color: var(--dark-gray);\n --day-selected-border-color: var(--blue);\n --day-selected-hover-color: var(--light-blue);\n --day-name-color: var(--gray);\n\n --navigation-arrow-color: var(--blue);\n --navigation-arrow-hover-color: var(--dark-blue);\n\n --time-hover-color: var(--near-white);\n --time-selected-color: var(--blue);\n --time-selected-hover-color: var(--blue);\n\n /* Typography */\n --title-font-size: 20px;\n --font-size: 16px;\n\n /* Miscelaneous */\n --shadow: 0px 1px 18px rgba(0, 0, 0, 0.14);\n}\n\n.react-datepicker-popper {\n z-index: 10;\n}\n\n.react-datepicker {\n display: flex;\n position: absolute;\n font-family: inherit;\n font-size: var(--font-size);\n background: var(--bg-color);\n box-shadow: var(--shadow);\n border: none;\n border-radius: 4px;\n}\n\n.react-datepicker-wrapper {\n width: 100%;\n}\n\n.react-datepicker__input-container {\n width: 100%;\n}\n\n.react-datepicker__triangle {\n display: none;\n}\n\n.react-datepicker__navigation {\n border: 0;\n text-indent: 0px;\n width: 16px;\n height: 16px;\n}\n\n.react-datepicker__navigation::before {\n border-style: solid;\n border-width: 3px 3px 0 0;\n content: '';\n display: inline-block;\n height: 8px;\n width: 8px;\n position: relative;\n left: 0;\n top: 3px;\n transform: rotate(-45deg);\n vertical-align: top;\n z-index: 1;\n cursor: pointer;\n}\n\n.react-datepicker__navigation--next:before {\n left: -2px;\n transform: rotate(45deg);\n}\n\n.react-datepicker__navigation--previous:before {\n left: 2px;\n transform: rotate(-135deg);\n}\n\n.react-datepicker__navigation {\n margin: 20px;\n}\n\n.react-datepicker__navigation--previous:before {\n border-color: var(--navigation-arrow-color);\n}\n\n.react-datepicker__navigation--previous:hover:before {\n border-color: var(--navigation-arrow-hover-color);\n}\n\n.react-datepicker__navigation--next:before {\n border-color: var(--navigation-arrow-color);\n}\n\n.react-datepicker__navigation--next:hover:before {\n border-color: var(--navigation-arrow-hover-color);\n}\n\n.react-datepicker__navigation--next--with-time:not(.react-datepicker__navigation--next--with-today-button) {\n right: calc(var(--time-width) + 10px);\n}\n\n.react-datepicker__month-container {\n margin: 20px;\n}\n\n.react-datepicker__time-container {\n width: auto;\n border-left: 1px solid #e3e4e6;\n}\n\n.react-datepicker__header {\n background-color: var(--bg-color);\n border: none;\n border-bottom: 1px solid #e3e4e6;\n padding: 0px;\n}\n\n.react-datepicker__current-month,\n.react-datepicker-time__header {\n font-size: var(--title-font-size);\n line-height: 28px;\n padding-bottom: 16px;\n}\n\n.react-datepicker__header.react-datepicker__header--time {\n display: none;\n}\n\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box {\n width: auto;\n}\n\n.react-datepicker__time-list {\n height: 333px !important;\n}\n\n/* Days */\n\n.react-datepicker__day-name,\n.react-datepicker__day,\n.react-datepicker__time-name {\n color: var(--day-color);\n width: var(--cell-size);\n height: var(--cell-size);\n line-height: var(--cell-size);\n margin: var(--cell-margins);\n border-radius: 0.3rem;\n}\n\n.react-datepicker__day:hover {\n background-color: var(--day-hover-bg-color);\n color: var(--day-hover-text-color);\n}\n\n.react-datepicker__day--disabled,\n.react-datepicker__day--disabled:hover {\n background-color: transparent;\n color: var(--day-disabled-text-color);\n}\n\n.react-datepicker__day--outside-month {\n color: var(--day-outside-month-color);\n}\n\n.react-datepicker__day--selected,\n.react-datepicker__day--in-selecting-range,\n.react-datepicker__day--in-range {\n /* background: var(--day-selected-color); */\n background: var(--white);\n color: var(--blue);\n box-shadow: inset 0 0 0 2px var(--day-selected-border-color);\n}\n\n.react-datepicker__day--selected:hover,\n.react-datepicker__day--in-selecting-range:hover,\n.react-datepicker__day--in-range:hover {\n background: var(--day-selected-hover-color);\n}\n\n.react-datepicker__day-name {\n color: var(--day-name-color);\n}\n\n.react-datepicker__month {\n margin: 0px;\n}\n\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item {\n width: var(--time-width);\n height: auto;\n padding: var(--time-paddings);\n}\n\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item:hover {\n background-color: var(--time-hover-color);\n}\n\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--selected {\n background-color: var(--time-selected-color);\n}\n\n.react-datepicker__time-container\n .react-datepicker__time\n .react-datepicker__time-box\n ul.react-datepicker__time-list\n li.react-datepicker__time-list-item--selected:hover {\n background-color: var(--time-selected-hover-color);\n}\n\n```" } ]
code_store-on-localhost_56d036ee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Checkbox/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nimport CheckIcon from '../icon/Check'\nimport CheckPartial from '../icon/CheckPartial'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass Checkbox extends PureComponent {\n handleChange = e =>\n this.props.onChange\n ? !this.props.disabled && this.props.onChange(e)\n : undefined\n\n render() {\n const {\n checked,\n disabled,\n id,\n label,\n name,\n required,\n value,\n partial,\n forwardedRef,\n } = this.props\n\n return (\n <div\n className={classNames(\n 'vtex-checkbox__line-container flex items-center relative',\n {\n pointer: !disabled,\n }\n )}>\n <div\n className={classNames('vtex-checkbox__container relative w1 h1', {\n mr3: label,\n })}>\n <div\n className={classNames(\n 'vtex-checkbox__inner-container h1 w1 absolute ba bw1 br1 ',\n {\n 'b--muted-4 pointer': !checked && !disabled,\n 'b--disabled bg-muted-5 c-disabled': !checked && disabled,\n 'b--action-primary bg-action-primary': checked && !disabled,\n 'b--muted-5 bg-muted-5': partial && !checked && disabled,\n 'b--disabled bg-disabled': checked && disabled,\n mr3: label,\n }\n )}\n style={{\n transition: 'background 20ms, border 100ms',\n backgroundColor: partial && !checked && !disabled && '#dbe9fd',\n borderColor: partial && !checked && !disabled && '#dbe9fd',\n }}\n />\n <div\n className=\"absolute w1 h1 flex o-100\"\n style={{\n left: 0,\n }}>\n <div\n className={`absolute top-0 left-0 bottom-0 overflow-hidden w-100 flex items-center align-center justify-center ${\n disabled ? 'c-on-disabled' : 'c-on-action-primary'\n }`}\n style={{ transition: 'right 110ms ease-in-out 30ms' }}>\n {checked ? (\n <CheckIcon size={12} color=\"currentColor\" />\n ) : (\n partial && (\n <CheckPartial\n size={12}\n color={disabled ? '#979899' : '#1346d8'}\n />\n )\n )}\n </div>\n </div>\n <input\n checked={checked}\n ref={forwardedRef}\n className={classNames('h1 w1 absolute o-0', {\n pointer: !disabled,\n })}\n disabled={disabled}\n required={required}\n id={id}\n name={name}\n onChange={this.handleChange}\n type=\"checkbox\"\n value={value}\n tabIndex={0}\n />\n </div>\n {label && (\n <label\n className={classNames(\n { 'c-disabled': disabled },\n { 'c-on-base pointer': !disabled }\n )}\n htmlFor={id}>\n {label}\n </label>\n )}\n </div>\n )\n }\n}\n\nCheckbox.defaultProps = {\n checked: false,\n disabled: false,\n required: false,\n partial: false,\n}\n\nCheckbox.propTypes = {\n /** (Input spec attribute) */\n checked: PropTypes.bool,\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** (Input spec attribute) */\n disabled: PropTypes.bool,\n /** (Input spec attribute) */\n id: PropTypes.string.isRequired,\n /** Checkbox label */\n label: PropTypes.node,\n /** (Input spec attribute) */\n name: PropTypes.string.isRequired,\n /** onChange event */\n onChange: PropTypes.func.isRequired,\n /** (Input spec attribute) */\n required: PropTypes.bool,\n /** (Input spec attribute) */\n value: PropTypes.string,\n /** Partial state */\n partial: PropTypes.bool,\n}\n\nexport default withForwardedRef(Checkbox)\n\n```" } ]
code_store-on-localhost_7cec8dd1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Checkbox/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Checkbox represents a need for the user to do a choice that is binary, required and independent from other choices.\n\n### ๐Ÿ‘ Dos\n\n- Initialize it with a default value that makes sense to your needs.\n- Use a text label, which should be intuitive and provide sufficient context for the user take that decision.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't use negative labels because they are harder to interpret.\n- Don't implement an \"autosave\" behavior: checkboxes should always require the use of a button (like \"SAVE\" or \"OK\") to commit the choice.\n\n### Related components\n\n- Consider using a <a href=\"#/Components/Forms/Toggle\">Toggle</a> if the choice could be read as \"turning something on or off\".\n- If the checkboxes are related, you can consider the use of a <a href=\"#/Components/Forms/CheckboxGroup\">CheckboxGroup</a>\n\nDefault\n\n```js\ninitialState = { check1: true, check2: false, check3: false }\n;<div>\n <div className=\"mb3\">\n <Checkbox\n checked={state.check1}\n id=\"option-0\"\n label=\"Checked\"\n name=\"default-checkbox-group\"\n onChange={e => setState({ check1: !state.check1 })}\n value=\"option-0\"\n />\n </div>\n <div className=\"mb3\">\n <Checkbox\n checked={state.check2}\n partial={true}\n id=\"option-3\"\n label=\"Partial\"\n name=\"default-checkbox-group\"\n onChange={e => setState({ check2: !state.check2 })}\n value=\"option-3\"\n />\n </div>\n <Checkbox\n checked={state.check3}\n id=\"option-1\"\n label=\"Not checked\"\n name=\"default-checkbox-group\"\n onChange={e => setState({ check3: !state.check3 })}\n value=\"option-1\"\n />\n</div>\n```\n\nDisabled\n\n```js\n<div>\n <div className=\"mb3\">\n <Checkbox\n checked={true}\n disabled\n label=\"Option 1\"\n id=\"option-1\"\n name=\"disabled-checkbox-group\"\n onChange={() => {}}\n value=\"option-1\"\n />\n </div>\n <div className=\"mb3\">\n <Checkbox\n checked={false}\n partial={true}\n disabled\n label=\"Option 2\"\n id=\"option-2\"\n name=\"disabled-checkbox-group\"\n onChange={() => {}}\n value=\"option-2\"\n />\n </div>\n <Checkbox\n checked={false}\n disabled\n label=\"Option 3\"\n id=\"option-3\"\n name=\"disabled-checkbox-group\"\n onChange={() => {}}\n value=\"option-3\"\n />\n</div>\n```\n\nWithout label\n\n```js\ninitialState = { check1: true, check2: false, check3: false }\n;<div>\n <div className=\"mb3\">\n <Checkbox\n checked={state.check1}\n name=\"disabled-checkbox-group\"\n onChange={e => setState({ check1: !state.check1 })}\n value=\"option-0\"\n id=\"option-0\"\n />\n </div>\n <div className=\"mb3\">\n <Checkbox\n checked={state.check2}\n partial={true}\n name=\"disabled-checkbox-group\"\n onChange={e => setState({ check2: !state.check2 })}\n value=\"option-1\"\n id=\"option-1\"\n />\n </div>\n <Checkbox\n checked={state.check3}\n name=\"disabled-checkbox-group\"\n onChange={e => setState({ check3: !state.check3 })}\n value=\"option-2\"\n id=\"option-2\"\n />\n</div>\n```\n\n```" } ]
code_store-on-localhost_5adb766b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Statement/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport SubjectAtom, { SubjectOptions } from './Atoms/SubjectAtom'\nimport VerbAtom from './Atoms/VerbAtom'\nimport ObjectAtom from './Atoms/ObjectAtom'\n\ntype Props = {\n isFullWidth?: boolean\n isRtl?: boolean\n omitSubject?: boolean\n omitVerbs?: boolean\n onChangeStatement: (statement: Props['statement']) => void\n options: SubjectOptions\n statement?: {\n subject: string\n verb: string\n object?: unknown\n error?: string\n }\n subjectPlaceholder: string\n}\n\nconst Statement: React.FC<Props> = ({\n isFullWidth = false,\n isRtl,\n omitSubject,\n omitVerbs,\n onChangeStatement,\n options,\n statement = { subject: '', verb: '', object: null, error: null },\n subjectPlaceholder,\n}) => {\n const verbOptions =\n statement.subject &&\n options[statement.subject].verbs.find(verb => verb.value === statement.verb)\n const statementAtoms = [\n !omitSubject && (\n <SubjectAtom\n key=\"subject\"\n isFullWidth={isFullWidth}\n onChange={subject => {\n const newStatement = {\n ...statement,\n subject,\n verb: options[subject].verbs[0].value,\n object: null,\n error: null,\n }\n onChangeStatement(newStatement)\n }}\n options={options}\n placeholder={subjectPlaceholder}\n subject={statement.subject}\n />\n ),\n !omitVerbs && (\n <VerbAtom\n key=\"verb\"\n disabled={!statement.subject}\n isFullWidth={isFullWidth}\n onChange={verb => {\n const newStatement = {\n ...statement,\n verb,\n object: null,\n error: null,\n }\n onChangeStatement(newStatement)\n }}\n verb={statement.verb}\n verbOptions={statement.subject ? options[statement.subject].verbs : []}\n />\n ),\n <ObjectAtom\n key=\"object\"\n disabled={!statement.verb}\n error={statement.error}\n object={statement.object}\n onChange={(object, error = null) => {\n const newStatement = {\n ...statement,\n object,\n error,\n }\n onChangeStatement(newStatement)\n }}\n renderObject={verbOptions && verbOptions.object}\n />,\n ]\n\n return (\n <div className=\"flex-column w-100 mv6 mv3-ns\">\n <div\n className={`flex w-100 items-start ${\n isFullWidth ? 'flex-column items-stretch' : ''\n }`}>\n {isRtl ? statementAtoms.reverse() : statementAtoms}\n </div>\n {statement.error && (\n <div className=\"red t-small mh3 mt2 lh-title\">{statement.error}</div>\n )}\n </div>\n )\n}\n\nexport default Statement\n\n```" } ]
code_store-on-localhost_51ccfa9e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Statement/typings.d.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type SelectOption<T> = {\n label: string\n value: T\n}\n\nexport type SelectOptionGroup = {\n label: string\n options: SelectOption[]\n}\n\nexport type GroupedOptions = {\n [group: string]: SelectOption[]\n}\n\nexport type SelectedOption = {\n group: SelectOptionGroup['label']\n option: SelectOption\n}\n\n```" } ]
code_store-on-localhost_3123ef30
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/InputButton/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Input from '../Input'\nimport { withForwardedRef } from '../../modules/withForwardedRef'\n\nclass InputButton extends Component {\n render() {\n const { button, isLoading, ...props } = this.props\n\n return (\n <div>\n <Input {...props} button={button} isLoadingButton={isLoading} />\n </div>\n )\n }\n}\n\nInputButton.defaultProps = {\n isLoading: false,\n}\n\nInputButton.propTypes = {\n /** (InputButton spec attribute) */\n button: PropTypes.string,\n /** Loading state */\n isLoading: PropTypes.bool,\n}\n\nexport default withForwardedRef(InputButton)\n\n```" } ]
code_store-on-localhost_6f507c3b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/InputButton/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nIn addition to the props above, InputButton accepts all the props the Input component does.\n\n#### A input with a button should be used in scenarios where the field needs its own button. Newsletter sign up, postal code input and promo code application are some common use case examples.\n\n### ๐Ÿ‘ Dos\n\n- Use it when more fields will be loaded below after submission, or when what was typed will be applied.\n- Use it when you have an input and a button in-line and the button is directly related to the input.\n- Use it in its large size when it's you might need to call attention to the input's existance or it carries importance in the context.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't use it exclusively for validating information that has been typed, prefer to do that automatically.\n- Don't use it in situations where the input might be read-only or when there's more than one button directly related to the input.\n- Don't use it in cramped spaces where the user might not be able to comfortably type the expected response, prefer to use the default input with a button below.\n\n### Related components\n\n- Consider using a <a href=\"#/Components/Forms/Input\">default input</a> with a sufix if you need to display information (e.g. tooltip) that doesn't qualify as a action.\n- Use a <a href=\"#/Components/Forms/InputSearch\">InputSearch</a> for search purposes or a <a href=\"#/Components/Forms/InputPassword\">InputPassword</a> for password purposes.\n\nWith submit button\n\n```js\n;<div>\n <div className=\"mb5\">\n <InputButton placeholder=\"Placeholder\" size=\"regular\" label=\"Regular\" button=\"Submit\" />\n </div>\n <div className=\"mb5\">\n <InputButton placeholder=\"Placeholder\" size=\"large\" label=\"Large\" button=\"Submit\" />\n </div>\n</div>\n```\n\nLoading state\n\n```js\ninitialState = { isLoading: false };\n<form onSubmit={\n (e) => {\n e.preventDefault\n setState({ isLoading: true })\n setTimeout(() => { setState({ isLoading: false }) }, 1200)\n }\n }>\n <div className=\"mb5\">\n <InputButton\n placeholder=\"Placeholder\"\n size=\"regular\"\n label=\"Regular loading\"\n button=\"Submit\"\n isLoading={state.isLoading}\n />\n </div>\n</form>\n```\n\nDisabled\n\n```js\n;<div>\n <div className=\"mb5\">\n <InputButton placeholder=\"Placeholder\" size=\"regular\" label=\"Regular disabled\" button=\"Submit\" disabled />\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_69b772dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Slider/Selector.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nexport default function Selector({\n onDragStart,\n position,\n active,\n disabled,\n value,\n displayPopup,\n formatValue,\n offset,\n icon,\n}) {\n const containerClasses = classNames(\n 'vtex-slider__selector-container absolute pointer',\n {\n 'z-2': active,\n 'z-1': !active,\n 'left-0': position === 'left',\n 'right-0': position === 'right',\n }\n )\n\n const containerStyle =\n position === 'left'\n ? { transform: `translateX(${offset}px) translateX(-50%)` }\n : { transform: `translateX(-${offset}px) translateX(50%)` }\n\n const dragCircleClasses = classNames(\n 'vtex-slider__selector br-100 bg-action-primary flex justify-center items-center',\n {\n 'bg-action-primary': active && !disabled,\n }\n )\n\n const popupClasses = classNames(\n 'vtex-slider__selector-tooltip flex justify-center items-center relative ph3 pv2 br2 t-small ba',\n {\n 'vtex-slider__tooltip--active bg-action-primary white b--action-primary': active,\n 'bg-base b--muted-2 c-muted-1': !active,\n }\n )\n\n return (\n <div\n className={containerClasses}\n onMouseDown={onDragStart(position)}\n onTouchStart={onDragStart(position)}\n style={{\n ...containerStyle,\n willChange: 'transform',\n top: 6.5,\n }}>\n {(active || displayPopup) && (\n <div className=\"absolute pb4\" style={{ left: '50%', bottom: '100%' }}>\n <div className={popupClasses} style={{ left: '-50%' }}>\n {formatValue(value)}\n </div>\n </div>\n )}\n <div\n className={dragCircleClasses}\n style={{\n height: '0.75rem',\n width: '0.75rem',\n boxShadow: '-1px 1px 3px rgba(0, 0, 0, 0.15)',\n }}>\n {icon}\n </div>\n </div>\n )\n}\n\nSelector.defaultProps = {\n active: false,\n disabled: false,\n value: 0,\n className: '',\n displayPopup: false,\n icon: null,\n}\n\nSelector.propTypes = {\n /** Position of the selector */\n position: PropTypes.oneOf(['left', 'right']).isRequired,\n /** onDragStart event */\n onDragStart: PropTypes.func.isRequired,\n /** If the selector is active */\n active: PropTypes.bool,\n /** If the selector is disabled */\n disabled: PropTypes.bool,\n /** Current value of the selector */\n value: PropTypes.number,\n /** Whether the popup is displayed when inactive */\n displayPopup: PropTypes.bool,\n /** Function to format the value */\n formatValue: PropTypes.func.isRequired,\n /** Margin offset value */\n offset: PropTypes.number.isRequired,\n /** Icon to show inside the handle */\n icon: PropTypes.node,\n}\n\n```" } ]
code_store-on-localhost_1237054b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Slider/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\n\nimport Selector from './Selector'\n\nconst UP_EVENTS = ['mouseup', 'pointerup', 'touchend']\n\nconst MOVE_EVENT_MAP = {\n mousedown: 'mousemove',\n touchstart: 'touchmove',\n pointerdown: 'pointermove',\n}\n\n/**\n * Round the value to the nearest step multiple\n */\nfunction quantize(value, step) {\n const numSteps = Math.round(value / step)\n const quantizedVal = numSteps * step\n\n return quantizedVal\n}\n\n/**\n * Get the event pageX attribute, with support for mobile events\n */\nfunction getPageX(evt) {\n if (evt.targetTouches && evt.targetTouches.length > 0) {\n return evt.targetTouches[0].pageX\n }\n\n return evt.pageX\n}\n\n/**\n * Check for the esc key event\n */\nfunction isEscKeyEvent(evt) {\n return evt.key === 'Escape' || evt.keyCode === 27\n}\n\nexport default class Slider extends Component {\n sliderRef = React.createRef()\n\n state = {\n dragging: null,\n translate: {\n left: 0,\n right: 0,\n },\n values: {\n left:\n this.props.defaultValues && this.props.defaultValues.length > 0\n ? this.props.defaultValues[0]\n : this.props.min,\n right:\n this.props.range &&\n this.props.defaultValues &&\n this.props.defaultValues.length >= 2\n ? this.props.defaultValues[1]\n : this.props.max,\n },\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.min !== this.props.min || prevProps.max !== this.props.max) {\n this.setState(\n {\n translate: {\n left: 0,\n right: 0,\n },\n values: {\n left: this.props.min,\n right: this.props.max,\n },\n },\n this.updateLayout\n )\n }\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.updateLayout)\n\n if (this.props.defaultValues && this.props.defaultValues.length > 0) {\n this.updateLayout()\n }\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.updateLayout)\n\n if (this.cancelDragEvent_) {\n this.cancelDragEvent_()\n this.cancelDragEvent_ = undefined\n }\n }\n\n updateLayout = () => {\n this.updatePositionForValue(this.state.values.left, 'left')\n this.updatePositionForValue(this.state.values.right, 'right')\n }\n\n getValueForPercent = (percentageComplete, position) => {\n const { min, max, step, range } = this.props\n\n const rawValue = min + percentageComplete * (max - min)\n\n let value\n\n if (rawValue !== min && rawValue !== max) {\n value = quantize(rawValue, step)\n } else {\n value = rawValue\n }\n\n if (value < min) {\n value = min\n } else if (value > max) {\n value = max\n }\n\n if (!range) {\n return value\n }\n\n if (position === 'left' && value >= this.state.values.right) {\n value = this.state.values.right - step\n } else if (position === 'right' && value <= this.state.values.left) {\n value = this.state.values.left + step\n }\n\n return value\n }\n\n getTranslateValueForInputValue = (value, position) => {\n const { max, min } = this.props\n const rect = this.sliderRef.current.getBoundingClientRect()\n const percentageComplete = (value - min) / (max - min)\n\n let translatePx = percentageComplete * rect.width\n\n if (position === 'right') {\n translatePx = rect.width - translatePx\n }\n\n return translatePx\n }\n\n handleSliderMouseDown = e => {\n const rect = this.sliderRef.current.getBoundingClientRect()\n const xPos = getPageX(e) - rect.left\n\n const leftPos = this.state.translate.left\n const rightPos = rect.width - this.state.translate.right\n\n let nearestPoint\n\n // Which one has a absolute value closer to 0\n if (\n !this.props.range ||\n Math.abs(leftPos - xPos) < Math.abs(rightPos - xPos)\n ) {\n nearestPoint = 'left'\n } else {\n nearestPoint = 'right'\n }\n\n this.handleDragStart(nearestPoint)(e)\n }\n\n handleDragStart = position => e => {\n e.stopPropagation()\n\n // allow only one handle to be dragged at a time\n if (this.props.disabled || this.state.dragging) {\n return\n }\n\n this.setState({\n dragging: position,\n })\n\n this.valuesBeforeDrag_ = this.state.values\n\n // https://reactjs.org/docs/events.html#event-pooling\n e.persist()\n\n const moveHandler = this.handleDrag(position)\n\n // The events bellow are attached to the body because we need\n // to support the dragging event *outside* of the slider bounds\n\n this.cancelDragEvent_ = () => {\n this.valuesBeforeDrag_ = undefined\n UP_EVENTS.forEach(evtName =>\n document.body.removeEventListener(evtName, handleUpEvent)\n )\n document.body.removeEventListener(MOVE_EVENT_MAP[e.type], moveHandler)\n document.body.removeEventListener('keydown', this.handleKeyDown)\n }\n\n const handleUpEvent = () => {\n this.cancelDragEvent_()\n this.handleDragEnd()\n }\n\n UP_EVENTS.forEach(evtName =>\n document.body.addEventListener(evtName, handleUpEvent)\n )\n document.body.addEventListener(MOVE_EVENT_MAP[e.type], moveHandler)\n document.body.addEventListener('keydown', this.handleKeyDown)\n\n this.updatePositionFromEvent(e, position)\n }\n\n updatePositionFromEvent = (e, position) => {\n const slider = this.sliderRef.current\n const rect = slider.getBoundingClientRect()\n\n const xPos = getPageX(e) - rect.left\n\n const percentageComplete = xPos / rect.width\n\n const value = this.getValueForPercent(percentageComplete, position)\n\n this.updatePositionForValue(value, position)\n }\n\n handleDrag = position => e => {\n e.preventDefault()\n this.updatePositionFromEvent(e, position)\n }\n\n updatePositionForValue = (value, position) => {\n const translatePx = this.getTranslateValueForInputValue(value, position)\n\n requestAnimationFrame(() => {\n this.setState({\n values: {\n ...this.state.values,\n [position]: value,\n },\n translate: {\n ...this.state.translate,\n [position]: translatePx,\n },\n })\n })\n }\n\n handleDragEnd = () => {\n this.setState({\n dragging: null,\n })\n\n this.cancelDragEvent_ = undefined\n\n if (this.props.range) {\n this.props.onChange([this.state.values.left, this.state.values.right])\n } else {\n this.props.onChange([this.state.values.left])\n }\n }\n\n handleKeyDown = evt => {\n if (!isEscKeyEvent(evt) || !this.state.dragging) {\n return\n }\n\n this.setState({\n dragging: false,\n values: this.valuesBeforeDrag_,\n })\n\n this.cancelDragEvent_()\n this.cancelDragEvent = undefined\n\n this.updateLayout()\n }\n\n render() {\n const {\n disabled,\n alwaysShowCurrentValue,\n formatValue,\n range,\n handleIcon,\n } = this.props\n const { left, right } = this.state.translate\n\n const lastLeftValue = this.valuesBeforeDrag_\n ? this.valuesBeforeDrag_.left\n : this.state.values.left\n const lastRightValue = this.valuesBeforeDrag_\n ? this.valuesBeforeDrag_.right\n : this.state.values.right\n\n const sliderSelectionStyle = range\n ? { left, right }\n : { left: 0, width: left }\n\n return (\n <div className=\"vtex-slider-container\">\n <div\n className=\"vtex-slider w-100 relative pointer\"\n style={{\n height: 24,\n // since we can't include css with the components, the\n // prefixed attributes need to be included\n MozUserSelect: 'none',\n msUserSelect: 'none',\n WebkitUserSelect: 'none',\n userSelect: 'none',\n }}\n onMouseDown={this.handleSliderMouseDown}\n onTouchStart={this.handleSliderMouseDown}>\n <div\n ref={this.sliderRef}\n className=\"vtex-slider__base w-100 bg-muted-4 absolute br-pill overflow-hidden\"\n style={{\n height: '0.25rem',\n top: '0.7rem',\n }}>\n <div\n className={classNames('absolute h-100', {\n 'bg-action-primary': !disabled,\n 'bg-muted-4': disabled,\n })}\n style={sliderSelectionStyle}\n />\n </div>\n <Selector\n offset={left}\n onDragStart={this.handleDragStart}\n position=\"left\"\n active={this.state.dragging === 'left'}\n displayPopup={alwaysShowCurrentValue}\n value={this.state.values.left}\n formatValue={formatValue}\n icon={handleIcon}\n />\n {range && (\n <Selector\n offset={right}\n onDragStart={this.handleDragStart}\n position=\"right\"\n active={this.state.dragging === 'right'}\n displayPopup={alwaysShowCurrentValue}\n value={this.state.values.right}\n formatValue={formatValue}\n icon={handleIcon}\n />\n )}\n </div>\n\n <div className=\"flex justify-end\">\n <label className=\"t-small c-muted-1\">\n {formatValue(lastLeftValue)}\n </label>\n {range && (\n <label className=\"t-small c-muted-1\">\n <span className=\"mh2\">&ndash;</span>\n {formatValue(lastRightValue)}\n </label>\n )}\n </div>\n </div>\n )\n }\n}\n\nSlider.defaultProps = {\n min: 0,\n max: 10,\n step: 1,\n onChange: () => {},\n alwaysShowCurrentValue: false,\n formatValue: a => a,\n range: false,\n handleIcon: null,\n}\n\nSlider.propTypes = {\n /** Minimum supported value */\n min: PropTypes.number,\n /** Maximum supported value */\n max: PropTypes.number,\n /** onChange event */\n onChange: PropTypes.func,\n /** Step value */\n step: PropTypes.number,\n /** Whether the slider is disabled */\n disabled: PropTypes.bool,\n /** Initial values */\n defaultValues: PropTypes.arrayOf(PropTypes.number),\n /** Whether to always display current value as a popup */\n alwaysShowCurrentValue: PropTypes.bool,\n /** Function to customize the format of the value */\n formatValue: PropTypes.func,\n /** Whether to render as a range input */\n range: PropTypes.bool,\n /** Optional icon to show inside the slider handle */\n handleIcon: PropTypes.node,\n}\n\n```" } ]
code_store-on-localhost_ec9923af
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Slider/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nSimple slider\n\n```jsx\n<Slider\n onChange={([value]) => {}}\n min={0}\n max={99}\n step={1}\n disabled={false}\n defaultValues={[0]}\n alwaysShowCurrentValue={false}\n formatValue={a => a + 1}\n/>\n```\n\nRange slider\n\n```jsx\n<Slider\n onChange={([leftValue, rightValue]) => {}}\n min={0}\n max={99}\n step={1}\n disabled={false}\n defaultValues={[0, 50]}\n alwaysShowCurrentValue={false}\n formatValue={a => a + 1}\n range\n/>\n```\n\n```" } ]
code_store-on-localhost_e8e7306e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/PageHeader/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nimport ArrowBack from '../icon/ArrowBack'\nimport Button from '../Button'\n\nclass PageHeader extends PureComponent {\n handleClick = e => {\n this.props.onLinkClick && this.props.onLinkClick(e)\n }\n\n render() {\n const { linkLabel, children, subtitle } = this.props\n\n return (\n <div className=\"vtex-pageHeader__container pa5 pa7-ns\">\n {linkLabel && (\n <div className=\"vtex-pageHeader-link__container\">\n <Button\n size=\"small\"\n variation=\"tertiary\"\n neutral\n onClick={this.handleClick}>\n <span\n className=\"flex align-baseline relative\"\n style={{ marginLeft: '-16px' }}>\n <span className=\"mr3\">\n <ArrowBack color=\"currentColor\" />\n </span>\n {linkLabel}\n </span>\n </Button>\n </div>\n )}\n\n <div\n className={`c-on-base flex flex-wrap flex-row justify-between\n ${linkLabel ? 'mt0' : 'mt7'}`}>\n <div className=\"vtex-pageHeader__title t-heading-2 order-0 flex-grow-1\">\n {this.props.title}\n </div>\n {children && (\n <div\n className={`vtex-pageHeader__children order-2 order-0-ns ${\n subtitle ? 'mt5' : ''\n } mt0-ns`}>\n {children}\n </div>\n )}\n <div className=\"w-100\" style={{ height: 0 }} />\n {subtitle && (\n <div className=\"vtex-pageHeader__subtitle t-body lh-copy c-muted-1 mv5 order-1 order-0-ns\">\n {subtitle}\n </div>\n )}\n </div>\n </div>\n )\n }\n}\n\nPageHeader.propTypes = {\n /** Title for the header */\n title: PropTypes.node.isRequired,\n /** Subtitle for the header */\n subtitle: PropTypes.node,\n /** Label for the back button */\n linkLabel: PropTypes.node,\n onLinkClick: PropTypes.func,\n children: PropTypes.node,\n}\n\nexport default PageHeader\n\n```" } ]
code_store-on-localhost_c4a8692a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/PageHeader/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A simple header for Admin modules and Apps with simple navigation needs.\n\n### ๐Ÿ‘ Dos\n\n- Keep the page title short. It's a title, after all. Use the module name in the title if it's the first page.\n- Use the previous page title as the label of the back link.\n- Use the main action button if it's clear what would be the most import action of the entire page. Otherwise just don't.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't change dynamically the main page action upon action on the page. The main action should be as static as the title is.\n\n### Related components\n\n<a href=\"#/Components/Navigation/Tabs\">Tabs</a> may be used in composition with the PageHeader for the main navigation.\n\nDefault\n\n```js\n<PageHeader title=\"Orders\" />\n```\n\nWith link\n\n```js\n<PageHeader\n title=\"Order details\"\n linkLabel=\"Orders\"\n onLinkClick={e => {\n console.log(e)\n }}\n/>\n```\n\nWith children\n\n```js\nconst Button = require('../Button').default\n\n;<PageHeader\n title=\"Order details\"\n linkLabel=\"Orders\"\n onLinkClick={e => {\n console.log(e)\n }}>\n <span className=\"mr4\">\n <Button variation=\"secondary\">Secondary</Button>\n </span>\n\n <Button variation=\"primary\">Primary</Button>\n</PageHeader>\n```\n\nWith children and subtitle\n\n```js\nconst Button = require('../Button').default\n\n;<PageHeader\n title=\"Order details\"\n subtitle=\"Some explanation or description for your page\"\n linkLabel=\"Orders\"\n onLinkClick={e => {\n console.log(e)\n }}>\n <span className=\"mr4\">\n <Button variation=\"secondary\">Secondary</Button>\n </span>\n\n <Button variation=\"primary\">Primary</Button>\n</PageHeader>\n```\n\n```" } ]
code_store-on-localhost_d9dc398b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/utils/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nexport const childrenOf = (...types) => {\n const fieldType = PropTypes.shape({\n type: PropTypes.oneOf(types),\n })\n\n return PropTypes.oneOfType([fieldType, PropTypes.arrayOf(fieldType)])\n}\n\n```" } ]
code_store-on-localhost_59e8e905
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/utils/zIndex.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default {\n modal: 10000,\n tooltip: 11000,\n}\n\n```" } ]
code_store-on-localhost_16db918d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/utils/react.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value)\n } else if (ref) {\n ref.current = value\n }\n}\n\n```" } ]
code_store-on-localhost_f53bb933
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/utils/withDeviceHoc.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useMedia } from 'use-media'\n\nexport enum Device {\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n}\n\nconst withDevice = Component => {\n function WithDevice(props) {\n // Taken at https://github.com/vtex-apps/device-detector/blob/master/react/useDevice.tsx#L22\n const isScreenMedium = useMedia({ minWidth: '40rem' })\n const isScreenLarge = useMedia({ minWidth: '64.1rem' })\n\n const device = isScreenLarge\n ? Device.desktop\n : isScreenMedium\n ? Device.tablet\n : Device.phone\n\n const isMobile = device.toLowerCase() === 'phone'\n\n return <Component device={device} isMobile={isMobile} {...props} />\n }\n\n return WithDevice\n}\n\nexport default withDevice\n\n```" } ]
code_store-on-localhost_e86d4a71
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Spinner/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport { baseClassname } from '../icon/utils'\n\nconst radius = 40\nconst circ = 2 * radius * Math.PI\n\nclass Spinner extends React.Component {\n render() {\n const { color, size, block } = this.props\n\n return (\n <svg\n className={`${baseClassname('spinner')} ${\n !color ? 'c-action-primary' : ''\n } ${block ? 'db' : ''}`}\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 100 100\"\n preserveAspectRatio=\"xMidYMid\"\n height={size}\n width={size}>\n <style>\n {`\n @keyframes vtex-spinner-rotate {\n from {\n transform-origin: 50% 50%;\n transform: rotate(0deg);\n }\n to {\n transform-origin: 50% 50%;\n transform: rotate(360deg);\n }\n }\n\n @keyframes vtex-spinner-fill {\n 0% {\n stroke-dasharray: 0 0 2 ${circ};\n }\n 50% {\n stroke-dasharray: 0 0 ${circ * 0.75} ${circ};\n }\n 100% {\n stroke-dasharray: 0 ${circ - 2} ${circ * 0.75} ${circ};\n }\n }\n\n .vtex-spinner_circle {\n animation: vtex-spinner-fill 1.25s infinite cubic-bezier(0.455, 0.030, 0.515, 0.955), vtex-spinner-rotate 0.625s infinite linear;\n }\n `}\n </style>\n\n <circle\n className=\"vtex-spinner_circle\"\n cx=\"50\"\n cy=\"50\"\n fill=\"none\"\n r={radius}\n stroke={color || 'currentColor'}\n strokeWidth=\"10\"\n strokeDasharray={`0 0 ${circ * 0.75} ${circ}`}\n strokeLinecap=\"round\"\n strokeDashoffset=\"1\"\n />\n </svg>\n )\n }\n}\n\nSpinner.propTypes = {\n /** Color of the spinner */\n color: PropTypes.string,\n /** Size (diameter) of the spinner */\n size: PropTypes.number,\n /** Sets the display to block */\n block: PropTypes.bool,\n}\n\nSpinner.defaultProps = {\n block: false,\n size: 40,\n}\n\nexport default Spinner\n\n```" } ]
code_store-on-localhost_5de0e370
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Spinner/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Spinner is a way of showing the user something is being loaded, either because of a user action or not. It should be used for short, indeterminate loading times.\n\n### ๐Ÿ‘ Dos\n\n- Mind the color contrast with the background.\n- For very long waiting times (10+ seconds) try giving some feedback about the progress that is being made in the background.\n- If you're showing a spinner in a button make sure to make it disabled while loading.\n- For very recurrent actions where the probability of success if very high consider using an optimistic approach. E.g.: a message being sent.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Only use spinners for loading times of more than 1 second. Less than that it'll cause more harm than good.\n- Avoid showing too many spinners at a given time in the same screen, it'll look overwhelming.\n\n### Related components\n\n- If you can assess the progression of the task prefer a <a href=\"#/Components/Display/ProgressBar\">Progress Bar</a>.\n- For whole screen loading try using Skeleton Pages (work in progress).\n\n#### Default\n\n```js\n<Spinner />\n```\n\n#### Custom color and size\n\n```js\n<span className=\"dib c-muted-1\">\n <Spinner color=\"currentColor\" size={20} />\n</span>\n```\n\n```" } ]
code_store-on-localhost_77bf09c7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/InputSearch/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Input from '../Input'\nimport SearchIcon from '../icon/Search'\nimport ClearIcon from '../icon/Clear'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass InputSearch extends Component {\n constructor(props) {\n super(props)\n this.state = {\n hover: false,\n focus: false,\n }\n }\n\n static iconSizes = {\n small: 14,\n regular: 16,\n large: 18,\n }\n static separatorHeight = {\n small: 28,\n regular: 36,\n large: 44,\n }\n\n handleClickClear = event => {\n this.props.onChange &&\n this.props.onChange({\n ...event,\n target: {\n ...event.target,\n value: '',\n },\n })\n this.props.onClear && this.props.onClear(event)\n }\n\n handleSubmit = event => {\n const { onSubmit, value } = this.props\n onSubmit &&\n onSubmit({\n ...event,\n target: {\n ...event.target,\n value,\n },\n preventDefault: event.preventDefault || (() => {}),\n })\n }\n\n handleHovering = hover => {\n this.setState({ hover })\n }\n\n handleFocus = focus => {\n this.setState({ focus })\n }\n\n render() {\n const { hover, focus } = this.state\n const { size } = this.props\n const iconSize =\n InputSearch.iconSizes[size] || InputSearch.iconSizes.regular\n\n return (\n <Input\n {...this.props}\n onFocus={() => this.handleFocus(true)}\n onBlur={() => this.handleFocus(false)}\n onMouseEnter={() => this.handleHovering(true)}\n onMouseLeave={() => this.handleHovering(false)}\n onKeyUp={e => e.key === 'Enter' && this.handleSubmit(e)}\n type=\"search\"\n suffix={\n <div className=\"flex flex-row items-center\">\n {this.props.value && (\n <span\n tabIndex={0}\n onClick={this.handleClickClear}\n className=\"pointer mr4 c-muted-3\">\n <ClearIcon size={iconSize} />\n </span>\n )}\n <div\n className={`mh2 bw1 bl ${\n focus ? 'b--muted-2' : hover ? 'b--muted-3' : 'b--muted-4'\n }`}\n style={{\n height:\n InputSearch.separatorHeight[size] ||\n InputSearch.separatorHeight.regular,\n }}\n />\n <span className=\"pointer pl4 c-link\" onClick={this.handleSubmit}>\n <SearchIcon size={iconSize} />\n </span>\n </div>\n }\n />\n )\n }\n}\n\nInputSearch.propTypes = {\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n onChange: PropTypes.func,\n onSubmit: PropTypes.func,\n onClear: PropTypes.func,\n size: PropTypes.string,\n value: PropTypes.string,\n}\n\nexport default withForwardedRef(InputSearch)\n\n```" } ]
code_store-on-localhost_b344dd5c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/InputSearch/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nSizes\n\n```js\ninitialState = { value1: '', value2: '', value3: '' }\n;<div>\n <InputSearch\n placeholder=\"Search...\"\n value={state.value1}\n label=\"Small\"\n size=\"small\"\n onChange={e => setState({ value1: e.target.value })}\n onSubmit={e => {\n e.preventDefault()\n console.log('submited! search this: ', e.target.value)\n }}\n />\n <br />\n <InputSearch\n placeholder=\"Search...\"\n value={state.value2}\n label=\"Regular\"\n size=\"regular\"\n onChange={e => setState({ value2: e.target.value })}\n onSubmit={e => {\n e.preventDefault()\n console.log('submited! search this: ', e.target.value)\n }}\n />\n <br />\n <InputSearch\n placeholder=\"Search...\"\n value={state.value3}\n label=\"Large\"\n size=\"large\"\n onChange={e => setState({ value3: e.target.value })}\n onSubmit={e => {\n e.preventDefault()\n console.log('submited! search this: ', e.target.value)\n }}\n />\n</div>\n```\n\n```" } ]
code_store-on-localhost_44353b3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ProgressBar/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport Progress from '../Progress'\nimport deprecated from '../../modules/deprecated'\n\nexport default deprecated({\n useNewComponent: {\n old: 'ProgressBar',\n new: 'Progress',\n },\n} as any)(Progress)\n\n```" } ]
code_store-on-localhost_a51ca42f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Toggle/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport DenyIcon from '../icon/Deny'\nimport CheckIcon from '../icon/Check'\n\nclass Toggle extends Component {\n componentDidMount() {\n if (this.props.size === 'small') {\n console.warn(\n 'Toggle: value \"small\" for the prop \"size\" is deprecatedโ€”the default \"regular\" size is now equivalent to what the size \"small\" was previously.'\n )\n }\n }\n\n render() {\n const {\n semantic,\n disabled,\n id,\n checked,\n label,\n size,\n helpText,\n } = this.props\n\n let labelClass = disabled ? 'c-disabled ' : 'c-on-base '\n let classes = 'flex items-center relative br4 '\n let circleClasses = 'absolute br-100 '\n let iconDenyClasses = 'absolute flex justify-center '\n let iconCheckClasses = 'absolute flex justify-center '\n\n let circleStyle = {\n boxShadow: disabled ? 'none' : '0 0 10px rgba(0,0,0,0.2)',\n transform: 'scale(0.8)',\n transition: 'all .1s ease-out',\n }\n let iconStyle = {\n transition: 'left .1s ease-out, opacity .1s ease-in-out',\n }\n\n // Background\n if (semantic) {\n if (!disabled) {\n iconCheckClasses += 'c-success '\n iconDenyClasses += 'c-danger '\n\n if (!checked) {\n classes += 'bg-danger '\n iconDenyClasses += 'o-100 '\n iconCheckClasses += 'o-0 '\n } else {\n classes += 'bg-success '\n iconDenyClasses += 'o-0 '\n iconCheckClasses += 'o-100 '\n }\n } else {\n classes += 'bg-disabled '\n iconCheckClasses += 'c-on-disabled '\n iconDenyClasses += 'c-on-disabled '\n\n if (!checked) {\n iconDenyClasses += 'o-100 '\n iconCheckClasses += 'o-0 '\n } else {\n iconDenyClasses += 'o-0 '\n iconCheckClasses += 'o-100 '\n }\n }\n } else if (disabled) {\n classes += 'bg-disabled '\n } else {\n if (!checked) {\n classes += 'bg-muted-2 '\n }\n\n if (checked) {\n classes += 'bg-action-primary '\n }\n }\n\n // Circle\n if (disabled) {\n circleClasses += 'bg-muted-3 '\n } else {\n circleClasses += 'bg-base '\n }\n\n let style = {\n transition: 'background 100ms ease-out',\n }\n\n let checkedOffset\n\n switch (size) {\n case 'large':\n classes += 'h2 '\n circleClasses += 'h2 w2 '\n iconDenyClasses += 'w2 '\n iconCheckClasses += 'w2 '\n\n labelClass += 'ml5 '\n\n style = {\n ...style,\n minWidth: '3.5rem',\n }\n circleStyle = {\n ...circleStyle,\n minWidth: '2rem',\n }\n\n checkedOffset = '1.5rem'\n break\n default:\n style = {\n ...style,\n height: '1.25rem',\n width: '2.25rem',\n minWidth: '2.25rem',\n }\n circleStyle = {\n ...circleStyle,\n height: '1.25rem',\n width: '1.25rem',\n minWidth: '1.25rem',\n }\n\n iconStyle = {\n ...iconStyle,\n transform: 'scale(0.7)',\n width: '1.25rem',\n }\n\n labelClass += 'ml3 '\n\n checkedOffset = '1rem'\n }\n\n const checkedStyle = {\n left: checked ? checkedOffset : 0,\n }\n\n circleStyle = { ...circleStyle, ...checkedStyle }\n iconStyle = { ...iconStyle, ...checkedStyle }\n\n return (\n <label htmlFor={id}>\n <div\n className={`flex flex-row items-center relative ${!disabled &&\n 'pointer'}`}>\n <div className={`vtex-toggle ${classes}`} style={style}>\n <div className={circleClasses} style={circleStyle} />\n {semantic && (\n <div className={iconDenyClasses} style={iconStyle}>\n <DenyIcon size={size === 'regular' ? 14 : 12} />\n </div>\n )}\n {semantic && (\n <div className={iconCheckClasses} style={iconStyle}>\n <CheckIcon size={size === 'regular' ? 15 : 13} />\n </div>\n )}\n </div>\n <input\n id={id}\n type=\"checkbox\"\n className=\"h-100 w-100 absolute o-0 pointer\"\n disabled={disabled}\n checked={checked}\n name={this.props.name}\n onClick={this.props.onClick}\n onChange={this.props.onChange}\n tabIndex={0}\n />\n {label && <span className={labelClass}>{label}</span>}\n </div>\n {helpText && (\n <div className=\"c-muted-1 t-small mt3 lh-title\">{helpText}</div>\n )}\n </label>\n )\n }\n}\n\nToggle.defaultProps = {\n checked: false,\n disabled: false,\n semantic: false,\n label: '',\n size: 'regular',\n}\n\nToggle.propTypes = {\n checked: PropTypes.bool,\n semantic: PropTypes.bool,\n disabled: PropTypes.bool,\n id: PropTypes.string,\n label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),\n name: PropTypes.string,\n onChange: PropTypes.func,\n onClick: PropTypes.func,\n size: PropTypes.oneOf(['regular', 'large']),\n helpText: PropTypes.node,\n}\n\nexport default Toggle\n\n```" } ]
code_store-on-localhost_e4eb47aa
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Toggle/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Toggle is a control for turning an option ON or OFF. Its effect is usually automatically applied, which is one of the main differences compared to checkboxes, that need a submit.\n\n### ๐Ÿ‘ Dos\n- The label should reflect the component state, like \"On/Off\", or \"Enabled/Disabled\", it shouldn't use an imperative tone (like \"Enable\").\n- Use the Semantic variation if turning this option ON is highly recommended from your application standpoint. In doubt prefer the default variation.\n- Be mindful of the default value of this field.\n- It's usually a good practice to be optimistic about its effect. Even if you're not sure if the resulting network request will be successful, pretend it does and let it change its state.\n\n### Related components\n- Consider using a <a href=\"#/Components/Forms/Checkbox\">Checkbox</a> if it's inside a form, or if the property doesn't have a clear \"ON/OFF\".\n\n\nDefault\n\n```js\ninitialState = {\n checked: true,\n};\n<div>\n <Toggle\n checked={state.checked}\n onChange={e => setState(prevState => ({ checked: !prevState.checked }))}\n />\n</div>;\n```\n\nWith labels\n\n```js\ninitialState = {\n checked: true,\n checked2: false,\n checkedLarge1: true,\n checkedLarge2: false\n};\n<div>\n <div className=\"dib\">\n <Toggle\n label={state.checked ? \"Activated\" : \"Deactivated\"}\n checked={state.checked}\n onChange={e => setState(prevState => ({ checked: !prevState.checked }))}\n />\n </div>\n <br />\n <div className=\"mt2 dib\">\n <Toggle\n label={state.checked2 ? \"Activated\" : \"Deactivated\"}\n checked={state.checked2}\n onChange={e => setState(prevState => ({ checked2: !prevState.checked2 }))}\n />\n </div>\n <br />\n <div className=\"mt6 dib\">\n <Toggle\n label={state.checkedLarge1 ? \"Activated\" : \"Deactivated\"}\n size=\"large\"\n checked={state.checkedLarge1}\n onChange={e =>\n setState(prevState => ({ checkedLarge1: !prevState.checkedLarge1 }))\n }\n />\n </div>\n <br />\n <div className=\"mt2 dib\">\n <Toggle\n label={state.checkedLarge2 ? \"Activated\" : \"Deactivated\"}\n size=\"large\"\n checked={state.checkedLarge2}\n onChange={e =>\n setState(prevState => ({ checkedLarge2: !prevState.checkedLarge2 }))\n }\n helpText=\"You can add help text!\"\n />\n </div>\n</div>;\n```\n\nSemantic\n \nUse the Semantic variation if turning this option ON is highly recommended from your application standpoint. In doubt prefer the default variation.\n\n```js\ninitialState = {\n checked: true,\n checked2: false,\n checkedLarge1: true,\n checkedLarge2: false\n};\n<div>\n <div className=\"dib\">\n <Toggle\n label={state.checked ? \"Activated\" : \"Deactivated\"}\n semantic\n checked={state.checked}\n onChange={e => setState(prevState => ({ checked: !prevState.checked }))}\n />\n </div>\n <br />\n <div className=\"mt2 dib\">\n <Toggle\n label={state.checked2 ? \"Activated\" : \"Deactivated\"}\n semantic\n checked={state.checked2}\n onChange={e => setState(prevState => ({ checked2: !prevState.checked2 }))}\n />\n </div>\n</div>;\n```\n\nDisabled\n\n```js\n<div>\n <div className=\"dib\">\n <Toggle disabled checked label=\"Label\" />\n </div>\n <br />\n <div className=\"dib\">\n <Toggle disabled label=\"Label\" />\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_c14332cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/AutocompleteInput/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { useState, useRef } from 'react'\n\nimport Spinner from '../Spinner'\nimport { useClickOutside, useArrowNavigation } from './hooks'\nimport Option, {\n AutocompleteOption,\n autocompleteOptionShape,\n getTermFromOption,\n} from './Option'\nimport SearchInput from './SearchInput'\n\nconst propTypes = {\n /** Input props. All HTMLInput props can be added too */\n input: PropTypes.shape({\n /** Clear input handler */\n onClear: PropTypes.func.isRequired,\n /** Search by term handler (fired on enter or when clicking the search button) */\n onSearch: PropTypes.func.isRequired,\n /** Change term handler */\n onChange: PropTypes.func.isRequired,\n /** Term to be searched */\n value: PropTypes.string,\n /** Determine if the input and button should be disabled */\n disabled: PropTypes.bool.isRequired,\n }).isRequired,\n /** Options props. More details in the examples */\n options: PropTypes.shape({\n /**\n * Determine if a spinner will be shown below the given options\n * to show that more options will be added\n */\n loading: PropTypes.bool,\n /**\n * Function that makes possible to the dev to customly render option.\n * Called with all props needed: `(props: { key: string, selected: boolean, value: OptionValue, searchTerm: string, roundedBottom: boolean, icon: ReactElement, onClick: () => void }, index: number)` and should return a React Node\n */\n renderOption: PropTypes.func,\n /**\n * List of options.\n * An option could be a string (denoting a search by term) or an object\n * with `{value: any, label: string}` (denoting the search is related to an entity).\n */\n value: PropTypes.arrayOf(autocompleteOptionShape).isRequired,\n /**\n * Icon representing the entity.\n * Shown when a value is an object to show the difference\n */\n icon: PropTypes.element,\n /**\n * Callback called when an option is selected\n * (clicked or via arrow keys + enter)\n */\n onSelect: PropTypes.func.isRequired,\n /**\n * Last searched terms. Can be used to enhance the Autocomplete experience.\n * Defined with: `{\n * value: OptionValue[],\n * onChange: (term: string | OptionValue) => any,\n * label: string\n * }`\n */\n lastSearched: PropTypes.shape({\n /** List of last searched options */\n value: PropTypes.arrayOf(autocompleteOptionShape).isRequired,\n /**\n * Last searched change handler.\n * Called when a term is searched or an option is selected.\n */\n onChange: PropTypes.func,\n /** Last Searched options's title */\n label: PropTypes.node.isRequired,\n }),\n }).isRequired,\n}\n\nexport type AutocompleteInputProps = PropTypes.InferProps<typeof propTypes>\n\nconst AutocompleteInput: React.FunctionComponent<PropTypes.InferProps<\n typeof propTypes\n>> = ({\n input: { value, onClear, onSearch, onChange, ...inputProps },\n options: {\n onSelect,\n value: options,\n renderOption,\n loading,\n lastSearched = {},\n icon,\n },\n}) => {\n const [term, setTerm] = useState(value || '')\n const [showPopover, setShowPopover] = useState(false)\n const containerRef = useRef<HTMLDivElement>(null)\n const searching = term.length\n const showLastSearched =\n !searching && (lastSearched as any)?.value?.length > 0\n\n const getShowedOptions = (): AutocompleteOption[] => {\n if (showLastSearched) {\n return (lastSearched as any)?.value\n }\n if (searching) {\n return options\n }\n return []\n }\n\n const showedOptions = getShowedOptions()\n\n const noSelectedOptionIndex = -1\n const [selectedOptionIndex, setSelectedOptionIndex] = useArrowNavigation(\n containerRef,\n showedOptions.length,\n noSelectedOptionIndex\n )\n useClickOutside(containerRef, () => setShowPopover(false))\n\n const addToLastSearched = (option: AutocompleteOption) => {\n (lastSearched as any)?.onChange(option)\n }\n\n const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n const selectedOption =\n selectedOptionIndex !== -1 ? showedOptions[selectedOptionIndex] : term\n addToLastSearched(selectedOption)\n setTerm(getTermFromOption(selectedOption))\n if (selectedOptionIndex !== -1) {\n onSelect(selectedOption)\n } else {\n onSearch(getTermFromOption(selectedOption))\n }\n setSelectedOptionIndex(-1)\n setShowPopover(false)\n }\n }\n\n const handleTermChange = (newTerm = '') => {\n if (!showPopover) {\n setShowPopover(true)\n }\n setTerm(newTerm)\n if (onChange) {\n onChange(newTerm)\n }\n }\n\n const handleClear = () => {\n setShowPopover(false)\n\n setTerm('')\n onClear()\n }\n\n const handleOptionClick = (option: AutocompleteOption) => {\n setTerm(getTermFromOption(option))\n onSelect(option)\n setShowPopover(false)\n }\n\n const getOptionProps = (option: any, index: any) => ({\n key: `${getTermFromOption(option)}-${index}`,\n selected: index === selectedOptionIndex,\n value: option,\n searchTerm: term,\n roundedBottom: index === showedOptions.length - 1,\n icon: typeof option !== 'string' && icon ? icon : null,\n onClick: () => {\n addToLastSearched(option)\n handleOptionClick(option)\n },\n })\n\n const renderOptions = (): React.ReactElement | React.ReactElement[] => (\n <div className=\"flex flex-column\">\n {showLastSearched ? (\n <div className=\"pa4 b f6\">\n {(lastSearched as any)?.label || 'Last searched terms'}\n </div>\n ) : null}\n {showedOptions.map((option, index) =>\n renderOption ? (\n renderOption(getOptionProps(option, index), index)\n ) : (\n <Option {...getOptionProps(option, index)} />\n )\n )}\n </div>\n )\n\n const popoverOpened = showPopover && (!!showedOptions.length || loading)\n\n return (\n <div ref={containerRef} className=\"flex flex-column w-100\">\n <SearchInput\n {...inputProps}\n value={\n selectedOptionIndex === -1\n ? term\n : getTermFromOption(showedOptions[selectedOptionIndex])\n }\n roundedBottom={!popoverOpened}\n onKeyDown={handleKeyDown}\n onFocus={() => setShowPopover(true)}\n onSearch={() => onSearch(term)}\n onClear={handleClear}\n onChange={handleTermChange}\n />\n {popoverOpened ? (\n <div className=\"relative\">\n <div className=\"absolute br--bottom br2 bb bl br bw1 b--muted-3 bg-base w-100 z-1 shadow-5\">\n {renderOptions()}\n {loading && (\n <div className=\"flex flex-row justify-center items-center pa4\">\n <Spinner size={20} />\n </div>\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nAutocompleteInput.propTypes = propTypes\n\nexport default AutocompleteInput\n\n```" } ]
code_store-on-localhost_3ed7c5d3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/AutocompleteInput/Option.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport classNames from 'classnames'\nimport PropTypes from 'prop-types'\nimport React, { useState } from 'react'\n\n/** Structured Autocomplete option shape */\nconst structuredAutocompleteOptionShape = PropTypes.shape({\n value: PropTypes.any,\n label: PropTypes.string.isRequired,\n})\n\ntype StructuredAutocompleteOption = PropTypes.InferType<\n typeof structuredAutocompleteOptionShape\n>\n\nexport type AutocompleteOption = string | StructuredAutocompleteOption\n\n/** Autocomplete option shape */\nexport const autocompleteOptionShape = PropTypes.oneOfType([\n PropTypes.string,\n structuredAutocompleteOptionShape,\n])\n\nexport const getTermFromOption = (option: AutocompleteOption): string =>\n typeof option === 'string' ? option : (option?.label || '') as string\n\nconst propTypes = {\n /** Determine if the option should have a rounded bottom */\n roundedBottom: PropTypes.bool,\n /** Option icon */\n icon: PropTypes.node,\n /** Search term used to highlight it into the label */\n searchTerm: PropTypes.string.isRequired,\n /** Option title */\n value: autocompleteOptionShape.isRequired,\n /** Determine if an option is selected and should be highlighted */\n selected: PropTypes.bool.isRequired,\n /** Click handler */\n onClick: PropTypes.func.isRequired,\n}\n\nconst Option: React.FunctionComponent<PropTypes.InferProps<\n typeof propTypes\n>> = props => {\n const { icon, selected, roundedBottom, searchTerm, onClick } = props\n const [highlightOption, setHighlightOption] = useState(false)\n const value = getTermFromOption(props.value)\n\n const renderOptionValue = (): string | React.ReactElement => {\n const index = value.toLowerCase().indexOf(searchTerm.toLowerCase())\n if (index === -1) {\n return value\n }\n const prefix = value.substring(0, index)\n const match = value.substr(index, searchTerm.length)\n const suffix = value.substring(index + match.length)\n return (\n <span className=\"truncate\">\n <span className=\"fw7\">{prefix}</span>\n {match}\n <span className=\"fw7\">{suffix}</span>\n </span>\n )\n }\n\n const buttonClasses = classNames('bn w-100 tl pointer pa4 f6', {\n 'br2 br--bottom': roundedBottom,\n 'bg-muted-5': highlightOption || selected,\n 'bg-base': !highlightOption && !selected,\n })\n\n return (\n <button\n className={buttonClasses}\n onFocus={() => setHighlightOption(true)}\n onMouseEnter={() => setHighlightOption(true)}\n onMouseLeave={() => setHighlightOption(false)}\n onClick={onClick}>\n <span className=\"h1 flex items-center\">\n <span className=\"mr3 c-muted-2 flex pt1\">{icon}</span>\n {renderOptionValue()}\n </span>\n </button>\n )\n}\n\nOption.propTypes = propTypes\n\nexport default Option\n\n```" } ]
code_store-on-localhost_a77d7997
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/AutocompleteInput/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### AutocompleteInput is a search input which, enhanced with a suggestions pop-up, gives the user a more complete search experience when needed.\n\n### ๐Ÿ‘ Dos\n\n- Help the user avoid errors.\n- Semantically similar phrases or words but grammarly different should appear once. E.g.: \"Dress\" and \"Dresses\".\n- Highlight the suggestions.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Exceed 10 suggestions. 6 is a great number of suggestions.\n\n#### Simple Autocomplete mocking server responses\n\n```jsx\nimport { uniq } from 'lodash'\nimport { useState, useRef } from 'react'\n\nconst allUsers = [\n 'Ana Clara',\n 'Ana Luiza',\n { value: 1, label: 'Bruno' },\n 'Carlos',\n 'Daniela',\n]\n\nconst UsersAutocomplete = () => {\n const [term, setTerm] = useState('')\n const [loading, setLoading] = useState(false)\n const timeoutRef = useRef(null)\n\n const options = {\n onSelect: (...args) => console.log('onSelect: ', ...args),\n loading,\n value: !term.length\n ? []\n : allUsers.filter(user =>\n typeof user === 'string'\n ? user.toLowerCase().includes(term.toLowerCase())\n : user.label.toLowerCase().includes(term.toLowerCase())\n ),\n }\n\n const input = {\n onChange: term => {\n if (term) {\n setLoading(true)\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n timeoutRef.current = setTimeout(() => {\n setLoading(false)\n setTerm(term)\n timeoutRef.current = null\n }, 1000)\n } else {\n setTerm(term)\n }\n },\n onSearch: (...args) => console.log('onSearch:', ...args),\n onClear: () => setTerm(''),\n placeholder: 'Search user... (e.g.: Ana)',\n value: term,\n }\n return <AutocompleteInput input={input} options={options} />\n}\n\n;<UsersAutocomplete />\n```\n\n#### Show search history\n\n```jsx\nimport { uniq } from 'lodash'\nimport { useState, useRef } from 'react'\n\nconst allUsers = [\n 'Ana Clara',\n 'Ana Luiza',\n { value: 1, label: 'Bruno' },\n 'Carlos',\n 'Daniela',\n]\n\nconst UsersAutocomplete = () => {\n const [term, setTerm] = useState('')\n const [loading, setLoading] = useState(false)\n const [lastSearched, setLastSearched] = useState([])\n const timeoutRef = useRef(null)\n\n const options = {\n onSelect: (...args) => console.log('onSelect: ', ...args),\n loading,\n value: !term.length\n ? []\n : allUsers.filter(user =>\n typeof user === 'string'\n ? user.toLowerCase().includes(term.toLowerCase())\n : user.label.toLowerCase().includes(term.toLowerCase())\n ),\n // --- This is what makes the Last Searched Terms work!\n // This can be stored anywhere the dev wants. To be persistent, for example.\n lastSearched: {\n value: lastSearched,\n label: 'Last searched users',\n onChange: option =>\n option && setLastSearched(uniq([...lastSearched, option])),\n },\n }\n\n const input = {\n onChange: term => {\n if (term) {\n setLoading(true)\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n timeoutRef.current = setTimeout(() => {\n setLoading(false)\n setTerm(term)\n timeoutRef.current = null\n }, 1000)\n } else {\n setTerm(term)\n }\n },\n onSearch: (...args) => console.log('onSearch:', ...args),\n onClear: () => setTerm(''),\n placeholder: 'Search user... (e.g.: Ana)',\n value: term,\n }\n return <AutocompleteInput input={input} options={options} />\n}\n\n;<UsersAutocomplete />\n```\n\n#### Custom option rendering\n\n```jsx\nimport { uniq } from 'lodash'\nimport { useState, useRef } from 'react'\n\nimport User from '../icon/User'\nimport Search from '../icon/Search'\n\nconst allUsers = [\n 'Ana',\n { value: 1, label: 'Ana Clara' },\n { value: 2, label: 'Ana Luiza', caption: 'VTEX' },\n { value: 3, label: 'Bruno' },\n]\n\nconst CustomOption = props => {\n const { roundedBottom, searchTerm, value, key, selected, onClick } = props\n const [highlightOption, setHighlightOption] = useState(false)\n\n const renderOptionHighlightedText = () => {\n const highlightableText = typeof value === 'string' ? value : value.label\n const index = highlightableText\n .toLowerCase()\n .indexOf(searchTerm.toLowerCase())\n if (index === -1) {\n return highlightableText\n }\n const prefix = highlightableText.substring(0, index)\n const match = highlightableText.substr(index, searchTerm.length)\n const suffix = highlightableText.substring(index + match.length)\n return (\n <span className=\"truncate\">\n <span className=\"fw7\">{prefix}</span>\n {match}\n <span className=\"fw7\">{suffix}</span>\n </span>\n )\n }\n\n const buttonClasses = `bn w-100 tl pointer pa4 f6 ${\n roundedBottom ? 'br2 br--bottom' : ''\n } ${highlightOption || selected ? 'bg-muted-5' : 'bg-base'}`\n\n const icon = typeof value === 'string' ? <Search size={14} /> : <User size={14} />\n\n // --- This is a good practice. Use <button />.\n return (\n <button\n key={key}\n className={buttonClasses}\n onFocus={() => setHighlightOption(true)}\n onMouseEnter={() => setHighlightOption(true)}\n onMouseLeave={() => setHighlightOption(false)}\n onClick={onClick}>\n <div className=\"flex items-center\">\n <span className=\"mr3 c-muted-2 flex pt1\">{icon}</span>\n <span className=\"pr2\">{renderOptionHighlightedText()}</span>\n {typeof value !== 'string' && (\n <div className=\"t-mini c-muted-1\">{value.caption}</div>\n )}\n </div>\n </button>\n )\n}\n\nconst UsersAutocomplete = () => {\n const [term, setTerm] = useState('')\n const [loading, setLoading] = useState(false)\n const [lastSearched, setLastSearched] = useState([])\n const timeoutRef = useRef(null)\n\n const options = {\n onSelect: (...args) => console.log('onSelect: ', ...args),\n loading,\n value: !term.length\n ? []\n : allUsers.filter(user =>\n typeof user === 'string'\n ? user.toLowerCase().includes(term.toLowerCase())\n : user.label.toLowerCase().includes(term.toLowerCase())\n ),\n lastSearched: {\n value: lastSearched,\n label: 'Last searched users',\n onChange: option =>\n option && setLastSearched(uniq([...lastSearched, option])),\n },\n // --- This is what makes the custom option work!\n renderOption: props => <CustomOption {...props} />,\n }\n\n const input = {\n onChange: term => {\n if (term) {\n setLoading(true)\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n timeoutRef.current = setTimeout(() => {\n setLoading(false)\n setTerm(term)\n timeoutRef.current = null\n }, 1000)\n } else {\n setTerm(term)\n }\n },\n onSearch: (...args) => console.log('onSearch:', ...args),\n onClear: () => setTerm(''),\n placeholder: 'Search user... (e.g.: Ana)',\n value: term,\n }\n return <AutocompleteInput input={input} options={options} />\n}\n\n;<UsersAutocomplete />\n```\n\n```" } ]
code_store-on-localhost_c6c0acb5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/AutocompleteInput/hooks.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useState, useEffect } from 'react'\n\nexport const useClickOutside = (\n ref: React.RefObject<HTMLElement> | null,\n onClickOutside: (e: Event) => void\n) => {\n const handleClickOutside = (e: Event) => {\n if (\n ref &&\n ref.current &&\n e.target instanceof Node &&\n !ref.current.contains(e.target)\n ) {\n onClickOutside(e)\n }\n }\n\n useEffect(() => {\n // Bind the event listener\n document.addEventListener('mousedown', handleClickOutside)\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener('mousedown', handleClickOutside)\n }\n })\n}\n\nexport const useArrowNavigation = (\n ref: React.RefObject<HTMLElement> | null,\n optionsLength: number,\n initialSelectedOptionIndex: number\n): [number, (index: number) => void] => {\n const [selectedOptionIndex, setSelectedOptionIndex] = useState(\n initialSelectedOptionIndex\n )\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (\n ref &&\n ref.current &&\n e.target instanceof Node &&\n ref.current.contains(e.target)\n ) {\n let index\n switch (e.key) {\n case 'ArrowUp':\n e.preventDefault()\n index = Math.max(selectedOptionIndex - 1, initialSelectedOptionIndex)\n return setSelectedOptionIndex(index)\n case 'ArrowDown':\n e.preventDefault()\n index = Math.min(selectedOptionIndex + 1, optionsLength - 1)\n return setSelectedOptionIndex(index)\n default:\n return\n }\n }\n }\n\n useEffect(() => {\n // Bind the event listener\n document.addEventListener('keydown', handleKeyDown)\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener('keydown', handleKeyDown)\n }\n })\n\n return [selectedOptionIndex, setSelectedOptionIndex]\n}\n\n```" } ]
code_store-on-localhost_1ade188b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EmptyState/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nclass EmptyState extends PureComponent {\n render() {\n const { title, children, testId } = this.props\n\n return (\n <div\n className=\"MAIN br3 flex c-muted-2 justify-center pv9 ph6 ph9-l tc\"\n data-testid={testId}>\n <div className=\"w-80 w-50-l\">\n {title && <span className=\"t-heading-3 mt0 mt0\">{title}</span>}\n {children && <div className=\"t-body lh-copy\">{children}</div>}\n </div>\n </div>\n )\n }\n}\n\nEmptyState.propTypes = {\n /** Title of the component (String) */\n title: (props, propName, componentName) => {\n if (!props.title && !props.children) {\n return new Error(\n `Prop 'title' or 'children' was not specified in '${componentName}'.`\n )\n }\n },\n /** node */\n children: (props, propName, componentName) => {\n if (!props.title && !props.children) {\n return new Error(\n `Prop 'title' or 'children' was not specified in '${componentName}'.`\n )\n }\n },\n /** Data attribute */\n testId: PropTypes.string,\n}\n\nexport default EmptyState\n\n```" } ]
code_store-on-localhost_319931da
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/EmptyState/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### An Empty State shows _something_ when there's nothing to show. Instead of leaving the user with a blank space, it explains what should be there and encourage to take an appropriate action.\n\n### ๐Ÿ‘ Dos\n- Guide the user to what should be done to populate that screen, either if it's an empty search result or onboarding of a new product feature.\n- Although its parts (heading, body and call-to-action) are all optional, do try to use most of them.\n- You may use as a call-to-action whatever makes more sense to you: a button, a link, etc.\n- Do use an illustration or icon if it's very important for your product to delight the user at this step.\n\n### ๐Ÿ‘Ž Don'ts\n- Don't use informal language. An empty state might be a break in the user expectations, so it's not the time to be funny. But do try to be friendly and instructive.\n- Don't reuse the same copy for empty search results and empty application states.\n\n\n```js\nconst Button = require('../Button').default\n\n;<div>\n <EmptyState title=\"A big headline\">\n <p>\n A longer explanation of what should be here, and why should I care about\n what should be here.\n </p>\n\n <div className=\"pt5\">\n <Button variation=\"secondary\" size=\"small\">\n <span className=\"flex align-baseline\">Suggested action</span>\n </Button>\n </div>\n </EmptyState>\n</div>\n```\n\n```" } ]
code_store-on-localhost_c99436cf
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Textarea/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass Textarea extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n active: false,\n }\n }\n\n static CharacterCountdown = props => {\n let classes = 't-small mt2 lh-title '\n if (props.value <= 10) {\n classes += 'c-danger'\n } else {\n classes += 'c-muted-1'\n }\n return (\n <div className={classes}>\n {props.value} {props.text}\n </div>\n )\n }\n\n handleChange = event => {\n this.props.onChange && this.props.onChange(event)\n }\n\n handleFocus = event => {\n this.setState({ active: true })\n this.props.onFocus && this.props.onFocus(event)\n }\n\n handleBlur = event => {\n this.setState({ active: false })\n this.props.onBlur && this.props.onBlur(event)\n }\n\n render() {\n const {\n errorMessage,\n error,\n label,\n helpText,\n dataAttributes,\n children,\n maxLength,\n resize,\n size,\n } = this.props\n const { active } = this.state\n\n const dataAttrs = {}\n for (const key of Object.keys(dataAttributes)) {\n dataAttrs[`data-${key}`] = dataAttributes[key]\n }\n\n const widthClass = 'w-100'\n const box = 'ma0 border-box'\n const border = 'bw1 br2 b--solid outline-0'\n const typography = 'c-on-base t-small'\n const padding = 'pv3 ph5'\n\n let classes = `${widthClass} ${box} ${padding} ${border} ${typography} `\n let labelClasses = `vtex-textarea__label db mb3 w-100 `\n\n if (active) {\n classes += 'b--muted-2 '\n } else if (!error && !errorMessage) {\n classes += 'b--muted-4 '\n if (!this.props.disabled) {\n classes += 'hover-b--muted-3 '\n }\n }\n\n if (error || errorMessage) {\n classes += 'b--danger hover-b--danger '\n }\n\n if (this.props.disabled) {\n classes += 'bg-disabled b--disabled c-disabled '\n } else {\n classes += 'bg-base '\n }\n\n switch (size) {\n case 'small':\n classes += 't-small '\n labelClasses += 't-small '\n break\n\n case 'large':\n classes += 't-body '\n labelClasses += 't-body '\n break\n\n default:\n classes += 't-body '\n labelClasses += 't-body '\n break\n }\n\n return (\n <label className=\"vtex-textarea\">\n {label && <span className={labelClasses}>{label}</span>}\n <textarea\n {...dataAttrs}\n onBlur={this.handleBlur}\n onFocus={this.handleFocus}\n onChange={this.handleChange}\n className={classes}\n autoComplete={this.props.autoComplete}\n autoFocus={this.props.autoFocus}\n disabled={this.props.disabled}\n maxLength={this.props.maxLength}\n minLength={this.props.minLength}\n name={this.props.name}\n placeholder={this.props.placeholder}\n readOnly={this.props.readOnly}\n required={this.props.required}\n spellCheck={this.props.spellCheck}\n id={this.props.id}\n rows={this.props.rows}\n defaultValue={this.props.defaultValue}\n value={this.props.value}\n style={{ resize, WebkitAppearance: 'none' }}>\n {children}\n </textarea>\n\n <div className=\"flex justify-between\">\n <div>\n {errorMessage && (\n <div className=\"c-danger t-small mt2 lh-title\">\n {errorMessage}\n </div>\n )}\n {helpText && (\n <div className=\"c-muted-1 t-small mt2 lh-title\">{helpText}</div>\n )}\n </div>\n {maxLength && (\n <Textarea.CharacterCountdown\n value={this.props.maxLength - this.props.value.length}\n text={this.props.characterCountdownText}\n />\n )}\n </div>\n </label>\n )\n }\n}\n\nTextarea.defaultProps = {\n autoFocus: false,\n dataAttributes: {},\n disabled: false,\n label: '',\n readOnly: false,\n resize: 'both',\n size: 'regular',\n error: false,\n characterCountdownText: 'characters left',\n rows: 5,\n}\n\nTextarea.propTypes = {\n /** Content of the textarea */\n children: PropTypes.string,\n /* Size of the textarea */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Controlled content of the textarea */\n value: PropTypes.string,\n /** Default content of the textarea */\n defaultValue: PropTypes.string,\n /** Error highlight */\n error: PropTypes.bool,\n /** Error message */\n errorMessage: PropTypes.string,\n /** Help text */\n helpText: PropTypes.node,\n /** Label */\n label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),\n /** Spec attribute */\n autoComplete: PropTypes.string,\n /** Spec attribute */\n autoFocus: PropTypes.bool,\n /** Spec attribute */\n disabled: PropTypes.bool,\n /** Spec attribute */\n id: PropTypes.string,\n /** If defined, the textarea will have a character countdown at the bottom right */\n maxLength: PropTypes.string,\n /** Spec attribute */\n minLength: PropTypes.string,\n /** Spec attribute */\n name: PropTypes.string,\n /** Spec attribute */\n placeholder: PropTypes.string,\n /** Spec attribute */\n readOnly: PropTypes.bool,\n /** Spec attribute */\n required: PropTypes.string,\n /** Controls if Textarea is resizable and the resize direction. */\n resize: PropTypes.oneOf(['both', 'horizontal', 'none', 'vertical']),\n /** Spec attribute */\n rows: PropTypes.number,\n /** Spec attribute */\n spellCheck: PropTypes.string,\n /** Spec attribute */\n wrap: PropTypes.string,\n /** List of data attributes as a object like `{'locale': 'en-US'}` */\n dataAttributes: PropTypes.object,\n /** onChange event */\n onChange: PropTypes.func,\n /** onFocus event */\n onFocus: PropTypes.func,\n /** onBlur event */\n onBlur: PropTypes.func,\n /** Helper text for character countdown (X characters left) */\n characterCountdownText: PropTypes.string,\n}\n\nexport default Textarea\n\n```" } ]
code_store-on-localhost_91efe005
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Textarea/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n```js\ninitialState = {\n value: '',\n}\n;<div>\n <div className=\"mb6\">\n <Textarea label=\"With a label\">I haz content</Textarea>\n </div>\n <div className=\"mb6\">\n <Textarea disabled label=\"Disabled\">\n Cant touch this!\n </Textarea>\n </div>\n <div className=\"mb6\">\n <Textarea\n label=\"With helper\"\n helpText={<span>Your help text goes here!</span>}\n />\n </div>\n <div className=\"mb6\">\n <Textarea label=\"With error\" error errorMessage=\"Somehow wrong\" />\n </div>\n <div className=\"mb6\">\n <Textarea\n label=\"Controlling text (no spaces) with character countdown\"\n onChange={e => setState({ value: e.target.value.trim() })}\n value={state.value}\n maxLength=\"100\"\n helpText=\"You can have helper text alongside the countdown.\"\n />\n </div>\n</div>\n```\n```" } ]
code_store-on-localhost_1991a0b6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/FilterOptions/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\nimport find from 'lodash/find'\nimport head from 'lodash/head'\n\nimport FilterColapsible from './FilterColapsible'\n\nclass FilterOptions extends PureComponent {\n handleStatementChange = statement => {\n const { statements } = this.props\n const { subject } = statement\n const filteredStatements = statements.filter(st => st.subject !== subject)\n this.props.onChangeStatements([...filteredStatements, statement])\n }\n\n extractStatement = (statements, subject) =>\n find(statements, st => st.subject === subject)\n\n createEmptyStatement = (subject, options) => {\n const availableVerbs =\n options && options[subject] ? options[subject].verbs : []\n const verb = head(availableVerbs) ? head(availableVerbs).value : null\n return {\n subject,\n verb,\n object: null,\n error: null,\n }\n }\n\n render() {\n const { options, statements } = this.props\n const optionsKeys = Object.keys(options)\n return (\n optionsKeys.length > 0 && (\n <div className={'flex flex-column'}>\n {optionsKeys.map(subject => {\n const statement =\n this.extractStatement(statements, subject) ||\n this.createEmptyStatement(subject, options)\n return (\n <div key={subject} className=\"ma2\">\n <FilterColapsible\n subject={subject}\n options={options}\n statement={statement}\n onChangeStatement={this.handleStatementChange}\n beginWithOpenCollapsibles={optionsKeys.length <= 3}\n />\n </div>\n )\n })}\n </div>\n )\n )\n }\n}\n\nFilterOptions.defaultProps = {\n options: [],\n}\n\nFilterOptions.propTypes = {\n /** filter options (mirroring statements from Conditions component) */\n options: PropTypes.objectOf(\n PropTypes.shape({\n label: PropTypes.string,\n verbs: PropTypes.array.isRequired,\n })\n ).isRequired,\n /** filter statements (mirroring statements from Conditions component) */\n statements: PropTypes.arrayOf(\n PropTypes.shape({\n subject: PropTypes.string,\n verb: PropTypes.string.isRequired,\n object: PropTypes.any,\n error: PropTypes.any,\n })\n ),\n /** Filters change callback: returns array of statement definitions */\n onChangeStatements: PropTypes.func.isRequired,\n}\n\nexport default FilterOptions\n\n```" } ]
code_store-on-localhost_f63c4439
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/FilterOptions/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### The FilterOptions is a more horizontally compacted way of displaying filter atoms. Although designed to be used with the Modal component, it can also be used on its own with any other way you chose to display your data.\n\nThe FilterOptions is optimized for small viewport applications which do not provide enough horizontal space to work with. Making use of vertical collapsible components, it displays filter data to the user allowing them to choose which filter suits their needs.\n\n### ๐Ÿ‘ Dos\n\n- Use the FilterOptions near of the content that will be filtered.\n- Try offering as many filters and operators as possible. With the diversity of operations VTEX supports, we can never predict all the diverse use cases our merchants need.\n- Hide the component when possible. After applying the filters is possible to display which filters are applied with other components.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't present too many filters in one single FilterOptions.\n\n### Related components\n\n- For applications with a larger viewport or when working with tables prefer using the <a href=\"#/Components/Display/FilterBar\">FilterBar</a> component.\n\nSimple product filter example\n\n```js\nconst Input = require('../Input').default\n\nclass MySimpleFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.getSimpleVerbs = this.getSimpleVerbs.bind(this)\n this.renderSimpleFilterLabel = this.renderSimpleFilterLabel.bind(this)\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n value={values || ''}\n onChange={e => onChangeObjectCallback(e.target.value)}\n />\n )\n }\n\n getSimpleVerbs() {\n return [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ]\n }\n\n renderSimpleFilterLabel(statement) {\n if (!statement || !statement.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n statement.verb === '='\n ? 'is'\n : statement.verb === '!='\n ? 'is not'\n : 'contains'\n } ${statement.object}`\n }\n\n render() {\n return (\n <FilterOptions\n alwaysVisibleFilters={['id', 'category', 'brand']}\n statements={this.state.statements}\n onChangeStatements={statements => this.setState({ statements })}\n clearAllFiltersButtonLabel=\"Clear Filters\"\n options={{\n id: {\n label: 'ID',\n renderFilterLabel: this.renderSimpleFilterLabel,\n verbs: this.getSimpleVerbs(),\n },\n category: {\n label: 'Category',\n renderFilterLabel: this.renderSimpleFilterLabel,\n verbs: this.getSimpleVerbs(),\n },\n brand: {\n label: 'Brand',\n renderFilterLabel: this.renderSimpleFilterLabel,\n verbs: this.getSimpleVerbs(),\n },\n }}\n />\n )\n }\n}\n;<MySimpleFilter />\n```\n\nFilter users example\n\n```js\nclass MyUsersFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.cpfInputObject = this.cpfInputObject.bind(this)\n this.ageInputObject = this.ageInputObject.bind(this)\n this.ageInputRangeObject = this.ageInputRangeObject.bind(this)\n this.classSelectorObject = this.classSelectorObject.bind(this)\n this.cpfValidationRegex = RegExp(\n '([0-9]{2}[.]?[0-9]{3}[.]?[0-9]{3}[/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[.]?[0-9]{3}[.]?[0-9]{3}[-]?[0-9]{2})'\n )\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n value={values || ''}\n onChange={e => onChangeObjectCallback(e.target.value)}\n />\n )\n }\n\n cpfInputObject(\n { statements, values, statementIndex, error, onChangeObjectCallback },\n shouldValidate = false\n ) {\n const errorMessage =\n shouldValidate && values\n ? this.cpfValidationRegex.test(values)\n ? null\n : 'Invalid CPF'\n : null\n return (\n <Input\n placeholder=\"Insert cpfโ€ฆ\"\n type=\"number\"\n errorMessage={errorMessage}\n min={0}\n value={values || ''}\n onChange={e => {\n onChangeObjectCallback(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n ageInputObject({\n statements,\n values,\n statementIndex,\n error,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n placeholder=\"Insert ageโ€ฆ\"\n type=\"number\"\n min=\"0\"\n max=\"180\"\n value={values || ''}\n onChange={e => {\n onChangeObjectCallback(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n ageInputRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <div className=\"flex\">\n <Input\n placeholder=\"Age fromโ€ฆ\"\n errorMessage={\n statements[statementIndex].object &&\n parseInt(statements[statementIndex].object.first) >=\n parseInt(statements[statementIndex].object.last)\n ? 'Must be smaller than other input'\n : ''\n }\n value={values && values.first ? values.first : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.first = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n placeholder=\"Age toโ€ฆ\"\n value={values && values.last ? values.last : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.last = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n </div>\n )\n }\n\n classSelectorObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n const initialValue = {\n vip: true,\n gold: true,\n silver: true,\n platinum: true,\n }\n\n const toCheckedMap = ([key, value]) => [key, { label: key, checked: value }]\n const toValues = ([key, value]) => [key, value.checked]\n\n const checkedMap = Object.fromEntries(\n Object.entries({ ...initialValue, ...(values || {}) }).map(toCheckedMap)\n )\n return (\n <CheckboxGroup\n name=\"simpleCheckboxGroup\"\n label=\"All Filters\"\n checkedMap={checkedMap}\n onGroupChange={checkedMap => {\n const newValues = Object.fromEntries(\n Object.entries(checkedMap).map(toValues)\n )\n onChangeObjectCallback(newValues)\n }}\n />\n )\n }\n\n render() {\n return (\n <FilterOptions\n alwaysVisibleFilters={['name', 'email', 'class']}\n statements={this.state.statements}\n onChangeStatements={statements => this.setState({ statements })}\n clearAllFiltersButtonLabel=\"Clear Filters\"\n options={{\n name: {\n label: 'Name',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains'\n } ${st.object}`\n },\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n },\n email: {\n label: 'Email',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains '\n } ${st.object}`\n },\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n },\n class: {\n label: 'Class',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'All'\n }\n const keys = st.object ? Object.keys(st.object) : {}\n const isAllTrue = !keys.some(key => !st.object[key])\n const isAllFalse = !keys.some(key => st.object[key])\n const trueKeys = keys.filter(key => st.object[key])\n let trueKeysLabel = ''\n trueKeys.forEach((key, index) => {\n trueKeysLabel += `${key}${\n index === trueKeys.length - 1 ? '' : ', '\n }`\n })\n return `${\n isAllTrue ? 'All' : isAllFalse ? 'None' : `${trueKeysLabel}`\n }`\n },\n verbs: [\n {\n label: 'includes',\n value: 'includes',\n object: {\n renderFn: this.classSelectorObject,\n extraParams: {},\n },\n },\n ],\n },\n age: {\n label: 'Age',\n renderFilterLabel: st =>\n `${\n st.verb === 'between'\n ? `between ${st.object.first} and ${st.object.last}`\n : `is ${st.object}`\n }`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.ageInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.ageInputRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n cpf: {\n label: 'Document',\n renderFilterLabel: st =>\n `${st.verb === '=' ? 'is' : 'contains'} ${st.object}`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: obj => this.cpfInputObject(obj, true),\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.cpfInputObject,\n extraParams: {},\n },\n },\n ],\n },\n }}\n />\n )\n }\n}\n;<MyUsersFilter />\n```\n\nFilter orders example\n\n```js\nclass MyOrdersFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.simpleInputVerbs = this.simpleInputVerbs.bind(this)\n this.datePickerObject = this.datePickerObject.bind(this)\n this.datePickerRangeObject = this.datePickerRangeObject.bind(this)\n this.statusSelectorObject = this.statusSelectorObject.bind(this)\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n value={values || ''}\n onChange={e => onChangeObjectCallback(e.target.value)}\n />\n )\n }\n\n simpleInputVerbs() {\n return [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ]\n }\n\n datePickerObject({\n statements,\n values,\n statementIndex,\n error,\n onChangeObjectCallback,\n }) {\n return (\n <div className=\"w-100\">\n <DatePicker\n value={values || new Date()}\n onChange={date => {\n onChangeObjectCallback(date)\n }}\n locale=\"pt-BR\"\n />\n </div>\n )\n }\n\n datePickerRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <div className=\"flex flex-column w-100\">\n <br />\n <DatePicker\n label=\"\u001cfrom\"\n value={(values && values.from) || new Date()}\n onChange={date => {\n onChangeObjectCallback({ ...(values || {}), from: date })\n }}\n locale=\"pt-BR\"\n />\n <br />\n <DatePicker\n label=\"to\"\n value={(values && values.to) || new Date()}\n onChange={date => {\n onChangeObjectCallback({ ...(values || {}), to: date })\n }}\n locale=\"pt-BR\"\n />\n </div>\n )\n }\n\n statusSelectorObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n const initialValue = {\n 'Window to cancelation': true,\n Canceling: true,\n Canceled: true,\n 'Payment pending': true,\n 'Payment approved': true,\n 'Ready for handling': true,\n 'Handling shipping': true,\n 'Ready for invoice': true,\n Invoiced: true,\n Complete: true,\n }\n const toCheckedMap = ([key, value]) => [key, { label: key, checked: value }]\n const toValues = ([key, value]) => [key, value.checked]\n\n const checkedMap = Object.fromEntries(\n Object.entries({ ...initialValue, ...(values || {}) }).map(toCheckedMap)\n )\n return (\n <CheckboxGroup\n name=\"simpleCheckboxGroup\"\n label=\"All Filters\"\n checkedMap={checkedMap}\n onGroupChange={checkedMap => {\n const newValues = Object.fromEntries(\n Object.entries(checkedMap).map(toValues)\n )\n onChangeObjectCallback(newValues)\n }}\n />\n )\n }\n\n render() {\n return (\n <FilterOptions\n alwaysVisibleFilters={['id', 'email', 'status', 'invoicedate']}\n statements={this.state.statements}\n onChangeStatements={statements => this.setState({ statements })}\n clearAllFiltersButtonLabel=\"Clear Filters\"\n options={{\n id: {\n label: 'Order ID',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains'\n } ${st.object}`\n },\n verbs: this.simpleInputVerbs(),\n },\n email: {\n label: 'Email',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains '\n } ${st.object}`\n },\n verbs: this.simpleInputVerbs(),\n },\n status: {\n label: 'Status',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'All'\n }\n const keys = st.object ? Object.keys(st.object) : {}\n const isAllTrue = !keys.some(key => !st.object[key])\n const isAllFalse = !keys.some(key => st.object[key])\n const trueKeys = keys.filter(key => st.object[key])\n let trueKeysLabel = ''\n trueKeys.forEach((key, index) => {\n trueKeysLabel += `${key}${\n index === trueKeys.length - 1 ? '' : ', '\n }`\n })\n return `${\n isAllTrue ? 'All' : isAllFalse ? 'None' : `${trueKeysLabel}`\n }`\n },\n verbs: [\n {\n label: 'includes',\n value: 'includes',\n object: {\n renderFn: this.statusSelectorObject,\n extraParams: {},\n },\n },\n ],\n },\n invoicedate: {\n label: 'Invoiced date',\n renderFilterLabel: st => {\n if (!st || !st.object) return '\u001cAll'\n return `${\n st.verb === 'between'\n ? `between ${st.object.from} and ${st.object.to}`\n : `is ${st.object}`\n }`\n },\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.datePickerObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.datePickerRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n utm: {\n label: 'UTM Source',\n renderFilterLabel: st =>\n `${st.verb === '=' ? 'is' : 'contains'} ${st.object}`,\n verbs: this.simpleInputVerbs(),\n },\n seller: {\n label: 'Seller',\n renderFilterLabel: st =>\n `${st.verb === '=' ? 'is' : 'contains'} ${st.object}`,\n verbs: this.simpleInputVerbs(),\n },\n }}\n />\n )\n }\n}\n;<MyOrdersFilter />\n```\n\nFilter Options with Modal Example\n\n```js\nconst Button = require('../Button').default\nconst Modal = require('../Modal').default\nconst Input = require('../Input').default\nconst CheckboxGroup = require('../CheckboxGroup').default\n\nclass MyUsersFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.cpfInputObject = this.cpfInputObject.bind(this)\n this.ageInputObject = this.ageInputObject.bind(this)\n this.ageInputRangeObject = this.ageInputRangeObject.bind(this)\n this.classSelectorObject = this.classSelectorObject.bind(this)\n this.cpfValidationRegex = RegExp(\n '([0-9]{2}[.]?[0-9]{3}[.]?[0-9]{3}[/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[.]?[0-9]{3}[.]?[0-9]{3}[-]?[0-9]{2})'\n )\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n value={values || ''}\n onChange={e => onChangeObjectCallback(e.target.value)}\n />\n )\n }\n\n cpfInputObject(\n { statements, values, statementIndex, error, onChangeObjectCallback },\n shouldValidate = false\n ) {\n const errorMessage =\n shouldValidate && values\n ? this.cpfValidationRegex.test(values)\n ? null\n : 'Invalid CPF'\n : null\n return (\n <Input\n placeholder=\"Insert cpfโ€ฆ\"\n type=\"number\"\n errorMessage={errorMessage}\n min={0}\n value={values || ''}\n onChange={e => {\n onChangeObjectCallback(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n ageInputObject({\n statements,\n values,\n statementIndex,\n error,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n placeholder=\"Insert ageโ€ฆ\"\n type=\"number\"\n min=\"0\"\n max=\"180\"\n value={values || ''}\n onChange={e => {\n onChangeObjectCallback(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n ageInputRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <div className=\"flex\">\n <Input\n placeholder=\"Age fromโ€ฆ\"\n errorMessage={\n statements[statementIndex].object &&\n parseInt(statements[statementIndex].object.first) >=\n parseInt(statements[statementIndex].object.last)\n ? 'Must be smaller than other input'\n : ''\n }\n value={values && values.first ? values.first : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.first = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n placeholder=\"Age toโ€ฆ\"\n value={values && values.last ? values.last : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.last = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n </div>\n )\n }\n\n classSelectorObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n const initialValue = {\n vip: true,\n gold: true,\n silver: true,\n platinum: true,\n }\n\n const toCheckedMap = ([key, value]) => [key, { label: key, checked: value }]\n const toValues = ([key, value]) => [key, value.checked]\n\n const checkedMap = Object.fromEntries(\n Object.entries({ ...initialValue, ...(values || {}) }).map(toCheckedMap)\n )\n return (\n <CheckboxGroup\n name=\"simpleCheckboxGroup\"\n label=\"All Filters\"\n checkedMap={checkedMap}\n onGroupChange={checkedMap => {\n const newValues = Object.fromEntries(\n Object.entries(checkedMap).map(toValues)\n )\n onChangeObjectCallback(newValues)\n }}\n />\n )\n }\n\n render() {\n return (\n <FilterOptions\n alwaysVisibleFilters={['name', 'email', 'class']}\n statements={this.state.statements}\n onChangeStatements={statements => this.setState({ statements })}\n clearAllFiltersButtonLabel=\"Clear Filters\"\n options={{\n name: {\n label: 'Name',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains'\n } ${st.object}`\n },\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n },\n email: {\n label: 'Email',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '='\n ? 'is'\n : st.verb === '!='\n ? 'is not'\n : 'contains '\n } ${st.object}`\n },\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n },\n class: {\n label: 'Class',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'All'\n }\n const keys = st.object ? Object.keys(st.object) : {}\n const isAllTrue = !keys.some(key => !st.object[key])\n const isAllFalse = !keys.some(key => st.object[key])\n const trueKeys = keys.filter(key => st.object[key])\n let trueKeysLabel = ''\n trueKeys.forEach((key, index) => {\n trueKeysLabel += `${key}${\n index === trueKeys.length - 1 ? '' : ', '\n }`\n })\n return `${\n isAllTrue ? 'All' : isAllFalse ? 'None' : `${trueKeysLabel}`\n }`\n },\n verbs: [\n {\n label: 'includes',\n value: 'includes',\n object: {\n renderFn: this.classSelectorObject,\n extraParams: {},\n },\n },\n ],\n },\n age: {\n label: 'Age',\n renderFilterLabel: st =>\n `${\n st.verb === 'between'\n ? `between ${st.object.first} and ${st.object.last}`\n : `is ${st.object}`\n }`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.ageInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.ageInputRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n cpf: {\n label: 'Document',\n renderFilterLabel: st =>\n `${st.verb === '=' ? 'is' : 'contains'} ${st.object}`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: obj => this.cpfInputObject(obj, true),\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.cpfInputObject,\n extraParams: {},\n },\n },\n ],\n },\n }}\n />\n )\n }\n}\n\nclass ModalExample extends React.Component {\n constructor() {\n super()\n this.state = { isModalOpen: false }\n this.handleOpenModal = this.handleOpenModal.bind(this)\n this.handleCloseModal = this.handleCloseModal.bind(this)\n }\n\n handleOpenModal() {\n this.setState({ isModalOpen: true })\n }\n\n handleCloseModal() {\n this.setState({ isModalOpen: false })\n }\n\n render() {\n return (\n <React.Fragment>\n <Button onClick={this.handleOpenModal}>Filters</Button>\n\n <Modal\n isOpen={this.state.isModalOpen}\n title=\"User Filters\"\n responsiveFullScreen\n centered\n bottomBar={\n <div className=\"nowrap\">\n <span className=\"mr4\">\n <Button variation=\"tertiary\" onClick={this.handleCloseModal}>\n Clear\n </Button>\n </span>\n <span>\n <Button variation=\"secondary\" onClick={this.handleCloseModal}>\n Apply\n </Button>\n </span>\n </div>\n }\n onClose={this.handleCloseModal}>\n <div style={{ width: '300px' }}>\n <MyUsersFilter />\n </div>\n </Modal>\n </React.Fragment>\n )\n }\n}\n\n;<ModalExample />\n```\n\n```" } ]
code_store-on-localhost_6dc27b1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/FilterOptions/FilterColapsible.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Statement from '../Statement'\nimport Collapsible from '../Collapsible'\n\nclass FilterColapsible extends PureComponent {\n constructor(props) {\n super(props)\n this.state = {\n isCollapsibleOpen: props.beginWithOpenCollapsibles,\n }\n }\n\n handleChangeStatement = (newValue, structure) => {\n const { statement } = this.props\n return this.props.onChangeStatement({ ...statement, [structure]: newValue })\n }\n\n render() {\n const { options, subject, statement } = this.props\n const { isCollapsibleOpen } = this.state\n\n const shouldOmitVerb = options[subject].verbs.length === 1\n\n return (\n <div className=\"flex items-stretch\">\n <Collapsible\n isOpen={isCollapsibleOpen}\n align=\"left\"\n caretColor=\"base\"\n header={\n <div className=\"flex items-center h-100 ph4 pv5\">\n <span className=\"flex nl3 \">\n <span className=\"fw5 f4\">{options[subject].label}</span>\n </span>\n </div>\n }\n onClick={e => this.setState({ isCollapsibleOpen: e.target.isOpen })}>\n <div className=\"ma5\">\n {isCollapsibleOpen && (\n <Statement\n isFullWidth\n omitSubject\n omitVerbs={shouldOmitVerb}\n options={options}\n subjectPlaceholder={'โ€ฆ'}\n statements={[statement]}\n onChangeStatement={this.handleChangeStatement}\n onChangeObjectCallback={value =>\n this.handleChangeStatement(value, 'object')\n }\n />\n )}\n </div>\n </Collapsible>\n </div>\n )\n }\n}\n\nFilterColapsible.defaultProps = {\n statement: {\n subject: null,\n verb: null,\n object: null,\n error: null,\n },\n}\n\nFilterColapsible.propTypes = {\n options: PropTypes.object.isRequired,\n subject: PropTypes.string.isRequired,\n statement: PropTypes.objectOf(\n PropTypes.shape({\n subject: PropTypes.string,\n verb: PropTypes.string.isRequired,\n object: PropTypes.object,\n error: PropTypes.any,\n })\n ),\n onChangeStatement: PropTypes.func.isRequired,\n beginWithOpenCollapsibles: PropTypes.bool,\n}\n\nexport default FilterColapsible\n\n```" } ]
code_store-on-localhost_46fb9735
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Button/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component, Fragment } from 'react'\n// import PropTypes from 'prop-types'\n\nimport Spinner from '../Spinner'\n// import { withForwardedRef, refShape } from '../../modules/withForwardedRef'\nimport { withForwardedRef } from '../../modules/withForwardedRef'\n\nclass Button extends Component<any> {\n handleClick = event => {\n !this.props.disabled &&\n !this.props.isLoading &&\n this.props.onClick &&\n this.props.onClick(event)\n }\n\n componentDidMount() {\n if (this.props.icon) {\n console.warn(\n 'Button: The prop \"icon\" of the \"Button\" component has been deprecated, and will be removed in a future version. Please use the component \"ButtonWithIcon\" instead'\n )\n }\n if (this.props.collapseLeft || this.props.collapseRight) {\n console.warn(\n 'Button: The props \"collapseLeft\" and \"collapseRight\" of the \"Button\" component have been deprecated, and will be removed in a future version. Please use the component \"ButtonPlain\" instead'\n )\n }\n }\n\n render() {\n const {\n size,\n block,\n variation,\n icon,\n children,\n isLoading,\n collapseLeft,\n collapseRight,\n isGrouped,\n isActiveOfGroup,\n isFirstOfGroup,\n isLastOfGroup,\n href,\n target,\n rel,\n referrerPolicy,\n download,\n noUpperCase,\n noWrap,\n } = this.props\n\n const disabled = this.props.disabled || isLoading\n const iconOnly = icon || this.props.iconOnly\n\n const isTertiary =\n variation === 'tertiary' ||\n variation === 'inverted-tertiary' ||\n variation === 'danger-tertiary'\n\n let classes = 'vtex-button bw1 ba fw5 v-mid relative pa0 lh-solid '\n let labelClasses =\n 'vtex-button__label flex items-center justify-center h-100 '\n let loaderSize = 15\n let horizontalPadding = 0\n\n classes += !isGrouped ? 'br2 ' : ''\n classes += isFirstOfGroup ? 'br2 br--left ' : ''\n classes += isLastOfGroup ? 'br2 br--right ' : ''\n\n switch (size) {\n case 'small':\n classes += 'min-h-small t-action--small '\n horizontalPadding = iconOnly ? 3 : 5\n break\n case 'large':\n classes += 'min-h-large t-action--large '\n horizontalPadding = iconOnly ? 5 : 7\n loaderSize = 25\n break\n default:\n classes += 'min-h-regular t-action '\n horizontalPadding = iconOnly ? 4 : 6\n loaderSize = 20\n break\n }\n\n if (isTertiary && (collapseLeft || collapseRight)) {\n horizontalPadding = 2\n }\n\n labelClasses += `ph${horizontalPadding} `\n\n if (isTertiary && noUpperCase) {\n labelClasses += 'ttn '\n }\n\n if (collapseLeft && isTertiary) {\n labelClasses += `nl1 `\n }\n if (collapseRight && isTertiary) {\n labelClasses += `nr1 `\n }\n if (noWrap) {\n labelClasses += 'nowrap '\n }\n\n if (iconOnly) {\n classes += 'icon-button dib '\n }\n\n const primaryEnabledClasses =\n 'bg-action-primary b--action-primary c-on-action-primary hover-bg-action-primary hover-b--action-primary hover-c-on-action-primary '\n const secondaryEnabledClasses =\n 'bg-action-secondary b--action-secondary c-on-action-secondary hover-bg-action-secondary hover-b--action-secondary hover-c-on-action-secondary '\n\n if (isGrouped && !disabled) {\n classes += isActiveOfGroup\n ? primaryEnabledClasses\n : secondaryEnabledClasses\n } else {\n switch (variation) {\n default:\n case 'primary': {\n if (disabled) {\n classes += 'bg-disabled b--muted-5 c-on-disabled '\n } else {\n classes += primaryEnabledClasses\n }\n break\n }\n case 'secondary': {\n if (disabled) {\n classes += 'bg-disabled b--muted-5 c-on-disabled '\n } else {\n classes += secondaryEnabledClasses\n }\n break\n }\n case 'tertiary': {\n if (disabled) {\n classes += 'bg-transparent b--transparent c-disabled '\n } else {\n classes +=\n 'bg-transparent b--transparent c-action-primary hover-b--transparent '\n }\n if (!disabled) {\n classes += 'hover-bg-action-secondary hover-b--action-secondary '\n }\n break\n }\n case 'inverted-tertiary': {\n if (disabled) {\n classes += 'bg-transparent b--transparent c-disabled '\n } else {\n classes += 'bg-transparent b--transparent c-on-base--inverted '\n }\n break\n }\n case 'danger': {\n if (disabled) {\n classes += 'bg-disabled b--muted-5 c-on-disabled '\n } else {\n classes +=\n 'bg-danger b--danger c-on-danger hover-bg-danger hover-b--danger hover-c-on-danger '\n }\n break\n }\n case 'danger-tertiary': {\n if (disabled) {\n classes += 'bg-transparent b--transparent c-disabled '\n } else {\n classes +=\n 'bg-transparent b--transparent c-danger hover-bg-danger--faded hover-b--danger--faded '\n }\n break\n }\n }\n }\n\n if (!disabled) {\n classes += 'pointer '\n }\n\n if (block) {\n classes += 'w-100 '\n labelClasses += 'w-100 border-box '\n }\n\n if (href) {\n classes += 'inline-flex items-center no-underline '\n }\n\n const style: any = {}\n\n if (iconOnly) {\n style.fontSize = 0\n }\n\n // Active state receives the hover color of the Button.\n // No token available for this.\n if (isActiveOfGroup && !disabled) {\n style.backgroundColor = '#0c389f'\n style.borderColor = '#0c389f'\n }\n\n const linkModeProps = {\n target,\n rel,\n referrerPolicy,\n download,\n }\n\n const Element = href ? 'a' : 'button'\n\n return (\n <Element\n id={this.props.id}\n data-testid={this.props.testId}\n autoFocus={iconOnly ? undefined : this.props.autoFocus}\n disabled={iconOnly ? undefined : this.props.disabled}\n name={iconOnly ? undefined : this.props.name}\n value={iconOnly ? undefined : this.props.value}\n tabIndex={0}\n className={classes}\n href={href}\n onClick={this.handleClick}\n onMouseEnter={this.props.onMouseEnter}\n onMouseLeave={this.props.onMouseLeave}\n onMouseOver={this.props.onMouseOver}\n onMouseOut={this.props.onMouseOut}\n onMouseUp={this.props.onMouseUp}\n onMouseDown={this.props.onMouseDown}\n onFocus={this.props.onFocus}\n onBlur={this.props.onBlur}\n ref={this.props.forwardedRef}\n style={style}\n // Button-mode exclusive props\n type={href ? undefined : this.props.type}\n // Link-mode exclusive props\n {...(href && linkModeProps)}>\n {isLoading ? (\n <Fragment>\n <span className=\"vtex-button__spinner-container top-0 left-0 w-100 h-100 absolute flex justify-center items-center\">\n <Spinner\n secondary={variation === 'primary' || variation === 'danger'}\n size={loaderSize}\n />\n </span>\n <span className={`${labelClasses} o-0`}>{children}</span>\n </Fragment>\n ) : (\n <div\n className={labelClasses}\n style={{\n paddingTop: '.25em',\n paddingBottom: '.32em',\n }}>\n {children}\n </div>\n )}\n </Element>\n )\n }\n}\n\nexport default withForwardedRef(Button) as any\n\n```" } ]
code_store-on-localhost_10154051
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Button/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### Buttons are independent interactive elements used to trigger actions or to perform navigation.\n\n### Chosing a variation\nOur Styleguide defines 3 main variations based on the button visual proeminence. As with any UI element, the proeminence should be proportional to the importance of that element.\n- Do mix variations as needed.\n- Avoid having more than one Primary button, save this kind for the most important or most recommended action in a given screen.\n- Use the Danger variation for destructive actions that delete data or lead to a state that is hard to recover. Danger buttons should _always_ have a confirmation dialog.\n- In doubt, use Secondary buttons.\n- Since reading speed can be slowed down by up to 20% when reading all caps (Breland & Breland - 1944), beware of \"phrase long\" button texts. Keep it short, and make your point in 3 words or less.\n\n\nTypes\n\n```js\n<div className=\"flex justify-center\">\n <div className=\"flex flex-column items-center w-100\">\n <span className=\"mb4\">\n <Button variation=\"primary\">Primary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"secondary\">Secondary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"tertiary\">Tertiary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"danger\">Danger</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"danger-tertiary\">Danger Tertiary</Button>\n </span>\n <span className=\"bg-base--inverted w-100 pa4 flex justify-center\">\n <span className=\"mb4\">\n <Button variation=\"inverted-tertiary\">Inverted Tertiary</Button>\n </span>\n </span>\n </div>\n <div className=\"flex flex-column items-center w-100\">\n <span className=\"mb4\">\n <Button variation=\"primary\" disabled>Primary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"secondary\" disabled>Secondary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"tertiary\" disabled>Tertiary</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"danger\" disabled>Danger</Button>\n </span>\n <span className=\"mb4\">\n <Button variation=\"danger-tertiary\" disabled>Danger Tertiary</Button>\n </span>\n <span className=\"bg-base--inverted w-100 pa4 flex justify-center\">\n <span className=\"mb4\">\n <Button variation=\"inverted-tertiary\" disabled>Inverted Tertiary</Button>\n </span>\n </span>\n </div>\n</div>\n```\n\nSizes\n\n```js\n<div>\n <div className=\"mb4\">\n <span className=\"mr4\">\n <Button variation=\"primary\" size=\"small\">\n Small\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"primary\">\n Regular\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"primary\" size=\"large\">\n Large\n </Button>\n </span>\n </div>\n <div className=\"mb4\">\n <span className=\"mr4\">\n <Button variation=\"secondary\" size=\"small\">\n Small\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"secondary\" size=\"regular\">\n Regular\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"secondary\" size=\"large\">\n Large\n </Button>\n </span>\n </div>\n <div className=\"mb4\">\n <span className=\"mr4\">\n <Button variation=\"tertiary\" size=\"small\">\n Small\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"tertiary\" size=\"regular\">\n Regular\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"tertiary\" size=\"large\">\n Large\n </Button>\n </span>\n </div>\n <div className=\"mb4\">\n <span className=\"mr4\">\n <Button variation=\"danger\" size=\"small\">\n Small\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"danger\" size=\"regular\">\n Regular\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"danger\" size=\"large\">\n Large\n </Button>\n </span>\n </div>\n <div className=\"mb4\">\n <span className=\"mr4\">\n <Button variation=\"danger-tertiary\" size=\"small\">\n Small\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"danger-tertiary\" size=\"regular\">\n Regular\n </Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"danger-tertiary\" size=\"large\">\n Large\n </Button>\n </span>\n </div>\n</div>\n```\n\nBox types\n\n```js\n<div>\n <div className=\"mb4\">\n <Button variation=\"primary\">Default</Button>\n </div>\n <div className=\"mb4\">\n <Button variation=\"primary\" block>\n Block\n </Button>\n </div>\n</div>\n```\n\nLink mode\n\n```js\n<div className=\"mb4\">\n <Button variation=\"primary\" href=\"http://vtex.com\" target=\"_blank\">Sign in</Button>\n</div>\n```\n\nCancelling out button paddings. Useful for visually aligning tertiary buttons\n\n```js\nconst Box = require('../Box').default\n\n;<>\n <div className=\"flex justify-center\">\n <div className=\"flex flex-column w-60\">\n <div className=\"t-heading-6 mb4\">Use collapse props when tertiary button is alone, to align it with the other elements</div>\n <div className=\"w-100 mb4\">\n <Box />\n </div>\n <div className=\"mb4 flex justify-between\">\n <Button variation=\"tertiary\" collapseLeft>Collapse left</Button>\n <Button variation=\"tertiary\" collapseRight>Collapse right</Button>\n </div>\n </div>\n </div>\n <div className=\"flex justify-center mt6\">\n <div className=\"flex flex-column w-60\">\n <div className=\"t-heading-6 mb4\">Don't collapse when the button is not alone</div>\n <div className=\"w-100 mb4\">\n <Box />\n </div>\n <div className=\"mb4 flex\">\n <Button variation=\"tertiary\">Default</Button>\n <div className=\"ml2\">\n <Button variation=\"secondary\">Another Button</Button>\n </div>\n </div>\n </div>\n </div>\n <div className=\"flex justify-center mt6\">\n <div className=\"flex flex-column w-60\">\n <div className=\"t-heading-6 mb4\">Collapse props don't work on primary and secondary variations (and it shouldn't)</div>\n <div className=\"w-100 mb4\">\n <Box />\n </div>\n <div className=\"mb4 flex justify-between\">\n <Button variation=\"primary\" collapseLeft>Collapse left</Button>\n <Button variation=\"primary\" collapseRight>Collapse right</Button>\n </div>\n <div className=\"w-100 mb4\">\n <Box />\n </div>\n <div className=\"mb4 flex justify-between\">\n <Button variation=\"secondary\" collapseLeft>Collapse left</Button>\n <Button variation=\"secondary\" collapseRight>Collapse right</Button>\n </div>\n </div>\n </div>\n</>;\n```\nColored container background\n\n```js\n<div className=\"bg-warning--faded pa5\">\n <div>\n <span className=\"mr4\">\n <Button variation=\"primary\">Primary</Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"secondary\">Secondary</Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"tertiary\">Neutral</Button>\n </span>\n </div>\n <div className=\"mt4\">\n <span className=\"mr4\">\n <Button variation=\"primary\" disabled>Primary</Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"secondary\" disabled>Secondary</Button>\n </span>\n <span className=\"mr4\">\n <Button variation=\"tertiary\" disabled>Neutral</Button>\n </span>\n </div>\n</div>\n```\n\nLoading state\n\n```js\ninitialState = { isLoading1: true, isLoading2: true, isLoading3: true };\n<div>\n <div className=\"mt4\">\n <Button\n variation=\"primary\"\n onClick={() => setState({ isLoading2: !state.isLoading2 })}\n isLoading={state.isLoading2}\n >\n Toggle loading state\n </Button>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_1acdd503
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Link/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport ExternalLink from '../icon/ExternalLink'\n\nconst classes =\n 'pointer c-link hover-c-link active-c-link no-underline underline-hover'\n\nconst Link = ({ children, href, target, mediumWeigth }) => (\n <a\n href={href}\n target={target}\n className={`${classes} ${mediumWeigth ? 'fw5' : ''}`}>\n {children}\n {target === '_blank' && (\n <span className=\"ml2\">\n <ExternalLink size={12} />\n </span>\n )}\n </a>\n)\n\nLink.defaultProps = {\n target: '_self',\n mediumWeigth: false,\n}\n\nLink.propTypes = {\n /** Content of the link */\n children: PropTypes.string.isRequired,\n /** Spec attribute */\n href: PropTypes.string.isRequired,\n /** Spec attribute */\n target: PropTypes.oneOf(['_self', '_blank', '_parent', '_top']),\n /** Weight property */\n mediumWeigth: PropTypes.bool,\n}\n\nexport default Link\n\n```" } ]
code_store-on-localhost_c2d05711
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Link/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Link is an anchor tag.\n\n### ๐Ÿ‘ Dos\n\n- Use them for links. When user needs to take an action, swtich for the <a href=\"#/Components/Forms/Button\">Button</a> component.\n- Use normal and medium weights when outside a paragraph. Designers can choose which one is the best depending on the context and layout.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Use medium weigth when the link is inline, eg, within a paragraph.\n\n### Related components\n\n- <a href=\"#/Components/Forms/Button\">Button</a>.\n\nWithin a paragraph:\n\n```js\n<div>\n <p>\n It is simply dummy text of the printing and typesetting industry. Lorem\n Ipsum has been the{' '}\n <Link href=\"https://www.vtex.com/\">industry's standard</Link> dummy text\n ever since the 1500s, when an unknown printer took a galley of type and\n scrambled it to make a type specimen book.\n </p>\n <p>\n <Link href=\"https://www.vtex.com/\" target=\"_blank\" mediumWeigth>\n External link\n </Link>\n </p>\n</div>\n```\n\nWithin an unordered list:\n\n```js\n<ul>\n <li>\n <Link href=\"#\">Item 1</Link>\n </li>\n <li>\n <Link href=\"#\" mediumWeigth>\n Item 2\n </Link>\n </li>\n <li>\n <Link href=\"#\">Item 3</Link>\n </li>\n</ul>\n```\n\n```" } ]
code_store-on-localhost_f19c58ff
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Dropzone/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent, createRef } from 'react'\nimport PropTypes from 'prop-types'\nimport ReactDropZone from 'react-dropzone'\n\nimport FileIcon from './FileIcon'\nimport Spinner from '../Spinner'\nimport ButtonWithIcon from '../ButtonWithIcon'\nimport IconDelete from '../icon/Delete'\n\nconst dropzoneRef = createRef()\n\nclass Dropzone extends PureComponent {\n state = {\n files: [],\n isHovering: false,\n fileDropped: false,\n }\n\n handleDragEnter = () => {\n this.setState({ isHovering: true })\n }\n\n handleDragLeave = () => {\n this.setState({ isHovering: false })\n }\n\n handleDropAccepted = files => {\n this.setState({ isHovering: false, fileDropped: true, files })\n this.props.onDropAccepted(files)\n }\n\n handleDropRejected = files => {\n this.setState({ isHovering: false })\n this.props.onDropRejected(files)\n }\n\n handleRemoveFile = fileIndex => {\n const { files } = this.state\n\n if (files.length > 1) {\n const filteredFiles = files.filter((_, i) => i !== fileIndex)\n this.setState({ files: filteredFiles }, () => {\n this.props.onFileReset(filteredFiles)\n })\n } else {\n this.handleReset()\n this.props.onFileReset()\n }\n }\n\n handleReset = () => {\n this.setState({ files: [], fileDropped: false })\n }\n\n render() {\n const { children, isLoading, icon, multiple } = this.props\n const { isHovering, fileDropped, files } = this.state\n const initialState = !isHovering && !fileDropped\n\n let dropzoneContainerClasses =\n 'flex flex-column items-center justify-center b--light-blue ba br2 bw1 b--dashed '\n let iconHolderClasses =\n 'flex items-center justify-center pa6 bg-near-white '\n const droppedContainerClasses = 'w-100 '\n\n const holderSize = '120px'\n const iconHolderStyles = {\n borderRadius: '100%',\n width: holderSize,\n height: holderSize,\n }\n\n if (initialState) {\n dropzoneContainerClasses += 'pa8 '\n }\n\n if (isHovering) {\n dropzoneContainerClasses += 'pa8 b--action-primary bg-action-secondary '\n iconHolderClasses += 'bg-action-primary '\n }\n\n if (fileDropped) {\n dropzoneContainerClasses += 'pv4 ph5 bg-muted-5 b--muted-3 '\n }\n\n return (\n <ReactDropZone\n ref={dropzoneRef}\n multiple={multiple}\n onDropAccepted={this.handleDropAccepted}\n onDropRejected={this.handleDropRejected}\n onDragEnter={this.handleDragEnter}\n onDragLeave={this.handleDragLeave}>\n {({ getRootProps, getInputProps }) => (\n <div className={dropzoneContainerClasses} {...getRootProps()}>\n {isLoading ? (\n <div className={iconHolderClasses} style={iconHolderStyles}>\n <Spinner size={32} />\n </div>\n ) : fileDropped ? (\n <div className={droppedContainerClasses}>\n {files.map((file, fileIndex) => (\n <div\n key={file.name}\n className={`black-70 flex flex-row justify-between items-center ${\n files.length > 1 && fileIndex !== files.length - 1\n ? 'mb2'\n : ''\n }`}>\n <span>{file.name}</span>\n <ButtonWithIcon\n onClick={() => this.handleRemoveFile(fileIndex)}\n variation=\"tertiary\"\n icon={<IconDelete />}\n />\n </div>\n ))}\n </div>\n ) : (\n <>\n <input {...getInputProps()} />\n <div className={iconHolderClasses} style={iconHolderStyles}>\n {icon || <FileIcon />}\n </div>\n {children && children}\n </>\n )}\n </div>\n )}\n </ReactDropZone>\n )\n }\n}\n\nDropzone.defaultProps = {\n onDropRejected: () => {},\n children: null,\n icon: null,\n isLoading: false,\n onFileReset: () => {},\n multiple: false,\n}\n\nDropzone.propTypes = {\n /** Callback when file(s) is(are) droppped and accepted */\n onDropAccepted: PropTypes.func.isRequired,\n /** Callback when file(s) is(are) droppped and rejected (e.g: when props.multiple is false and multiple files are dragged and dropped.*/\n onDropRejected: PropTypes.func,\n /** Callback when a file is removed */\n onFileReset: PropTypes.func,\n /** Content after the file icon */\n children: PropTypes.node,\n /** Loading state */\n isLoading: PropTypes.bool,\n /** Custom icon */\n icon: PropTypes.node,\n /** Allow multiple files drop */\n multiple: PropTypes.bool,\n}\n\nexport default Dropzone\n\n```" } ]
code_store-on-localhost_58f7a081
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Dropzone/FileIcon.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\n\nconst FileIcon = () => (\n <svg width=\"40\" height=\"46\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path\n d=\"M24.793.793A1 1 0 0 0 24.086.5H1.5a1 1 0 0 0-1 1v43a1 1 0 0 0 1 1h37a1 1 0 0 0 1-1V15.914a1 1 0 0 0-.293-.707L24.793.793z\"\n fill=\"#E3E4E6\"\n />\n <path\n d=\"M9.5 33.5h21M9.5 24.5h21\"\n stroke=\"#3F3F40\"\n strokeWidth=\"1.2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M9.5 15.5h6\"\n stroke=\"#F71963\"\n strokeWidth=\"1.2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path d=\"M24.5.5v15h15\" fill=\"#CACBCC\" />\n </svg>\n)\n\nexport default FileIcon\n\n```" } ]
code_store-on-localhost_5aeafaae
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Dropzone/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A Dropzone is an area for a drag and drop of files.\n\nWorking example\n\n```js\nclass MyDropZone extends React.Component {\n constructor() {\n super()\n this.state = { files: null }\n this.handleFile = this.handleFile.bind(this)\n }\n\n handleFile(files) {\n console.log(files)\n }\n\n handleReset(files) {\n if (files) {\n console.log(files)\n }\n }\n\n render() {\n return (\n <Dropzone onDropAccepted={this.handleFile} onFileReset={this.handleReset}>\n <div className=\"pt7\">\n <div>\n <span className=\"f4\">Drop here your XLS or </span>\n <span className=\"f4 c-link\" style={{ cursor: 'pointer' }}>\n choose a file\n </span>\n </div>\n </div>\n </Dropzone>\n )\n }\n}\n;<MyDropZone />\n```\n\nCustom icon\n\n```js\nconst TableIcon = (\n <svg width=\"44\" height=\"36\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M0 24h44v11a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1V24z\" fill=\"#E3E4E6\" />\n <rect x=\"4\" y=\"29\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"18\" y=\"29\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"36\" y=\"29\" width=\"4\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <path d=\"M44 12H0V1a1 1 0 0 1 1-1h42a1 1 0 0 1 1 1v11z\" fill=\"#F71963\" />\n <rect\n x=\"40\"\n y=\"7\"\n width=\"4\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 40 7)\"\n fill=\"#fff\"\n />\n <rect\n x=\"26\"\n y=\"7\"\n width=\"8\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 26 7)\"\n fill=\"#fff\"\n />\n <rect\n x=\"12\"\n y=\"7\"\n width=\"8\"\n height=\"2\"\n rx=\"1\"\n transform=\"rotate(180 12 7)\"\n fill=\"#fff\"\n />\n <path d=\"M0 12h44v12H0V12z\" fill=\"#CACBCC\" />\n <rect x=\"4\" y=\"17\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"18\" y=\"17\" width=\"8\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n <rect x=\"36\" y=\"17\" width=\"4\" height=\"2\" rx=\"1\" fill=\"#727273\" />\n </svg>\n)\n;<div>\n <Dropzone icon={TableIcon} />\n</div>\n```\n\nLoading state\n\n```js\n<Dropzone isLoading />\n```\n\n```" } ]
code_store-on-localhost_97ad4fde
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/CheckboxContainer.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Checkbox from '../Checkbox'\n\nclass CheckboxContainer extends Component {\n static defaultProps = {\n partial: false,\n disabled: false,\n }\n\n static propTypes = {\n checked: PropTypes.bool.isRequired,\n partial: PropTypes.bool,\n onClick: PropTypes.func.isRequired,\n disabled: PropTypes.bool,\n id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n }\n\n render() {\n const { checked, partial, id, onClick, disabled } = this.props\n\n return (\n <div className=\"flex items-center justify-center aspect-ratio--object\">\n <div\n className=\"br2 h2 w2 flex items-center justify-center\"\n onClick={e => {\n e.stopPropagation()\n onClick(id)\n // prevents the onRowClick event from happening\n }}>\n <Checkbox\n checked={checked}\n partial={partial}\n value={`${id}`}\n id={`${id}`}\n name={`row_${id}`}\n onChange={() => {}}\n disabled={disabled}\n />\n </div>\n </div>\n )\n }\n}\n\nexport default CheckboxContainer\n\n```" } ]
code_store-on-localhost_4bf1f775
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/sampleData.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst generateRandomColorObject = () => {\n const tagData = [\n {\n color: '#F71963',\n label: 'Rebel pink',\n },\n {\n color: '#00BBD4',\n label: 'Young blue',\n },\n {\n color: '#D6D8E0',\n label: 'Cold gray',\n },\n {\n color: '#142032',\n label: 'Serious black',\n },\n ]\n return tagData[Math.floor(Math.random() * tagData.length)]\n}\n\nexport default {\n defaultSchema: {\n properties: {\n name: {\n type: 'string',\n title: 'Name',\n },\n email: {\n type: 'string',\n title: 'Email',\n width: 300,\n },\n number: {\n type: 'number',\n title: 'Number',\n },\n },\n },\n items: [\n {\n email: 'olen.stamm21@yahoo.com',\n name: 'Patrick Rothfuss',\n number: 1.52725,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'junius0@gmail.com',\n name: 'Hurricane Skywalker IV',\n number: 2.84639,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'judd_gulgowski22@yahoo.com',\n name: 'Tom Braddy',\n number: 4.10182,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'catharine.leuschke62@hotmail.com',\n name: 'Momochi Zabuza',\n number: 6.33245,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'candido_ryan@hotmail.com',\n name: 'Freddie Mercury',\n number: 7.96637,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'freda_ritchie26@yahoo.com',\n name: 'Dr. Lempi Mosciski',\n number: 8.42623,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'elissa28@gmail.com',\n name: 'Nikita Feeney',\n number: 9.11769,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'reginald1@yahoo.com',\n name: 'Janick Lesch',\n number: 10.85311,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'hailee.botsford24@gmail.com',\n name: 'Mr. Ron Smith',\n number: 3.23851,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'gaetano.mayert71@yahoo.com',\n name: 'Norris Murazik',\n number: 5.33725,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'jerad_hyatt@hotmail.com',\n name: 'Golda Carter',\n number: 11.44288,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'jaquan.fisher61@yahoo.com',\n name: 'Dr. Cassandra Jerde',\n number: 12.73372,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'marlee_ziemann@yahoo.com',\n name: 'Kvothe Kshlerin',\n number: 13.62416,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'erman_Beier@yahoo.com',\n name: 'Arch Hegmann',\n number: 14.8212,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'arturo_schroeder30@yahoo.com',\n name: 'Alejandro Strosin',\n number: 15.73701,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'santos_doyle36@gmail.com',\n name: 'Zidane Vandervort',\n number: 16.26124,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'yvonne.gleason@hotmail.com',\n name: 'Tonny Balistreri',\n number: 17.79484,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'michaela51@hotmail.com',\n name: 'Emanuel Ullrich',\n number: 18.57879,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'erik_kuvalis41@hotmail.com',\n name: 'Beto',\n number: 19.87262,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'edwardo_kuvalis@hotmail.com',\n name: 'Mrs. Deion Beahan',\n number: 20.13464,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'alexa_ondricka45@hotmail.com',\n name: 'Trent Kerluke',\n number: 21.9677,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'darron_brakus63@yahoo.com',\n name: 'Jacquelyn Flatley Jr.',\n number: 22.55405,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'jamie.hermann60@gmail.com',\n name: 'Ervin Kuphal',\n number: 23.76965,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n {\n email: 'cleo.klein@hotmail.com',\n name: 'Terrence Gutmann',\n number: 24.55731,\n color: generateRandomColorObject(),\n color1: generateRandomColorObject(),\n color2: generateRandomColorObject(),\n color3: generateRandomColorObject(),\n color4: generateRandomColorObject(),\n color5: generateRandomColorObject(),\n color6: generateRandomColorObject(),\n },\n ],\n}\n\n```" } ]
code_store-on-localhost_400086c2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport { StickyContainer } from 'react-sticky'\nimport PropTypes from 'prop-types'\nimport reduce from 'lodash/reduce'\nimport map from 'lodash/map'\nimport isEmpty from 'lodash/isEmpty'\n\nimport Box from '../Box'\nimport EmptyState from '../EmptyState'\nimport FilterBar from '../FilterBar'\nimport SimpleTable from './SimpleTable'\nimport Toolbar from './Toolbar'\nimport CheckboxContainer from './CheckboxContainer'\nimport Totalizers from '../Totalizer'\nimport BulkActions from './BulkActions'\nimport SwitchablePagination from './SwitchablePagination'\n\nclass Table extends PureComponent {\n constructor(props) {\n super(props)\n this.state = {\n hiddenFields: this.getInitialHiddenFieldsFromSchema(props.schema),\n tableRowHeight: this.getRowHeight(props.density),\n selectedDensity: props.density,\n allChecked: false,\n selectedRows: this.props.bulkActions.selectedRows || [],\n allLinesSelected: false,\n }\n }\n\n componentDidUpdate() {\n const { bulkActions } = this.props\n const { selectedRows } = this.state\n\n if (\n bulkActions &&\n bulkActions.selectedRows &&\n bulkActions.selectedRows !== selectedRows\n ) {\n this.setState({ selectedRows: bulkActions.selectedRows })\n }\n }\n\n getInitialHiddenFieldsFromSchema = schema => {\n const hiddenFields = []\n Object.keys(schema.properties).forEach(key => {\n if (schema.properties[key].hidden) {\n hiddenFields.push(key)\n }\n })\n return hiddenFields\n }\n\n getRowHeight = density => {\n switch (density) {\n case 'low':\n return 76\n case 'medium':\n return 48\n case 'high':\n return 32\n default:\n return 45\n }\n }\n\n handleTableRowHeight = density => {\n const { tableRowHeight } = this.state\n const newHeight = this.getRowHeight(density)\n if (tableRowHeight !== newHeight) {\n this.setState({\n tableRowHeight: newHeight,\n selectedDensity: density,\n })\n }\n }\n\n handleToggleColumn = key => {\n const { hiddenFields } = this.state\n const newFieldsArray = hiddenFields.slice()\n const index = hiddenFields.indexOf(key)\n index === -1 ? newFieldsArray.push(key) : newFieldsArray.splice(index, 1)\n this.setState({ hiddenFields: newFieldsArray })\n }\n\n handleShowAllColumns = () => {\n this.setState({ hiddenFields: [] })\n }\n\n handleHideAllColumns = () => {\n this.setState({ hiddenFields: Object.keys(this.props.schema.properties) })\n }\n\n handleSelectionChange = () => {\n if (this.props.bulkActions && this.props.bulkActions.onChange) {\n const selectedParameters = this.state.allLinesSelected\n ? { allLinesSelected: true }\n : { selectedRows: this.state.selectedRows }\n this.props.bulkActions.onChange(selectedParameters)\n }\n }\n\n handleSelectAllLines = () => {\n const { items: selectedRows } = this.props\n this.setState(\n { selectedRows, allLinesSelected: true },\n this.handleSelectionChange\n )\n }\n\n handleSelectAllVisibleLines = () => {\n const selectedRows = this.state.selectedRows.slice(0)\n const { items } = this.props\n const itemsLength = items.length\n\n if (selectedRows.length <= itemsLength && selectedRows.length !== 0) {\n this.handleDeselectAllLines()\n } else {\n this.setState({ selectedRows: items }, this.handleSelectionChange)\n }\n }\n\n handleSelectLine = rowData => {\n const selectedRows = this.state.selectedRows.slice(0)\n const { id } = rowData\n\n if (selectedRows.some(el => el.id === id)) {\n const filteredRows = selectedRows.filter(row => row.id !== id)\n this.setState({ selectedRows: filteredRows }, this.handleSelectionChange)\n } else {\n selectedRows.push({ ...rowData })\n this.setState({ selectedRows }, this.handleSelectionChange)\n }\n }\n\n handleDeselectAllLines = () => {\n this.setState(\n { selectedRows: [], allLinesSelected: false },\n this.handleSelectionChange\n )\n }\n\n handleInputSearchClearWithBulkAction = event => {\n const {\n toolbar: {\n inputSearch: { onClear = () => {} },\n },\n } = this.props\n this.handleDeselectAllLines()\n onClear(event)\n }\n\n render() {\n const {\n items,\n schema,\n disableHeader,\n emptyStateLabel,\n emptyStateChildren,\n fixFirstColumn,\n onRowClick,\n onRowHover,\n sort,\n onSort,\n updateTableKey,\n containerHeight,\n toolbar,\n pagination,\n fullWidth,\n dynamicRowHeight,\n lineActions,\n loading,\n bulkActions,\n totalizers,\n filters,\n } = this.props\n const {\n hiddenFields,\n tableRowHeight,\n selectedDensity,\n selectedRows,\n allLinesSelected,\n } = this.state\n\n const hasPrimaryBulkAction =\n bulkActions &&\n bulkActions.main &&\n typeof bulkActions.main.handleCallback === 'function'\n const hasSecondaryBulkActions =\n bulkActions.others && bulkActions.others.length > 0\n const hasBulkActions = hasPrimaryBulkAction || hasSecondaryBulkActions\n\n if (hasBulkActions) {\n schema.properties = {\n bulk: {\n width: 40,\n headerRenderer: () => {\n const { selectedRows } = this.state\n const selectedRowsLength = selectedRows.length\n const itemsLength = this.props.items.length\n\n const isChecked = selectedRowsLength === itemsLength\n const isPartial =\n selectedRowsLength > 0 && selectedRowsLength < itemsLength\n\n return (\n <CheckboxContainer\n checked={isChecked}\n onClick={this.handleSelectAllVisibleLines}\n id=\"all\"\n partial={isPartial}\n />\n )\n },\n cellRenderer: ({ rowData }) => (\n <CheckboxContainer\n checked={this.state.selectedRows.some(\n row => row.id === rowData.id\n )}\n onClick={() => this.handleSelectLine(rowData)}\n id={rowData.id}\n disabled={this.state.allLinesSelected}\n />\n ),\n },\n ...schema.properties,\n }\n\n items.map((item, i) => (item.id = i))\n }\n\n const properties = Object.keys(schema.properties)\n const emptyState = !!(\n properties.length === 0 || properties.length === hiddenFields.length\n )\n const displayProperties = reduce(\n schema.properties,\n (acc, value, key) => {\n if (hiddenFields.includes && hiddenFields.includes(key)) {\n return acc\n }\n return { ...acc, [key]: value }\n },\n {}\n )\n const displaySchema = {\n ...schema,\n properties: displayProperties,\n }\n\n // if pagination and bulk actions features are active at the same time\n // when paginating, bulk actions active lines should be deselected\n const paginationClone = pagination ? Object.assign({}, pagination) : null\n if (paginationClone && hasBulkActions) {\n paginationClone.onNextClick = () => {\n this.handleDeselectAllLines()\n pagination.onNextClick()\n }\n paginationClone.onPrevClick = () => {\n this.handleDeselectAllLines()\n pagination.onPrevClick()\n }\n }\n\n // extend toolbar's input search onClear when bulk action is turned on to\n // deselect all lines when clearing to avoid weird unwanted behaviors\n // until a permanent solution for https://github.com/vtex/styleguide/issues/873\n // is found\n const extendedToolbar = toolbar\n ? {\n ...toolbar,\n inputSearch: toolbar.inputSearch\n ? {\n ...toolbar.inputSearch,\n onClear: hasBulkActions\n ? this.handleInputSearchClearWithBulkAction\n : toolbar.inputSearch.onClear,\n }\n : null,\n }\n : null\n\n return (\n <div className=\"vtex-table__container\">\n {extendedToolbar && (\n <Toolbar\n loading={loading}\n hiddenFields={hiddenFields}\n onToggleColumn={this.handleToggleColumn}\n onDeselectAllLines={this.handleDeselectAllLines}\n onHideAllColumns={this.handleHideAllColumns}\n onShowAllColumns={this.handleShowAllColumns}\n onToggleDensity={this.handleTableRowHeight}\n selectedDensity={selectedDensity}\n schema={schema}\n actions={extendedToolbar}\n />\n )}\n\n {filters && (\n <div className=\"mb5\">\n <FilterBar {...filters} />\n </div>\n )}\n\n {totalizers && (\n <div className=\"mb5\">\n {Array.isArray(totalizers) ? (\n <Totalizers items={totalizers} />\n ) : (\n <Totalizers {...totalizers} />\n )}\n </div>\n )}\n\n <SwitchablePagination\n enabled={!loading && !isEmpty(paginationClone)}\n {...paginationClone}>\n <StickyContainer>\n <BulkActions\n hasPrimaryBulkAction={hasPrimaryBulkAction}\n hasSecondaryBulkActions={hasSecondaryBulkActions}\n selectedRows={selectedRows}\n bulkActions={bulkActions}\n allLinesSelected={allLinesSelected}\n onSelectAllLines={this.handleSelectAllLines}\n onDeselectAllLines={this.handleDeselectAllLines}\n />\n\n {emptyState ? (\n <Box>\n <EmptyState title={emptyStateLabel}>\n {emptyStateChildren}\n </EmptyState>\n </Box>\n ) : (\n <SimpleTable\n fullWidth={fullWidth}\n items={items}\n schema={displaySchema}\n fixFirstColumn={fixFirstColumn}\n rowHeight={tableRowHeight}\n disableHeader={disableHeader}\n emptyStateLabel={emptyStateLabel}\n emptyStateChildren={emptyStateChildren}\n dynamicRowHeight={dynamicRowHeight}\n onRowClick={onRowClick}\n onRowHover={onRowHover}\n sort={sort}\n onSort={onSort}\n key={hiddenFields.toString()}\n updateTableKey={updateTableKey}\n lineActions={lineActions}\n loading={loading}\n containerHeight={containerHeight}\n selectedRowsIndexes={map(selectedRows, 'id')}\n density={selectedDensity}\n />\n )}\n </StickyContainer>\n </SwitchablePagination>\n </div>\n )\n }\n}\n\nTable.defaultProps = {\n loading: false,\n density: 'medium',\n fixFirstColumn: false,\n toolbar: null,\n emptyStateLabel: 'Nothing to show.',\n fullWidth: false,\n bulkActions: {},\n totalizers: [],\n}\n\nTable.propTypes = {\n /** Array of objects with data */\n items: PropTypes.array.isRequired,\n /** JSON defining the data model schema for the items (More info about it after the examples) */\n schema: PropTypes.object.isRequired,\n /** Do not render the table header (only the rows) */\n disableHeader: PropTypes.bool,\n /** Fix first column so only the following ones scroll horizontaly */\n fixFirstColumn: PropTypes.bool,\n /** Callback invoked when a user clicks on a table row. ({ event: Event, index: number, rowData: any }): void */\n onRowClick: PropTypes.func,\n /** Callback invoked when a user hovers a table row. (rowIndex): void */\n onRowHover: PropTypes.func,\n /** Sort order and which property (key in schema) is table data sorted by. */\n sort: PropTypes.shape({\n sortOrder: PropTypes.oneOf(['ASC', 'DESC']),\n sortedBy: PropTypes.string,\n }),\n /** Callback to handle sort ({ sortOrder, sortedBy }) : object */\n onSort: PropTypes.func,\n /** Forces table re-render when changed */\n updateTableKey: PropTypes.string,\n /** In case you need precise control of table container height (number in pixels) */\n containerHeight: PropTypes.number,\n /** Row info visual density */\n density: PropTypes.oneOf(['low', 'medium', 'high']),\n /** Label for emptystate */\n emptyStateLabel: PropTypes.string,\n /** Children for emptystate */\n emptyStateChildren: PropTypes.node,\n /** Full width property */\n fullWidth: PropTypes.bool,\n /** Allows rows to show the full height of their content */\n dynamicRowHeight: PropTypes.bool,\n /** Line actions column */\n lineActions: PropTypes.arrayOf(\n PropTypes.shape({\n /** Function that returns a string for the action label */\n label: PropTypes.func,\n /** Mark whether the action performs a dangerous option or not */\n isDangerous: PropTypes.bool,\n /** Handles the callback function of the action */\n onClick: PropTypes.func,\n })\n ),\n /** Controls the table loading state */\n loading: PropTypes.bool,\n /** Toolbar (search and actions) */\n toolbar: PropTypes.shape({\n inputSearch: PropTypes.shape({\n onSubmit: PropTypes.func,\n onClear: PropTypes.func,\n }),\n density: PropTypes.shape({\n buttonLabel: PropTypes.string,\n lowOptionLabel: PropTypes.string,\n mediumOptionLabel: PropTypes.string,\n highOptionLabel: PropTypes.string,\n alignMenu: PropTypes.oneOf(['right', 'left']),\n handleCallback: PropTypes.func,\n }),\n fields: PropTypes.shape({\n label: PropTypes.string,\n showAllLabel: PropTypes.string,\n hideAllLabel: PropTypes.string,\n alignMenu: PropTypes.oneOf(['right', 'left']),\n }),\n download: PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n disabled: PropTypes.bool,\n }),\n upload: PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n disabled: PropTypes.bool,\n }),\n extraActions: PropTypes.shape({\n label: PropTypes.string,\n actions: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n })\n ),\n alignMenu: PropTypes.oneOf(['right', 'left']),\n }),\n newLine: PropTypes.shape({\n label: PropTypes.string.isRequired,\n handleCallback: PropTypes.func.isRequired,\n disabled: PropTypes.bool,\n }),\n }),\n pagination: PropTypes.shape({\n onNextClick: PropTypes.func,\n onPrevClick: PropTypes.func,\n currentItemFrom: PropTypes.number,\n currentItemTo: PropTypes.number,\n textOf: PropTypes.node,\n totalItems: PropTypes.number,\n }),\n bulkActions: PropTypes.shape({\n texts: PropTypes.shape({\n secondaryActionsLabel: PropTypes.string.isRequired,\n rowsSelected: PropTypes.func.isRequired,\n selectAll: PropTypes.string,\n allRowsSelected: PropTypes.func,\n }),\n totalItems: PropTypes.number,\n onChange: PropTypes.func,\n selectedRows: PropTypes.array,\n main: PropTypes.shape({\n label: PropTypes.string.isRequired,\n handleCallback: PropTypes.func.isRequired,\n }),\n others: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string.isRequired,\n handleCallback: PropTypes.func.isRequired,\n })\n ),\n fixed: PropTypes.bool,\n }),\n /** Totalizers property */\n totalizers: PropTypes.oneOfType([\n PropTypes.array,\n PropTypes.shape({\n mobileScroll: PropTypes.bool,\n horizontalLayout: PropTypes.bool,\n items: PropTypes.array,\n }),\n ]),\n /** Filters property */\n filters: PropTypes.shape({ ...FilterBar.propTypes }),\n}\n\nexport default Table\n\n```" } ]
code_store-on-localhost_717f9c73
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/BulkActions.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\nimport classNames from 'classnames'\nimport { Sticky } from 'react-sticky'\n\nimport Button from '../Button'\nimport ButtonWithIcon from '../ButtonWithIcon'\nimport ActionMenu from '../ActionMenu'\nimport Close from '../icon/Close'\nimport BulkActionsSelectedRows from './BulkActionsSelectedRows'\n\nconst DEFAULT_BAR_HEIGHT_PX = '56px'\nconst close = <Close />\n\nclass BulkActions extends PureComponent {\n render() {\n const {\n hasPrimaryBulkAction,\n hasSecondaryBulkActions,\n selectedRows,\n bulkActions,\n allLinesSelected,\n onSelectAllLines,\n onDeselectAllLines,\n } = this.props\n\n const hasBulkActions = hasPrimaryBulkAction || hasSecondaryBulkActions\n const selectedRowsLength = selectedRows.length\n const hasRowsSelected = selectedRowsLength > 0\n const fixed = bulkActions && bulkActions.fixed\n const canStickToTop = fixed && hasRowsSelected\n\n const bulkActionsReturnedParameters = allLinesSelected\n ? { allLinesSelected: true }\n : { selectedRows }\n\n return (\n <Sticky disableCompensation={!canStickToTop}>\n {({ style: stickyStyle, isSticky }) => (\n <div\n className={classNames(\n 'flex flex-row justify-between bg-action-primary c-on-action-primary ph4',\n {\n 'pv4 overflow-auto': hasRowsSelected,\n 'overflow-hidden': !hasRowsSelected,\n 'shadow-4 z-1': canStickToTop && isSticky,\n 'br3 br--top': !(canStickToTop && isSticky),\n }\n )}\n style={{\n ...(canStickToTop && stickyStyle),\n height: hasRowsSelected ? DEFAULT_BAR_HEIGHT_PX : 0,\n transition: 'height 0.2s ease-in-out, padding 0.2s ease-in-out',\n }}>\n {hasBulkActions && (\n <div className=\"flex flex-row\">\n {hasPrimaryBulkAction && (\n <div className=\"mr4\">\n <Button\n variation=\"secondary\"\n size=\"small\"\n onClick={() =>\n bulkActions.main.handleCallback(\n bulkActionsReturnedParameters\n )\n }>\n {bulkActions.main.label}\n </Button>\n </div>\n )}\n {hasSecondaryBulkActions && (\n <ActionMenu\n label={bulkActions.texts.secondaryActionsLabel}\n buttonProps={{ variation: 'secondary', size: 'small' }}\n options={bulkActions.others.map(el => ({\n label: el.label,\n isDangerous: el.isDangerous,\n onClick: () =>\n el.handleCallback(bulkActionsReturnedParameters),\n }))}\n />\n )}\n </div>\n )}\n <div className=\"tr flex flex-row items-center\">\n {!allLinesSelected && bulkActions && bulkActions.texts && (\n <span className=\"mr4 c-muted-4\">\n {bulkActions.texts.rowsSelected(\n <BulkActionsSelectedRows\n selectedRowsLength={selectedRowsLength}\n />\n )}\n </span>\n )}\n {bulkActions &&\n bulkActions.texts &&\n bulkActions.texts.selectAll &&\n bulkActions.texts.allRowsSelected && (\n <span className=\"mr2\">\n {allLinesSelected ? (\n bulkActions.texts.allRowsSelected(\n <span className=\"b\">{bulkActions.totalItems}</span>\n )\n ) : (\n <Button onClick={() => onSelectAllLines()}>\n <span className=\"ttu\">\n {`${bulkActions.texts.selectAll} ${bulkActions.totalItems}`}\n </span>\n </Button>\n )}\n </span>\n )}\n <ButtonWithIcon\n icon={close}\n onClick={() => onDeselectAllLines()}\n />\n </div>\n </div>\n )}\n </Sticky>\n )\n }\n}\n\nBulkActions.defaultProps = {\n hasPrimaryBulkAction: false,\n hasSecondaryBulkActions: false,\n allLinesSelected: false,\n selectedRows: [],\n bulkActions: {},\n onSelectAllLines: () => {},\n}\n\nBulkActions.propTypes = {\n hasPrimaryBulkAction: PropTypes.bool,\n hasSecondaryBulkActions: PropTypes.bool,\n allLinesSelected: PropTypes.bool,\n\n selectedRows: PropTypes.array,\n bulkActions: PropTypes.object,\n\n onSelectAllLines: PropTypes.func,\n onDeselectAllLines: PropTypes.func.isRequired,\n}\n\nexport default BulkActions\n\n```" } ]
code_store-on-localhost_381ed463
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### A table displays any kind of structured data and offers controls to easily navigate, search and filter through it. Data may be from just numbers to complex entities that employ other components to represent itself, like images, tags, links, etc.\n\nOur Table was built to be highly composable and flexible. All parts are optional, and you can compose your table with any other Styleguide components. A Table may be used from a small table with numbers to full CRUD-like functionalities, from a small data display to the main screen of a complex module. All parts are plug'n'play parts that you can turn on and off to match your needs.\n\n### ๐Ÿ‘ Dos\n\n- Try to support as many of the Table features as you can in your system - if we designed there it's because it's highly recommended to have.\n- Provide as many domain-specific actions as you want in the dropdown slot.\n- Line actions: should be mostly for actions that are resolved in the same screen, or if it's was identified to be a very recurrent action.\n\nSimple example\n\n```js\nconst sampleData = require('./sampleData').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(15)\nconst defaultSchema = {\n properties: {\n name: {\n title: 'Name',\n width: 300,\n },\n email: {\n title: 'Email',\n minWidth: 350,\n },\n number: {\n title: 'Number',\n // default is 200px\n minWidth: 100,\n },\n },\n}\n\n;<div>\n <div className=\"mb5\">\n <Table\n fullWidth\n schema={defaultSchema}\n items={itemsCopy}\n density=\"high\"\n onRowClick={({ rowData }) => {\n alert(\n `you just clicked ${rowData.name}, number is ${rowData.number} and email ${rowData.email}`\n )\n }}\n />\n </div>\n</div>\n```\n\n# Table schema\n\nThe Schema property is a JSON used to define the table columns and how they should behave visually. The Schema has properties and each one of them defines a column in the table.\nExample with simple structure:\n\n```md\n{\nproperties: {\ncolumn1: {\ntitle: \"First Column\"\n},\ncolumn2: {\ntitle: \"Second Column\",\nwidth: 350\n}\n}\n}\n```\n\n##### title\n\n- Control the title which appears on table Header.\n- It receives only strings.\n- If you want to customize it with a component, you can use the `headerRenderer` prop.\n\n##### width\n\n- Control the column width.\n- It receives only numbers, which are values in pixels.\n- Default value is 200px\n\n##### minWidth\n\n- Fix a minimum width to the column.\n- It receives only numbers, which are values in pixels.\n- Default value is 200px\n\n##### cellRenderer\n\n- Customize the render method of a single column cell.\n- It receives a function that returns a node (react component).\n- The function has the following params: ({ cellData, rowData, updateCellMeasurements })\n- Default is render the value as a string.\n- If you use `dynamicRowHeights` option in your table, you may need to use `updateCellMeasurements` to update the cell measurement cache (e.g. in an `onLoad` prop for images).\n- If you have a custom cell component that has a click interaction and at the same time you use the onRowClick Table prop, you might stumble uppon the problem of both click actions being fired. We can work around that by doing a wrapper around cellRenderer to stop click event propagation, like so:\n\n##### headerRight\n\n- Use this boolean property to align right the text of a header. Useful for monetary values.\n- Usage: `headerRight: true`.\n- You will have to use the `cellRenderer` proerty to also align right the content of the column.\n\n```jsx noeditor static\n{\n properties: {\n column1: {\n cellRenderer: ({ cellData, rowData }) => {\n return (\n <div\n onClick={e => {\n e.stopPropagation()\n // the click event propagation start on the checkbox click below, and propagates up the DOM tree.\n // this wrapper is going to catch the event right after it fires and stop it's propagation.\n // stoping the click event from propagating until the row component node,\n // so the onRowClick will not be fired.\n // you can learm more about DOM event propagation here: http://tiny.cc/c1625y\n }}>\n <Checkbox\n checked={this.state.check}\n id=\"select-option\"\n name=\"select-option\"\n onChange={() => this.setState({ check: !this.state.check })}\n />\n </div>\n )\n }\n }\n }\n}\n```\n\nExample customizing color column cell, with clickable badges\n\n```js\nconst sampleData = require('./sampleData').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(20)\nconst Tag = require('../Tag').default\nclass CustomTableExample extends React.Component {\n constructor() {\n super()\n this.state = {\n orderedItems: itemsCopy,\n }\n }\n\n render() {\n const customSchema = {\n properties: {\n name: {\n title: 'Name',\n width: 300,\n },\n email: {\n title: 'Email',\n width: 350,\n },\n color: {\n title: 'Color',\n // you can customize cell component render (also header component with headerRenderer)\n cellRenderer: ({ cellData }) => {\n return (\n <Tag\n bgColor={cellData.color}\n color=\"#fff\"\n onClick={e => {\n // if you use cellRender click event AND onRowclick event\n // you should stop the event propagation so the cell click fires and row click don't\n e.stopPropagation()\n alert(\n `you just clicked a cell to remove ${cellData.label}, HEX: ${cellData.color}`\n )\n }}>\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n }\n\n return (\n <div>\n <div className=\"mb5\">\n <Table\n schema={customSchema}\n items={this.state.orderedItems}\n indexColumnLabel=\"Index\"\n onRowClick={({ rowData }) => {\n alert(`you just clicked the row with ${rowData.name}`)\n }}\n />\n </div>\n </div>\n )\n }\n}\n;<CustomTableExample />\n```\n\n##### sortable\n\n- Sinalize that a column is sortable, so the header will be clickable.\n- This prop receives a boolean.\n- On sortable header's click the Table `onSort` callback will be fired.\n\nExample sortable by Name\n\n```js\nconst sampleData = require('./sampleData').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(20)\nconst Tag = require('../Tag').default\nclass CustomTableExample extends React.Component {\n constructor() {\n super()\n this.state = {\n orderedItems: itemsCopy,\n dataSort: {\n sortedBy: null,\n sortOrder: null,\n },\n }\n\n this.sortNameAlphapeticallyASC = this.sortNameAlphapeticallyASC.bind(this)\n this.sortNameAlphapeticallyDESC = this.sortNameAlphapeticallyDESC.bind(this)\n this.handleSort = this.handleSort.bind(this)\n }\n\n sortNameAlphapeticallyASC(a, b) {\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0\n }\n sortNameAlphapeticallyDESC(a, b) {\n return a.name < b.name ? 1 : a.name > b.name ? -1 : 0\n }\n\n handleSort({ sortOrder, sortedBy }) {\n // I'll just handle sort by 'name', but I could handle multiple properties\n if (sortedBy === 'name') {\n const orderedItems =\n sortOrder === 'ASC'\n ? itemsCopy.slice().sort(this.sortNameAlphapeticallyASC)\n : itemsCopy.slice().sort(this.sortNameAlphapeticallyDESC)\n // the above const could come out of an API call to sort items for example\n this.setState({\n orderedItems,\n dataSort: {\n sortedBy,\n sortOrder,\n },\n })\n }\n }\n\n render() {\n const customSchema = {\n properties: {\n name: {\n title: 'Name',\n width: 300,\n // sortable boolean in a schema property makes it sortable,\n // (clicking header triggers onSort callback).\n sortable: true,\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Value',\n headerRight: true,\n cellRenderer: data => (\n <div className=\"w-100 tr\">$ {data.cellData}</div>\n ),\n },\n },\n }\n\n return (\n <div>\n <div className=\"mb5\">\n <Table\n schema={customSchema}\n items={this.state.orderedItems}\n sort={{\n sortedBy: this.state.dataSort.sortedBy,\n sortOrder: this.state.dataSort.sortOrder,\n }}\n onSort={this.handleSort}\n />\n </div>\n </div>\n )\n }\n}\n;<CustomTableExample />\n```\n\n##### headerRenderer\n\n- Customized the render method of a single header cell.\n- It receives a function that returns a node (react component).\n- The function has the following params: ({ columnIndex, key, title })\n- This prop will not work if the `sortable` prop for the same header is active.\n\nexample customizing number column header to use intl FormattedMessage\n\n```js\nconst sampleData = require('./sampleData').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(20)\nconst Tag = require('../Tag').default\nclass FormattedMessage extends React.Component {\n render() {\n const renderTextByIntlId = id => {\n switch (id) {\n case 'some.intl.message.id':\n return 'Number'\n break\n default:\n return 'Deafult Header title'\n break\n }\n }\n return <span>{renderTextByIntlId(this.props.id)}</span>\n }\n}\n\nclass CustomTableExample extends React.Component {\n constructor() {\n super()\n this.state = {\n orderedItems: itemsCopy,\n }\n }\n\n render() {\n const customSchema = {\n properties: {\n name: {\n title: 'Name',\n width: 250,\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'some.intl.message.id',\n headerRenderer: ({ title }) => {\n return <FormattedMessage id={title} />\n },\n },\n },\n }\n\n return (\n <div>\n <div className=\"mb5\">\n <Table schema={customSchema} items={this.state.orderedItems} />\n </div>\n </div>\n )\n }\n}\n;<CustomTableExample />\n```\n\n# Features\n\n<div className=\"center mw7 pv6\">\n ![](./table.png)\n</div>\n\n##### Custom empty state\n\nEmpty states can also be customized, the passed children will be rendered inside an EmptyState component.\nIt's worth to customize empty state using this prop so the other table features will behave accordingly (e.g. the topbar, pagination and totalizers).\n\n```js\nconst sampleData = require('./sampleData').default\nconst Button = require('../Button').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(15)\nconst defaultSchema = {\n properties: {\n name: {\n title: 'Name',\n width: 300,\n },\n email: {\n title: 'Email',\n minWidth: 350,\n },\n number: {\n title: 'Number',\n // default is 200px\n minWidth: 100,\n },\n },\n}\n\n;<div>\n <div>\n <Table\n fullWidth\n schema={defaultSchema}\n items={[]}\n emptyStateLabel=\"This is my custom empty state title\"\n emptyStateChildren={\n <React.Fragment>\n <p>\n A longer explanation of what should be here, and why should I care\n about what should be here.\n </p>\n <div className=\"pt5\">\n <Button variation=\"secondary\" size=\"small\">\n <span className=\"flex align-baseline\">Suggested action</span>\n </Button>\n </div>\n </React.Fragment>\n }\n onRowClick={({ rowData }) => {\n alert(\n `you just clicked ${rowData.name}, number is ${rowData.number} and email ${rowData.email}`\n )\n }}\n />\n </div>\n</div>\n```\n\n##### Pagination\n\nThis feature uses the pagination component in the bottom, after the table content.\n\n```js\nconst ArrowDown = require('../icon/ArrowDown').default\nconst ArrowUp = require('../icon/ArrowUp').default\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 5\nconst initialState = {\n tableLength,\n currentPage: 1,\n slicedData: sampleData.items.slice(0, tableLength),\n currentItemFrom: 1,\n currentItemTo: tableLength,\n itemsLength: sampleData.items.length,\n emptyStateLabel: 'Nothing to show.',\n}\nconst jsonschema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n width: 150,\n },\n color: {\n title: 'Color',\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n\n this.handleNextClick = this.handleNextClick.bind(this)\n this.handlePrevClick = this.handlePrevClick.bind(this)\n this.goToPage = this.goToPage.bind(this)\n this.handleRowsChange = this.handleRowsChange.bind(this)\n }\n\n handleNextClick() {\n const newPage = this.state.currentPage + 1\n const itemFrom = this.state.currentItemTo + 1\n const itemTo = tableLength * newPage\n const data = sampleData.items.slice(itemFrom - 1, itemTo)\n this.goToPage(newPage, itemFrom, itemTo, data)\n }\n\n handlePrevClick() {\n if (this.state.currentPage === 0) return\n const newPage = this.state.currentPage - 1\n const itemFrom = this.state.currentItemFrom - tableLength\n const itemTo = this.state.currentItemFrom - 1\n const data = sampleData.items.slice(itemFrom - 1, itemTo)\n this.goToPage(newPage, itemFrom, itemTo, data)\n }\n\n goToPage(currentPage, currentItemFrom, currentItemTo, slicedData) {\n this.setState({\n currentPage,\n currentItemFrom,\n currentItemTo,\n slicedData,\n })\n }\n\n handleRowsChange(e, value) {\n this.setState(\n {\n tableLength: parseInt(value),\n currentItemTo: parseInt(value),\n },\n () => {\n // this callback garantees new sliced items respect filters and tableLength\n const { filterStatements } = this.state\n this.handleFiltersChange(filterStatements)\n }\n )\n }\n\n render() {\n return (\n <Table\n schema={jsonschema}\n items={this.state.slicedData}\n emptyStateLabel={this.state.emptyStateLabel}\n pagination={{\n onNextClick: this.handleNextClick,\n onPrevClick: this.handlePrevClick,\n currentItemFrom: this.state.currentItemFrom,\n currentItemTo: this.state.currentItemTo,\n onRowsChange: this.handleRowsChange,\n textShowRows: 'Show rows',\n textOf: 'of',\n totalItems: this.state.itemsLength,\n rowsOptions: [5, 10, 15, 25],\n }}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n##### Line actions\n\nThis feature creates a last extra column with an ActionMenu component per line.\n\n```js\nconst sampleData = require('./sampleData').default\nconst itemsCopy = sampleData.items\n .slice()\n .reverse()\n .splice(15)\nconst defaultSchema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n },\n number: {\n title: 'Number',\n },\n },\n}\n\nconst lineActions = [\n {\n label: ({ rowData }) => `Action for ${rowData.name}`,\n onClick: ({ rowData }) => alert(`Executed action for ${rowData.name}`),\n },\n {\n label: ({ rowData }) => `DANGEROUS action for ${rowData.name}`,\n isDangerous: true,\n onClick: ({ rowData }) =>\n alert(`Executed a DANGEROUS action for ${rowData.name}`),\n },\n]\n\n;<div>\n <div className=\"mb5\">\n <Table\n fullWidth\n schema={defaultSchema}\n items={itemsCopy}\n lineActions={lineActions}\n />\n </div>\n</div>\n```\n\n##### Fixed first column\n\nThis case is recomended if you have lots of columns, so the most important information could be fixed\n\n```js\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 5\nconst initialState = {\n tableLength,\n currentPage: 1,\n slicedData: sampleData.items.slice(0, tableLength),\n currentItemFrom: 1,\n currentItemTo: tableLength,\n searchValue: '',\n itemsLength: sampleData.items.length,\n emptyStateLabel: 'Nothing to show.',\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n this.customColorTagProperty = this.customColorTagProperty.bind(this)\n }\n\n customColorTagProperty(index) {\n return {\n title: `Color${index ? ` ${index}` : ''}`,\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n }\n }\n\n render() {\n const customSchema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n },\n color: this.customColorTagProperty(),\n color1: this.customColorTagProperty(1),\n color2: this.customColorTagProperty(2),\n color3: this.customColorTagProperty(3),\n color4: this.customColorTagProperty(4),\n color5: this.customColorTagProperty(5),\n color6: this.customColorTagProperty(6),\n },\n }\n\n return (\n <Table\n schema={customSchema}\n items={this.state.slicedData}\n fixFirstColumn\n emptyStateLabel={this.state.emptyStateLabel}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n##### Toolbar\n\nThe toolbar is a bundle of features, including search input, columns visibility toggler, density controls, import and export buttons, extra actions menu using ActionMenu component and a newLine button to help with entry creation (you can see the illustrative diagram in the begining of the page for a better visualization of this structure)\n\n```js\nconst ArrowDown = require('../icon/ArrowDown').default\nconst ArrowUp = require('../icon/ArrowUp').default\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 5\nconst initialState = {\n slicedData: sampleData.items.slice(0, tableLength),\n searchValue: '',\n emptyStateLabel: 'Nothing to show.',\n}\nconst jsonschema = {\n properties: {\n name: {\n title: 'Name',\n width: 170,\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n width: 150,\n },\n color: {\n title: 'Color',\n width: 170,\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n\n this.handleInputSearchChange = this.handleInputSearchChange.bind(this)\n this.handleInputSearchSubmit = this.handleInputSearchSubmit.bind(this)\n this.handleInputSearchClear = this.handleInputSearchClear.bind(this)\n }\n\n handleInputSearchChange(e) {\n this.setState({ searchValue: e.target.value })\n }\n\n handleInputSearchClear(e) {\n this.setState({ ...initialState })\n }\n\n handleInputSearchSubmit(e) {\n e.preventDefault()\n\n if (!this.state.searchValue) {\n this.setState({ ...initialState })\n } else {\n this.setState({\n slicedData: [],\n emptyStateLabel: 'No results found.',\n })\n }\n }\n\n render() {\n return (\n <Table\n schema={jsonschema}\n items={this.state.slicedData}\n toolbar={{\n inputSearch: {\n value: this.state.searchValue,\n placeholder: 'Search stuff...',\n onChange: this.handleInputSearchChange,\n onClear: this.handleInputSearchClear,\n onSubmit: this.handleInputSearchSubmit,\n },\n density: {\n buttonLabel: 'Line density',\n lowOptionLabel: 'Low',\n mediumOptionLabel: 'Medium',\n highOptionLabel: 'High',\n },\n download: {\n label: 'Export',\n handleCallback: () => alert('Callback()'),\n },\n upload: {\n label: 'Import',\n handleCallback: () => alert('Callback()'),\n },\n fields: {\n label: 'Toggle visible fields',\n showAllLabel: 'Show All',\n hideAllLabel: 'Hide All',\n },\n extraActions: {\n label: 'More options',\n actions: [\n {\n label: 'An action',\n handleCallback: () => alert('An action'),\n },\n {\n label: 'Another action',\n handleCallback: () => alert('Another action'),\n },\n {\n label: 'A third action',\n handleCallback: () => alert('A third action'),\n },\n ],\n },\n newLine: {\n label: 'New',\n handleCallback: () => alert('handle new line callback'),\n },\n }}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n##### Totalizers\n\nThis uses the Totalizer component between the toolbar and the table content\n\n```js\nconst ArrowDown = require('../icon/ArrowDown').default\nconst ArrowUp = require('../icon/ArrowUp').default\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 5\nconst initialState = {\n slicedData: sampleData.items.slice(0, tableLength),\n emptyStateLabel: 'Nothing to show.',\n}\nconst jsonschema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n width: 150,\n },\n color: {\n title: 'Color',\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n }\n\n render() {\n return (\n <Table\n schema={jsonschema}\n items={this.state.slicedData}\n emptyStateLabel={this.state.emptyStateLabel}\n totalizers={[\n {\n label: 'Saldo em conta',\n value: 23837,\n },\n {\n label: 'Entradas',\n value: 'R$ 36239,05',\n iconBackgroundColor: '#eafce3',\n icon: <ArrowUp color=\"#79B03A\" size={14} />,\n },\n\n {\n label: 'Saรญdas',\n value: '- R$ 13.485,26',\n icon: <ArrowDown size={14} />,\n },\n {\n label: 'Vendas',\n value: 23837,\n isLoading: true,\n },\n ]}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n##### Filters\n\nThis feature uses FilterBar component inserting it between the toolbar and table content (just like the Totalizers, it's a separate component).\n\n```js\nconst ArrowDown = require('../icon/ArrowDown').default\nconst ArrowUp = require('../icon/ArrowUp').default\nconst Checkbox = require('../Checkbox').default\nconst Input = require('../Input').default\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 7\nconst initialState = {\n tableLength,\n slicedData: sampleData.items.slice(0, tableLength),\n emptyStateLabel: 'Nothing to show.',\n filterStatements: [],\n}\nconst jsonschema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n width: 150,\n },\n color: {\n title: 'Color',\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.simpleInputVerbsAndLabel = this.simpleInputVerbsAndLabel.bind(this)\n this.numberInputObject = this.numberInputObject.bind(this)\n this.numberInputRangeObject = this.numberInputRangeObject.bind(this)\n this.colorSelectorObject = this.colorSelectorObject.bind(this)\n this.handleFiltersChange = this.handleFiltersChange.bind(this)\n }\n\n simpleInputObject({ value, onChange }) {\n return (\n <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n )\n }\n\n simpleInputVerbsAndLabel() {\n return {\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '=' ? 'is' : st.verb === '!=' ? 'is not' : 'contains'\n } ${st.object}`\n },\n verbs: [\n {\n label: 'is',\n value: '=',\n object: this.simpleInputObject,\n },\n {\n label: 'is not',\n value: '!=',\n object: this.simpleInputObject,\n },\n {\n label: 'contains',\n value: 'contains',\n object: this.simpleInputObject,\n },\n ],\n }\n }\n\n numberInputObject({ value, onChange }) {\n return (\n <Input\n placeholder=\"Insert numberโ€ฆ\"\n type=\"number\"\n min=\"0\"\n max=\"180\"\n value={value || ''}\n onChange={e => {\n onChange(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n numberInputRangeObject({ value, onChange }) {\n return (\n <div className=\"flex\">\n <Input\n placeholder=\"fromโ€ฆ\"\n errorMessage={\n value &&\n value.first &&\n value.last &&\n parseInt(value.first) >= parseInt(value.last)\n ? 'Must be smaller than other input'\n : ''\n }\n value={value && value.first ? value.first : ''}\n onChange={e => {\n const currentObject = value || {}\n currentObject.first = e.target.value.replace(/\\D/g, '')\n\n onChange(currentObject)\n }}\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n placeholder=\"toโ€ฆ\"\n value={value && value.last ? value.last : ''}\n onChange={e => {\n const currentObject = value || {}\n currentObject.last = e.target.value.replace(/\\D/g, '')\n\n onChange(currentObject)\n }}\n />\n </div>\n )\n }\n\n colorSelectorObject({ value, onChange }) {\n const initialValue = {\n pink: true,\n black: true,\n blue: true,\n gray: true,\n ...(value || {}),\n }\n const toggleValueByKey = key => {\n const newValue = {\n ...(value || initialValue),\n [key]: value ? !value[key] : false,\n }\n return newValue\n }\n return (\n <div>\n {Object.keys(initialValue).map((opt, index) => {\n return (\n <div className=\"mb3\" key={`class-statment-object-${opt}-${index}`}>\n <Checkbox\n checked={value ? value[opt] : initialValue[opt]}\n label={opt}\n name=\"default-checkbox-group\"\n onChange={() => {\n const newValue = toggleValueByKey(`${opt}`)\n const newValueKeys = Object.keys(newValue)\n const isEmptyFilter = !newValueKeys.some(\n key => !newValue[key]\n )\n onChange(isEmptyFilter ? null : newValue)\n }}\n value={opt}\n />\n </div>\n )\n })}\n </div>\n )\n }\n\n handleFiltersChange(statements = []) {\n // here you should receive filter values, so you can fire mutations ou fetch filtered data from APIs\n // For the sake of example I'll filter the data manually since there is no API\n const { tableLength } = this.state\n let newData = sampleData.items.slice()\n statements.forEach(st => {\n if (!st || !st.object) return\n const { subject, verb, object } = st\n switch (subject) {\n case 'color':\n if (!object) return\n const colorsMap = {\n '#F71963': 'pink',\n '#00BBD4': 'blue',\n '#D6D8E0': 'gray',\n '#142032': 'black',\n }\n newData = newData.filter(item => object[colorsMap[item.color.color]])\n break\n case 'name':\n case 'email':\n if (verb === 'contains') {\n newData = newData.filter(item => item[subject].includes(object))\n } else if (verb === '=') {\n newData = newData.filter(item => item[subject] === object)\n } else if (verb === '!=') {\n newData = newData.filter(item => item[subject] !== object)\n }\n break\n case 'number':\n if (verb === '=') {\n newData = newData.filter(item => item.number === parseInt(object))\n } else if (verb === 'between') {\n newData = newData.filter(\n item =>\n item.number >= parseInt(object.first) &&\n item.number <= parseInt(object.last)\n )\n }\n break\n }\n })\n const newDataLength = newData.length\n const newSlicedData = newData.slice(0, tableLength)\n this.setState({\n filterStatements: statements,\n slicedData: newSlicedData,\n itemsLength: newDataLength,\n currentItemTo: tableLength > newDataLength ? newDataLength : tableLength,\n })\n }\n\n render() {\n return (\n <Table\n schema={jsonschema}\n items={this.state.slicedData}\n emptyStateLabel={this.state.emptyStateLabel}\n filters={{\n alwaysVisibleFilters: ['color', 'name'],\n statements: this.state.filterStatements,\n onChangeStatements: this.handleFiltersChange,\n clearAllFiltersButtonLabel: 'Clear Filters',\n collapseLeft: true,\n options: {\n color: {\n label: 'Color',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'All'\n }\n const keys = st.object ? Object.keys(st.object) : {}\n const isAllTrue = !keys.some(key => !st.object[key])\n const isAllFalse = !keys.some(key => st.object[key])\n const trueKeys = keys.filter(key => st.object[key])\n let trueKeysLabel = ''\n trueKeys.forEach((key, index) => {\n trueKeysLabel += `${key}${\n index === trueKeys.length - 1 ? '' : ', '\n }`\n })\n return `${\n isAllTrue ? 'All' : isAllFalse ? 'None' : `${trueKeysLabel}`\n }`\n },\n verbs: [\n {\n label: 'includes',\n value: 'includes',\n object: this.colorSelectorObject,\n },\n ],\n },\n name: {\n label: 'Name',\n ...this.simpleInputVerbsAndLabel(),\n },\n email: {\n label: 'Email',\n ...this.simpleInputVerbsAndLabel(),\n },\n number: {\n label: 'Number',\n renderFilterLabel: st =>\n `${\n st.verb === 'between'\n ? `between ${st.object.first} and ${st.object.last}`\n : `is ${st.object}`\n }`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: this.numberInputObject,\n },\n {\n label: 'is between',\n value: 'between',\n object: this.numberInputRangeObject,\n },\n ],\n },\n },\n }}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n##### Bulk actions\n\nBulk actions allow the user to select some or all the rows to apply an action. Texts have to be given to the component via a `texts` object.\nActions are passed via the `main` object and the `others` array props. Each object is composed of a `label` and the action event via `onClick` key.\n\nThe returned value for all lines selected is an object `allLinesSelected: true` otherwise the data of the rows are returned in the key `selectedRows` as an array.\n\n##### NOTE 1:\n\n`onRowClick` actions are not happening when clicking the checkbox.\n\n##### NOTE 2:\n\nThere are two \"select all\" items.\n\n- The **upper checkbox** on the left side selects the currently visible items, in the example below, 5.\n- The **Select all** button on the right side, selects all items from the database (by concept, since you will probably only load the visible items). Since not all items might be loaded in the table, the callback will only return a flag telling your app to handle all items for the next database operation.\n\nCheck the console when selecting/unselecting rows or clicking an action button in the example below to see the action parameters\n\n```js\nconst itemsCopy = [\n {\n email: 'olen.stamm21@yahoo.com',\n name: 'Patrick Rothfuss',\n number: 1.52725,\n },\n {\n email: 'junius0@gmail.com',\n name: 'Hurricane Skywalker IV',\n number: 2.84639,\n },\n {\n email: 'judd_gulgowski22@yahoo.com',\n name: 'Tom Braddy',\n number: 4.10182,\n },\n {\n email: 'catharine.leuschke62@hotmail.com',\n name: 'Momochi Zabuza',\n number: 6.33245,\n },\n {\n email: 'candido_ryan@hotmail.com',\n name: 'Freddie Mercury',\n number: 7.96637,\n },\n]\nconst defaultSchema = {\n properties: {\n name: {\n type: 'string',\n title: 'Name',\n },\n email: {\n type: 'string',\n title: 'Email',\n },\n number: {\n type: 'number',\n title: 'Number',\n },\n },\n}\n\n;<div className=\"mb5\">\n <Table\n fullWidth\n schema={defaultSchema}\n items={itemsCopy}\n density=\"high\"\n bulkActions={{\n texts: {\n secondaryActionsLabel: 'Actions',\n rowsSelected: qty => (\n <React.Fragment>Selected rows: {qty}</React.Fragment>\n ),\n selectAll: 'Select all',\n allRowsSelected: qty => (\n <React.Fragment>All rows selected: {qty}</React.Fragment>\n ),\n },\n totalItems: 122,\n onChange: params => console.log(params),\n main: {\n label: 'Main Action',\n handleCallback: params => console.log(params),\n },\n others: [\n {\n label: 'Action 1',\n handleCallback: params => console.log(params),\n },\n {\n label: 'Action 2',\n handleCallback: params => console.log(params),\n },\n {\n label: 'Dangerous action',\n isDangerous: true,\n handleCallback: params => console.log(params),\n },\n ],\n }}\n />\n</div>\n```\n\n##### Full blown example\n\nWith Toolbar, Totalizers, Pagination and Filters\n\n```js\nconst ArrowDown = require('../icon/ArrowDown').default\nconst ArrowUp = require('../icon/ArrowUp').default\nconst Checkbox = require('../Checkbox').default\nconst Input = require('../Input').default\nconst sampleData = require('./sampleData').default\nconst Tag = require('../Tag').default\nconst tableLength = 5\nconst initialState = {\n tableLength,\n currentPage: 1,\n slicedData: sampleData.items.slice(0, tableLength),\n currentItemFrom: 1,\n currentItemTo: tableLength,\n searchValue: '',\n itemsLength: sampleData.items.length,\n emptyStateLabel: 'Nothing to show.',\n filterStatements: [],\n}\nconst jsonschema = {\n properties: {\n name: {\n title: 'Name',\n },\n email: {\n title: 'Email',\n width: 300,\n },\n number: {\n title: 'Number',\n width: 150,\n },\n color: {\n title: 'Color',\n cellRenderer: ({ cellData }) => {\n return (\n <Tag bgColor={cellData.color} color=\"#fff\">\n <span className=\"nowrap\">{cellData.label}</span>\n </Tag>\n )\n },\n },\n },\n}\n\nclass ResourceListExample extends React.Component {\n constructor() {\n super()\n this.state = initialState\n\n this.handleNextClick = this.handleNextClick.bind(this)\n this.handlePrevClick = this.handlePrevClick.bind(this)\n this.goToPage = this.goToPage.bind(this)\n this.handleInputSearchChange = this.handleInputSearchChange.bind(this)\n this.handleInputSearchSubmit = this.handleInputSearchSubmit.bind(this)\n this.handleInputSearchClear = this.handleInputSearchClear.bind(this)\n this.handleRowsChange = this.handleRowsChange.bind(this)\n this.simpleInputObject = this.simpleInputObject.bind(this)\n this.simpleInputVerbsAndLabel = this.simpleInputVerbsAndLabel.bind(this)\n this.numberInputObject = this.numberInputObject.bind(this)\n this.numberInputRangeObject = this.numberInputRangeObject.bind(this)\n this.colorSelectorObject = this.colorSelectorObject.bind(this)\n this.handleFiltersChange = this.handleFiltersChange.bind(this)\n }\n\n handleNextClick() {\n const newPage = this.state.currentPage + 1\n const itemFrom = this.state.currentItemTo + 1\n const itemTo = tableLength * newPage\n const data = sampleData.items.slice(itemFrom - 1, itemTo)\n this.goToPage(newPage, itemFrom, itemTo, data)\n }\n\n handlePrevClick() {\n if (this.state.currentPage === 0) return\n const newPage = this.state.currentPage - 1\n const itemFrom = this.state.currentItemFrom - tableLength\n const itemTo = this.state.currentItemFrom - 1\n const data = sampleData.items.slice(itemFrom - 1, itemTo)\n this.goToPage(newPage, itemFrom, itemTo, data)\n }\n\n goToPage(currentPage, currentItemFrom, currentItemTo, slicedData) {\n this.setState({\n currentPage,\n currentItemFrom,\n currentItemTo,\n slicedData,\n })\n }\n\n handleRowsChange(e, value) {\n this.setState(\n {\n tableLength: parseInt(value),\n currentItemTo: parseInt(value),\n },\n () => {\n // this callback garantees new sliced items respect filters and tableLength\n const { filterStatements } = this.state\n this.handleFiltersChange(filterStatements)\n }\n )\n }\n\n handleInputSearchChange(e) {\n this.setState({ searchValue: e.target.value })\n }\n\n handleInputSearchClear(e) {\n this.setState({ ...initialState })\n }\n\n handleInputSearchSubmit(e) {\n const value = e && e.target && e.target.value\n const regex = new RegExp(value, 'i')\n if (!value) {\n this.setState({ ...initialState })\n } else {\n this.setState({\n slicedData: initialState.slicedData\n .slice()\n .filter(item => regex.test(item.name) || regex.test(item.email)),\n })\n }\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n value={values || ''}\n onChange={e => onChangeObjectCallback(e.target.value)}\n />\n )\n }\n\n simpleInputVerbsAndLabel() {\n return {\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'Any'\n }\n return `${\n st.verb === '=' ? 'is' : st.verb === '!=' ? 'is not' : 'contains'\n } ${st.object}`\n },\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is not',\n value: '!=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n {\n label: 'contains',\n value: 'contains',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n }\n }\n\n numberInputObject({\n statements,\n values,\n statementIndex,\n error,\n onChangeObjectCallback,\n }) {\n return (\n <Input\n placeholder=\"Insert numberโ€ฆ\"\n type=\"number\"\n min=\"0\"\n max=\"180\"\n value={values || ''}\n onChange={e => {\n onChangeObjectCallback(e.target.value.replace(/\\D/g, ''))\n }}\n />\n )\n }\n\n numberInputRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n return (\n <div className=\"flex\">\n <Input\n placeholder=\"Number fromโ€ฆ\"\n errorMessage={\n statements[statementIndex].object &&\n parseInt(statements[statementIndex].object.first) >=\n parseInt(statements[statementIndex].object.last)\n ? 'Must be smaller than other input'\n : ''\n }\n value={values && values.first ? values.first : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.first = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n placeholder=\"Number toโ€ฆ\"\n value={values && values.last ? values.last : ''}\n onChange={e => {\n const currentObject = values || {}\n currentObject.last = e.target.value.replace(/\\D/g, '')\n\n onChangeObjectCallback(currentObject)\n }}\n />\n </div>\n )\n }\n\n colorSelectorObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n onChangeObjectCallback,\n }) {\n const initialValue = {\n pink: true,\n black: true,\n blue: true,\n gray: true,\n ...(values || {}),\n }\n const toggleValueByKey = key => {\n const newValues = {\n ...(values || initialValue),\n [key]: values ? !values[key] : false,\n }\n return newValues\n }\n return (\n <div>\n {Object.keys(initialValue).map((opt, index) => {\n return (\n <div className=\"mb3\" key={`class-statment-object-${opt}-${index}`}>\n <Checkbox\n checked={values ? values[opt] : initialValue[opt]}\n label={opt}\n name=\"default-checkbox-group\"\n onChange={() => {\n const newValue = toggleValueByKey(`${opt}`)\n const newValueKeys = Object.keys(newValue)\n const isEmptyFilter = !newValueKeys.some(\n key => !newValue[key]\n )\n onChangeObjectCallback(isEmptyFilter ? null : newValue)\n }}\n value={opt}\n />\n </div>\n )\n })}\n </div>\n )\n }\n\n handleFiltersChange(statements = []) {\n // here you should receive filter values, so you can fire mutations ou fetch filtered data from APIs\n // For the sake of example I'll filter the data manually since there is no API\n const { tableLength } = this.state\n let newData = sampleData.items.slice()\n statements.forEach(st => {\n if (!st || !st.object) return\n const { subject, verb, object } = st\n switch (subject) {\n case 'color':\n if (!object) return\n const colorsMap = {\n '#F71963': 'pink',\n '#00BBD4': 'blue',\n '#D6D8E0': 'gray',\n '#142032': 'black',\n }\n newData = newData.filter(item => object[colorsMap[item.color.color]])\n break\n case 'name':\n case 'email':\n if (verb === 'contains') {\n newData = newData.filter(item => item[subject].includes(object))\n } else if (verb === '=') {\n newData = newData.filter(item => item[subject] === object)\n } else if (verb === '!=') {\n newData = newData.filter(item => item[subject] !== object)\n }\n break\n case 'number':\n if (verb === '=') {\n newData = newData.filter(item => item.number === parseInt(object))\n } else if (verb === 'between') {\n newData = newData.filter(\n item =>\n item.number >= parseInt(object.first) &&\n item.number <= parseInt(object.last)\n )\n }\n break\n }\n })\n const newDataLength = newData.length\n const newSlicedData = newData.slice(0, tableLength)\n this.setState({\n filterStatements: statements,\n slicedData: newSlicedData,\n itemsLength: newDataLength,\n currentItemTo: tableLength > newDataLength ? newDataLength : tableLength,\n })\n }\n\n render() {\n return (\n <Table\n schema={jsonschema}\n items={this.state.slicedData}\n emptyStateLabel={this.state.emptyStateLabel}\n toolbar={{\n inputSearch: {\n value: this.state.searchValue,\n placeholder: 'Search stuff...',\n onChange: this.handleInputSearchChange,\n onClear: this.handleInputSearchClear,\n onSubmit: this.handleInputSearchSubmit,\n },\n density: {\n buttonLabel: 'Line density',\n lowOptionLabel: 'Low',\n mediumOptionLabel: 'Medium',\n highOptionLabel: 'High',\n },\n download: {\n label: 'Export',\n handleCallback: () => alert('Callback()'),\n },\n upload: {\n label: 'Import',\n handleCallback: () => alert('Callback()'),\n },\n fields: {\n label: 'Toggle visible fields',\n showAllLabel: 'Show All',\n hideAllLabel: 'Hide All',\n },\n extraActions: {\n label: 'More options',\n actions: [\n {\n label: 'An action',\n handleCallback: () => alert('An action'),\n },\n {\n label: 'Another action',\n handleCallback: () => alert('Another action'),\n },\n {\n label: 'A third action',\n handleCallback: () => alert('A third action'),\n },\n ],\n },\n newLine: {\n label: 'New',\n handleCallback: () => alert('handle new line callback'),\n actions: [\n 'General',\n 'Desktop & Screen Saver',\n 'Dock',\n 'Language & Region',\n ].map(label => ({\n label,\n onClick: () => {},\n })),\n },\n }}\n pagination={{\n onNextClick: this.handleNextClick,\n onPrevClick: this.handlePrevClick,\n currentItemFrom: this.state.currentItemFrom,\n currentItemTo: this.state.currentItemTo,\n onRowsChange: this.handleRowsChange,\n textShowRows: 'Show rows',\n textOf: 'of',\n totalItems: this.state.itemsLength,\n rowsOptions: [5, 10, 15, 25],\n }}\n totalizers={[\n {\n label: 'Saldo em conta',\n value: 23837,\n },\n {\n label: 'Entradas',\n value: 'R$ 36239,05',\n iconBackgroundColor: '#eafce3',\n icon: <ArrowUp color=\"#79B03A\" size={14} />,\n },\n\n {\n label: 'Saรญdas',\n value: '- R$ 13.485,26',\n icon: <ArrowDown size={14} />,\n },\n {\n label: 'Vendas',\n value: 23837,\n isLoading: true,\n },\n ]}\n bulkActions={{\n texts: {\n secondaryActionsLabel: 'Actions',\n rowsSelected: qty => (\n <React.Fragment>Selected rows: {qty}</React.Fragment>\n ),\n selectAll: 'Select all',\n allRowsSelected: qty => (\n <React.Fragment>All rows selected: {qty}</React.Fragment>\n ),\n },\n totalItems: 122,\n onChange: params => console.log(params),\n main: {\n label: 'Main Action',\n handleCallback: params => console.log(params),\n },\n others: [\n {\n label: 'Action 1',\n handleCallback: params => console.log(params),\n },\n {\n label: 'Action 2',\n handleCallback: params => console.log(params),\n },\n {\n label: 'Dangerous action',\n isDangerous: true,\n handleCallback: params => console.log(params),\n },\n ],\n }}\n filters={{\n alwaysVisibleFilters: ['color', 'name'],\n statements: this.state.filterStatements,\n onChangeStatements: this.handleFiltersChange,\n clearAllFiltersButtonLabel: 'Clear Filters',\n collapseLeft: true,\n options: {\n color: {\n label: 'Color',\n renderFilterLabel: st => {\n if (!st || !st.object) {\n // you should treat empty object cases only for alwaysVisibleFilters\n return 'All'\n }\n const keys = st.object ? Object.keys(st.object) : {}\n const isAllTrue = !keys.some(key => !st.object[key])\n const isAllFalse = !keys.some(key => st.object[key])\n const trueKeys = keys.filter(key => st.object[key])\n let trueKeysLabel = ''\n trueKeys.forEach((key, index) => {\n trueKeysLabel += `${key}${\n index === trueKeys.length - 1 ? '' : ', '\n }`\n })\n return `${\n isAllTrue ? 'All' : isAllFalse ? 'None' : `${trueKeysLabel}`\n }`\n },\n verbs: [\n {\n label: 'includes',\n value: 'includes',\n object: {\n renderFn: this.colorSelectorObject,\n extraParams: {},\n },\n },\n ],\n },\n name: {\n label: 'Name',\n ...this.simpleInputVerbsAndLabel(),\n },\n email: {\n label: 'Email',\n ...this.simpleInputVerbsAndLabel(),\n },\n number: {\n label: 'Number',\n renderFilterLabel: st =>\n `${\n st.verb === 'between'\n ? `between ${st.object.first} and ${st.object.last}`\n : `is ${st.object}`\n }`,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.numberInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.numberInputRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n },\n }}\n />\n )\n }\n}\n;<ResourceListExample />\n```\n\n```" } ]
code_store-on-localhost_86cec68d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/SimpleTable.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport {\n MultiGrid,\n AutoSizer,\n CellMeasurer,\n CellMeasurerCache,\n} from 'react-virtualized'\n\nimport ArrowDown from '../icon/ArrowDown'\nimport ArrowUp from '../icon/ArrowUp'\nimport OptionsDots from '../icon/OptionsDots'\nimport EmptyState from '../EmptyState'\nimport Spinner from '../Spinner'\nimport ActionMenu from '../ActionMenu'\n\nconst ARROW_SIZE = 11\nconst HEADER_HEIGHT = 36\nconst DEFAULT_COLUMN_WIDTH = 200\nconst LINE_ACTIONS_COLUMN_WIDTH = 70\nconst NO_TITLE_COLUMN = ' '\nconst SELECTED_ROW_BACKGROUND = '#dbe9fd'\nconst EMPTY_STATE_SIZE_IN_ROWS = 5\n\nclass SimpleTable extends Component {\n constructor(props) {\n super(props)\n\n this.state = {\n hoverRowIndex: -1,\n tableHeight: 0,\n scrollbarWidth: 0,\n }\n\n this._cache = new CellMeasurerCache({\n defaultHeight: props.rowHeight,\n minHeight: props.rowHeight,\n fixedWidth: true,\n })\n }\n\n componentDidMount() {\n this.setState({\n tableHeight:\n this.props.containerHeight || this.calculateContainerHeight(),\n })\n }\n\n componentDidUpdate() {\n if (!this.props.containerHeight) {\n this.updateTableHeight()\n }\n }\n\n updateTableHeight() {\n const calculatedContainerHeight = this.calculateContainerHeight()\n if (this.state.tableHeight !== calculatedContainerHeight) {\n this.setState({\n tableHeight: calculatedContainerHeight,\n })\n }\n }\n\n toggleSortType = key => {\n const {\n sort: { preferentialSortOrder = 'ASC', sortOrder, sortedBy },\n } = this.props\n\n if (sortedBy !== key) {\n return {\n sortOrder: preferentialSortOrder,\n sortedBy: key,\n }\n }\n\n return {\n sortOrder: sortOrder === 'ASC' ? 'DESC' : 'ASC',\n sortedBy: key,\n }\n }\n\n handleRowHover = rowIndex => {\n const { onRowClick, onRowHover } = this.props\n const { isLineActionsHovered } = this.state\n if (onRowClick && !isLineActionsHovered) {\n this.setState({\n hoverRowIndex: rowIndex,\n })\n } else {\n this.setState({\n hoverRowIndex: -1,\n })\n }\n\n onRowHover(rowIndex)\n }\n\n calculateColWidth = (\n schema,\n properties,\n index,\n fullWidth,\n fullWidthColWidth\n ) => {\n const col = schema.properties[properties[index]]\n return col.width\n ? col.width\n : fullWidth\n ? Math.max(col.minWidth || 100, fullWidthColWidth)\n : DEFAULT_COLUMN_WIDTH\n }\n\n calculateRowHeight = index => {\n const { disableHeader, dynamicRowHeight, rowHeight } = this.props\n const isHeader = !disableHeader && index === 0\n if (isHeader) {\n return HEADER_HEIGHT\n }\n\n if (dynamicRowHeight) {\n return this._cache.rowHeight({ index })\n }\n\n return rowHeight\n }\n\n addLineActionsToSchema = (schema, lineActions) => {\n return {\n ...schema.properties,\n // eslint-disable-next-line camelcase\n _VTEX_Table_Internal_lineActions: {\n title: NO_TITLE_COLUMN,\n width: LINE_ACTIONS_COLUMN_WIDTH,\n cellRenderer: ({ rowData }) => {\n return (\n <ActionMenu\n buttonProps={{\n variation: 'tertiary',\n icon: <OptionsDots />,\n onMouseEnter: () =>\n this.setState({ isLineActionsHovered: true }),\n onMouseLeave: () =>\n this.setState({ isLineActionsHovered: false }),\n }}\n options={lineActions.map(action => ({\n ...action,\n label: action.label({ rowData }),\n onClick: () => action.onClick({ rowData }),\n }))}\n />\n )\n },\n },\n }\n }\n\n handleScrollbarPresenceChange = ({ horizontal, size }) => {\n if (horizontal) {\n this.setState({ scrollbarWidth: size || 0 })\n }\n }\n\n calculateContainerHeight = () => {\n const { rowHeight, items, disableHeader } = this.props\n const { scrollbarWidth } = this.state\n\n if (items.length === 0) {\n return (\n HEADER_HEIGHT + rowHeight * EMPTY_STATE_SIZE_IN_ROWS + scrollbarWidth\n )\n }\n\n const rowCount = disableHeader ? items.length : items.length + 1\n\n let rawTableHeight = 0\n for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {\n rawTableHeight += this.calculateRowHeight(rowIndex)\n }\n\n return rawTableHeight + scrollbarWidth\n }\n\n render() {\n const {\n schema,\n items,\n fixFirstColumn,\n disableHeader,\n density,\n emptyStateLabel,\n emptyStateChildren,\n onRowClick,\n sort: { sortOrder, sortedBy },\n onSort,\n updateTableKey,\n fullWidth,\n lineActions,\n loading,\n selectedRowsIndexes,\n } = this.props\n const { hoverRowIndex, tableHeight } = this.state\n\n if (lineActions)\n schema.properties = this.addLineActionsToSchema(schema, lineActions)\n const properties = Object.keys(schema.properties)\n\n const tableKey = `vtex-table--${updateTableKey}--${density}`\n\n return (\n <div className=\"vh-100 w-100 dt\" style={{ height: tableHeight }}>\n {loading ? (\n <div\n className=\"dtc v-mid tc\"\n style={{ height: tableHeight - HEADER_HEIGHT }}>\n <Spinner />\n </div>\n ) : (\n <div>\n <AutoSizer key={tableKey}>\n {({ width }) => {\n const colsWidth = Object.keys(schema.properties).reduce(\n (acc, curr) => {\n const col = schema.properties[curr]\n return acc + (col.width ? col.width : 0)\n },\n 0\n )\n\n const colsWithoutWidth = Object.keys(schema.properties).filter(\n curr => {\n const col = schema.properties[curr]\n return !col.width\n }\n )\n\n const fullWidthColWidth =\n (width - colsWidth) / colsWithoutWidth.length\n\n return (\n <MultiGrid\n onScrollbarPresenceChange={\n this.handleScrollbarPresenceChange\n }\n height={tableHeight}\n width={width}\n deferredMeasurementCache={this._cache}\n tabIndex={null}\n fixedRowCount={disableHeader ? 0 : 1}\n rowCount={disableHeader ? items.length : items.length + 1}\n rowHeight={({ index }) => this.calculateRowHeight(index)}\n enableFixedRowScroll={!disableHeader}\n hideTopRightGridScrollbar={!disableHeader}\n overscanRowCount={0}\n styleTopRightGrid={\n fixFirstColumn ? { overflow: 'hidden' } : {}\n }\n styleTopLeftGrid={\n fixFirstColumn ? { overflow: 'hidden' } : {}\n }\n fixedColumnCount={fixFirstColumn ? 1 : 0}\n columnCount={properties.length}\n columnWidth={({ index }) =>\n this.calculateColWidth(\n schema,\n properties,\n index,\n fullWidth,\n fullWidthColWidth\n )\n }\n enableFixedColumnScroll\n overscanColumnCount={0}\n cellRenderer={({\n columnIndex,\n key,\n rowIndex,\n style,\n parent,\n }) => {\n const property = properties[columnIndex]\n if (!disableHeader && rowIndex === 0) {\n // Header row\n const title =\n schema.properties[property].title || property\n const headerRight =\n schema.properties[property].headerRight || false\n const headerRenderer =\n schema.properties[property].headerRenderer\n const arrowIsDown =\n sortOrder === 'ASC' && sortedBy === property\n const arrowIsUp =\n sortOrder === 'DESC' && sortedBy === property\n return (\n <CellMeasurer\n cache={this._cache}\n columnIndex={columnIndex}\n key={key}\n parent={parent}\n rowIndex={rowIndex}>\n <div\n key={key}\n style={{\n ...style,\n height: HEADER_HEIGHT,\n }}\n className={`flex items-center w-100 h-100 c-muted-2 f6 truncate ph4 ${\n columnIndex === 0 && fixFirstColumn ? 'br' : ''\n } bt bb b--muted-4 overflow-x-hidden ${\n headerRight ? 'tr' : 'tl'\n }`}>\n {schema.properties[property].sortable ? (\n <div\n className=\"w-100 pointer c-muted-1 b t-small\"\n onClick={() => {\n onSort(this.toggleSortType(property))\n }}>\n {!headerRight && title}\n <div\n className={`inline-flex ${\n headerRight ? 'pr2' : 'pl3'\n }`}>\n {arrowIsDown ? (\n <ArrowDown size={ARROW_SIZE} />\n ) : arrowIsUp ? (\n <ArrowUp size={ARROW_SIZE} />\n ) : null}\n </div>\n {headerRight && title}\n </div>\n ) : columnIndex === 0 && fixFirstColumn ? (\n <div className=\"w-100\">{title}</div>\n ) : headerRenderer ? (\n headerRenderer({\n columnIndex,\n key,\n rowIndex,\n style,\n title,\n })\n ) : (\n <span className=\"w-100\">{title}</span>\n )}\n </div>\n </CellMeasurer>\n )\n }\n const cellRenderer =\n schema.properties[property].cellRenderer\n const rowData =\n items[disableHeader ? rowIndex : rowIndex - 1]\n const cellData = rowData[property]\n\n const cellClassNames = `flex items-center w-100 h-100 ph4 bb\n b--muted-4 truncate ${\n disableHeader && rowIndex === 0\n ? 'bt'\n : ''\n } ${\n onRowClick && rowIndex === hoverRowIndex\n ? 'pointer bg-near-white c-link'\n : ''\n } ${columnIndex === 0 && fixFirstColumn ? 'br' : ''}`\n\n return (\n <CellMeasurer\n cache={this._cache}\n columnIndex={columnIndex}\n key={key}\n parent={parent}\n rowIndex={rowIndex}>\n {({ measure: updateCellMeasurements }) => (\n <div\n key={key}\n style={{\n ...style,\n height: this.calculateRowHeight(rowIndex),\n width: this.calculateColWidth(\n schema,\n properties,\n columnIndex,\n fullWidth,\n fullWidthColWidth\n ),\n backgroundColor: selectedRowsIndexes.includes(\n rowIndex - 1\n )\n ? SELECTED_ROW_BACKGROUND\n : '',\n }}\n className={cellClassNames}\n onClick={\n onRowClick &&\n property !== '_VTEX_Table_Internal_lineActions'\n ? event =>\n onRowClick({\n event,\n index: rowIndex,\n rowData,\n })\n : null\n }\n onMouseEnter={\n onRowClick\n ? () => this.handleRowHover(rowIndex)\n : null\n }\n onMouseLeave={\n onRowClick\n ? () => this.handleRowHover(-1)\n : null\n }>\n {cellRenderer\n ? cellRenderer({\n cellData,\n rowData,\n updateCellMeasurements,\n })\n : cellData}\n </div>\n )}\n </CellMeasurer>\n )\n }}\n />\n )\n }}\n </AutoSizer>\n {items.length === 0 && (\n <div style={{ marginTop: HEADER_HEIGHT }}>\n <EmptyState title={emptyStateLabel}>\n {emptyStateChildren}\n </EmptyState>\n </div>\n )}\n </div>\n )}\n </div>\n )\n }\n}\n\nSimpleTable.defaultProps = {\n indexColumnLabel: null,\n fixFirstColumn: false,\n items: [],\n disableHeader: false,\n sort: {\n sortOrder: null,\n sortedBy: null,\n },\n fullWidth: false,\n dynamicRowHeight: false,\n selectedRowsIndexes: [],\n onRowHover: () => {},\n}\n\nSimpleTable.propTypes = {\n items: PropTypes.array.isRequired,\n schema: PropTypes.object.isRequired,\n indexColumnLabel: PropTypes.string,\n fixFirstColumn: PropTypes.bool,\n density: PropTypes.string,\n disableHeader: PropTypes.bool,\n onRowClick: PropTypes.func,\n onRowHover: PropTypes.func,\n emptyStateLabel: PropTypes.string,\n emptyStateChildren: PropTypes.node,\n sort: PropTypes.shape({\n sortOrder: PropTypes.oneOf(['ASC', 'DESC']),\n sortedBy: PropTypes.string,\n preferentialSortOrder: PropTypes.oneOf(['ASC', 'DESC']),\n }),\n onSort: PropTypes.func,\n updateTableKey: PropTypes.string,\n containerHeight: PropTypes.number,\n rowHeight: PropTypes.number.isRequired,\n dynamicRowHeight: PropTypes.bool,\n fullWidth: PropTypes.bool,\n lineActions: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.func,\n isDangerous: PropTypes.bool,\n onClick: PropTypes.func,\n })\n ),\n loading: PropTypes.bool,\n selectedRowsIndexes: PropTypes.array,\n}\n\nexport default SimpleTable\n\n```" } ]
code_store-on-localhost_14ae4567
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/Toolbar.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent } from 'react'\nimport PropTypes from 'prop-types'\n\nimport ActionMenu from '../ActionMenu'\nimport InputSearch from '../InputSearch'\nimport Button from '../Button'\nimport ButtonWithIcon from '../ButtonWithIcon'\nimport ButtonGroup from '../ButtonGroup'\nimport Toggle from '../Toggle'\nimport IconColumns from '../icon/Columns'\nimport IconDensity from '../icon/Density'\nimport IconDownload from '../icon/Download'\nimport IconPlus from '../icon/Plus'\nimport IconUpload from '../icon/Upload'\nimport IconOptionsDots from '../icon/OptionsDots'\n\nconst MAX_FIELDS_BOX_HEIGHT = 192\nconst FIELDS_BOX_ITEM_HEIGHT = 36\nconst FIELDS_BOX_WIDTH = 292\nconst BOX_SHADOW_STYLE = { boxShadow: '0px 1px 18px rgba(0, 0, 0, 0.14)' }\nconst DENSITY_OPTIONS = ['low', 'medium', 'high']\nconst ICON_OPTICAL_COMPENSATION = { marginTop: '1.5px' }\nconst LIGHT_ICON_SIZE = 16\nconst MEDIUM_ICON_SIZE = 14\nconst HEAVY_ICON_SIZE = 13\n\nclass Toolbar extends PureComponent {\n constructor(props) {\n super(props)\n this.fieldsBtnRef = React.createRef()\n this.extraActionsBtnRef = React.createRef()\n this.densityBtnRef = React.createRef()\n this.state = {\n isFieldsBoxVisible: false,\n isDensityBoxVisible: false,\n }\n }\n\n handleToggleBox = boxKey => {\n const isBoxVisible = this.state[boxKey]\n if (isBoxVisible) {\n document.removeEventListener('mousedown', this.handleClickOutside)\n } else {\n document.addEventListener('mousedown', this.handleClickOutside)\n }\n this.setState({ [`${boxKey}`]: !isBoxVisible })\n }\n\n handleClickOutside = e => {\n if (\n // handle clicks outside the show/hide fields btn or box\n this.fieldsBtnRef &&\n this.fieldsBtnRef.current &&\n !this.fieldsBtnRef.current.contains(e.target) &&\n this.state.isFieldsBoxVisible\n ) {\n // closes the box if it's open\n this.handleToggleBox('isFieldsBoxVisible')\n }\n if (\n this.densityBtnRef &&\n this.densityBtnRef.current &&\n !this.densityBtnRef.current.contains(e.target) &&\n this.state.isDensityBoxVisible\n ) {\n this.handleToggleBox('isDensityBoxVisible')\n }\n }\n\n calculateFieldsBoxHeight = () => {\n const { schema } = this.props\n const estimate =\n Object.keys(schema.properties).length * FIELDS_BOX_ITEM_HEIGHT\n return estimate > MAX_FIELDS_BOX_HEIGHT ? MAX_FIELDS_BOX_HEIGHT : estimate\n }\n\n calculateExtraActionsBoxHeight = () => {\n const {\n actions: { extraActions },\n } = this.props\n const estimate = extraActions.actions.length * FIELDS_BOX_ITEM_HEIGHT\n return estimate > MAX_FIELDS_BOX_HEIGHT ? MAX_FIELDS_BOX_HEIGHT : estimate\n }\n\n handleInputSearchSubmit = e => {\n this.props.onDeselectAllLines && this.props.onDeselectAllLines()\n\n this.props.actions.inputSearch.onSubmit &&\n this.props.actions.inputSearch.onSubmit(e)\n }\n\n render() {\n const {\n actions: {\n inputSearch,\n download,\n upload,\n fields,\n extraActions,\n newLine,\n density,\n },\n hiddenFields,\n schema,\n onHideAllColumns,\n onShowAllColumns,\n onToggleColumn,\n onToggleDensity,\n selectedDensity,\n loading,\n } = this.props\n const { isFieldsBoxVisible, isDensityBoxVisible } = this.state\n const isDownloadVisible = download && download.handleCallback\n const isUploadVisible = upload && upload.handleCallback\n const isFieldsVisible = fields && fields.showAllLabel && fields.hideAllLabel\n const isExtraActionsVisible =\n extraActions && extraActions.label && extraActions.actions.length > 0\n const isNewLineVisible = newLine && newLine.label\n const isSearchBarVisible = !!inputSearch\n const isDensityVisible =\n density &&\n density.buttonLabel &&\n density.lowOptionLabel &&\n density.mediumOptionLabel &&\n density.highOptionLabel\n\n const newLineButtonProps = {\n disabled: loading || (newLine && newLine.disabled),\n isLoading: newLine && newLine.isLoading,\n variation: 'primary',\n size: 'regular',\n }\n\n const forcedColor = 'c-on-base'\n\n const inputSearchAlone =\n inputSearch &&\n !isDensityVisible &&\n !isFieldsVisible &&\n !isDownloadVisible &&\n !isUploadVisible &&\n !isExtraActionsVisible &&\n !isNewLineVisible\n\n return (\n <div\n id=\"toolbar\"\n className={`mb5 flex flex-row w-100 ${\n isSearchBarVisible ? 'justify-between' : 'justify-end'\n }`}>\n {inputSearch && (\n <div className={inputSearchAlone ? 'w-100 w-40-ns' : 'w-40'}>\n <InputSearch\n disabled={loading}\n {...inputSearch}\n onSubmit={this.handleInputSearchSubmit}\n />\n </div>\n )}\n <div className=\"flex flex-row items-center\">\n {isDensityVisible && (\n <div\n id=\"toggleDensity\"\n title={density.buttonLabel}\n ref={this.densityBtnRef}\n className=\"relative mh1\">\n <ButtonWithIcon\n icon={\n <span\n className=\"c-on-base mh2\"\n style={ICON_OPTICAL_COMPENSATION}>\n <IconDensity size={MEDIUM_ICON_SIZE} />\n </span>\n }\n disabled={loading}\n variation=\"tertiary\"\n size=\"regular\"\n onClick={() => this.handleToggleBox('isDensityBoxVisible')}\n />\n {isDensityBoxVisible && (\n <div\n className={`absolute ${\n density.alignMenu === 'right' ? 'right-0' : 'left-0'\n } z-999 ba b--muted-4 br2 mt2 mh2`}\n style={BOX_SHADOW_STYLE}>\n <div className=\"w-100 b2 br2 bg-base\">\n <div\n style={{ height: 3 * FIELDS_BOX_ITEM_HEIGHT }}\n className=\"overflow-auto\">\n {DENSITY_OPTIONS.map((key, index) => {\n const isKeySelected = selectedDensity === key\n return (\n <div\n key={index}\n className={`flex justify-between ph6 pv3 ${\n isKeySelected ? 'b--emphasis' : 'b--transparent'\n } pointer hover-bg-muted-5 bl bw1`}\n onClick={() => {\n onToggleDensity(key)\n this.handleToggleBox('isDensityBoxVisible')\n density.handleCallback &&\n density.handleCallback(key)\n }}>\n <span\n className={`w-100 ${isKeySelected ? 'fw5' : ''}`}>\n {density[`${key}OptionLabel`]}\n </span>\n </div>\n )\n })}\n </div>\n </div>\n </div>\n )}\n </div>\n )}\n {isFieldsVisible && (\n <div\n id=\"toggleFieldsBtn\"\n title={fields.label}\n ref={this.fieldsBtnRef}\n className=\"relative mh1\">\n <ButtonWithIcon\n icon={\n <span\n className=\"c-on-base mh2\"\n style={ICON_OPTICAL_COMPENSATION}>\n <IconColumns size={MEDIUM_ICON_SIZE} />\n </span>\n }\n disabled={loading}\n variation=\"tertiary\"\n size=\"regular\"\n onClick={() => this.handleToggleBox('isFieldsBoxVisible')}\n />\n {isFieldsBoxVisible && (\n <div\n className={`absolute ${\n fields.alignMenu === 'right' ? 'right-0' : 'left-0'\n } z-999 ba b--muted-4 br2 mt2 mh2`}>\n <div\n className=\"w-100 b2 br2 bg-base\"\n style={{\n ...BOX_SHADOW_STYLE,\n width: FIELDS_BOX_WIDTH,\n }}>\n <div className=\"flex inline-flex bb b--muted-4 w-100 pl6 pv4\">\n <Button\n variation=\"secondary\"\n size=\"regular\"\n onClick={onShowAllColumns}>\n {fields.showAllLabel}\n </Button>\n <div className=\"mh4\">\n <Button\n variation=\"secondary\"\n size=\"regular\"\n onClick={onHideAllColumns}>\n {fields.hideAllLabel}\n </Button>\n </div>\n </div>\n <div\n style={{ height: this.calculateFieldsBoxHeight() }}\n className=\"overflow-auto\">\n {Object.keys(schema.properties)\n .filter(\n field =>\n !!(schema.properties[field].title || field).trim()\n )\n .map((field, index) => (\n <div\n key={index}\n className=\"flex justify-between ph6 pv3 pointer hover-bg-muted-5\"\n onClick={() => onToggleColumn(field)}>\n <span className=\"w-70 truncate\">\n {schema.properties[field].title || field}\n </span>\n <Toggle\n size=\"regular\"\n checked={!hiddenFields.includes(field)}\n />\n </div>\n ))}\n </div>\n </div>\n </div>\n )}\n </div>\n )}\n {isDownloadVisible && (\n <div title={download.label} className=\"mh2\">\n <ButtonWithIcon\n icon={\n <span\n className={`${download.disabled ? '' : forcedColor} mh2`}>\n <IconDownload size={MEDIUM_ICON_SIZE} />\n </span>\n }\n variation=\"tertiary\"\n disabled={download.disabled}\n isLoading={download.isLoading}\n size=\"regular\"\n onClick={download.handleCallback}>\n {download.label && (\n <span className={`${download.disabled ? '' : forcedColor}`}>\n {download.label}\n </span>\n )}\n </ButtonWithIcon>\n </div>\n )}\n {isUploadVisible && (\n <div title={upload.label} className=\"mh2\">\n <ButtonWithIcon\n icon={\n <span\n className={`${upload.disabled ? '' : forcedColor} mh2`}\n style={ICON_OPTICAL_COMPENSATION}>\n <IconUpload size={HEAVY_ICON_SIZE} />\n </span>\n }\n variation=\"tertiary\"\n disabled={upload.disabled}\n isLoading={upload.isLoading}\n size=\"regular\"\n onClick={upload.handleCallback}>\n {upload.label && (\n <span className={`${upload.disabled ? '' : forcedColor}`}>\n {upload.label}\n </span>\n )}\n </ButtonWithIcon>\n </div>\n )}\n {isExtraActionsVisible && (\n <div title={extraActions.label} className=\"mh2\">\n <ActionMenu\n hideCaretIcon\n buttonProps={{\n variation: 'tertiary',\n icon: (\n <span className=\"c-on-base\">\n <IconOptionsDots />\n </span>\n ),\n size: 'regular',\n }}\n options={extraActions.actions.map(action => {\n return {\n label: action.label,\n onClick: action.handleCallback,\n }\n })}\n />\n </div>\n )}\n {isNewLineVisible &&\n (newLine.actions ? (\n <ButtonGroup\n buttons={[\n <ButtonWithIcon\n isActiveOfGroup\n key=\"new-line-button\"\n icon={<IconPlus solid size={LIGHT_ICON_SIZE} />}\n onClick={newLine.handleCallback}\n {...newLineButtonProps}>\n {newLine.label}\n </ButtonWithIcon>,\n <ActionMenu\n isActiveOfGroup\n key=\"actions-button\"\n buttonProps={newLineButtonProps}\n options={newLine.actions}\n />,\n ]}\n />\n ) : (\n <ButtonWithIcon\n icon={<IconPlus solid size={LIGHT_ICON_SIZE} />}\n onClick={newLine.handleCallback}\n {...newLineButtonProps}>\n {newLine.label}\n </ButtonWithIcon>\n ))}\n </div>\n </div>\n )\n }\n}\n\nToolbar.defaultProps = {\n actions: {\n extraActions: {\n actions: [],\n },\n },\n}\n\nToolbar.propTypes = {\n actions: PropTypes.shape({\n inputSearch: PropTypes.shape({\n onSubmit: PropTypes.func,\n }),\n density: PropTypes.shape({\n buttonLabel: PropTypes.string,\n lowOptionLabel: PropTypes.string,\n handleCallback: PropTypes.func,\n mediumOptionLabel: PropTypes.string,\n highOptionLabel: PropTypes.string,\n alignMenu: PropTypes.oneOf(['right', 'left']),\n }),\n fields: PropTypes.shape({\n label: PropTypes.string,\n showAllLabel: PropTypes.string,\n hideAllLabel: PropTypes.string,\n alignMenu: PropTypes.oneOf(['right', 'left']),\n }),\n download: PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n isLoading: PropTypes.bool,\n disabled: PropTypes.bool,\n }),\n upload: PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n isLoading: PropTypes.bool,\n disabled: PropTypes.bool,\n }),\n extraActions: PropTypes.shape({\n label: PropTypes.string,\n actions: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n })\n ),\n alignMenu: PropTypes.oneOf(['right', 'left']),\n isLoading: PropTypes.bool,\n }),\n newLine: PropTypes.shape({\n label: PropTypes.string.isRequired,\n handleCallback: PropTypes.func.isRequired,\n disabled: PropTypes.bool,\n isLoading: PropTypes.bool,\n actions: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.string,\n handleCallback: PropTypes.func,\n toggle: PropTypes.shape({\n checked: PropTypes.bool,\n semantic: PropTypes.bool,\n }),\n })\n ),\n }),\n }),\n schema: PropTypes.object.isRequired,\n hiddenFields: PropTypes.array,\n onToggleColumn: PropTypes.func,\n onDeselectAllLines: PropTypes.func,\n onHideAllColumns: PropTypes.func,\n onShowAllColumns: PropTypes.func,\n onToggleDensity: PropTypes.func,\n selectedDensity: PropTypes.string,\n loading: PropTypes.bool,\n}\n\nexport default Toolbar\n\n```" } ]
code_store-on-localhost_95d0e300
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/BulkActionsSelectedRows.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nclass BulkActionsSelectedRows extends Component {\n shouldComponentUpdate(nextProps) {\n // This prevents the value from showing 0 when bar is closing\n // It reduces the \"noise\" given to the user from a ux point of view\n if (nextProps.selectedRowsLength === 0) {\n return false\n }\n return true\n }\n\n render() {\n return this.props.selectedRowsLength\n }\n}\n\nBulkActionsSelectedRows.propTypes = {\n selectedRowsLength: PropTypes.number.isRequired,\n}\n\nexport default BulkActionsSelectedRows\n\n```" } ]
code_store-on-localhost_d8845539
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Table/SwitchablePagination.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport Pagination from '../Pagination'\n\nfunction SwitchablePagination({ children, enabled, ...paginationProps }) {\n if (enabled) {\n return <Pagination {...paginationProps}>{children}</Pagination>\n }\n return children\n}\n\nSwitchablePagination.defaultProps = {\n enabled: false,\n}\n\nSwitchablePagination.propTypes = {\n currentItemFrom: PropTypes.number,\n currentItemTo: PropTypes.number,\n enabled: PropTypes.bool,\n onNextClick: PropTypes.func,\n onPrevClick: PropTypes.func,\n onRowsChange: PropTypes.func,\n rowsOptions: PropTypes.array,\n textOf: PropTypes.node,\n textShowRows: PropTypes.node,\n totalItems: PropTypes.number,\n}\n\nexport default SwitchablePagination\n\n```" } ]
code_store-on-localhost_b9c1f4d6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ModalDialog/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\n\nimport Modal from '../Modal'\nimport Button from '../Button'\n\nconst NOOP = () => {}\n\nclass ModalDialog extends Component {\n handleCloseTransitionFinish = () => {\n this.props.onCloseTransitionFinish && this.props.onCloseTransitionFinish()\n }\n\n handleConfirmation = () => {\n this.props.confirmation &&\n this.props.confirmation.onClick &&\n this.props.confirmation.onClick()\n }\n\n handleCancelation = () => {\n this.props.cancelation &&\n this.props.cancelation.onClick &&\n this.props.cancelation.onClick()\n }\n\n render() {\n const { confirmation, cancelation, loading, onClose } = this.props\n\n return (\n <Modal\n {...this.props}\n onClose={loading ? NOOP : onClose}\n onCloseTransitionFinish={this.handleCloseTransitionFinish}>\n {this.props.children}\n <div className=\"vtex-modal__confirmation flex justify-end mt8\">\n <span className=\"mr4\">\n <Button\n size=\"small\"\n variation=\"tertiary\"\n disabled={loading}\n onClick={this.handleCancelation}>\n {cancelation.label}\n </Button>\n </span>\n\n <Button\n size=\"small\"\n variation={confirmation.isDangerous ? 'danger' : 'primary'}\n isLoading={loading}\n onClick={this.handleConfirmation}>\n {confirmation.label}\n </Button>\n </div>\n </Modal>\n )\n }\n}\n\nModalDialog.propTypes = {\n children: PropTypes.node,\n confirmation: PropTypes.shape({\n label: PropTypes.string.isRequired,\n onClick: PropTypes.func.isRequired,\n isDangerous: PropTypes.bool,\n }).isRequired,\n cancelation: PropTypes.shape({\n label: PropTypes.string.isRequired,\n onClick: PropTypes.func.isRequired,\n }).isRequired,\n onClose: PropTypes.func,\n loading: PropTypes.bool,\n onCloseTransitionFinish: PropTypes.func,\n}\n\nexport default ModalDialog\n\n```" } ]
code_store-on-localhost_fc693706
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ModalDialog/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nDefault\n\n```js\nconst Button = require('../Button').default\n\nclass ModalDialogExample extends React.Component {\n constructor() {\n super()\n this.state = { isModalOpen: false }\n this.handleModalToggle = this.handleModalToggle.bind(this)\n }\n\n handleModalToggle() {\n this.setState({ isModalOpen: !this.state.isModalOpen })\n }\n\n render() {\n return (\n <div>\n <Button onClick={this.handleModalToggle}>Open modal</Button>\n\n <ModalDialog\n centered\n confirmation={{\n onClick: this.handleModalToggle,\n label: 'Ok',\n }}\n cancelation={{\n onClick: this.handleModalToggle,\n label: 'Cancel',\n }}\n isOpen={this.state.isModalOpen}\n onClose={this.handleModalToggle}>\n <h1>Confirm?</h1>\n <p>\n Some child content before the action buttons. Lorem ipsum dolor sit\n amet, consectetur adipiscing elit. Praesent semper eget magna sit\n amet maximus. In rutrum, justo sodales euismod dignissim, justo orci\n venenatis lectus, vel semper turpis nunc a justo.\n </p>\n </ModalDialog>\n </div>\n )\n }\n}\n\n;<ModalDialogExample />\n```\n\nLoading\n\n```js\nconst Button = require('../Button').default\n\nclass ModalDialogExample extends React.Component {\n constructor() {\n super()\n this.state = { isModalOpen: false, loading: false }\n this.handleOpen = this.handleOpen.bind(this)\n this.handleConfirmation = this.handleConfirmation.bind(this)\n this.handleCancelation = this.handleCancelation.bind(this)\n }\n\n handleOpen() {\n this.setState({ isModalOpen: true })\n }\n\n handleConfirmation() {\n this.setState({ loading: true })\n setTimeout(\n () => this.setState({ isModalOpen: false, loading: false }),\n 1500\n )\n }\n\n handleCancelation() {\n this.setState({ isModalOpen: false })\n }\n\n render() {\n const { isModalOpen, loading } = this.state\n return (\n <div>\n <Button onClick={this.handleOpen}>Open modal</Button>\n\n <ModalDialog\n centered\n loading={loading}\n confirmation={{\n onClick: this.handleConfirmation,\n label: 'Ok',\n }}\n cancelation={{\n onClick: this.handleCancelation,\n label: 'Cancel',\n }}\n isOpen={isModalOpen}\n onClose={this.handleCancelation}>\n <h1>Confirm?</h1>\n <p>\n Some child content before the action buttons. Lorem ipsum dolor sit\n amet, consectetur adipiscing elit. Praesent semper eget magna sit\n amet maximus. In rutrum, justo sodales euismod dignissim, justo orci\n venenatis lectus, vel semper turpis nunc a justo.\n </p>\n </ModalDialog>\n </div>\n )\n }\n}\n\n;<ModalDialogExample />\n```\n\nDangerous\n\n```js\nconst Button = require('../Button').default\n\nclass ModalDialogExample extends React.Component {\n constructor() {\n super()\n this.state = { isModalOpen: false, loading: false }\n this.handleOpen = this.handleOpen.bind(this)\n this.handleConfirmation = this.handleConfirmation.bind(this)\n this.handleCancelation = this.handleCancelation.bind(this)\n }\n\n handleOpen() {\n this.setState({ isModalOpen: true })\n }\n\n handleConfirmation() {\n this.setState({ loading: true })\n setTimeout(\n () => this.setState({ isModalOpen: false, loading: false }),\n 1500\n )\n }\n\n handleCancelation() {\n this.setState({ isModalOpen: false })\n }\n\n render() {\n const { isModalOpen, loading } = this.state\n return (\n <div>\n <Button onClick={this.handleOpen}>Open modal</Button>\n\n <ModalDialog\n centered\n loading={loading}\n confirmation={{\n onClick: this.handleConfirmation,\n label: 'Are you sure?',\n isDangerous: true,\n }}\n cancelation={{\n onClick: this.handleCancelation,\n label: 'Cancel',\n }}\n isOpen={isModalOpen}\n onClose={this.handleCancelation}>\n <h1>Do you really, really, want to do that?</h1>\n <p>\n Some child content before the action buttons. Lorem ipsum dolor sit\n amet, consectetur adipiscing elit. Praesent semper eget magna sit\n amet maximus. In rutrum, justo sodales euismod dignissim, justo orci\n venenatis lectus, vel semper turpis nunc a justo.\n </p>\n </ModalDialog>\n </div>\n )\n }\n}\n\n;<ModalDialogExample />\n```\n\n```" } ]
code_store-on-localhost_a20e28bb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Collapsible/styles.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n.jsFocusVisible :focus:not([data-focus-visible-added]) {\n outline: none;\n}\n\n\n```" } ]
code_store-on-localhost_306b4b97
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Collapsible/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component, Fragment } from 'react'\nimport PropTypes from 'prop-types'\n\nimport CaretDown from '../icon/CaretDown'\nimport CaretUp from '../icon/CaretUp'\nimport { jsFocusVisible } from './styles.css'\n\nconst colorMap = {\n base: 'c-on-base',\n primary: 'c-action-primary',\n muted: 'c-muted-3',\n}\n\nfunction handleClick(callback, isOpen) {\n callback &&\n callback({\n target: {\n isOpen,\n },\n })\n}\n\nfunction mapToCSSClass(color) {\n return colorMap[color]\n}\n\nclass Collapsible extends Component {\n constructor(props) {\n super(props)\n this.childrenRef = React.createRef()\n this.openTimeout = null\n this.closeTimeout = null\n this.state = {\n height: 0,\n }\n }\n\n handleTransitionEnd = () => {\n this.setState({\n height: this.props.isOpen ? 'auto' : 0,\n })\n }\n\n openCard = () => {\n this.childrenRef.current.style.height = 'auto'\n const childrenHeight = this.childrenRef.current.offsetHeight\n this.childrenRef.current.style.height = 0\n /** after force setting element height like the line above\n * you have to force layout / reflow so the height value\n * may actually apply. You can do this by requesting\n * element offsetHeight again, like the line below\n */\n this.childrenRef.current.offsetHeight\n this.setState({\n height: childrenHeight,\n })\n }\n\n closeCard = () => {\n const childrenHeight = this.childrenRef.current.offsetHeight\n this.setState(\n {\n height: childrenHeight,\n },\n () => {\n window.requestAnimationFrame(() => this.setState({ height: 0 }))\n }\n )\n }\n\n componentDidMount() {\n if (this.props.isOpen) {\n this.setState({ height: 'auto' })\n }\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.isOpen !== this.props.isOpen) {\n if (this.props.isOpen) {\n this.openCard()\n } else {\n this.closeCard()\n }\n }\n }\n\n render() {\n const {\n align,\n children,\n header,\n muted,\n onClick: callback,\n isOpen,\n arrowAlign,\n } = this.props\n let { caretColor } = this.props\n const { height } = this.state\n const childrenContainerStyle = {\n height,\n overflow: 'hidden',\n transition: 'height 250ms ease-in-out',\n }\n if (muted) {\n caretColor = caretColor || 'muted'\n console.warn(\n `The \"muted\" prop on the \"Collapsible\" component is depreacted and will be removed in a future version. Use \"caretColor='muted'\" instead.`\n )\n }\n\n const color = caretColor ? mapToCSSClass(caretColor) : 'c-action-primary'\n\n return (\n <div className={jsFocusVisible}>\n <div\n className=\"flex flex-row items-center pointer\"\n tabIndex={0}\n role=\"button\"\n onClick={() => handleClick(callback, !isOpen)}\n onKeyDown={e => e.key === 'Enter' && handleClick(callback, !isOpen)}\n aria-expanded={isOpen}>\n {align === 'left' ? (\n <Fragment>\n <div className={`${color} mr3 self-${arrowAlign}`}>\n {isOpen ? <CaretUp /> : <CaretDown />}\n </div>\n <div className=\"flex-grow-1\">{header}</div>\n </Fragment>\n ) : (\n <Fragment>\n <div className=\"flex-grow-1\">{header}</div>\n <div className={`${color} ml3 self-${arrowAlign}`}>\n {isOpen ? <CaretUp /> : <CaretDown />}\n </div>\n </Fragment>\n )}\n </div>\n <div\n ref={this.childrenRef}\n style={childrenContainerStyle}\n role=\"region\"\n onTransitionEnd={this.handleTransitionEnd}>\n {children}\n </div>\n </div>\n )\n }\n}\n\nCollapsible.defaultProps = {\n align: 'left',\n isOpen: false,\n muted: false,\n arrowAlign: 'center',\n}\n\nCollapsible.propTypes = {\n /** Caret alignment.\n * Use _right_ alignment only in small width scenarios. */\n align: PropTypes.oneOf(['right', 'left']),\n /** Content of the collapsible */\n children: PropTypes.node.isRequired,\n /** Component to be used as the header of the collapsible. */\n header: PropTypes.node.isRequired,\n /** @deprecated Use the 'muted' option in the caretColor prop instead.\n * To be used only in dense scenarios, or when the affordance is clearly\n * conveyed by the context. */\n muted: PropTypes.bool,\n /** Controls whether the collapsible is open or not. */\n isOpen: PropTypes.bool,\n /** _onClick_ event. */\n onClick: PropTypes.func,\n /** Color or semantic to be applied to the Caret Icon in the Collapsible header.*/\n caretColor: PropTypes.oneOf(Object.keys(colorMap)),\n /** Vertical position of arrow icon.*/\n arrowAlign: PropTypes.oneOf([\n 'start',\n 'center',\n 'end',\n 'baseline',\n 'stretch',\n ]),\n}\n\nexport default Collapsible\n\n```" } ]
code_store-on-localhost_5b0efeea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Collapsible/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### Collapsibles are containers that allows an toggling the display of an initially hidden content. Its main objective is to hide from view detailed information that might not be necessarily.\n\n### ๐Ÿ‘ Dos\n\n- Do make your header as complex as you want, but avoid nesting interactive elements.\n- Do nest collapsibles if needed, but avoid too many levels.\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't hide information that you consider critical for the user in that given moment. For the same reason, it doesn't make sense to initialize a collapsible in the expanded state.\n- Avoid using the right-aligned variation with widths larger than around 600px or if affordance might be at stake.\n- Avoid using the muted variation if affordance is not well secured.\n\n\nUsage\n \n```js\ninitialState = { isOpen1: false, isOpen2: false }\n;<div>\n <Collapsible\n header={<span>Here goes your header</span>}\n onClick={e => setState({ isOpen1: e.target.isOpen })}\n isOpen={state.isOpen1}\n >\n <div className=\"mt4\">\n Here goes your content\n </div>\n </Collapsible>\n</div>\n```\n\n\"Read-more-like\" example\n\n```js\nconst Input = require('../Input').default\ninitialState = { isOpen: false }\n;<div className=\"w-50\">\n <div className=\"mb3\">\n <Input label=\"Name\" />\n </div>\n <div className=\"mb3\">\n <Input label=\"Email\" prefix={<span>@</span>} />\n </div>\n <div className=\"mb5 mt5\">\n <Collapsible\n header={\n <span className=\"c-action-primary hover-c-action-primary fw5\">\n Advanced settings\n </span>\n }\n onClick={e => setState({ isOpen: e.target.isOpen })}\n isOpen={state.isOpen}\n >\n <div className=\"mt4\">\n <div className=\"mb3\">\n <Input label=\"Surname\" />\n </div>\n <div className=\"mb3\">\n <Input label=\"Nickname\" />\n </div>\n </div>\n </Collapsible>\n </div>\n</div>\n```\n\nCustom Caret Color Example\n\n```js\ninitialState = { isOpen1: false, isOpen2: false, isOpen3: false }\n;<div>\n <Collapsible\n header={<span>Here goes your base header</span>}\n onClick={e => setState({ isOpen1: e.target.isOpen })}\n isOpen={state.isOpen1}\n caretColor=\"base\"\n >\n <div className=\"mt4\">\n Here goes your content\n </div>\n </Collapsible>\n <Collapsible\n header={<span>Here goes your primary header</span>}\n onClick={e => setState({ isOpen2: e.target.isOpen })}\n isOpen={state.isOpen2}\n caretColor=\"primary\"\n >\n <div className=\"mt4\">\n Here goes your content\n </div>\n </Collapsible>\n <Collapsible\n header={<span>Here goes your muted header</span>}\n onClick={e => setState({ isOpen3: e.target.isOpen })}\n isOpen={state.isOpen3}\n caretColor=\"muted\"\n >\n <div className=\"mt4\">\n Here goes your content\n </div>\n </Collapsible>\n</div>\n```\n\nNavigation bar example\n\n```js\nconst PageBlock = require('../PageBlock').default\ninitialState = { isOpen1: false, isOpen2: false, isOpen3: false }\n\n;<div>\n <div className=\"w5\">\n <div className=\"mt4\">\n <Collapsible\n header={\n <div className=\"c-on-base hover-c-emphasis\">\n <span>\n <svg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'>\n <path d='M7 8H1C0.4 8 0 8.4 0 9V15C0 15.6 0.4 16 1 16H7C7.6 16 8 15.6 8 15V9C8 8.4 7.6 8 7 8Z'\n fill='currentColor' />\n <path d='M11 4H2V6H10V14H12V5C12 4.4 11.6 4 11 4Z' fill='currentColor' />\n <path d='M15 0H6V2H14V10H16V1C16 0.4 15.6 0 15 0Z' fill='currentColor' />\n </svg>\n </span>\n <span className=\"ml5 fw5\">\n Catalog\n </span>\n </div>\n }\n align=\"right\"\n onClick={e => setState({ isOpen1: e.target.isOpen })}\n isOpen={state.isOpen1}\n caretColor=\"muted\"\n >\n <div className=\"ml6 mt4\">\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Products and SKUs</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Categories</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Brands</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Import and export</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Reports</a>\n </div>\n </Collapsible>\n </div>\n\n <div className=\"mt4\">\n <Collapsible\n header={\n <div className=\"c-on-base hover-c-emphasis\">\n <span>\n <svg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'>\n <path d='M16 5V3C16 2.4 15.6 2 15 2H1C0.4 2 0 2.4 0 3V5H16Z' fill='currentColor'\n />\n <path fillRule='evenodd' clipRule='evenodd' d='M0 7V13C0 13.6 0.4 14 1 14H15C15.6 14 16 13.6 16 13V7H0ZM6 11H2V10H6V11ZM12 11H14V10H12V11Z'\n fill='currentColor' />\n </svg>\n </span>\n <span className=\"ml5 fw5\">\n Payments\n </span>\n </div>\n }\n align=\"right\"\n onClick={e => setState({ isOpen2: e.target.isOpen })}\n isOpen={state.isOpen2}\n caretColor=\"muted\"\n >\n <div className=\"ml6 mt4\">\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Transactions</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Bank conciliation</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Gift card</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Settings</a>\n </div>\n </Collapsible>\n </div>\n\n <div className=\"mt4\">\n <Collapsible\n header={\n <div className=\"c-on-base hover-c-emphasis\">\n <span>\n <svg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'>\n <path d='M16 12H5.8C5.5 11.2 4.8 10.5 4 10.2V1C4 0.4 3.6 0 3 0H0V2H2V10.2C0.8 10.6 0 11.7 0 13C0 14.7 1.3 16 3 16C4.3 16 5.4 15.2 5.8 14H16V12Z'\n fill='currentColor' />\n <path d='M7 10H14C14.6 10 15 9.6 15 9V4C15 3.4 14.6 3 14 3H7C6.4 3 6 3.4 6 4V9C6 9.6 6.4 10 7 10Z'\n fill='currentColor' />\n </svg>\n </span>\n <span className=\"ml5 fw5\">\n Inventory & shipping\n </span>\n </div>\n }\n align=\"right\"\n onClick={e => setState({ isOpen3: e.target.isOpen })}\n isOpen={state.isOpen3}\n caretColor=\"muted\"\n >\n <div className=\"ml6 mt4\">\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Dashboard</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Shipping</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Inventory</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Pickup points</a>\n <a href=\"#\" className=\"mt3 c-muted-1 link db hover-c-link\">Settings</a>\n </div>\n </Collapsible>\n </div>\n </div>\n</div>\n```\n\nFAQ accordion example\n\n```js\nconst PageBlock = require('../PageBlock').default\nconst Box = require('../Box').default\n\ninitialState = { openQuestion: null }\n\nfunction toggleAccordion(questionNbr) {\n return e => setState(\n { openQuestion: state.openQuestion !== questionNbr ? questionNbr : null }\n );\n}\n\n;<div>\n <div className=\"bg-muted-5 pa8\">\n <div className=\"w-100\">\n <Box>\n <Collapsible\n header={\n <div className=\"pv6 hover-c-on-action-secondary\">\n What is your name?\n </div>\n }\n onClick={toggleAccordion(1)}\n isOpen={ state.openQuestion===1 }\n >\n <div className=\"bg-muted-5 pa6\">\n Arthur, King of the Britons.\n </div>\n </Collapsible>\n\n <hr className=\"ma0 bb bb-0 b--black-10\"/>\n\n <Collapsible\n header={\n <div className=\"pv6 hover-c-on-action-secondary\">\n What is your quest?\n </div>\n }\n onClick={toggleAccordion(2)}\n isOpen={ state.openQuestion===2 }\n >\n <div className=\"bg-muted-5 pa6\">\n To seek the Holy Grail.\n </div>\n </Collapsible>\n\n <hr className=\"ma0 bb bb-0 b--black-10\"/>\n\n <Collapsible\n header={\n <div className=\"pv6 hover-c-on-action-secondary\">\n What is your favorite color?\n </div>\n }\n onClick={toggleAccordion(3)}\n isOpen={ state.openQuestion===3 }\n >\n <div className=\"bg-muted-5 pa6\">\n Pink.\n </div>\n </Collapsible>\n\n <hr className=\"ma0 bb bb-0 b--black-10\"/>\n\n <Collapsible\n header={\n <div className=\"pv6 hover-c-on-action-secondary\">\n What is the air-speed velocity of an unladen swallow?\n </div>\n }\n onClick={toggleAccordion(4)}\n isOpen={ state.openQuestion===4 }\n >\n <div className=\"bg-muted-5 pa6\">\n What do you mean? An African or European swallow?\n </div>\n </Collapsible>\n </Box>\n </div>\n </div>\n</div>\n```\n\n```" } ]
code_store-on-localhost_08f68ae4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Divider/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nconst propTypes = {\n orientation: PropTypes.oneOf(['vertical', 'horizontal']),\n}\n\nconst Divider: React.FC<PropTypes.InferProps<typeof propTypes>> = props => {\n const size = {\n [props.orientation === 'horizontal' ? 'height' : 'width']: 1,\n }\n return <div className=\"bg-light-gray\" style={size} />\n}\n\nDivider.propTypes = propTypes\nDivider.defaultProps = {\n orientation: 'horizontal',\n}\n\nexport default Divider\n\n```" } ]
code_store-on-localhost_266ea178
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Divider/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Horizontal\n\n```jsx\n<div className=\"flex flex-column h3\">\n <span>text 1</span>\n <Divider orientation=\"horizontal\" />\n <span>text 2</span>\n</div>\n```\n\n# Vertical\n\n```jsx\n<div className=\"flex h3\">\n <span>text 1</span>\n <Divider orientation=\"vertical\" />\n <span>text 2</span>\n</div>\n```\n\n```" } ]
code_store-on-localhost_3a7bcd89
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Menu/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { Overlay } from 'react-overlays'\n\nimport Toggle from '../Toggle'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nconst DEFAULT_WIDTH = 292\nconst CONTAINER_MARGIN = 6\nconst WINDOW_MARGIN = 10\nconst DEFAULT_DOCUMENT_ELEMENT = {\n scrollTop: 0,\n scrollLeft: 0,\n clientWidth: 0,\n clientHeight: 0,\n}\n\nclass Menu extends Component {\n constructor(props) {\n super(props)\n this.containerElement = React.createRef()\n this.menuElement = props.forwardedRef || React.createRef()\n }\n\n state = {\n hasCalculatedSize: false, // hides the menu while calculating its size and position\n isUpwards: false, // opens the menu from bottom to top, if it doesn't fit on the screen otherwise\n isVisible: false, // triggers the opening animation\n menuHeight: 0,\n containerHeight: 0,\n }\n\n onWindowResize = () => this.forceUpdate()\n\n componentDidMount() {\n if (window) window.addEventListener('resize', this.onWindowResize)\n }\n\n componentWillUnmount() {\n if (window) window.removeEventListener('resize', this.onWindowResize)\n }\n\n getMenuBounds = () =>\n this.menuElement.current &&\n this.menuElement.current.getBoundingClientRect &&\n this.menuElement.current.getBoundingClientRect()\n\n getContainerBounds = () =>\n this.containerElement.current &&\n this.containerElement.current.getBoundingClientRect &&\n this.containerElement.current.getBoundingClientRect()\n\n updateMenu() {\n const menuBounds = this.getMenuBounds()\n const containerBounds = this.getContainerBounds()\n\n if (!menuBounds || !containerBounds) return\n\n const containerHeight = containerBounds.height\n\n const initialMenuHeight = menuBounds.height\n\n const itemHeight = initialMenuHeight / this.props.options.length\n\n const isOutOfBounds =\n menuBounds.top + initialMenuHeight + containerHeight > window.innerHeight\n\n const isUpwards =\n isOutOfBounds && containerBounds.top > window.innerHeight / 2\n\n const maxMenuHeight = isUpwards\n ? menuBounds.top - CONTAINER_MARGIN - WINDOW_MARGIN - containerHeight\n : window.innerHeight - menuBounds.top - CONTAINER_MARGIN - WINDOW_MARGIN\n\n // Makes the height of the menu, if it doesn't entirely fit on the screen,\n // fall in the middle of an item, to hint that the menu scrolls\n const visibleItemsNum = Math.round(maxMenuHeight / itemHeight)\n const adjustedMenuHeight = visibleItemsNum * itemHeight - itemHeight / 2\n\n const menuHeight =\n maxMenuHeight < initialMenuHeight ? adjustedMenuHeight : 0\n\n this.setState(\n {\n containerHeight,\n menuHeight,\n isUpwards,\n hasCalculatedSize: true,\n },\n () => {\n // triggers the menu opening animation\n setTimeout(() => {\n this.setState({ isVisible: true })\n }, 1)\n }\n )\n }\n\n componentDidUpdate(prevProps) {\n if (!prevProps.open && this.props.open) {\n this.updateMenu()\n }\n\n if (prevProps.open && !this.props.open) {\n this.setState({\n hasCalculatedSize: false,\n isUpwards: false,\n isVisible: false,\n menuHeight: 0,\n containerHeight: 0,\n })\n }\n }\n\n render() {\n const { options, align, open, onClose, children, width } = this.props\n const { hasCalculatedSize, isUpwards, isVisible, menuHeight } = this.state\n\n const isRight = align === 'right'\n\n return (\n <div className=\"relative\">\n <div ref={this.containerElement}>{children}</div>\n <Overlay show={open}>\n {() => {\n const { top, left, right, height } = this.getContainerBounds()\n\n const {\n scrollTop,\n scrollLeft,\n clientWidth,\n clientHeight,\n } = document ? document.documentElement : DEFAULT_DOCUMENT_ELEMENT\n\n return (\n <div\n ref={this.menuElement}\n style={{\n transform:\n !hasCalculatedSize || isVisible\n ? 'scale(1)'\n : 'scale(0.9, 0.6)',\n transformOrigin: `${isRight ? '75%' : '25%'} ${\n isUpwards ? '100%' : '0'\n }`,\n transition: isVisible\n ? 'transform 50ms ease-out, opacity 25ms'\n : 'none',\n [isUpwards ? 'bottom' : 'top']: isUpwards\n ? clientHeight - (top + scrollTop - CONTAINER_MARGIN)\n : top + scrollTop + height + CONTAINER_MARGIN,\n [isRight ? 'right' : 'left']: isRight\n ? clientWidth - right\n : left + scrollLeft,\n width: width || DEFAULT_WIDTH,\n }}\n className={`absolute z-999 ba b--muted-4 br2 shadow-5 ${\n isRight ? 'right-0' : 'left-0'\n }\n ${isVisible ? 'o-100' : 'o-0'}`}>\n <div className=\"b2 br2 bg-base\">\n <div\n style={{ height: menuHeight || 'auto' }}\n className={menuHeight ? 'overflow-auto' : ''}>\n {options.map((option, index) => (\n <button\n key={index}\n className=\"flex justify-between items-center t-body ph6 h-regular pointer hover-bg-muted-5 ma0 bg-transparent bn w-100 tl\"\n onClick={() => {\n option.onClick(option)\n if (onClose) {\n onClose()\n }\n }}>\n <span\n className={`${\n option.toggle ? 'w-70 truncate' : 'w-100 truncate'\n } ${option.isDangerous ? 'c-danger' : ''}`}>\n {option.label}\n </span>\n {option.toggle && (\n <div style={{ pointerEvents: 'none' }}>\n <Toggle\n size=\"regular\"\n semantic={option.toggle.semantic}\n checked={option.toggle.checked}\n />\n </div>\n )}\n </button>\n ))}\n </div>\n </div>\n </div>\n )\n }}\n </Overlay>\n </div>\n )\n }\n}\n\nMenu.defaultProps = {\n options: [],\n align: 'right',\n open: false,\n}\n\nMenu.propTypes = {\n /** The element which will open the menu--the menu will\n * be positioned around this element */\n children: PropTypes.node,\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** Menu visibility (default is false) */\n open: PropTypes.bool,\n /** Menu Box width (default is 292px) */\n width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /** Menu options */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n label: PropTypes.node,\n onClick: PropTypes.func,\n /** whether option has inline toggle */\n toggle: PropTypes.shape({\n checked: PropTypes.bool,\n semantic: PropTypes.bool,\n }),\n })\n ),\n /** function to close the menu after clicking an option */\n onClose: PropTypes.func,\n /** Menu Box align (default is right) */\n align: PropTypes.oneOf(['right', 'left']),\n}\n\nexport default withForwardedRef(Menu)\n\n```" } ]
code_store-on-localhost_c009d081
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/index.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport ButtonWithIcon from '../ButtonWithIcon/index'\nimport IconPlus from '../icon/Plus/index'\nimport IconClose from '../icon/Close/index'\nimport Separator from './Separator'\nimport StrategySelector from './StrategySelector'\nimport Statement from '../Statement/index'\nimport { Labels, Operator } from './typings'\nimport { DEFAULT_LABELS, MEDIUM_ICON_SIZE } from './constants'\nimport { SubjectOptions } from '../Statement/Atoms/SubjectAtom'\n\ntype Props = {\n canDelete?: boolean\n isFullWidth?: boolean\n isRtl?: boolean\n labels?: Labels\n onChangeStatements: (statement: Props['statements']) => void\n onChangeOperator: (operator: Props['operator']) => void\n operator: Operator\n options: SubjectOptions\n hideOperator?: boolean\n statements: {\n subject: string\n verb: string\n object?: unknown\n error?: string\n }[]\n subjectPlaceholder: string\n}\n\nconst Conditions: React.FC<Props> = ({\n canDelete,\n statements,\n options,\n subjectPlaceholder,\n isFullWidth,\n isRtl,\n labels = {} as Props['labels'],\n hideOperator,\n operator,\n onChangeOperator,\n onChangeStatements,\n}) => {\n const objectIsEmpty = object => {\n if (object === undefined) return true\n if (object === null) return true\n if (object === '') return true\n if (Array.isArray(object) && object.length === 0) return true\n return false\n }\n\n const canAddNewCondition = () => {\n if (statements.length === 0) return false\n\n const hasIncompleteCondition = statements.some(\n condition =>\n condition.subject === '' ||\n condition.verb === '' ||\n objectIsEmpty(condition.object)\n )\n return !hasIncompleteCondition\n }\n\n const handleAddNewCondition = () => {\n const emptyStatement = {\n subject: '',\n verb: '',\n object: null,\n }\n\n onChangeStatements([...statements, emptyStatement])\n }\n\n const handleRemoveStatement = index => {\n const updatedStatements = statements\n .slice(0, index)\n .concat(statements.slice(index + 1))\n\n onChangeStatements(updatedStatements)\n }\n\n const handleUpdatestatement = (newStatement, statementIndex) => {\n const newStatements = statements.map((statement, idx) =>\n idx === statementIndex ? newStatement : statement\n )\n onChangeStatements(newStatements)\n }\n\n return (\n <div>\n {!hideOperator && (\n <div className={`mh6 ${isRtl ? 'flex justify-end' : ''}`}>\n <StrategySelector\n isRtl={isRtl}\n operator={operator}\n labels={labels}\n onChangeOperator={operator => onChangeOperator(operator)}\n />\n </div>\n )}\n\n <div className=\"t-body c-on-base ph5 mt4 br3 b--muted-4 ba\">\n {statements.length === 0 ? (\n <div className=\"flex-grow-1 mv6\">\n <Statement\n isRtl={isRtl}\n isFullWidth={isFullWidth}\n onChangeStatement={newStatement =>\n onChangeStatements([newStatement])\n }\n options={options}\n subjectPlaceholder={subjectPlaceholder}\n />\n </div>\n ) : (\n <div className=\"mv5\">\n {statements.map((statement, statementIndex) => {\n // if statement is configured as unique we should filter subject\n // options that were already selected in other statements.\n const uniqueBasedSubjects = Object.keys(options).filter(\n subject =>\n !options[subject].unique ||\n !statements.some(\n (stmt, idx) =>\n stmt.subject === subject && idx !== statementIndex\n )\n )\n\n const uniqueBasedOptions = uniqueBasedSubjects.reduce(\n (uniqueOptions, subject) => ({\n ...uniqueOptions,\n [subject]: options[subject],\n }),\n {}\n )\n\n const statementContent = [\n <div key=\"1\" className=\"flex-grow-1\">\n <Statement\n isRtl={isRtl}\n isFullWidth={isFullWidth}\n onChangeStatement={newStatement => {\n handleUpdatestatement(newStatement, statementIndex)\n }}\n options={uniqueBasedOptions}\n subjectPlaceholder={subjectPlaceholder}\n statement={statement}\n />\n </div>,\n canDelete &&\n (!isFullWidth ? (\n <div\n key=\"2\"\n className=\"ma3 c-muted-2 pointer hover-c-danger\"\n onClick={() => handleRemoveStatement(statementIndex)}>\n <IconClose size={25} />\n </div>\n ) : (\n <div key=\"3\" className=\"tr mh3\">\n <ButtonWithIcon\n variation=\"tertiary\"\n collapseRight\n size=\"small\"\n icon={<IconClose className=\"c-on-action-primary\" />}\n onClick={() => handleRemoveStatement(statementIndex)}\n >\n {labels.delete || DEFAULT_LABELS.delete}\n </ButtonWithIcon>\n </div>\n )),\n ]\n\n return (\n <div\n className=\"flex flex-column w-100 mv3\"\n key={statementIndex}>\n <div\n className={`flex ${\n isFullWidth\n ? 'flex-column items-strech'\n : 'flex-row items-center'\n }`}>\n {isRtl ? statementContent.reverse() : statementContent}\n </div>\n\n {statementIndex !== statements.length - 1 && (\n <Separator\n label={\n operator === 'all'\n ? labels.operatorAnd || DEFAULT_LABELS.operatorAnd\n : labels.operatorOr || DEFAULT_LABELS.operatorOr\n }\n />\n )}\n </div>\n )\n })}\n </div>\n )}\n <Separator />\n <div className={`mv5 mh3 ${isRtl ? 'flex justify-end' : ''}`}>\n <ButtonWithIcon\n variation=\"tertiary\"\n collapseLeft\n size=\"small\"\n icon={<IconPlus solid size={MEDIUM_ICON_SIZE} />}\n iconPosition={isRtl ? 'right' : 'left'}\n disabled={!canAddNewCondition()}\n onClick={handleAddNewCondition}>\n {labels.addNewCondition || DEFAULT_LABELS.addNewCondition}\n </ButtonWithIcon>\n </div>\n </div>\n </div>\n )\n}\n\n// this is so styleguidist can pick the prop types reference\nConditions.propTypes = {\n /** Shows or hides the delete button */\n canDelete: PropTypes.bool,\n /** Wether to show this component stretched to the width */\n isFullWidth: PropTypes.bool,\n /** Whether the order of elements and text if right to left */\n isRtl: PropTypes.bool,\n /** Labels for the controls and texts, default is english */\n labels: PropTypes.shape({\n addNewCondition: PropTypes.string,\n addConditionBtn: PropTypes.string,\n delete: PropTypes.string,\n noConditions: PropTypes.string,\n operatorAll: PropTypes.string,\n operatorAnd: PropTypes.string,\n operatorAny: PropTypes.string,\n operatorOr: PropTypes.string,\n headerPrefix: PropTypes.string,\n headerSufix: PropTypes.string,\n }),\n /** Conditions change callback: array of statement definitions */\n onChangeStatements: PropTypes.func.isRequired,\n /** Operator (any, all) change callback */\n onChangeOperator: PropTypes.func,\n /** Operator indicates whether all the statements should be met or any of them */\n operator: PropTypes.oneOf(['all', 'any']),\n /** Possible options and respective data types, verb options */\n options: PropTypes.any.isRequired,\n /** Show or hide the header that selects the operator (any vs all) */\n hideOperator: PropTypes.bool,\n /** one statement = {subject: string, verb: string, object: unknown, error: string} */\n statements: PropTypes.array,\n /** Placeholder for subject dropdown */\n subjectPlaceholder: PropTypes.string.isRequired,\n}\n\nConditions.defaultProps = {\n operator: 'any',\n hideOperator: false,\n statements: [],\n onChangeOperator: () => {},\n onChangeStatements: () => {},\n labels: {\n addNewCondition: 'add new condition',\n delete: 'Remove',\n headerPrefix: 'Matching',\n headerSufix: 'following conditions:',\n operatorAll: 'all',\n operatorAnd: 'and',\n operatorAny: 'any',\n operatorOr: 'or',\n },\n}\n\nexport default Conditions\n\n```" } ]
code_store-on-localhost_a4e77eb4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/typings.d.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type Labels = {\n addNewCondition?: string\n delete?: string\n operatorAll?: string\n operatorAnd?: string\n operatorAny?: string\n operatorOr?: string\n headerPrefix?: string\n headerSufix?: string\n}\n\nexport type Operator = 'all' | 'any'\n\n```" } ]
code_store-on-localhost_4532db39
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n#### Conditions works like a filter\n\n- Conditions component is based on creating statements.\n\n### Statements\n\n- Statements are composed of 3 basic atoms (subject, verb and object), here are some use cases if you are filtering user data for example:\n\n- Filtering a specific user by name\n\n - subject: User Name\n - verb: is\n - object: John Doe\n\n- Filtering gmail users\n\n - subject: Email\n - verb: contains\n - object: @gmail.com\n\n### ๐Ÿ‘ Dos\n\n- Use clear verbs and subjects, which should be intuitive and provide sufficient context for the user take that decision.\n- Initialize it with a default value that makes sense to your needs. (example: initial render already with an active filter)\n\n### ๐Ÿ‘Ž Don'ts\n\n- Don't use too complex components as objects for a statement. If your statement object is too complex, maybe you should break it in simpler statements options and the complex case can be contemplated by using multiple simpler statements.\n\nSimple\n\n```js\nconst Input = require('../Input').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nclass SimpleConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n email: {\n label: 'Email',\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n canDelete\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ simpleStatements: statements })\n }}\n operator={this.state.operator}\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n />\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\nUnique\n\n```js\nconst Input = require('../Input').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nclass SimpleConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n unique: true,\n },\n surname: {\n label: 'Last name',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n unique: true,\n },\n country: {\n label: 'Country of residence',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n unique: true,\n },\n email: {\n label: 'Email',\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n canDelete\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ simpleStatements: statements })\n }}\n operator={this.state.operator}\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n />\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\nMobile\n\n```js\nconst Input = require('../Input').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nclass SimpleConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n email: {\n label: 'Email',\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n canDelete\n isFullWidth\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ simpleStatements: statements })\n }}\n operator={this.state.operator}\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n />\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\nComplex\n\n```js\nconst DatePicker = require('../DatePicker').default\nconst Dropdown = require('../Dropdown').default\nconst Input = require('../Input').default\nconst Select = require('../EXPERIMENTAL_Select').default\n\nconst possibleColors = [\n { label: 'White', value: 'white' },\n { label: 'Black', value: 'black' },\n { label: 'Grey', value: 'grey' },\n { label: 'Yellow', value: 'yellow' },\n { label: 'Red', value: 'red' },\n { label: 'Blue', value: 'blue' },\n { label: 'Green', value: 'green' },\n { label: 'Brown', value: 'brown' },\n { label: 'Pink', value: 'pink' },\n { label: 'Orange', value: 'orange' },\n { label: 'Purple', value: 'purple' },\n { label: 'Dark-blue', value: 'dark-blue' },\n { label: 'Dark-red', value: 'dark-red' },\n { label: 'Light-blue', value: 'light-blue' },\n]\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nfunction ComplexDropdownObject({ value, onChange }) {\n return (\n <Dropdown\n value={value}\n options={possibleColors}\n onChange={(e, value) => {\n onChange(value)\n }}\n />\n )\n}\n\nfunction ComplexSelectObject({ value, onChange }) {\n return (\n <Select\n multi\n value={value}\n onChange={values => onChange(values)}\n options={possibleColors}\n />\n )\n}\n\nfunction ComplexNumericInputObject({ value, onChange }) {\n return (\n <Input\n min=\"0\"\n onChange={e => onChange(e.target.value.replace(/\\D/g, ''))}\n placeholder=\"Insert age...\"\n type=\"number\"\n value={value || ''}\n />\n )\n}\n\nfunction ComplexNumericInputRangeObject({ value, onChange }) {\n return (\n <div className=\"flex\">\n <Input\n type=\"number\"\n min=\"0\"\n placeholder=\"Age from...\"\n errorMessage={\n value && parseInt(value.first) >= parseInt(value.last)\n ? 'Must be smaller than other input'\n : ''\n }\n value={value && value.first ? value.first : ''}\n onChange={e =>\n onChange({\n ...value,\n first: e.target.value.replace(/\\D/g, ''),\n })\n }\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n type=\"number\"\n min={(value && `${parseInt(value.first) + 1}`) || '0'}\n placeholder=\"Age to...\"\n value={value && value.last ? value.last : ''}\n onChange={e =>\n onChange({\n ...value,\n last: e.target.value.replace(/\\D/g, ''),\n })\n }\n />\n </div>\n )\n}\n\nfunction ComplexDatePickerObject({ value, onChange }) {\n return (\n <DatePicker\n locale=\"en-US\"\n onChange={date => onChange(date)}\n value={value}\n />\n )\n}\n\nfunction ComplexDatePickerRangeObject({ value, onChange }) {\n return (\n <div className=\"flex\">\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n errorMessage={\n value && value.from >= value.to ? 'Must be before end date' : ''\n }\n locale=\"en-US\"\n onChange={date =>\n onChange({\n ...value,\n from: date,\n })\n }\n value={value && value.from}\n />\n </div>\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n locale=\"en-US\"\n onChange={date =>\n onChange({\n ...value,\n to: date,\n })\n }\n value={value && value.to}\n />\n </div>\n </div>\n )\n}\n\nclass ComplexConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n statements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n age: {\n unique: true,\n label: 'User age',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <ComplexNumericInputObject {...props} />,\n },\n {\n label: 'is between',\n value: 'between',\n object: props => <ComplexNumericInputRangeObject {...props} />,\n },\n ],\n },\n color: {\n unique: true,\n label: 'User favorite color',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <ComplexDropdownObject {...props} />,\n },\n {\n label: 'is any of',\n value: 'any',\n object: props => <ComplexSelectObject {...props} />,\n },\n ],\n },\n birthday: {\n unique: true,\n label: 'User birthday',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <ComplexDatePickerObject {...props} />,\n },\n {\n label: 'is between',\n value: 'between',\n object: props => <ComplexDatePickerRangeObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ statements })\n }}\n onChangeOperator={this.handleToggleOperator}\n operator={this.state.operator}\n options={options}\n statements={this.state.statements}\n subjectPlaceholder=\"Select subject\"\n />\n )\n }\n}\n;<ComplexConditionsCase />\n```\n\nGrouped\n\n```js\nconst Input = require('../Input').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nclass GroupedConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\n group: 'Group 1',\n unique: true,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n lastname: {\n label: 'Last name',\n group: 'Group 1',\n unique: true,\n verbs: [\n {\n label: 'is',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n email: {\n label: 'Email',\n group: 'Group 2',\n unique: true,\n verbs: [\n {\n label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n canDelete\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ simpleStatements: statements })\n }}\n operator={this.state.operator}\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n />\n )\n }\n}\n;<GroupedConditionsCase />\n```\n\nRTL example\n\n```js\nconst Input = require('../Input').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nclass SimpleConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n render() {\n const options = {\n name: {\n label: 'ืฉื ืžืฉืชืžืฉ',\n verbs: [\n {\n label: 'ื”ื•ื',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'ืœื',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n email: {\n label: 'ื“ื•ื\"ืœ',\n verbs: [\n {\n label: 'ืžื›ื™ืœ',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'ื”ื•ื',\n value: '=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'ืœื',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n ],\n },\n }\n\n return (\n <Conditions\n canDelete\n isRtl={true}\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n console.log('Changed statements to:', statements)\n this.setState({ simpleStatements: statements })\n }}\n operator={this.state.operator}\n options={options}\n subjectPlaceholder=\"ื‘ื—ืจ ื ื•ืฉื\"\n statements={this.state.simpleStatements}\n labels={{\n headerPrefix: 'ืžื”ืชื ืื™ื ื”ื‘ืื™ื',\n operatorAll: 'ื›ืœ',\n operatorAny: 'ืœื›ืœ ืื—ื“',\n headerSufix: 'ืชื•ืื',\n addNewCondition: 'ื”ื•ืกืฃ ืชื ืื™ ื—ื“ืฉ',\n operatorAnd: 'ื•',\n operatorOr: 'ืื•',\n }}\n />\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\n```" } ]
code_store-on-localhost_93447b4f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/StrategySelector.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport IconCaretDown from '../icon/CaretDown/index.js'\nimport { Labels, Operator } from './typings'\nimport { DEFAULT_LABELS, SMALL_ICON_SIZE } from './constants'\n\ntype Props = {\n isRtl?: boolean\n labels: Pick<\n Labels,\n 'headerPrefix' | 'headerSufix' | 'operatorAll' | 'operatorAny'\n >\n onChangeOperator: (operator: Props['operator']) => void\n operator: Operator\n}\n\nconst StrategySelector: React.FC<Props> = ({\n isRtl,\n operator,\n onChangeOperator,\n labels,\n}) => {\n const handleOperatorChange = event => {\n const newOperator = event.target.value\n if (operator !== newOperator) {\n onChangeOperator(newOperator)\n }\n }\n\n const seletorContent = [\n <span key=\"seletorContent-operator\" className=\"mh3 b\">\n {operator === 'all'\n ? labels.operatorAll || DEFAULT_LABELS.operatorAll\n : labels.operatorAny || DEFAULT_LABELS.operatorAny}\n </span>,\n <select\n key=\"seletorContent-select\"\n className=\"o-0 absolute top-0 left-0 w-100 bottom-0 pointer t-small\"\n onChange={handleOperatorChange}\n value={operator}\n style={{\n // safari select height fix\n WebkitAppearance: 'menulist-button',\n }}>\n <option value=\"all\">\n {labels.operatorAll || DEFAULT_LABELS.operatorAll}\n </option>\n <option value=\"any\">\n {labels.operatorAny || DEFAULT_LABELS.operatorAny}\n </option>\n </select>,\n <IconCaretDown key=\"seletorContent-icon\" size={SMALL_ICON_SIZE} />,\n ]\n\n return (\n <div className=\"flex flex-row nowrap\">\n <span className={isRtl ? 'mr3' : ''}>\n {labels.headerPrefix || DEFAULT_LABELS.headerPrefix}\n </span>\n <div className=\"c-link relative\">\n {isRtl ? seletorContent.reverse() : seletorContent}\n </div>\n <span className={isRtl ? '' : 'ml3'}>\n {labels.headerSufix || DEFAULT_LABELS.headerSufix}\n </span>\n </div>\n )\n}\n\nexport default StrategySelector\n\n```" } ]
code_store-on-localhost_458837de
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/constants.ts from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Labels } from './typings'\n\nexport const DEFAULT_LABELS: Labels = {\n addNewCondition: 'add new condition',\n delete: 'Remove',\n headerPrefix: 'Matching',\n headerSufix: 'following conditions:',\n operatorAll: 'all',\n operatorAnd: 'and',\n operatorAny: 'any',\n operatorOr: 'or',\n}\n\nexport const SMALL_ICON_SIZE = 14\nexport const MEDIUM_ICON_SIZE = 16\n\n```" } ]
code_store-on-localhost_4b482437
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/Conditions/Separator.tsx from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst SEPARATOR_LINE_OPTICAL_COMPENSATION = '32px'\n\ntype Props = {\n label?: string\n}\n\nconst Separator: React.FC<Props> = ({ label }) => {\n return (\n <div\n style={{ width: `calc(100% + ${SEPARATOR_LINE_OPTICAL_COMPENSATION})` }}\n className=\"flex flex-row w-100 nowrap items-center mv3 nl5\">\n <hr className=\"ma0 b--black-10 bb bb-0 w-50\" />\n {label && <span className=\"gray ph3 dib bg-white\">{label}</span>}\n <hr className=\"ma0 b--black-10 bb bb-0 w-50\" />\n </div>\n )\n}\n\nexport default Separator\n\n```" } ]
code_store-on-localhost_a4a977e4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/Gradient.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { CustomPicker } from 'react-color'\nimport { Hue } from 'react-color/lib/components/common'\n\n/**\n * Gradient Component\n */\nclass Gradient extends React.Component {\n render() {\n return (\n <div className=\"gradient-container relative w-100 mv6\">\n <Hue\n {...this.props}\n onChange={this.props.onChange}\n pointer={() => (\n <div\n className=\"pointer-gradient\"\n style={{ background: this.props.hex }}\n />\n )}\n direction=\"horizontal\"\n />\n </div>\n )\n }\n}\n\nGradient.propTypes = {\n /** onChange event */\n onChange: PropTypes.func,\n /** Pointer Hex Color */\n hex: PropTypes.string,\n}\n\nexport default CustomPicker(Gradient)\n\n```" } ]
code_store-on-localhost_bd3afaf3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/ColorOptions.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport Gradient from './Gradient'\nimport Saturation from './Saturation'\nimport Alpha from './Alpha'\nimport RGBInput from './RGBInput'\nimport HSVInput from './HSVInput'\nimport Dropdown from '../Dropdown'\nimport ColorHistory from './ColorHistory'\n\n/** HSV Key to Dropdown */\nconst HSV_INPUT = 'HSV_KEY'\n/** RGB Key to Dropdown */\nconst RGB_INPUT = 'RGB_KEY'\n\n/**\n * ColorOptions Component\n */\nexport default class ColorOptions extends React.Component {\n /** Initial State */\n state = {\n currentInput: RGB_INPUT,\n }\n\n /**\n * Handle input changes\n */\n handleOnChangeInput = e => {\n this.setState({\n currentInput: e.target.value,\n })\n }\n\n /**\n * Render ColorOptions Component\n */\n render() {\n return (\n <div className=\"absolute pa3 w-100 z-5 bg-base options-container br2\">\n <div className=\"mv3 relative items-end flex w-100\">\n <div className=\"w-75\">\n {this.state.currentInput === RGB_INPUT ? (\n <RGBInput\n color={this.props.color.rgba}\n onChange={this.props.onColorChange}\n />\n ) : (\n <HSVInput\n color={this.props.color.hsva}\n onChange={this.props.onColorChange}\n />\n )}\n </div>\n <div className=\"w-25 mb3\">\n <Dropdown\n size=\"small\"\n options={[\n { value: RGB_INPUT, label: 'RGB' },\n { value: HSV_INPUT, label: 'HSV' },\n ]}\n value={this.state.currentInput}\n onChange={this.handleOnChangeInput}\n />\n </div>\n </div>\n <Saturation\n color={this.props.color.rgba}\n onChangeComplete={this.props.onColorChange}\n />\n <Gradient\n color={this.props.color.rgba}\n onChangeComplete={this.props.onColorChange}\n />\n <Alpha\n color={this.props.color.rgba}\n onChangeComplete={this.props.onColorChange}\n />\n <ColorHistory {...this.props} />\n </div>\n )\n }\n}\n\nColorOptions.propTypes = {\n /** Color input */\n color: PropTypes.object.isRequired,\n /** ColorChange event */\n onColorChange: PropTypes.func,\n}\n\n```" } ]
code_store-on-localhost_6b28c9f5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/color-picker.global.css from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n/**\n* ColorPicker\n*/\n\n/** Gradient container style */\n.gradient-container {\n height: 0.25rem;\n}\n\n/** Saturation container style */\n.saturation-container {\n min-height: 12rem;\n}\n\n/** Gradient container inner's div style */\n.gradient-container div {\n border-radius: 0.25rem;\n}\n\n/** Saturation container inner's div style */\n.saturation-container div {\n border-radius: 0.25rem;\n}\n\n/** Default Pointer styles */\n.pointer-gradient, .pointer-saturation {\n border-radius: 1rem !important; \n cursor: pointer;\n transform: translate(-50%, -0.4375rem);\n box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);\n}\n\n/** Gradient Point style */\n.pointer-gradient {\n width: 1rem;\n height: 1rem;\n border: 0.125rem solid #ffffff;\n}\n\n/** Saturation Pointer style */\n.pointer-saturation {\n width: 0.625rem;\n height: 0.625rem;\n border: 0.125rem solid #ffffff;\n}\n\n/** Options Container Style */\n.options-container {\n box-shadow: 0px 4px 8px rgba(15, 54, 102, 0.15);\n min-width: 20rem;\n}\n\n/** Remove input number spinners */\ninput::-webkit-outer-spin-button,\ninput::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}\n```" } ]
code_store-on-localhost_f138bda3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/Saturation.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { CustomPicker } from 'react-color'\nimport { PropTypes } from 'prop-types'\nimport { Saturation } from 'react-color/lib/components/common'\n\n/** SaturationCustom Component */\nclass SaturationCustom extends React.Component {\n render() {\n const { hex } = this.props\n return (\n <div className=\"saturation-container relative w-100\">\n <Saturation\n {...this.props}\n pointer={() => (\n <div className=\"pointer-saturation\" style={{ background: hex }} />\n )}\n />\n </div>\n )\n }\n}\n\nSaturationCustom.propTypes = {\n /** onChenge event */\n onChange: PropTypes.func,\n /** Pointer hex color */\n hex: PropTypes.string,\n}\n\nexport default CustomPicker(SaturationCustom)\n\n```" } ]
code_store-on-localhost_1082e640
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/index.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport OutsideClickHandler from 'react-outside-click-handler'\nimport PropTypes from 'prop-types'\n\nimport colorutil from './colorUtil'\nimport HexInput from './HexInput'\nimport ColorOptions from './ColorOptions'\n\nimport './color-picker.global.css'\n\n/**\n * ColorPicker Component\n */\nclass ColorPicker extends React.Component {\n state = {\n showOptions: false,\n }\n\n validColor() {\n const { rgba, hsva, hex } = this.props.color\n const color = rgba || hsva || hex\n const hsvaAux = color && (hsva || colorutil.any.to.hsv(color))\n const hexAux = color && (hex || colorutil.any.to.hex(color))\n const rgbaAux = color && (rgba || colorutil.any.to.rgb(color))\n\n return {\n rgba: rgbaAux,\n hsva: hsvaAux,\n hex: hexAux,\n }\n }\n\n handleColorChange = color => {\n const { onChange } = this.props\n onChange &&\n onChange({\n rgba: color.rgb || color.rgba,\n hsva: color.hsv || color.hsva,\n hex: color.hex,\n })\n }\n\n handleOutsideClick = () => {\n this.setState({ showOptions: false })\n }\n\n handleShowOptions = () => {\n this.setState({ showOptions: !this.state.showOptions })\n }\n\n render() {\n const { title, disabled } = this.props\n const { rgba, hsva, hex } = this.validColor()\n\n const styleColorBox = {\n backgroundColor: `rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`,\n height: '1.5rem',\n }\n\n return (\n <OutsideClickHandler onOutsideClick={this.handleOutsideClick}>\n <div className=\"relative dib w-100\">\n {title && (\n <div className=\"bb b--muted-4 mb3 t-heading-5 pv5\">{title}</div>\n )}\n <div className=\"flex w-100\">\n <div className=\"w-25 pa1\">\n <div className=\"t-small w-100 c-on-base db mb3\">\n {this.props.label}\n </div>\n <div\n className={`ba bw1 b--muted-4 br2 pa1 ${\n disabled ? '' : 'hover-b--action-primary pointer'\n }`}\n onClick={this.handleShowOptions}>\n <div className=\"br1\" style={styleColorBox} />\n </div>\n </div>\n <div className=\"w-75 pa1\">\n <HexInput\n rgb={rgba}\n onChange={this.handleColorChange}\n disabled={disabled}\n />\n </div>\n </div>\n <div>\n {this.state.showOptions && !disabled && (\n <ColorOptions\n {...this.props}\n color={{ rgba, hex, hsva }}\n onColorChange={this.handleColorChange}\n />\n )}\n </div>\n </div>\n </OutsideClickHandler>\n )\n }\n}\n\n/** Default props values */\nColorPicker.defaultProps = {\n label: 'Default',\n}\n\nColorPicker.propTypes = {\n /** onChange event */\n onChange: PropTypes.func,\n /** Color Label */\n label: PropTypes.string,\n /** ColorPicker Title */\n title: PropTypes.string,\n /** Color format */\n color: PropTypes.shape({\n /** RGBA color format */\n rgba: PropTypes.object,\n /** HSVA color format */\n hsva: PropTypes.object,\n /** HEX color format */\n hex: PropTypes.string,\n }).isRequired,\n /** Color history */\n colorHistory: PropTypes.array.isRequired,\n /** Disable component */\n disabled: PropTypes.bool,\n}\n\nexport default ColorPicker\n\n```" } ]
code_store-on-localhost_391075b5
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/RGBInput.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { PropTypes } from 'prop-types'\n\nimport colorutil from './colorUtil'\nimport Input from '../Input'\n\n/**\n * RGBInput Component\n */\nclass RGBInput extends React.Component {\n getValue = event => {\n const max = Number(event.target.max)\n const min = Number(event.target.min)\n let value = Number(event.target.value)\n\n if (value > max) value = max\n if (value < min) value = min\n\n return value\n }\n handleChange = (event, key) => {\n const value = this.getValue(event)\n\n const rgb = { ...this.props.color, [key]: value }\n const hsv = colorutil.rgb.to.hsv(rgb)\n const hex = colorutil.rgb.to.hex(rgb)\n\n this.props.onChange({\n hsv,\n hex,\n rgb,\n })\n }\n render() {\n return (\n <div className=\"relative flex mv3\">\n <div className=\"ph2 w-25\">\n <Input\n label=\"R\"\n size=\"small\"\n type=\"number\"\n min=\"0\"\n max=\"255\"\n value={this.props.color.r}\n onChange={e => this.handleChange(e, 'r')}\n />\n </div>\n <div className=\"ph2 w-25\">\n <Input\n label=\"G\"\n size=\"small\"\n type=\"number\"\n min=\"0\"\n max=\"255\"\n value={this.props.color.g}\n onChange={e => this.handleChange(e, 'g')}\n />\n </div>\n <div className=\"ph2 w-25\">\n <Input\n label=\"B\"\n size=\"small\"\n type=\"number\"\n min=\"0\"\n max=\"255\"\n value={this.props.color.b}\n onChange={e => this.handleChange(e, 'b')}\n />\n </div>\n <div className=\"ph2 w-25\">\n <Input\n label=\"A\"\n size=\"small\"\n type=\"number\"\n min=\"0\"\n max=\"1\"\n step=\"0.01\"\n value={this.props.color.a}\n onChange={e => this.handleChange(e, 'a')}\n />\n </div>\n </div>\n )\n }\n}\n\nRGBInput.propTypes = {\n /** inChange event */\n onChange: PropTypes.func.isRequired,\n /** Color Input */\n color: PropTypes.object.isRequired,\n}\n\nexport default RGBInput\n\n```" } ]
code_store-on-localhost_ddae1541
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/README.md from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\nColor Picker lets users select a color value using three differenets way: RGBA (Red, green, blue and alpha properties), [HSVA](https://en.wikipedia.org/wiki/HSL_and_HSV) (Hue, saturation, value and alpha properties) or hexadecimal (color code abstraction to rgb values).\n\n### ๐Ÿ‘ Dos\n- Use color picker in cenarios that user needs to choose an specific color value.\n- You can use multiples color picker components, if you need more than one color to be setted.\n\n### ๐Ÿ‘Ž Don'ts\n- Donโ€™t use color picker in cenarios that users must only reference a color name.\n\n#### Simple ColorPicker\n\n```js\nclass ColorPickerExample extends React.Component {\n constructor() {\n super()\n this.state = { color:{ hex: '#141E7A' }, history: [] }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(color) {\n const { history } = this.state\n history.push(color)\n this.setState({\n history,\n color,\n })\n }\n\n render() {\n return (\n <div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.color}\n colorHistory={this.state.history}\n onChange={ this.handleChange }\n />\n </div>\n </div>\n )\n }\n}\n\n;<ColorPickerExample />\n```\n\n#### ColorPicker with Title\n\n```js\nclass ColorPickerExample extends React.Component {\n constructor() {\n super()\n this.state = { color:{ hex: '#141E7A' }, history: [] }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(color) {\n const { history } = this.state\n history.push(color)\n this.setState({\n history\n })\n }\n\n render() {\n return (\n <div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.color}\n title=\"Color Title\"\n colorHistory={this.state.history}\n onChange={ this.handleChange }\n />\n </div>\n </div>\n )\n }\n}\n\n;<ColorPickerExample />\n```\n#### Multiples ColorPickers\n\n```js\nconst black = require('./index.js').COLOR\n\nclass ColorPickerExample extends React.Component {\n constructor() {\n super()\n this.handleChange = this.handleChange.bind(this)\n this.state = {\n colorDefault: { hex: '#141E7A' },\n colorActive: { hex: '#141E7A' },\n colorHover:{ hex: '#141E7A' },\n history: [],\n }\n }\n\n render() {\n return (\n <div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.colorDefault}\n colorHistory={this.state.history}\n onChange={ (color) => this.handleChange(color, 'colorDefault') }\n />\n </div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.colorActive}\n colorLabel=\"Active\"\n colorHistory={this.state.history}\n onChange={ (color) => this.handleChange(color, 'colorActive') }\n />\n </div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.colorHover}\n colorLabel=\"Hover\"\n colorHistory={this.state.history}\n onChange={ (color) => this.handleChange(color, 'colorHover') }\n />\n </div>\n </div>\n )\n }\n\n handleChange(color, picker) {\n const { history } = this.state\n history.push(color)\n this.setState({\n history,\n [picker]: color,\n })\n }\n}\n\n;<ColorPickerExample />\n```\n\n#### ColorPicker Disabled\n\n```js\nclass ColorPickerExample extends React.Component {\n constructor() {\n super()\n this.state = { color:{ hex: '#141E7A' }, history: [] }\n\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(color) {\n const { history } = this.state\n history.push(color)\n this.setState({\n history\n })\n }\n\n render() {\n return (\n <div>\n <div className=\"w-50\">\n <ColorPicker\n color={this.state.color}\n disabled\n colorHistory={this.state.history}\n onChange={ this.handleChange }\n />\n </div>\n </div>\n )\n }\n}\n\n;<ColorPickerExample />\n```\n\n```" } ]
code_store-on-localhost_ecf8b5e2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/colorUtil.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nconst COLOR_CONSTS = {\n RGB_MAX_VALUE: 255,\n}\n\nconst COLOR_FORMAT = {\n HSV: 'hsv',\n RGB: 'rgb',\n HEX: 'hex',\n}\n\n/** Convert RGB to HSV format */\nconst rgbTohsv = rgb => {\n const { r, g, b, a } = rgb\n const rAux = r / COLOR_CONSTS.RGB_MAX_VALUE\n const gAux = g / COLOR_CONSTS.RGB_MAX_VALUE\n const bAux = b / COLOR_CONSTS.RGB_MAX_VALUE\n const cMax = Math.max(rAux, gAux, bAux)\n const cMin = Math.min(rAux, gAux, bAux)\n const theta = cMax - cMin\n\n let h, s\n // Calcule Hue\n if (theta === 0) {\n h = 0\n } else {\n if (cMax === rAux) h = ((gAux - bAux) / theta) % 6\n else if (cMax === gAux) h = (bAux - rAux) / theta + 2\n else h = (rAux - gAux) / theta + 4\n }\n\n h = Math.round(h * 60)\n\n // Calcule Saturation\n if (cMax === 0) {\n s = 0\n } else {\n s = parseFloat((theta / cMax).toFixed(2))\n }\n\n // Calcule Value\n const v = parseFloat(cMax.toFixed(2))\n\n return {\n h,\n s,\n v,\n a,\n }\n}\n\n/** Convert RGB to Hex*/\nconst rgbTohex = rgb => {\n const { r, g, b } = rgb\n let rString = r.toString(16).toUpperCase()\n let gString = g.toString(16).toUpperCase()\n let bString = b.toString(16).toUpperCase()\n\n if (rString.length < 2) {\n rString = `0${rString}`\n }\n\n if (gString.length < 2) {\n gString = `0${gString}`\n }\n\n if (bString.length < 2) {\n bString = `0${bString}`\n }\n\n const hex = `#${rString}${gString}${bString}`\n\n return hex\n}\n\n/** Convert HSV to RGB */\nconst hsvToRgb = hsv => {\n const { h, s, v, a } = hsv\n const c = v * s\n const x = c * (1 - Math.abs(((h / 60) % 2) - 1))\n const m = v - c\n\n let rAux, gAux, bAux\n\n if (h >= 0 && h < 60) {\n rAux = c\n gAux = x\n bAux = 0\n } else if (h >= 60 && h < 120) {\n rAux = x\n gAux = c\n bAux = 0\n } else if (h >= 120 && h < 180) {\n rAux = 0\n gAux = c\n bAux = x\n } else if (h >= 180 && h < 240) {\n rAux = 0\n gAux = x\n bAux = c\n } else if (h >= 240 && h < 300) {\n rAux = x\n gAux = 0\n bAux = c\n } else {\n rAux = c\n gAux = 0\n bAux = x\n }\n\n const r = Math.round((rAux + m) * COLOR_CONSTS.RGB_MAX_VALUE)\n const g = Math.round((gAux + m) * COLOR_CONSTS.RGB_MAX_VALUE)\n const b = Math.round((bAux + m) * COLOR_CONSTS.RGB_MAX_VALUE)\n\n return {\n r,\n g,\n b,\n a,\n }\n}\n\n/** Convert HSV to Hex */\nconst hsvTohex = hsv => {\n const rgb = hsvToRgb(hsv)\n return rgbTohex(rgb)\n}\n\n/** Convert Hex to RGB */\nconst hexTorgb = hex => {\n const r = parseInt(hex.substring(1, 3), 16)\n const g = parseInt(hex.substring(3, 5), 16)\n const b = parseInt(hex.substring(5, 7), 16)\n return {\n r,\n g,\n b,\n a: 1,\n }\n}\n\n/** Convert Hex to HSV */\nconst hexTohsv = hex => {\n const rgb = hexTorgb(hex)\n return rgbTohsv(rgb)\n}\n\nconst validHex = hex => {\n return /(^#[0-9A-F]{6}$)/i.test(hex)\n}\n\n/** Get color format */\nconst colorFormat = color => {\n if (validHex(color)) return COLOR_FORMAT.HEX\n else if ('h' in color && 's' in color && 'v' in color) return COLOR_FORMAT.HSV\n else if ('r' in color && 'g' in color && 'b' in color) return COLOR_FORMAT.RGB\n}\n\n/** Convert Any format suported(RGB, HSV and HEX) to RGB */\nconst anyTorgb = color => {\n const format = colorFormat(color)\n switch (format) {\n case COLOR_FORMAT.HEX:\n return hexTorgb(color)\n case COLOR_FORMAT.HSV:\n return hsvToRgb(color)\n case COLOR_FORMAT.RGB:\n return color\n default:\n return\n }\n}\n\n/** Convert Any format suported(RGB, HSV and HEX) to HSV */\nconst anyTohsv = color => {\n const format = colorFormat(color)\n switch (format) {\n case COLOR_FORMAT.HEX:\n return hexTohsv(color)\n case COLOR_FORMAT.HSV:\n return color\n case COLOR_FORMAT.RGB:\n return rgbTohsv(color)\n default:\n return\n }\n}\n\n/** Convert Any format suported(RGB, HSV and HEX) to HEX */\nconst anyTohex = color => {\n const format = colorFormat(color)\n switch (format) {\n case COLOR_FORMAT.HEX:\n return color\n case COLOR_FORMAT.HSV:\n return hsvTohex(color)\n case COLOR_FORMAT.RGB:\n return rgbTohex(color)\n default:\n return\n }\n}\n\nexport default {\n rgb: {\n to: {\n hsv: rgbTohsv,\n hex: rgbTohex,\n },\n },\n hsv: {\n to: {\n rgb: hsvToRgb,\n hex: hsvTohex,\n },\n },\n hex: {\n to: {\n rgb: hexTorgb,\n hsv: hexTohsv,\n },\n },\n any: {\n to: {\n rgb: anyTorgb,\n hsv: anyTohsv,\n hex: anyTohex,\n },\n },\n validateHex: validHex,\n}\n\n```" } ]
code_store-on-localhost_77003af0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/ColorHistory.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport colorutil from './colorUtil'\n\n/**\n * ColorHistory Component\n */\nclass ColorHistory extends React.Component {\n /**\n * Render sigle color block\n */\n renderColorBlock = colorInput => {\n const { rgba, hsva, hex } = colorInput\n const color = rgba || hsva || hex || '#FFFFFF'\n const colorInRGB = colorutil.any.to.rgb(color)\n const styleColorBox = {\n backgroundColor: `rgba(${colorInRGB.r},${colorInRGB.g},${colorInRGB.b},${colorInRGB.a})`,\n height: '1.5rem',\n }\n const output = {\n rgba: colorInRGB,\n hsva: colorutil.any.to.hsv(color),\n hex: colorutil.any.to.hex(color),\n }\n\n return (\n <div\n onClick={() => this.props.onColorChange(output)}\n className=\"br2 ba b--muted-4 w-100 ma1 hover-b--action-primary pointer\"\n style={styleColorBox}\n />\n )\n }\n\n /**\n * Render a list of color blocks\n */\n renderColorList = colorList => {\n const blocks = []\n const appendColor = color =>\n color\n ? blocks.push(this.renderColorBlock(color))\n : blocks.push(this.renderColorBlock(this.props.defaultColor))\n for (let i = 0; i < this.props.historyLength; i++) {\n appendColor(colorList && colorList[i])\n }\n return blocks\n }\n\n /**\n * Render ColorHistory component\n */\n render() {\n const { colorHistory } = this.props\n return (\n <div className=\"flex\">{this.renderColorList(colorHistory.reverse())}</div>\n )\n }\n}\n\n/**\n * ColorHistory default props\n */\nColorHistory.defaultProps = {\n /** Default historyLength */\n historyLength: 9,\n /** Default color to empty blocks */\n defaultColor: { hex: '#FFFFFF' },\n}\n\n/** ColorHistory Props */\nColorHistory.propTypes = {\n /** Color history list */\n colorHistory: PropTypes.array,\n /** Color history length */\n historyLength: PropTypes.number,\n /** Default color to empty blocks */\n defaultColor: PropTypes.object,\n /** onColorChange event */\n onColorChange: PropTypes.func,\n}\n\nexport default ColorHistory\n\n```" } ]
code_store-on-localhost_11d6fc11
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of store-on-localhost/src/monobloco/components/new/Styleguide/components/ColorPicker/HexInput.js from the store-on-localhost VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport colorutil from './colorUtil'\nimport Input from '../Input'\n\n/** HexInput Component */\nclass HexInput extends React.Component {\n state = {\n inputValue: '#000000',\n error: false,\n }\n handleChange = e => {\n e.preventDefault()\n const inputValue = e.target.value\n this.setState({ inputValue: inputValue })\n if (this.validation(inputValue)) {\n const { onChange } = this.props\n const rgb = colorutil.hex.to.rgb(inputValue)\n const hsv = colorutil.rgb.to.hsv(rgb)\n onChange({\n rgb,\n hsv,\n hex: inputValue,\n })\n }\n }\n validation = color => {\n const validColor = colorutil.validateHex(color)\n this.setState({\n error: !validColor,\n })\n return validColor\n }\n\n componentDidMount() {\n this.updateInputValue()\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.rgb !== this.props.rgb) {\n this.updateInputValue()\n }\n }\n\n updateInputValue() {\n const { rgb } = this.props\n const color = colorutil.rgb.to.hex(rgb)\n this.setState({ inputValue: color })\n }\n\n render() {\n const { disabled, errorMessage } = this.props\n const { error, inputValue } = this.state\n return (\n <div className=\"mb5\">\n <Input\n error={error}\n label=\"Hex\"\n value={inputValue}\n size=\"small\"\n onChange={this.handleChange}\n errorMessage={error && errorMessage}\n disabled={disabled}\n />\n </div>\n )\n }\n}\n\n/** Default props values */\nHexInput.defaultProps = {\n errorMessage: 'Invalid Hex Color',\n disable: false,\n}\n\nHexInput.propTypes = {\n /** onChange event */\n onChange: PropTypes.func,\n /** RGB color input */\n rgb: PropTypes.object,\n /** Erro message */\n errorMessage: PropTypes.string,\n /** Disable component */\n disabled: PropTypes.bool,\n}\n\nexport default HexInput\n\n```" } ]