File size: 2,107 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useMemo } from 'react';

import type { InternalDescriptionsItemType } from '..';
import { devUseWarning } from '../../_util/warning';

// Calculate the sum of span in a row
function getCalcRows(
  rowItems: InternalDescriptionsItemType[],
  mergedColumn: number,
): [rows: InternalDescriptionsItemType[][], exceed: boolean] {
  let rows: InternalDescriptionsItemType[][] = [];
  let tmpRow: InternalDescriptionsItemType[] = [];
  let exceed = false;
  let count = 0;

  rowItems
    .filter((n) => n)
    .forEach((rowItem) => {
      const { filled, ...restItem } = rowItem;

      if (filled) {
        tmpRow.push(restItem);
        rows.push(tmpRow);
        // reset
        tmpRow = [];
        count = 0;
        return;
      }
      const restSpan = mergedColumn - count;
      count += rowItem.span || 1;
      if (count >= mergedColumn) {
        if (count > mergedColumn) {
          exceed = true;
          tmpRow.push({ ...restItem, span: restSpan });
        } else {
          tmpRow.push(restItem);
        }
        rows.push(tmpRow);
        // reset
        tmpRow = [];
        count = 0;
      } else {
        tmpRow.push(restItem);
      }
    });

  if (tmpRow.length > 0) {
    rows.push(tmpRow);
  }

  rows = rows.map((rows) => {
    const count = rows.reduce((acc, item) => acc + (item.span || 1), 0);
    if (count < mergedColumn) {
      // If the span of the last element in the current row is less than the column, then add its span to the remaining columns
      const last = rows[rows.length - 1];
      last.span = mergedColumn - (count - (last.span || 1));
      return rows;
    }
    return rows;
  });
  return [rows, exceed];
}

const useRow = (mergedColumn: number, items: InternalDescriptionsItemType[]) => {
  const [rows, exceed] = useMemo(() => getCalcRows(items, mergedColumn), [items, mergedColumn]);

  if (process.env.NODE_ENV !== 'production') {
    const warning = devUseWarning('Descriptions');

    warning(!exceed, 'usage', 'Sum of column `span` in a line not match `column` of Descriptions.');
  }

  return rows;
};

export default useRow;