All files / src/select SelectMultiple.tsx

57.14% Statements 40/70
55.26% Branches 42/76
51.72% Functions 15/29
56.92% Lines 37/65

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                                                                                                                                                                                                                                                                                                13x   13x   4x                             25x 25x       4x   4x   4x   4x 4x                   4x                 4x 4x 2x 12x               12x           4x 25x     4x 4x     4x   4x                                     4x       25x                                       25x                                                           27x                                       8x 8x 2x     8x 4x 4x     1x             8x 4x   4x 4x                                              
import React, { useState, useRef, useEffect } from "react";
import { Combine, StyledProps } from "../_type";
import { DropdownProps, Dropdown, CommonDropdownProps } from "../dropdown";
import { List } from "../list";
import { Checkbox } from "../checkbox";
import { useDefaultValue, ControlledProps, ChangeContext } from "../form";
import { SelectOption } from "./SelectOption";
import { CheckTree } from "../checktree";
import { Button } from "../button";
import { useTranslation } from "../i18n";
import { withStatics } from "../_util/with-statics";
import { useConfig } from "../_util/config-context";
import { EmptyTip } from "../tips";
import { SearchBox } from "../searchbox";
import { SelectSearchProps } from "./SelectProps";
import { injectValue } from "../_util/inject-value";
 
export interface SelectMultipleProps
  extends Combine<
    SelectSearchProps<SelectOption>,
    CommonDropdownProps,
    StyledProps,
    ControlledProps<string[]>
  > {
  /**
   * 选项列表
   */
  options?: SelectOption[];
 
  /**
   * 表示全选的选项
   */
  allOption?: SelectOption | false;
 
  /**
   * 如果开启了全选支持,则可以指定哪些记录从全选的范围内排除
   *
   * - 默认为 'disabled' 可以排除禁用的记录
   * - 提供回调则自定义哪些记录应该排除,对于应该排除的记录,应该返回 `true`
   *
   * @default "disabled"
   */
  shouldOptionExcludeFromAll?: "disabled" | ((option: SelectOption) => boolean);
 
  /**
   * 允许不选择项
   *
   * @default true
   */
  allowEmpty?: boolean;
 
  /**
   * 是否暂存操作结果
   *
   * - 设置为 `true`,则会提供确定和取消按钮,确定后才会触发 onChange
   * - 设置为 `false`,则不渲染确定和取消按钮,修改后直接触发 onChange
   *
   * @default true
   */
  staging?: boolean;
 
  /**
   * 占位符
   * @default "请选择"(已处理国际化)
   */
  placeholder?: string;
 
  /**
   * 是否禁用
   * @default false
   */
  disabled?: boolean;
 
  /**
   * 下拉选框的外观
   *
   * - `default` 无边框,适用于页面标题和表格内
   * - `button` 为按钮风格,有边框,多用于操作栏中
   * - `link` 为超链接风格
   * - `filter` 为过滤组件风格,多用于表头筛选
   * - `pure` 无额外样式
   *
   * 原有 `raw` 类型建议使用 `pure` 进行改造
   *
   * @default "default"
   * @version 2.0.9
   */
  appearance?: DropdownProps["appearance"];
 
  /**
   * **\[Deprecated\]** 请使用 `appearance` 属性
   * @deprecated
   */
  appearence?: DropdownProps["appearence"];
 
  /**
   * 按钮显示内容,默认会显示当前选中的选项
   *
   * @docType React.ReactNode | ((selectedOptions: SelectOption[]) => React.ReactNode)
   */
  button?:
    | React.ReactNode
    | ((selectedOptions: SelectOption[]) => React.ReactNode);
 
  /**
   * 下拉框大小
   */
  size?: DropdownProps["size"];
 
  /**
   * 弹出区域自定义类名
   */
  boxClassName?: DropdownProps["boxClassName"];
 
  /**
   * 弹出区域自定义样式
   */
  boxStyle?: DropdownProps["boxStyle"];
 
  /**
   * 可使用字符串或 [StatusTip](/component/tips) 相关组件
   */
  tips?: React.ReactNode;
 
  /**
   * 是否在下拉框收起后清空搜索框
   * @default true
   * @version 2.1.0
   */
  autoClearSearchValue?: boolean;
 
  /**
   * 展开时回调
   * @version 2.1.0
   */
  onOpen?: DropdownProps["onOpen"];
 
  /**
   * 收起时回调
   * @version 2.1.0
   */
  onClose?: DropdownProps["onClose"];
}
 
const noop = () => null;
 
export const SelectMultiple = withStatics(
  function SelectMultiple(props: SelectMultipleProps) {
    const { classPrefix } = useConfig();
    const {
      staging = true,
      value,
      onChange,
      options = [],
      allOption,
      shouldOptionExcludeFromAll = "disabled",
      allowEmpty = true,
      onOpen = noop,
      onClose = noop,
      searchable,
      searchPlaceholder = "",
      onSearch = noop,
      filter = (inputValue: string, { text, value }: SelectOption) => {
        const optionText = String(typeof text === "string" ? text : value);
        return !searchable || optionText.includes(inputValue);
      },
      autoClearSearchValue = true,
      ...dropdownProps
    } = useDefaultValue(props, []);
 
    const t = useTranslation();
 
    const [stagingValue, setStagingValue] = useState<string[]>(value);
 
    const InputRef = useRef<HTMLInputElement>(null);
    const [inputValue, setInputValue] = useState<string>("");
    function focus() {
      if (searchable) {
        setTimeout(() => {
          if (InputRef.current) {
            InputRef.current.focus();
          }
        }, 100); // 第一次展开时 Input 还未渲染
      }
    }
    const handleChange = (value: string[], context: ChangeContext) => {
      if (staging === false) {
        onChange(value, context);
        return;
      }
      setStagingValue(value);
    };
 
    // 「全部」选项和其余选项是数关系
    const relations = {};
    if (allOption) {
      for (const option of options) {
        Iif (
          // 用户可以指定哪些选项从全选逻辑中排除
          (typeof shouldOptionExcludeFromAll === "function" &&
            shouldOptionExcludeFromAll(option)) ||
          (shouldOptionExcludeFromAll === "disabled" && option.disabled)
        ) {
          // continue
        } else {
          relations[option.value] = allOption.value;
        }
      }
    }
 
    // 筛选
    const filteredOptions = options.filter(options =>
      filter(inputValue, options)
    );
 
    let { tips } = props;
    Iif (!tips && filteredOptions.length === 0) {
      tips = <EmptyTip />;
    }
    tips = tips ? <List.StatusTip>{tips}</List.StatusTip> : null;
 
    return (
      <Dropdown
        {...dropdownProps}
        updateOnChildrenChange
        button={<ValueBrief {...props} value={value} />}
        onOpen={() => {
          setStagingValue(value);
          focus();
          onOpen();
        }}
        onClose={() => {
          if (autoClearSearchValue && inputValue !== "") {
            setInputValue("");
          }
          onClose();
        }}
        clickClose={false}
      >
        {close => (
          <CheckTree
            relations={relations}
            value={(staging ? stagingValue : value) || value}
            onChange={handleChange}
            disabledNames={options.filter(x => x.disabled).map(x => x.value)}
          >
            {searchable && (
              <SearchBox
                simple
                ref={InputRef}
                value={inputValue}
                onChange={value => {
                  setInputValue(value);
                  onSearch(value);
                }}
                onClear={focus}
                placeholder={searchPlaceholder}
              />
            )}
            <List type="option" className={`${classPrefix}-list--checkoption`}>
              {allOption &&
                options.length === filteredOptions.length &&
                renderSelectOption(allOption)}
              {tips}
              {filteredOptions.map(option => renderSelectOption(option))}
            </List>
            {staging !== false && (
              <Dropdown.Footer>
                <Button
                  type="primary"
                  disabled={!allowEmpty && stagingValue.length === 0}
                  onClick={event => {
                    onChange(stagingValue, { event });
                    close();
                  }}
                >
                  {t.okText}
                </Button>
                <Button type="weak" onClick={close}>
                  {t.cancelText}
                </Button>
              </Dropdown.Footer>
            )}
          </CheckTree>
        )}
      </Dropdown>
    );
  },
  {
    defaultLabelAlign: "middle",
  }
);
 
function renderSelectOption(option: SelectOption): JSX.Element {
  return (
    <List.Item
      key={option.value}
      tooltip={option.tooltip}
      disabled={option.disabled}
    >
      <Checkbox onClick={evt => evt.stopPropagation()} name={option.value}>
        {option.text || option.value}
      </Checkbox>
    </List.Item>
  );
}
 
function ValueBrief({
  value,
  allOption,
  options,
  button,
  placeholder,
}: SelectMultipleProps): JSX.Element {
  const t = useTranslation();
  const [selectedOptions, setSelectedOptions] = useState<SelectOption[]>(
    value.map(x => options.find(y => y.value === x)).filter(Boolean)
  );
  // options 变化时不影响已选择值显示
  useEffect(() => {
    setSelectedOptions(selectedOptions => {
      return value
        .map(
          v =>
            options.find(option => option.value === v) ||
            selectedOptions.find(option => option.value === v)
        )
        .filter(Boolean);
    });
  }, [value]); // eslint-disable-line react-hooks/exhaustive-deps
 
  if (button) {
    return <>{injectValue(button)(selectedOptions)}</>;
  }
  Eif (!value || !value.length) {
    return <>{placeholder || t.pleaseSelect}</>;
  }
  if (
    allOption &&
    value.length === options.length &&
    value.filter(v => options.find(o => o.value === v)).length ===
      options.length
  ) {
    return <>{allOption.text || allOption.value}</>;
  }
 
  const exceed = selectedOptions.length > 5;
 
  return (
    <span title={selectedOptions.map(o => o.text || o.value).join(", ")}>
      {selectedOptions
        .slice(0, 5)
        .map(o => o.text || o.value)
        .join(", ")}
      {exceed && "..."}
    </span>
  );
}