es-grid-template 1.8.71 → 1.8.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/es/grid-component/TempTable.js +2 -1
  2. package/es/group-component/ColumnsChoose.d.ts +13 -0
  3. package/es/group-component/ColumnsChoose.js +211 -0
  4. package/es/group-component/ColumnsGroup/ColumnsGroup.d.ts +12 -0
  5. package/es/group-component/ColumnsGroup/ColumnsGroup.js +230 -0
  6. package/es/group-component/ColumnsGroup/index.d.ts +1 -0
  7. package/es/group-component/ColumnsGroup/index.js +1 -0
  8. package/es/group-component/ContextMenu.d.ts +19 -0
  9. package/es/group-component/ContextMenu.js +74 -0
  10. package/es/group-component/InternalTable.d.ts +8 -0
  11. package/es/group-component/InternalTable.js +224 -0
  12. package/es/group-component/TableContainer.d.ts +49 -0
  13. package/es/group-component/TableContainer.js +375 -0
  14. package/es/group-component/TableContainerEdit.d.ts +48 -0
  15. package/es/group-component/TableContainerEdit.js +2068 -0
  16. package/es/group-component/body/EditableCell.d.ts +16 -0
  17. package/es/group-component/body/EditableCell.js +1066 -0
  18. package/es/group-component/body/TableBody.d.ts +14 -0
  19. package/es/group-component/body/TableBody.js +82 -0
  20. package/es/group-component/body/TableBodyCell.d.ts +12 -0
  21. package/es/group-component/body/TableBodyCell.js +587 -0
  22. package/es/group-component/body/TableBodyCellEdit.d.ts +17 -0
  23. package/es/group-component/body/TableBodyCellEdit.js +1398 -0
  24. package/es/group-component/body/TableBodyCellEmpty.d.ts +12 -0
  25. package/es/group-component/body/TableBodyCellEmpty.js +149 -0
  26. package/es/group-component/body/TableBodyRow.d.ts +21 -0
  27. package/es/group-component/body/TableBodyRow.js +199 -0
  28. package/es/group-component/body/TableBodyRowGroupCell.d.ts +12 -0
  29. package/es/group-component/body/TableBodyRowGroupCell.js +567 -0
  30. package/es/group-component/components/ControlCheckbox.d.ts +13 -0
  31. package/es/group-component/components/ControlCheckbox.js +84 -0
  32. package/es/group-component/components/EditForm/EditForm.d.ts +27 -0
  33. package/es/group-component/components/EditForm/EditForm.js +394 -0
  34. package/es/group-component/components/EditForm/index.d.ts +1 -0
  35. package/es/group-component/components/EditForm/index.js +1 -0
  36. package/es/group-component/components/InputControl/InputControl.d.ts +27 -0
  37. package/es/group-component/components/InputControl/InputControl.js +118 -0
  38. package/es/group-component/components/InputControl/index.d.ts +1 -0
  39. package/es/group-component/components/InputControl/index.js +1 -0
  40. package/es/group-component/components/async-select/index.d.ts +11 -0
  41. package/es/group-component/components/async-select/index.js +38 -0
  42. package/es/group-component/components/async-table-select/index.d.ts +11 -0
  43. package/es/group-component/components/async-table-select/index.js +40 -0
  44. package/es/group-component/components/checkbox-control/index.d.ts +13 -0
  45. package/es/group-component/components/checkbox-control/index.js +40 -0
  46. package/es/group-component/components/checkbox-filter/CheckboxFilter.d.ts +18 -0
  47. package/es/group-component/components/checkbox-filter/CheckboxFilter.js +258 -0
  48. package/es/group-component/components/checkbox-filter/FilterSearch.d.ts +12 -0
  49. package/es/group-component/components/checkbox-filter/FilterSearch.js +36 -0
  50. package/es/group-component/components/command/Command.d.ts +10 -0
  51. package/es/group-component/components/command/Command.js +35 -0
  52. package/es/group-component/components/number/index.d.ts +12 -0
  53. package/es/group-component/components/number/index.js +42 -0
  54. package/es/group-component/components/number-range/index.d.ts +13 -0
  55. package/es/group-component/components/number-range/index.js +79 -0
  56. package/es/group-component/features/operator.d.ts +24 -0
  57. package/es/group-component/features/operator.js +62 -0
  58. package/es/group-component/footer/TableFooter.d.ts +7 -0
  59. package/es/group-component/footer/TableFooter.js +34 -0
  60. package/es/group-component/footer/TableFooterCell.d.ts +7 -0
  61. package/es/group-component/footer/TableFooterCell.js +66 -0
  62. package/es/group-component/footer/TableFooterRow.d.ts +8 -0
  63. package/es/group-component/footer/TableFooterRow.js +30 -0
  64. package/es/group-component/header/TableHead.d.ts +15 -0
  65. package/es/group-component/header/TableHead.js +98 -0
  66. package/es/group-component/header/TableHeadCell.d.ts +15 -0
  67. package/es/group-component/header/TableHeadCell.js +310 -0
  68. package/es/group-component/header/TableHeadCell2.d.ts +17 -0
  69. package/es/group-component/header/TableHeadCell2.js +321 -0
  70. package/es/group-component/header/TableHeadGroupCell.d.ts +17 -0
  71. package/es/group-component/header/TableHeadGroupCell.js +94 -0
  72. package/es/group-component/header/TableHeadRow.d.ts +15 -0
  73. package/es/group-component/header/TableHeadRow.js +52 -0
  74. package/es/group-component/header/renderFilter.d.ts +20 -0
  75. package/es/group-component/header/renderFilter.js +291 -0
  76. package/es/group-component/hook/convert.d.ts +1 -0
  77. package/es/group-component/hook/convert.js +28 -0
  78. package/es/group-component/hook/useColumns.d.ts +28 -0
  79. package/es/group-component/hook/useColumns.js +306 -0
  80. package/es/group-component/hook/useFilterOperator.d.ts +7 -0
  81. package/es/group-component/hook/useFilterOperator.js +33 -0
  82. package/es/group-component/hook/utils.d.ts +220 -0
  83. package/es/group-component/hook/utils.js +2340 -0
  84. package/es/group-component/index.d.ts +2 -0
  85. package/es/group-component/index.js +2 -0
  86. package/es/group-component/style.d.ts +22 -0
  87. package/es/group-component/style.js +48 -0
  88. package/es/group-component/style.scss +1438 -0
  89. package/es/group-component/table/Grid.d.ts +33 -0
  90. package/es/group-component/table/Grid.js +438 -0
  91. package/es/group-component/table/TableWrapper.d.ts +33 -0
  92. package/es/group-component/table/TableWrapper.js +250 -0
  93. package/es/group-component/useContext.d.ts +100 -0
  94. package/es/group-component/useContext.js +21 -0
  95. package/es/table-component/InternalTable.js +6 -1
  96. package/es/table-component/TableContainer.js +4 -2
  97. package/es/table-component/body/TableBodyCell.js +49 -40
  98. package/es/table-component/body/TableBodyRow.js +4 -1
  99. package/es/table-component/hook/utils.d.ts +1 -0
  100. package/es/table-component/hook/utils.js +15 -7
  101. package/es/table-component/style.js +1 -1
  102. package/es/table-component/table/Grid.js +3 -0
  103. package/es/table-component/useContext.d.ts +5 -0
  104. package/es/table-virtuoso/InternalTable.js +2 -2
  105. package/es/table-virtuoso/body/TableBodyCell.js +2 -7
  106. package/es/table-virtuoso/body/TableBodyCellRowGroup.d.ts +14 -0
  107. package/es/table-virtuoso/body/TableBodyCellRowGroup.js +196 -0
  108. package/es/table-virtuoso/body/TableBodyRow.d.ts +1 -1
  109. package/es/table-virtuoso/body/TableBodyRow.js +43 -1
  110. package/es/table-virtuoso/hook/utils.d.ts +1 -0
  111. package/es/table-virtuoso/hook/utils.js +29 -0
  112. package/es/table-virtuoso/style.js +3 -1
  113. package/es/table-virtuoso/table/Grid.js +2 -2
  114. package/es/table-virtuoso/table/TableWrapper.d.ts +7 -1
  115. package/es/table-virtuoso/table/TableWrapper.js +24 -5
  116. package/es/table-virtuoso/useContext.d.ts +6 -3
  117. package/es/table-virtuoso/useContext.js +18 -0
  118. package/lib/grid-component/TempTable.js +2 -1
  119. package/lib/group-component/ColumnsChoose.d.ts +13 -0
  120. package/lib/group-component/ColumnsChoose.js +221 -0
  121. package/lib/group-component/ColumnsGroup/ColumnsGroup.d.ts +12 -0
  122. package/lib/group-component/ColumnsGroup/ColumnsGroup.js +241 -0
  123. package/lib/group-component/ColumnsGroup/index.d.ts +1 -0
  124. package/lib/group-component/ColumnsGroup/index.js +16 -0
  125. package/lib/group-component/ContextMenu.d.ts +19 -0
  126. package/lib/group-component/ContextMenu.js +83 -0
  127. package/lib/group-component/InternalTable.d.ts +8 -0
  128. package/lib/group-component/InternalTable.js +233 -0
  129. package/lib/group-component/TableContainer.d.ts +49 -0
  130. package/lib/group-component/TableContainer.js +382 -0
  131. package/lib/group-component/TableContainerEdit.d.ts +48 -0
  132. package/lib/group-component/TableContainerEdit.js +2075 -0
  133. package/lib/group-component/body/EditableCell.d.ts +16 -0
  134. package/lib/group-component/body/EditableCell.js +1075 -0
  135. package/lib/group-component/body/TableBody.d.ts +14 -0
  136. package/lib/group-component/body/TableBody.js +91 -0
  137. package/lib/group-component/body/TableBodyCell.d.ts +12 -0
  138. package/lib/group-component/body/TableBodyCell.js +595 -0
  139. package/lib/group-component/body/TableBodyCellEdit.d.ts +17 -0
  140. package/lib/group-component/body/TableBodyCellEdit.js +1405 -0
  141. package/lib/group-component/body/TableBodyCellEmpty.d.ts +12 -0
  142. package/lib/group-component/body/TableBodyCellEmpty.js +156 -0
  143. package/lib/group-component/body/TableBodyRow.d.ts +21 -0
  144. package/lib/group-component/body/TableBodyRow.js +206 -0
  145. package/lib/group-component/body/TableBodyRowGroupCell.d.ts +12 -0
  146. package/lib/group-component/body/TableBodyRowGroupCell.js +575 -0
  147. package/lib/group-component/components/ControlCheckbox.d.ts +13 -0
  148. package/lib/group-component/components/ControlCheckbox.js +92 -0
  149. package/lib/group-component/components/EditForm/EditForm.d.ts +27 -0
  150. package/lib/group-component/components/EditForm/EditForm.js +404 -0
  151. package/lib/group-component/components/EditForm/index.d.ts +1 -0
  152. package/lib/group-component/components/EditForm/index.js +16 -0
  153. package/lib/group-component/components/InputControl/InputControl.d.ts +27 -0
  154. package/lib/group-component/components/InputControl/InputControl.js +127 -0
  155. package/lib/group-component/components/InputControl/index.d.ts +1 -0
  156. package/lib/group-component/components/InputControl/index.js +16 -0
  157. package/lib/group-component/components/async-select/index.d.ts +11 -0
  158. package/lib/group-component/components/async-select/index.js +47 -0
  159. package/lib/group-component/components/async-table-select/index.d.ts +11 -0
  160. package/lib/group-component/components/async-table-select/index.js +49 -0
  161. package/lib/group-component/components/checkbox-control/index.d.ts +13 -0
  162. package/lib/group-component/components/checkbox-control/index.js +48 -0
  163. package/lib/group-component/components/checkbox-filter/CheckboxFilter.d.ts +18 -0
  164. package/lib/group-component/components/checkbox-filter/CheckboxFilter.js +267 -0
  165. package/lib/group-component/components/checkbox-filter/FilterSearch.d.ts +12 -0
  166. package/lib/group-component/components/checkbox-filter/FilterSearch.js +44 -0
  167. package/lib/group-component/components/command/Command.d.ts +10 -0
  168. package/lib/group-component/components/command/Command.js +44 -0
  169. package/lib/group-component/components/number/index.d.ts +12 -0
  170. package/lib/group-component/components/number/index.js +50 -0
  171. package/lib/group-component/components/number-range/index.d.ts +13 -0
  172. package/lib/group-component/components/number-range/index.js +87 -0
  173. package/lib/group-component/features/operator.d.ts +24 -0
  174. package/lib/group-component/features/operator.js +67 -0
  175. package/lib/group-component/footer/TableFooter.d.ts +7 -0
  176. package/lib/group-component/footer/TableFooter.js +44 -0
  177. package/lib/group-component/footer/TableFooterCell.d.ts +7 -0
  178. package/lib/group-component/footer/TableFooterCell.js +75 -0
  179. package/lib/group-component/footer/TableFooterRow.d.ts +8 -0
  180. package/lib/group-component/footer/TableFooterRow.js +37 -0
  181. package/lib/group-component/header/TableHead.d.ts +15 -0
  182. package/lib/group-component/header/TableHead.js +107 -0
  183. package/lib/group-component/header/TableHeadCell.d.ts +15 -0
  184. package/lib/group-component/header/TableHeadCell.js +319 -0
  185. package/lib/group-component/header/TableHeadCell2.d.ts +17 -0
  186. package/lib/group-component/header/TableHeadCell2.js +330 -0
  187. package/lib/group-component/header/TableHeadGroupCell.d.ts +17 -0
  188. package/lib/group-component/header/TableHeadGroupCell.js +103 -0
  189. package/lib/group-component/header/TableHeadRow.d.ts +15 -0
  190. package/lib/group-component/header/TableHeadRow.js +59 -0
  191. package/lib/group-component/header/renderFilter.d.ts +20 -0
  192. package/lib/group-component/header/renderFilter.js +301 -0
  193. package/lib/group-component/hook/convert.d.ts +1 -0
  194. package/lib/group-component/hook/convert.js +34 -0
  195. package/lib/group-component/hook/useColumns.d.ts +28 -0
  196. package/lib/group-component/hook/useColumns.js +318 -0
  197. package/lib/group-component/hook/useFilterOperator.d.ts +7 -0
  198. package/lib/group-component/hook/useFilterOperator.js +40 -0
  199. package/lib/group-component/hook/utils.d.ts +220 -0
  200. package/lib/group-component/hook/utils.js +2468 -0
  201. package/lib/group-component/index.d.ts +2 -0
  202. package/lib/group-component/index.js +9 -0
  203. package/lib/group-component/style.d.ts +22 -0
  204. package/lib/group-component/style.js +55 -0
  205. package/lib/group-component/style.scss +1438 -0
  206. package/lib/group-component/table/Grid.d.ts +33 -0
  207. package/lib/group-component/table/Grid.js +443 -0
  208. package/lib/group-component/table/TableWrapper.d.ts +33 -0
  209. package/lib/group-component/table/TableWrapper.js +259 -0
  210. package/lib/group-component/useContext.d.ts +100 -0
  211. package/lib/group-component/useContext.js +27 -0
  212. package/lib/table-component/InternalTable.js +6 -1
  213. package/lib/table-component/TableContainer.js +4 -2
  214. package/lib/table-component/body/TableBodyCell.js +49 -40
  215. package/lib/table-component/body/TableBodyRow.js +4 -1
  216. package/lib/table-component/hook/utils.d.ts +1 -0
  217. package/lib/table-component/hook/utils.js +16 -7
  218. package/lib/table-component/style.js +1 -1
  219. package/lib/table-component/table/Grid.js +3 -0
  220. package/lib/table-component/useContext.d.ts +5 -0
  221. package/lib/table-virtuoso/InternalTable.js +2 -2
  222. package/lib/table-virtuoso/body/TableBodyCell.js +2 -7
  223. package/lib/table-virtuoso/body/TableBodyCellRowGroup.d.ts +14 -0
  224. package/lib/table-virtuoso/body/TableBodyCellRowGroup.js +203 -0
  225. package/lib/table-virtuoso/body/TableBodyRow.d.ts +1 -1
  226. package/lib/table-virtuoso/body/TableBodyRow.js +43 -1
  227. package/lib/table-virtuoso/hook/utils.d.ts +1 -0
  228. package/lib/table-virtuoso/hook/utils.js +32 -1
  229. package/lib/table-virtuoso/style.js +3 -1
  230. package/lib/table-virtuoso/table/Grid.js +2 -2
  231. package/lib/table-virtuoso/table/TableWrapper.d.ts +7 -1
  232. package/lib/table-virtuoso/table/TableWrapper.js +24 -5
  233. package/lib/table-virtuoso/useContext.d.ts +6 -3
  234. package/lib/table-virtuoso/useContext.js +18 -0
  235. package/package.json +1 -1
@@ -0,0 +1,2340 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { presetPalettes } from "@ant-design/colors";
3
+ import dayjs from "dayjs";
4
+ import moment from "moment";
5
+ export const newGuid = () => {
6
+ for (let i = 0; i < 20; i++) {
7
+ // @ts-ignore
8
+ // const id = crypto.randomUUID()
9
+ return uuidv4();
10
+ }
11
+ };
12
+ export const convertDayjsToDate = (dateString, format) => {
13
+ const dayjsDate = dayjs(dateString, format); // Parse using the provided format
14
+ if (!dayjsDate.isValid()) {
15
+ throw new Error('Invalid date or format');
16
+ }
17
+ // return moment(dayjsDate.toDate()).format() // Convert to JavaScript Date
18
+ return dayjsDate.toDate(); // Convert to JavaScript Date
19
+ };
20
+ export const convertDateToDayjs = (date, format) => {
21
+ const dateValue = date ? dayjs(date).format(format) : null;
22
+ return dateValue ? dayjs(dateValue, format) : null;
23
+ };
24
+ export const getCommonPinningStyles = column => {
25
+ const isPinned = column.getIsPinned();
26
+ return {
27
+ left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
28
+ right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
29
+ opacity: 1,
30
+ position: isPinned ? "sticky" : "relative",
31
+ width: 'auto',
32
+ zIndex: isPinned ? 2 : 0
33
+ };
34
+ };
35
+ export const getCommonPinningStyles2 = header => {
36
+ const isPinned = header.column.getIsPinned();
37
+ // const isLastLeftPinnedColumn = isPinned === "left" && column.getIsLastColumn("left");
38
+ // const isFirstRightPinnedColumn =isPinned === "right" && column.getIsFirstColumn("right");
39
+
40
+ return {
41
+ // boxShadow: isFirstRightPinnedColumn
42
+ // ? "#e0e0e0 2px 0px 1px -1px inset"
43
+ // : undefined,
44
+
45
+ left: isPinned === "left" ? `${header.getStart("left")}px` : undefined,
46
+ right: isPinned === "right" ? `${header.getAfter("right")}px` : undefined,
47
+ opacity: 1,
48
+ position: isPinned ? "sticky" : "relative",
49
+ width: 'auto',
50
+ zIndex: isPinned ? 2 : 0
51
+ };
52
+ };
53
+ export const sumSize = items => {
54
+ return items.reduce((total, item) => total + item.size, 0);
55
+ };
56
+ export const appendIfNotExists = (a, b) => {
57
+ const existingKeys = new Set(a.map(item => item.index));
58
+ b.forEach(item => {
59
+ if (!existingKeys.has(item.index)) {
60
+ a.push(item);
61
+ }
62
+ });
63
+ return a;
64
+ };
65
+ export const getNewItemsOnly = (a, b) => {
66
+ const existingKeys = new Set(a.map(item => item.key));
67
+ return b.filter(item => !existingKeys.has(item.key));
68
+ };
69
+ export const extendsObject = (...list) => {
70
+ const result = {
71
+ ...list[0]
72
+ };
73
+ for (let i = 1; i < list.length; i++) {
74
+ const obj = list[i];
75
+ if (obj) {
76
+ Object.keys(obj).forEach(key => {
77
+ const val = obj[key];
78
+ if (val !== undefined) {
79
+ result[key] = val;
80
+ }
81
+ });
82
+ }
83
+ }
84
+ return result;
85
+ };
86
+ export const isEmpty = d => {
87
+ return d === null || d === undefined || d === '';
88
+ };
89
+ export const getFormat = (colFormat, format) => {
90
+ return {
91
+ thousandSeparator: colFormat?.thousandSeparator ?? format?.thousandSeparator,
92
+ decimalSeparator: colFormat?.decimalSeparator ?? format?.decimalSeparator,
93
+ decimalScale: colFormat?.decimalScale ?? format?.decimalScale ? Number(colFormat?.decimalScale ?? format?.decimalScale) : colFormat?.decimalScale ?? format?.decimalScale,
94
+ allowNegative: colFormat?.allowNegative ?? format?.allowNegative,
95
+ // check nhập số âm
96
+ prefix: colFormat?.prefix ?? format?.prefix,
97
+ suffix: colFormat?.suffix ?? format?.suffix,
98
+ fixedDecimalScale: colFormat?.fixedDecimalScale ?? format?.fixedDecimalScale,
99
+ // mặc định thêm số 0 sau số thập phân
100
+ dateFormat: colFormat?.dateFormat ?? format?.dateFormat,
101
+ datetimeFormat: colFormat?.datetimeFormat ?? format?.datetimeFormat,
102
+ timeFormat: colFormat?.timeFormat ?? format?.timeFormat,
103
+ weekFormat: colFormat?.weekFormat ?? format?.weekFormat,
104
+ monthFormat: colFormat?.monthFormat ?? format?.monthFormat,
105
+ yearFormat: colFormat?.yearFormat ?? format?.yearFormat
106
+ };
107
+ };
108
+ export function convertFormat(formatStr) {
109
+ // return formatStr.split('').map((char, i) => {
110
+ // if (char === 'D' || char === 'd') {
111
+ // return 'd'; // ngày: lowercase
112
+ // }
113
+ // if (char === 'Y' || char === 'y') {
114
+ // return 'y'; // năm: lowercase
115
+ // }
116
+ // if (char === 'M' || char === 'm') {
117
+ // return char; // tháng: giữ nguyên
118
+ // }
119
+ // return char; // separator
120
+ // }).join('');
121
+
122
+ return formatStr.split('').map(char => {
123
+ if (char === 'D' || char === 'd') return 'd';
124
+ if (char === 'Y' || char === 'y') return 'y';
125
+ if ('Hhmsa'.includes(char)) return char; // giờ, phút, giây, am/pm
126
+ if (char === 'M' || char === 'm') return char; // tháng: giữ nguyên
127
+ return char; // dấu phân cách
128
+ }).join('');
129
+ }
130
+ export const getDatepickerFormat = (type, format) => {
131
+ const typeFormat = type ? type.toLowerCase() : '';
132
+ switch (typeFormat) {
133
+ case "date":
134
+ case "daterange":
135
+ return format?.dateFormat ?? 'DD/MM/YYYY';
136
+ case "datetime":
137
+ return format?.datetimeFormat ?? 'DD/MM/YYYY HH:mm';
138
+ case "week":
139
+ return format?.weekFormat ?? 'DD/MM';
140
+ case "month":
141
+ return format?.monthFormat ?? 'MM/YYYY';
142
+ case "quarter":
143
+ return format?.dateFormat ?? 'DD/MM/YYYY';
144
+ case "year":
145
+ return format?.yearFormat ?? 'YYYY';
146
+ case "time":
147
+ return format?.timeFormat ?? 'HH:mm';
148
+ default:
149
+ return 'DD/MM/YYYY';
150
+ }
151
+ };
152
+ export const getDateRangeFormat = (type, format) => {
153
+ const typeFormat = type ? type.toLowerCase() : '';
154
+ switch (typeFormat) {
155
+ case "date":
156
+ case "daterange":
157
+ return convertFormat(format?.dateFormat ?? 'dd/MM/yyyy');
158
+ case "datetime":
159
+ return format?.datetimeFormat ?? 'dd/MM/yyyy HH:mm';
160
+ case "week":
161
+ return format?.weekFormat ?? 'dd/MM';
162
+ case "month":
163
+ return format?.monthFormat ?? 'MM/yyyy';
164
+ case "quarter":
165
+ return format?.dateFormat ?? 'dd/MM/yyyy';
166
+ case "year":
167
+ return format?.yearFormat ?? 'yyyy';
168
+ case "time":
169
+ return format?.timeFormat ?? 'HH:mm';
170
+ default:
171
+ return 'dd/MM/yyyy';
172
+ }
173
+ };
174
+ export const getTypeFilter = col => {
175
+ if (col?.typeFilter) {
176
+ return col.typeFilter;
177
+ }
178
+ const type = col?.type ?? 'Text';
179
+ switch (type) {
180
+ case "number":
181
+ return 'Number';
182
+ case "date":
183
+ return 'Date';
184
+ case "datetime":
185
+ return 'Datetime';
186
+ case "boolean":
187
+ return 'Checkbox';
188
+ case "checkbox":
189
+ return 'Checkbox';
190
+
191
+ // case "week": return ''
192
+ // case "month": return 'Month'
193
+ // case "quarter": return col.format?.dateFormat ? col.format?.dateFormat : 'DD/MM/YYYY'
194
+ // case "year": return col.format?.yearFormat ? col.format?.yearFormat : 'YYYY'
195
+ // case "time": return col.format?.timeFormat ? col.format?.timeFormat : 'HH:mm'
196
+ case "string":
197
+ default:
198
+ return 'Text';
199
+ }
200
+ };
201
+ export const addRowIdArray = inputArray => {
202
+ if (inputArray) {
203
+ return inputArray.map(item => {
204
+ if (typeof item.children !== "string" && item.children && item.children.length > 0) {
205
+ item.children = addRowIdArray(item.children);
206
+ }
207
+
208
+ // return { ...item, rowId: item.rowId ?? item.id ?? newGuid() }
209
+ return {
210
+ ...item,
211
+ rowId: item.id ?? item.rowId ?? newGuid()
212
+ };
213
+ });
214
+ } else {
215
+ return [];
216
+ }
217
+ };
218
+ export function groupArrayByColumns(arr, columns) {
219
+ const result = [];
220
+ const checkEmpty = d => {
221
+ return d === null || d === undefined || d === '';
222
+ };
223
+ if (columns) {
224
+ arr.forEach(item => {
225
+ let currentLevel = result;
226
+ columns.forEach((column, index) => {
227
+ const value = item[column];
228
+ const existingItem = currentLevel.find(i => i[column] === value);
229
+ if (existingItem) {
230
+ currentLevel = existingItem.children;
231
+ } else {
232
+ // const newItem = {[column]: value, field: column, rowId: !isEmpty(value) ? (value) : newGuid(), parentId: !isEmpty(item[columns[index - 1]]) ? (item[columns[index - 1]]) : null, indent: index, children: [] }
233
+ const newItem = {
234
+ [column]: value,
235
+ field: column,
236
+ rowId: newGuid(),
237
+ // rowId: item[column],
238
+ parentId: !isEmpty(item[columns[index - 1]]) ? item[columns[index - 1]] : null,
239
+ // parentId: item.rowId[index - 1],
240
+ // indent: index,
241
+ children: []
242
+ };
243
+ currentLevel.push(newItem);
244
+ currentLevel = newItem.children;
245
+ }
246
+ });
247
+ currentLevel.push({
248
+ ...item,
249
+ rowId: item.id ?? item.rowId,
250
+ parentId: !checkEmpty(columns[columns.length - 1]) ? item[columns[columns.length - 1]] : null
251
+ // parentId: item.rowId[columns.length - 1],
252
+ // indent: columns.length
253
+ });
254
+ });
255
+ return result;
256
+ } else {
257
+ return arr;
258
+ }
259
+ }
260
+ export const flatColumns2 = columns => {
261
+ return columns.reduce((list, column) => {
262
+ const subColumns = column.children;
263
+ if (column.field === 'selection_column') {
264
+ return [...list, {
265
+ ...column
266
+ }];
267
+ }
268
+ if (subColumns && subColumns.length > 0) {
269
+ return [...list, ...flatColumns2(subColumns).map(subColum => ({
270
+ ...subColum
271
+ }))];
272
+ }
273
+ return [...list, {
274
+ ...column
275
+ }];
276
+ }, []);
277
+ };
278
+ export const checkThousandSeparator = (thousandSeparator, decimalSeparator) => {
279
+ if (thousandSeparator) {
280
+ if (decimalSeparator) {
281
+ if (thousandSeparator === decimalSeparator) {
282
+ return ',';
283
+ } else {
284
+ return thousandSeparator;
285
+ }
286
+ } else {
287
+ return thousandSeparator;
288
+ }
289
+ } else {
290
+ return undefined;
291
+ }
292
+ };
293
+ export const checkDecimalSeparator = (thousandSeparator, decimalSeparator) => {
294
+ if (decimalSeparator) {
295
+ if (thousandSeparator) {
296
+ if (thousandSeparator === decimalSeparator) {
297
+ return '.';
298
+ } else {
299
+ return decimalSeparator;
300
+ }
301
+ } else {
302
+ return decimalSeparator;
303
+ }
304
+ } else {
305
+ if (thousandSeparator && thousandSeparator === '.') {
306
+ return ',';
307
+ }
308
+ return '.';
309
+ }
310
+ };
311
+ export const getFixedFields = (columns, type) => {
312
+ const result = [];
313
+ function traverse(cols) {
314
+ for (const col of cols) {
315
+ if ((col.fixed ?? col.fixedType) === type && col.field && (col.visible !== false || col.hidden)) {
316
+ result.push(col.field);
317
+ }
318
+ if (col.children && col.children.length > 0) {
319
+ traverse(col.children);
320
+ }
321
+ }
322
+ }
323
+ traverse(columns);
324
+ return result;
325
+ };
326
+ export function areStringArraysEqual(a, b) {
327
+ if (a.length !== b.length) return false;
328
+ const sortedA = [...a].sort();
329
+ const sortedB = [...b].sort();
330
+ return sortedA.every((val, index) => val === sortedB[index]);
331
+ }
332
+ export const getDefaultOperator = col => {
333
+ if (col.operator) {
334
+ return col.operator;
335
+ }
336
+ if (col.typeFilter) {
337
+ switch (col.typeFilter) {
338
+ case 'Number':
339
+ case 'Date':
340
+ case 'Datetime':
341
+ case 'Time':
342
+ case 'Month':
343
+ case 'Quarter':
344
+ case 'Year':
345
+ case 'Week':
346
+ case 'Dropdown':
347
+ case 'Checkbox':
348
+ case 'CheckboxDropdown':
349
+ case 'CheckboxTree':
350
+ case 'DropTree':
351
+ return 'equal';
352
+ case 'Text':
353
+ default:
354
+ return 'contains';
355
+ }
356
+ }
357
+ switch (col.type) {
358
+ case 'number':
359
+ case 'date':
360
+ case 'datetime':
361
+ case 'week':
362
+ case 'year':
363
+ case 'quarter':
364
+ return 'equal';
365
+ case 'string':
366
+ default:
367
+ return 'contains';
368
+ }
369
+ };
370
+ export function isEqualSet(setA, setB) {
371
+ if (setA.size !== setB.size) {
372
+ return false;
373
+ }
374
+ for (const item of setA) {
375
+ if (!setB.has(item)) {
376
+ return false;
377
+ }
378
+ }
379
+ return true;
380
+ }
381
+ export const getLastSelectCell = selectCells => {
382
+ if (selectCells.size === 0) {
383
+ return {
384
+ row: 0,
385
+ col: 0
386
+ };
387
+ }
388
+ const lastValue = [...selectCells].at(-1);
389
+ const [row, col] = lastValue.split("-").map(Number);
390
+ return {
391
+ row,
392
+ col
393
+ };
394
+ };
395
+ export function getCellsByPosition(cellSet, position = "bottom") {
396
+ const cells = Array.from(cellSet).map(key => {
397
+ const [row, col] = key.split("-").map(Number);
398
+ return {
399
+ row,
400
+ col,
401
+ key
402
+ };
403
+ });
404
+ switch (position) {
405
+ case "top":
406
+ {
407
+ // const minRow = Math.min(...cells.map(c => c.row));
408
+ // return cells.filter(c => c.row === minRow).map(c => c.key);
409
+
410
+ // const rows = cells.map(c => c.row).filter(r => r > 0);
411
+ // if (rows.length === 0) return [];
412
+ // const minRow = Math.min(...rows);
413
+ // return cells.filter(c => c.row === minRow).map(c => c.key);
414
+
415
+ const minRow = Math.min(...cells.map(c => c.row));
416
+ if (minRow === 0) {
417
+ return [];
418
+ } // Bỏ qua nếu rowIndex = 0
419
+
420
+ return cells.filter(c => c.row === minRow).map(c => `${c.row}-${c.col}`);
421
+ }
422
+ case "bottom":
423
+ {
424
+ const maxRow = Math.max(...cells.map(c => c.row));
425
+ return cells.filter(c => c.row === maxRow).map(c => c.key);
426
+ }
427
+ case "left":
428
+ {
429
+ // const minCol = Math.min(...cells.map(c => c.col));
430
+ // return cells.filter(c => c.col === minCol).map(c => c.key);
431
+
432
+ // const cols = cells.map(c => c.col).filter(c => c > 0);
433
+ // if (cols.length === 0) return [];
434
+ // const minCol = Math.min(...cols);
435
+ // return cells.filter(c => c.col === minCol).map(c => c.key);
436
+
437
+ const minCol = Math.min(...cells.map(c => c.col));
438
+ if (minCol === 0) {
439
+ return [];
440
+ } // Bỏ qua nếu colIndex = 0
441
+
442
+ // Trả về các ô cùng row, nhưng ở cột bên trái
443
+ return cells.filter(c => c.col === minCol).map(c => `${c.row}-${c.col}`);
444
+ }
445
+ case "right":
446
+ {
447
+ const maxCol = Math.max(...cells.map(c => c.col));
448
+ return cells.filter(c => c.col === maxCol).map(c => c.key);
449
+ }
450
+ default:
451
+ return [];
452
+ }
453
+ }
454
+ export const onAddBgSelectedCell = (selectedCells, id, isFocusCellIndex) => {
455
+ const selectors = Array.from(selectedCells).map(pos => {
456
+ const [row1, col1] = pos.split('-');
457
+ return `[data-row-index="${row1}"][data-col-index="${col1}"]`;
458
+ });
459
+ const table = document.querySelector(`#${id}`);
460
+
461
+ //// xóa class các ô đã chọn trước đó
462
+ const cellsSelected = table ? table?.querySelectorAll('.ui-rc-table-cell.selected-bg') : null;
463
+ if (cellsSelected) {
464
+ cellsSelected.forEach(cell => {
465
+ cell.classList.remove('selected-bg');
466
+ });
467
+ }
468
+
469
+ /// thêm class
470
+ const cells = table && selectors.length > 0 ? table?.querySelectorAll(selectors.join(',')) : null;
471
+ if (cells) {
472
+ cells.forEach(cell => {
473
+ cell.classList.add('selected-bg');
474
+ });
475
+ }
476
+ const rowsArray = [...new Set([...selectedCells].map(item => item.split("-")[0]))];
477
+ const rowsSelectors = rowsArray.map(r => `.rc-ui-cell-index[data-row-index="${r}"]`).join(", ");
478
+ const cellsIndex = table && rowsSelectors.length > 0 ? table?.querySelectorAll(rowsSelectors) : null;
479
+ if (cellsIndex && isFocusCellIndex !== false) {
480
+ cellsIndex.forEach(cell => {
481
+ cell.classList.add('focus');
482
+ });
483
+ }
484
+
485
+ // // tăng z-index để hiển thị round point paste
486
+ // const row = getLastSelectCell(selectedCells).row
487
+ // const col = getLastSelectCell(selectedCells).col
488
+ // const cell: any = table?.querySelector(`.ui-rc-table-cell[data-row-index="${row}"][data-col-index="${col}"]`)
489
+ //
490
+ // if (cell) {
491
+ // cell.style.zIndex = 1
492
+ // }
493
+ //
494
+ // if (cell && cell.classList.contains('ui-rc-table-cell-fix-left')) {
495
+ // cell.style.zIndex = 3;
496
+ // }
497
+
498
+ // thêm class border selected
499
+
500
+ // addBorderClass(selectedCells, 'bottom', 'cell-border-bottom', id)
501
+ // addBorderClass(selectedCells, 'right', 'cell-border-right', id)
502
+ // addBorderClass(selectedCells, 'top', 'cell-border-top', id)
503
+ // addBorderClass(selectedCells, 'left', 'cell-border-left', id)
504
+ };
505
+ export const onRemoveBgSelectedCell = (selectedCells, id, rowsSelected) => {
506
+ const table = document.querySelector(`#${id}`);
507
+ const cells = table ? table?.querySelectorAll('.ui-rc-table-cell.selected-bg') : null;
508
+ if (cells) {
509
+ cells.forEach(cell => {
510
+ cell.classList.remove('selected-bg');
511
+ });
512
+ }
513
+ const cellsIndex = table ? table?.querySelectorAll('.ui-rc-table-cell.focus') : null;
514
+ if (cellsIndex) {
515
+ cellsIndex.forEach(cell => {
516
+ cell.classList.remove('focus');
517
+ });
518
+ }
519
+
520
+ // xóa class selected ô STT
521
+
522
+ if (rowsSelected && rowsSelected.size > 0) {
523
+ const rowsSelectedArray = [...new Set([...rowsSelected].map(item => item.split("-")[0]))];
524
+ const rowsSelectedSelectors = rowsSelectedArray.map(r => `.rc-ui-cell-index[data-row-index="${r}"]`).join(", ");
525
+ const cellsSelectedIndex = table && rowsSelectedSelectors.length > 0 ? table?.querySelectorAll(rowsSelectedSelectors) : null;
526
+ if (cellsSelectedIndex) {
527
+ cellsSelectedIndex.forEach(cell => {
528
+ cell.classList.remove('selected');
529
+ });
530
+ }
531
+ }
532
+ };
533
+ export function getColIdsBetween(table, a, b) {
534
+ const ids = table.getVisibleLeafColumns().map(c => c.id);
535
+ const [start, end] = [ids.indexOf(a), ids.indexOf(b)].sort((x, y) => x - y);
536
+ return ids.slice(start, end + 1);
537
+ }
538
+ export function getRowIdsBetween(table, a, b) {
539
+ // const ids = table.getRowModel().rows.map(r => r.id);
540
+ const ids = table.getRowModel().flatRows.map(r => r.id);
541
+ const [start, end] = [ids.indexOf(a), ids.indexOf(b)].sort((x, y) => x - y);
542
+ return ids.slice(start, end + 1);
543
+ }
544
+ export const updateArrayByKey = (arr, element, key) => {
545
+ if (arr) {
546
+ return arr.map(it => {
547
+ const item = {
548
+ ...it
549
+ };
550
+ if (item[key] === element[key]) {
551
+ return {
552
+ ...item,
553
+ ...element
554
+ };
555
+ } else if (item.children && item.children.length > 0) {
556
+ item.children = updateArrayByKey(item.children, element, key);
557
+ }
558
+ return item;
559
+ });
560
+ } else {
561
+ return [];
562
+ }
563
+ };
564
+ export const unFlattenData = data => {
565
+ const idToNodeMap = {};
566
+ const tree = [];
567
+
568
+ // Bước 1: Tạo map id -> node
569
+ data.forEach(item => {
570
+ // idToNodeMap[item.rowId] = { ...item, children: [] }
571
+ idToNodeMap[item.rowId] = {
572
+ ...item
573
+ };
574
+ });
575
+
576
+ // Bước 2: Gắn vào parent hoặc đẩy lên root nếu không có parent
577
+ data.forEach(item => {
578
+ const currentNode = idToNodeMap[item.rowId];
579
+ if (!item.parentId) {
580
+ tree.push(currentNode);
581
+ } else {
582
+ const parentNode = idToNodeMap[item.parentId];
583
+ if (parentNode) {
584
+ parentNode.children = parentNode.children ?? [];
585
+ parentNode.children.push(currentNode);
586
+ } else {
587
+ // Nếu parentId không tồn tại thì xem như root
588
+ tree.push(currentNode);
589
+ }
590
+ }
591
+ });
592
+ return tree;
593
+ };
594
+ export const flattenArray = arr => {
595
+ if (!arr) {
596
+ return [];
597
+ }
598
+ return arr.reduce((r, {
599
+ children,
600
+ ...rest
601
+ }) => {
602
+ r.push(rest);
603
+ if (children) {
604
+ r.push(...flattenArray(children));
605
+ }
606
+ return r;
607
+ }, []);
608
+ };
609
+ export function updateOrInsert(dataArray, dataFilter) {
610
+ const updatedArray = [...dataArray];
611
+ dataFilter.forEach(filterItem => {
612
+ const existingIndex = updatedArray.findIndex(item => item.rowId === filterItem.rowId);
613
+ if (existingIndex !== -1) {
614
+ // Cập nhật item đã tồn tại
615
+ updatedArray[existingIndex] = {
616
+ ...updatedArray[existingIndex],
617
+ ...filterItem
618
+ };
619
+ } else {
620
+ // Tìm vị trí cuối cùng của item trước đó trong dataFilter
621
+ const prevIndexInFilter = dataFilter.findIndex(f => f.rowId === filterItem.rowId) - 1;
622
+ if (prevIndexInFilter >= 0) {
623
+ const prevId = dataFilter[prevIndexInFilter].rowId;
624
+ const prevIndexInArray = updatedArray.findIndex(item => item.rowId === prevId);
625
+ if (prevIndexInArray !== -1) {
626
+ // Thêm ngay sau phần tử trước đó
627
+ updatedArray.splice(prevIndexInArray + 1, 0, filterItem);
628
+ return;
629
+ }
630
+ }
631
+
632
+ // Nếu không tìm thấy phần tử trước đó, hoặc là phần đầu tiên, thì push vào cuối
633
+ updatedArray.push(filterItem);
634
+ }
635
+ });
636
+ return updatedArray;
637
+ }
638
+ export const findItemByKey = (array, key, value) => {
639
+ for (let i = 0; i < array.length; i++) {
640
+ const item = array[i];
641
+ if (item[key] === value) {
642
+ return item;
643
+ }
644
+ if (item.children && item.children.length > 0) {
645
+ const foundInChildren = findItemByKey(item.children, key, value);
646
+ if (foundInChildren) {
647
+ return foundInChildren;
648
+ }
649
+ }
650
+ }
651
+ return null;
652
+ };
653
+ export const isFormattedNumber = str => {
654
+ if (!str) return false;
655
+ if (typeof str !== 'string') return false;
656
+ const regexUS = /^\d{1,3}(,\d{3})*(\.\d+)?$/; // 100,000.111
657
+ const regexEU = /^\d{1,3}(\.\d{3})*(,\d+)?$/; // 100.000,111
658
+
659
+ // Không có dấu hàng nghìn, chỉ dấu thập phân: 100000.1 hoặc 100000,01
660
+ const regexDecimalOnly = /^-?\d+([.,]\d{1,})$/;
661
+ return regexUS.test(str) || regexEU.test(str) || regexDecimalOnly.test(str);
662
+ };
663
+ export const detectSeparators = str => {
664
+ if (typeof str !== 'string') return null;
665
+ const hasComma = str.includes(',');
666
+ const hasDot = str.includes('.');
667
+
668
+ // Trường hợp có cả dấu , và .
669
+ if (hasComma && hasDot) {
670
+ const lastComma = str.lastIndexOf(',');
671
+ const lastDot = str.lastIndexOf('.');
672
+ return lastComma > lastDot ? {
673
+ thousandSeparator: '.',
674
+ decimalSeparator: ','
675
+ } : {
676
+ thousandSeparator: ',',
677
+ decimalSeparator: '.'
678
+ };
679
+ }
680
+
681
+ // Trường hợp chỉ có dấu phẩy
682
+ if (hasComma && !hasDot) {
683
+ const parts = str.split(',');
684
+ if (parts.length === 2) {
685
+ return parts[1].length === 3 ? {
686
+ thousandSeparator: ',',
687
+ decimalSeparator: undefined
688
+ } : {
689
+ thousandSeparator: undefined,
690
+ decimalSeparator: ','
691
+ };
692
+ }
693
+ }
694
+
695
+ // Trường hợp chỉ có dấu chấm
696
+ if (hasDot && !hasComma) {
697
+ const parts = str.split('.');
698
+ if (parts.length === 2) {
699
+ return parts[1].length === 3 ? {
700
+ thousandSeparator: '.',
701
+ decimalSeparator: undefined
702
+ } : {
703
+ thousandSeparator: undefined,
704
+ decimalSeparator: '.'
705
+ };
706
+ }
707
+ }
708
+
709
+ // Không có dấu hoặc không hợp lệ
710
+ return null;
711
+ };
712
+ function isDate(value) {
713
+ if (value instanceof Date) {
714
+ return !isNaN(value.getTime());
715
+ }
716
+ if (typeof value === "string") {
717
+ // Chỉ chấp nhận định dạng yyyy-mm-dd hoặc mm/yyyy
718
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) || /^\d{2}\/\d{4}$/.test(value);
719
+ }
720
+ return false;
721
+ }
722
+
723
+ // Chuỗi MM/YYYY → Date
724
+ export function isDateString(str) {
725
+ return typeof str === "string" && (/^\d{2}\/\d{4}$/.test(str) || /^\d{4}-\d{2}-\d{2}$/.test(str));
726
+ }
727
+ function parseToDate(str) {
728
+ if (/^\d{2}\/\d{4}$/.test(str)) {
729
+ const [month, year] = str.split('/');
730
+ return new Date(parseInt(year), parseInt(month) - 1, 1);
731
+ }
732
+ return new Date(str);
733
+ }
734
+
735
+ // So sánh ngày (cùng ngày/tháng/năm)
736
+ export function compareDates(date1, date2) {
737
+ return date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear();
738
+ }
739
+
740
+ // Helper: compare MM/YYYY date string with itemValue
741
+ export function compareDate(itemValue, value) {
742
+ const [month, year] = value.split('/').map(Number);
743
+ const date = new Date(itemValue);
744
+ return date.getMonth() + 1 === month && date.getFullYear() === year;
745
+ }
746
+ export const removeVietnameseTones = str => {
747
+ if (!str) {
748
+ return '';
749
+ }
750
+ return str.normalize('NFD') // Tách các ký tự có dấu thành ký tự cơ bản + dấu
751
+ .replace(/[\u0300-\u036f]/g, '') // Xóa dấu
752
+ .replace(/đ/g, 'd') // Thay thế đ
753
+ .replace(/Đ/g, 'D').replace(/[^a-zA-Z0-9\s]/g, '') // Loại bỏ ký tự đặc biệt
754
+ .replace(/\s+/g, ' ') // Thay nhiều khoảng trắng thành 1 khoảng trắng
755
+ .trim();
756
+ };
757
+ export const shouldInclude = (item, queries) => {
758
+ if (item.isFilterState === true) {
759
+ return true;
760
+ }
761
+ let result = null;
762
+ for (const query of queries) {
763
+ const {
764
+ field,
765
+ value,
766
+ operator,
767
+ predicate
768
+ } = query;
769
+ const itemValue = item[field];
770
+ let condition = false;
771
+ const isDateComparison = isDate(itemValue) || isDateString(value);
772
+ const itemDate = isDateComparison ? new Date(itemValue) : null;
773
+ const queryDate = isDateComparison ? parseToDate(value) : null;
774
+ const itemStr = removeVietnameseTones(itemValue?.toString().toLowerCase?.() ?? '');
775
+ const queryStr = removeVietnameseTones(value?.toString().toLowerCase?.() ?? '');
776
+ switch (operator.toLowerCase()) {
777
+ case "equal":
778
+ condition = isDateComparison ? compareDates(itemDate, queryDate) : itemValue === value;
779
+ break;
780
+ case "notequal":
781
+ condition = isDateComparison ? !compareDates(itemDate, queryDate) : itemValue !== value;
782
+ break;
783
+ case "greaterthan":
784
+ // @ts-ignore
785
+ condition = isDateComparison ? itemDate > queryDate : itemValue > value;
786
+
787
+ // condition = isDateComparison ? invalidDate(itemDate) && invalidDate(queryDate) && itemDate > queryDate : itemValue > value;
788
+ break;
789
+ case "greaterthanorequal":
790
+ // @ts-ignore
791
+ condition = isDateComparison ? itemDate >= queryDate : itemValue >= value;
792
+ break;
793
+ case "lessthan":
794
+ // @ts-ignore
795
+ condition = isDateComparison ? itemDate < queryDate : itemValue < value;
796
+ break;
797
+ case "lessthanorequal":
798
+ // @ts-ignore
799
+ condition = isDateComparison ? itemDate <= queryDate : itemValue <= value;
800
+ break;
801
+ case "contains":
802
+ condition = itemStr?.includes(queryStr);
803
+ break;
804
+ case "startswith":
805
+ condition = itemStr?.startsWith(queryStr);
806
+ break;
807
+ case "endswith":
808
+ condition = itemStr?.endsWith(queryStr);
809
+ break;
810
+ default:
811
+ console.warn(`Unknown operator: ${operator}`);
812
+ break;
813
+ }
814
+ if (predicate === "and") {
815
+ result = result === null ? condition : result && condition;
816
+ } else if (predicate === "or") {
817
+ result = result === null ? condition : result || condition;
818
+ }
819
+ }
820
+ return result;
821
+ };
822
+
823
+ // function compareValues(a: any, b: any, order: "ascend" | "descend") {
824
+ // const desc = order === "descend";
825
+
826
+ // if (a == null && b == null) return 0;
827
+ // if (a == null) return desc ? 1 : -1;
828
+ // if (b == null) return desc ? -1 : 1;
829
+
830
+ // // Nếu là số
831
+ // if (typeof a === "number" && typeof b === "number") {
832
+ // return desc ? b - a : a - b;
833
+ // }
834
+
835
+ // // Nếu là ngày hợp lệ
836
+ // const dateA = new Date(a);
837
+ // const dateB = new Date(b);
838
+ // if (!isNaN(dateA.getTime()) && !isNaN(dateB.getTime())) {
839
+ // return desc
840
+ // ? dateB.getTime() - dateA.getTime()
841
+ // : dateA.getTime() - dateB.getTime();
842
+ // }
843
+
844
+ // // Mặc định coi như string
845
+ // return desc
846
+ // ? String(b).localeCompare(String(a))
847
+ // : String(a).localeCompare(String(b));
848
+ // }
849
+
850
+ // export function sortData(data: any[], sorter: Sorter[]): any[] {
851
+ // const sorted = [...data].sort((a, b) => {
852
+ // for (const { field, order } of sorter) {
853
+ // const result = compareValues(a[field], b[field], order);
854
+ // if (result !== 0) return result;
855
+ // }
856
+ // return 0;
857
+ // });
858
+
859
+ // return sorted.map(item => ({
860
+ // ...item,
861
+ // children: item.children
862
+ // ? sortData(item.children, sorter)
863
+ // : undefined
864
+ // }));
865
+ // }
866
+
867
+ // export function filterDataByColumns(data: any[], queries: any[], sorter: Sorter[], keysFilter: string[] | undefined) {
868
+
869
+ // if (!queries || queries.length === 0) {
870
+ // return sorter ? sortData(data, sorter) : data;
871
+ // }
872
+
873
+ // let filtered = data.map(item => {
874
+ // const newItem = { ...item }
875
+
876
+ // if (Array.isArray(item.children)) {
877
+ // newItem.children = filterDataByColumns(item.children, queries, sorter, keysFilter)
878
+ // }
879
+
880
+ // const isSelfMatched = shouldInclude(item, queries) || keysFilter?.includes(newItem?.rowId)
881
+
882
+ // // Nếu chính item thỏa hoặc có con thỏa → giữ lại
883
+ // if (isSelfMatched || (newItem.children && newItem.children.length > 0)) {
884
+ // return newItem
885
+ // }
886
+
887
+ // return null // loại bỏ node không phù hợp
888
+ // })
889
+ // .filter(Boolean) // xóa các null
890
+
891
+ // if (sorter && sorter.length > 0) {
892
+ // filtered = sortData(filtered, sorter);
893
+ // }
894
+
895
+ // return filtered;
896
+ // }
897
+
898
+ function getSortValue(item, field) {
899
+ if (item[field] !== undefined) return item[field];
900
+ if (item.children && item.children.length > 0) {
901
+ return getSortValue(item.children[0], field);
902
+ }
903
+ return undefined;
904
+ }
905
+ function compareValues(a, b, order) {
906
+ const desc = order === "descend";
907
+ if (a == null && b == null) return 0;
908
+ if (a == null) return desc ? 1 : -1;
909
+ if (b == null) return desc ? -1 : 1;
910
+
911
+ // Nếu là số
912
+ if (typeof a === "number" && typeof b === "number") {
913
+ return desc ? b - a : a - b;
914
+ }
915
+
916
+ // Nếu là ngày hợp lệ
917
+ const dateA = new Date(a);
918
+ const dateB = new Date(b);
919
+ if (!isNaN(dateA.getTime()) && !isNaN(dateB.getTime())) {
920
+ return desc ? dateB.getTime() - dateA.getTime() : dateA.getTime() - dateB.getTime();
921
+ }
922
+
923
+ // Mặc định coi như string
924
+ return desc ? String(b).localeCompare(String(a)) : String(a).localeCompare(String(b));
925
+ }
926
+ export function sortData(data, sorter) {
927
+ const sorted = [...data].sort((a, b) => {
928
+ for (const {
929
+ field,
930
+ order
931
+ } of sorter) {
932
+ const result = compareValues(getSortValue(a, field), getSortValue(b, field), order);
933
+ if (result !== 0) return result;
934
+ }
935
+ return 0;
936
+ });
937
+ return sorted.map(item => ({
938
+ ...item,
939
+ children: item.children ? sortData(item.children, sorter) : undefined
940
+ }));
941
+ }
942
+ export function filterDataByColumns(data, queries, sorter, keysFilter) {
943
+ if (!queries || queries.length === 0) {
944
+ return sorter ? sortData(data, sorter) : data;
945
+ }
946
+ let filtered = data.map(item => {
947
+ const newItem = {
948
+ ...item
949
+ };
950
+ if (Array.isArray(item.children)) {
951
+ newItem.children = filterDataByColumns(item.children, queries, sorter, keysFilter);
952
+ }
953
+ const isSelfMatched = shouldInclude(item, queries) || keysFilter?.includes(newItem?.rowId);
954
+
955
+ // Nếu chính item thỏa hoặc có con thỏa → giữ lại
956
+ if (isSelfMatched || newItem.children && newItem.children.length > 0) {
957
+ return newItem;
958
+ }
959
+ return null; // loại bỏ node không phù hợp
960
+ }).filter(Boolean); // xóa các null
961
+
962
+ if (sorter && sorter.length > 0) {
963
+ filtered = sortData(filtered, sorter);
964
+ }
965
+ return filtered;
966
+ }
967
+ export const getAllRowKey = data => {
968
+ const a = flattenArray(data);
969
+ return a.length ? a.map(it => it.rowId) : undefined;
970
+ };
971
+ export const isEditable = (column, rowData) => {
972
+ if (column && typeof column.editEnable === 'function') {
973
+ return column.editEnable(rowData);
974
+ }
975
+ return column?.editEnable;
976
+ };
977
+ export const checkFieldKey = key => {
978
+ if (key) {
979
+ return key;
980
+ } else {
981
+ return 'value';
982
+ }
983
+ };
984
+ export const convertArrayWithIndent = (inputArray, parentIndent = 0) => {
985
+ if (inputArray) {
986
+ return inputArray.map(item => {
987
+ const indent = parentIndent;
988
+ if (item.children && item.children.length > 0) {
989
+ item.children = convertArrayWithIndent(item.children, indent + 1);
990
+ }
991
+ return {
992
+ ...item,
993
+ indent,
994
+ rowId: item.rowId ? item.rowId : item.id ? item.id : newGuid()
995
+ };
996
+ });
997
+ } else {
998
+ return [];
999
+ }
1000
+ };
1001
+ export const convertLabelToTitle = data => {
1002
+ return data.map(item => {
1003
+ const {
1004
+ label,
1005
+ title,
1006
+ value,
1007
+ key,
1008
+ ...rest
1009
+ } = item;
1010
+ const newItem = {
1011
+ ...rest,
1012
+ value,
1013
+ label,
1014
+ key: key ?? value,
1015
+ title: title ?? label
1016
+ };
1017
+ if (item.children) {
1018
+ newItem.children = convertLabelToTitle(item.children);
1019
+ }
1020
+ return newItem;
1021
+ });
1022
+ };
1023
+ export const isNullOrUndefined = d => {
1024
+ return d === null || d === undefined;
1025
+ };
1026
+ export const isObjEmpty = obj => {
1027
+ if (isNullOrUndefined(obj)) {
1028
+ return true;
1029
+ } else {
1030
+ return Object.keys(obj).length === 0;
1031
+ }
1032
+ };
1033
+ export const isDisable = (column, rowData) => {
1034
+ if (column && typeof column?.disable === 'function') {
1035
+ return column.disable(rowData);
1036
+ }
1037
+ return !!column?.disable;
1038
+ };
1039
+ export const customWeekStartEndFormat = (value, weekFormat) => {
1040
+ return `${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value).endOf('week').format(weekFormat)}`;
1041
+ };
1042
+ export const parseBooleanToValue = (value, type) => {
1043
+ return type === 'boolean' ? value : Number(value);
1044
+ };
1045
+ export const isNameColor = strColor => {
1046
+ const s = new Option().style;
1047
+ s.color = strColor;
1048
+ return s.color === strColor;
1049
+ };
1050
+ export const isColor = value => {
1051
+ const hexRegex = /^#([0-9A-F]{3}){1,2}$/i;
1052
+ const rgbRegex = /^rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)$/;
1053
+ const rgbaRegex = /^rgba\((\d{1,3}), (\d{1,3}), (\d{1,3}), (0|1|0?\.\d+)\)$/;
1054
+ const hslRegex = /^hsl\(\d{1,3}, \d{1,3}%, \d{1,3}%\)$/;
1055
+ const hslaRegex = /^hsla\(\d{1,3}, \d{1,3}%, \d{1,3}%, (0|1|0?\.\d+)\)$/;
1056
+ const namedColors = /^(?:aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|purple|red|silver|teal|white|yellow)$/i;
1057
+ return hexRegex.test(value) || rgbRegex.test(value) || rgbaRegex.test(value) || hslRegex.test(value) || hslaRegex.test(value) || namedColors.test(value) || isNameColor(value);
1058
+ };
1059
+ export const genPresets = (presets = presetPalettes) => {
1060
+ return Object.entries(presets).map(([label, colors]) => ({
1061
+ label,
1062
+ colors,
1063
+ key: label
1064
+ }));
1065
+ };
1066
+ export const getEditType = (column, rowData) => {
1067
+ if (column && typeof column.editType === 'function') {
1068
+ return column.editType(rowData);
1069
+ }
1070
+ return column?.editType ?? 'text';
1071
+ };
1072
+ export const getDefaultValue = defaultValue => {
1073
+ if (defaultValue && typeof defaultValue === 'function') {
1074
+ return defaultValue();
1075
+ }
1076
+ return defaultValue;
1077
+ };
1078
+ export const flattenData = (childrenColumnName, data) => {
1079
+ let list = [];
1080
+ (data || []).forEach(record => {
1081
+ list.push(record);
1082
+ if (record && typeof record === 'object' && childrenColumnName in record) {
1083
+ list = [...list, ...flattenData(childrenColumnName, record[childrenColumnName])];
1084
+ }
1085
+ });
1086
+ return list;
1087
+ };
1088
+ export const getSelectedCellMatrix = (table, startCell, endCell) => {
1089
+ if (!startCell || !endCell) return {
1090
+ rowIds: [],
1091
+ colIds: [],
1092
+ startRowIndex: undefined,
1093
+ endRowIndex: undefined,
1094
+ startColIndex: undefined,
1095
+ endColIndex: undefined,
1096
+ colRange: [],
1097
+ rowRange: []
1098
+ };
1099
+
1100
+ // const rowIds = table.getRowModel().rows.map(r => r.id);
1101
+ const rowIds = table.getRowModel().flatRows.map(r => r.id);
1102
+ const colIds = table.getVisibleLeafColumns().map(c => c.id);
1103
+
1104
+ // const colIds = table.getAllLeafColumns().map(c => c.id);
1105
+
1106
+ const [startRowIndex, endRowIndex] = [rowIds.indexOf(startCell.rowId), rowIds.indexOf(endCell.rowId)].sort((a, b) => a - b);
1107
+ const [startColIndex, endColIndex] = [colIds.indexOf(startCell.colId), colIds.indexOf(endCell.colId)].sort((a, b) => a - b);
1108
+ return {
1109
+ rowRange: rowIds.slice(startRowIndex, endRowIndex + 1),
1110
+ colRange: colIds.slice(startColIndex, endColIndex + 1),
1111
+ startRowIndex,
1112
+ endRowIndex,
1113
+ startColIndex,
1114
+ endColIndex,
1115
+ rowIds,
1116
+ colIds
1117
+ };
1118
+ };
1119
+ export function addRowsDownWithCtrl(arr, n) {
1120
+ if (!Array.isArray(arr) || arr.length === 0) {
1121
+ return {
1122
+ combined: arr,
1123
+ addedRows: []
1124
+ };
1125
+ }
1126
+ const m = arr.length;
1127
+ const numCols = arr[0].length;
1128
+ const addedRows = [];
1129
+
1130
+ // Hàm kiểm tra kiểu date hợp lệ
1131
+ const isValidDate = item => {
1132
+ // return !isNaN(Date.parse(d))
1133
+
1134
+ if (typeof item === 'number') {
1135
+ // return 'number'
1136
+ return false;
1137
+ }
1138
+ if (typeof item === 'string') {
1139
+ // Kiểm tra nếu là chuỗi ISO date hợp lệ
1140
+ const date = new Date(item);
1141
+ if (!isNaN(date.getTime()) && item.includes('T')) {
1142
+ // return 'date'
1143
+ return true;
1144
+ }
1145
+ // return 'string'
1146
+ return false;
1147
+ }
1148
+ return !isNaN(Date.parse(item));
1149
+ };
1150
+
1151
+ // Lấy giá trị mẫu của cột j từ hàng đầu tiên
1152
+ const getSample = j => arr[0][j];
1153
+
1154
+ // Xác định chế độ xử lý cho mỗi cột:
1155
+ // mode = 'number-stepping' | 'date-stepping' | 'number-constant' | 'cycle'
1156
+ const modes = [];
1157
+ const steps = []; // bước tăng, nếu có (cho number hoặc date)
1158
+
1159
+ for (let j = 0; j < numCols; j++) {
1160
+ const sample = getSample(j);
1161
+ if (m === 1) {
1162
+ // Nếu mảng chỉ có 1 hàng: nếu là số thì giữ nguyên; nếu là date thì tăng 1 ngày; còn lại giữ nguyên.
1163
+ if (typeof sample === "number") {
1164
+ modes[j] = "number-constant";
1165
+ } else if (isValidDate(sample)) {
1166
+ modes[j] = "date-stepping";
1167
+ steps[j] = 24 * 3600 * 1000; // 1 ngày = 86400000 ms
1168
+ } else {
1169
+ modes[j] = "cycle";
1170
+ }
1171
+ } else if (m === 2) {
1172
+ // Nếu mảng có 2 hàng: nếu là số thì tính bước = row2 - row1, tương tự với date
1173
+ const first = arr[0][j],
1174
+ second = arr[1][j];
1175
+ if (typeof first === "number" && typeof second === "number") {
1176
+ modes[j] = "number-stepping";
1177
+ steps[j] = second - first;
1178
+ } else if (isValidDate(first) && isValidDate(second)) {
1179
+ modes[j] = "date-stepping";
1180
+ steps[j] = Date.parse(second) - Date.parse(first);
1181
+ } else {
1182
+ modes[j] = "cycle";
1183
+ }
1184
+ } else {
1185
+ // Nếu mảng có >2 hàng
1186
+ const first = arr[0][j],
1187
+ second = arr[1][j],
1188
+ third = arr[2][j];
1189
+ if (typeof first === "number" && typeof second === "number" && typeof third === "number") {
1190
+ const step1 = second - first;
1191
+ const step2 = third - second;
1192
+ if (step1 === step2) {
1193
+ modes[j] = "number-stepping";
1194
+ steps[j] = step1;
1195
+ } else {
1196
+ modes[j] = "cycle";
1197
+ }
1198
+ } else if (isValidDate(first) && isValidDate(second) && isValidDate(third)) {
1199
+ const step1 = Date.parse(second) - Date.parse(first);
1200
+ const step2 = Date.parse(third) - Date.parse(second);
1201
+ if (step1 === step2) {
1202
+ modes[j] = "date-stepping";
1203
+ steps[j] = step1;
1204
+ } else {
1205
+ modes[j] = "cycle";
1206
+ }
1207
+ } else {
1208
+ modes[j] = "cycle";
1209
+ }
1210
+ }
1211
+ }
1212
+
1213
+ // Tạo các dòng mới (thêm n dòng)
1214
+ // Với mỗi cột, nếu chế độ là stepping thì lấy giá trị cuối của mảng ban đầu và cộng thêm (i+1)*step
1215
+ // Nếu chế độ là cycle thì dùng arr[i mod m][j]
1216
+ for (let i = 0; i < n; i++) {
1217
+ const newRow = [];
1218
+ for (let j = 0; j < numCols; j++) {
1219
+ let newValue;
1220
+ switch (modes[j]) {
1221
+ case "number-constant":
1222
+ // Mảng có 1 hàng, số giữ nguyên
1223
+ newValue = arr[0][j];
1224
+ break;
1225
+ case "number-stepping":
1226
+ {
1227
+ // Lấy giá trị cuối của cột j trong mảng ban đầu
1228
+ const lastValue = arr[m - 1][j];
1229
+ newValue = lastValue + (i + 1) * steps[j];
1230
+ }
1231
+ break;
1232
+ case "date-stepping":
1233
+ {
1234
+ // Lấy giá trị cuối, chuyển về date, cộng thêm (i+1)*step, chuyển lại về định dạng ISO
1235
+ const lastDate = new Date(arr[m - 1][j]);
1236
+ const newTime = lastDate.getTime() + (i + 1) * steps[j];
1237
+ newValue = moment(new Date(newTime)).format();
1238
+ }
1239
+ break;
1240
+ case "cycle":
1241
+ default:
1242
+ // Lặp lại nội dung theo vòng tròn: dùng hàng thứ (i mod m)
1243
+ newValue = arr[i % m][j];
1244
+ break;
1245
+ }
1246
+ newRow.push(newValue);
1247
+ }
1248
+ addedRows.push(newRow);
1249
+ }
1250
+ const combined = arr.concat(addedRows);
1251
+ return {
1252
+ combined,
1253
+ addedRows
1254
+ };
1255
+ }
1256
+ export function addRowsDown(arr, n) {
1257
+ if (!Array.isArray(arr) || arr.length === 0) {
1258
+ return {
1259
+ combined: arr,
1260
+ addedRows: []
1261
+ };
1262
+ }
1263
+ const m = arr.length;
1264
+ const numCols = arr[0].length;
1265
+ const addedRows = [];
1266
+
1267
+ // // Hàm kiểm tra kiểu date hợp lệ
1268
+ // const isValidDate = (item: any) => {
1269
+ //
1270
+ //
1271
+ // // return !isNaN(Date.parse(d))
1272
+ //
1273
+ // if (typeof item === 'number') {
1274
+ // // return 'number'
1275
+ // return false
1276
+ // }
1277
+ // if (typeof item === 'string') {
1278
+ // // Kiểm tra nếu là chuỗi ISO date hợp lệ
1279
+ // const date = new Date(item)
1280
+ // if (!isNaN(date.getTime()) && item.includes('T')) {
1281
+ // // return 'date'
1282
+ // return true
1283
+ // }
1284
+ // // return 'string'
1285
+ // return false
1286
+ // }
1287
+ //
1288
+ // return !isNaN(Date.parse(item))
1289
+ //
1290
+ // }
1291
+
1292
+ // Lấy giá trị mẫu của cột j từ hàng đầu tiên
1293
+ const getSample = j => arr[0][j];
1294
+
1295
+ // Xác định chế độ xử lý cho mỗi cột:
1296
+ // mode = 'number-stepping' | 'date-stepping' | 'number-constant' | 'cycle'
1297
+ const modes = [];
1298
+ const steps = []; // bước tăng, nếu có (cho number hoặc date)
1299
+
1300
+ for (let j = 0; j < numCols; j++) {
1301
+ const sample = getSample(j);
1302
+ if (m === 1) {
1303
+ // Nếu mảng chỉ có 1 hàng: nếu là số thì giữ nguyên; nếu là date thì tăng 1 ngày; còn lại giữ nguyên.
1304
+ if (typeof sample === "number") {
1305
+ modes[j] = "number-constant";
1306
+ }
1307
+ // else if (isValidDate(sample)) {
1308
+ // modes[j] = "date-stepping"
1309
+ // steps[j] = 24 * 3600 * 1000 // 1 ngày = 86400000 ms
1310
+ // }
1311
+ else {
1312
+ modes[j] = "cycle";
1313
+ }
1314
+ } else if (m === 2) {
1315
+ // Nếu mảng có 2 hàng: nếu là số thì tính bước = row2 - row1, tương tự với date
1316
+ const first = arr[0][j],
1317
+ second = arr[1][j];
1318
+ if (typeof first === "number" && typeof second === "number") {
1319
+ modes[j] = "number-stepping";
1320
+ steps[j] = second - first;
1321
+ }
1322
+ // else if (isValidDate(first) && isValidDate(second)) {
1323
+ // modes[j] = "date-stepping"
1324
+ // steps[j] = Date.parse(second) - Date.parse(first)
1325
+ // }
1326
+ else {
1327
+ modes[j] = "cycle";
1328
+ }
1329
+ } else {
1330
+ // Nếu mảng có >2 hàng
1331
+ const first = arr[0][j],
1332
+ second = arr[1][j],
1333
+ third = arr[2][j];
1334
+ if (typeof first === "number" && typeof second === "number" && typeof third === "number") {
1335
+ const step1 = second - first;
1336
+ const step2 = third - second;
1337
+ if (step1 === step2) {
1338
+ modes[j] = "number-stepping";
1339
+ steps[j] = step1;
1340
+ } else {
1341
+ modes[j] = "cycle";
1342
+ }
1343
+ }
1344
+ // else if (isValidDate(first) && isValidDate(second) && isValidDate(third)) {
1345
+ // const step1 = Date.parse(second) - Date.parse(first)
1346
+ // const step2 = Date.parse(third) - Date.parse(second)
1347
+ // if (step1 === step2) {
1348
+ // modes[j] = "date-stepping"
1349
+ // steps[j] = step1
1350
+ // } else {
1351
+ // modes[j] = "cycle"
1352
+ // }
1353
+ // }
1354
+ else {
1355
+ modes[j] = "cycle";
1356
+ }
1357
+ }
1358
+ }
1359
+
1360
+ // Tạo các dòng mới (thêm n dòng)
1361
+ // Với mỗi cột, nếu chế độ là stepping thì lấy giá trị cuối của mảng ban đầu và cộng thêm (i+1)*step
1362
+ // Nếu chế độ là cycle thì dùng arr[i mod m][j]
1363
+ for (let i = 0; i < n; i++) {
1364
+ const newRow = [];
1365
+ for (let j = 0; j < numCols; j++) {
1366
+ let newValue;
1367
+ switch (modes[j]) {
1368
+ case "number-constant":
1369
+ // Mảng có 1 hàng, số giữ nguyên
1370
+ newValue = arr[0][j];
1371
+ break;
1372
+ case "number-stepping":
1373
+ {
1374
+ // Lấy giá trị cuối của cột j trong mảng ban đầu
1375
+ const lastValue = arr[m - 1][j];
1376
+ newValue = lastValue + (i + 1) * steps[j];
1377
+ }
1378
+ break;
1379
+ // case "date-stepping":
1380
+ // {
1381
+ // // Lấy giá trị cuối, chuyển về date, cộng thêm (i+1)*step, chuyển lại về định dạng ISO
1382
+ // const lastDate = new Date(arr[m - 1][j])
1383
+ // const newTime = lastDate.getTime() + (i + 1) * steps[j]
1384
+ // newValue = moment(new Date(newTime)).format()
1385
+ // }
1386
+ // break
1387
+ case "cycle":
1388
+ default:
1389
+ // Lặp lại nội dung theo vòng tròn: dùng hàng thứ (i mod m)
1390
+ newValue = arr[i % m][j];
1391
+ break;
1392
+ }
1393
+ newRow.push(newValue);
1394
+ }
1395
+ addedRows.push(newRow);
1396
+ }
1397
+ const combined = arr.concat(addedRows);
1398
+ return {
1399
+ combined,
1400
+ addedRows
1401
+ };
1402
+ }
1403
+ export function addRowsUpWithCtrl(array, n) {
1404
+ const arr = array.reverse();
1405
+ if (!Array.isArray(arr) || arr.length === 0) {
1406
+ return {
1407
+ combined: arr,
1408
+ addedRows: []
1409
+ };
1410
+ }
1411
+ const m = arr.length;
1412
+ const numCols = arr[0].length;
1413
+ const addedRows = [];
1414
+
1415
+ // Hàm kiểm tra kiểu date hợp lệ
1416
+ const isValidDate = item => {
1417
+ // return !isNaN(Date.parse(d))
1418
+
1419
+ if (typeof item === 'number') {
1420
+ // return 'number'
1421
+ return false;
1422
+ }
1423
+ if (typeof item === 'string') {
1424
+ // Kiểm tra nếu là chuỗi ISO date hợp lệ
1425
+ const date = new Date(item);
1426
+ if (!isNaN(date.getTime()) && item.includes('T')) {
1427
+ // return 'date'
1428
+ return true;
1429
+ }
1430
+ // return 'string'
1431
+ return false;
1432
+ }
1433
+ return !isNaN(Date.parse(item));
1434
+ };
1435
+
1436
+ // Lấy giá trị mẫu của cột j từ hàng đầu tiên
1437
+ const getSample = j => arr[0][j];
1438
+
1439
+ // Xác định chế độ xử lý cho mỗi cột:
1440
+ // mode = 'number-stepping' | 'date-stepping' | 'number-constant' | 'cycle'
1441
+ const modes = [];
1442
+ const steps = []; // bước tăng, nếu có (cho number hoặc date)
1443
+
1444
+ for (let j = 0; j < numCols; j++) {
1445
+ const sample = getSample(j);
1446
+ if (m === 1) {
1447
+ // Nếu mảng chỉ có 1 hàng: nếu là số thì giữ nguyên; nếu là date thì tăng 1 ngày; còn lại giữ nguyên.
1448
+ if (typeof sample === "number") {
1449
+ modes[j] = "number-constant";
1450
+ } else if (isValidDate(sample)) {
1451
+ modes[j] = "date-stepping";
1452
+ steps[j] = 24 * 3600 * 1000; // 1 ngày = 86400000 ms
1453
+ } else {
1454
+ modes[j] = "cycle";
1455
+ }
1456
+ } else if (m === 2) {
1457
+ // Nếu mảng có 2 hàng: nếu là số thì tính bước = row2 - row1, tương tự với date
1458
+ const first = arr[0][j],
1459
+ second = arr[1][j];
1460
+ if (typeof first === "number" && typeof second === "number") {
1461
+ modes[j] = "number-stepping";
1462
+ steps[j] = second - first;
1463
+ } else if (isValidDate(first) && isValidDate(second)) {
1464
+ modes[j] = "date-stepping";
1465
+ steps[j] = Date.parse(second) - Date.parse(first);
1466
+ } else {
1467
+ modes[j] = "cycle";
1468
+ }
1469
+ } else {
1470
+ // Nếu mảng có >2 hàng
1471
+ const first = arr[0][j],
1472
+ second = arr[1][j],
1473
+ third = arr[2][j];
1474
+ if (typeof first === "number" && typeof second === "number" && typeof third === "number") {
1475
+ const step1 = second - first;
1476
+ const step2 = third - second;
1477
+ if (step1 === step2) {
1478
+ modes[j] = "number-stepping";
1479
+ steps[j] = step1;
1480
+ } else {
1481
+ modes[j] = "cycle";
1482
+ }
1483
+ } else if (isValidDate(first) && isValidDate(second) && isValidDate(third)) {
1484
+ const step1 = Date.parse(second) - Date.parse(first);
1485
+ const step2 = Date.parse(third) - Date.parse(second);
1486
+ if (step1 === step2) {
1487
+ modes[j] = "date-stepping";
1488
+ steps[j] = step1;
1489
+ } else {
1490
+ modes[j] = "cycle";
1491
+ }
1492
+ } else {
1493
+ modes[j] = "cycle";
1494
+ }
1495
+ }
1496
+ }
1497
+
1498
+ // Tạo các dòng mới (thêm n dòng)
1499
+ // Với mỗi cột, nếu chế độ là stepping thì lấy giá trị cuối của mảng ban đầu và cộng thêm (i+1)*step
1500
+ // Nếu chế độ là cycle thì dùng arr[i mod m][j]
1501
+ for (let i = n - 1; i >= 0; i--) {
1502
+ const newRow = [];
1503
+ for (let j = 0; j < numCols; j++) {
1504
+ let newValue;
1505
+ switch (modes[j]) {
1506
+ case "number-constant":
1507
+ // Mảng có 1 hàng, số giữ nguyên
1508
+ newValue = arr[0][j];
1509
+ break;
1510
+ case "number-stepping":
1511
+ {
1512
+ // Lấy giá trị cuối của cột j trong mảng ban đầu
1513
+
1514
+ const lastValue = arr[m - 1][j];
1515
+ newValue = lastValue - (i + 1) * steps[j] * -1;
1516
+ }
1517
+ break;
1518
+ case "date-stepping":
1519
+ {
1520
+ // Lấy giá trị cuối, chuyển về date, cộng thêm (i+1)*step, chuyển lại về định dạng ISO
1521
+
1522
+ const lastDate = new Date(arr[m - 1][j]);
1523
+ const newTime = m === 1 ? lastDate.getTime() - (i + 1) * steps[j] : lastDate.getTime() - (i + 1) * steps[j] * -1;
1524
+ newValue = moment(new Date(newTime)).format();
1525
+ }
1526
+ break;
1527
+ case "cycle":
1528
+ default:
1529
+ // Lặp lại nội dung theo vòng tròn: dùng hàng thứ (i mod m)
1530
+
1531
+ newValue = arr[i % m][j];
1532
+ break;
1533
+ }
1534
+ newRow.push(newValue);
1535
+ }
1536
+ addedRows.push(newRow);
1537
+ }
1538
+ const combined = arr.concat(addedRows);
1539
+ return {
1540
+ combined,
1541
+ addedRows
1542
+ };
1543
+ }
1544
+ export function addRowsUp(array, n) {
1545
+ const arr = array.reverse();
1546
+ if (!Array.isArray(arr) || arr.length === 0) {
1547
+ return {
1548
+ combined: arr,
1549
+ addedRows: []
1550
+ };
1551
+ }
1552
+ const m = arr.length;
1553
+ const numCols = arr[0].length;
1554
+ const addedRows = [];
1555
+
1556
+ // Hàm kiểm tra kiểu date hợp lệ
1557
+ // const isValidDate = (item: any) => {
1558
+ //
1559
+ //
1560
+ // // return !isNaN(Date.parse(d))
1561
+ //
1562
+ // if (typeof item === 'number') {
1563
+ // // return 'number'
1564
+ // return false
1565
+ // }
1566
+ // if (typeof item === 'string') {
1567
+ // // Kiểm tra nếu là chuỗi ISO date hợp lệ
1568
+ // const date = new Date(item)
1569
+ // if (!isNaN(date.getTime()) && item.includes('T')) {
1570
+ // // return 'date'
1571
+ // return true
1572
+ // }
1573
+ // // return 'string'
1574
+ // return false
1575
+ // }
1576
+ //
1577
+ // return !isNaN(Date.parse(item))
1578
+ //
1579
+ // }
1580
+
1581
+ // Lấy giá trị mẫu của cột j từ hàng đầu tiên
1582
+ const getSample = j => arr[0][j];
1583
+
1584
+ // Xác định chế độ xử lý cho mỗi cột:
1585
+ // mode = 'number-stepping' | 'date-stepping' | 'number-constant' | 'cycle'
1586
+ const modes = [];
1587
+ const steps = []; // bước tăng, nếu có (cho number hoặc date)
1588
+
1589
+ for (let j = 0; j < numCols; j++) {
1590
+ const sample = getSample(j);
1591
+ if (m === 1) {
1592
+ // Nếu mảng chỉ có 1 hàng: nếu là số thì giữ nguyên; nếu là date thì tăng 1 ngày; còn lại giữ nguyên.
1593
+ if (typeof sample === "number") {
1594
+ modes[j] = "number-constant";
1595
+ } else {
1596
+ modes[j] = "cycle";
1597
+ }
1598
+ } else if (m === 2) {
1599
+ // Nếu mảng có 2 hàng: nếu là số thì tính bước = row2 - row1, tương tự với date
1600
+ const first = arr[0][j],
1601
+ second = arr[1][j];
1602
+ if (typeof first === "number" && typeof second === "number") {
1603
+ modes[j] = "number-stepping";
1604
+ steps[j] = second - first;
1605
+ } else {
1606
+ modes[j] = "cycle";
1607
+ }
1608
+ } else {
1609
+ // Nếu mảng có >2 hàng
1610
+ const first = arr[0][j],
1611
+ second = arr[1][j],
1612
+ third = arr[2][j];
1613
+ if (typeof first === "number" && typeof second === "number" && typeof third === "number") {
1614
+ const step1 = second - first;
1615
+ const step2 = third - second;
1616
+ if (step1 === step2) {
1617
+ modes[j] = "number-stepping";
1618
+ steps[j] = step1;
1619
+ } else {
1620
+ modes[j] = "cycle";
1621
+ }
1622
+ } else {
1623
+ modes[j] = "cycle";
1624
+ }
1625
+ }
1626
+ }
1627
+
1628
+ // Tạo các dòng mới (thêm n dòng)
1629
+ // Với mỗi cột, nếu chế độ là stepping thì lấy giá trị cuối của mảng ban đầu và cộng thêm (i+1)*step
1630
+ // Nếu chế độ là cycle thì dùng arr[i mod m][j]
1631
+ for (let i = n - 1; i >= 0; i--) {
1632
+ const newRow = [];
1633
+ for (let j = 0; j < numCols; j++) {
1634
+ let newValue;
1635
+ switch (modes[j]) {
1636
+ case "number-constant":
1637
+ // Mảng có 1 hàng, số giữ nguyên
1638
+ newValue = arr[0][j];
1639
+ break;
1640
+ case "number-stepping":
1641
+ {
1642
+ // Lấy giá trị cuối của cột j trong mảng ban đầu
1643
+
1644
+ const lastValue = arr[m - 1][j];
1645
+ newValue = lastValue - (i + 1) * steps[j] * -1;
1646
+ }
1647
+ break;
1648
+ case "cycle":
1649
+ default:
1650
+ // Lặp lại nội dung theo vòng tròn: dùng hàng thứ (i mod m)
1651
+
1652
+ newValue = arr[i % m][j];
1653
+ break;
1654
+ }
1655
+ newRow.push(newValue);
1656
+ }
1657
+ addedRows.push(newRow);
1658
+ }
1659
+ const combined = arr.concat(addedRows);
1660
+ return {
1661
+ combined,
1662
+ addedRows
1663
+ };
1664
+ }
1665
+ export const convertFilters = filters => {
1666
+ const result = [];
1667
+ filters.forEach(({
1668
+ key,
1669
+ column,
1670
+ filteredKeys,
1671
+ operator
1672
+ }) => {
1673
+ if (!filteredKeys || filteredKeys.length === 0) {
1674
+ return;
1675
+ }
1676
+ if (column?.typeFilter === "DateRange" && filteredKeys.length === 2) {
1677
+ result.push({
1678
+ key,
1679
+ field: column?.field,
1680
+ value: filteredKeys[0],
1681
+ predicate: "and",
1682
+ operator: "greaterthanorequal"
1683
+ }, {
1684
+ key,
1685
+ field: column?.field,
1686
+ value: filteredKeys[1],
1687
+ predicate: "and",
1688
+ operator: "lessthanorequal"
1689
+ });
1690
+ } else if (column?.typeFilter === "NumberRange") {
1691
+ if ((filteredKeys[0] || filteredKeys[0] === 0) && !filteredKeys[1]) {
1692
+ result.push({
1693
+ key,
1694
+ field: column?.field,
1695
+ value: filteredKeys[0],
1696
+ predicate: "and",
1697
+ operator: "greaterthanorequal"
1698
+ });
1699
+ }
1700
+ if ((filteredKeys[1] || filteredKeys[1] === 0) && !filteredKeys[0]) {
1701
+ result.push({
1702
+ key,
1703
+ field: column?.field,
1704
+ value: filteredKeys[1],
1705
+ predicate: "and",
1706
+ operator: "lessthanorequal"
1707
+ });
1708
+ }
1709
+ if ((filteredKeys[0] || filteredKeys[0] === 0) && (filteredKeys[1] || filteredKeys[1] === 0)) {
1710
+ result.push({
1711
+ key,
1712
+ field: column?.field,
1713
+ value: filteredKeys[0],
1714
+ predicate: "and",
1715
+ operator: "greaterthanorequal"
1716
+ }, {
1717
+ key,
1718
+ field: column?.field,
1719
+ value: filteredKeys[1],
1720
+ predicate: "and",
1721
+ operator: "lessthanorequal"
1722
+ });
1723
+ }
1724
+ } else if (column?.typeFilter === 'Checkbox') {
1725
+ filteredKeys.forEach(value => {
1726
+ result.push({
1727
+ key,
1728
+ field: column?.field,
1729
+ value,
1730
+ predicate: "or",
1731
+ operator
1732
+ });
1733
+ });
1734
+ } else {
1735
+ result.push({
1736
+ key,
1737
+ field: column?.field,
1738
+ value: filteredKeys[0],
1739
+ predicate: 'and',
1740
+ operator
1741
+ });
1742
+ }
1743
+ });
1744
+ return result;
1745
+ };
1746
+
1747
+ // export function getInvisibleColumns(columns: ColumnTable[]): Record<string, boolean> {
1748
+ // const result: Record<string, boolean> = {};
1749
+ // for (const col of columns) {
1750
+ // if (col.visible === false || col.hidden) {
1751
+ // result[col.field ?? ''] = false;
1752
+ // }
1753
+ // }
1754
+ // return result;
1755
+ // }
1756
+
1757
+ export function getInvisibleColumns(columns) {
1758
+ const result = {};
1759
+ function traverse(cols) {
1760
+ for (const col of cols) {
1761
+ if (col.visible === false) {
1762
+ result[col.field ?? ''] = false;
1763
+ }
1764
+ if (col.children && col.children.length > 0) {
1765
+ traverse(col.children);
1766
+ }
1767
+ }
1768
+ }
1769
+ traverse(columns);
1770
+ return result;
1771
+ }
1772
+ export const getAllVisibleKeys = columns => {
1773
+ const keys = [];
1774
+ const traverse = (cols, parentHidden = false) => {
1775
+ for (const col of cols) {
1776
+ if (col.hidden || parentHidden) {
1777
+ continue;
1778
+ }
1779
+ if (col.key) {
1780
+ keys.push(col.key);
1781
+ }
1782
+ if (col.children) {
1783
+ traverse(col.children, col.hidden);
1784
+ }
1785
+ }
1786
+ };
1787
+ traverse(columns);
1788
+ return keys;
1789
+ };
1790
+ export const getAllVisibleKeys1 = columns => {
1791
+ const keys = [];
1792
+ const traverse = (cols, parentHidden = false) => {
1793
+ for (const col of cols) {
1794
+ if (col.visible === false || col.hidden || parentHidden) {
1795
+ continue;
1796
+ }
1797
+ if (col.field) {
1798
+ keys.push(col.field);
1799
+ }
1800
+ if (col.children) {
1801
+ traverse(col.children, col.visible);
1802
+ }
1803
+ }
1804
+ };
1805
+ traverse(columns);
1806
+ return keys;
1807
+ };
1808
+ export function getHiddenParentKeys(columns, parentKeys = []) {
1809
+ const hiddenParents = new Set();
1810
+ for (const column of columns) {
1811
+ if (column.children) {
1812
+ const currentPath = column.key ? [...parentKeys, column.key] : [...parentKeys];
1813
+ const childHiddenParents = getHiddenParentKeys(column.children, currentPath);
1814
+ if (childHiddenParents.length > 0) {
1815
+ childHiddenParents.forEach(key => hiddenParents.add(key));
1816
+ currentPath.forEach(key => hiddenParents.add(key));
1817
+ }
1818
+ } else if (column.hidden) {
1819
+ parentKeys.forEach(key => hiddenParents.add(key));
1820
+ }
1821
+ }
1822
+ return Array.from(hiddenParents);
1823
+ }
1824
+ export function getHiddenParentKeys1(columns, parentKeys = []) {
1825
+ const hiddenParents = new Set();
1826
+ for (const column of columns) {
1827
+ if (column.children) {
1828
+ const currentPath = column.field ? [...parentKeys, column.field] : [...parentKeys];
1829
+ const childHiddenParents = getHiddenParentKeys1(column.children, currentPath);
1830
+ if (childHiddenParents.length > 0) {
1831
+ childHiddenParents.forEach(key => hiddenParents.add(key));
1832
+ currentPath.forEach(key => hiddenParents.add(key));
1833
+ }
1834
+ } else if (column.visible !== false && column.hidden !== true) {
1835
+ parentKeys.forEach(key => hiddenParents.add(key));
1836
+ }
1837
+ }
1838
+ return Array.from(hiddenParents);
1839
+ }
1840
+ export const getVisibleColumnKeys = columns => {
1841
+ const allKeys = getAllVisibleKeys(columns);
1842
+ const allParentKeys = getHiddenParentKeys(columns);
1843
+ return allKeys.filter(item => !allParentKeys.includes(item));
1844
+ };
1845
+ export const getVisibleColumnKeys1 = columns => {
1846
+ const allKeys = getAllVisibleKeys1(columns);
1847
+ const allParentKeys = getHiddenParentKeys1(columns);
1848
+ return allKeys.filter(item => !allParentKeys.includes(item));
1849
+ };
1850
+ export function isObjEqual(obj1, obj2) {
1851
+ // Trường hợp tham chiếu bằng nhau
1852
+ if (obj1 === obj2) return true;
1853
+
1854
+ // Nếu 1 trong 2 không phải object hoặc null thì so sánh trực tiếp
1855
+ if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
1856
+ return obj1 === obj2;
1857
+ }
1858
+
1859
+ // Lấy danh sách key
1860
+ const keys1 = Object.keys(obj1);
1861
+ const keys2 = Object.keys(obj2);
1862
+
1863
+ // Nếu số key khác nhau thì khác nhau
1864
+ if (keys1.length !== keys2.length) return false;
1865
+
1866
+ // Duyệt và so sánh từng key
1867
+ for (const key of keys1) {
1868
+ if (!keys2.includes(key)) return false;
1869
+ if (!isObjEqual(obj1[key], obj2[key])) return false;
1870
+ }
1871
+ return true;
1872
+ }
1873
+
1874
+ // Sorting function
1875
+ export const sortByType = arr => {
1876
+ if (arr) {
1877
+ return arr.sort((a, b) => {
1878
+ if ((a.fixed ?? a.fixedType) === 'left' && (b.fixed ?? b.fixedType) !== 'left') {
1879
+ return -1;
1880
+ } else if ((a.fixed ?? a.fixedType) !== 'left' && (b.fixed ?? b.fixedType) === 'left') {
1881
+ return 1;
1882
+ } else if ((a.fixed ?? a.fixedType) === 'right' && (b.fixed ?? b.fixedType) !== 'right') {
1883
+ return 1;
1884
+ } else if ((a.fixed ?? a.fixedType) !== 'right' && (b.fixed ?? b.fixedType) === 'right') {
1885
+ return -1;
1886
+ }
1887
+ return 0;
1888
+ });
1889
+ } else {
1890
+ return [];
1891
+ }
1892
+ };
1893
+ export function convertColumnsToTreeData(columns, groupColumns) {
1894
+ // return columns.map((col) => {
1895
+ // const node: TreeDataNode = {
1896
+ // key: String(col.id ?? col.id ?? col.header), // key duy nhất
1897
+ // title: String(col.header ?? col.id ?? ''), // tiêu đề
1898
+ // }
1899
+
1900
+ // // Nếu có children (nested columns)
1901
+ // if ('columns' in col && Array.isArray((col as any).columns)) {
1902
+ // node.children = convertColumnsToTreeData(
1903
+ // (col as any).columns as ColumnDef<T, any>[]
1904
+ // )
1905
+ // }
1906
+
1907
+ // return node
1908
+ // })
1909
+
1910
+ return columns.filter(col => {
1911
+ const meta = col.meta ?? {};
1912
+ const inGroup = groupColumns ? groupColumns.includes(String(col.id ?? col.id)) : false;
1913
+
1914
+ // Điều kiện filter:
1915
+ // - Nếu meta.showInColumnChoose = false => loại bỏ
1916
+ // - Nếu không nằm trong groupColumns và không phải column group => loại bỏ
1917
+ if (meta.showInColumnChoose === false) return false;
1918
+ if (inGroup && !('columns' in col && Array.isArray(col.columns))) {
1919
+ return false;
1920
+ }
1921
+ return true;
1922
+ }).map(col => {
1923
+ const node = {
1924
+ key: String(col.id ?? col.id ?? col.header),
1925
+ // title: () => col.header as any
1926
+ title: col.header
1927
+
1928
+ // title: String(col.header ?? col.id ?? ''),
1929
+ };
1930
+ if ('columns' in col && Array.isArray(col.columns)) {
1931
+ const children = convertColumnsToTreeData(col.columns, groupColumns);
1932
+ if (children.length > 0) {
1933
+ node.children = children;
1934
+ }
1935
+ }
1936
+ return node;
1937
+ });
1938
+ }
1939
+ export const updateColumns1 = (columns, includes) => {
1940
+ return columns.map(column => {
1941
+ const newColumn = {
1942
+ ...column
1943
+ };
1944
+ let hasVisibleChild = false;
1945
+ if (!column.field) {
1946
+ return column;
1947
+ }
1948
+ if (newColumn.children) {
1949
+ newColumn.children = updateColumns1(newColumn.children, includes);
1950
+ hasVisibleChild = newColumn.children.some(child => !child.hidden);
1951
+ }
1952
+ newColumn.visible = !!(newColumn.field && includes.includes(newColumn.field));
1953
+ if (newColumn.children && newColumn.children.length > 0) {
1954
+ newColumn.visible = !hasVisibleChild;
1955
+ }
1956
+ return newColumn;
1957
+ });
1958
+ };
1959
+ export const convertToObj = arr => {
1960
+ // const result = Object.keys(obj).reduce((acc: any, key) => {
1961
+ // acc[key] = false;
1962
+ // return acc;
1963
+ // }, {});
1964
+
1965
+ // return result
1966
+
1967
+ return Object.fromEntries(arr.map(key => [key, false]));
1968
+ };
1969
+ export const convertToObjTrue = arr => {
1970
+ // const result = Object.keys(obj).reduce((acc: any, key) => {
1971
+ // acc[key] = false;
1972
+ // return acc;
1973
+ // }, {});
1974
+
1975
+ // return result
1976
+
1977
+ return Object.fromEntries(arr.map(key => [key, true]));
1978
+ };
1979
+ export const getDiffent2Array = (a, b) => {
1980
+ return [...a.filter(x => !b.includes(x)), ...b.filter(x => !a.includes(x))];
1981
+ };
1982
+ export function findFirst(items) {
1983
+ // const leftItem = items.find(item => item.getIsPinned() === 'left')
1984
+ const leftItem = items.find(item => item.getIsPinned() === 'left');
1985
+ if (leftItem) return leftItem;
1986
+ return null;
1987
+ }
1988
+ export function isTreeArray(arr) {
1989
+ if (!Array.isArray(arr) || arr.length === 0) {
1990
+ return false;
1991
+ }
1992
+ for (const item of arr) {
1993
+ if (!item) {
1994
+ return false;
1995
+ }
1996
+ if (item.children?.length > 0) {
1997
+ return true;
1998
+ }
1999
+ }
2000
+ return false;
2001
+ }
2002
+ export function updateColumnWidthsRecursive(columns, sizing) {
2003
+ return columns.map(col => {
2004
+ const updated = {
2005
+ ...col
2006
+ };
2007
+
2008
+ // cập nhật width nếu có trong sizing
2009
+ if (sizing[col.field] !== undefined) {
2010
+ updated.width = sizing[col.field];
2011
+ }
2012
+
2013
+ // nếu có children thì gọi đệ quy
2014
+ if (col.children && col.children.length > 0) {
2015
+ updated.children = updateColumnWidthsRecursive(col.children, sizing);
2016
+ }
2017
+ return updated;
2018
+ });
2019
+ }
2020
+ export function updateWidthsByOther(source, target) {
2021
+ const targetMap = new Map();
2022
+
2023
+ // tạo map {field -> width} từ target
2024
+ const buildMap = cols => {
2025
+ cols.forEach(col => {
2026
+ if (col.width !== undefined) {
2027
+ targetMap.set(col.field, col.width);
2028
+ }
2029
+ if (col.children) {
2030
+ buildMap(col.children);
2031
+ }
2032
+ });
2033
+ };
2034
+ buildMap(target);
2035
+
2036
+ // cập nhật width từ map
2037
+ const update = cols => cols.map(col => {
2038
+ const updated = {
2039
+ ...col
2040
+ };
2041
+ if (targetMap.has(col.field)) {
2042
+ updated.width = targetMap.get(col.field);
2043
+ }
2044
+ if (col.children) {
2045
+ updated.children = update(col.children);
2046
+ }
2047
+ return updated;
2048
+ });
2049
+ return update(source);
2050
+ }
2051
+ export function findAllChildrenKeys2(data, rowKey, childrenColumnName) {
2052
+ const keys = [];
2053
+ function dig(list) {
2054
+ (list || []).forEach(item => {
2055
+ keys.push(item[rowKey]);
2056
+ dig(item[childrenColumnName]);
2057
+ });
2058
+ }
2059
+ dig(data);
2060
+ return keys;
2061
+ }
2062
+ export function parseExcelText(text) {
2063
+ // const text = e.clipboardData?.getData('text/plain') ?? '';
2064
+ if (!text) return [];
2065
+
2066
+ // Excel thường dùng \r\n giữa dòng, \t giữa cột
2067
+ const rows = text.split(/\r?\n/) // tách theo dòng
2068
+ .filter(r => r.trim() !== '') // bỏ dòng trống
2069
+ .map(row => row.split('\t') // tách theo cột
2070
+ .map(cell => cell.replace(/\r/g, '').replace(/\n/g, '\n')) // giữ xuống dòng trong ô
2071
+ );
2072
+ return rows;
2073
+ }
2074
+ export function parseExcelClipboard(e) {
2075
+ const text = e.clipboardData?.getData('text/plain') ?? '';
2076
+ if (!text) return [];
2077
+
2078
+ // Excel thường dùng \r\n giữa dòng, \t giữa cột
2079
+ const rows = text.split(/\r?\n/) // tách theo dòng
2080
+ .filter(r => r.trim() !== '') // bỏ dòng trống
2081
+ .map(row => row.split('\t') // tách theo cột
2082
+ .map(cell => cell.replace(/\r/g, '').replace(/\n/g, '\n')) // giữ xuống dòng trong ô
2083
+ );
2084
+ return rows;
2085
+ }
2086
+ export function parseExcelClipboardText(text) {
2087
+ const rows = [];
2088
+ let curRow = [];
2089
+ let curCell = '';
2090
+ let inQuotes = false;
2091
+ for (let i = 0; i < text.length; i++) {
2092
+ const ch = text[i];
2093
+ if (ch === '"') {
2094
+ // "" -> an escaped quote inside quoted field
2095
+ if (inQuotes && text[i + 1] === '"') {
2096
+ curCell += '"';
2097
+ i++; // skip next
2098
+ } else {
2099
+ inQuotes = !inQuotes; // open/close quote
2100
+ }
2101
+ continue;
2102
+ }
2103
+
2104
+ // tab as column separator (only if not inside quotes)
2105
+ if (ch === '\t' && !inQuotes) {
2106
+ curRow.push(curCell);
2107
+ curCell = '';
2108
+ continue;
2109
+ }
2110
+
2111
+ // newline as row separator (handle \r\n and lone \r or \n), only outside quotes
2112
+ if ((ch === '\r' || ch === '\n') && !inQuotes) {
2113
+ // handle CRLF
2114
+ if (ch === '\r' && text[i + 1] === '\n') i++;
2115
+ curRow.push(curCell);
2116
+ curCell = '';
2117
+ rows.push(curRow);
2118
+ curRow = [];
2119
+ continue;
2120
+ }
2121
+
2122
+ // normal character
2123
+ curCell += ch;
2124
+ }
2125
+
2126
+ // push last cell/row (if any)
2127
+ // avoid adding one spurious empty row when text ends with newline (we already pushed that row)
2128
+ if (curCell !== '' || curRow.length > 0) {
2129
+ curRow.push(curCell);
2130
+ rows.push(curRow);
2131
+ }
2132
+
2133
+ // if the whole input was empty, return []
2134
+ if (rows.length === 1 && rows[0].length === 1 && rows[0][0] === '' && text.trim() === '') {
2135
+ return [];
2136
+ }
2137
+ return rows;
2138
+ }
2139
+ export function parseClipboardEvent(e) {
2140
+ const dataTransfer = e.clipboardData ?? e.nativeEvent?.clipboardData;
2141
+ if (!dataTransfer) return [];
2142
+
2143
+ // 1) try HTML (better fidelity for Excel)
2144
+ const html = dataTransfer.getData?.('text/html');
2145
+ if (html) {
2146
+ try {
2147
+ const doc = new DOMParser().parseFromString(html, 'text/html');
2148
+ const table = doc.querySelector('table');
2149
+ if (table) {
2150
+ const result = [];
2151
+ for (const tr of Array.from(table.rows)) {
2152
+ const row = [];
2153
+ for (const cell of Array.from(tr.cells)) {
2154
+ // innerText preserves newlines from <br>
2155
+ row.push(cell.innerText ?? '');
2156
+ }
2157
+ result.push(row);
2158
+ }
2159
+ if (result.length) return result;
2160
+ }
2161
+ } catch {
2162
+ // fallback to text parsing
2163
+ }
2164
+ }
2165
+
2166
+ // 2) fallback: parse plain text (TSV with quoted fields)
2167
+ const text = dataTransfer.getData?.('text/plain') ?? '';
2168
+ return parseExcelClipboardText(text);
2169
+ }
2170
+ export function arraysEqualIgnoreOrderFast(a, b) {
2171
+ if (a.length !== b.length) return false;
2172
+ const count = Object.create(null);
2173
+ for (let i = 0; i < a.length; i++) {
2174
+ const key = a[i];
2175
+ count[key] = (count[key] || 0) + 1;
2176
+ }
2177
+ for (let i = 0; i < b.length; i++) {
2178
+ const key = b[i];
2179
+ if (!count[key]) return false;
2180
+ count[key]--;
2181
+ if (count[key] === 0) delete count[key];
2182
+ }
2183
+ return Object.keys(count).length === 0;
2184
+ }
2185
+ export function filterByIds(a, b) {
2186
+ const idSet = new Set(a);
2187
+ return b.filter(item => idSet.has(item.id));
2188
+ }
2189
+ export function excludeItems(arrayA, arrayB) {
2190
+ const idsInB = new Set(arrayB.map(item => item.id));
2191
+
2192
+ // Lọc A, chỉ giữ lại phần tử không có trong B
2193
+ return arrayA.filter(item => !idsInB.has(item.id));
2194
+ }
2195
+ export function getAllChildren(row) {
2196
+ const children = row.subRows ?? [];
2197
+ return children.reduce((acc, child) => {
2198
+ return acc.concat(child, getAllChildren(child));
2199
+ }, []);
2200
+ }
2201
+
2202
+ // export function toggleSelectAllChildren(row: any) {
2203
+ // const children = row.subRows ?? [];
2204
+
2205
+ // return children.reduce((acc: any, child: any) => {
2206
+ // return acc.concat(child, getAllChildren(child));
2207
+ // }, []);
2208
+ // }
2209
+
2210
+ export function toggleRowAndChildren(row, isSelected) {
2211
+ // Toggle chính row hiện tại
2212
+ row.toggleSelected(isSelected);
2213
+
2214
+ // Nếu có subRows thì gọi đệ quy
2215
+ if (row.subRows && row.subRows.length > 0) {
2216
+ row.subRows.forEach(subRow => toggleRowAndChildren(subRow, isSelected));
2217
+ }
2218
+ }
2219
+ export function countUnselectedChildren(row) {
2220
+ const parent = row.getParentRow();
2221
+ if (!parent) return 0; // Không có cha thì return 0
2222
+
2223
+ const unselectedCount = parent.subRows.filter(child => !child.getIsSelected()).length;
2224
+ return unselectedCount;
2225
+ }
2226
+ export function removeDuplicatesByKey(arr, key = 'id') {
2227
+ const map = new Map();
2228
+ for (const item of arr) {
2229
+ if (!map.has(item[key])) {
2230
+ map.set(item[key], item);
2231
+ }
2232
+ }
2233
+ return Array.from(map.values());
2234
+ }
2235
+ export const getTableHeight = (height, minHeight) => {
2236
+ if (height && !minHeight) {
2237
+ return height;
2238
+ }
2239
+ if (minHeight && !height) {
2240
+ return minHeight;
2241
+ }
2242
+ if (minHeight && height) {
2243
+ return Math.max(minHeight, height);
2244
+ // if (height > minHeight) {
2245
+ // return height
2246
+ // }
2247
+
2248
+ // if (minHeight > height) {
2249
+ // return minHeight
2250
+ // }
2251
+ }
2252
+ };
2253
+ export const convertFlatColumn1 = array => {
2254
+ const tmp = [...array];
2255
+ let result = [];
2256
+ tmp.forEach(item => {
2257
+ if (item.children) {
2258
+ result = result.concat(convertFlatColumn1(item.children));
2259
+ } else {
2260
+ result.push(item);
2261
+ }
2262
+ });
2263
+ return result;
2264
+ };
2265
+ export const updateColumnsByGroup = (columns, columnsGroup) => {
2266
+ return columns.map(column => {
2267
+ const newColumn = {
2268
+ ...column
2269
+ };
2270
+ let hasVisibleChild = false;
2271
+ if (!column.field) {
2272
+ return column;
2273
+ }
2274
+ if (newColumn.children) {
2275
+ newColumn.children = updateColumnsByGroup(newColumn.children, columnsGroup);
2276
+ hasVisibleChild = newColumn.children.some(child => child.visible !== false);
2277
+ }
2278
+
2279
+ // Map previous behaviour (hidden = true when field in columnsGroup)
2280
+ // to the new `visible` property: visible = !hidden
2281
+ newColumn.visible = !(newColumn.field && columnsGroup.includes(newColumn.field));
2282
+
2283
+ // For parent columns, visibility depends on whether any child is visible
2284
+ if (newColumn.children && newColumn.children.length > 0) {
2285
+ newColumn.visible = !!hasVisibleChild;
2286
+ }
2287
+ return newColumn;
2288
+ });
2289
+ };
2290
+ export const removeColumns = (columns, groupColumns) => {
2291
+ const ttt = [...columns];
2292
+ return ttt.filter(column => !groupColumns.includes(column.field)).map(column => {
2293
+ const newCol = {
2294
+ ...column
2295
+ };
2296
+ if (newCol?.children && newCol?.children.length > 0) {
2297
+ newCol.children = removeColumns(newCol.children, groupColumns);
2298
+ }
2299
+ return newCol;
2300
+ });
2301
+ };
2302
+ export const fixColumnsLeft = (columns, fixedFields) => {
2303
+ return columns.map(col => {
2304
+ const isFixed = col.field && fixedFields.includes(col.field);
2305
+ const newCol = {
2306
+ ...col,
2307
+ ...(isFixed && {
2308
+ fixed: 'left'
2309
+ })
2310
+ };
2311
+ if (col.children?.length) {
2312
+ // @ts-ignore
2313
+ newCol.children = fixColumnsLeft(col.children, fixedFields);
2314
+ }
2315
+ return newCol;
2316
+ });
2317
+ };
2318
+ const SPECIAL_FIELDS = ['selection_column', '#'];
2319
+ export function sortColumnsByField(columns, priorityFields) {
2320
+ // xử lý children trước
2321
+ const normalized = columns.map(col => ({
2322
+ ...col,
2323
+ ...(col.children && {
2324
+ children: sortColumnsByField(col.children, priorityFields)
2325
+ })
2326
+ }));
2327
+ const specialFixedLeft = [];
2328
+ const priority = [];
2329
+ const rest = [];
2330
+ for (const col of normalized) {
2331
+ if (col.fixed === 'left' && col.field && SPECIAL_FIELDS.includes(col.field)) {
2332
+ specialFixedLeft.push(col);
2333
+ } else if (col.field && priorityFields.includes(col.field)) {
2334
+ priority.push(col);
2335
+ } else {
2336
+ rest.push(col);
2337
+ }
2338
+ }
2339
+ return [...specialFixedLeft, ...priority, ...rest];
2340
+ }