All files / src/cascader CascaderBox.tsx

10% Statements 4/40
0% Branches 0/23
6.25% Functions 1/16
10.26% Lines 4/39

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                              3x   3x 3x               3x                                                                                                                                                                                                                                                            
import React, { useMemo, useState, useLayoutEffect } from "react";
import classNames from "classnames";
import { DropdownBox } from "../dropdown/Dropdown";
import {
  CascaderBoxProps,
  CascaderData,
  CascaderOption,
} from "./CascaderProps";
import { Tabs, TabPanel } from "../tabs";
import { CascaderLoading } from "./CascaderLoading";
 
export function getOptions(
  data: CascaderData,
  valueList: CascaderBoxProps["value"]
): CascaderOption[] {
  const options = [];
 
  let curLevel = data;
  valueList.forEach(value => {
    const option = curLevel.options.find(option => option.value === value);
    options.push(option);
    if (option && option.child) {
      curLevel = option.child;
    }
  });
 
  return options;
}
 
export function CascaderBox({
  data,
  value,
  onChange,
  onLoad,
  onClose,
  changeOnSelect,
  className,
  style,
  scheduleUpdate,
  classPrefix,
}: CascaderBoxProps & { scheduleUpdate: () => void }) {
  // 内部状态
  const [internalValue, setInternalValue] = useState(value);
  useLayoutEffect(() => {
    setInternalValue(value);
  }, [value]);
 
  // 面板
  const panels = useMemo(() => {
    const panels = [data];
    internalValue.forEach(value => {
      const option = panels[panels.length - 1].options.find(
        option => option.value === value
      );
      if (option && option.child) {
        panels.push(option.child);
      }
    });
    return panels;
  }, [data, internalValue]);
  const [curPanelIndex, setCurPanelIndex] = useState(panels.length - 1);
 
  useLayoutEffect(() => {
    if (scheduleUpdate) {
      scheduleUpdate();
    }
  }, [curPanelIndex, scheduleUpdate]);
 
  function handleSelect(index, value, { event, hasChild }) {
    const newValue = [...internalValue.slice(0, index), value];
    if (changeOnSelect) {
      onChange(newValue, { event, options: getOptions(data, newValue) });
    } else {
      setInternalValue(newValue);
      if (!hasChild) {
        onChange(newValue, { event, options: getOptions(data, newValue) });
      }
    }
 
    if (hasChild) {
      setCurPanelIndex(index + 1);
    } else {
      onClose();
    }
  }
 
  return (
    <DropdownBox className={className} style={style}>
      <div
        className={classNames(
          `${classPrefix}-cascader-menu`,
          `${classPrefix}-cascader-menu__col${(panels[curPanelIndex] &&
            panels[curPanelIndex].col) ||
            4}`
        )}
      >
        <Tabs
          className={`${classPrefix}-tabs--bordered`}
          animated={false}
          activeId={String(curPanelIndex)}
          onActive={({ id }) => setCurPanelIndex(+id)}
          tabs={panels.map(({ title }, index) => ({
            id: String(index),
            label: title,
          }))}
        >
          {panels.map(({ options }, index) => {
            return (
              <TabPanel id={String(index)} key={index}>
                {options ? (
                  <ul className={`${classPrefix}-cascader-menu__list`}>
                    {options.map(({ value, label, child }) => (
                      <li key={value}>
                        <div
                          className={classNames(
                            `${classPrefix}-cascader-menu__label`,
                            {
                              "is-selected": internalValue[index] === value,
                            }
                          )}
                          onClick={event =>
                            handleSelect(index, value, {
                              event,
                              hasChild: Boolean(child),
                            })
                          }
                        >
                          {label || value}
                        </div>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <ul
                    className={`${classPrefix}-cascader-menu__list`}
                    style={{ margin: 0 }}
                  >
                    <CascaderLoading
                      onLoad={() =>
                        onLoad(internalValue, getOptions(data, internalValue))
                      }
                    />
                  </ul>
                )}
              </TabPanel>
            );
          })}
        </Tabs>
      </div>
    </DropdownBox>
  );
}