All files / src/checktree CheckTree.tsx

62.3% Statements 76/122
55.07% Branches 38/69
60.87% Functions 14/23
62.18% Lines 74/119

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 369 370 371 372 373 374 375 376 377 378 379                                                                                                                                  15x 15x   15x 15x   15x                     15x       116x         116x       116x                     116x   116x   116x         4x           4x         4x 4x                                 15x   15x 5x 35x 2x 2x         15x           4x                       15x     15x     15x   110x     110x 110x 45x 45x   110x       15x     15x           15x   15x     465x 102x                                                                                                               221x 93x     128x     128x 88x       88x 88x     40x 40x 40x 105x 105x 20x   105x 87x       40x       40x   40x         18x       18x     18x 12x 6x   6x         6x 14x           4x                 4x 4x                                           4x 3x   1x       4x   4x     15x                
import React, { useState, useMemo } from "react";
import warning from "warning";
import { CheckContext } from "../check";
import { CheckChangeContext, CheckProps } from "../check/Check";
import { ControlledProps, useDefaultValue } from "../form/controlled";
 
export interface CheckTreeProps extends ControlledProps<string[]> {
  /**
   * 已勾选的叶子节点的 name 集合
   */
  value?: string[];
 
  /**
   * 勾选的节点变更时回调
   */
  onChange?: (value: string[], context: CheckChangeContext) => void;
 
  /**
   * 提供树的节点关系,每个子节点对应其父节点
   */
  relations: CheckTreeRelation;
 
  /**
   * 组件树内容,内部的 <Checkbox /> 状态将被托管
   */
  children?: React.ReactNode;
 
  /**
   * 禁用的控件 name
   */
  disabledNames?: string[];
 
  /**
   * 是否支持按 Shift 快捷键时多选
   * @default true
   */
  shiftSelect?: boolean;
 
  // /**
  //  * disabled 的组件是否从全选的范围内排除
  //  * @default true
  //  */
  // excludeDisabledFromParent?: boolean;
}
 
/**
 * CheckTree 关系定义 interface
  ```ts
  interface CheckTreeRelation {
    [child: string]: string;
  }
  ```
 */
export interface CheckTreeRelation {
  [child: string]: string;
}
 
export function CheckTree(props: CheckTreeProps) {
  const {
    relations,
    children,
    value,
    onChange,
    shiftSelect = true,
    disabledNames = [],
  } = useDefaultValue(props);
  const [prevCheck, setPrevCheck] = useState<string>(null);
 
  const disabledSet = completeDisabledNames(relations, disabledNames);
  const model = useMemo(
    () =>
      getTreeModel(
        relations,
        value,
        disabledSet,
        shiftSelect,
        prevCheck,
        setPrevCheck
      ),
    [disabledSet, prevCheck, relations, shiftSelect, value]
  );
 
  return (
    <CheckContext.Provider
      value={{
        inject(checkProps) {
          Iif (checkProps.type !== "checkbox") {
            return checkProps;
          }
 
          // 没有 name 时不受控
          Iif (typeof checkProps.name === "undefined") {
            return checkProps;
          }
 
          warning(
            typeof checkProps.value === "undefined",
            'Component managed by <CheckTree> will ignore the "value" prop'
          );
 
          // [TODO] Table seclectable
          // warning(
          //   typeof checkProps.disabled === 'undefined',
          //   'Component managed by <CheckTree> will ignore the "disabled" prop'
          // );
 
          model.visit(checkProps);
 
          const checkName = checkProps.name;
 
          return {
            ...model.getNodeState(checkName),
            disabled: disabledNames.includes(checkProps.name),
            // 支持 checkbox 上的 onChange 处理时阻止默认的处理行为
            onChange: (checked, context) => {
              Iif (typeof checkProps.onChange === "function") {
                checkProps.onChange(checked, context);
                if (context.event.defaultPrevented) {
                  return;
                }
              }
              const selection = model.handleChange(
                checkProps.name,
                checked,
                context.event
              );
              Eif (typeof onChange === "function") {
                onChange(selection, context);
              }
            },
            ...checkProps,
          };
        },
      }}
    >
      {children}
    </CheckContext.Provider>
  );
}
 
function completeDisabledNames(
  relations: CheckTreeRelation,
  names: string[]
): Set<string> {
  const nameSet = new Set<string>(names);
 
  for (let i = 0; i < names.length; ++i) {
    Object.entries(relations).forEach(([child, parent]) => {
      if (names[i] === parent && !nameSet.has(child)) {
        nameSet.add(child);
        names.push(child);
      }
    });
  }
 
  return nameSet;
}
 
function isEventWithShiftKey(
  event: React.SyntheticEvent
): event is React.SyntheticEvent & { shiftKey: boolean } {
  return "shiftKey" in event;
}
 
function getTreeModel(
  relations: CheckTreeRelation,
  selection: string[],
  disabledSet: Set<string>,
  shiftSelect: boolean,
  prevCheck: string,
  setPrevCheck: (name: string) => void
) {
  // find parent via child
  const parentMap = new Map<string, string>();
 
  // find chilren via parent
  const childrenMap = new Map<string, Set<string>>();
 
  // build the parent map and children map for perfomance
  for (const [child, parent] of Object.entries(relations)) {
    // set parent for child
    parentMap.set(child, parent);
 
    // set children for parent
    let childrenSet = childrenMap.get(parent);
    if (!childrenSet) {
      childrenSet = new Set<string>();
      childrenMap.set(parent, childrenSet);
    }
    childrenSet.add(child);
  }
 
  // selected leaf
  const selectionSet = new Set<string>(selection);
 
  // find node state via checkName
  const nodeStateMap = new Map<
    string,
    { value: boolean; indeterminate: boolean }
  >();
 
  // classify check by level
  let levelMap: string[][] = [[]];
 
  const visited: CheckProps[] = [];
 
  function visit(check: CheckProps) {
    if (!visited.find(({ name }) => name === check.name)) {
      visited.push(check);
    }
  }
 
  function calcLevel() {
    const roots = visited
      .filter(check => !parentMap.has(check.name))
      .map(c => c.name);
 
    if (roots.length) {
      let curLevel = 0;
      levelMap = [roots];
      const nameSet = new Set<string>(roots);
 
      while (true) {
        levelMap[curLevel + 1] = [];
        /* eslint-disable no-loop-func */
        levelMap[curLevel].forEach(checkName => {
          if (childrenMap.has(checkName)) {
            const children = childrenMap.get(checkName);
            visited.forEach(({ name }) => {
              if (children.has(name) && !nameSet.has(name)) {
                nameSet.add(name);
                levelMap[curLevel + 1].push(name);
              }
            });
          }
        });
        /* eslint-enable no-loop-func */
        curLevel += 1;
        if (!levelMap[curLevel].length) {
          break;
        }
      }
    }
  }
 
  function getVisitedIndex(checkName: string) {
    let index;
    let level;
    levelMap.forEach((checks, _level) => {
      checks.forEach((name, _index) => {
        if (name === checkName) {
          level = _level;
          index = _index;
        }
      });
    });
    return [level, index];
  }
 
  function getVisitedName(level: number, index: number) {
    return levelMap[level][index];
  }
 
  function getNodeState(checkName: string) {
    if (nodeStateMap.has(checkName)) {
      return nodeStateMap.get(checkName);
    }
 
    const children = childrenMap.get(checkName);
 
    // 叶子节点直接看是否在选取里
    if (!children) {
      const nodeState = {
        value: selectionSet.has(checkName),
        indeterminate: false,
      };
      nodeStateMap.set(checkName, nodeState);
      return nodeState;
    }
 
    let hasTouchedChild = false;
    let isAllChildrenChecked = true;
    for (const child of children) {
      const childState = getNodeState(child);
      if (childState.value || childState.indeterminate) {
        hasTouchedChild = true;
      }
      if (!childState.value) {
        isAllChildrenChecked = false;
      }
    }
 
    const nodeState = {
      value: isAllChildrenChecked,
      indeterminate: !isAllChildrenChecked && hasTouchedChild,
    };
    nodeStateMap.set(checkName, nodeState);
 
    return nodeState;
  }
 
  function setNodeState(checkName: string, checked: boolean) {
    // disabled
    Iif (disabledSet.has(checkName)) {
      return;
    }
 
    const children = childrenMap.get(checkName);
 
    // 叶子节点,直接设置
    if (!children) {
      if (checked) {
        selectionSet.add(checkName);
      } else {
        selectionSet.delete(checkName);
      }
    }
    // 递归设置
    else {
      for (const child of children) {
        setNodeState(child, checked);
      }
    }
  }
 
  function getSelection() {
    return Array.from(selectionSet);
  }
 
  function handleChange(
    checkName: string,
    checked: boolean,
    event: React.SyntheticEvent
  ) {
    // 多选
    Eif (shiftSelect) {
      Iif (event && isEventWithShiftKey(event) && event.shiftKey) {
        calcLevel();
        const [level, index] = getVisitedIndex(checkName);
        if (prevCheck !== null) {
          const [prevLevel, prevIndex] = getVisitedIndex(prevCheck);
          if (level === prevLevel) {
            // 清空文字选区
            if ("getSelection" in window) {
              window.getSelection().removeAllRanges();
            }
 
            const min = index < prevIndex ? index : prevIndex;
            const max = index > prevIndex ? index : prevIndex;
            for (let i = min; i <= max; ++i) {
              setNodeState(getVisitedName(level, i), true);
            }
            setPrevCheck(checkName);
            return getSelection();
          }
        }
      }
 
      if (checked) {
        setPrevCheck(checkName);
      } else {
        setPrevCheck(null);
      }
    }
 
    setNodeState(checkName, checked);
 
    return getSelection();
  }
 
  return {
    visit,
    getNodeState,
    setNodeState,
    getSelection,
    handleChange,
  };
}