/* Copyright (c) 2018-2020 Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ // @flow import * as React from 'react'; import {getOverrides} from '../helpers/overrides.js'; import { Action as StyledAction, Root as StyledRoot, ActionIcon as StyledActionIcon, Text as StyledText, } from './styled-components.js'; import {KIND, VARIANT, SIZE} from './constants.js'; import {getTextFromChildren} from './utils.js'; import type {PropsT, SharedPropsArgT} from './types.js'; import {isFocusVisible, forkFocus, forkBlur} from '../utils/focusVisible.js'; const Tag = React.forwardRef((props, ref) => { const { children, closeable = true, color, size = SIZE.small, disabled = false, isFocused = false, isHovered = false, kind = KIND.primary, onActionClick = event => {}, onActionKeyDown = event => {}, onClick = null, onKeyDown = null, overrides = {}, title, variant = VARIANT.light, } = props; const [focusVisible, setFocusVisible] = React.useState(false); function handleFocus(event: SyntheticEvent<>) { if (isFocusVisible(event)) { setFocusVisible(true); } } function handleBlur(event: SyntheticEvent<>) { if (focusVisible !== false) { setFocusVisible(false); } } function handleKeyDown(event: KeyboardEvent) { if (event.currentTarget !== event.target) { return; } const key = event.key; if (onClick && key === 'Enter') { onClick(event); } if (closeable && (key === 'Backspace' || key === 'Delete')) { onActionClick(event); onActionKeyDown(event); } if (onKeyDown) { onKeyDown(event); } } const [Root, rootProps] = getOverrides(overrides.Root, StyledRoot); const [Action, actionProps] = getOverrides(overrides.Action, StyledAction); const [ActionIcon, actionIconProps] = getOverrides( overrides.ActionIcon, StyledActionIcon, ); const [Text, textProps] = getOverrides(overrides.Text, StyledText); const clickable = typeof onClick === 'function'; const rootHandlers = disabled ? {} : { onClick: onClick, onKeyDown: handleKeyDown, }; const actionHandlers = disabled ? {} : { onClick: event => { // we don't want onClick to be called when the close icon is clicked event.stopPropagation(); onActionClick(event); }, }; const sharedProps: SharedPropsArgT = { $clickable: clickable, $closeable: closeable, $color: color, $disabled: disabled, $isFocused: isFocused, $isHovered: isHovered, $kind: kind, $variant: variant, $isFocusVisible: focusVisible, $size: size, }; const titleText = title || getTextFromChildren(children); const isButton = (clickable || closeable) && !disabled; const actionSize = { [SIZE.small]: '12', [SIZE.medium]: '16', [SIZE.large]: '20', }[size]; return ( {children} {closeable ? ( ) : null} ); }); Tag.displayName = 'Tag'; export default Tag; declare var __DEV__: boolean; declare var __NODE__: boolean; declare var __BROWSER__: boolean;