All files / src/tagsearchbox/valueselect PureInput.tsx

10% Statements 2/20
0% Branches 0/10
0% Functions 0/7
11.76% Lines 2/17

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                1x                     1x                                                                    
import React, { useEffect, forwardRef, useImperativeHandle } from "react";
 
export interface PureInputProps {
  inputValue: string;
  onChange: (value: any[]) => void;
  onSelect: (value: any[]) => void;
}
 
const keys = {
  "9": "tab",
  "13": "enter",
};
 
function getValue(value: string): any[] {
  return value.split("|").map(item => {
    return { name: item.trim() };
  });
}
 
export const PureInput = forwardRef(function Input(
  { onChange, inputValue, onSelect }: PureInputProps,
  ref
) {
  useEffect(() => {
    // 编辑完成时 inputValue 被置空,此时 onChange 会导致标签键寻找失败
    if (inputValue.trim()) {
      onChange(getValue(inputValue));
    }
  }, [inputValue, onChange]);
 
  useImperativeHandle(ref, () => ({
    handleKeyDown,
  }));
 
  function handleKeyDown(keyCode: number): boolean {
    if (!keys[keyCode]) {
      return false;
    }
 
    switch (keys[keyCode]) {
      case "tab":
      case "enter":
        if (inputValue.length <= 0) return false;
        if (onSelect) {
          onSelect(getValue(inputValue).filter(i => !!i.name));
        }
        return false;
    }
    return false;
  }
 
  return null;
});