All files / src/tagselect TagSelect.tsx

35.24% Statements 37/105
35.06% Branches 27/77
42.42% Functions 14/33
34.34% Lines 34/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368                                                                                                                                                                                          1x     6x 6x                                   15x 15x                 6x   6x 6x 6x 6x 6x   6x   6x 15x 15x     6x                             6x 3x     6x 2x 2x   1x               6x           6x   6x 6x       6x       6x     6x   8x                                                                                                   3x                                                                                                                                                                                                                                         4x 4x 4x          
import React, { useState, useRef, useEffect } from "react";
import classNames from "classnames";
import { StyledProps, Combine } from "../_type";
import { ControlledProps, useDefaultValue } from "../form";
import { CommonDropdownProps, DropdownProps } from "../dropdown";
import { useTranslation } from "../i18n";
import { useConfig } from "../_util/config-context";
import { Popover, TriggerProps } from "../popover";
import { Tag } from "../tag";
import { useOutsideClick } from "../_util/use-outside-click";
import { EmptyTip } from "../tips";
import { useDefault } from "../_util/use-default";
import { SelectOption } from "../select/SelectOption";
import { TagSelectInput } from "./TagSelectInput";
import { TagSelectBox, TagSelectBoxProps, getListItems } from "./TagSelectBox";
import { KeyCode } from "../_util/key-code";
 
// 整个 标签选择输入框的 属性
export interface TagSelectProps
  extends Combine<
    CommonDropdownProps,
    ControlledProps<
      string[],
      React.SyntheticEvent,
      { event: React.SyntheticEvent; option: SelectOption }
    >,
    StyledProps
  > {
  /**
   * 下拉选项列表
   */
  options?: SelectOption[];
 
  /**
   * 是否仅能选择 `options` 中的值
   *
   * @default false
   */
  optionsOnly?: boolean;
 
  /**
   * 自定义搜索筛选规则
   *
   * 默认根据输入值筛选
   */
  filter?: (inputValue: string, option: SelectOption) => boolean;
 
  /**
   * 搜索值变化回调
   */
  onSearch?: (inputValue: string) => void;
 
  /**
   * 当输入框获得焦点时调用此函数
   */
  onFocus?: (e: React.FocusEvent) => void;
 
  /**
   * 输入框中的提示
   * @default "请选择"(已处理国际化)
   */
  placeholder?: string;
 
  /**
   * 弹出区域自定义类名
   */
  boxClassName?: DropdownProps["boxClassName"];
 
  /**
   * 弹出区域自定义样式
   */
  boxStyle?: DropdownProps["boxStyle"];
 
  /**
   * 状态提示
   *
   * 可使用字符串或 [StatusTip](/component/tips) 相关组件
   */
  tips?: React.ReactNode;
 
  /**
   * 是否在选项选中后自动清空搜索值
   * @default true
   */
  autoClearSearchValue?: boolean;
 
  /**
   * 滚动到底部事件
   * @version 2.1.0
   */
  onScrollBottom?: TagSelectBoxProps["onScrollBottom"];
}
 
const noop = () => {};
 
export function TagSelect(props: TagSelectProps) {
  const t = useTranslation();
  const { classPrefix } = useConfig();
  const {
    options = [],
    optionsOnly,
    value,
    onChange,
    placeholder = t.pleaseSelect,
    className,
    style,
    boxClassName,
    boxStyle = {},
    placement = "bottom-start",
    placementOffset = 5,
    closeOnScroll = true,
    escapeWithReference,
    onSearch = noop,
    onFocus = noop,
    filter = (inputValue: string, { text, value }: SelectOption) => {
      const optionText = String(typeof text === "string" ? text : value);
      return optionText.includes(inputValue);
    },
    defaultOpen = false,
    open,
    onOpenChange,
    autoClearSearchValue = true,
    overlayClassName,
    overlayStyle,
    onScrollBottom = () => null,
  } = useDefaultValue(props, []);
 
  const [isOpened, setIsOpened] = useDefault(open, defaultOpen, onOpenChange);
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  const [wrapperWidth, setWrapperWidth] = useState<number>(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const [inputValue, setInputValue] = useState<string>("");
 
  const listRef = useRef(null);
 
  const filteredOptions = options
    .filter(options => filter(inputValue, options))
    .filter(option => !value.includes(option.value));
 
  // 支持输入任意值
  Iif (!optionsOnly && inputValue.trim()) {
    // 是否有和搜索值相同的项
    const hasEqualOption = options.find(({ text, value }) => {
      const optionText = String(typeof text === "string" ? text : value);
      return optionText.trim() === inputValue.trim();
    });
    // 是否有和搜索值相同的值
    const hasEqualValue = value.find(v => v.trim() === inputValue.trim());
 
    if (!hasEqualOption && !hasEqualValue) {
      filteredOptions.unshift({ value: inputValue.trim() });
    }
  }
 
  // options 变化时不影响已选择的 value 显示
  const [displayOptions, setDisplayOptions] = useState<SelectOption[]>(
    value.map(v => options.find(option => option.value === v) || { value: v })
  );
 
  const updateDisplayOptions = (value: string[]) =>
    setDisplayOptions(displayOptions => {
      return value.map(
        v =>
          options.find(option => option.value === v) ||
          displayOptions.find(option => option.value === v) || {
            value: v,
          }
      );
    });
 
  // onChange 前更新 displayOptions 保证 onChange 中改变 options 时信息不丢失
  const handleChange: TagSelectProps["onChange"] = (value, context) => {
    updateDisplayOptions(value);
    onChange(value, context);
  };
 
  // options 变化时不影响已选择值显示
  useEffect(() => updateDisplayOptions(value), [value]); // eslint-disable-line react-hooks/exhaustive-deps
 
  let { tips } = props;
  Iif (typeof tips === "undefined" && filteredOptions.length === 0) {
    tips = <EmptyTip />;
  }
 
  const items = getListItems({
    tips,
    options: filteredOptions,
  });
  const count = items.length;
 
  // 渲染数据
  return (
    <div
      ref={ref => ref && setWrapperWidth(ref.clientWidth)}
      className={classNames(`${classPrefix}-tag-input`, className, {
        "is-active": isOpened,
      })}
      style={style}
      onClick={() => inputRef.current.focus()}
    >
      <Popover
        trigger={ClickTrigger}
        visible={isOpened}
        onVisibleChange={setIsOpened}
        placement={placement}
        closeOnScroll={closeOnScroll}
        escapeWithReference={escapeWithReference}
        placementOffset={placementOffset}
        overlayClassName={overlayClassName}
        overlayStyle={overlayStyle}
        overlay={({ scheduleUpdate }) => (
          <TagSelectBox
            listRef={listRef}
            items={items}
            itemRefContent={
              filteredOptions[0]
                ? filteredOptions[0].text || filteredOptions[0].value
                : undefined
            }
            currentIndex={currentIndex % count}
            width={wrapperWidth}
            onChange={(optionValue, context) => {
              handleChange([...value, optionValue], context);
              if (autoClearSearchValue && inputValue) {
                setInputValue("");
                setCurrentIndex(0);
              }
              inputRef.current.focus();
            }}
            scheduleUpdate={scheduleUpdate}
            className={boxClassName}
            style={boxStyle}
            tips={tips}
            onScrollBottom={onScrollBottom}
          />
        )}
      >
        <div
          className={`${classPrefix}-tag-input__inner`}
          style={{ cursor: "text" }}
        >
          <div className={`${classPrefix}-tag-group`}>
            {displayOptions.map(option => (
              <Tag
                key={option.value}
                onClose={event => {
                  event.stopPropagation();
                  handleChange(value.filter(v => v !== option.value), {
                    event,
                    option,
                  });
                  inputRef.current.focus();
                }}
              >
                {option.text || option.value}
              </Tag>
            ))}
            <TagSelectInput
              ref={inputRef}
              className={`${classPrefix}-input--tag`}
              placeholder={value.length === 0 ? placeholder : ""}
              onFocus={e => {
                setIsOpened(true);
                onFocus(e);
              }}
              value={inputValue}
              onChange={value => {
                onSearch(value);
                setInputValue(value);
                setCurrentIndex(0);
              }}
              maxWidth={Math.max(wrapperWidth - 12, 0)}
              onKeyDown={(
                event: React.KeyboardEvent<
                  HTMLInputElement | HTMLTextAreaElement
                >
              ) => {
                const { option } = items[currentIndex % count] || {};
                const getOptionIndex = (current: number, step: number = 1) => {
                  let flag = 1;
                  let index = (current + step + count) % count;
                  let item = items[index % count];
                  while (flag < count && !item.option) {
                    flag += 1;
                    index = (index + step + count) % count;
                    item = items[index % count];
                  }
                  return index;
                };
 
                switch (event.keyCode) {
                  case KeyCode.Backspace:
                    if (
                      event.currentTarget.value.length === 0 &&
                      value.length > 0
                    ) {
                      handleChange(value.slice(0, -1), {
                        event,
                        option: options.find(
                          option => option.value === value[value.length - 1]
                        ),
                      });
                      setCurrentIndex(0);
                    }
                    break;
 
                  case KeyCode.Enter:
                    if (isOpened && option && !option.disabled) {
                      handleChange([...value, option.value], { event, option });
                      if (autoClearSearchValue && inputValue) {
                        setInputValue("");
                        setCurrentIndex(0);
                      }
                    }
                    break;
 
                  case KeyCode.Up:
                    event.preventDefault();
                    setCurrentIndex(c => {
                      const index = getOptionIndex(c, -1);
                      if (listRef.current) {
                        listRef.current.scrollToItem(index);
                      }
                      return index;
                    });
                    break;
 
                  case KeyCode.Down:
                    event.preventDefault();
                    setCurrentIndex(c => {
                      const index = getOptionIndex(c);
                      if (listRef.current) {
                        listRef.current.scrollToItem(index);
                      }
                      return index;
                    });
                    break;
 
                  case KeyCode.Esc:
                    setIsOpened(false);
                    inputRef.current.blur();
                    break;
                }
              }}
            />
          </div>
        </div>
      </Popover>
    </div>
  );
}
 
function ClickTrigger({
  overlayElementRef,
  childrenElementRef,
  visible,
  setVisible,
  closeDelay = 0,
  render,
}: TriggerProps) {
  const { listen } = useOutsideClick([childrenElementRef, overlayElementRef]);
  listen(() => visible && setVisible(false, closeDelay));
  return render({
    overlayProps: {},
    childrenProps: {},
  });
}