index.tsx 2.64 KB
import type { ElementRef, ReactNode } from 'react';
import { forwardRef } from 'react';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';

export type UTabsSize = 'md' | 'lg';

// antd Tabs 自带 size(SizeType),语义是控件尺寸,与我们「页面级 / 抽屉放大版」不同,
// 这里剔除后自定义 size,避免两套 size 含义打架。
export interface UTabsProps extends Omit<TabsProps, 'size'> {
  /** 尺寸:md 页面级(默认,14px);lg 抽屉/详情内的放大版(16px)。 */
  size?: UTabsSize;
}

/**
 * 系统级分段导航(Tabs)。在 antd Tabs 之上统一三件事:
 *  1. 自动带 .uj-page__tabs,页面不必再手写 className;
 *  2. 统一的字号、配色、激活态、聚焦环(见 ui.css 的 .uj-page__tabs 规则);
 *  3. size 区分页面级与抽屉内放大版,避免各页面各写一套作用域 CSS。
 *
 * 计角标请用配套 tabLabel(),替代各页面手搓的 uj-num / approval-detail-tab-count。
 */
export const UTabs = forwardRef<ElementRef<typeof Tabs>, UTabsProps>(
  ({ className, size = 'md', ...rest }, ref) => {
    const base = size === 'lg' ? 'uj-page__tabs uj-page__tabs--lg' : 'uj-page__tabs';
    return <Tabs ref={ref} {...rest} className={className ? `${base} ${className}` : base} />;
  },
);

UTabs.displayName = 'UTabs';

export default UTabs;

export interface TabLabelOptions {
  /** 角标数字/文案;传 null / undefined / '' 则不渲染角标。 */
  count?: ReactNode;
  /** 角标色调:neutral 灰底(默认),primary 主色底强调。 */
  tone?: 'neutral' | 'primary';
  /** 角标无障碍标签;不传则隐藏(aria-hidden)。 */
  countLabel?: string;
}

/**
 * 生成带计数角标的 tab 文案,统一替代各页面手搓的 uj-num / approval-detail-tab-count。
 *
 *   label: tabLabel('待我审批', { count: total })                       // 灰底角标
 *   label: tabLabel('待我审批', { count: total, tone: 'primary' })      // 主色强调角标
 *   label: tabLabel('管理层市场费', { count: n, countLabel: `共 ${n} 项` }) // 带朗读
 */
export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode {
  const count = options?.count;
  const visible = count !== null && count !== undefined && count !== '';
  return (
    <span className="uj-tabs__label">
      {text}
      {visible ? (
        <span
          className={'uj-tabs__count' + (options?.tone === 'primary' ? ' uj-tabs__count--primary' : '')}
          aria-hidden={options?.countLabel ? undefined : true}
          aria-label={options?.countLabel}
        >
          {count}
        </span>
      ) : null}
    </span>
  );
}