import React, { useCallback, useEffect, useRef, useState } from "react"; import PropTypes from "prop-types"; import IconButton from "../../icon-button"; import Tooltip from "../../tooltip"; import { useClickOutside } from "../../utils/useClickOutside.js"; import { DeleteIcon, WarningIcon } from "../svg"; import { MAX_EMAIL_LENGTH, MAX_EMAIL_LENGTH_WITH_DOTS, sliceEmail, } from "./helpers"; import { StyledChip, StyledChipInput, StyledChipValue, StyledContainer, } from "../styled-emailchips.js"; const Chip = (props) => { const { value, currentChip, isSelected, isValid, invalidEmailText, chipOverLimitText, onDelete, onDoubleClick, onSaveNewChip, onClick, } = props; function initNewValue() { return value?.email === value?.name || value?.name === "" ? value?.email : `"${value?.name}" <${value?.email}>`; } const [newValue, setNewValue] = useState(initNewValue()); const [chipWidth, setChipWidth] = useState(0); const [isChipOverLimit, setIsChipOverLimit] = useState(false); const tooltipRef = useRef(null); const warningRef = useRef(null); const chipRef = useRef(null); const chipInputRef = useRef(null); useEffect(() => { setChipWidth(chipRef.current?.clientWidth); }, [chipRef]); useEffect(() => { if (isSelected) { chipRef.current?.scrollIntoView({ block: "end" }); } }, [isSelected]); useEffect(() => { if (newValue.length > MAX_EMAIL_LENGTH) { setIsChipOverLimit(true); } else { setIsChipOverLimit(false); } }, [newValue]); useClickOutside(warningRef, () => tooltipRef.current.hideTooltip()); useClickOutside( chipInputRef, () => { onSaveNewChip(value, newValue); }, newValue ); const onChange = (e) => { if ( e.target.value.length <= MAX_EMAIL_LENGTH_WITH_DOTS || e.target.value.length < newValue.length ) { setNewValue(e.target.value); } }; const onClickHandler = (e) => { if (e.shiftKey) { document.getSelection().removeAllRanges(); } onClick(value, e.shiftKey); }; const onDoubleClickHandler = () => { onDoubleClick(value); }; const onIconClick = () => { onDelete(value); }; const onInputKeyDown = useCallback( (e) => { const code = e.code; switch (code) { case "Enter": case "NumpadEnter": { onSaveNewChip(value, newValue); setNewValue(sliceEmail(newValue).email); break; } case "Escape": { setNewValue(initNewValue()); onDoubleClick(null); return false; } } }, [newValue] ); if (value?.email === currentChip?.email) { return ( {isChipOverLimit && ( {}} id="input" effect="float" /> )} ); } return ( {!isValid && (
{}} id="group" reference={tooltipRef} place={"top"} />
)} {value?.name || value?.email}
); }; Chip.propTypes = { value: PropTypes.object, currentChip: PropTypes.object, isSelected: PropTypes.bool, isValid: PropTypes.bool, invalidEmailText: PropTypes.string, chipOverLimitText: PropTypes.string, onClick: PropTypes.func, onDoubleClick: PropTypes.func, onDelete: PropTypes.func, onSaveNewChip: PropTypes.func, }; export default Chip;