docbrown/app/javascript/shared/components/defaultSelectionTemplate.jsx
Ridhwana ffa5e023bb
Implementing validation for the Multi Input Crayons Component (#18185)
* WIP: add the validation

* feat/WIP: set the color of the button to red

* feat: change color temporarily

* feat: add accessibility for validation

* feat: add the styling changes for the multi input

* feat: add focus visible styling as well

* fix: add comma to scss file to separate attributes

* chore: rename regex to inputRegex

* refactor: move out validation into a function

* chore: rename regex to inputRegex

* feat: add a validation Regex as a prop

* feat: update the text description

* chore: update spelling oops

* feat: remove comment

* remove comments

* rename error

* feat: add showLabel and labelText to the stories component

* cater for when we don't pass in a validationRegex

* some small tweaks

Co-authored-by: Suzanne Aitchison <suzanne@forem.com>
2022-07-22 12:51:06 +01:00

71 lines
2 KiB
JavaScript

import { h } from 'preact';
import PropTypes from 'prop-types';
import { Icon, ButtonNew as Button } from '@crayons';
import { Close } from '@images/x.svg';
/**
* Responsible for the layout of a selected item in the crayons autocomplete and multi input components
*
* @param {string} name The selected item name
* @param {string} buttonVariant Optional button variant
* @param {string} className Optional classname for selected item
* @param {Function} onEdit Callback for edit click on the name of the selected item
* @param {Function} onDeselect Callback for deselect click on the close icon
*/
export const DefaultSelectionTemplate = ({
name,
enableValidation = false,
valid = true,
buttonVariant = 'default',
className = 'c-autocomplete--multi__selected',
onEdit,
onDeselect,
}) => {
const conditionalAttributes = () => {
if (enableValidation) {
return { 'aria-describedby': `invalid-item-${name}` };
}
return {};
};
return (
<>
{enableValidation && (
<div
id={`invalid-item-${name}`}
className="screen-reader-only"
aria-live="assertive"
>
{!valid ? 'Invalid entry' : ''}
</div>
)}
<div role="group" aria-label={name} className="flex mr-1 mb-1 w-max">
<Button
variant={buttonVariant}
className={`${className} p-1 cursor-text`}
aria-label={`Edit ${name}`}
{...conditionalAttributes()}
onClick={onEdit}
>
{name}
</Button>
<Button
variant={buttonVariant}
className={`${className} p-1`}
aria-label={`Remove ${name}`}
onClick={onDeselect}
>
<Icon src={Close} />
</Button>
</div>
</>
);
};
DefaultSelectionTemplate.propTypes = {
name: PropTypes.string.isRequired,
buttonVariant: PropTypes.string,
className: PropTypes.string,
onEdit: PropTypes.func.isRequired,
onDeselect: PropTypes.func.isRequired,
};