TreeSelect.tsx 3.63 KB
import { useState } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react';

import styles from './Shared.module.css';
import { Icon } from './Icon';
import { cx, notifyPopupOpen, useExclusivePopup } from './utils';

const selectPopupOpenEvent = 'gl-select-popup-open';

export interface TreeSelectNode {
  label: ReactNode;
  value: string;
  disabled?: boolean;
  children?: TreeSelectNode[];
}

export interface TreeSelectProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> {
  /** 树节点保留 children 结构,供组织、分类、权限范围等层级选择使用。 */
  treeData: TreeSelectNode[];
  value?: string;
  placeholder?: string;
  onChange?: (value: string, node: TreeSelectNode) => void;
}

function findNode(nodes: TreeSelectNode[], value?: string): TreeSelectNode | undefined {
  for (const node of nodes) {
    if (node.value === value) return node;
    const child = findNode(node.children ?? [], value);
    if (child) return child;
  }
  return undefined;
}

export function TreeSelect({ treeData, value, placeholder = '请选择', onChange, ...props }: TreeSelectProps) {
  const [open, setOpen] = useState(false);
  const popupId = useExclusivePopup(selectPopupOpenEvent, setOpen);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [innerValue, setInnerValue] = useState<string | undefined>(value);
  const currentValue = value ?? innerValue;
  const currentNode = findNode(treeData, currentValue);

  const renderNodes = (nodes: TreeSelectNode[], level = 0): ReactNode[] =>
    nodes.flatMap((node) => {
      const hasChildren = Boolean(node.children?.length);
      const isExpanded = expanded.has(node.value);
      const item = (
        <div
          key={node.value}
          className={cx(styles.treeItem, node.value === currentValue && styles.optionSelected, node.disabled && styles.disabled)}
          role="treeitem"
          aria-expanded={hasChildren ? isExpanded : undefined}
          aria-disabled={node.disabled || undefined}
          aria-selected={!hasChildren && node.value === currentValue}
          style={{ paddingLeft: 8 + level * 16 }}
          onClick={() => {
            if (node.disabled) return;
            if (hasChildren) {
              const nextExpanded = new Set(expanded);
              if (isExpanded) {
                nextExpanded.delete(node.value);
              } else {
                nextExpanded.add(node.value);
              }
              setExpanded(nextExpanded);
              return;
            }
            if (value === undefined) setInnerValue(node.value);
            onChange?.(node.value, node);
            setOpen(false);
          }}
        >
          {hasChildren ? <Icon name={isExpanded ? 'chevron-down' : 'chevron-right'} /> : <span className={styles.treeSpacer} />}
          {node.label}
        </div>
      );
      return isExpanded && node.children ? [item, ...renderNodes(node.children, level + 1)] : [item];
    });

  const toggleOpen = () => {
    setOpen((nextOpen) => {
      if (!nextOpen) notifyPopupOpen(selectPopupOpenEvent, popupId);
      return !nextOpen;
    });
  };

  return (
    <span className={styles.selectWrapper}>
      <button {...props} className={cx(styles.control, styles.fieldButton)} role="combobox" aria-expanded={open} type="button" onClick={toggleOpen}>
        <span>{currentNode?.label ?? placeholder}</span>
        <Icon className={styles.fieldIcon} name={open ? 'chevron-down' : 'chevron-right'} />
      </button>
      {open ? (
        <div className={cx(styles.popup, styles.selectPopup)} role="tree">
          {renderNodes(treeData)}
        </div>
      ) : null}
    </span>
  );
}