useFillHeight.ts 6.69 KB
import { useCallback, useLayoutEffect, useRef, useState } from 'react';

export interface FillHeight {
  /** antd Table 的 scroll.y:表体滚动容器的最大高度。 */
  scrollY: number;
  /** 空态占位单元格的高度:扣掉横向滚动条,正好等于表体的可视高度。 */
  fillHeight: number;
}

/** 表体最小高度:容器再矮也不让表体塌成一条线。 */
const MIN_BODY_H = 60;

/**
 * 测量填充表格可滚动表体的高度(做法对齐 atlas 的 useTableFill)。
 *
 * antd 的 scroll.y 只是 inline max-height —— 只是上限、不会撑高,所以数据少时
 * 表体会塌成内容高度、下方留白。这里把同一个值写到 --uj-table-body-h,
 * CSS 给 .ant-table-body 设了同样的 min-height(见 ui.css),于是
 *   表体实际高 = clamp(min-height, 内容高, max-height) ≡ y
 * 表格总高恒等于容器高度,与行数/滚动条无关。
 *
 * 首帧的「容器 − 表头 − 分页器」只是种子值(表头换行、分页器有无都会让公式偏一点),
 * 第二轮起用表格实际渲染高度自校正:overflow = wrapper.offsetHeight − avail,y -= overflow。
 * 因为表体高恒等于 y,这一步一次收敛,与表头/分页器测得准不准无关。
 *
 * 三个不能改的约束:
 *  1) 自校正必须挂在「新 y 已生效」之后(useLayoutEffect 依赖 size)——在 rAF 里 setState
 *     之后立刻量到的还是旧 DOM,y 会被连续放大,直到分页器被容器裁掉。
 *  2) |overflow| ≤ 1px 时必须直接 return,不回落到公式值——否则 y 会在两个值之间横跳。
 *  3) 只观察外部输入:容器、分页器。绝不观察 .ant-table-wrapper —— 它的高度由 y 决定,
 *     观察它等于接上自捻回路,分页器会肉眼可见地抖。
 */
export function useFillHeight() {
  const wrapRef = useRef<HTMLDivElement>(null);
  const [size, setSize] = useState<FillHeight | undefined>(undefined);
  /** 当前已生效的 y。用 ref 而非 state:measure 要读最新值,且它自身不该触发渲染。 */
  const currentRef = useRef<number | undefined>(undefined);
  /** 自校正安全阀:数学上一次收敛,这里只防异常布局下的死循环。 */
  const roundsRef = useRef(0);

  /** @returns 是否改动了 y(true 表示还要等它生效后复核一轮) */
  const measure = useCallback((): boolean => {
    const wrap = wrapRef.current;
    if (!wrap) return false;
    const host = wrap.clientHeight;
    if (host <= 0) return false; // 还没布局出来

    const cs = getComputedStyle(wrap);
    const padY = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
    const avail = host - padY;

    const wrapper = wrap.querySelector<HTMLElement>('.ant-table-wrapper');
    let next: number;

    // 表体自己也是滚动容器:横向滚动条占掉的可视高度必须从空态占位里扣掉,
    // 否则占位比可视区高,空列表会凭空多出一根竖向滚动条。
    const applyFillHeight = (y: number): number => {
      const body = wrap.querySelector<HTMLElement>('.ant-table-body');
      const hScroll = body ? Math.max(0, body.offsetHeight - body.clientHeight) : 0;
      const fillHeight = Math.max(0, y - hScroll);
      wrap.style.setProperty('--uj-fill-h', `${fillHeight}px`);
      return fillHeight;
    };

    if (wrapper && currentRef.current !== undefined) {
      // ① 自校正:用表格实际渲染高度反推
      const overflow = wrapper.offsetHeight - avail;
      if (Math.abs(overflow) <= 1) {
        // 已贴合,锁死 y。横向滚动条仍可能在数据/列宽变化后出现或消失,单独刷新占位高度。
        applyFillHeight(currentRef.current);
        return false;
      }
      next = Math.max(Math.floor(currentRef.current - overflow), MIN_BODY_H);
    } else {
      // ② 首帧种子:扣除表头与分页器的 margin box(antd 默认 margin: 16px 0)
      const theadH = wrap.querySelector('.ant-table-thead')?.getBoundingClientRect().height ?? 0;
      const pager = wrap.querySelector<HTMLElement>('.ant-pagination');
      let pagerH = 0;
      if (pager) {
        const ps = getComputedStyle(pager);
        pagerH =
          pager.getBoundingClientRect().height +
          (parseFloat(ps.marginTop) || 0) +
          (parseFloat(ps.marginBottom) || 0);
      }
      next = Math.max(Math.floor(avail - theadH - pagerH) - 2, MIN_BODY_H);
    }

    if (currentRef.current !== undefined && Math.abs(next - currentRef.current) <= 1) return false;

    currentRef.current = next;
    const fillHeight = applyFillHeight(next);
    wrap.style.setProperty('--uj-table-body-h', `${next}px`);
    setSize({ scrollY: next, fillHeight });
    return true;
  }, []);

  // ① 收敛主循环:size 变化 → antd 已把新 max-height 写进 DOM → 此刻量到的才是真值。
  useLayoutEffect(() => {
    if (roundsRef.current >= 8) return;
    const changed = measure();
    roundsRef.current = changed ? roundsRef.current + 1 : 0;
  }, [size, measure]);

  // ② 外部输入变化才重测:容器尺寸 / 分页器尺寸 / 表格或分页器从无到有。
  useLayoutEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    const el = wrap;

    const trigger = () => {
      roundsRef.current = 0;
      measure();
    };

    let watchedPager: Element | null = null;
    // 函数声明而非 const:ro 的回调要调用它,它又要往 ro 上挂观察,两者互相引用。
    function watchPager() {
      const pager = el.querySelector('.ant-pagination');
      if (pager && pager !== watchedPager) {
        watchedPager = pager;
        ro.observe(pager);
      }
    }

    const ro = new ResizeObserver(() => {
      trigger();
      // 分页器可能晚于首帧才出现,这里顺带挂上观察
      watchPager();
    });
    ro.observe(el);
    watchPager();

    // 结构变化才重测。签名必须同时含「表格」与「分页器」:
    // 只看表格会漏掉「表格已在、分页器后来出现」——首屏 loading 的真实场景,
    // 漏掉它 y 就停在没扣分页器高度的值上,分页器被容器裁掉。
    // 行数据增删不改变签名,避免无谓重测。
    const signature = () =>
      `${Boolean(el.querySelector('.ant-table-wrapper'))}|${Boolean(
        el.querySelector('.ant-pagination'),
      )}`;
    let lastSig = signature();
    const mo = new MutationObserver(() => {
      watchPager();
      const sig = signature();
      if (sig === lastSig) return;
      lastSig = sig;
      trigger();
    });
    mo.observe(el, { childList: true, subtree: true });

    return () => {
      ro.disconnect();
      mo.disconnect();
    };
  }, [measure]);

  return { wrapRef, size };
}