Ben Lin
2024-10-30 28a53fe81cdb551d2bf2023167487a3060e0f180
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
import type { ComputedRef, Ref } from 'vue';
import { nextTick, unref } from 'vue';
import { warn } from '@/utils/log';
 
export function useTableScrollTo(
  tableElRef: Ref<ComponentRef>,
  getDataSourceRef: ComputedRef<Recordable[]>,
) {
  let bodyEl: HTMLElement | null;
 
  async function findTargetRowToScroll(targetRowData: Recordable) {
    const { id } = targetRowData;
    const targetRowEl: HTMLElement | null | undefined = bodyEl?.querySelector(
      `[data-row-key="${id}"]`,
    );
    //Add a delay to get new dataSource
    await nextTick();
    bodyEl?.scrollTo({
      top: targetRowEl?.offsetTop ?? 0,
      behavior: 'smooth',
    });
  }
 
  function scrollTo(pos: string): void {
    const table = unref(tableElRef);
    if (!table) return;
 
    const tableEl: Element = table.$el;
    if (!tableEl) return;
 
    if (!bodyEl) {
      bodyEl = tableEl.querySelector('.ant-table-body');
      if (!bodyEl) return;
    }
 
    const dataSource = unref(getDataSourceRef);
    if (!dataSource) return;
 
    // judge pos type
    if (pos === 'top') {
      findTargetRowToScroll(dataSource[0]);
    } else if (pos === 'bottom') {
      findTargetRowToScroll(dataSource[dataSource.length - 1]);
    } else {
      const targetRowData = dataSource.find((data) => data.id === pos);
      if (targetRowData) {
        findTargetRowToScroll(targetRowData);
      } else {
        warn(`id: ${pos} doesn't exist`);
      }
    }
  }
 
  return { scrollTo };
}