Navigation.tsx 8.38 KB
import type { ReactNode } from 'react';

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

export interface TabsItem {
  key: string;
  label: ReactNode;
  disabled?: boolean;
  children?: ReactNode;
}

export interface NavigationItem {
  key: string;
  label: ReactNode;
  disabled?: boolean;
  children?: NavigationItem[];
}

export interface NavigationProps {
  /** Navigation 通过受控 activeKey 承载后台层级菜单,业务侧只传配置和路由状态。 */
  activeKey?: string;
  items: NavigationItem[];
  ariaLabel?: string;
  onChange?: (key: string) => void;
}

export function Navigation({ activeKey, ariaLabel = '导航', items, onChange }: NavigationProps) {
  return (
    <nav className={styles.navigation} aria-label={ariaLabel}>
      {items.map((item) => {
        const hasChildren = Boolean(item.children?.length);
        const parentActive = hasChildren && item.children?.some((child) => child.key === activeKey);

        return (
          <div key={item.key} className={styles.navigationGroup}>
            <button
              className={styles.navigationItem}
              data-active-parent={parentActive ? 'true' : undefined}
              disabled={item.disabled}
              type="button"
              onClick={() => {
                if (!item.disabled) onChange?.(item.key);
              }}
            >
              {item.label}
            </button>
            {hasChildren ? (
              <div className={styles.navigationChildren}>
                {item.children?.map((child) => {
                  const selected = child.key === activeKey;
                  return (
                    <button
                      key={child.key}
                      className={cx(styles.navigationItem, styles.navigationChild, selected && styles.navigationItemActive)}
                      aria-current={selected ? 'page' : undefined}
                      disabled={child.disabled}
                      type="button"
                      onClick={() => {
                        if (!child.disabled) onChange?.(child.key);
                      }}
                    >
                      {child.label}
                    </button>
                  );
                })}
              </div>
            ) : null}
          </div>
        );
      })}
    </nav>
  );
}

export interface TabsProps {
  /** Tabs 采用受控 activeKey,切换只通过 onChange 通知业务侧。 */
  activeKey: string;
  items: TabsItem[];
  onChange?: (key: string) => void;
}

export function Tabs({ activeKey, items, onChange }: TabsProps) {
  const active = items.find((item) => item.key === activeKey);
  return (
    <div className={styles.tabs}>
      <div className={styles.tabList} role="tablist">
        {items.map((item) => (
          <button
            key={item.key}
            className={styles.tab}
            disabled={item.disabled}
            role="tab"
            type="button"
            aria-selected={item.key === activeKey}
            onClick={() => {
              if (!item.disabled) onChange?.(item.key);
            }}
          >
            {item.label}
          </button>
        ))}
      </div>
      <div role="tabpanel">{active?.children}</div>
    </div>
  );
}

export interface StepsProps {
  current: number;
  status?: 'process' | 'finish' | 'error';
  items: Array<{ title: ReactNode }>;
}

export function Steps({ current, items, status = 'process' }: StepsProps) {
  return (
    <ol className={styles.row}>
      {items.map((item, index) => {
        const state = index < current ? '完成' : index === current && status === 'error' ? '错误' : index === current ? '进行中' : '等待';
        return <li key={index} className={styles.stack}><strong>{item.title}</strong><span>{state}</span></li>;
      })}
    </ol>
  );
}

export interface CollapseItem {
  key: string;
  title: ReactNode;
  children?: ReactNode;
  disabled?: boolean;
}

export interface CollapseProps {
  /** Collapse 支持多面板展开,activeKeys 由外部控制。 */
  activeKeys: string[];
  items: CollapseItem[];
  onChange?: (keys: string[]) => void;
}

export function Collapse({ activeKeys, items, onChange }: CollapseProps) {
  return (
    <div className={styles.stack}>
      {items.map((item) => {
        const open = activeKeys.includes(item.key);
        return (
          <section key={item.key} className={styles.panel}>
            <button
              className={cx(styles.fieldButton, styles.control)}
              disabled={item.disabled}
              type="button"
              aria-expanded={open}
              onClick={() => onChange?.(open ? activeKeys.filter((key) => key !== item.key) : [...activeKeys, item.key])}
            >
              <span>{item.title}</span>
              <Icon name={open ? 'chevron-down' : 'chevron-right'} />
            </button>
            {open ? <div className={styles.section}>{item.children}</div> : null}
          </section>
        );
      })}
    </div>
  );
}

export interface EmptyProps {
  description?: ReactNode;
  action?: ReactNode;
}

export function Empty({ action, description = '暂无数据' }: EmptyProps) {
  return <div className={styles.stack}><div className={styles.muted}>{description}</div>{action}</div>;
}

export interface StatePlaceholderProps {
  /** StatePlaceholder 表达内容区状态;失败态明确区别于空数据,不使用“暂无数据”兜底。 */
  state: 'empty' | 'filtered-empty' | 'error' | 'forbidden' | 'offline';
  title?: ReactNode;
  description?: ReactNode;
  primaryAction?: ReactNode;
  secondaryAction?: ReactNode;
  icon?: ReactNode;
}

const stateDefaults: Record<StatePlaceholderProps['state'], { title: string; description: string; role: 'status' | 'alert'; icon: ReactNode }> = {
  empty: { title: '暂无数据', description: '当前内容为空', role: 'status', icon: <Icon name="file" /> },
  'filtered-empty': { title: '未找到匹配结果', description: '请调整搜索或筛选条件', role: 'status', icon: <Icon name="search" /> },
  error: { title: '加载失败', description: '数据请求失败,请稍后重试', role: 'alert', icon: <Icon name="warning-circle" /> },
  forbidden: { title: '权限受限', description: '当前账号暂无访问权限', role: 'alert', icon: <Icon name="close-circle" /> },
  offline: { title: '网络不可用', description: '请检查网络连接后重试', role: 'alert', icon: <Icon name="refresh" /> },
};

const stateClassNames: Record<StatePlaceholderProps['state'], string | undefined> = {
  empty: undefined,
  'filtered-empty': styles.statePlaceholderFiltered,
  error: styles.statePlaceholderError,
  forbidden: styles.statePlaceholderForbidden,
  offline: styles.statePlaceholderOffline,
};

export function StatePlaceholder({ description, icon, primaryAction, secondaryAction, state, title }: StatePlaceholderProps) {
  const defaults = stateDefaults[state];
  const resolvedTitle = title ?? defaults.title;

  return (
    <div className={cx(styles.statePlaceholder, stateClassNames[state])} role={defaults.role} aria-label={String(resolvedTitle)}>
      <div className={styles.statePlaceholderIcon} aria-hidden="true">{icon ?? defaults.icon}</div>
      <strong className={styles.statePlaceholderTitle}>{resolvedTitle}</strong>
      <div className={styles.muted}>{description ?? defaults.description}</div>
      {(primaryAction || secondaryAction) ? <div className={styles.statePlaceholderActions}>{primaryAction}{secondaryAction}</div> : null}
    </div>
  );
}

export function Skeleton({ active = false }: { active?: boolean }) {
  return <div aria-label="加载占位" className={cx(styles.skeleton, active && styles.stack)} style={{ width: '100%', height: 16 }} />;
}

export function SkeletonAvatar() {
  return <div aria-label="头像加载占位" className={styles.skeleton} style={{ width: 32, height: 32, borderRadius: 999 }} />;
}

export function SkeletonParagraph({ rows = 3 }: { rows?: number }) {
  return <div aria-label="段落加载占位" className={styles.stack}>{Array.from({ length: rows }, (_, index) => <div key={index} className={styles.skeleton} style={{ width: `${100 - index * 12}%`, height: 14 }} />)}</div>;
}

export function SkeletonButton() {
  return <div aria-label="按钮加载占位" className={styles.skeleton} style={{ width: 72, height: 32 }} />;
}

export function SkeletonInput() {
  return <div aria-label="输入框加载占位" className={styles.skeleton} style={{ width: 180, height: 32 }} />;
}