id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_store-on-localhost_dd49d920
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/PhoneNumber.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport { Validations } from '../utils'\nimport Context from '../context'\nimport PropTypes from 'prop-types'\n\nconst PhoneNumber = ({ children }) => {\n return (\n <Context.Consumer>\n {({ state: { phoneNumber }, handlers: { handlePhoneNumberChange } }) =>\n children({\n value: phoneNumber,\n setValue: handlePhoneNumberChange,\n validation: {\n ...Validations,\n validatePhone: () => true, // compatibility\n },\n })\n }\n </Context.Consumer>\n )\n}\n\nPhoneNumber.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default PhoneNumber\n\n```"
}
] |
code_store-on-localhost_e4afdc5a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/IdentityProviders.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 Context from '../context'\n\nconst shouldShowGoogleLogin = providers =>\n providers &&\n providers.oAuthProviders &&\n providers.oAuthProviders.length > 0 &&\n providers.oAuthProviders.some(idp => idp.providerName === 'Google')\n\nconst IdentityProviders = ({ children }) => (\n <Context.Consumer>\n {({ state: { identityProviders } }) =>\n children({\n value: {\n ...identityProviders,\n googleOAuth: shouldShowGoogleLogin(identityProviders),\n },\n })\n }\n </Context.Consumer>\n)\n\nIdentityProviders.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default IdentityProviders\n\n```"
}
] |
code_store-on-localhost_31aca515
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/UserAccounts.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 Context from '../context'\nimport { Validations } from '../utils'\n\nconst UserAccounts = ({ children }) => (\n <Context.Consumer>\n {({ state: { userAccounts }, handlers: { handleUserAccountsChange } }) =>\n children({\n value: (userAccounts || []).filter(email =>\n Validations.validateEmail(email)\n ),\n setValue: handleUserAccountsChange,\n validation: Validations,\n })\n }\n </Context.Consumer>\n)\n\nUserAccounts.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default UserAccounts\n\n```"
}
] |
code_store-on-localhost_658f5756
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/UserInfo.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport PropTypes from 'prop-types'\nimport { Validations } from '../utils'\nimport Context from '../context'\n\nconst UserInfo = ({ children }) => {\n const {\n state: { userInfo },\n } = useContext(Context)\n return children({\n value: userInfo,\n setValue: () =>\n console.warn('UserInfo Component does not expose a setValue'),\n validation: Validations,\n })\n}\n\nUserInfo.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default UserInfo\n\n```"
}
] |
code_store-on-localhost_6beac9c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/Recaptcha.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 { Validations } from '../utils'\nimport Context from '../context'\n\nconst Recaptcha = ({ children }) => {\n return (\n <Context.Consumer>\n {({ state: { recaptcha }, handlers: { handleRecaptchaChange } }) =>\n children({\n value: recaptcha,\n setValue: handleRecaptchaChange,\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n}\nRecaptcha.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default Recaptcha\n\n```"
}
] |
code_store-on-localhost_d1bc5142
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-components/Email.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 { Validations } from '../utils'\nimport Context from '../context'\n\nconst Email = ({ children }) => {\n return (\n <Context.Consumer>\n {({ state: { email }, handlers: { handleEmailChange } }) =>\n children({\n value: email,\n setValue: handleEmailChange,\n validation: Validations,\n })\n }\n </Context.Consumer>\n )\n}\n\nEmail.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\nexport default Email\n\n```"
}
] |
code_store-on-localhost_85019757
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/usePhoneNumber.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\n\nconst usePhoneNumber = () => {\n const {\n state: { phoneNumber },\n handlers: { handlePhoneNumberChange },\n } = useContext(Context)\n\n return [phoneNumber, handlePhoneNumberChange]\n}\n\nexport default usePhoneNumber\n\n```"
}
] |
code_store-on-localhost_b9f5ddae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/usePassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\n\nconst usePassword = () => {\n const {\n state: { password },\n handlers: { handlePasswordChange },\n } = useContext(Context)\n\n return [password, handlePasswordChange]\n}\n\nexport default usePassword\n\n```"
}
] |
code_store-on-localhost_4b1e4c0e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useToken.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useEffect } from 'react'\nimport Context from '../context'\n\nconst useToken = () => {\n const {\n state: { token },\n handlers: { handleTokenChange },\n } = useContext(Context)\n\n useEffect(() => () => handleTokenChange(''), [handleTokenChange])\n\n return [token, handleTokenChange]\n}\n\nexport default useToken\n\n```"
}
] |
code_store-on-localhost_5c112a66
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useRecaptcha.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\n\nconst useRecaptcha = () => {\n const {\n state: { recaptcha },\n handlers: { handleRecaptchaChange },\n } = useContext(Context)\n\n return [recaptcha, handleRecaptchaChange]\n}\n\nexport default useRecaptcha\n\n```"
}
] |
code_store-on-localhost_3efcb35f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useUserInfo.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\n\nconst UserInfo = () => {\n const {\n state: { userInfo },\n } = useContext(Context)\n\n return userInfo\n}\n\nexport default UserInfo\n\n```"
}
] |
code_store-on-localhost_1b827ab4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useCurrentPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context.js'\n\nconst useCurrentPassword = () => {\n const {\n state: { currentPassword },\n handlers: { handleCurrentPasswordChange },\n } = useContext(Context)\n\n return [currentPassword, handleCurrentPasswordChange]\n}\n\nexport default useCurrentPassword\n\n```"
}
] |
code_store-on-localhost_2bb8d5b7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport { default as useCurrentPassword } from './useCurrentPassword'\nexport { default as useEmail } from './useEmail'\nexport { default as useIdentityProviders } from './useIdentityProviders'\nexport { default as usePassword } from './usePassword'\nexport { default as usePhoneNumber } from './usePhoneNumber'\nexport { default as useRecaptcha } from './useRecaptcha'\nexport { default as useToken } from './useToken'\nexport { default as useUserAccounts } from './useUserAccounts'\nexport { default as useUserInfo } from './useUserInfo'\n\n```"
}
] |
code_store-on-localhost_c3268b94
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useUserAccounts.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\nimport { Validations } from '../utils'\n\nconst useUserAccounts = () => {\n const {\n state: { userAccounts },\n handlers: { handleUserAccountsChange },\n } = useContext(Context)\n\n const emails = (userAccounts || []).filter(email =>\n Validations.validateEmail(email)\n )\n\n return [emails, handleUserAccountsChange]\n}\n\nexport default useUserAccounts\n\n```"
}
] |
code_store-on-localhost_c46294b6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useEmail.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\n\nimport Context from '../context'\n\nconst useEmail = () => {\n const {\n state: { email },\n handlers: { handleEmailChange },\n } = useContext(Context)\n\n return [email, handleEmailChange]\n}\n\nexport default useEmail\n\n```"
}
] |
code_store-on-localhost_fcc47c60
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/state-hooks/useIdentityProviders.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport Context from '../context'\n\nconst shouldShowGoogleLogin = providers =>\n providers &&\n providers.oAuthProviders &&\n providers.oAuthProviders.length > 0 &&\n providers.oAuthProviders.some(idp => idp.providerName === 'Google')\n\nconst useIdentityProviders = () => {\n const {\n state: { identityProviders },\n } = useContext(Context)\n\n const providers = {\n ...identityProviders,\n googleOAuth: shouldShowGoogleLogin(identityProviders),\n }\n return providers\n}\n\nexport default useIdentityProviders\n\n```"
}
] |
code_store-on-localhost_4fa6e60a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useRegisterMfaPhone.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport { Services, Constants, NOOP } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport Context from '../context'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useRegisterMfaPhone = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n useNewSession = false,\n} = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { phoneNumber },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const recaptcha = null\n\n const registerMfaPhoneNumber = useCallback(() => {\n return (useNewSession\n ? Services.withMfaSession(\n () =>\n Services.registerMfaPhoneNumber({\n phoneNumber,\n recaptcha,\n parentAppId,\n }),\n { parentAppId }\n )\n : Services.registerMfaPhoneNumber({\n phoneNumber,\n recaptcha,\n parentAppId,\n })\n )\n .then(({ authStatus }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Pending) {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => {\n onFailure(error)\n })\n })\n })\n }, [\n useNewSession,\n parentAppId,\n phoneNumber,\n setLoading,\n setGlobalLoading,\n onSuccess,\n onFailure,\n ])\n\n const registerMfaPhoneNumberAction = useRefCallback(() => {\n setLoading(true, () => {\n setGlobalLoading(true, () => {\n registerMfaPhoneNumber()\n })\n })\n }, [setLoading, setGlobalLoading, registerMfaPhoneNumber])\n\n return [\n registerMfaPhoneNumberAction,\n {\n state: { phoneNumber },\n loading: loading,\n },\n ]\n}\n\nexport default useRegisterMfaPhone\n\n```"
}
] |
code_store-on-localhost_a1584589
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useLogInWithPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\n\nimport { Services, Constants, NOOP } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useLogInWithPassword = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n onRequiresSmsMfa = NOOP,\n onRequiresAppMfa = NOOP,\n onRequiresPasswordUpdate = NOOP,\n onRequiresMfaRegistration = NOOP,\n useNewSession = false,\n saveUserAccount,\n} = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { email, password, userAccounts, recaptcha, fingerprint },\n handlers: {\n handleRecaptchaChange,\n setGlobalLoading,\n setMfaPhone,\n withSession,\n handleUserAccountsChange,\n handleCurrentPasswordChange,\n handlePasswordChange,\n },\n parentAppId,\n } = useContext(Context)\n\n const validatePassword = useCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n return (useNewSession\n ? withSession(() =>\n Services.validatePassword({\n login: email,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n })\n )\n : Services.validatePassword({\n login: email,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n })\n )\n .then(({ authStatus, phoneNumber }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n if (saveUserAccount && !userAccounts.includes(email)) {\n handleUserAccountsChange([...userAccounts, email])\n }\n return setGlobalLoading(false, onSuccess)\n } else if (authStatus === API_AUTH_STATUS.RequiresMFAAuthenticator) {\n return setGlobalLoading(false, onRequiresAppMfa)\n } else if (authStatus === API_AUTH_STATUS.RequiresPhoneRegistration) {\n return setGlobalLoading(false, onRequiresMfaRegistration)\n } else if (authStatus === API_AUTH_STATUS.RequiresMFA) {\n return setMfaPhone(phoneNumber, onRequiresSmsMfa)\n } else if (authStatus === API_AUTH_STATUS.ExpiredPassword) {\n return setGlobalLoading(false, () => {\n handleCurrentPasswordChange(password)\n handlePasswordChange('')\n onRequiresPasswordUpdate()\n })\n }\n\n return setGlobalLoading(false, () =>\n onFailure(getError({ authStatus }))\n )\n })\n })\n .catch(({ response }) => {\n const error = response && response.data\n\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n }, [\n setLoading,\n setGlobalLoading,\n useNewSession,\n withSession,\n email,\n password,\n recaptcha,\n fingerprint,\n parentAppId,\n saveUserAccount,\n userAccounts,\n onSuccess,\n handleUserAccountsChange,\n onRequiresAppMfa,\n onRequiresMfaRegistration,\n setMfaPhone,\n onRequiresSmsMfa,\n handleCurrentPasswordChange,\n handlePasswordChange,\n onRequiresPasswordUpdate,\n onFailure,\n ])\n\n const validatePasswordAction = useRefCallback(() => {\n handleRecaptchaChange('')\n return validatePassword()\n }, [handleRecaptchaChange, validatePassword])\n\n return [validatePasswordAction, { state: { email, password }, loading }]\n}\n\nexport default useLogInWithPassword\n\n```"
}
] |
code_store-on-localhost_c735b38a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useRegisterMfaAuthenticator.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useContext, useEffect } from 'react'\n\nimport { Services, Constants, NOOP } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useRegisterMfaAuthenticator = ({\n skip = false,\n useNewSession = false,\n onSuccess = NOOP,\n onFailure = NOOP,\n} = {}) => {\n const [loading, setLoading] = useState(false)\n const [error, setError] = useState(null)\n const [data, setData] = useState(null)\n const {\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const startAuthenticatorRegistration = useRefCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n\n const onDone = () => {\n setGlobalLoading(false)\n setLoading(false)\n }\n\n return (useNewSession\n ? Services.withMfaSession(\n () => Services.registerMfaAuthenticator({ parentAppId }),\n {\n parentAppId,\n }\n )\n : Services.registerMfaAuthenticator({ parentAppId })\n )\n .then(data => {\n const { authStatus } = data\n\n if (authStatus !== Constants.ApiAuthStatus.Pending) {\n setError(getError(authStatus))\n onDone()\n return\n }\n\n setLoading(false)\n setError(null)\n setData(data)\n onSuccess(data)\n onDone()\n })\n .catch(error => {\n setLoading(false)\n setError(error)\n setData(null)\n onFailure(getError(error))\n onDone()\n })\n }, [\n setLoading,\n setGlobalLoading,\n useNewSession,\n Services,\n parentAppId,\n Constants,\n setError,\n getError,\n setData,\n onSuccess,\n onFailure,\n ])\n\n useEffect(() => {\n if (!skip) {\n startAuthenticatorRegistration()\n }\n }, [skip, startAuthenticatorRegistration])\n\n return [\n startAuthenticatorRegistration,\n {\n value: data,\n loading,\n error,\n },\n ]\n}\n\nexport default useRegisterMfaAuthenticator\n\n```"
}
] |
code_store-on-localhost_c67e94bc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useLogInWithAccessKey.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport Context from '../context'\nimport { Services, Constants, NOOP } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport getError from '../utils/getError'\nimport useStateWithCallback from '../utils/useStateWithCallback'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useLogInWithAccessKey = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n saveUserAccount,\n disableSetPreference = false,\n} = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { email, token, userAccounts, recaptcha },\n handlers: { setGlobalLoading, handleUserAccountsChange },\n parentAppId,\n } = useContext(Context)\n\n const verifyToken = useCallback(() => {\n return Services.validateToken({\n login: email,\n accesskey: token,\n recaptcha,\n setPreference: !disableSetPreference,\n parentAppId,\n })\n .then(({ authStatus }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n if (saveUserAccount && !userAccounts.includes(email)) {\n handleUserAccountsChange([...userAccounts, email])\n }\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () =>\n onFailure(getError({ authStatus }))\n )\n })\n })\n .catch(errorCode => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(getError(errorCode)))\n })\n })\n }, [\n email,\n token,\n recaptcha,\n disableSetPreference,\n parentAppId,\n setLoading,\n setGlobalLoading,\n saveUserAccount,\n userAccounts,\n onSuccess,\n handleUserAccountsChange,\n onFailure,\n ])\n\n const verifyTokenAction = useRefCallback(() => {\n setLoading(true, () => {\n setGlobalLoading(true, () => {\n return verifyToken()\n })\n })\n }, [setLoading, setGlobalLoading, verifyToken])\n\n return [\n verifyTokenAction,\n {\n state: { email, token },\n loading,\n },\n ]\n}\n\nexport default useLogInWithAccessKey\n\n```"
}
] |
code_store-on-localhost_7723b65a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useReCAPTCHA.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { useRef, useEffect } from 'react'\nimport ReactDOM from 'react-dom'\nimport GoogleRecaptcha from 'react-google-recaptcha'\nimport { NOOP, Constants } from '../utils'\nconst {\n ReCAPTCHA: { SiteKey },\n} = Constants\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useReCAPTCHA = ({ onSuccess = NOOP } = {}) => {\n const recaptchaRef = useRef(null)\n\n const verifyRecaptcha = useRefCallback(() => {\n if (recaptchaRef) {\n recaptchaRef.current.execute()\n }\n }, [recaptchaRef])\n\n useEffect(() => {\n const div = document.createElement('div')\n div.setAttribute('class', 'dn')\n document.body.append(div)\n ReactDOM.render(\n <GoogleRecaptcha\n ref={recaptchaRef}\n sitekey={SiteKey}\n size=\"invisible\"\n badge=\"inline\"\n onChange={onSuccess}\n />,\n div\n )\n return () => div.remove()\n }, [onSuccess, recaptchaRef])\n\n return [verifyRecaptcha]\n}\n\nexport default useReCAPTCHA\n\n```"
}
] |
code_store-on-localhost_f5fc2cda
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useSetPasswordAfterLogin.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport Context from '../context'\nimport { Services, Constants, NOOP } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport useStateWithCallback from '../utils/useStateWithCallback'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useSetPasswordAfterLogin = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n disableSetPreference = false,\n} = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { email, password, scope, account },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const setPassword = useCallback(() => {\n return Services.setPasswordAfterLogin({\n accountName: account,\n scope,\n password,\n setPreference: !disableSetPreference,\n parentAppId,\n })\n .then(({ authStatus } = { authStatus: 'UnexpectedError' }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }, [\n account,\n scope,\n password,\n disableSetPreference,\n parentAppId,\n setLoading,\n setGlobalLoading,\n onSuccess,\n onFailure,\n ])\n\n const setPasswordAction = useRefCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n return setPassword()\n }, [setLoading, setGlobalLoading, setPassword])\n\n return [\n setPasswordAction,\n {\n state: { email, password },\n loading,\n },\n ]\n}\n\nexport default useSetPasswordAfterLogin\n\n```"
}
] |
code_store-on-localhost_8c5457fd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useAuthStateInitializer.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useEffect, useCallback } from 'react'\nimport { useRuntime } from '../../../../../vtex.render-runtime'\nimport { Services, NOOP } from '../utils'\nimport getError from '../utils/getError'\n\nconst useAuthStateInitializer = ({\n scope = 'STORE',\n onSuccess = NOOP,\n onFailure = NOOP,\n skip = false,\n parentAppId = null,\n} = {}) => {\n const [loading, setLoading] = useState(!skip)\n const [data, setData] = useState()\n const [error, setError] = useState()\n const { account } = useRuntime()\n\n const fetchInitialData = useCallback(() => {\n Services.getInitialData({\n accountName: account,\n scopeName: scope,\n parentAppId,\n }).then(\n ({\n identityProviders: {\n oAuthProviders,\n samlProviders,\n passwordAuthentication: password,\n accessKeyAuthentication: accessKey,\n },\n userInfo,\n fingerprint,\n }) => {\n setData({\n identityProviders: {\n oAuthProviders,\n samlProviders,\n password,\n accessKey,\n },\n userInfo,\n fingerprint,\n })\n },\n error => {\n setError(error)\n }\n )\n }, [account, parentAppId, scope])\n\n useEffect(() => {\n !skip && fetchInitialData()\n }, [skip, fetchInitialData])\n\n useEffect(() => {\n if (data) {\n setLoading(false)\n onSuccess(data)\n }\n }, [data, setLoading, onSuccess])\n\n useEffect(() => {\n if (error) {\n setLoading(false)\n onFailure(getError(error))\n }\n }, [error, setLoading, onFailure])\n\n return {\n loading,\n error,\n value: data || {\n identityProviders: null,\n userInfo: null,\n },\n }\n}\n\nexport default useAuthStateInitializer\n\n```"
}
] |
code_store-on-localhost_10fb362d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useRedirectLogout.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { Services } from '../utils'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useRedirectLogout = ({ returnUrl } = {}) => {\n const redirectLogout = useRefCallback(() => {\n Services.redirectLogout({ returnUrl })\n }, [Services, returnUrl])\n\n return [redirectLogout]\n}\n\nexport default useRedirectLogout\n\n```"
}
] |
code_store-on-localhost_b750faa4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useResendMfaToken.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useContext, useCallback } from 'react'\nimport { Services, NOOP } from '../utils'\nimport Context from '../context'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useResendMfaToken = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useStateWithCallback()\n const [error, setError] = useState()\n const {\n state: { phoneNumber },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const recaptcha = null\n\n const resendMfaToken = useCallback(() => {\n return Services.resendMfa({ recaptcha, parentAppId })\n .then(({ authStatus }) => {\n setLoading(false, () => {\n if (authStatus === 'Pending') {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n setError(error)\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }, [\n recaptcha,\n parentAppId,\n setLoading,\n setGlobalLoading,\n onSuccess,\n onFailure,\n setError,\n ])\n\n const resendMfaTokenAction = useRefCallback(() => {\n setLoading(true, () => {\n setGlobalLoading(true, resendMfaToken)\n })\n }, [setLoading, setGlobalLoading, resendMfaToken])\n\n return [\n resendMfaTokenAction,\n {\n state: { phoneNumber },\n loading,\n error,\n },\n ]\n}\n\nexport default useResendMfaToken\n\n```"
}
] |
code_store-on-localhost_37f13486
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useStartLoginSession.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport { Services, NOOP } from '../utils'\nimport Context from '../context'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useStartLoginSession = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { account, returnUrl, scope, email },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const startSession = useCallback(() => {\n return Services.startSession({\n accountName: account,\n returnUrl,\n scope,\n user: email,\n parentAppId,\n })\n .then(() => {\n setLoading(false, () => {\n return setGlobalLoading(false, onSuccess)\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }, [\n account,\n returnUrl,\n scope,\n email,\n parentAppId,\n setLoading,\n setGlobalLoading,\n onSuccess,\n onFailure,\n ])\n\n const startSessionAction = useRefCallback(() => {\n setLoading(true, () => setGlobalLoading(true, startSession))\n }, [setLoading, setGlobalLoading, startSession])\n\n return [\n startSessionAction,\n {\n state: { email },\n loading,\n },\n ]\n}\n\nexport default useStartLoginSession\n\n```"
}
] |
code_store-on-localhost_7052550b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport { default as useGetIdentityProviders } from './useGetIdentityProviders'\nexport { default as useGetLoginPreference } from './useGetLoginPreference'\nexport { default as useLogInWithAccessKey } from './useLogInWithAccessKey'\nexport { default as useLogInWithPassword } from './useLogInWithPassword'\nexport { default as useLogOut } from './useLogOut'\nexport { default as useOAuthPopup } from './useOAuthPopup'\nexport { default as useOAuthRedirect } from './useOAuthRedirect'\nexport { default as useReCAPTCHA } from './useReCAPTCHA'\nexport { default as useRedirectAfterLogin } from './useRedirectAfterLogin'\nexport { default as useRedirectLogout } from './useRedirectLogout'\nexport {\n default as useRegisterMfaAuthenticator,\n} from './useRegisterMfaAuthenticator'\nexport { default as useRegisterMfaPhone } from './useRegisterMfaPhone'\nexport { default as useResendMfaToken } from './useResendMfaToken'\nexport { default as useSendAccessKey } from './useSendAccessKey'\nexport { default as useSetPassword } from './useSetPassword'\nexport { default as useSetPasswordAfterLogin } from './useSetPasswordAfterLogin'\nexport { default as useStartLoginSession } from './useStartLoginSession'\nexport { default as useValidateMfa } from './useValidateMfa'\n\n```"
}
] |
code_store-on-localhost_4f317d49
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useLogOut.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { Services, NOOP } from '../utils'\nimport { useContext, useCallback } from 'react'\nimport Context from '../context'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useLogOut = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const logOut = useCallback(() => {\n return Services.logout({ parentAppId })\n .then(() => {\n setLoading(false, () => {\n return setGlobalLoading(false, onSuccess)\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(error))\n })\n })\n }, [parentAppId, setLoading, setGlobalLoading, onSuccess, onFailure])\n\n const logOutAction = useRefCallback(() => {\n setLoading(true, () => {\n setGlobalLoading(true, logOut)\n })\n }, [setLoading, setGlobalLoading, logOut])\n\n return [\n logOutAction,\n {\n loading,\n },\n ]\n}\n\nexport default useLogOut\n\n```"
}
] |
code_store-on-localhost_968d9531
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useSendAccessKey.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport { Services, NOOP } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useSendAccessKey = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n useNewSession = false,\n} = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { email, token, recaptcha, locale },\n handlers: { setGlobalLoading, withSession },\n parentAppId,\n } = useContext(Context)\n\n const sendToken = useCallback(\n async ({\n email: specificEmail,\n preference,\n recaptcha: specificRecaptcha,\n }) => {\n const user = {\n email: specificEmail || email,\n ...(preference && { preference }),\n }\n const specifiedRecaptcha = specificRecaptcha || recaptcha\n setLoading(true)\n setGlobalLoading(true)\n return (useNewSession\n ? withSession(() =>\n Services.sendVerificationCode({\n email: user.email,\n locale,\n recaptcha: specifiedRecaptcha,\n parentAppId,\n })\n )\n : Services.sendVerificationCode({\n email: user.email,\n locale,\n recaptcha: specifiedRecaptcha,\n parentAppId,\n })\n )\n .then(() => {\n setLoading(false, () => {\n return setGlobalLoading(false, () => onSuccess(user))\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n },\n [\n email,\n recaptcha,\n setLoading,\n setGlobalLoading,\n useNewSession,\n withSession,\n locale,\n parentAppId,\n onSuccess,\n onFailure,\n ]\n )\n\n const sendTokenAction = useRefCallback(\n ({ email, preference, recaptcha } = {}) => {\n sendToken({\n email,\n preference,\n recaptcha,\n })\n },\n [sendToken]\n )\n\n return [\n sendTokenAction,\n {\n state: {\n email,\n token,\n recaptcha,\n },\n loading,\n },\n ]\n}\n\nexport default useSendAccessKey\n\n```"
}
] |
code_store-on-localhost_e45b5897
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useRedirectAfterLogin.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useContext } from 'react'\nimport { Services } from '../utils'\nimport Context from '../context'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useRedirectAfterLogin = ({ autorun } = {}) => {\n const {\n state: { returnUrl },\n } = useContext(Context)\n\n const redirect = useRefCallback(() => Services.redirect({ returnUrl }), [\n Services,\n returnUrl,\n ])\n\n useEffect(() => {\n autorun && redirect()\n }, [autorun, redirect])\n\n return [redirect]\n}\n\nexport default useRedirectAfterLogin\n\n```"
}
] |
code_store-on-localhost_215f4251
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useOAuthRedirect.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useState, useContext } from 'react'\nimport { Services, NOOP } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useOAuthRedirect = ({\n provider,\n onSuccess = NOOP,\n onFailure = NOOP,\n autorun = false,\n useNewSession = false,\n} = {}) => {\n const [loading, setLoading] = useState(false)\n const {\n handlers: { setGlobalLoading, withSession },\n } = useContext(Context)\n\n const startSessionAndRedirect = useRefCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n\n const onDone = () => {\n setLoading(false)\n setGlobalLoading(false)\n }\n\n const start = useNewSession\n ? withSession(() => Services.redirectOAuth({ provider }))\n : Services.redirectOAuth({ provider })\n\n start\n .then(() => {\n onSuccess()\n onDone()\n })\n .catch(error => {\n onFailure(getError(error))\n onDone()\n })\n }, [\n setLoading,\n setGlobalLoading,\n useNewSession,\n withSession,\n Services,\n provider,\n onSuccess,\n onFailure,\n getError,\n ])\n\n useEffect(() => {\n autorun && startSessionAndRedirect()\n }, [autorun, startSessionAndRedirect])\n\n return [startSessionAndRedirect, { loading }]\n}\n\nexport default useOAuthRedirect\n\n```"
}
] |
code_store-on-localhost_9a015630
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useGetIdentityProviders.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useEffect, useContext } from 'react'\nimport { useRuntime } from '../../../../../vtex.render-runtime'\n\nimport { Services, NOOP } from '../utils'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\n\nimport Context from '../context'\n\nconst useGetIdentityProviders = ({\n onSuccess = NOOP,\n onFailure = NOOP,\n skip = false,\n} = {}) => {\n const [loading, setLoading] = useState(!skip)\n const [providers, setProviders] = useState()\n const [error, setError] = useState()\n const { account } = useRuntime()\n const {\n parentAppId,\n state: { scope },\n } = useContext(Context)\n\n const fetchIdentityProviders = useRefCallback(() => {\n Services.getIdentityProviders({\n accountName: account,\n scopeName: scope,\n parentAppId,\n }).then(\n ({\n oAuthProviders,\n samlProviders,\n passwordAuthentication: password,\n accessKeyAuthentication: accessKey,\n }) => {\n setProviders({\n oAuthProviders,\n samlProviders,\n password,\n accessKey,\n })\n },\n error => {\n setError(error)\n onFailure(getError(error))\n }\n )\n }, [Services, account, scope, setProviders, setError, onFailure, getError])\n\n useEffect(() => {\n !skip && fetchIdentityProviders()\n }, [skip, fetchIdentityProviders])\n\n useEffect(() => {\n if (providers) {\n setLoading(false)\n onSuccess()\n }\n }, [providers, setLoading, onSuccess])\n\n return [\n fetchIdentityProviders,\n {\n loading,\n error,\n value: providers,\n },\n ]\n}\n\nexport default useGetIdentityProviders\n\n```"
}
] |
code_store-on-localhost_1312017c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useValidateMfa.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback, useEffect } from 'react'\nimport { Services, Constants, NOOP } from '../utils'\nimport getError from '../utils/getError'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport Context from '../context'\nimport useStateWithCallback from '../utils/useStateWithCallback'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst useValidateMfa = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { token },\n handlers: { setGlobalLoading, handleTokenChange },\n parentAppId,\n } = useContext(Context)\n\n const validateMfa = useCallback(() => {\n return Services.validateMfa({ mfaToken: token, parentAppId })\n .then(({ authStatus }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n setGlobalLoading(false, onSuccess)\n return\n }\n setGlobalLoading(false, () => onFailure(getError({ authStatus })))\n })\n })\n .catch(errorCode => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(getError(errorCode)))\n })\n })\n }, [token, parentAppId, setLoading, setGlobalLoading, onSuccess, onFailure])\n\n const validateMfaAction = useRefCallback(() => {\n setLoading(true, () => {\n setGlobalLoading(true, validateMfa)\n })\n }, [setLoading, setGlobalLoading, validateMfa])\n\n useEffect(() => {\n return () => handleTokenChange('')\n }, [handleTokenChange])\n\n return [\n validateMfaAction,\n {\n state: { token },\n loading,\n },\n ]\n}\n\nexport default useValidateMfa\n\n```"
}
] |
code_store-on-localhost_a1895dd9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useSetPassword.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext, useCallback } from 'react'\nimport { Services, Constants, NOOP } from '../utils'\nconst { ApiAuthStatus: API_AUTH_STATUS } = Constants\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\nimport useStateWithCallback from '../utils/useStateWithCallback'\n\nconst useSetPassword = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useStateWithCallback(false)\n const {\n state: { email, password, currentPassword, token },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const recaptcha = null\n\n const setPassword = useCallback(() => {\n return Services.setPassword({\n login: email,\n newPassword: password,\n currentPassword,\n accesskey: token,\n recaptcha,\n parentAppId,\n })\n .then(({ authStatus } = { authStatus: 'UnexpectedError' }) => {\n setLoading(false, () => {\n if (authStatus === API_AUTH_STATUS.Success) {\n return setGlobalLoading(false, onSuccess)\n }\n return setGlobalLoading(false, () => onFailure({ authStatus }))\n })\n })\n .catch(error => {\n setLoading(false, () => {\n setGlobalLoading(false, () => onFailure(getError(error)))\n })\n })\n }, [\n email,\n password,\n currentPassword,\n token,\n parentAppId,\n setLoading,\n setGlobalLoading,\n onSuccess,\n onFailure,\n ])\n\n const setPasswordAction = useRefCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n return setPassword()\n }, [setLoading, setGlobalLoading, setPassword])\n\n return [\n setPasswordAction,\n {\n state: { email, password, currentPassword, token },\n loading,\n },\n ]\n}\n\nexport default useSetPassword\n\n```"
}
] |
code_store-on-localhost_bc4a7019
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useGetLoginPreference.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useState, useEffect, useContext } from 'react'\n\nimport Context from '../context'\nimport { Services, NOOP } from '../utils'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\n\nconst preferenceByKey = {\n NoPreference: 'NO_PREFERENCE',\n Password: 'PASSWORD',\n AccessKey: 'TOKEN',\n}\n\nconst useGetLoginPreference = ({ onSuccess = NOOP, onFailure = NOOP } = {}) => {\n const [loading, setLoading] = useState(true)\n const [loginPreference, setLoginPreference] = useState()\n const [error, setError] = useState()\n const {\n state: { email, scope, account },\n parentAppId,\n } = useContext(Context)\n\n const fetchLoginPreference = useRefCallback(\n (givenEmail = email) => {\n Services.getLoginPreference({\n accountName: account,\n scopeName: scope,\n email: givenEmail,\n parentAppId,\n })\n .then(data => {\n setLoginPreference(preferenceByKey[data])\n })\n .then(setLoginPreference, error => {\n setError(error)\n onFailure(getError(error))\n })\n },\n [\n Services,\n account,\n scope,\n parentAppId,\n setLoginPreference,\n preferenceByKey,\n setError,\n onFailure,\n getError,\n ]\n )\n\n useEffect(() => {\n if (loginPreference) {\n setLoading(false)\n onSuccess(loginPreference)\n }\n }, [loginPreference, setLoading, onSuccess])\n\n return [\n fetchLoginPreference,\n {\n loading,\n error,\n value: loginPreference,\n },\n ]\n}\n\nexport default useGetLoginPreference\n\n```"
}
] |
code_store-on-localhost_ca0fb388
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/service-hooks/useOAuthPopup.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useEffect, useState, useContext, useCallback } from 'react'\nimport { Services, NOOP } from '../utils'\nimport Context from '../context'\nimport getError from '../utils/getError'\nimport useRefCallback from '../utils/useRefCallback'\n\nfunction openWindow(url, title) {\n const newWindow = window.open(\n url,\n title,\n 'toolbar=no, location=no, directories=no, status=no, copyhistory=no, menubar=no,width=800,height=600,scrollbars=yes'\n )\n if (window.focus) newWindow.focus()\n return newWindow\n}\n\nconst useOAuthPopup = ({\n provider,\n onSuccess = NOOP,\n onFailure = NOOP,\n autorun = false,\n useNewSession = false,\n} = {}) => {\n const [loading, setLoading] = useState(false)\n const {\n state: { account, returnUrl, scope, email, fingerprint },\n handlers: { setGlobalLoading },\n parentAppId,\n } = useContext(Context)\n\n const onDone = useCallback(() => {\n setLoading(false)\n setGlobalLoading(false)\n }, [setGlobalLoading])\n\n const openPopup = useRefCallback(() => {\n setLoading(true)\n setGlobalLoading(true)\n\n const getOAuthRedirectUrl = useNewSession\n ? Services.withSession({\n accountName: account,\n returnUrl,\n scope,\n user: email,\n fingerprint,\n parentAppId,\n useOAuthPopup: true,\n })(() => Services.getOAuthRedirectUrl({ provider }))\n : Services.getOAuthRedirectUrl({ provider })\n\n const popup = openWindow('', provider)\n popup.opener = null\n getOAuthRedirectUrl\n .then(({ url }) => {\n popup.location.assign(url)\n\n const id = setInterval(() => {\n if (!popup || popup.closed) {\n onFailure(getError({ message: 'OAuth popup window closed' }))\n onDone()\n clearInterval(id)\n return\n }\n try {\n if (popup.location.href.indexOf(window.location.host) !== -1) {\n const qs = new URLSearchParams(popup.location.search)\n const authStatus = qs.get('authStatus')\n if (authStatus === 'Success') {\n popup.close()\n onDone()\n onSuccess()\n }\n clearInterval(id)\n }\n // eslint-disable-next-line\n } catch {}\n }, 500)\n })\n .catch(error => {\n popup.close()\n onFailure(getError(error))\n onDone()\n })\n }, [\n setGlobalLoading,\n useNewSession,\n account,\n returnUrl,\n scope,\n email,\n fingerprint,\n parentAppId,\n provider,\n onFailure,\n onSuccess,\n onDone,\n ])\n\n useEffect(() => {\n autorun && openPopup()\n }, [autorun, openPopup])\n\n return [openPopup, { loading }]\n}\n\nexport default useOAuthPopup\n\n```"
}
] |
code_store-on-localhost_7d5dc41b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/UnexpectedError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport StandardError from './StandardError'\n\nclass UnknownError extends StandardError {\n constructor(details) {\n super(\n 'An unexpected error occurred in the client or the server.',\n 'UnexpectedError',\n details\n )\n }\n}\n\nexport default UnknownError\n\n```"
}
] |
code_store-on-localhost_956a6b48
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/StandardError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nclass StandardError extends Error {\n constructor(message, code, details) {\n super(message)\n this.code = code\n if (details) {\n this.details = details\n }\n }\n}\n\nexport default StandardError\n\n```"
}
] |
code_store-on-localhost_521d19c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/BlockedUserError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport StandardError from './StandardError'\n\nclass BlockedUserError extends StandardError {\n constructor(details) {\n super(\n 'Too many login attempts. Send recaptcha to continue.',\n 'BlockedUser',\n details\n )\n }\n}\n\nexport default BlockedUserError\n\n```"
}
] |
code_store-on-localhost_45f66f7a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport NetworkError from './NetworkError'\nimport UnexpectedError from './UnexpectedError'\nimport BlockedUserError from './BlockedUserError'\nimport WrongCredentialsError from './WrongCredentials'\nimport InvalidRecaptchaError from './InvalidRecaptchaError'\n\nexport {\n NetworkError,\n UnexpectedError,\n BlockedUserError,\n WrongCredentialsError,\n InvalidRecaptchaError,\n}\n\n```"
}
] |
code_store-on-localhost_e471dfc8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/NetworkError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport StandardError from './StandardError'\n\nclass NetworkError extends StandardError {\n constructor(details) {\n super(\n \"The app couldn't reach the internet. It may be offline.\",\n 'NetworkError',\n details\n )\n }\n}\n\nexport default NetworkError\n\n```"
}
] |
code_store-on-localhost_f791a178
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/WrongCredentials.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport StandardError from './StandardError'\n\nclass WrongCredentialsError extends StandardError {\n constructor(details) {\n super('Password or token entered is incorrect', 'WrongCredentials', details)\n }\n}\n\nexport default WrongCredentialsError\n\n```"
}
] |
code_store-on-localhost_2d5519ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/VtexId/errors/InvalidRecaptchaError.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport StandardError from './StandardError'\n\nclass InvalidRecaptchaError extends StandardError {\n constructor(details) {\n super(\n 'The current recaptcha value is invalid.',\n 'InvalidRecaptcha',\n details\n )\n }\n}\n\nexport default InvalidRecaptchaError\n\n```"
}
] |
code_store-on-localhost_def8662f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/docs/Pathline.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 copy from 'clipboard-copy'\nimport { MdContentCopy } from 'react-icons/md'\nimport ToolbarButton from 'rsg-components/ToolbarButton'\nimport Styled from 'rsg-components/Styled'\n\nexport const styles = ({ space, fontFamily, fontSize, color }) => ({\n pathline: {\n fontFamily: fontFamily.monospace,\n fontSize: fontSize.small,\n color: color.light,\n wordBreak: 'break-all',\n },\n copyButton: {\n marginLeft: space[0],\n },\n})\n\nexport function PathlineRenderer({ classes, children }) {\n const npmString = `import ${children.componentName} from '@vtex/styleguide/lib/${children.dir}'`\n const vtexIOString = `import { ${children.componentName} } from 'vtex.styleguide'`\n\n return (\n <div className={classes.pathline}>\n <small>\n <strong>VTEX IO</strong>\n </small>\n <br />\n {vtexIOString}\n <ToolbarButton\n small\n className={classes.copyButton}\n onClick={() => copy(vtexIOString)}\n title=\"Copy to clipboard\">\n <MdContentCopy />\n </ToolbarButton>\n\n <br />\n <br />\n <small>\n <strong>npm</strong>\n </small>\n <br />\n {npmString}\n <ToolbarButton\n small\n className={classes.copyButton}\n onClick={() => copy(npmString)}\n title=\"Copy to clipboard\">\n <MdContentCopy />\n </ToolbarButton>\n </div>\n )\n}\n\nPathlineRenderer.propTypes = {\n classes: PropTypes.object.isRequired,\n children: PropTypes.object,\n}\n\nexport default Styled(styles)(PathlineRenderer)\n\n```"
}
] |
code_store-on-localhost_66e94565
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/docs/UsageTabButton.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nconst UsageTabButton = () => {\n return null\n}\n\nUsageTabButton.propTypes = {\n onClick: PropTypes.func.isRequired,\n name: PropTypes.string.isRequired,\n props: PropTypes.shape({\n props: PropTypes.array,\n methods: PropTypes.array,\n }).isRequired,\n active: PropTypes.bool,\n}\n\nexport default UsageTabButton\n\n```"
}
] |
code_store-on-localhost_cf52027c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/docs/CodeTabButton.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 TabButton from 'rsg-components/TabButton'\nimport { MdCode } from 'react-icons/md'\n\nconst CodeTabButton = props => (\n <TabButton {...props}>\n <MdCode /> {props.active ? 'Hide code' : 'Show code'}\n </TabButton>\n)\n\nCodeTabButton.propTypes = {\n onClick: PropTypes.func.isRequired,\n name: PropTypes.string.isRequired,\n active: PropTypes.bool,\n}\n\nexport default CodeTabButton\n\n```"
}
] |
code_store-on-localhost_2eb98df4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/docs/HeadingRenderer.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 styles = {\n h1: 'near-black f1 fw1 mt9 mb8 lh-title',\n h2: 'near-black f1 fw8 mt8 mb3 lh-title',\n h3: 'near-black f5 fw6 mt7 mb2 ttu lh-title',\n h4: 'near-black f3 fw4 mt3 mb2 lh-copy',\n h5: 'near-black f5 fw5 mv2',\n h6: 'near-black f6 fw5 mv1',\n}\n\nfunction HeadingRenderer({ level, children, ...props }) {\n const Tag = `h${level}`\n const headingClasses = styles[Tag]\n\n return (\n <Tag {...props} className={headingClasses}>\n {children}\n </Tag>\n )\n}\n\nHeadingRenderer.propTypes = {\n classes: PropTypes.object,\n level: PropTypes.oneOf([1, 2, 3, 4, 5, 6]).isRequired,\n children: PropTypes.node,\n}\n\nexport default HeadingRenderer\n\n```"
}
] |
code_store-on-localhost_c28aa801
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport { default as ActionMenu } from './ActionMenu'\nexport { default as Alert } from './Alert'\nexport { default as AutocompleteInput } from './AutocompleteInput'\nexport { default as BarChart } from './EXPERIMENTAL_Charts/BarChart'\nexport { default as Box } from './Box'\nexport { default as BubbleChart } from './EXPERIMENTAL_Charts/BubbleChart'\nexport { default as Button } from './Button'\nexport { default as ButtonGroup } from './ButtonGroup'\nexport { default as ButtonPlain } from './ButtonPlain'\nexport { default as ButtonWithIcon } from './ButtonWithIcon'\nexport { default as Card } from './Card'\nexport { default as Checkbox } from './Checkbox'\nexport { default as CheckboxGroup } from './CheckboxGroup'\nexport { default as Collapsible } from './Collapsible'\nexport { default as ColorPicker } from './ColorPicker'\nexport { default as Conditions } from './Conditions'\nexport { default as DatePicker } from './DatePicker'\nexport { default as Divider } from './Divider'\nexport { default as Dropdown } from './Dropdown'\nexport { default as Dropzone } from './Dropzone'\nexport { default as EmptyState } from './EmptyState'\nexport { default as EXPERIMENTAL_Conditions } from './EXPERIMENTAL_Conditions'\nexport { default as EXPERIMENTAL_Select } from './EXPERIMENTAL_Select'\nexport { default as EXPERIMENTAL_Table } from './EXPERIMENTAL_Table'\nexport { default as EXPERIMENTAL_TableTree } from './EXPERIMENTAL_TableTree'\nexport { default as EXPERIMENTAL_useCheckboxTree } from './EXPERIMENTAL_useCheckboxTree'\nexport { default as EXPERIMENTAL_useTableMeasures } from './EXPERIMENTAL_Table/hooks/useTableMeasures'\nexport { default as EXPERIMENTAL_useTableProportion } from './EXPERIMENTAL_Table/hooks/useTableProportion'\nexport { default as EXPERIMENTAL_useTableSort } from './EXPERIMENTAL_Table/hooks/useTableSort'\nexport { default as EXPERIMENTAL_useTableVisibility } from './EXPERIMENTAL_Table/hooks/useTableVisibility'\nexport { default as FilterBar } from './FilterBar'\nexport { default as FilterOptions } from './FilterOptions'\nexport { default as FloatingActionBar } from './FloatingActionBar'\nexport { default as IconArrowBack } from './icon/ArrowBack'\nexport { default as IconArrowDown } from './icon/ArrowDown'\nexport { default as IconArrowUp } from './icon/ArrowUp'\nexport { default as IconBars } from './icon/Bars'\nexport { default as IconBold } from './icon/Bold'\nexport { default as IconCalendar } from './icon/Calendar'\nexport { default as IconCaretDown } from './icon/CaretDown'\nexport { default as IconCaretLeft } from './icon/CaretLeft'\nexport { default as IconCaretRight } from './icon/CaretRight'\nexport { default as IconCaretUp } from './icon/CaretUp'\nexport { default as IconCheck } from './icon/Check'\nexport { default as IconCheckPartial } from './icon/CheckPartial' // not a render entrypoint\nexport { default as IconClear } from './icon/Clear'\nexport { default as IconClock } from './icon/Clock'\nexport { default as IconClose } from './icon/Close'\nexport { default as IconCog } from './icon/Cog'\nexport { default as IconColumns } from './icon/Columns'\nexport { default as IconCopy } from './icon/Copy'\nexport { default as IconDelete } from './icon/Delete'\nexport { default as IconDensity } from './icon/Density'\nexport { default as IconDeny } from './icon/Deny'\nexport { default as IconDownload } from './icon/Download'\nexport { default as IconEdit } from './icon/Edit'\nexport { default as IconExternalLink } from './icon/ExternalLink'\nexport { default as IconExternalLinkMini } from './icon/ExternalLinkMini'\nexport { default as IconFailure } from './icon/Failure'\nexport { default as IconFilter } from './icon/Filter'\nexport { default as IconGrid } from './icon/Grid'\nexport { default as IconHelp } from './icon/Help'\nexport { default as IconImage } from './icon/Image'\nexport { default as IconInfo } from './icon/Info'\nexport { default as IconInlineGrid } from './icon/InlineGrid'\nexport { default as IconItalic } from './icon/Italic'\nexport { default as IconLink } from './icon/Link'\nexport { default as IconMinus } from './icon/Minus'\nexport { default as IconOptionsDots } from './icon/OptionsDots'\nexport { default as IconOrderedList } from './icon/OrderedList'\nexport { default as IconPlus } from './icon/Plus'\nexport { default as IconPlusLines } from './icon/PlusLines'\nexport { default as IconPrinter } from './icon/Printer'\nexport { default as IconSave } from './icon/Save'\nexport { default as IconSearch } from './icon/Search'\nexport { default as IconShoppingCart } from './icon/ShoppingCart'\nexport { default as IconSuccess } from './icon/Success'\nexport { default as IconTableFilter } from './icon/TableFilter'\nexport { default as IconText } from './icon/Text'\nexport { default as IconUnderline } from './icon/Underline'\nexport { default as IconUnorderedList } from './icon/UnorderedList'\nexport { default as IconUpload } from './icon/Upload'\nexport { default as IconUser } from './icon/User'\nexport { default as IconVisibilityOff } from './icon/VisibilityOff'\nexport { default as IconVisibilityOn } from './icon/VisibilityOn'\nexport { default as IconWarning } from './icon/Warning'\nexport { default as Input } from './Input'\nexport { default as InputButton } from './InputButton'\nexport { default as InputCurrency } from './InputCurrency'\nexport { default as InputPassword } from './InputPassword'\nexport { default as InputSearch } from './InputSearch'\nexport { default as Layout } from './Layout'\nexport { default as LineChart } from './EXPERIMENTAL_Charts/LineChart'\nexport { default as Link } from './Link'\nexport { default as Menu } from './Menu'\nexport { default as Modal } from './Modal'\nexport { default as ModalDialog } from './ModalDialog'\nexport { default as MultiSelect } from './MultiSelect'\nexport { default as NumericStepper } from './NumericStepper'\nexport { default as PageBlock } from './PageBlock'\nexport { default as PageHeader } from './PageHeader'\nexport { default as Pagination } from './Pagination'\nexport { default as PasswordInput } from './PasswordInput'\nexport { default as Progress } from './Progress'\nexport { default as ProgressBar } from './ProgressBar'\nexport { default as Radio } from './Radio'\nexport { default as RadioGroup } from './RadioGroup'\nexport { default as ScatterChart } from './EXPERIMENTAL_Charts/ScatterChart'\nexport { default as SelectableCard } from './SelectableCard'\nexport { default as Slider } from './Slider'\nexport { default as Spinner } from './Spinner'\nexport { default as Tab } from './Tab'\nexport { default as Table } from './Table'\nexport { default as Tabs } from './Tabs'\nexport { default as Tag } from './Tag'\nexport { default as Textarea } from './Textarea'\nexport { default as TimePicker } from './TimePicker'\nexport { default as Toggle } from './Toggle'\nexport { default as Tooltip } from './Tooltip'\nexport { default as Totalizer } from './Totalizer'\nexport {\n ToastContext,\n ToastConsumer,\n ToastProvider,\n withToast,\n} from './ToastProvider'\n\n```"
}
] |
code_store-on-localhost_e60919e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/modules/deprecated.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/**\n * This module helps warning deprecated Components or props\n * API props:\n * deprecated({\n * useNewComponent: {\n * old: OldComponentName\n * new: NewComponentName,\n * },\n * useNewProps: {\n * OldPropName: NewPropName,\n * OtherOldPropName: OtherNewPropName,\n * },\n * })(Component)\n **/\nimport React, { Component } from 'react'\n\n// Attempt to get the wrapped component's name\nconst getComponentName = target => {\n if (target.displayName && typeof target.displayName === 'string') {\n return target.displayName\n }\n\n return target.name || 'Unamed component'\n}\n\nconst mapNewProps = (propsMap, props) => {\n const newProps = {}\n Object.keys(propsMap).map(deprecatedProp => {\n if (props[deprecatedProp]) {\n newProps[propsMap[deprecatedProp]] = props[deprecatedProp]\n }\n })\n return {\n ...props,\n ...newProps,\n }\n}\n\nexport default function deprecated({ useNewComponent, useNewProps }) {\n return WrappedComponent =>\n class Deprecated extends Component {\n componentDidMount() {\n if (useNewComponent) {\n console.warn(\n `\"${useNewComponent.old}\" component is deprecated, you should use \"${useNewComponent.new}\" instead`\n )\n }\n if (useNewProps) {\n Object.keys(useNewProps).map(deprecatedProp => {\n if (this.props[deprecatedProp]) {\n console.warn(\n `\"${getComponentName(\n WrappedComponent\n )}\" prop \"${deprecatedProp}\" is deprecated, you should use \"${\n useNewProps[deprecatedProp]\n }\" instead`\n )\n }\n })\n }\n }\n\n render() {\n const newProps = useNewProps\n ? mapNewProps(useNewProps, this.props)\n : this.props\n return <WrappedComponent {...newProps} />\n }\n }\n}\n\n```"
}
] |
code_store-on-localhost_0d1454ac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/modules/withForwardedRef.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\n// For more info see: https://stackoverflow.com/a/51127130/10725088\nconst Element =\n typeof window === 'undefined' || typeof window.Element === 'undefined'\n ? function() {}\n : window.Element\n\nexport const refShape = PropTypes.oneOfType([\n PropTypes.func,\n PropTypes.shape({\n current: PropTypes.instanceOf(Element),\n }),\n])\n\nexport function withForwardedRef(Component: any) {\n const ComponentWithRef = React.forwardRef((props, ref) => {\n return <Component {...props} forwardedRef={ref} />\n })\n\n ComponentWithRef.displayName = Component.displayName || Component.name\n\n return ComponentWithRef as any\n}\n\n```"
}
] |
code_store-on-localhost_b9ec63c5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ButtonWithIcon/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\n\nimport Button from '../Button'\nimport { withForwardedRef } from '../../modules/withForwardedRef'\n\nclass ButtonWithIcon extends Component<any> {\n static defaultProps = {\n iconPosition: 'left',\n }\n\n render() {\n const { icon, iconPosition, size, children } = this.props\n\n const hasIconOnly = !children\n\n let iconMargin\n let paddingOffset\n\n switch (size) {\n case 'small':\n iconMargin = 2\n paddingOffset = 1\n break\n case 'large':\n iconMargin = 4\n paddingOffset = 3\n break\n default:\n iconMargin = 3\n paddingOffset = 2\n break\n }\n\n return (\n <Button {...this.props} icon={false} iconOnly={hasIconOnly}>\n {hasIconOnly ? (\n icon\n ) : (\n <span\n className={`flex items-center ${\n iconPosition === 'left'\n ? `nr${paddingOffset}`\n : `nl${paddingOffset}`\n }`}>\n {icon && iconPosition === 'left' && (\n <div\n className={`mr${iconMargin} nl${iconMargin} flex items-center`}>\n {icon}\n </div>\n )}\n <div>{children}</div>\n {icon && iconPosition === 'right' && (\n <div\n className={`ml${iconMargin} nr${iconMargin} flex items-center`}>\n {icon}\n </div>\n )}\n </span>\n )}\n </Button>\n )\n }\n}\n\nexport default withForwardedRef(ButtonWithIcon) as any\n\n```"
}
] |
code_store-on-localhost_a50577d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ButtonWithIcon/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, `ButtonWithIcon` accepts all the props the\n[`Button`](/#/Components/Forms/Button) component does.\n\n```js\nconst ArrowBack = require('../icon/ArrowBack').default\nconst Delete = require('../icon/Delete').default\nconst Edit = require('../icon/Edit').default\nconst PlusLines = require('../icon/PlusLines').default\n\nconst arrow = <ArrowBack />\nconst remove = <Delete />\nconst edit = <Edit />\nconst plus = <PlusLines />\n\n;<div className=\"flex\">\n <div className=\"mr2\">\n <ButtonWithIcon icon={arrow} variation=\"tertiary\">\n Back\n </ButtonWithIcon>\n </div>\n <div className=\"mr2\">\n <ButtonWithIcon icon={edit} variation=\"secondary\">\n Edit\n </ButtonWithIcon>\n </div>\n <div className=\"mr2\">\n <ButtonWithIcon icon={plus} iconPosition=\"right\">\n Add\n </ButtonWithIcon>\n </div>\n <div className=\"mr2\">\n <ButtonWithIcon icon={remove} variation=\"danger\" />\n </div>\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_637d29c3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/RadioGroup/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'\nimport classNames from 'classnames'\n\nimport Radio from '../Radio'\n\nclass RadioGroup extends React.Component {\n handleChange = event => {\n this.props.onChange(event)\n }\n\n render() {\n const {\n options,\n value,\n name,\n disabled,\n hideBorder,\n label,\n testId,\n size,\n } = this.props\n\n const large = size === 'large'\n\n return (\n <div>\n <fieldset className=\"vtex-input w-100 bn pa0 m0\" data-testid={testId}>\n {label && (\n <legend className=\"dt\" style={{ padding: '0.01em 0 0 0' }}>\n <span\n className={classNames(\n 'vtex-input__label db mb3 w-100 c-on-base',\n { 't-body': large, 't-small': !large }\n )}>\n {label}\n </span>\n </legend>\n )}\n {options.map((option, i) => {\n const isFirst = i === 0\n const isLast = i === options.length - 1\n const isDisabled = disabled || option.disabled\n const id = `${name}-${i}`\n return (\n <label\n className={`db br3 ${classNames({\n 'b--muted-4 ba pv2 ph4': !hideBorder,\n pointer: !isDisabled,\n })}`}\n key={id}\n style={{\n ...(!isFirst && {\n borderTopLeftRadius: 0,\n borderTopRightRadius: 0,\n borderTop: 'none',\n }),\n ...(!isLast && {\n borderBottomLeftRadius: 0,\n borderBottomRightRadius: 0,\n }),\n }}>\n <div className={classNames({ mt3: !hideBorder })}>\n <Radio\n id={id}\n isLast={isLast}\n name={name}\n disabled={isDisabled}\n onChange={this.handleChange}\n label={option.label}\n value={option.value}\n checked={value === option.value}\n />\n </div>\n </label>\n )\n })}\n </fieldset>\n </div>\n )\n }\n}\n\nRadioGroup.propTypes = {\n /** Options list */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])\n .isRequired,\n label: PropTypes.node.isRequired,\n disabled: PropTypes.bool,\n })\n ).isRequired,\n /** Name attribute for the radio inputs, which will also be used to generate ids */\n name: PropTypes.string.isRequired,\n /** Current selected value */\n value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /** onChange event handler */\n onChange: PropTypes.func.isRequired,\n /** Disable the entire group */\n disabled: PropTypes.bool,\n /** Hide group border */\n hideBorder: PropTypes.bool,\n /** Label */\n label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),\n /** Data attribute */\n testId: PropTypes.string,\n /** Input size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n}\n\nRadioGroup.defaultProps = {\n disabled: false,\n hideBorder: false,\n}\n\nexport default RadioGroup\n\n```"
}
] |
code_store-on-localhost_fd08c032
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/RadioGroup/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### A Radio Group represents a need for the user to make a choice among a few offered options.\n\n### ๐ Dos\n\n- Keep the list of options short. More than 6 options might start looking weird.\n- Labels should be clear and if possible short.\n- Mind the order of the options. Some good rule of thumbs for ordering are: most to least frequently used, simplest to most complex, least to most risk.\n- Use a \"None\" option if you need an unselected state.\n- Consider adding an \"Other\" option if needed, maybe in conjunction with a Text Input to capture the user need.\n\n### ๐ Don'ts\n\n- Don't offer overlapping options, they should be clearly mutually exclusive.\n\n### Related components\n\n- Consider using a <a href=\"#/Components/Forms/Checkbox\">Checkbox</a> if you need the user to select more than one option.\n- Consider using a <a href=\"#/Components/Forms/Dropdown\">Dropdown</a> if you have several options and they don't need much explanation.\n- Consider using a <a href=\"#/Components/Forms/SelectableCard\">Selectable Card</a> if you prefer your options to be displayed horizontally or more detailed.\n\nDefault\n\n```js\ninitialState = { value: 'cyan' }\n;<RadioGroup\n hideBorder\n name=\"colors\"\n options={[\n { value: 'cyan', label: 'Cyan' },\n { value: 'magenta', label: 'Magenta' },\n { value: 'yellow', label: 'Yellow' },\n { value: 'key', label: 'Black' },\n ]}\n value={state.value}\n onChange={e => setState({ value: e.currentTarget.value })}\n/>\n```\n\nOne option disabled\n\n```js\n<RadioGroup\n hideBorder\n name=\"radioGroupExample2\"\n options={[\n {\n value: 'value1',\n label: (\n <div>\n <div className=\"b\">L</div>\n <div className=\"c-muted-1\">Lightness</div>\n </div>\n ),\n },\n {\n value: 'value2',\n label: (\n <div>\n <div className=\"b\">a*</div>\n <div className=\"c-muted-1\">GreenโRed</div>\n </div>\n ),\n disabled: true,\n },\n {\n value: 'value3',\n label: (\n <div>\n <div className=\"b\">b*</div>\n <div className=\"c-muted-1\">BlueโYellow</div>\n </div>\n ),\n },\n ]}\n value=\"value1\"\n onChange={() => {}}\n/>\n```\n\nEntire group disabled\n\n```js\n<RadioGroup\n hideBorder\n name=\"radioGroupExample3\"\n disabled\n options={[\n { value: 'value1', label: 'Hue' },\n { value: 'value2', label: 'Saturation' },\n { value: 'value3', label: 'Value' },\n ]}\n value=\"value1\"\n onChange={() => {}}\n/>\n```\n\nWith optional border\n\n```js\n<RadioGroup\n name=\"radioGroupExample3\"\n options={[\n { value: 'value1', label: 'Hue' },\n { value: 'value2', label: 'Saturation' },\n { value: 'value3', label: 'Value' },\n ]}\n value=\"value1\"\n onChange={() => {}}\n/>\n```\n\n```"
}
] |
code_store-on-localhost_ae9dd19e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tabs/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { cloneElement } from 'react'\nimport PropTypes from 'prop-types'\n\nconst Tabs = ({ children, fullWidth, sticky }) => {\n const childrenArray = [].concat(children)\n\n const selectedTab = childrenArray.find(child => child.props.active)\n\n const content = selectedTab && selectedTab.props.children\n return (\n <div\n className={`vtex-tabs w-100 h-100 flex flex-column ${\n sticky ? 'overflow-y-hidden' : ''\n }`}>\n <div className=\"vtex-tabs__nav flex flex-row bb b--muted-4\">\n {childrenArray.map((child, index) =>\n cloneElement(child, {\n fullWidth,\n key: child.props.key != null ? child.props.key : index,\n })\n )}\n </div>\n <div\n className={`vtex-tabs__content w-100 ${\n sticky ? 'overflow-y-auto' : ''\n }`}>\n {content}\n </div>\n </div>\n )\n}\n\nTabs.defaultProps = {\n fullWidth: false,\n sticky: false,\n}\n\nTabs.propTypes = {\n children: PropTypes.arrayOf(PropTypes.node),\n fullWidth: PropTypes.bool,\n sticky: PropTypes.bool,\n}\n\nexport default Tabs\n\n```"
}
] |
code_store-on-localhost_e149834f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tabs/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n```md\nTo import Tabs children (Tab) when using in `npm` you can either\n\n`import Tab from '@vtex/styleguide/lib/Tab'` or\n\n`import Tab from '@vtex/styleguide/lib/Tabs/Tab'`\n```\n\n#### Tabs are navigation solutions for alternating between content that is in the same level of hierarchy.\n\n### ๐ Dos\n\n- Use short labels.\n- Use tabs in any place of your page hierarchy: as a top-level navigation or inside another component.\n- You may use icons instead of text if you want, but be mindful it may hurt usability.\n\n### ๐ Don'ts\n\n- Don't use too many tabs. More than 5 starts looking weird.\n- Don't use dropdown menus with these tabs (althought we might one day support that).\n- Don't nest tabs directly inside tabs, it will be very confusing. (@todo we might need an alternative visual for tabs when used inside other tabs)\n- Avoid forcing the user to alternate back-and-forth between tabs to execute an important task.\n\n### Related components\n\n- <a href=\"#/Components/Forms/ButtonGroup\">ButtonGroup</a>\n\nDefault\n\n```js\nconst Tab = require('./Tab').default\n;<div>\n <Tabs>\n <Tab label=\"label 1\" active onClick={() => {}} />\n <Tab label=\"label 2\" onClick={() => {}} />\n <Tab label=\"label 3\" onClick={() => {}} />\n </Tabs>\n</div>\n```\n\nFull width tabs\n\n```js\nconst Tab = require('./Tab').default\n;<div>\n <Tabs fullWidth>\n <Tab label=\"full width 1\" active onClick={() => {}} />\n <Tab label=\"full width 2\" onClick={() => {}} />\n <Tab label=\"full width 3\" onClick={() => {}} />\n </Tabs>\n</div>\n```\n\nDisabled tabs\n\n```js\nconst Tab = require('./Tab').default\n;<div>\n <Tabs>\n <Tab label=\"Active and disabled tab\" active disabled onClick={() => {}} />\n <Tab label=\"Disabled tab\" disabled onClick={() => {}} />\n </Tabs>\n</div>\n```\n\nWorking example\n\n```js\nconst Tab = require('./Tab').default\nclass TabsExample extends React.Component {\n constructor() {\n super()\n this.state = {\n currentTab: 1,\n }\n this.handleTabChange = this.handleTabChange.bind(this)\n }\n\n handleTabChange(tabIndex) {\n this.setState({\n currentTab: tabIndex,\n })\n }\n\n render() {\n return (\n <div>\n <Tabs>\n <Tab\n label=\"Tab 1\"\n active={this.state.currentTab === 1}\n onClick={() => this.handleTabChange(1)}>\n <p>Content for tab 1</p>\n </Tab>\n <Tab\n label=\"Tab 2\"\n active={this.state.currentTab === 2}\n onClick={() => this.handleTabChange(2)}>\n <p>Content for tab 2</p>\n </Tab>\n <Tab\n label=\"Tab 3\"\n active={this.state.currentTab === 3}\n onClick={() => this.handleTabChange(3)}>\n <p>Content for tab 3</p>\n </Tab>\n </Tabs>\n </div>\n )\n }\n}\n;<TabsExample />\n```\n\nSticky Example\n\n```jsx\nconst Tab = require('./Tab').default\n;<div className=\"h4\">\n <Tabs sticky>\n <Tab label=\"Tab 1\" active>\n <div className=\"h5 flex flex-column\">\n <p>Scroll to see full content</p>\n <div className=\"flex items-end h-100\">\n <p>The end!</p>\n </div>\n </div>\n </Tab>\n </Tabs>\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_8ba6232c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tabs/Tab.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 Tab extends Component {\n handleClick = e => {\n !this.props.disabled && this.props.onClick && this.props.onClick(e)\n }\n\n render() {\n const { active, fullWidth, label, disabled } = this.props\n\n let tabStyle =\n 'c-muted-1 b--transparent hover-c-action-primary pointer vtex-tab__button--inactive'\n\n if (active && disabled) {\n tabStyle = 'fw5 b--muted-1 c-muted-2'\n } else if (active) {\n tabStyle = 'c-on-muted b--emphasis fw5 vtex-tab__button--active'\n } else if (disabled) {\n tabStyle = 'b--muted-4 c-muted-3'\n }\n\n return (\n <button\n type=\"button\"\n onClick={this.handleClick}\n className={`vtex-tab__button bt-0 bl-0 br-0 bw1 ${\n fullWidth ? 'w-100' : ''\n } ${tabStyle}\n v-mid relative h-regular ph6 t-body bg-transparent outline-0\n `}>\n {label}\n </button>\n )\n }\n}\n\nTab.defaultProps = {\n disabled: false,\n}\n\nTab.propTypes = {\n active: PropTypes.bool,\n fullWidth: PropTypes.bool,\n children: PropTypes.node,\n label: PropTypes.any.isRequired,\n onClick: PropTypes.func,\n disabled: PropTypes.bool,\n}\n\nexport default Tab\n\n```"
}
] |
code_store-on-localhost_e3232401
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/FilterBar/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 ButtonWithIcon from '../ButtonWithIcon'\nimport IconClose from '../icon/Close'\nimport deprecated from '../../modules/deprecated'\nimport FilterTag from './FilterTag'\n\nconst HEAVY_ICON_OPTICAL_COMPENSATION = { marginTop: '1px' }\n\nconst isStatementComplete = st => st.subject && st.verb && st.object\nconst filterExtraOptions = (options, alwaysVisibleFilters, statements) => {\n return Object.keys(options)\n .filter(\n key =>\n !alwaysVisibleFilters.includes(key) &&\n !statements.some(st => st.subject === key && st.object)\n )\n .reduce(\n (filteredOptions, key) => ({ ...filteredOptions, [key]: options[key] }),\n {}\n )\n}\n\nconst FILTER_VALUE_LABEL_MAX_LENGTH = 17\nconst truncateFilterValue = filterValue =>\n `${filterValue.substring(0, FILTER_VALUE_LABEL_MAX_LENGTH)}${\n filterValue.length <= FILTER_VALUE_LABEL_MAX_LENGTH ? '' : 'โฆ'\n }`\n\nclass FilterBar extends PureComponent {\n constructor(props) {\n super(props)\n\n this.state = {\n visibleExtraOptions: [],\n }\n }\n\n toggleExtraFilterOption = key => {\n const { visibleExtraOptions } = this.state\n const newVisibleExtraOptions = [\n ...(visibleExtraOptions.indexOf(key) === -1 ? [key] : []),\n ...visibleExtraOptions.filter(op => op !== key),\n ]\n this.setState({ visibleExtraOptions: newVisibleExtraOptions })\n }\n\n handleSubmitFilter = st => {\n const { statements } = this.props\n const hasStatement = statements.some(_st => _st.subject === st.subject)\n if (hasStatement) {\n const newStatements = statements.map(_st => {\n if (_st.subject === st.subject) {\n return {\n ..._st,\n ...st,\n }\n }\n return _st\n })\n this.changeStatementsCallback(newStatements)\n } else {\n const newStatements = statements.slice(0)\n newStatements.push(st)\n this.changeStatementsCallback(newStatements)\n }\n }\n\n handleMoreOptionsSelected = st => {\n if (isStatementComplete(st)) {\n this.handleSubmitFilter(st)\n this.toggleExtraFilterOption(st.subject)\n }\n }\n\n handleFilterClear = subject => {\n const { alwaysVisibleFilters, statements } = this.props\n const newStatements = statements.filter(_st => _st.subject !== subject)\n this.changeStatementsCallback(newStatements)\n !alwaysVisibleFilters.includes(subject) &&\n this.toggleExtraFilterOption(subject)\n }\n\n changeStatementsCallback = statements => {\n this.props.onChangeStatements(statements)\n }\n\n handleClearAllfilters = () => {\n this.setState({ visibleExtraOptions: [] })\n this.changeStatementsCallback([])\n }\n\n render() {\n const {\n options,\n moreOptionsLabel,\n alwaysVisibleFilters,\n clearAllFiltersButtonLabel,\n statements,\n subjectPlaceholder,\n submitFilterLabel,\n newFilterLabel,\n testIds,\n } = this.props\n const { visibleExtraOptions } = this.state\n const optionsKeys = Object.keys(options)\n\n return (\n optionsKeys.length > 0 && (\n <div className={`flex flex-wrap nl1`}>\n {optionsKeys\n .filter(\n key =>\n alwaysVisibleFilters.includes(key) ||\n visibleExtraOptions.includes(key)\n )\n .map(subject => {\n const statement = statements.find(st => st.subject === subject)\n return (\n <div key={`VTEX__filter_option--${subject}`} className=\"ma2\">\n <FilterTag\n alwaysVisible={alwaysVisibleFilters.includes(subject)}\n getFilterLabel={() => {\n const label =\n options[subject] &&\n options[subject].renderFilterLabel(statement)\n return (\n (label &&\n typeof label === 'string' &&\n truncateFilterValue(label)) ||\n 'โฆ'\n )\n }}\n submitFilterLabel={submitFilterLabel}\n subject={subject}\n options={options}\n statements={statements}\n onClickClear={() => this.handleFilterClear(subject)}\n onSubmitFilterStatement={this.handleSubmitFilter}\n />\n </div>\n )\n })}\n {alwaysVisibleFilters.length + visibleExtraOptions.length !==\n optionsKeys.length && (\n <div className=\"ma2\">\n <FilterTag\n testIds={testIds}\n isMoreOptions\n subjectPlaceholder={subjectPlaceholder}\n getFilterLabel={() => moreOptionsLabel}\n submitFilterLabel={submitFilterLabel}\n newFilterLabel={newFilterLabel}\n options={{\n ...filterExtraOptions(\n options,\n alwaysVisibleFilters,\n statements\n ),\n }}\n statements={[]}\n onSubmitFilterStatement={this.handleMoreOptionsSelected}\n />\n </div>\n )}\n {clearAllFiltersButtonLabel &&\n statements.some(st => !!st && !!st.object) && (\n <div className=\"ml-auto mt1\">\n <ButtonWithIcon\n icon={\n <span\n className=\"flex items-center c-muted-2\"\n style={HEAVY_ICON_OPTICAL_COMPENSATION}>\n <IconClose size={13} />\n </span>\n }\n size=\"small\"\n variation=\"tertiary\"\n onClick={this.handleClearAllfilters}>\n <span className=\"c-muted-2\">\n {clearAllFiltersButtonLabel}\n </span>\n </ButtonWithIcon>\n </div>\n )}\n </div>\n )\n )\n }\n}\n\nFilterBar.defaultProps = {\n options: [],\n moreOptionsLabel: 'More',\n alwaysVisibleFilters: [],\n subjectPlaceholder: 'Select a filterโฆ',\n submitFilterLabel: 'Apply',\n newFilterLabel: 'New Filter',\n statements: [],\n testIds: {},\n}\n\nexport const filterBarPropTypes = {\n /** filter options (mirroring statements from Conditions component) */\n options: PropTypes.object.isRequired,\n /** filter statements (mirroring statements from Conditions component) */\n statements: PropTypes.array,\n /** Filters change callback: returns array of statement definitions */\n onChangeStatements: PropTypes.func.isRequired,\n /** label for MORE options */\n moreOptionsLabel: PropTypes.string,\n /** filter options that are always visible outside MORE options */\n alwaysVisibleFilters: PropTypes.arrayOf(PropTypes.string),\n /** if this label is passed, when some filter is not empty a clear all button will appear */\n clearAllFiltersButtonLabel: PropTypes.string,\n /** Subject select placeholder inside 'More options' */\n subjectPlaceholder: PropTypes.string,\n /** Submit button label for statement inside FilterTag */\n submitFilterLabel: PropTypes.string,\n /** New Filter title label for inside the 'More options' menu */\n newFilterLabel: PropTypes.string,\n testIds: PropTypes.shape({\n moreOptionsButton: PropTypes.string,\n submitFiltersButton: PropTypes.string,\n }),\n}\n\nFilterBar.propTypes = filterBarPropTypes\n\nexport default deprecated({\n useNewProps: {\n submitFilterLable: 'submitFilterLabel',\n newFilterLable: 'newFilterLabel',\n },\n})(FilterBar)\n\n```"
}
] |
code_store-on-localhost_7cf75b7f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/FilterBar/FilterTag.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { PureComponent, Fragment } from 'react'\nimport PropTypes from 'prop-types'\nimport merge from 'lodash/merge'\nimport classNames from 'classnames'\n\nimport withDevice from '../utils/withDeviceHoc'\nimport Button from '../Button'\nimport IconClear from '../icon/Clear'\nimport IconCaretDown from '../icon/CaretDown'\nimport Statement from '../Statement'\nimport Menu from './Menu'\n\nconst OPEN_MENU_STYLE = { backgroundColor: '#dbe9fd' }\nconst emptyVirtualStatement = {\n subject: null,\n verb: null,\n object: null,\n error: null,\n}\n\nconst filterStatementBySubject = (statements = [], subject, options = {}) => {\n const hasStatement = statements.some(st => st.subject === subject)\n return hasStatement\n ? statements.filter(st => st.subject === subject)\n : [\n {\n ...emptyVirtualStatement,\n subject: subject,\n verb:\n options[subject] && options[subject].verbs.length > 0\n ? options[subject].verbs[0].value\n : null,\n },\n ]\n}\n\nclass FilterTag extends PureComponent {\n constructor(props) {\n super(props)\n this.filterMenuContainer = React.createRef()\n\n this.state = {\n isMenuOpen: false,\n virtualStatement: filterStatementBySubject(\n props.statements,\n props.subject,\n props.options\n )[0],\n }\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n if (\n nextProps.statements &&\n nextProps.statements.length > 0 &&\n nextProps.subject &&\n nextProps.statements.some(st => st.subject === nextProps.subject)\n ) {\n const statement = filterStatementBySubject(\n nextProps.statements,\n nextProps.subject,\n nextProps.options\n )[0]\n return {\n virtualStatement: merge({}, statement, prevState.virtualStatement),\n }\n }\n return prevState\n }\n\n openMenu = () => {\n if (this.state.isMenuOpen) return\n\n document.addEventListener('mousedown', this.handleClickOutside)\n this.setState({\n isMenuOpen: true,\n virtualStatement: filterStatementBySubject(\n this.props.statements,\n this.props.subject,\n this.props.options\n )[0],\n })\n }\n\n handleCloseMenu = () => {\n if (!this.state.isMenuOpen) return\n\n document.removeEventListener('mousedown', this.handleClickOutside)\n this.setState({\n isMenuOpen: false,\n virtualStatement: filterStatementBySubject(\n [],\n this.props.subject,\n this.props.options\n )[0],\n })\n }\n\n handleClickOutside = e => {\n if (\n this.filterMenuContainer &&\n this.filterMenuContainer.current &&\n !this.filterMenuContainer.current.contains(e.target) &&\n this.state.isMenuOpen\n ) {\n this.handleCloseMenu()\n }\n }\n\n componentWillUnmount() {\n if (this.state.isMenuOpen) {\n this.handleCloseMenu()\n }\n }\n\n handleChangeStatement = statement => {\n this.setState(state => {\n return {\n virtualStatement: merge({}, state.virtualStatement, {\n ...statement,\n }),\n }\n })\n }\n\n resetVirtualStatement = () => {\n const { subject, options } = this.props\n const statement = filterStatementBySubject([], subject, options)\n this.setState({ virtualStatement: statement })\n }\n\n render() {\n const {\n options,\n subject,\n statements,\n alwaysVisible,\n getFilterLabel,\n subjectPlaceholder,\n onClickClear,\n isMoreOptions,\n onSubmitFilterStatement,\n submitFilterLabel,\n newFilterLabel,\n isMobile,\n testIds,\n } = this.props\n const { isMenuOpen, virtualStatement } = this.state\n\n const statement = filterStatementBySubject(statements, subject)[0]\n const isEmpty = !!(\n statements &&\n (!statement || (statement && !statement.object))\n )\n\n const shouldOmitSubject = !isMoreOptions\n const shouldOmitVerb = isMoreOptions\n ? false\n : options[subject].verbs.length === 1\n\n // this is temporary just to assure backward compatibility\n const compatibleOptions = {}\n Object.keys(options).forEach(opt => {\n compatibleOptions[opt] = merge({}, { ...options[opt] })\n compatibleOptions[opt].verbs = options[opt].verbs.map(verb => {\n if (typeof verb.object === 'function') {\n return verb\n }\n console.warn(\n '[Deprecation alert]',\n 'FilterBar prop \"options\" will change contract due to Conditions and Statement refactor.',\n 'please if you are using it let @guigs and @eric know...'\n )\n return {\n ...verb,\n object: ({ error, onChange, value }) => {\n return (\n <>\n {verb.object.renderFn({\n statements: [merge({}, statement, virtualStatement)],\n values: value,\n statementIndex: 0,\n error,\n extraParams: verb.object && verb.object.extraParams,\n onChangeObjectCallback: onChange,\n })}\n </>\n )\n },\n }\n })\n })\n\n return (\n <div\n ref={this.filterMenuContainer}\n style={{\n ...(isMenuOpen && OPEN_MENU_STYLE),\n }}\n className={`br2 ba b--solid ${\n isEmpty || isMoreOptions ? '' : 'pr4'\n } pv1 dib ${\n alwaysVisible && isEmpty\n ? 'bg-transparent hover-bg-muted-5 b--muted-4'\n : isMoreOptions\n ? 'hover-bg-muted-5 b--muted-4'\n : 'bg-action-secondary hover-bg-action-secondary b--action-secondary'\n } c-on-base`}>\n <div className=\"flex items-stretch\">\n <Menu\n open={isMenuOpen}\n onBackgroundClick={this.handleCloseMenu}\n align=\"left\"\n options={options[subject]}\n button={\n <button\n type=\"button\"\n className=\"bw1 ba br2 v-mid relative bg-transparent b--transparent c-action-primary pointer w-100 outline-0\"\n onClick={isMenuOpen ? this.handleCloseMenu : this.openMenu}>\n <div className=\"flex items-center justify-center h-100 ph3 \">\n <span className=\"flex items-center nl1 nowrap\">\n {isMoreOptions ? (\n <span\n className=\"fw5\"\n data-testid={testIds.moreOptionsButton}>\n {getFilterLabel()}\n </span>\n ) : isMobile ? (\n <span className=\"ttu f6 fw5\">\n {options[subject].label}\n </span>\n ) : (\n <Fragment>\n <span>{`${options[subject].label}:\\xa0`}</span>\n <span className=\"fw5\">{`${getFilterLabel(\n filterStatementBySubject(statements, subject)\n )}`}</span>\n </Fragment>\n )}\n {!isMobile && (\n <div className=\"ml2 nr2\">\n <IconCaretDown size={11} color=\"currentColor\" />\n </div>\n )}\n </span>\n </div>\n </button>\n }>\n <div className=\"ma6 ma5-ns h-75 h-auto-ns flex flex-column justify-between\">\n <div\n className={classNames({\n 'overflow-scroll': isMobile && 'overflow-scroll',\n })}>\n <div\n className={`flex flex-wrap ${isMoreOptions ? 'mb6' : 'mb3'}`}>\n {isMoreOptions && (\n <span className=\"f4 mh3\">{newFilterLabel}</span>\n )}\n <div className=\"flex flex-column\">\n {shouldOmitVerb && (\n <span className=\"mh3\">\n {options[subject].verbs[0].label}\n </span>\n )}\n </div>\n </div>\n <Statement\n isFullWidth\n omitSubject={shouldOmitSubject}\n omitVerbs={shouldOmitVerb}\n options={compatibleOptions}\n subjectPlaceholder={subjectPlaceholder}\n statement={\n isMoreOptions\n ? virtualStatement\n : merge({}, statement, virtualStatement)\n }\n onChangeStatement={this.handleChangeStatement}\n onChangeObjectCallback={st =>\n this.handleChangeStatement({\n ...st,\n error: null,\n })\n }\n />\n </div>\n <div className=\"flex justify-end mt4 mh3\">\n <Button\n testId={testIds.submitFiltersButton}\n block={isMobile}\n type=\"submit\"\n disabled={virtualStatement && !virtualStatement.object}\n onClick={() => {\n onSubmitFilterStatement(virtualStatement)\n this.resetVirtualStatement()\n this.handleCloseMenu()\n }}>\n {submitFilterLabel}\n </Button>\n </div>\n </div>\n </Menu>\n {!isEmpty && !isMoreOptions && (\n <div\n className=\"flex items-center c-link hover-c-link pointer\"\n onClick={() => {\n this.resetVirtualStatement()\n onClickClear()\n }}>\n <IconClear solid size={16} />\n </div>\n )}\n </div>\n </div>\n )\n }\n}\n\nFilterTag.defaultProps = {\n alwaysVisible: false,\n isMoreOptions: false,\n subjectPlaceholder: 'โฆ',\n newFilterLabel: 'New filter',\n testIds: {},\n}\n\nFilterTag.propTypes = {\n options: PropTypes.object.isRequired,\n subject: PropTypes.string,\n statements: PropTypes.array,\n alwaysVisible: PropTypes.bool,\n getFilterLabel: PropTypes.func,\n subjectPlaceholder: PropTypes.string,\n onClickClear: PropTypes.func,\n isMoreOptions: PropTypes.bool,\n onSubmitFilterStatement: PropTypes.func.isRequired,\n submitFilterLabel: PropTypes.string.isRequired,\n newFilterLabel: PropTypes.string,\n device: PropTypes.string,\n isMobile: PropTypes.bool,\n testIds: PropTypes.shape({\n moreOptionsButton: PropTypes.string,\n submitFiltersButton: PropTypes.string,\n }),\n}\n\nexport default withDevice(FilterTag)\n\n```"
}
] |
code_store-on-localhost_11f15fca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/FilterBar/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### The FilterBar is a slim, optimized way of displaying filter atoms. Although tailored to be used with the Table component, it can also be used on its own with any other way you chose to display your data.\n\n<div className=\"center mw7 pv6\">\n \n</div>\n\nDifferent from regular filter panels, ours optimizes for both the screen real-estate and discoverability of new filters. You can have dozens of different, complex available filters, and still present to the user a slim and simple-to-use interface.\n\n### ๐ Dos\n\n- Apply user research to choose which filters to show in the highlighted section.\n- Use the FilterBar always on top 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\n### ๐ Don'ts\n\n- Don't present too many filters in the highlighted zone.\n\n### Related components\n\n- For applications with a small viewport or when working with modals prefer using the <a href=\"#/Components/Display/FilterOptions\">FilterOptions</a> component.\n\nSimple product filter 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 MySimpleFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.getSimpleVerbs = this.getSimpleVerbs.bind(this)\n this.renderSimpleFilterLabel = this.renderSimpleFilterLabel.bind(this)\n }\n\n getSimpleVerbs() {\n return [\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 label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\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 <FilterBar\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\nconst Input = require('../Input').default\nconst Checkbox = require('../Checkbox').default\n\nconst CPF_VALIDATION_REGEX = RegExp('[0-9]{3}.[0-9]{3}.[0-9]{3}-[0-9]{2}')\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nfunction CpfInputObject({ value, error, onChange }) {\n return (\n <Input\n placeholder=\"Insert cpf (with punctuation)โฆ\"\n errorMessage={value && error}\n value={value || ''}\n onChange={e => onChange(e.target.value)}\n />\n )\n}\n\nfunction CpfInputObjectWithValidation({ onChange, ...props }) {\n return (\n <CpfInputObject\n {...props}\n onChange={value => {\n if (value && value.length < 15 && CPF_VALIDATION_REGEX.test(value)) {\n onChange(value)\n } else {\n onChange(value, 'Invalid CPF')\n }\n }}\n />\n )\n}\n\nfunction AgeInputObject({ value, onChange }) {\n return (\n <Input\n placeholder=\"Insert ageโฆ\"\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\nfunction AgeInputRangeObject({ value, onChange }) {\n const { from = '', to = '' } = value\n return (\n <div className=\"flex\">\n <Input\n placeholder=\"Age fromโฆ\"\n errorMessage={\n parseInt(from) >= parseInt(to)\n ? 'Must be smaller than other input'\n : ''\n }\n value={from}\n onChange={e => {\n const newValue = { from, to }\n newValue.from = e.target.value.replace(/\\D/g, '')\n\n onChange(newValue)\n }}\n />\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <Input\n placeholder=\"Age toโฆ\"\n value={to}\n onChange={e => {\n const newValue = { from, to }\n newValue.to = e.target.value.replace(/\\D/g, '')\n\n onChange(newValue)\n }}\n />\n </div>\n )\n}\n\nfunction ClassSelectorObject({ value, error, onChange }) {\n const initialValue = {\n vip: true,\n gold: true,\n silver: true,\n platinum: true,\n ...(value || {}),\n }\n const toggleValueByKey = key => {\n const newValues = {\n ...(value || initialValue),\n [key]: value ? !value[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={value ? value[opt] : initialValue[opt]}\n id={`class-${opt}`}\n label={opt}\n name=\"class-checkbox-group\"\n onChange={() => {\n const newValue = toggleValueByKey(`${opt}`)\n onChange(newValue)\n }}\n value={opt}\n />\n </div>\n )\n })}\n </div>\n )\n}\n\nclass MyUsersFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n }\n\n render() {\n return (\n <FilterBar\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: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'is not',\n value: '!=',\n object: props => <SimpleInputObject {...props} />,\n },\n {\n label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\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: 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 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: props => <ClassSelectorObject {...props} />,\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: props => <AgeInputObject {...props} />,\n },\n {\n label: 'is between',\n value: 'between',\n object: props => <AgeInputRangeObject {...props} />,\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: props => <CpfInputObjectWithValidation {...props} />,\n },\n {\n label: 'contains',\n value: 'contains',\n object: props => <CpfInputObject {...props} />,\n },\n ],\n },\n }}\n />\n )\n }\n}\n;<MyUsersFilter />\n```\n\nFilter orders example\n\n```js\nconst Input = require('../Input').default\nconst Checkbox = require('../Checkbox').default\nconst DatePicker = require('../DatePicker').default\n\nfunction SimpleInputObject({ value, onChange }) {\n return <Input value={value || ''} onChange={e => onChange(e.target.value)} />\n}\n\nfunction DatePickerObject({ value, onChange }) {\n return (\n <div className=\"w-100\">\n <DatePicker\n value={value || new Date()}\n onChange={date => {\n onChange(date)\n }}\n locale=\"pt-BR\"\n />\n </div>\n )\n}\n\nfunction DatePickerRangeObject({ value, onChange }) {\n return (\n <div className=\"flex flex-column w-100\">\n <br />\n <DatePicker\n label=\"\u001cfrom\"\n value={(value && value.from) || new Date()}\n onChange={date => {\n onChange({ ...(value || {}), from: date })\n }}\n locale=\"pt-BR\"\n />\n <br />\n <DatePicker\n label=\"to\"\n value={(value && value.to) || new Date()}\n onChange={date => {\n onChange({ ...(value || {}), to: date })\n }}\n locale=\"pt-BR\"\n />\n </div>\n )\n}\n\nfunction StatusSelectorObject({ value, onChange }) {\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 ...(value || {}),\n }\n const toggleValueByKey = key => {\n return {\n ...(value || initialValue),\n [key]: value ? !value[key] : false,\n }\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 id={`status-${opt}`}\n label={opt}\n name=\"status-checkbox-group\"\n onChange={() => {\n const newValue = toggleValueByKey(`${opt}`)\n onChange(newValue)\n }}\n value={opt}\n />\n </div>\n )\n })}\n </div>\n )\n}\n\nclass MyOrdersFilter extends React.Component {\n constructor() {\n super()\n this.state = { statements: [] }\n this.simpleInputVerbs = this.simpleInputVerbs.bind(this)\n }\n\n simpleInputVerbs() {\n return [\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 label: 'contains',\n value: 'contains',\n object: props => <SimpleInputObject {...props} />,\n },\n ]\n }\n\n render() {\n return (\n <FilterBar\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: props => <StatusSelectorObject {...props} />,\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: props => <DatePickerObject {...props} />,\n },\n {\n label: 'is between',\n value: 'between',\n object: props => <DatePickerRangeObject {...props} />,\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\n```"
}
] |
code_store-on-localhost_7e612b4d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/FilterBar/Menu.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 Close from '../icon/Close'\nimport withDevice from '../utils/withDeviceHoc'\n\nconst DEFAULT_WIDTH = 292\nconst CONTAINER_MARGIN = 6\nconst WINDOW_MARGIN = 10\n\nclass Menu extends Component {\n constructor(props) {\n super(props)\n this.containerElement = React.createRef()\n this.menuElement = 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 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\n : window.innerHeight -\n menuBounds.top -\n containerHeight -\n CONTAINER_MARGIN -\n 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 {\n width,\n align,\n open,\n children,\n button,\n isMobile,\n options,\n } = this.props\n const {\n hasCalculatedSize,\n isUpwards,\n isVisible,\n menuHeight,\n containerHeight,\n } = this.state\n\n const isRight = align === 'right'\n\n const optionsLabel = (options && options.label) || ''\n\n let styles = {\n boxShadow: '0px 1px 18px rgba(0, 0, 0, 0.14)',\n }\n\n if (isMobile) {\n styles = {\n ...styles,\n top: 0,\n height: '100%',\n }\n }\n\n if (!isMobile) {\n styles = {\n ...styles,\n transform:\n !hasCalculatedSize || isVisible ? 'scale(1)' : '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']: containerHeight + CONTAINER_MARGIN,\n }\n }\n\n const openContainerClasses = classNames(\n 'fixed absolute-ns w-100 w-auto-ns z-999 ba bw1 b--muted-4 bg-base',\n {\n 'right-0': isRight,\n 'left-0': !isRight,\n br0: isMobile,\n br2: !isMobile,\n 'o-100': isVisible,\n 'o-0': !isVisible,\n }\n )\n\n return (\n <div className=\"relative\">\n <div ref={this.containerElement}>{button}</div>\n {open && (\n <>\n <div\n ref={this.menuElement}\n style={styles}\n className={openContainerClasses}>\n <div\n className=\"b2-ns br2-ns bg-base h-100 h-auto-ns\"\n style={{ width: isMobile ? '100%' : width || DEFAULT_WIDTH }}>\n <div\n className={\n menuHeight\n ? 'overflow-auto h-100 h-auto-ns'\n : 'h-100 h-auto-ns'\n }>\n {isMobile && (\n <div className=\"flex justify-between flex-row items-baseline pa6 mh3\">\n <div className=\"truncate f3 pr6\">{optionsLabel}</div>\n <div onClick={this.props.onBackgroundClick}>\n <Close size={20} color=\"currentColor\" />\n </div>\n </div>\n )}\n {children}\n </div>\n </div>\n </div>\n </>\n )}\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 /** Menu visibility (default is false) */\n open: PropTypes.bool,\n options: PropTypes.array,\n button: PropTypes.element,\n /** Menu Box width (default is 292px) */\n width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\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 /** Function to handle callback on overlay click */\n onBackgroundClick: PropTypes.func,\n /** Boolean if the device is mobile */\n isMobile: PropTypes.bool,\n}\n\nexport default withDevice(Menu)\n\n```"
}
] |
code_store-on-localhost_85f6fcf5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Dropdown/ArrowDownIcon.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 ArrowDownIcon 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 d=\"M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z\" />\n </g>\n </svg>\n )\n }\n}\n\nArrowDownIcon.defaultProps = {\n size: 16,\n color: 'currentColor',\n}\n\nArrowDownIcon.propTypes = {\n size: PropTypes.number.isRequired,\n color: PropTypes.string.isRequired,\n}\n\nexport default ArrowDownIcon\n\n```"
}
] |
code_store-on-localhost_d0cf02ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Dropdown/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 ArrowDownIcon from './ArrowDownIcon'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nclass Dropdown extends Component {\n constructor(props) {\n super(props)\n\n // The initial value sent to the dropdown is kept in order to know\n // whether or not to create and keep a first disabled option.\n // If the initial value is invalid/empty, an empty option is kept\n // so the select will have an empty state. Otherwise, the first\n // value would automatically be chosen.\n // However, you can't select a null/undefined option, so nil values\n // are transformed to empty string.\n this.initialValue = props.value == null ? '' : props.value\n }\n\n handleChange = e => {\n const { disabled, onChange } = this.props\n const {\n target: { value },\n } = e\n\n !disabled && onChange && onChange(e, value)\n }\n\n getOptionFromValue = value => {\n const { options } = this.props\n const option = options.filter(option => option.value === value)[0]\n if (!option) return null\n return option\n }\n\n getDropdownIdentification = () => {\n const { label, id, options } = this.props\n if (label) {\n return `Dropdown with the label \"${label}\"`\n } else if (id) {\n return `Dropdown #${id}`\n }\n return `Dropdown with the options ${options\n .map(option => option.label)\n .join(', ')}`\n }\n\n getPlaceholder = () => {\n const { placeholder, label, helpText } = this.props\n const placeholderValue = placeholder || label || helpText || ''\n\n if (placeholderValue === '' && !this.sentPlaceholderWarning) {\n const identificationText = this.getDropdownIdentification()\n console.warn(\n `The following dropdown has a placeholder option, but no placeholder text. Please use at least one of these props: placeholder, label, or helpText. ${identificationText}`\n )\n\n this.sentPlaceholderWarning = true\n }\n\n return placeholderValue\n }\n\n getSelectedOption = () => {\n return this.getOptionFromValue(this.props.value)\n }\n\n getValueLabel() {\n const selectedOption = this.getSelectedOption()\n return selectedOption ? selectedOption.label : this.getPlaceholder()\n }\n\n componentDidMount() {\n if (this.props.size === 'x-large') {\n console.warn(\n 'Dropdown: 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\n render() {\n const {\n label,\n id,\n testId,\n value,\n size,\n disabled,\n options,\n error,\n errorMessage,\n helpText,\n placeholder,\n preventTruncate,\n autoFocus,\n form,\n name,\n required,\n variation,\n selectTestId,\n } = this.props\n\n const hasValidInitialValue =\n this.getOptionFromValue(this.initialValue) !== null\n\n const isPlaceholder = this.getSelectedOption() === null\n const isInline = variation.toLowerCase() === 'inline'\n let width\n let iconSize\n\n let classes = 'bg-transparent bn w-100 h-100 '\n let containerClasses = `${isInline ? '' : 'bw1'} br2 relative `\n let selectClasses = 'o-0 absolute top-0 left-0 h-100 w-100 bottom-00 '\n\n let labelClasses = 'vtex-dropdown__label db mb3 w-100 c-on-base '\n\n const valueLabel = this.getValueLabel()\n const showCaption = !valueLabel\n\n const color = isInline ? 'c-link ' : 'c-on-base '\n\n classes += disabled ? '' : 'pointer '\n selectClasses += disabled ? '' : 'pointer '\n classes +=\n !disabled && valueLabel\n ? !isPlaceholder\n ? color\n : 'c-muted-2 '\n : 'c-disabled '\n\n switch (size) {\n case 'small':\n classes += isInline ? 'ph2 ' : 'pl5 pr3 '\n selectClasses += 't-small '\n labelClasses += 't-small '\n containerClasses += `${isInline ? 'h-auto' : 'h-small'} t-small `\n iconSize = 18\n break\n case 'large':\n classes += isInline ? 'ph2 ' : 'ph5 '\n selectClasses += 't-body '\n labelClasses += 't-body '\n containerClasses += `${isInline ? 'h-auto' : 'h-large'} t-body `\n iconSize = 18\n break\n case 'x-large':\n // DEPRECATED\n classes += 't-body pv5 ph5 '\n selectClasses += 't-body '\n labelClasses += 't-body '\n iconSize = 22\n break\n default:\n classes += isInline ? 'ph2 ' : 'pl5 pr4 '\n selectClasses += 't-body '\n labelClasses += 't-small '\n containerClasses += `${isInline ? 'h-auto' : 'h-regular'} t-body `\n iconSize = 18\n break\n }\n\n const containerStyle = { width }\n\n if (disabled) {\n containerClasses += 'ba b--disabled bw1 bg-disabled '\n } else if (error || errorMessage) {\n containerClasses += 'ba b--danger hover-b--danger '\n } else if (isInline) {\n containerClasses += 'fw5 '\n } else {\n containerClasses += 'bg-base hover-b--muted-3 ba b--muted-4 '\n }\n\n return (\n <div\n className={`vtex-dropdown ${\n isInline ? 'vtex-dropdown--inline dib' : ''\n }`}\n data-testid={testId}>\n <label>\n {label && <span className={labelClasses}>{label}</span>}\n <div className={containerClasses} style={containerStyle}>\n <div id={id} className={`vtex-dropdown__button ${classes}`}>\n <div className={`flex ${isInline ? '' : 'h-100'}`}>\n <div\n className={`vtex-dropdown__caption flex-auto tl truncate ${\n isInline ? '' : 'h-100'\n }`}>\n <div\n className={`${isInline ? '' : 'h-100'} flex items-center`}>\n {showCaption ? placeholder : valueLabel}\n </div>\n </div>\n <div\n className={`vtex-dropdown__arrow flex-none flex items-center pl2 ${\n disabled ? 'c-on-disabled' : 'c-action-primary'\n }`}>\n <ArrowDownIcon size={iconSize} />\n </div>\n </div>\n </div>\n\n <select\n data-testid={selectTestId}\n disabled={disabled}\n className={selectClasses}\n onChange={this.handleChange}\n ref={this.props.forwardedRef}\n // Check the comment on the constructor regarding nil values\n value={value == null ? '' : value}\n autoFocus={autoFocus}\n form={form}\n name={name}\n required={required}\n style={{\n // safari select height fix\n WebkitAppearance: 'menulist-button',\n }}>\n {/* iOS hack to optionally prevent truncating options */}\n {preventTruncate && <optgroup label={label || helpText || ''} />}\n\n {/* Creates a disabled first option in case the first value is invalid or empty */}\n {(!hasValidInitialValue || placeholder) && (\n <option\n disabled\n value={!hasValidInitialValue ? this.initialValue : null}>\n {this.getPlaceholder()}\n </option>\n )}\n {options.map(option => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n </div>\n </label>\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 </div>\n )\n }\n}\n\nDropdown.defaultProps = {\n size: 'regular',\n options: [],\n variation: 'default',\n}\n\nDropdown.propTypes = {\n /** Error highlight */\n error: PropTypes.bool,\n /** Error message */\n errorMessage: PropTypes.node,\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** Help text */\n helpText: PropTypes.node,\n /** Dropdown label */\n label: PropTypes.node,\n /** Dropdown placeholder value */\n placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n /** Dropdown size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Dropdown options list */\n options: PropTypes.arrayOf(\n PropTypes.shape({\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])\n .isRequired,\n label: PropTypes.oneOfType([PropTypes.string, PropTypes.number])\n .isRequired,\n })\n ),\n /** Prevent truncating large options texts on some devices/browsers, such as iOS */\n preventTruncate: PropTypes.bool,\n /** Spec attribute */\n id: PropTypes.string,\n /** Data attribute */\n testId: PropTypes.string,\n /** Data attribute for select*/\n selectTestId: PropTypes.string,\n /** Spec attribute */\n autoFocus: PropTypes.bool,\n /** Spec attribute */\n value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /** Spec attribute */\n disabled: PropTypes.bool,\n /** Dropdown variation */\n variation: PropTypes.oneOf(['default', 'inline']),\n /** Spec attribute */\n form: PropTypes.string,\n /** Spec attribute */\n name: PropTypes.string,\n /** Spec attribute */\n required: PropTypes.bool,\n /** onChange event */\n onChange: PropTypes.func,\n /** onClose event */\n onClose: PropTypes.func,\n /** onOpen event */\n onOpen: PropTypes.func,\n}\n\nexport default withForwardedRef(Dropdown)\n\n```"
}
] |
code_store-on-localhost_a76a8ba4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Dropdown/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### A Dropdown lets the user pick an option from a list.\n\n### ๐ Dos\n\n- Mind the order of the options, like putting more probable to be picked on that. In doubt, sort them alphanumerically (from A to Z and from 0 to 9).\n\n### ๐ Don'ts\n\n- Don't use a Dropdown if you have more than a few dozens options. Most users don't know about the keyboard search feature and will have to scan through all the options. In this case you'll probably need something a little fancier (work not in progress).\n\n### Related components\n\n- Consider a <a href=\"#/Components/Forms/RadioGroup\">Radio Group</a> if there are fewer than 4 options to choose from, or you need more space to explain each of the options.\n- For multiple picks, use the <a href=\"#/Components/๐ป%20Experimental/Select\">Select</a> (work in progress).\n\nSizes\n\n```js\n<div>\n <div className=\"mb5\">\n <Dropdown\n label=\"Small\"\n size=\"small\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n\n <div className=\"mb5\">\n <Dropdown\n label=\"Regular\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n\n <div className=\"mb5\">\n <Dropdown\n label=\"Large\"\n size=\"large\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n</div>\n```\n\nVariations\n\n```js\n;<div className=\"w-40\">\n <div className=\"mb5\">\n <Dropdown\n label=\"Placeholder\"\n placeholder=\"Select an artist\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"\"\n onChange={() => {}}\n />\n </div>\n <div className=\"mb5\">\n <Dropdown\n label=\"Disabled\"\n disabled\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n <div className=\"mb5\">\n <Dropdown\n label=\"Error\"\n errorMessage=\"Required field\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n <div className=\"mb5\">\n <Dropdown\n label=\"Help text\"\n helpText={<span>Your help text goes here!</span>}\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n { value: 'goya', label: 'Goya' },\n { value: 'monet', label: 'Monet' },\n { value: 'picasso', label: 'Picasso' },\n { value: 'tolouseLautrec', label: 'Toulouse-Lautrec' },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n <div>\n <Dropdown\n label=\"Prevent truncate\"\n preventTruncate\n options={[\n {\n value: 'chagall',\n label: 'Marc Zakharovich Chagall, born Moishe Zakharovich Shagal',\n },\n {\n value: 'dali',\n label:\n 'Salvador Domingo Felipe Jacinto Dalรญ i Domรจnech, Marquis of Dalรญ de Pรบbol, known professionally as Salvador Dalรญ',\n },\n { value: 'goya', label: 'Francisco Josรฉ de Goya y Lucientes' },\n { value: 'monet', label: 'Oscar-Claude Monet' },\n { value: 'picasso', label: 'Pablo Picasso' },\n {\n value: 'tolouseLautrec',\n label:\n 'Henri Marie Raymond de Toulouse-Lautrec-Monfa, also known as Henri de Toulouse-Lautrec',\n },\n ]}\n value=\"tolouseLautrec\"\n onChange={() => {}}\n />\n </div>\n <div className=\"mt5\">\n Inline example:\n <Dropdown\n variation=\"inline\"\n size=\"large\"\n options={[\n { value: 'chagall', label: 'Chagall' },\n { value: 'dali', label: 'Dali' },\n ]}\n value=\"dali\"\n onChange={() => {}}\n />\n </div>\n</div>\n```\n\nExample: Working React Component\n\n```js\nclass Example extends React.Component {\n constructor(props) {\n super(props)\n\n this.state = {\n options: [\n { value: 'painterChagall', label: 'Chagall' },\n { value: 'painterDali', label: 'Dali' },\n { value: 'painterGoya', label: 'Goya' },\n { value: 'painterMonet', label: 'Monet' },\n { value: 'painterPicasso', label: 'Picasso' },\n { value: 'painterTolouseLautrec', label: 'Toulouse-Lautrec' },\n ],\n selectedPainter: '',\n }\n this.handleChange = this.handleChange.bind(this)\n }\n\n handleChange(e, value) {\n this.setState({ selectedPainter: value })\n }\n\n render() {\n const selectedPainter = this.state.options.find(\n painter => painter.value === this.state.selectedPainter\n )\n\n const { label, value } = selectedPainter || {}\n\n return (\n <div className=\"w-40\">\n <div>\n <Dropdown\n label=\"Painter\"\n options={this.state.options}\n onChange={this.handleChange}\n value={this.state.selectedPainter}\n placeholder=\"Select a painter\"\n {...this.props}\n />\n </div>\n <div className=\"mt6\">\n <div className=\"fw5 mb3\">Selected Painter</div>\n <p>Label: {label || <span className=\"c-muted-1\">undefined</span>}</p>\n <p>Value: {value || <span className=\"c-muted-1\">undefined</span>}</p>\n </div>\n </div>\n )\n }\n}\n;<Example />\n```\n\n```"
}
] |
code_store-on-localhost_b7daef94
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ToastProvider/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 ToastManager from './ToastManager'\n\nconst ToastContext = React.createContext({\n showToast: () => {},\n hideToast: () => {},\n toastState: null,\n})\n\nclass ToastProvider extends Component {\n constructor(props) {\n super(props)\n\n this.toastManager = React.createRef()\n }\n\n render() {\n const { children, positioning } = this.props\n return (\n <ToastManager positioning={positioning}>\n {({ showToast, hideToast, state: toastState }) => (\n <ToastContext.Provider\n value={{\n showToast,\n hideToast,\n toastState,\n }}>\n {children}\n </ToastContext.Provider>\n )}\n </ToastManager>\n )\n }\n}\n\nToastProvider.propTypes = {\n children: PropTypes.node,\n /** Sets the position of the toasts based either on the dimensions of the parent element of the ToastProvider, or window dimensions */\n positioning: PropTypes.oneOf(['parent', 'window']),\n}\n\nToastProvider.defaultProps = {\n positioning: 'parent',\n}\n\nconst ToastConsumer = ({ children }) => (\n <ToastContext.Consumer>{value => children(value)}</ToastContext.Consumer>\n)\n\nToastConsumer.propTypes = {\n children: PropTypes.func.isRequired,\n}\n\n// eslint-disable-next-line react/display-name\nconst withToast = WrappedComponent => props => (\n <ToastConsumer>\n {({ showToast, hideToast, toastState }) => (\n <WrappedComponent\n showToast={showToast}\n hideToast={hideToast}\n toastState={toastState}\n {...props}\n />\n )}\n </ToastConsumer>\n)\n\nexport { ToastContext, ToastProvider, ToastConsumer, withToast }\n\n```"
}
] |
code_store-on-localhost_f308076d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ToastProvider/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### Toasts give users instant feedback about the tasks they just did. Its main objective is to ensure tasks confirmation and success.\n\n### ๐ Dos\n- Toasts are always self-dismissing, but users should be allowed to dismiss by themselves as well.\n- Keep messages in a low to mild priority spectrum. Toasts are intended to be either neutral or positive.\n\n### ๐ Don'ts\n- Do not present critical or high priority actions on a Toast. If that's the case, you might consider using [Alerts](#alert) instead.\n- Due to its low to mild priority usage and dismissability, warning and error semantic styles do not apply to Toasts.\n\n\n```js\nimport { useState } from 'react'\nconst Button = require('../Button').default\nconst ToastConsumer = require('./index').ToastConsumer\n\nconst App = () => (\n // Wrap the entire application on a toast provider\n <ToastProvider\n positioning=\"window\"\n >\n <Content/>\n </ToastProvider>\n)\n\nconst Content = () => {\n const [count, setCount] = useState(0)\n return(\n // Wrap the components that are going to display toasts\n // on a ToastConsumer, with a function as a child, as\n // the example below:\n <div>\n <div className=\"mb5\">\n Click on a button to show the corresponding toast\n </div>\n <div className=\"mb8\">\n <ToastConsumer>\n { ({ showToast }) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={() => showToast('Your toast is ready')}>\n Short text\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'The bread has been inserted into the toaster',\n action: {\n label:'Undo',\n onClick: () =>\n alert('Bread removed from toaster'),\n },\n })\n }\n >\n With action\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'The toast is done, with a layer of butter on top, along with a nice cup of coffee.',\n action: {\n label: 'Thanks',\n onClick: () => {},\n }\n })\n }\n >\n Long text\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </div>\n\n <div className=\"mb5\">\n Toast duration and control\n </div>\n <div className=\"mb8\">\n <ToastConsumer>\n {({showToast, hideToast}) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'This message lasts 30 seconds',\n duration: 30000,\n })\n }\n >\n 30 seconds\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'This message stays here until closed',\n duration: Infinity,\n })\n }\n >\n Permanent\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'This message stays here until closed programatically',\n dismissable: false,\n })\n }\n >\n Undismissable\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"danger\"\n onClick={hideToast}\n >\n Close all toasts\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </div>\n\n <div className=\"mb5\">\n Toast position\n </div>\n <div className=\"mb8\">\n <ToastConsumer>\n {({showToast, hideToast}) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'Everything you own in the box to the left',\n duration: 3000,\n horizontalPosition: 'left'\n })\n }\n >\n To the left, to the left\n </Button>\n </div>\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'All right all right all right',\n duration: 3000,\n horizontalPosition: 'right'\n })\n }\n >\n All right\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </div>\n\n <div className=\"mb5\">\n Link on toast action\n </div>\n <ToastConsumer>\n {({showToast, hideToast}) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => showToast({\n message: 'Item added to cart',\n duration: 8000,\n action: {\n label: 'See cart',\n href: 'http://vtex.com',\n target: '_blank'\n }\n })\n }\n >\n Add to cart\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n <div className=\"mv5 mt8\">\n Link on toast action\n </div>\n <ToastConsumer>\n {({showToast, hideToast}) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={\n () => {\n setCount(count => count + 1)\n showToast({\n message: `You clicked ${count} times`,\n keepAfterUpdate: true,\n duration: 5000,\n })\n }\n }\n >\n One more in same Toast\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </div>\n)\n}\n\n\n;<App/>\n\n```\n\n```js\n const withToast = require('./index').withToast\n const Input = require('../Input').default\n const debounce = require('lodash/debounce')\n\n class App extends React.Component {\n constructor(props){\n super(props)\n\n this.state = {\n value: '',\n }\n\n this.handleInputChange = this.handleInputChange.bind(this)\n this.showToast = debounce(this.showToast.bind(this), 300)\n }\n\n handleInputChange(event) {\n this.setState({ value: event.currentTarget.value })\n }\n\n componentDidUpdate(_, prevState) {\n const { value } = this.state\n if ( prevState.value !== this.state.value ) {\n if (value === ''){\n this.showToast('The text has been erased')\n } else {\n this.showToast(`You typed: โ${this.state.value}โ`)\n }\n }\n }\n\n showToast(message) {\n this.props.showToast({ message })\n }\n\n render() {\n const {value} = this.state\n return (\n <React.Fragment>\n <div className=\"mb6\">\n <h3>Higher-order component</h3>\n For use on component lifecycle methods (componentDidMount, componentDidUpdate, etc)\n </div>\n <Input\n value={value}\n label=\"Write something below to display a toast\"\n onChange={this.handleInputChange}\n placeholder=\"Type here\"\n />\n </React.Fragment>\n )\n }\n }\n\n const AppWithToast = withToast(App)\n\n\n ;<ToastProvider positioning=\"window\">\n <AppWithToast />\n </ToastProvider>\n```\n\n```"
}
] |
code_store-on-localhost_f96a62c0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ToastProvider/ToastManager.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'\nimport isString from 'lodash/isString'\n\nimport Toast from './Toast'\n\nexport default class ToastManager extends Component {\n constructor(props) {\n super(props)\n\n this.container = React.createRef()\n }\n\n state = {\n currentToast: null,\n nextToast: null,\n isToastVisible: false,\n }\n\n showToast = args => {\n if (isString(args)) {\n args = { message: args }\n }\n const {\n message = '',\n action,\n dismissable,\n duration,\n horizontalPosition = 'left',\n keepAfterUpdate = false,\n } = args\n\n if (this.state.currentToast && !keepAfterUpdate) {\n // If there is a toast present already, queue up the next toast\n // It will be displayed when the current toast is closed, on handleToastClose\n this.setState({\n nextToast: {\n message,\n action,\n dismissable,\n duration,\n horizontalPosition,\n },\n })\n this.hideToast()\n } else {\n this.setState({\n currentToast: {\n message,\n action,\n dismissable,\n duration,\n horizontalPosition,\n keepAfterUpdate,\n },\n isToastVisible: true,\n })\n }\n }\n\n hideToast = () => {\n this.setState({\n isToastVisible: false,\n })\n }\n\n handleToastClose = () => {\n this.setState(state => {\n return {\n // If there is a toast queued up, shows it.\n // Otherwise, nextToast will be null, and state.toast will be cleared up\n currentToast: state.nextToast,\n isToastVisible: !!state.nextToast,\n nextToast: null,\n state: state.horizontalPosition,\n }\n })\n }\n\n getParentBounds = () => {\n const parentContainer =\n this.container.current && this.container.current.parentNode\n return (\n parentContainer &&\n parentContainer.getBoundingClientRect &&\n parentContainer.getBoundingClientRect()\n )\n }\n\n updateContainerBounds = () => {\n const windowBounds = {\n left: 0,\n right: window.innerWidth,\n top: 0,\n bottom: window.innerHeight,\n }\n\n const bounds =\n (this.props.positioning === 'parent' && this.getParentBounds()) ||\n windowBounds\n\n if (this.container.current) {\n this.container.current.style.left = `${bounds.left}px`\n this.container.current.style.right = `${window.innerWidth -\n bounds.right}px`\n this.container.current.style.top = `${bounds.top}px`\n this.container.current.style.bottom = `${Math.max(\n 0,\n window.innerHeight - bounds.bottom\n )}px`\n }\n }\n\n componentDidUpdate() {\n this.updateContainerBounds()\n }\n\n render() {\n const { children } = this.props\n const { currentToast } = this.state\n\n return (\n <Fragment>\n {children({\n showToast: this.showToast,\n hideToast: this.hideToast,\n state: this.state,\n })}\n <div\n className=\"fixed z-max overflow-hidden\"\n ref={this.container}\n style={{\n pointerEvents: 'none',\n }}>\n {currentToast && (\n <Toast\n message={currentToast.message}\n action={currentToast.action}\n duration={currentToast.duration}\n dismissable={currentToast.dismissable}\n horizontalPosition={currentToast.horizontalPosition}\n keepAfterUpdate={currentToast.keepAfterUpdate}\n visible={this.state.isToastVisible}\n onClose={this.handleToastClose}\n />\n )}\n </div>\n </Fragment>\n )\n }\n}\n\nToastManager.propTypes = {\n positioning: PropTypes.oneOf(['parent', 'window']),\n children: PropTypes.func.isRequired,\n}\n\n```"
}
] |
code_store-on-localhost_393f42b9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ToastProvider/Toast.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 CloseIcon from '../icon/Close'\nimport Button from '../Button'\n\nconst nextFrame = callback => {\n const FRAME_DURATION = 16\n setTimeout(callback, FRAME_DURATION)\n}\n\nconst DURATION_BASE = 3000\nconst DURATION_INCREMENT = 30\nconst DURATION_ACTION_INCREMENT = 2000\nconst TRANSITION_DURATION = 160\n\nexport default class Toast extends Component {\n static defaultProps = {\n dismissable: true,\n }\n\n constructor(props) {\n super(props)\n this.state = {\n isOpen: false,\n isSingleLine: false,\n }\n this.messageElement = React.createRef()\n this.buttonElement = React.createRef()\n }\n\n componentDidMount() {\n if (this.props.visible) {\n // sets the open state on the next frame\n // so the opening transition will run\n nextFrame(() => this.open())\n\n this.startAutoClose()\n }\n this.updateButtonWrap()\n }\n\n // Duration increases along with the length of the message\n getDefaultDuration = () =>\n DURATION_BASE +\n this.props.message.length * DURATION_INCREMENT +\n (this.props.action ? DURATION_ACTION_INCREMENT : 0)\n\n startAutoClose = () => {\n this.stopAutoClose()\n const { duration } = this.props\n\n if (duration <= 0 || duration === Infinity) {\n return\n }\n\n this.autoCloseTimeout = setTimeout(\n this.close,\n this.props.duration || this.getDefaultDuration()\n )\n }\n\n stopAutoClose = () => {\n if (this.autoCloseTimeout == null) return\n\n clearTimeout(this.autoCloseTimeout)\n this.autoCloseTimeout = null\n }\n\n handleMouseOver = () => {\n this.stopAutoClose()\n }\n\n handleMouseOut = () => {\n this.startAutoClose()\n }\n\n handleCloseClick = () => {\n this.close()\n }\n\n open = () => {\n this.setState({\n isOpen: true,\n })\n }\n\n close = () => {\n if (!this.state.isOpen) {\n return\n }\n this.stopAutoClose()\n\n setTimeout(() => {\n this.props.onClose()\n }, TRANSITION_DURATION)\n\n this.setState({\n isOpen: false,\n })\n }\n\n handleActionClick = e => {\n const { isOpen } = this.state\n if (!isOpen) return\n\n const { action } = this.props\n const actionHandler = action && action.onClick\n\n if (actionHandler) {\n actionHandler(e)\n }\n\n this.close()\n }\n\n componentDidUpdate(prevProps) {\n if (!this.props.visible && prevProps.visible) {\n this.close()\n } else if (this.props.visible && !prevProps.visible) {\n this.open()\n this.startAutoClose()\n }\n if (\n this.props.message !== prevProps.message ||\n (this.props.visible && !prevProps.visible)\n ) {\n this.updateButtonWrap()\n }\n\n if (this.props.keepAfterUpdate) {\n this.startAutoClose()\n }\n }\n\n // Lets the toast to be single line on mobile\n // if the message is short enough\n updateButtonWrap() {\n this.setState(\n {\n isSingleLine: false,\n },\n () => {\n const messageWidth = this.getElementWidth(this.messageElement)\n const buttonWidth = this.getElementWidth(this.buttonElement)\n const windowWidth = window.innerWidth || 0\n const threshold = 75\n\n if (messageWidth != null && buttonWidth != null) {\n if (messageWidth + buttonWidth <= windowWidth - threshold) {\n this.setState({\n isSingleLine: true,\n })\n }\n }\n }\n )\n }\n\n getElementWidth(ref) {\n const element = ref && ref.current\n const bounds =\n element &&\n element.getBoundingClientRect &&\n element.getBoundingClientRect()\n return bounds && bounds.width\n }\n\n render() {\n const { isOpen, isSingleLine } = this.state\n const { action, dismissable, horizontalPosition, message } = this.props\n const hasAction = !!(\n action &&\n action.label &&\n (action.onClick || action.href)\n )\n\n return (\n <div\n className={`vtex-toast-container absolute bottom-0 ${horizontalPosition}-0 z-5 ma7-ns mb0-s w-100 w-auto-ns mw6-m mw-40-l`}\n onMouseOver={this.handleMouseOver}\n onMouseOut={this.handleMouseOut}\n style={{\n pointerEvents: 'all',\n transition: `transform ${TRANSITION_DURATION}ms ${\n isOpen ? 'ease-out' : 'ease-in'\n }`,\n transform: `translate3d(0, ${isOpen ? 0 : '170%'}, 0)`,\n minWidth: '18rem',\n }}>\n <div className=\"vtex-toast flex justify-between items-start items-center-ns t-body bg-base--inverted c-on-base--inverted pa5 br2-ns shadow-5\">\n <div className={`${isSingleLine ? 'flex' : 'flex-ns'} flex-grow-1`}>\n <div className=\"flex items-center flex-grow-1\">\n <div className=\"pr5 mw6-ns lh-copy\" ref={this.messageElement}>\n {message}\n </div>\n </div>\n\n {hasAction && (\n <div className=\"flex flex-grow-1 justify-end items-center\">\n <div className={`${isSingleLine ? 'nt4' : 'nt4-ns'} nb4`}>\n <Button\n ref={this.buttonElement}\n variation=\"inverted-tertiary\"\n href={action.href}\n target={action.target}\n rel={action.rel}\n download={action.download}\n onClick={this.handleActionClick}>\n {action.label}\n </Button>\n </div>\n </div>\n )}\n </div>\n {dismissable && (\n <div className=\"pt2 pt0-ns\">\n <div\n className=\"vtex-alert__close-icon pointer flex items-center pa3 white nr3 nv3\"\n onClick={this.handleCloseClick}>\n <CloseIcon color=\"currentColor\" size={16} />\n </div>\n </div>\n )}\n </div>\n </div>\n )\n }\n}\n\nToast.propTypes = {\n onClose: PropTypes.func.isRequired,\n message: PropTypes.string.isRequired,\n horizontalPosition: PropTypes.oneOf(['left', 'right']),\n action: PropTypes.shape({\n label: PropTypes.string.isRequired,\n onClick: PropTypes.func,\n href: PropTypes.string,\n target: PropTypes.string,\n rel: PropTypes.string,\n download: PropTypes.string,\n }),\n keepAfterUpdate: PropTypes.string,\n visible: PropTypes.bool,\n duration: PropTypes.number,\n dismissable: PropTypes.bool,\n}\n\n```"
}
] |
code_store-on-localhost_021dc1d0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Pagination/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 CaretLeft from '../icon/CaretLeft'\nimport CaretRight from '../icon/CaretRight'\nimport ButtonWithIcon from '../ButtonWithIcon'\nimport Dropdown from '../Dropdown'\nimport PageIndicator from './PageIndicator'\n\nconst caretLeft = <CaretLeft />\nconst caretRight = <CaretRight />\n\nclass Pagination extends PureComponent {\n constructor(props) {\n super(props)\n this.state = {\n selectedRowsOptionIndex: 0,\n }\n }\n\n handleRowsChange = (e, value) => {\n const { rowsOptions } = this.props\n const optionIndex = rowsOptions.indexOf(parseInt(value, 10))\n this.setState({ selectedRowsOptionIndex: optionIndex })\n this.props.onRowsChange && this.props.onRowsChange(e, value)\n }\n\n handlePrevPage = e => {\n this.props.onPrevClick && this.props.onPrevClick(e)\n }\n\n handleNextPage = e => {\n this.props.onNextClick && this.props.onNextClick(e)\n }\n\n createRowOptions = rowsOptions => {\n if (rowsOptions) {\n const opts = []\n rowsOptions.forEach(o => opts.push({ label: o, value: o }))\n return opts\n }\n return null\n }\n\n render() {\n const {\n rowsOptions,\n totalItems,\n currentItemFrom,\n currentItemTo,\n textOf,\n textShowRows,\n selectedOption,\n hasPageTopIndicator,\n itemLabel,\n testIds,\n } = this.props\n const { selectedRowsOptionIndex } = this.state\n\n const dropdownOptions = this.createRowOptions(rowsOptions)\n\n const isPrevDisabled = currentItemFrom <= 1\n const isNextDisabled = currentItemTo >= totalItems\n\n const itemTo = currentItemTo > totalItems ? totalItems : currentItemTo\n\n return (\n <div className=\"flex flex-column\">\n {hasPageTopIndicator && (\n <div className=\"mt2 mb5\">\n <PageIndicator\n currentItemFrom={currentItemFrom}\n itemTo={itemTo}\n textOf={textOf}\n totalItems={totalItems}\n itemLabel={itemLabel}\n />\n </div>\n )}\n {this.props.children}\n <div\n className={classNames([\n 'flex flex-row items-center',\n {\n 'justify-between': rowsOptions,\n 'justify-end': !rowsOptions,\n },\n ])}>\n {dropdownOptions && (\n <div className=\"flex flex-row pt5 items-baseline\">\n <span className=\"mr4 c-muted-2 t-small self-center\">\n {textShowRows}\n </span>\n <Dropdown\n size=\"small\"\n options={dropdownOptions}\n selectTestId={testIds.rowsOptions}\n value={\n selectedOption ||\n dropdownOptions[selectedRowsOptionIndex].label\n }\n onChange={this.handleRowsChange}\n />\n </div>\n )}\n\n <div className=\"flex flex-row pt5 items-center\">\n <PageIndicator\n currentItemFrom={currentItemFrom}\n itemTo={itemTo}\n textOf={textOf}\n totalItems={totalItems}\n testId={testIds.pageIndicator}\n />\n <div className=\"ml4\">\n <ButtonWithIcon\n icon={caretLeft}\n variation=\"secondary\"\n size=\"small\"\n disabled={isPrevDisabled}\n onClick={this.handlePrevPage}\n testId={testIds.prevBtn}\n />\n </div>\n <div className=\"ml2\">\n <ButtonWithIcon\n icon={caretRight}\n variation=\"secondary\"\n size=\"small\"\n disabled={isNextDisabled}\n onClick={this.handleNextPage}\n testId={testIds.nextBtn}\n />\n </div>\n </div>\n </div>\n </div>\n )\n }\n}\n\nPagination.defaultProps = {\n rowsOptions: null,\n hasPageTopIndicator: false,\n testIds: {},\n}\n\nPagination.propTypes = {\n children: PropTypes.node,\n\n rowsOptions: PropTypes.array,\n currentItemFrom: PropTypes.number.isRequired,\n currentItemTo: PropTypes.number.isRequired,\n textOf: PropTypes.node.isRequired,\n textShowRows: PropTypes.node.isRequired,\n totalItems: PropTypes.number.isRequired,\n itemLabel: PropTypes.string,\n /**\n * Use this prop if you want to control the number of rows selected, instead of leaving it to the Pagination component.\n */\n selectedOption: PropTypes.number,\n\n onRowsChange: PropTypes.func,\n onNextClick: PropTypes.func,\n onPrevClick: PropTypes.func,\n\n hasPageTopIndicator: PropTypes.bool,\n\n testIds: PropTypes.shape({\n rowsOptions: PropTypes.string,\n prevBtn: PropTypes.string,\n nextBtn: PropTypes.string,\n pageIndicator: PropTypes.string,\n }),\n}\n\nexport default Pagination\n\n```"
}
] |
code_store-on-localhost_aba61194
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Pagination/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n```js\n <div>\n <Pagination\n rowsOptions={[5,10,15,20]}\n currentItemFrom={1}\n currentItemTo={10}\n textOf=\"de\"\n textShowRows=\"show rows\"\n totalItems={20}\n />\n </div>\n```\n\n```"
}
] |
code_store-on-localhost_30c4ee73
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Pagination/PageIndicator.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\nfunction PageIndicator({\n currentItemFrom,\n itemTo,\n textOf,\n totalItems,\n itemLabel,\n testId,\n}) {\n return (\n <div className=\"c-muted-2 t-small\" data-testid={testId}>\n {`${currentItemFrom} - ${itemTo} `}\n {textOf} {totalItems} {itemLabel}\n </div>\n )\n}\n\nPageIndicator.defaultProps = {\n itemLabel: '',\n}\n\nPageIndicator.propTypes = {\n currentItemFrom: PropTypes.number.isRequired,\n itemTo: PropTypes.number.isRequired,\n textOf: PropTypes.string.isRequired,\n totalItems: PropTypes.node.isRequired,\n itemLabel: PropTypes.node,\n testId: PropTypes.string,\n}\n\nexport default PageIndicator\n\n```"
}
] |
code_store-on-localhost_eeb88676
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/TimePicker/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 DatePicker from '../DatePicker'\nimport IconClock from '../icon/Clock'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nfunction TimePicker(props) {\n return (\n <DatePicker\n {...props}\n ref={props.forwardedRef}\n timeIntervals={props.interval}\n prefix={<IconClock />}\n useTimeOnly\n />\n )\n}\n\nTimePicker.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 /** 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 /** 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 /** Times to be included */\n includeTimes: PropTypes.arrayOf(PropTypes.instanceOf(Date)),\n /** Interval between times */\n interval: PropTypes.oneOf([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60]),\n /** Label */\n label: PropTypes.string,\n /** Locale string ('en-US', 'pt-BR', ...) */\n locale: PropTypes.string.isRequired,\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 /** Spec attribute */\n readOnly: PropTypes.bool,\n /** Spec attribute */\n required: PropTypes.bool,\n /** TimePicker size */\n size: PropTypes.oneOf(['small', 'regular', 'large']),\n /** Spec attribute */\n tabIndex: PropTypes.string,\n /** Interval between times (in min) */\n intervals: PropTypes.number,\n /** Value of the selected time */\n value: PropTypes.instanceOf(Date).isRequired,\n}\n\nexport default withForwardedRef(TimePicker)\n\n```"
}
] |
code_store-on-localhost_5fb4117a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/TimePicker/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### A TimePicker lets the user select a single time.\n\n### ๐ Don'ts\n\n- Time suggestions should help the user to find an option more easily given its context of use (per hour, every half hour, 15 minutes, etc.) so we do not recommend using intervals shorter than 5 minutes.\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\nSimple _TimePicker_\n\n```js\ninitialState = { date1: undefined, date2: undefined, date3: undefined }\n;<div>\n <div className=\"mb5\">\n <TimePicker\n label=\"Small\"\n size=\"small\"\n placeholder=\"Select a time or type a custom one...\"\n value={state.date1}\n onChange={date => setState({ date1: date })}\n locale=\"pt-BR\"\n />\n </div>\n <div className=\"mb5\">\n <TimePicker\n label=\"Regular\"\n placeholder=\"Select a time or type a custom one...\"\n value={state.date2}\n onChange={date => setState({ date2: date })}\n locale=\"pt-BR\"\n />\n </div>\n <div className=\"mb5\">\n <TimePicker\n label=\"Large\"\n placeholder=\"Select a time or type a custom one...\"\n size=\"large\"\n value={state.date3}\n onChange={date => setState({ date3: date })}\n locale=\"pt-BR\"\n />\n </div>\n</div>\n```\n\nLocale\n\n```js\nconst RadioGroup = require('../RadioGroup').default\ninitialState = { locale: 'pt-BR', date: undefined }\n;<div>\n <div className=\"mb5\">\n <RadioGroup\n name=\"locale\"\n label=\"Choose locale for DateTimePicker\"\n options={[\n { value: 'pt-BR', label: 'pt-BR' },\n { value: 'en-US', label: 'en-US' },\n { value: 'en-GB', label: 'en-GB' },\n { value: 'es', label: 'es' },\n ]}\n value={state.locale}\n onChange={e => setState({ locale: e.target.value })}\n />\n </div>\n <div className=\"mb5\">\n <TimePicker\n placeholder=\"Select a time or type a custom one...\"\n locale={state.locale}\n value={state.date}\n onChange={date => setState({ date })}\n />\n </div>\n</div>\n```\n\nUsing ref\n\n```js\nconst Button = require('../Button').default\ninitialState = { date: undefined }\nconst ref = React.createRef()\n;<div>\n <div className=\"mb5\">\n <TimePicker\n ref={ref}\n label=\"Click in the button below to focus on this TimePicker\"\n placeholder=\"Select a time or type a custom one...\"\n value={state.date}\n onChange={date => setState({ date })}\n locale=\"pt-BR\"\n />\n </div>\n\n <div className=\"mb5\">\n <Button onClick={() => ref.current.setFocus()}>Focus!</Button>\n </div>\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_478ff115
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/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, { FC, cloneElement, Children } from 'react'\n\nimport TooltipPopup, { Position, Size } from './TooltipPopup'\nimport { useTooltip, Trigger } from './hooks'\n\nconst propTypes = {\n /** Label to be shown. As element, can be a string, number...*/\n label: PropTypes.node.isRequired,\n /** Tooltip position */\n position: PropTypes.oneOf<Position>(['top', 'right', 'bottom', 'left']),\n /** Tooltip font size */\n size: PropTypes.oneOf<Size>(['mini', 'small']),\n /** Fallback position. Used when the tooltip cannot be shown in the original position */\n fallbackPosition: PropTypes.oneOf<Position>([\n 'top',\n 'right',\n 'bottom',\n 'left',\n ]),\n /** Event to trigger the tooltip */\n trigger: PropTypes.oneOf<Trigger>(['click', 'hover', 'focus']),\n /** Element that will trigger the event */\n children: PropTypes.element.isRequired,\n /** Delay to show and hide the tooltip (ms) */\n delay: PropTypes.number,\n /** Tooltip animation duration (ms) */\n duration: PropTypes.number,\n /** Tooltip timming function used to animate the tooltip */\n timmingFn: PropTypes.string,\n}\n\ntype Props = PropTypes.InferProps<typeof propTypes>\n\nconst defaultProps: Props = {\n trigger: 'hover',\n position: 'top',\n size: 'small',\n delay: 0,\n duration: 200,\n timmingFn: 'ease-in-out',\n}\n\nconst Tooltip: FC<Props> = ({ trigger, children, ...popupProps }) => {\n const [handleTooltip, tooltip] = useTooltip({ trigger })\n const child = Children.only(children)\n return (\n <>\n <TooltipPopup {...tooltip} {...popupProps} />\n {cloneElement(child, handleTooltip(child))}\n </>\n )\n}\n\nTooltip.propTypes = propTypes\nTooltip.defaultProps = defaultProps\n\nexport default Tooltip\n\n```"
}
] |
code_store-on-localhost_a8b38648
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/tooltip.css from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.popup {\n max-height: 11rem;\n will-change: transform;\n}\n\n\n```"
}
] |
code_store-on-localhost_7c64d0bd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/TooltipPopup.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, { FC, useEffect, useRef, useState } from 'react'\n\nimport Portal from './Portal'\nimport { useRect } from './hooks'\nimport zIndex from '../utils/zIndex'\nimport style from './tooltip.css'\n\nexport type Position = 'top' | 'right' | 'bottom' | 'left'\nexport type Size = 'mini' | 'small'\n\nconst OFFSET = 8\nconst hasComputedDimensions = rect => rect && rect.width && rect.height\n\nfunction getChildRefPropType() {\n if (typeof HTMLElement !== 'undefined') {\n return PropTypes.shape({ current: PropTypes.instanceOf(HTMLElement) })\n }\n return PropTypes.shape({ current: PropTypes.elementType })\n}\n\nconst propTypes = {\n /** Tooltip content */\n label: PropTypes.node.isRequired,\n /** Tooltip position */\n position: PropTypes.oneOf<Position>(['top', 'bottom', 'left', 'right']),\n /** Tooltip font size */\n size: PropTypes.oneOf<Size>(['mini', 'small']),\n /** Fallback position (when the tooltip cannot appear in the original position) */\n fallbackPosition: PropTypes.oneOf<Position>([\n 'top',\n 'bottom',\n 'left',\n 'right',\n ]),\n /** Boolean to see if the popup should appear */\n visible: PropTypes.bool,\n /** Delay to show the tooltip */\n delay: PropTypes.number,\n /** Tooltip animation duration */\n duration: PropTypes.number,\n /** Tooltip timming function used to animate the tooltip */\n timmingFn: PropTypes.string,\n /** Child ref. Used to correctly position the tooltip */\n childRef: getChildRefPropType(),\n}\n\nconst defaultProps = {\n visible: false,\n}\n\nconst TooltipPopup: FC<PropTypes.InferProps<typeof propTypes>> = ({\n position,\n size,\n fallbackPosition,\n label,\n visible,\n delay,\n duration,\n timmingFn,\n childRef,\n}) => {\n const [showPopup, setShowPopup] = useState(visible)\n const popupRef = useRef<HTMLDivElement>()\n const childRect = useRect(childRef, visible)\n const popupRect = useRect(popupRef, visible)\n\n useEffect(() => {\n if (visible) {\n setShowPopup(true)\n }\n }, [visible])\n\n const popupClasses = classNames(\n 'absolute pv3 ph4 bg-base--inverted c-on-base--inverted br2 shadow-4 mw5 overflow-hidden',\n style.popup,\n {\n dn: !visible || !showPopup || !childRect || !popupRect,\n 'o-0': !visible || !hasComputedDimensions(popupRect),\n 'o-100': visible && hasComputedDimensions(popupRect),\n 't-mini': size === 'mini',\n 't-small': size === 'small',\n }\n )\n\n const positionStyle = getStyles(\n childRect,\n popupRect,\n position,\n fallbackPosition\n )\n\n return (\n <Portal>\n <div\n role=\"tooltip\"\n className={popupClasses}\n style={{\n ...positionStyle,\n zIndex: zIndex.tooltip,\n transition: `opacity ${duration}ms ${timmingFn} ${delay}ms`,\n }}\n ref={popupRef}\n onTransitionEnd={() => setShowPopup(visible)}>\n {label}\n </div>\n </Portal>\n )\n}\n\nconst getStyles = (childRect, popupRect, position, fallbackPosition) => {\n return childRect && popupRect && window && hasComputedDimensions(popupRect)\n ? getPopupPosition(childRect, popupRect, position, fallbackPosition)\n : { top: 0, left: 0 }\n}\n\nconst FALLBACK_POSITION = {\n top: 'right',\n right: 'bottom',\n bottom: 'left',\n left: 'top',\n}\n\nconst getFallbackPosition = (position, fallback) =>\n fallback || FALLBACK_POSITION[position]\n\nconst getPopupPosition = (childRect, popupRect, position, fallbackPosition) =>\n getPopupPositionRecursively(\n childRect,\n popupRect,\n position,\n fallbackPosition,\n position\n )\nconst getPopupPositionRecursively = (\n childRect,\n popupRect,\n position,\n fallbackPosition,\n originalPosition\n) => {\n const horizontalMax = window.innerWidth + window.pageXOffset\n const verticalMax = window.innerHeight + window.pageYOffset\n const styles = {\n left:\n childRect.left +\n window.pageXOffset +\n (childRect.width - popupRect.width) / 2 +\n (position === 'right'\n ? (childRect.width + popupRect.width) / 2 + OFFSET\n : 0) -\n (position === 'left'\n ? (childRect.width + popupRect.width) / 2 + OFFSET\n : 0),\n top:\n childRect.top +\n window.pageYOffset -\n (position === 'top' ? popupRect.height + OFFSET : 0) +\n (position === 'bottom' ? childRect.height + OFFSET : 0) +\n (position === 'right' || position === 'left'\n ? (childRect.height - popupRect.height) / 2\n : 0),\n }\n\n const collisions = {\n top: styles.top < window.pageYOffset,\n right: styles.left + popupRect.width > horizontalMax,\n bottom: styles.top + popupRect.height > verticalMax,\n left: styles.left < window.pageXOffset,\n }\n\n if (collisions[position]) {\n fallbackPosition = getFallbackPosition(position, fallbackPosition)\n // If there is no place without collisions, it will not be shown\n return fallbackPosition === originalPosition\n ? null\n : getPopupPositionRecursively(\n childRect,\n popupRect,\n fallbackPosition,\n null,\n originalPosition\n )\n }\n\n const top = Math.max(\n window.pageYOffset + 1,\n Math.min(styles.top, verticalMax - popupRect.height - 1)\n )\n const left = Math.max(\n window.pageXOffset + 1,\n Math.min(styles.left, horizontalMax - popupRect.width - 1)\n )\n\n const transform = `translate3d(${Math.round(left)}px, ${Math.round(\n top - document.body.offsetHeight\n )}px, 0)`\n\n return {\n transform,\n WebkitTransform: transform,\n }\n}\n\nTooltipPopup.propTypes = propTypes\nTooltipPopup.defaultProps = defaultProps\n\nexport default TooltipPopup\n\n```"
}
] |
code_store-on-localhost_03d1d0c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### Tooltips are a small informative text that appear when an item is being, hovered, focused or touched.\n\n### ๐ Dos\n\n- Do use tooltips when you want to add a label to an specific icon.\n- Do use tooltips when you want to add an informative text in situations where more clarification may be needed.\n\n### ๐ Don'ts\n\n- Don't change the tooltip colors.\n- Don't use long texts in tooltips - a good character limit is 220.\n\n#### Positioning tooltip\n\nThe position where the tooltip appears can be set and its fallback position too. By default the tooltip appears at the top and follows clockwise.\n\n```jsx\nconst Button = require('../Button').default\n\n;<div className=\"flex w-100 justify-between\">\n <Tooltip label=\"Tooltip text\">\n <Button variation=\"tertiary\">Top</Button>\n </Tooltip>\n <Tooltip label=\"Tooltip text\" position=\"left\">\n <Button variation=\"tertiary\">Left</Button>\n </Tooltip>\n <Tooltip label=\"Tooltip text\" position=\"right\">\n <Button variation=\"tertiary\">Right</Button>\n </Tooltip>\n <Tooltip label=\"Tooltip text\" position=\"bottom\">\n <Button variation=\"tertiary\">Bottom</Button>\n </Tooltip>\n</div>\n```\n\n#### Label and Informative text\n\n```jsx\nconst Edit = require('../icon/Edit').default\nconst Info = require('../icon/Info').default\n\n;<div className=\"flex w-100 justify-center items-center\">\n <div className=\"ph9\">\n <Tooltip label=\"Edit\">\n <span className=\"c-on-base pointer\">\n <Edit />\n </span>\n </Tooltip>\n </div>\n <div className=\"ph9\">\n <Tooltip label=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\">\n <span className=\"c-on-base pointer\">\n <Info />\n </span>\n </Tooltip>\n </div>\n</div>\n```\n\n#### Hover vs Focused\n\n```jsx\nconst Button = require('../Button').default\n\n;<div className=\"flex w-100 items-center justify-center\">\n <div className=\"pa3\">\n <Tooltip label=\"Tooltip text\">\n <Button variation=\"tertiary\">Hover</Button>\n </Tooltip>\n </div>\n <div className=\"pa3\">\n <Tooltip label=\"Tooltip text\" trigger=\"focus\">\n <Button variation=\"tertiary\">Focused</Button>\n </Tooltip>\n </div>\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_96653b83
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/Portal.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'\nimport ReactDOM from 'react-dom'\n\nimport { setRef } from '../utils/react'\n\nfunction getContainer(container: any) {\n container = typeof container === 'function' ? container() : container\n // eslint-disable-next-line react/no-find-dom-node\n return ReactDOM.findDOMNode(container)\n}\n\nconst useEnhancedEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nconst propTypes = {\n /**\n * The children to render into the `container`.\n */\n children: PropTypes.node,\n /**\n * A node, component instance, or function that returns either.\n * The `container` will have the portal children appended to it.\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes.oneOfType([\n PropTypes.func,\n PropTypes.instanceOf(React.Component),\n PropTypes.instanceOf(typeof Element === 'undefined' ? Object : Element),\n ]),\n /**\n * Callback fired once the children has been mounted into the `container`.\n */\n onRendered: PropTypes.func,\n}\n\n/**\n * Portals provide a first-class way to render children into a DOM node\n * that exists outside the DOM hierarchy of the parent component.\n */\nconst Portal = (props: PropTypes.InferProps<typeof propTypes>, ref) => {\n const { children, container, onRendered } = props\n const [mountNode, setMountNode] = React.useState(null)\n\n useEnhancedEffect(() => {\n setMountNode(getContainer(container) || document.body)\n }, [container])\n\n useEnhancedEffect(() => {\n if (mountNode) {\n setRef(ref, mountNode)\n return () => {\n setRef(ref, null)\n }\n }\n\n return undefined\n }, [ref, mountNode])\n\n useEnhancedEffect(() => {\n if (onRendered && mountNode) {\n onRendered()\n }\n }, [onRendered, mountNode])\n\n return mountNode ? ReactDOM.createPortal(children, mountNode) : mountNode\n}\n\nPortal.propTypes = propTypes\n\nexport default React.forwardRef<\n HTMLElement,\n PropTypes.InferProps<typeof propTypes>\n>(Portal as any)\n\n```"
}
] |
code_store-on-localhost_24df5f2a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Tooltip/hooks.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport get from 'lodash/get'\nimport { RefObject, useState, useRef, useLayoutEffect } from 'react'\n\nimport observeRect from './utils/dom'\nimport { setRef } from '../utils/react'\n\nexport type Trigger = 'click' | 'hover' | 'focus'\n\nexport function useRect(nodeRef, observe = true) {\n const [rect, setRect] = useState(null)\n const observerRef = useRef(null)\n useLayoutEffect(() => {\n if (!observerRef.current && nodeRef.current) {\n observerRef.current = observeRect(nodeRef.current, setRect)\n }\n if (observerRef.current && observe) {\n observerRef.current.observe()\n }\n return () => observerRef.current && observerRef.current.unobserve()\n }, [observe, nodeRef])\n return rect\n}\n\nexport function useTooltip({\n trigger,\n}: {\n trigger?: Trigger\n} = {}): [\n (c: React.ReactElement) => object,\n { childRef: RefObject<HTMLElement>; visible: boolean }\n] {\n const childRef = useRef<HTMLElement>()\n const [visible, setVisible] = useState(false)\n const handleTooltip = (\n child: React.ReactElement & { ref?: RefObject<HTMLElement> }\n ) => {\n return {\n ref: node => {\n // Keep your own reference\n if (node) {\n setRef(childRef, node)\n }\n // Call the original ref, if any\n setRef(child.ref, node)\n },\n ...(trigger === 'hover'\n ? {\n onMouseEnter: (...args) => {\n setVisible(true)\n const onMouseEnter = get(child, 'props.onMouseEnter')\n if (onMouseEnter) {\n return onMouseEnter.call(child.props, ...args)\n }\n },\n onMouseLeave: (...args) => {\n setVisible(false)\n const onMouseLeave = get(child, 'props.onMouseLeave')\n if (onMouseLeave) {\n return onMouseLeave.call(child.props, ...args)\n }\n },\n }\n : {}),\n ...(trigger === 'click' || trigger === 'focus'\n ? {\n onClick: (...args) => {\n // Firefox and Safari, both on Mac OS, doesn't focus on click, like\n // Google Chrome does, so...\n if (childRef.current) {\n childRef.current.focus()\n }\n const onClick = get(child, 'props.onClick')\n if (onClick) {\n return onClick.call(child.props, ...args)\n }\n },\n onFocus: (...args) => {\n setVisible(true)\n const onFocus = get(child, 'props.onFocus')\n if (onFocus) {\n return onFocus.call(child.props, ...args)\n }\n },\n onBlur: (...args) => {\n setVisible(false)\n const onBlur = get(child, 'props.onBlur')\n if (onBlur) {\n return onBlur.call(child.props, ...args)\n }\n },\n }\n : {}),\n }\n }\n return [handleTooltip, { childRef, visible }]\n}\n\n```"
}
] |
code_store-on-localhost_771a3e07
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useMemo, useCallback, useEffect, useReducer, useState } from 'react'\nimport PropTypes from 'prop-types'\nimport isEmpty from 'lodash/isEmpty'\n\nimport { getFlat } from './util'\nimport { defaultComparatorCurry, ROOT_KEY, ROOT_VALUE } from './constants'\nimport { useCheckboxesInput, Tree } from './types'\nimport reducer, { ActionType } from './reducer'\n\nexport default function useCheckboxTree<T>({\n items,\n onToggle,\n nodesKey = 'children',\n checked = [],\n comparator = defaultComparatorCurry,\n isDisabled = (_: T | Tree<T>) => false,\n}: useCheckboxesInput<T>) {\n const [checkedItems, dispatch] = useReducer(reducer, checked)\n const [lastToggledItem, setLastToggledItem] = useState(null)\n\n const itemTree = useMemo(() => {\n return { [ROOT_KEY]: ROOT_VALUE, [nodesKey]: items }\n }, [items, nodesKey])\n\n const disabledItems = useMemo(() => {\n return getFlat(itemTree).filter(isDisabled)\n }, [isDisabled, itemTree])\n\n const toggle = useCallback(\n (item: T | Tree<T>): void => {\n if (!isDisabled(item)) {\n dispatch({\n type: ActionType.Toggle,\n itemToToggle: { item, nodesKey, comparator },\n isDisabled,\n })\n setLastToggledItem(item)\n }\n },\n [comparator, isDisabled, nodesKey]\n )\n\n useEffect(() => {\n onToggle && onToggle({ checkedItems, disabledItems, item: lastToggledItem })\n }, [checkedItems, disabledItems, lastToggledItem, onToggle, toggle])\n\n const toggleAll = useCallback(() => {\n toggle(itemTree)\n }, [itemTree, toggle])\n\n useEffect(() => {\n const shake = (tree: Tree<T>) => {\n const childNodes = tree[nodesKey] as Array<T>\n\n if (!childNodes || isEmpty(childNodes)) return\n\n const childrenChecked = childNodes\n .filter(childNode => !isDisabled(childNode))\n .every(childNode => checkedItems.some(comparator(childNode)))\n\n const rootChecked = checkedItems.some(comparator(tree))\n\n if (childrenChecked && !rootChecked && !isDisabled(tree))\n dispatch({ type: ActionType.Check, item: tree })\n\n if (!childrenChecked && rootChecked)\n dispatch({\n type: ActionType.Uncheck,\n itemToToggle: { item: tree, comparator },\n })\n\n childNodes.forEach(shake)\n }\n shake(itemTree)\n }, [checkedItems, toggle, itemTree, nodesKey, comparator, isDisabled])\n\n const isChecked = useCallback(\n (item: T | Tree<T>) => {\n const children = item[nodesKey]\n const onCheckedList = (item: T | Tree<T>) =>\n checkedItems.some(comparator(item))\n const notDisabled = (item: T | Tree<T>) => !isDisabled(item)\n\n const notDisabledChildren = children && children.filter(notDisabled)\n const notEmpty = !!notDisabledChildren && !isEmpty(notDisabledChildren)\n\n return notEmpty\n ? notDisabledChildren.every(onCheckedList)\n : checkedItems.some(comparator(item))\n },\n [checkedItems, comparator, isDisabled, nodesKey]\n )\n\n const isPartiallyChecked = useCallback(\n (item: T | Tree<T>) => {\n return (\n !isDisabled(item) &&\n item[nodesKey] &&\n getFlat(item, [], nodesKey)\n .slice(1)\n .some(child => checkedItems.some(comparator(child)))\n )\n },\n [checkedItems, comparator, isDisabled, nodesKey]\n )\n\n const allChecked = useMemo(() => {\n return isChecked(itemTree)\n }, [isChecked, itemTree])\n\n const someChecked = useMemo(() => {\n return checkedItems.length > 0\n }, [checkedItems])\n\n const allDisabled = useMemo(() => {\n return isDisabled(itemTree)\n }, [isDisabled, itemTree])\n\n const check = (item: T | Tree<T>) => {\n if (!isDisabled(item))\n dispatch({\n type: ActionType.BulkCheck,\n itemToToggle: { item, comparator, nodesKey },\n isDisabled,\n })\n }\n\n const checkAll = () => check(itemTree)\n\n const uncheck = useCallback(\n (item: T | Tree<T>) => {\n if (!isDisabled(item))\n dispatch({\n type: ActionType.BulkUncheck,\n itemToToggle: { item, comparator, nodesKey },\n })\n },\n [comparator, isDisabled, nodesKey]\n )\n\n const uncheckAll = useCallback(() => {\n uncheck(itemTree)\n }, [itemTree, uncheck])\n\n const setChecked = (checked: Array<T>) => {\n dispatch({ type: ActionType.SetChecked, checked })\n }\n\n return {\n checkedItems,\n isChecked,\n allChecked,\n allDisabled,\n someChecked,\n isPartiallyChecked,\n itemTree,\n toggle,\n toggleAll,\n check,\n checkAll,\n uncheck,\n uncheckAll,\n isDisabled,\n disabledItems,\n setChecked,\n lastToggledItem,\n }\n}\n\nexport const checkboxesPropTypes = {\n checkboxes: PropTypes.shape({\n checkedItems: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.string,\n })\n ),\n itemTree: PropTypes.shape({\n id: PropTypes.string,\n }),\n toggle: PropTypes.func,\n isChecked: PropTypes.func,\n isPartiallyChecked: PropTypes.func,\n }),\n}\n\n```"
}
] |
code_store-on-localhost_3ddb596a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n๐ก If you want a detailed explanation of each input/output, proceed to the `Detailed Props` section.\n\nThe `EXPERIMENTAL_useChecbokTree` is a hook to helps to hold state the state of checkboxes lists or trees. The following documentation exposes some examples of usage to give you an overview of how it works. To better structure our examples, let's imagine that we have a collection of clothes featuring the props `id`, `name`, `color` and `qtd` (for quantity). It is desired to select each one separately or all of them with a single checkbox (root):\n\n```js\nconst useCheckboxTree = require('./index.tsx').default\nconst Checkbox = require('../Checkbox/index.js').default\n\nconst ID_PREFIX = 'simple-example'\n\nfunction SimpleExample() {\n const items = [\n { id: 'one', name: 'jacket', color: 'red', qtd: 12 },\n { id: 'two', name: 'shirt', color: 'pink', qtd: 0 },\n { id: 'three', name: 'sweater', color: 'blue', qtd: 8 },\n { id: 'four', name: 'hat', color: 'purple', qtd: 0 },\n ]\n\n const checkboxes = useCheckboxTree({\n items,\n })\n\n return (\n <>\n <div className=\"mb3\">\n <Checkbox\n id={`${ID_PREFIX}-${checkboxes.itemTree.id}`}\n checked={checkboxes.allChecked}\n partial={checkboxes.someChecked}\n onChange={checkboxes.toggleAll}\n label=\"Clothes\"\n />\n </div>\n\n <div className=\"ml5\">\n {checkboxes.itemTree.children.map(item => {\n const id = `${ID_PREFIX}-${item.id}`\n const label = `${item.qtd} ${item.color} ${item.name}${\n item.qtd > 1 ? 's' : ''\n } left`\n return (\n <Checkbox\n key={id}\n id={id}\n label={label}\n checked={checkboxes.isChecked(item)}\n partial={checkboxes.isPartiallyChecked(item)}\n disabled={checkboxes.isDisabled(item)}\n onChange={() => checkboxes.toggle(item)}\n />\n )\n })}\n </div>\n </>\n )\n}\n;<SimpleExample />\n```\n\n### Handling disabled items\n\nThe disabled items are controlled by the `isDisabled` function, that receives an item as param. In the following example, an item should be disabled if the quantity is below 1.\n\n```js\nconst useCheckboxTree = require('./index.tsx').default\nconst Checkbox = require('../Checkbox/index.js').default\n\nconst ID_PREFIX = 'disabled-example'\n\nfunction DisabledExample() {\n const items = [\n { id: 'one', name: 'jacket', color: 'red', qtd: 12 },\n { id: 'two', name: 'shirt', color: 'pink', qtd: 0 },\n { id: 'three', name: 'sweater', color: 'blue', qtd: 8 },\n { id: 'four', name: 'hat', color: 'purple', qtd: 0 },\n ]\n\n const checkboxes = useCheckboxTree({\n items,\n isDisabled: item => item.qtd < 1,\n })\n\n return (\n <>\n <div className=\"mb3\">\n <Checkbox\n id={`${ID_PREFIX}-${checkboxes.itemTree.id}`}\n checked={checkboxes.allChecked}\n partial={checkboxes.someChecked}\n onChange={checkboxes.toggleAll}\n label=\"Clothes\"\n />\n </div>\n\n <div className=\"ml5\">\n {checkboxes.itemTree.children.map(item => {\n const id = `${ID_PREFIX}-${item.id}`\n const label = `${item.qtd} ${item.color} ${item.name}${\n item.qtd > 1 ? 's' : ''\n } left`\n return (\n <Checkbox\n key={id}\n id={id}\n label={label}\n checked={checkboxes.isChecked(item)}\n partial={checkboxes.isPartiallyChecked(item)}\n disabled={checkboxes.isDisabled(item)}\n onChange={() => checkboxes.toggle(item)}\n />\n )\n })}\n </div>\n </>\n )\n}\n;<DisabledExample />\n```\n\n### Granting unicity\n\nUnicity should be granted by the `comparator` curry, in which the curried parameters are two items and must return true if items are equal. In the example above there are some items with repeated `id`s, so we define a comparator that compares `id` and `color`.\n\nโ ๏ธIf you encounter a collection that contains deep equal items, a good solution is to map it into a new collection adding a prop to grants unicity, and then use the comparator function.\n\n```js\nconst useCheckboxTree = require('./index.tsx').default\nconst Checkbox = require('../Checkbox/index.js').default\n\nconst ID_PREFIX = 'comparator-example'\n\nfunction ComparatorExample() {\n const items = [\n { id: 'one', name: 'jacket', color: 'red', qtd: 12 },\n { id: 'one', name: 'shirt', color: 'pink', qtd: 0 },\n { id: 'one', name: 'sweater', color: 'blue', qtd: 8 },\n { id: 'four', name: 'hat', color: 'purple', qtd: 0 },\n ]\n\n const checkboxes = useCheckboxTree({\n items,\n comparator: item => candidate =>\n item.id === candidate.id && item.color === candidate.color,\n })\n\n return (\n <>\n <div className=\"mb3\">\n <Checkbox\n id={`${ID_PREFIX}-${checkboxes.itemTree.id}`}\n checked={checkboxes.allChecked}\n partial={checkboxes.someChecked}\n onChange={checkboxes.toggleAll}\n label=\"Clothes\"\n />\n </div>\n\n <div className=\"ml5\">\n {checkboxes.itemTree.children.map(item => {\n const id = `${ID_PREFIX}-${item.id}-${item.color}`\n const label = `${item.qtd} ${item.color} ${item.name}${\n item.qtd > 1 ? 's' : ''\n } left`\n return (\n <Checkbox\n key={id}\n id={id}\n label={label}\n checked={checkboxes.isChecked(item)}\n partial={checkboxes.isPartiallyChecked(item)}\n onChange={() => checkboxes.toggle(item)}\n />\n )\n })}\n </div>\n </>\n )\n}\n;<ComparatorExample />\n```\n\n### Nested Items\n\nYour items can be trees of any depth as well. To control which prop contains the nested items ('related' in our example) use the `nodesKey` input. You can also define default checked items with the `checked` input.\n\n```js\nconst useCheckboxTree = require('./index.tsx').default\nconst Checkbox = require('../Checkbox/index.js').default\n\nconst ID_PREFIX = 'tree-example'\n\nfunction TreeExample() {\n const items = [\n {\n id: '1',\n name: 'jacket',\n color: 'red',\n qtd: 12,\n related: [\n { id: '1.1', name: 'sweater', color: 'blue', qtd: 8 },\n {\n id: '1.2',\n name: 'shirt',\n color: 'pink',\n qtd: 1,\n related: [\n { id: '1.2.1', name: 't-shirt', color: 'lime', qtd: 2 },\n { id: '1.2.2', name: 'shirt', color: 'pink', qtd: 2 },\n ],\n },\n ],\n },\n {\n id: '2',\n name: 'hat',\n color: 'purple',\n qtd: 10,\n related: [\n { id: '2.1', name: 'cap', color: 'black', qtd: 17 },\n { id: '2.2', name: 'bandana', color: 'green', qtd: 6 },\n ],\n },\n ]\n\n const checkboxes = useCheckboxTree({\n items,\n nodesKey: 'related',\n checked: [\n { id: '1.2.2', name: 'shirt', color: 'pink', qtd: 2 },\n { id: '2.2', name: 'bandana', color: 'green', qtd: 6 },\n ],\n })\n\n function recursiveRender(item, depth = 0) {\n const id = `${ID_PREFIX}-${item.id}`\n const label = `${item.qtd} ${item.color} ${item.name}${\n item.qtd > 1 ? 's' : ''\n } left`\n\n const containerProps = {\n className: 'mt3',\n style: { marginLeft: 18 * depth },\n }\n\n return item.related ? (\n <div {...containerProps}>\n <Checkbox\n key={id}\n id={id}\n label={label}\n checked={checkboxes.isChecked(item)}\n partial={checkboxes.isPartiallyChecked(item)}\n onChange={() => checkboxes.toggle(item)}\n />\n {item.related.map(related => recursiveRender(related, depth + 1))}\n </div>\n ) : (\n <div {...containerProps}>\n <Checkbox\n key={id}\n id={id}\n label={label}\n checked={checkboxes.isChecked(item)}\n partial={checkboxes.isPartiallyChecked(item)}\n onChange={() => checkboxes.toggle(item)}\n />\n </div>\n )\n }\n\n return (\n <>\n <div className=\"mb3\">\n <Checkbox\n id={`${ID_PREFIX}-${checkboxes.itemTree.id}`}\n checked={checkboxes.allChecked}\n partial={checkboxes.someChecked}\n onChange={checkboxes.toggleAll}\n label=\"Clothes - Select All\"\n />\n </div>\n\n <div className=\"ml5\">\n {checkboxes.itemTree.related.map(item => recursiveRender(item))}\n </div>\n </>\n )\n}\n;<TreeExample />\n```\n\n## Detailed props\n\n#### Input\n\nThe `useCheckboxTree` hook receives a single object as a parameter, which contains the following props:\n\n##### items\n\n- Represents the items of your collection. Each one will be related to a single checkbox and may be toggled by parents.\n- **Type**: `Array<T>`\n- โ ๏ธThis property is required!\n\n##### nodesKey\n\n- Name of the property that contains the nested items, which is children by default.\n- Type: `string`\n- **Default**: `'children'`\n\n##### checked\n\n- List of items that are checked by default.\n- Type: `Array<T>`\n- **Default**: `[]`\n\n##### comparator\n\n- The curry that defines the condition that makes an item unique in the collection. You MUST grant item unicity! If the comparator condition is ambiguous the toggle algorithm will not work as it supposed to.\n- **Type**: `(item: T) => (candidante: T) => boolean`\n- **Default**: `(item: T) => (candidante: T) => item.id === candidate.id`\n\n##### onToggle\n\n- Funtion that is called on every item toggle.\n- **Type**: `({ checkedItems: T[], disabledItems: T[] }) => void`\n- **Default**: `undefined`\n\n##### isDisabled\n\n- Function that defines a item disabled or not. Returns `true` for a disabled item\n- **Type**: `(item: T | Tree<T>) => boolean`\n- **Default**: `() => false`\n\n#### Output\n\nSimilarly to input, the output is also a single object. All the exported properties are either states, memos or callbacks - meaning that you can safely include then as dependencies of your custom effects. They are so many to support a large number of use cases, and normally you will not need all of them to reach your solution.\n\n##### itemTree\n\n- Parsed tree that has the shape:\n\n```ts\ntype Tree<T>{\n id: 'VTEX_CheckboxTreeRoot' //id of the root\n [nodesKey]: T[] //Your items will be here\n}\n```\n\n- **Type**: `Tree<T>`.\n\n##### checkedItems\n\n- Current list of items that are checked (including the root).\n- **Type**: `Array<T>`.\n\n##### disabledItems\n\n- List of items that are disabled\n- **Type**: `Array<T>`\n\n##### isChecked\n\n- If a item is checked or not\n- **Type**: `(item: T | Tree<T>) => boolean`\n\n##### isPartiallyChecked\n\n- Return if an item or a tree is checked partially\n- **Type**: `(item: T | Tree<T>) => boolean`\n\n##### allChecked\n\n- Returns true if all the items are checked\n- **Type**: `boolean`\n\n##### someChecked\n\n- Returns true if one some item is checked\n- **Type**: `boolean`\n\n##### toggle\n\n- Bulk toggle one item or a tree\n- **Type**: `(item: T | Tree<T>) => void`\n\n##### check\n\n- Bulk checks one item or tree\n- **Type**: `(item: T | Tree<T>) => void`\n\n##### uncheck\n\n- Bulk unchecks one item or tree\n- **Type**: `(item: T | Tree<T>) => void`\n\n##### toggleAll\n\n- Toggle the root\n- **Type**: `() => void`\n\n##### checkAll\n\n- Check the root\n- **Type**: `() => void`\n\n##### uncheckAll\n\n- Uncheck the root\n- **Type**: `() => void`\n\n##### setChecked\n\n- Sets the current `checkedItems`\n- **Type**: `(checked: Array<T>) => void`\n\n```"
}
] |
code_store-on-localhost_b3b95c02
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/types.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ROOT_KEY } from './constants'\nimport useCheckboxTree from '.'\n\nexport type ChildKey<T> = { [key: string]: Array<T> }\n\nexport type comparatorCurry<T> = (item: T) => (candidate: T) => boolean\n\nexport type Checkboxes<T> = ReturnType<typeof useCheckboxTree>\n\nexport type Tree<T> = { [x: string]: string | T[]; [ROOT_KEY]: string } | T\n\nexport type toggleCallback<T> = {\n checkedItems: Array<unknown>\n disabledItems: Array<T>\n item: T | Tree<T>\n}\n\nexport type useCheckboxesInput<T> = {\n items: Array<T>\n onToggle?: (callback: toggleCallback<T>) => void\n nodesKey?: string\n checked?: Array<T>\n comparator?: comparatorCurry<Tree<T>>\n isDisabled?: (item: T | Tree<T>) => boolean\n}\n\n```"
}
] |
code_store-on-localhost_88cfdd1b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/reducer.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { getBulkChecked, getBulkUnchecked, getToggledState } from './util'\nimport { comparatorCurry, Tree } from './types'\n\nexport default function reducer<T>(state: Array<T>, action: Action<T>) {\n switch (action.type) {\n case ActionType.Check: {\n const { item } = action\n return [...state, item]\n }\n case ActionType.Uncheck: {\n const {\n itemToToggle: { item, comparator },\n } = action\n const rowFilter = (row: T) => !comparator(row)(item)\n return state.filter(rowFilter)\n }\n case ActionType.BulkCheck: {\n const { itemToToggle, isDisabled } = action\n if (!itemToToggle) return state\n const { item, nodesKey, comparator } = itemToToggle\n return getBulkChecked(state, item, nodesKey, comparator, isDisabled)\n }\n case ActionType.BulkUncheck: {\n const { itemToToggle } = action\n if (!itemToToggle) return state\n const { item, nodesKey, comparator } = itemToToggle\n return getBulkUnchecked(state, item, nodesKey, comparator)\n }\n case ActionType.Toggle: {\n const { itemToToggle, isDisabled } = action\n if (!itemToToggle) return state\n const { item, nodesKey, comparator } = itemToToggle\n return getToggledState(state, item, nodesKey, comparator, isDisabled)\n }\n case ActionType.SetChecked: {\n const { checked } = action\n return checked || state\n }\n default: {\n return state\n }\n }\n}\n\nexport enum ActionType {\n Check,\n Uncheck,\n Toggle,\n BulkCheck,\n BulkUncheck,\n SetChecked,\n}\n\nexport type Action<T> = {\n type: ActionType\n item?: T\n checked?: Array<T>\n itemToToggle?: {\n item: T\n nodesKey?: string\n comparator?: comparatorCurry<T>\n }\n isDisabled?: (item: T | Tree<T>) => boolean\n}\n\n```"
}
] |
code_store-on-localhost_83a3d015
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/constants.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ntype ItemWithID = {\n id: string\n}\n\nexport const defaultComparatorCurry = (item: ItemWithID) => (\n candidate: ItemWithID\n) => item.id === candidate.id\n\nexport const ROOT_KEY = 'id'\nexport const ROOT_VALUE = 'VTEX_CheckboxTreeRoot'\n\n```"
}
] |
code_store-on-localhost_b7b8156c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_useCheckboxTree/util.ts from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { comparatorCurry, Tree } from './types'\n\n/**\n * Checks nested items\n * @param checked\n * @param item\n * @param nodesKey\n * @param comparator\n */\nexport function getBulkChecked<T>(\n checked: Array<Tree<T>>,\n item: T,\n nodesKey = 'children',\n comparator: comparatorCurry<Tree<T>>,\n isDisabled: (item: T | Tree<T>) => boolean\n): Array<Tree<T>> {\n const notDisabled = (item: T | Tree<T>) => !isDisabled(item)\n return [...checked, ...getFlat(item, [], nodesKey)]\n .filter(notDisabled)\n .reduce(\n (acc: Array<Tree<T>>, item: T) =>\n acc.some(comparator(item)) ? acc : [...acc, item],\n []\n ) as Array<Tree<T>>\n}\n\n/**\n * Unchecks nested items\n * @param checked\n * @param item\n * @param nodesKey\n * @param comparator\n */\nexport function getBulkUnchecked<T>(\n checked: Array<Tree<T>>,\n item: T,\n nodesKey = 'children',\n comparator: comparatorCurry<Tree<T>>\n): Array<Tree<T>> {\n const flatCurry = (item: T, nodesKey: string) => getFlat(item, [], nodesKey)\n const flat = flatCurry(item, nodesKey)\n const bulkFilter = (row: T) => !flat.some(comparator(row))\n return checked.filter(bulkFilter)\n}\n\n/**\n * Return new state with items toggled\n * @param state\n * @param item\n */\nexport function getToggledState<T>(\n state: Array<Tree<T>>,\n item: T,\n nodesKey = 'children',\n comparator: comparatorCurry<Tree<T>>,\n isDisabled: (item: T | Tree<T>) => boolean\n): Array<Tree<T>> {\n const stateIncludesItem = state.some(comparator(item))\n const filter = (row: T) => !comparator(row)(item)\n\n if (stateIncludesItem) {\n return item[nodesKey]\n ? getBulkUnchecked<T>(state, item, nodesKey, comparator)\n : state.filter(filter)\n }\n return item[nodesKey]\n ? getBulkChecked<T>(state, item, nodesKey, comparator, isDisabled)\n : ([...state, item] as Array<Tree<T>>)\n}\n\n/**\n * Represents a tree section on a single array.\n */\nexport function getFlat<T>(\n tree: Tree<T>,\n arr: Array<Tree<T>> = [],\n nodesKey = 'children'\n): Array<T> {\n arr.push(tree)\n if (tree[nodesKey])\n (tree[nodesKey] as Array<Tree<T>>).forEach(child =>\n getFlat(child, arr, nodesKey)\n )\n return arr as T[]\n}\n\n```"
}
] |
code_store-on-localhost_338adeaf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Box/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport PropTypes, { InferProps } from 'prop-types'\n\nconst propTypes = {\n /** Content of the box */\n children: PropTypes.node.isRequired,\n /** Use the full size of the box. */\n noPadding: PropTypes.bool,\n /** Title to the box */\n title: PropTypes.string,\n}\n\ntype Props = InferProps<typeof propTypes>\n\nconst Box: FC<Props> = ({ children, noPadding, title }) => {\n const padding = noPadding ? '' : 'pa7'\n return (\n <div\n className={`styleguide__box bg-base t-body c-on-base ${padding} br3 b--muted-4 ba`}>\n {title && <h3 className=\"t-heading-4 mt0\">{title}</h3>}\n {children}\n </div>\n )\n}\n\nBox.propTypes = propTypes\n\nexport default Box\n\n```"
}
] |
code_store-on-localhost_9f3ac835
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Box/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### A simple container for organizing stuff of any sizes or hierarchies.\n\n### ๐ Don'ts\n\n- Don't make the whole box as a big interactable area, use a <a href=\"#/Components/Containers/Card\">Card</a> for that.\n\n```\n<div className=\"bg-muted-5 pa8\">\n <Box title=\"Lorem ipsum\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse convallis leo id tellus commodo tincidunt. Pellentesque et blandit risus. Duis rhoncus neque odio, quis suscipit lectus venenatis non. Vivamus ornare aliquet facilisis. Nullam eu lacinia felis. Proin dapibus consequat erat, vel aliquam urna commodo a. \n </Box>\n</div>\n```\n```"
}
] |
code_store-on-localhost_4f1d864b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/InputCurrency/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 NumberFormat from 'react-number-format'\n\nimport Input from '../Input'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\n/** WORKAROUND incoming!\n * BaseInput is a wrapper for the Input component for being able to use the\n * prefix prop with the NumberFormat component.\n * We can remove this as soon as the following issue is resolved:\n * https://github.com/s-yadav/react-number-format/issues/276\n *\n */\nconst BaseInput = props => {\n const { inputPrefix: prefix, inputSuffix: suffix, inputRef: ref } = props\n\n return <Input {...props} prefix={prefix} suffix={suffix} ref={ref} />\n}\n\nBaseInput.propTypes = {\n inputPrefix: PropTypes.string,\n inputSuffix: PropTypes.string,\n inputRef: refShape,\n}\n\nconst baseNumber = 9999999999.9999999999\n\nclass InputCurrency extends Component {\n handleChange = ({ floatValue }) => {\n const { onChange } = this.props\n onChange &&\n onChange({\n ...event,\n target: {\n ...event.target,\n value: floatValue,\n },\n })\n }\n\n render() {\n const {\n locale,\n currencyCode,\n forwardedRef,\n /** We exclude the onChange event because\n * NumberFormat uses onValueChange instead */\n /* eslint-disable-next-line no-unused-vars */\n onChange,\n ...props\n } = this.props\n\n const formatter = new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currencyCode,\n })\n\n const formattedParts = formatter.formatToParts\n ? formatter.formatToParts(baseNumber)\n : null\n const prefix = formattedParts\n ? !formattedParts.map(part => part.type).indexOf('currency')\n : true\n const [currencySymbol] = formattedParts\n ? formattedParts\n .filter(part => part.type === 'currency')\n .map(part => part.value)\n : ['$']\n const [decimalSeparator] = formattedParts\n ? formattedParts\n .filter(part => part.type === 'decimal')\n .map(part => part.value)\n : ['.']\n const [thousandSeparator] = formattedParts\n ? formattedParts\n .filter(part => part.type === 'group')\n .map(part => part.value)\n : [',']\n const [fraction] = formattedParts\n ? formattedParts\n .filter(part => part.type === 'fraction')\n .map(part => part.value)\n : ['99']\n\n return (\n <div>\n <NumberFormat\n {...props}\n inputRef={forwardedRef}\n inputPrefix={prefix ? currencySymbol : null}\n inputSuffix={prefix ? null : currencySymbol}\n decimalSeparator={decimalSeparator || false}\n decimalScale={fraction ? fraction.length : 0}\n fixedDecimalScale={!!decimalSeparator}\n thousandSeparator={thousandSeparator}\n onValueChange={this.handleChange}\n customInput={BaseInput}\n />\n </div>\n )\n }\n}\n\nInputCurrency.propTypes = {\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** _onChange event. You can get the numeric value of the input from the event\n * as _event.target.floatValue_ */\n onChange: PropTypes.func,\n onClear: PropTypes.func,\n size: PropTypes.string,\n defaultValue: PropTypes.number,\n value: PropTypes.number,\n /** Locale ISO string ('en-US', 'pt-BR', etc.)*/\n locale: PropTypes.string.isRequired,\n /** Currency code in ISO 4217 ('USD', 'BRL', etc.) */\n currencyCode: PropTypes.string.isRequired,\n}\n\nexport default withForwardedRef(InputCurrency)\n\n```"
}
] |
code_store-on-localhost_adf1828c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/InputCurrency/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### InputCurrency lets an user easily enter monetary values. The component understands currency codes and locales, so it can automatically format the input with the correct combination of commas, periods, etc.\n\nSizes\n\n```js\ninitialState = { value: undefined }\n;<div>\n <div className=\"mb5\">\n <InputCurrency\n label=\"Small\"\n size=\"small\"\n placeholder=\"Type a monetary value\"\n locale=\"pt-BR\"\n currencyCode=\"BRL\"\n value={state.value}\n onChange={e => setState({ value: e.target.value })}\n />\n </div>\n <div className=\"mb5\">\n <InputCurrency\n label=\"Regular\"\n placeholder=\"Type a monetary value\"\n locale=\"pt-BR\"\n currencyCode=\"BRL\"\n value={state.value}\n onChange={e => setState({ value: e.target.value })}\n />\n </div>\n <div className=\"mb5\">\n <InputCurrency\n label=\"Large\"\n size=\"large\"\n placeholder=\"Type a monetary value\"\n locale=\"pt-BR\"\n currencyCode=\"BRL\"\n value={state.value}\n onChange={e => setState({ value: e.target.value })}\n />\n </div>\n</div>\n```\n\nCurrency variations\n\n```js\nconst Dropdown = require('../Dropdown/index.js').default\nclass InputExamples extends React.Component {\n constructor() {\n super()\n this.state = {\n value: undefined,\n selectedCurrency: 'USD',\n currencyOptions: [\n {\n label: 'Real',\n value: 'BRL',\n },\n {\n label: 'US Dollar',\n value: 'USD',\n },\n {\n label: 'Euro',\n value: 'EUR',\n },\n {\n label: 'Yen',\n value: 'JPY',\n },\n ],\n }\n }\n\n render() {\n const { currencyOptions, selectedCurrency, value } = this.state\n\n return (\n <div className=\"w-40\">\n <div className=\"mb5\">\n <Dropdown\n label=\"Currency\"\n options={currencyOptions}\n value={selectedCurrency}\n onChange={(e, value) => this.setState({ selectedCurrency: value })}\n />\n </div>\n <div className=\"mb5\">\n <InputCurrency\n label=\"Product value\"\n placeholder=\"Type a monetary value\"\n locale=\"pt-BR\"\n currencyCode={selectedCurrency}\n value={value}\n onChange={e => this.setState({ value: e.target.value })}\n />\n </div>\n </div>\n )\n }\n}\n;<InputExamples />\n```\n\n```"
}
] |
code_store-on-localhost_49bafa6b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_Conditions/Statement.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 Button from '../Button'\nimport IconClose from '../icon/Close'\nimport SubjectAtom from './Atoms/SubjectAtom'\nimport VerbAtom from './Atoms/VerbAtom'\nimport ObjectAtom from './Atoms/ObjectAtom'\n\nclass Statement extends React.Component {\n constructor(props) {\n super(props)\n this.handleChangeStatement(\n {\n subject: React.createRef(),\n verb: React.createRef(),\n object: React.createRef(),\n },\n 'refs'\n )\n }\n\n handleChangeStatement = (newValue, structure) => {\n this.props.onChangeStatement(newValue, structure)\n }\n\n handleRemoveStatement = () => {\n this.props.onRemoveStatement()\n }\n\n getChoiceBySubject = subject => {\n const { options } = this.props\n return options[subject]\n }\n\n resetPredicate = subjectValue => {\n const { options } = this.props\n\n this.handleChangeStatement(\n options[subjectValue].verbs[0].value ||\n Statement.defaultProps.statements[0].verb,\n 'verb'\n )\n\n this.handleChangeStatement(\n Statement.defaultProps.statements[0].object,\n 'object'\n )\n\n this.handleChangeStatement(null, 'error')\n }\n\n clearObjects = () => {\n this.handleChangeStatement(\n Statement.defaultProps.statements[0].object,\n 'object'\n )\n this.handleChangeStatement(null, 'error')\n }\n\n render() {\n const {\n canDelete,\n options,\n subjectPlaceholder,\n isRtl,\n isFullWidth,\n statements,\n statementIndex,\n labels,\n onChangeObjectCallback,\n } = this.props\n const condition = statements[statementIndex]\n const atomProps = {\n statements: statements,\n options: options,\n isFullWidth: isFullWidth,\n statementIndex: statementIndex,\n onChangeObjectCallback,\n }\n\n const statementAtoms = [\n <SubjectAtom\n ref={condition.refs.subject}\n key=\"subject\"\n {...atomProps}\n placeholder={subjectPlaceholder}\n onChangeStatement={(value, structure) => {\n this.handleChangeStatement(value, structure)\n this.resetPredicate(value)\n }}\n />,\n <VerbAtom\n ref={condition.refs.verb}\n key=\"verb\"\n {...atomProps}\n onChangeStatement={(value, structure) => {\n this.handleChangeStatement(value, structure)\n }}\n />,\n <ObjectAtom key=\"object\" {...atomProps} />,\n ]\n\n return (\n <div>\n <div className=\"flex-column w-100 mv3\">\n <div\n className={`flex w-100 items-start ${\n isFullWidth ? 'flex-column items-stretch' : ''\n }`}>\n {canDelete && !isFullWidth && isRtl && (\n <div\n className=\"ma3 c-muted-2 pointer hover-c-danger\"\n onClick={this.handleRemoveStatement}>\n <IconClose size={25} />\n </div>\n )}\n {isRtl ? [...statementAtoms].reverse() : statementAtoms}\n {canDelete && !isFullWidth && !isRtl && (\n <div\n className=\"ma3 c-muted-2 pointer hover-c-danger\"\n onClick={this.handleRemoveStatement}>\n <IconClose size={25} />\n </div>\n )}\n {canDelete && isFullWidth && (\n <div className=\"tr\">\n <Button\n variation=\"tertiary\"\n size=\"small\"\n onClick={this.handleRemoveStatement}>\n <div className=\"dib\">\n <IconClose className=\"c-on-action-primary\" />\n </div>\n\n <div className=\"dib mb1 v-mid\" style={{ lineHeight: '10px' }}>\n {labels.delete}\n </div>\n </Button>\n </div>\n )}\n </div>\n {condition.error && condition.error.message && (\n <div className=\"red t-small mh3 mt2 lh-title\">\n {condition.error.message}\n </div>\n )}\n </div>\n </div>\n )\n }\n}\n\nStatement.defaultProps = {\n onRemoveStatement: () => {},\n onChangeStatement: () => {},\n onChangeObjectCallback: () => {},\n canDelete: true,\n statements: [{ subject: '', verb: '', object: null }],\n isRtl: false,\n isFullWidth: false,\n statementIndex: 0,\n labels: { delete: 'DELETE' },\n}\n\nStatement.propTypes = {\n /** Shows or hides the delete button */\n canDelete: PropTypes.bool,\n /** Current selected options for this Statement */\n statements: PropTypes.arrayOf(\n PropTypes.shape({\n refs: PropTypes.shape({\n subject: PropTypes.string,\n verb: PropTypes.string,\n object: PropTypes.any,\n }),\n error: PropTypes.string,\n })\n ),\n /** Possible options and respective data types, verb options */\n options: PropTypes.object.isRequired,\n /** Placeholder for subject dropdown */\n subjectPlaceholder: PropTypes.string.isRequired,\n /** Stretch component to 100% of the width */\n isFullWidth: PropTypes.bool,\n /** Whether the order of elements and text if right to left */\n isRtl: PropTypes.bool,\n /** Statement change callback */\n onChangeStatement: PropTypes.func,\n /** Statement remove callback */\n onRemoveStatement: PropTypes.func,\n /** To which row does this Statement belong to? */\n statementIndex: PropTypes.number,\n /** Labels for the controls and texts, default is english */\n labels: PropTypes.shape({\n delete: PropTypes.string,\n }),\n /** Please use the following one with caution, I did not test it, so it can break everything */\n onChangeObjectCallback: PropTypes.func,\n}\n\nexport default Statement\n\n```"
}
] |
code_store-on-localhost_b401d616
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_Conditions/StrategySelector.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 IconCaretDown from '../icon/CaretDown'\n\nclass StrategySelector extends React.Component {\n handleOperatorChange = event => {\n const newOperator = event.target.value\n const { operator } = this.props\n if (operator !== newOperator) {\n this.props.onChangeOperator(newOperator)\n }\n }\n\n render() {\n const { labels } = this.props\n\n return (\n <div className=\"flex flex-row nowrap\">\n <span>{labels.headerPrefix}</span>\n <div className=\"c-link relative\">\n <span className=\"mh3 b\">\n {this.props.operator === 'all'\n ? labels.operatorAll\n : labels.operatorAny}\n </span>\n <select\n className=\"o-0 absolute top-0 left-0 w-100 bottom-0 pointer t-small\"\n onChange={this.handleOperatorChange}\n value={this.props.operator}\n style={{\n // safari select height fix\n WebkitAppearance: 'menulist-button',\n }}>\n <option value=\"all\">{labels.operatorAll}</option>\n <option value=\"any\">{labels.operatorAny}</option>\n </select>\n <IconCaretDown size={14} />\n </div>\n <span className=\"ml3\">{labels.headerSufix}</span>\n </div>\n )\n }\n}\n\nStrategySelector.propTypes = {\n /** Operator indicates whether all the conditions should be met or any of them */\n operator: PropTypes.oneOf(['all', 'any']),\n /** Operator change callback: one of 'any', 'all' */\n onChangeOperator: PropTypes.func,\n /** Labels for the controls and texts, default is english */\n labels: PropTypes.shape({\n operatorAll: PropTypes.string,\n operatorAny: PropTypes.string,\n headerPrefix: PropTypes.string,\n headerSufix: PropTypes.string,\n }),\n}\n\nexport default StrategySelector\n\n```"
}
] |
code_store-on-localhost_a54d39df
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_Conditions/Separator.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\nclass Separator extends React.Component {\n render() {\n const { label } = this.props\n\n return (\n <div>\n <div\n style={{\n marginLeft: -17,\n width: 'calc(100% + 34px)',\n }}\n className=\"flex flex-row w-100 nowrap items-center mv3\">\n <hr className=\"ma0 b--black-10 bb bb-0 w-100\" />\n </div>\n <div className=\"w-100 tc\" style={{ marginTop: -18 }}>\n <span className=\"gray ph3 dib bg-white\">{label}</span>\n </div>\n </div>\n )\n }\n}\n\nSeparator.propTypes = {\n /** `and` or `or` label */\n label: PropTypes.string,\n}\n\nexport default Separator\n\n```"
}
] |
code_store-on-localhost_7afe19ca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_Conditions/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable camelcase */\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport Button from '../Button'\nimport IconPlus from '../icon/Plus'\nimport Separator from './Separator'\nimport StrategySelector from './StrategySelector'\nimport Statement from './Statement'\n\n/**\n * @visibleName Conditions\n */\nclass EXPERIMENTAL_Conditions extends React.Component {\n static defaultProps = {\n operator: 'any',\n showOperator: true,\n statements: [],\n onChangeOperator: () => {},\n onChangeStatements: () => {},\n labels: {\n operatorAll: 'all',\n operatorAnd: 'and',\n operatorAny: 'any',\n operatorOr: 'or',\n headerPrefix: 'Matching',\n headerSufix: 'following conditions:',\n addConditionBtn: 'add condition',\n noConditions: 'No conditions selected.',\n addNewCondition: 'add new condition',\n },\n }\n\n 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 canAddNewCondition = () => {\n const { statements } = this.props\n if (statements.length === 0) return true\n\n const hasIncompleteCondition = statements.some(\n condition =>\n condition.subject === '' ||\n condition.verb === '' ||\n this.objectIsEmpty(condition.object)\n )\n return !hasIncompleteCondition\n }\n\n handleAddNewCondition = () => {\n const emptyStatement = {\n subject: '',\n verb: '',\n object: null,\n }\n\n this.props.onChangeStatements([...this.props.statements, emptyStatement])\n }\n\n handleRemoveStatement = index => {\n const currentStatements = this.props.statements\n const updatedStatements = currentStatements\n .slice(0, index)\n .concat(currentStatements.slice(index + 1))\n\n this.props.onChangeStatements(updatedStatements)\n }\n\n handleChangeStatement = (statementIndex, newValue, structure) => {\n const updatedCurrentStatements = [...this.props.statements]\n if (structure === 'verb') {\n updatedCurrentStatements[statementIndex].object = null\n }\n updatedCurrentStatements[statementIndex][structure] = newValue\n this.props.onChangeStatements(updatedCurrentStatements)\n }\n\n componentDidMount() {\n console.warn(\n `Experimental component warning:\n\n Conditions component is in an experimental state.\n This component may suffer breaking changes in a near future, even in minor or patch versions.\n It may even cease to exist without further notice ๐ป`\n )\n }\n render() {\n const {\n canDelete,\n statements,\n options,\n subjectPlaceholder,\n isFullWidth,\n isRtl,\n labels,\n showOperator,\n operator,\n } = this.props\n\n return (\n <div>\n {showOperator && (\n <div className=\"mh6\">\n <StrategySelector\n operator={operator}\n labels={labels}\n onChangeOperator={operator =>\n this.props.onChangeOperator({ operator })\n }\n />\n </div>\n )}\n\n <div className=\"t-body c-on-base ph5 mt4 br3 b--muted-4 ba\">\n {this.props.statements.length === 0 ? (\n <div className=\"mv6 mh3\">\n <span className=\"light-gray\">{labels.noConditions}</span>\n </div>\n ) : (\n <div className=\"mv5\">\n {statements.map((statement, statementIndex) => {\n return (\n <div\n className=\"flex flex-column w-100 mv3\"\n key={statementIndex}>\n <Statement\n canDelete={canDelete}\n isRtl={isRtl}\n isFullWidth={isFullWidth}\n onChangeStatement={(newValue, structure) => {\n this.handleChangeStatement(\n statementIndex,\n newValue,\n structure\n )\n }}\n onRemoveStatement={() =>\n this.handleRemoveStatement(statementIndex)\n }\n options={options}\n subjectPlaceholder={subjectPlaceholder}\n statements={statements}\n statementIndex={statementIndex}\n labels={labels}\n />\n\n {statementIndex !== statements.length - 1 && (\n <Separator\n label={\n operator === 'all'\n ? labels.operatorAnd\n : labels.operatorOr\n }\n />\n )}\n </div>\n )\n })}\n </div>\n )}\n\n <div\n style={{\n marginLeft: -17,\n width: 'calc(100% + 34px)',\n }}\n className=\"flex flex-row w-100 nowrap items-center mv3\">\n <hr className=\"ma0 b--black-10 bb bb-0 w-100\" />\n </div>\n\n <div style={{ marginLeft: -10 }} className=\"mv5\">\n <Button\n variation=\"tertiary\"\n size=\"small\"\n disabled={!this.canAddNewCondition()}\n onClick={this.handleAddNewCondition}>\n <span className=\"flex align-baseline\">\n <span className=\"mr2\">\n <IconPlus solid size={16} color=\"currentColor\" />\n </span>\n {labels.addNewCondition}\n </span>\n </Button>\n </div>\n </div>\n </div>\n )\n }\n}\n\nEXPERIMENTAL_Conditions.propTypes = {\n /** Shows or hides the delete button */\n canDelete: PropTypes.bool,\n /** Operator indicates whether all the statements should be met or any of them */\n operator: PropTypes.oneOf(['all', 'any']),\n /** Current selected options for all statements */\n statements: PropTypes.arrayOf(\n PropTypes.shape({\n subject: PropTypes.string,\n verb: PropTypes.string,\n object: PropTypes.any,\n error: PropTypes.any,\n })\n ),\n /** Possible options and respective data types, verb options */\n options: PropTypes.object.isRequired,\n /** Placeholder for subject dropdown */\n subjectPlaceholder: PropTypes.string.isRequired,\n /** Wether to show this component stretched to the width */\n isFullWidth: PropTypes.bool,\n /** Conditions change callback: array of statement definitions */\n onChangeStatements: PropTypes.func,\n /** Operator (any, all) change callback */\n onChangeOperator: PropTypes.func,\n /** Whether the order of elements and text if right to left */\n isRtl: PropTypes.bool,\n /** Show or hide the header that selects the operator (any vs all) */\n showOperator: 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}\n\nexport default EXPERIMENTAL_Conditions\n\n```"
}
] |
code_store-on-localhost_323e181c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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_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\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 this.simpleInputObject = this.simpleInputObject.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <Input\n value={values}\n onChange={e => {\n statements[statementIndex].object = e.target.value\n this.setState({ simpleStatements: statements })\n }}\n />\n )\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\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 },\n email: {\n label: 'Email',\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 }\n\n return (\n <EXPERIMENTAL_Conditions\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n operator={this.state.operator}\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n this.setState({ simpleStatements: statements })\n }}\n />\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\nComplex\n\n```js\nconst Dropdown = require('../Dropdown').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\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 this.complexDropdownObject = this.complexDropdownObject.bind(this)\n this.complexMultiselectObject = this.complexMultiselectObject.bind(this)\n this.complexDatePickerObject = this.complexDatePickerObject.bind(this)\n this.complexDatePickerRangeObject = this.complexDatePickerRangeObject.bind(\n this\n )\n this.complexNumericInputObject = this.complexNumericInputObject.bind(this)\n this.complexNumericInputRangeObject = this.complexNumericInputRangeObject.bind(\n this\n )\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n complexDropdownObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <Dropdown\n value={values}\n options={possibleColors}\n onChange={(e, value) => {\n statements[statementIndex].object = value\n\n this.setState({ statements })\n }}\n />\n )\n }\n\n complexMultiselectObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <div className=\"nt3\">\n <MultiSelect\n emptyState={term => {\n return `Your search for the color \"${term}\" did not find any results.`\n }}\n options={possibleColors}\n onChange={selected => {\n statements[statementIndex].object = selected\n\n this.setState({ statements })\n }}\n selected={values || []}\n />\n </div>\n )\n }\n\n complexDatePickerObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <DatePicker\n value={values || new Date()}\n onChange={date => {\n statements[statementIndex].object = date\n this.setState({ statements })\n }}\n locale=\"en-US\"\n />\n )\n }\n\n complexDatePickerRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <div className=\"flex\">\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n style={{ maxWidth: 140 }}\n value={values && values.from}\n errorMessage={\n statements[statementIndex].object &&\n statements[statementIndex].object.from >=\n statements[statementIndex].object.to\n ? 'Must be before end date'\n : ''\n }\n onChange={date => {\n statements[statementIndex].object = {\n ...(statements[statementIndex].object || {}),\n from: date,\n }\n\n this.setState({ statements })\n }}\n locale=\"en-US\"\n />\n </div>\n\n <div className=\"mv4 mh3 c-muted-2 b\">and</div>\n\n <div style={{ maxWidth: 140 }}>\n <DatePicker\n value={values && values.to}\n onChange={date => {\n statements[statementIndex].object = {\n ...(statements[statementIndex].object || {}),\n to: date,\n }\n\n this.setState({ statements })\n }}\n locale=\"en-US\"\n />\n </div>\n </div>\n )\n }\n\n complexNumericInputObject({ statements, values, statementIndex, error }) {\n return (\n <Input\n placeholder=\"Insert age...\"\n type=\"number\"\n min={0}\n value={values}\n onChange={e => {\n statements[statementIndex].object = e.target.value.replace(/\\D/g, '')\n this.setState({ statements })\n }}\n />\n )\n }\n\n complexNumericInputRangeObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\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 = statements[statementIndex].object || {}\n currentObject.first = e.target.value.replace(/\\D/g, '')\n\n statements[statementIndex].object = currentObject\n\n this.setState({ statements })\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 = statements[statementIndex].object || {}\n currentObject.last = e.target.value.replace(/\\D/g, '')\n\n statements[statementIndex].object = currentObject\n\n this.setState({ statements })\n }}\n />\n </div>\n )\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: {\n renderFn: this.complexNumericInputObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.complexNumericInputRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n color: {\n unique: true,\n label: 'User favorite color',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.complexDropdownObject,\n extraParams: {},\n },\n },\n {\n label: 'is any of',\n value: 'any',\n object: {\n renderFn: this.complexMultiselectObject,\n extraParams: {},\n },\n },\n ],\n },\n birthday: {\n unique: true,\n label: 'User birthday',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.complexDatePickerObject,\n extraParams: {},\n },\n },\n {\n label: 'is between',\n value: 'between',\n object: {\n renderFn: this.complexDatePickerRangeObject,\n extraParams: {},\n },\n },\n ],\n },\n }\n\n return (\n <EXPERIMENTAL_Conditions\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.statements}\n operator={this.state.operator}\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n this.setState({ statements })\n }}\n />\n )\n }\n}\n;<ComplexConditionsCase />\n```\n\nUsing ref\n\n```js\nconst Button = require('../Button').default\nconst Input = require('../Input').default\n\nclass SimpleConditionsCase extends React.Component {\n constructor() {\n super()\n\n this.state = {\n simpleStatements: [\n { subject: 'name', verb: '=', object: 'a', error: null },\n { subject: 'name', verb: '=', object: 'b', error: null },\n { subject: 'name', verb: '=', object: 'c', error: null },\n ],\n operator: 'all',\n }\n\n this.handleToggleOperator = this.handleToggleOperator.bind(this)\n this.simpleInputObject = this.simpleInputObject.bind(this)\n }\n\n handleToggleOperator(operator) {\n this.setState({ operator: this.state.operator === 'all' ? 'any' : 'all' })\n }\n\n simpleInputObject({\n statements,\n values,\n statementIndex,\n error,\n extraParams,\n }) {\n return (\n <Input\n ref={statements[statementIndex].refs.object}\n value={values}\n onChange={e => {\n statements[statementIndex].object = e.target.value\n this.setState({ simpleStatements: statements })\n }}\n />\n )\n }\n\n render() {\n const options = {\n name: {\n label: 'User name',\n verbs: [\n {\n label: 'is',\n value: '=',\n object: {\n renderFn: this.simpleInputObject,\n extraParams: {},\n },\n },\n ],\n },\n }\n\n return (\n <div>\n <EXPERIMENTAL_Conditions\n options={options}\n subjectPlaceholder=\"Select subject\"\n statements={this.state.simpleStatements}\n operator={this.state.operator}\n onChangeOperator={this.handleToggleOperator}\n onChangeStatements={statements => {\n this.setState({ simpleStatements: statements })\n }}\n />\n <div className=\"mt4\">\n <span className=\"mr4\">\n <Button\n onClick={() =>\n this.state.simpleStatements[0].refs.subject.current.focus()\n }>\n Focus on first subject\n </Button>\n </span>\n <span className=\"mr4\">\n <Button\n onClick={() =>\n this.state.simpleStatements[0].refs.verb.current.focus()\n }>\n Focus on first verb\n </Button>\n </span>\n <span className=\"mr4\">\n <Button\n onClick={() =>\n this.state.simpleStatements[0].refs.object.current.focus()\n }>\n Focus on first object\n </Button>\n </span>\n </div>\n </div>\n )\n }\n}\n;<SimpleConditionsCase />\n```\n\n```"
}
] |
code_store-on-localhost_38e9ef8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Radio/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\nclass Radio extends PureComponent {\n constructor(props) {\n super(props)\n this.radio = React.createRef()\n this.container = React.createRef()\n }\n\n handleContainerClick = e => {\n const { disabled } = this.props\n if (!disabled && e.target === this.container.current) {\n this.radio.current.click()\n }\n }\n\n render() {\n const {\n checked,\n disabled,\n id,\n isLast,\n label,\n name,\n onChange,\n required,\n value,\n } = this.props\n\n return (\n <div\n className={classNames('flex items-start relative', {\n pointer: !disabled,\n mb3: !isLast,\n })}\n ref={this.container}\n onClick={this.handleContainerClick}>\n {/* This empty div is used so that the radio circle is not a direct child of\n * a flex element, and thus can set a fixed width. Otherwise, the width would\n * be used as flex-basis, and would not be set directly */}\n <div>\n <div\n className={classNames(\n 'fake-radio relative ba br-100 mr3 flex justify-center items-center',\n {\n 'b--muted-4 pointer': !disabled && !checked,\n 'b--action-primary pointer': !disabled && checked,\n 'b--muted-4 bg-muted-5': disabled,\n }\n )}\n style={{\n borderWidth: '3px',\n height: '1.25rem',\n width: '1.25rem',\n transition: 'border 100ms ease-in-out',\n }}>\n <div\n className={classNames('br-100', {\n 'bg-action-primary': !disabled,\n 'bg-muted-3': disabled,\n })}\n style={{\n height: '0.5rem',\n width: '0.5rem',\n transform: `scale(${checked ? 1 : 0})`,\n transition: `transform 80ms ${\n checked ? 'ease-out' : 'ease-in'\n }`,\n }}\n />\n </div>\n </div>\n <input\n checked={checked}\n className={classNames('absolute o-0', {\n pointer: !disabled,\n })}\n disabled={disabled}\n required={required}\n id={id}\n name={name}\n onChange={onChange}\n type=\"radio\"\n value={value}\n style={{\n height: '1.5rem',\n width: '1.5rem',\n }}\n ref={this.radio}\n />\n <label\n style={{ wordBreak: 'break-word' }}\n className={classNames(\n { 'c-disabled': disabled },\n { 'c-on-base pointer': !disabled },\n 'flex flex-auto'\n )}\n htmlFor={id}>\n {label}\n </label>\n </div>\n )\n }\n}\n\nRadio.defaultProps = {\n checked: false,\n disabled: false,\n required: false,\n isLast: false,\n}\n\nRadio.propTypes = {\n /** (Radio spec attribute) */\n checked: PropTypes.bool,\n /** (Radio spec attribute) */\n disabled: PropTypes.bool,\n /** (Radio spec attribute) */\n id: PropTypes.string.isRequired,\n /** (Radio spec attribute) */\n isLast: PropTypes.bool,\n /** Radio label */\n label: PropTypes.node.isRequired,\n /** (Radio spec attribute) */\n name: PropTypes.string.isRequired,\n /** onChange event */\n onChange: PropTypes.func.isRequired,\n /** (Radio spec attribute) */\n required: PropTypes.bool,\n /** (Radio spec attribute) */\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,\n}\n\nexport default Radio\n\n```"
}
] |
code_store-on-localhost_add0717b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Card/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 Card extends PureComponent {\n render() {\n const { children, noPadding } = this.props\n const padding = noPadding ? '' : 'pa6'\n\n return (\n <div\n style={{ boxShadow: '0 3px 9px 0 rgba(61, 62, 64, 0.2)' }}\n className={`vtex-card card w-100 b2 br2 bg-base c-on-base ${padding}`}>\n {children}\n </div>\n )\n }\n}\n\nCard.propTypes = {\n /** Content of the card */\n children: PropTypes.node.isRequired,\n /** Use the full size of the card. */\n noPadding: PropTypes.bool,\n}\n\nexport default Card\n\n```"
}
] |
code_store-on-localhost_bfa4ba57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/Card/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n#### A Card like any container improves scannability of a design when well used. What sets the Card apart is that it has higher visual prominence and invites interactivity with its fancy drop shadow.\n\n### ๐ Dos\n\n- It works best when used as a big button.\n- Do use buttons inside it if you need, but keep it simple.\n\n### ๐ Don'ts\n\n- Don't nest cards.\n- Avoid using it to encompass the entirety of a page.\n\n### Related components\n\n- In doubt prefer using a simple <a href=\"#/Components/Containers/Box\">Box</a>.\n\nDefault\n\n```js\n<div style={{ padding: '80px', color: '#585959', background: '#fafafa' }}>\n <Card>\n <h3>Lorem Ipsum</h3>\n <p>\n It is simply dummy text of the printing and typesetting industry. Lorem\n Ipsum has been the industry's standard dummy text ever since the 1500s,\n when an unknown printer took a galley of type and scrambled it to make a\n type specimen book.\n </p>\n <p>\n It has survived not only five centuries, but also the leap into electronic\n typesetting, remaining essentially unchanged. It was popularised in the\n 1960s with the release of Letraset sheets containing Lorem Ipsum passages,\n and more recently with desktop publishing software like Aldus PageMaker\n including versions of Lorem Ipsum.\n </p>\n </Card>\n</div>\n```\n\nFull width\n\n```js\n<div style={{ padding: '80px', color: '#585959', background: '#fafafa' }}>\n <Card noPadding>\n <h3 className=\"pl6 pr6 pt6\">Spider</h3>\n <img\n width=\"100%\"\n src=\"//cdn.shopify.com/s/files/1/2426/4557/collections/spider-header123_1800x_c0da37d9-6f9c-4b9e-bcaa-f984f3c869fe_1800x.png?v=1512524794\"\n />\n <p className=\"pl6 pr6 pb6\">\n It is simply dummy text of the printing and typesetting industry. Lorem\n Ipsum has been the industry's standard dummy text ever since the 1500s,\n when an unknown printer took a galley of type and scrambled it to make a\n type specimen book.\n </p>\n </Card>\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_8825beda
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ButtonGroup/index.js from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React, { Component } from 'react'\n\nimport Button from '../Button'\nimport ButtonWithIcon from '../ButtonWithIcon'\nimport ActionMenu from '../ActionMenu'\nimport { childrenOf } from '../utils'\n\nclass ButtonGroup extends Component {\n render() {\n const { buttons } = this.props\n\n return (\n <div className=\"button_group flex flex-row\">\n {buttons.map((btn, i) => {\n const TagName = btn.type\n\n return i === 0 ? (\n // First button\n <span key={i} className=\"mr1 isFirstOfGroup\">\n <TagName {...btn.props} isGrouped isFirstOfGroup />\n </span>\n ) : buttons.length - 1 === i ? (\n // Last button\n <TagName key={i} {...btn.props} isGrouped isLastOfGroup />\n ) : (\n // Others\n <span key={i} className=\"mr1\">\n <TagName {...btn.props} isGrouped />\n </span>\n )\n })}\n </div>\n )\n }\n}\n\nButtonGroup.defaultProps = {}\n\nButtonGroup.propTypes = {\n buttons: childrenOf(Button, ButtonWithIcon, ActionMenu),\n}\n\nexport default ButtonGroup\n\n```"
}
] |
code_store-on-localhost_0f23aa37
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/ButtonGroup/README.md from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\nButton group receives a list of button components with an extra available prop `isActiveOfGroup` as a boolean to display an active state. This has to be handled on the app side.\n\n### Related components\n\n- <a href=\"#/Components/Navigation/Tabs\">tabs</a>\n\nDefault\n\n```js\nconst Button = require('../Button').default\ninitialState = { active: 1 }\n;<div>\n <ButtonGroup\n buttons={[\n <Button\n isActiveOfGroup={state.active === 1}\n onClick={() => setState({ active: 1 })}>\n one\n </Button>,\n <Button\n isActiveOfGroup={state.active === 2}\n onClick={() => setState({ active: 2 })}>\n two\n </Button>,\n <Button\n isActiveOfGroup={state.active === 3}\n onClick={() => setState({ active: 3 })}>\n three\n </Button>,\n ]}\n />\n</div>\n```\n\nSizes\n\n```js\nconst Button = require('../Button').default\ninitialState = { active: 1 }\n;<div>\n <ButtonGroup\n buttons={[\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 1}\n onClick={() => setState({ active: 1 })}>\n {state.active === 1 ? 'loading' : 'load'}\n </Button>,\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 2}\n onClick={() => setState({ active: 2 })}>\n two\n </Button>,\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 3}\n onClick={() => setState({ active: 3 })}>\n three\n </Button>,\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 4}\n onClick={() => setState({ active: 4 })}>\n four\n </Button>,\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 5}\n onClick={() => setState({ active: 5 })}>\n five\n </Button>,\n <Button\n size=\"small\"\n isActiveOfGroup={state.active === 6}\n onClick={() => setState({ active: 6 })}\n isLoading={state.active === 1}>\n Load?\n </Button>,\n ]}\n />\n</div>\n```\n\nMisc\n\n```js\nconst Button = require('../Button').default\ninitialState = { active: 1 }\n;<div>\n <ButtonGroup\n buttons={[\n <Button\n disabled\n isActiveOfGroup={state.active === 1}\n onClick={() => setState({ active: 1 })}>\n disabled\n </Button>,\n <Button\n variation=\"secondary\"\n isActiveOfGroup={state.active === 2}\n onClick={() => setState({ active: 2 })}>\n secondary\n </Button>,\n <Button\n variation=\"tertiary\"\n isActiveOfGroup={state.active === 3}\n onClick={() => setState({ active: 3 })}>\n tertiary\n </Button>,\n <Button\n variation=\"danger\"\n isActiveOfGroup={state.active === 4}\n onClick={() => setState({ active: 4 })}>\n danger\n </Button>,\n <Button\n variation=\"danger-tertiary\"\n isActiveOfGroup={state.active === 5}\n onClick={() => setState({ active: 5 })}>\n danger-tertiary\n </Button>,\n ]}\n />\n</div>\n```\n\nButtons with icon\n\n```js\nconst ArrowBack = require('../icon/ArrowBack').default\nconst Delete = require('../icon/Delete').default\nconst Edit = require('../icon/Edit').default\nconst PlusLines = require('../icon/PlusLines').default\nconst ButtonWithIcon = require('../ButtonWithIcon').default\n\nconst arrow = <ArrowBack />\nconst remove = <Delete />\nconst edit = <Edit />\nconst plus = <PlusLines />\n\ninitialState = { active: 1 }\n;<div>\n <ButtonGroup\n buttons={[\n <ButtonWithIcon\n isActiveOfGroup={state.active === 1}\n onClick={() => setState({ active: 1 })}\n icon={arrow}>\n Back\n </ButtonWithIcon>,\n <ButtonWithIcon\n isActiveOfGroup={state.active === 2}\n onClick={() => setState({ active: 2 })}\n icon={edit}\n />,\n <ButtonWithIcon\n isActiveOfGroup={state.active === 3}\n onClick={() => setState({ active: 3 })}\n icon={plus}\n iconPosition=\"right\"\n />,\n <ButtonWithIcon\n isActiveOfGroup={state.active === 4}\n onClick={() => setState({ active: 4 })}\n icon={remove}\n />,\n ]}\n />\n</div>\n```\n\nSplit Button\n\n```js\nconst Button = require('../Button').default\nconst ActionMenu = require('../ActionMenu').default\nconst CaretDown = require('../icon/CaretDown').default\nconst caretDown = <CaretDown />\n\nconst options = [\n 'General',\n 'Desktop & Screen Saver',\n 'Dock',\n 'Language & Region',\n].map(label => ({\n label,\n onClick: () => {},\n}))\n\ninitialState = { active: 1 }\n;<div>\n <ButtonGroup\n buttons={[\n <Button isActiveOfGroup>new</Button>,\n <ActionMenu\n isActiveOfGroup\n hideCaretIcon\n buttonProps={{\n variation: 'primary',\n icon: <CaretDown color=\"currentColor\" />,\n iconPosition: 'right',\n }}\n options={options}\n />,\n ]}\n />\n</div>\n```\n\n```"
}
] |
code_store-on-localhost_2f86b5d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building 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/index.tsx from the store-on-localhost VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, Fragment, useEffect } from 'react'\nimport PropTypes, { InferProps } from 'prop-types'\nimport classNames from 'classnames'\n\nimport Spinner from '../Spinner'\nimport { withForwardedRef, refShape } from '../../modules/withForwardedRef'\n\nconst SIZE = {\n SMALL: 'small',\n REGULAR: 'regular',\n LARGE: 'large',\n}\n\nconst VARIATION = {\n PLAIN: 'plain',\n INVERTED: 'inverted',\n DANGER: 'danger',\n}\n\nconst loaderSize = {\n [SIZE.SMALL]: 15,\n [SIZE.REGULAR]: 20,\n [SIZE.LARGE]: 25,\n}\n\nconst propTypes = {\n /** Button size */\n size: PropTypes.oneOf(Object.values(SIZE)),\n /** Button prominence variation */\n variation: PropTypes.oneOf(Object.values(VARIATION)),\n /** [DEPRECATED] If you are using just an Icon component inside, use this as true */\n icon: PropTypes.bool,\n /** Loading state */\n isLoading: PropTypes.bool,\n /** @ignore For internal use\n * Sets reduced paddings in order to keep the button squareish if it\n * only has an icon */\n iconOnly: PropTypes.bool,\n /** (Button spec attribute) */\n id: PropTypes.string,\n /** Data attribute */\n testId: PropTypes.string,\n /** (Button spec attribute) */\n autoFocus: PropTypes.bool,\n /** (Button spec attribute) */\n autoComplete: PropTypes.string,\n /** (Button spec attribute) */\n disabled: PropTypes.bool,\n /** @ignore Forwarded Ref */\n forwardedRef: refShape,\n /** (Button spec attribute) */\n name: PropTypes.string,\n /** (Button spec attribute) */\n type: PropTypes.string,\n /** (Button spec attribute) */\n value: PropTypes.string,\n /** Label of the Button */\n children: PropTypes.node.isRequired,\n /** onClick event. */\n onClick: PropTypes.func,\n /** URL for link mode. Converts the button internally to a link. */\n href: PropTypes.string,\n /** onMouseEnter event */\n onMouseEnter: PropTypes.func,\n /** onMouseLeave event */\n onMouseLeave: PropTypes.func,\n /** onMouseOver event */\n onMouseOver: PropTypes.func,\n /** onMouseOut event */\n onMouseOut: PropTypes.func,\n /** onMouseUp event */\n onMouseUp: PropTypes.func,\n /** onMouseDown event */\n onMouseDown: PropTypes.func,\n /** onFocus event */\n onFocus: PropTypes.func,\n /** onBlur event */\n onBlur: PropTypes.func,\n /** Link spec */\n target: PropTypes.string,\n /** Link spec */\n rel: PropTypes.string,\n /** Link spec */\n referrerPolicy: PropTypes.string,\n /** Link spec */\n download: PropTypes.string,\n /** Disables label wrapping */\n noWrap: PropTypes.bool,\n}\n\ntype Props = InferProps<typeof propTypes>\n\nconst ButtonPlain: FunctionComponent<Props> = props => {\n const handleClick = (event: React.MouseEvent) => {\n !props.disabled && !props.isLoading && props.onClick && props.onClick(event)\n }\n\n useEffect(() => {\n if (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 }, [props.icon])\n\n const {\n size,\n variation,\n children,\n icon,\n isLoading,\n href,\n target,\n rel,\n referrerPolicy,\n download,\n noWrap,\n } = props\n\n const disabled = props.disabled || isLoading\n const iconOnly = icon || props.iconOnly\n const horizontalPadding = iconOnly ? 1 : 2\n const horizontalCompensation = `nr${horizontalPadding} nl${horizontalPadding} `\n\n const classes = classNames(\n 'vtex-button bw1 ba fw5 v-mid relative pa0 br2 bn',\n horizontalCompensation,\n {\n 't-action--small': size === SIZE.SMALL,\n 't-action': size === SIZE.REGULAR,\n 't-action--large': size === SIZE.LARGE,\n },\n { 'icon-button dib': iconOnly },\n {\n 'bg-transparent b--transparent c-disabled': disabled,\n 'bg-transparent b--transparent c-action-primary hover-b--transparent hover-bg-action-secondary hover-b--action-secondary':\n !disabled && variation === VARIATION.PLAIN,\n 'bg-transparent b--transparent c-on-base--inverted':\n !disabled && variation === VARIATION.INVERTED,\n 'bg-transparent b--transparent c-danger hover-bg-danger--faded hover-b--danger--faded':\n !disabled && variation === VARIATION.DANGER,\n },\n { pointer: !disabled },\n { 'inline-flex items-center no-underline': href }\n )\n\n const labelClasses = classNames(\n 'flex items-center justify-center h-100 pv1 ttn ',\n `ph${horizontalPadding}`,\n { nowrap: noWrap }\n )\n\n const style: { fontSize?: number } = {}\n\n if (iconOnly) {\n style.fontSize = 0\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={props.id}\n data-testid={props.testId}\n autoFocus={iconOnly ? undefined : props.autoFocus}\n disabled={iconOnly ? undefined : props.disabled}\n name={iconOnly ? undefined : props.name}\n value={iconOnly ? undefined : props.value}\n tabIndex={0}\n className={classes}\n href={href}\n onClick={handleClick}\n onMouseEnter={props.onMouseEnter}\n onMouseLeave={props.onMouseLeave}\n onMouseOver={props.onMouseOver}\n onMouseOut={props.onMouseOut}\n onMouseUp={props.onMouseUp}\n onMouseDown={props.onMouseDown}\n onFocus={props.onFocus}\n onBlur={props.onBlur}\n ref={props.forwardedRef as any}\n style={style}\n // Button-mode exclusive props\n type={href ? undefined : (props.type as 'button' | 'submit' | 'reset')}\n // Link-mode exclusive props\n {...(href && linkModeProps)}>\n {isLoading ? (\n <Fragment>\n <span className=\"top-0 left-0 w-100 h-100 absolute flex justify-center items-center\">\n <Spinner\n secondary={variation === VARIATION.DANGER}\n size={loaderSize[size]}\n />\n </span>\n <span className={`${labelClasses} o-0`}>{children}</span>\n </Fragment>\n ) : (\n <div className={labelClasses}>{children}</div>\n )}\n </Element>\n )\n}\n\nButtonPlain.defaultProps = {\n size: SIZE.REGULAR,\n variation: VARIATION.PLAIN,\n disabled: false,\n autoFocus: false,\n icon: false,\n type: 'button',\n isLoading: false,\n}\n\nButtonPlain.propTypes = propTypes\n\nexport default withForwardedRef(ButtonPlain)\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.