utils.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /* eslint-disable max-len */
  2. /* eslint-disable no-param-reassign */
  3. /* eslint-disable eqeqeq */
  4. import {
  5. isEqualWith,
  6. get,
  7. filter,
  8. find,
  9. map,
  10. clone as lodashClone,
  11. each,
  12. findIndex,
  13. some,
  14. includes,
  15. toString,
  16. isFunction
  17. } from 'lodash';
  18. import { strings, numbers } from './constants';
  19. import isNullOrUndefined from '../utils/isNullOrUndefined';
  20. import Logger from '../utils/Logger';
  21. export function equalWith(value: any, other: any, customizer?: (...args: any[]) => boolean) {
  22. return isEqualWith(value, other, (objVal, othVal, ...rest) => {
  23. if (typeof objVal === 'function' && typeof othVal === 'function') {
  24. return toString(objVal) === toString(othVal);
  25. }
  26. if (typeof customizer === 'function') {
  27. return customizer(objVal, othVal, ...rest);
  28. }
  29. // If customizer returns undefined, comparisons are handled by isEqual instead
  30. return undefined;
  31. });
  32. }
  33. export function getColumnKey(column: any, keyPropNames: any[]): any {
  34. keyPropNames = Array.isArray(keyPropNames) ? keyPropNames : ['key', 'dataIndex'];
  35. let key = null;
  36. each(keyPropNames, propName => {
  37. key = get(column, propName);
  38. if (key != null) {
  39. return false;
  40. }
  41. return undefined;
  42. });
  43. return key;
  44. }
  45. /**
  46. *
  47. * @param {Array<number>} arr
  48. * @param {number} [beginIndex] begin index, included
  49. * @param {number} [endIndex] end index, not included
  50. * @returns {number}
  51. */
  52. export function arrayAdd(arr: any[] = [], beginIndex = 0, endIndex?: number) {
  53. beginIndex = beginIndex < 0 || typeof beginIndex !== 'number' ? 0 : beginIndex;
  54. endIndex = endIndex > arr.length || typeof endIndex !== 'number' ? arr.length : endIndex;
  55. let result = 0;
  56. each(arr, (value, index) => {
  57. if (index >= beginIndex && index < endIndex) {
  58. result += typeof value === 'number' && !isNaN(value) ? value : 0;
  59. }
  60. });
  61. return result;
  62. }
  63. export function isLastLeftFixed(columns: Record<string, any>[], column: Record<string, any>, checkKeys = ['key']) {
  64. const leftFixedColumns = filter(columns, col => col.fixed === true || col.fixed === 'left');
  65. const index = findIndex(leftFixedColumns, col =>
  66. checkKeys.every(key => col[key] != null && col[key] === column[key])
  67. );
  68. return leftFixedColumns.length > 0 && index === leftFixedColumns.length - 1;
  69. }
  70. export function isFirstFixedRight(columns: Record<string, any>[], column: Record<string, any>, checkKeys = ['key']) {
  71. const rightFixedColumns = filter(columns, col => col.fixed === 'right');
  72. const index = findIndex(rightFixedColumns, col =>
  73. checkKeys.every(key => col[key] != null && col[key] === column[key])
  74. );
  75. return rightFixedColumns.length > 0 && index === 0;
  76. }
  77. export function isAnyFixed(columns: Record<string, any>[], fixedSet = ['left', true, 'right']) {
  78. if (typeof fixedSet === 'string' || typeof fixedSet === 'boolean') {
  79. fixedSet = [fixedSet];
  80. }
  81. return fixedSet.length > 0 && some(columns, col => fixedSet.includes(col.fixed));
  82. }
  83. export function isAnyFixedRight(columns: Record<string, any>[]) {
  84. return some(columns, col => col.fixed === 'right');
  85. }
  86. export function isFixedLeft(column: Record<string, any>) {
  87. return ['left', true].includes(get(column, 'fixed'));
  88. }
  89. export function isFixedRight(column: Record<string, any>) {
  90. return ['right'].includes(get(column, 'fixed'));
  91. }
  92. export function isFixed(column: Record<string, any>) {
  93. return isFixedLeft(column) || isFixedRight(column);
  94. }
  95. export function isInnerColumnKey(key: string | number) {
  96. return [
  97. strings.DEFAULT_KEY_COLUMN_EXPAND,
  98. strings.DEFAULT_KEY_COLUMN_SCROLLBAR,
  99. strings.DEFAULT_KEY_COLUMN_SELECTION,
  100. ].includes(key as any);
  101. }
  102. export function isExpandedColumn(column: Record<string, any>) {
  103. return get(column, 'key') === strings.DEFAULT_KEY_COLUMN_EXPAND;
  104. }
  105. export function isScrollbarColumn(column: Record<string, any>) {
  106. return get(column, 'key') === strings.DEFAULT_KEY_COLUMN_SCROLLBAR;
  107. }
  108. export function isSelectionColumn(column: Record<string, any>) {
  109. return get(column, 'key') === strings.DEFAULT_KEY_COLUMN_SELECTION;
  110. }
  111. export function filterColumns(columns: Record<string, any>[], ignoreKeys = [strings.DEFAULT_KEY_COLUMN_SCROLLBAR as string]) {
  112. return filter(columns, col => !ignoreKeys.includes(col.key));
  113. }
  114. /**
  115. * get width of scroll bar
  116. * @param {Array} columns
  117. * @returns {Number|undefined}
  118. */
  119. export function getScrollbarColumnWidth(columns: Record<string, any>[] = []) {
  120. const len = columns.length;
  121. if (len) {
  122. const lastColumn = columns[len - 1];
  123. if (get(lastColumn, 'key') === strings.DEFAULT_KEY_COLUMN_SCROLLBAR) {
  124. return get(lastColumn, 'width', 0);
  125. }
  126. }
  127. }
  128. export function getRecordKey(record: Record<string, any>, rowKey: string | number | ((record: any) => string | number)) {
  129. if (rowKey === undefined) {
  130. rowKey = 'key';
  131. }
  132. return typeof rowKey === 'function' ? rowKey(record) : get(record, rowKey);
  133. }
  134. /**
  135. * Determine whether the expandedRowKeys includes a key (rowKey will be added to expandedRowKeys when the expand button is clicked)
  136. * @param {*} expandedRowKeys
  137. * @param {*} key
  138. */
  139. export function isExpanded(expandedRowKeys: (string | number)[], key: string | number) {
  140. return key != null && includes(expandedRowKeys, key);
  141. }
  142. /**
  143. * Determine whether the selectedKeysSet includes the key
  144. * @param {Set} selectedRowKeysSet
  145. * @param {String} key
  146. */
  147. export function isSelected(selectedRowKeysSet: Set<string | number>, key: string | number) {
  148. return key !== null && selectedRowKeysSet.has(key);
  149. }
  150. /**
  151. * Whether the key is included in the disabledRowKeysSet
  152. * @param {Set} disabledRowKeysSet
  153. * @param {String} key
  154. */
  155. export function isDisabled(disabledRowKeysSet: Set<string | number>, key: string | number) {
  156. return key !== null && disabledRowKeysSet.has(key);
  157. }
  158. export function getRecord(data: any[], recordKey: string | number, rowKey: string | number | ((record: any) => string | number)) {
  159. if (rowKey === undefined) {
  160. rowKey = 'key';
  161. }
  162. return find(data, record => recordKey != null && recordKey !== '' && getRecordKey(record, rowKey) === recordKey);
  163. }
  164. export function getRecordChildren(record: Record<string, any>, childrenRecordName: string) {
  165. if (childrenRecordName === undefined) {
  166. childrenRecordName = 'children';
  167. }
  168. return get(record, childrenRecordName);
  169. }
  170. export function genExpandedRowKey(recordKey = '', suffix?: string) {
  171. if (suffix === undefined) {
  172. suffix = '__expanded_row';
  173. }
  174. return recordKey + suffix;
  175. }
  176. export function getDefaultVirtualizedRowConfig(size = '', sectionRow = false) {
  177. const config: { height?: number; minHeight?: number } = {};
  178. if (size === 'small') {
  179. config.height = sectionRow ?
  180. numbers.DEFAULT_VIRTUALIZED_SECTION_ROW_SMALL_HEIGHT :
  181. numbers.DEFAULT_VIRTUALIZED_ROW_SMALL_HEIGHT;
  182. config.minHeight = numbers.DEFAULT_VIRTUALIZED_ROW_SMALL_MIN_HEIGHT;
  183. } else if (size === 'middle') {
  184. config.height = sectionRow ?
  185. numbers.DEFAULT_VIRTUALIZED_SECTION_ROW_MIDDLE_HEIGHT :
  186. numbers.DEFAULT_VIRTUALIZED_ROW_MIDDLE_HEIGHT;
  187. config.minHeight = numbers.DEFAULT_VIRTUALIZED_ROW_MIDDLE_MIN_HEIGHT;
  188. } else {
  189. config.height = sectionRow ?
  190. numbers.DEFAULT_VIRTUALIZED_SECTION_ROW_HEIGHT :
  191. numbers.DEFAULT_VIRTUALIZED_ROW_HEIGHT;
  192. config.minHeight = numbers.DEFAULT_VIRTUALIZED_ROW_MIN_HEIGHT;
  193. }
  194. return config;
  195. }
  196. export function flattenColumns(cols: Record<string, any>[], childrenColumnName = 'children'): Record<string, any>[] {
  197. const list = [];
  198. if (Array.isArray(cols) && cols.length) {
  199. for (const col of cols) {
  200. if (Array.isArray(col[childrenColumnName]) && col[childrenColumnName].length) {
  201. list.push(...flattenColumns(col[childrenColumnName], childrenColumnName));
  202. } else {
  203. warnIfNoDataIndex(col);
  204. list.push(col);
  205. }
  206. }
  207. }
  208. return list;
  209. }
  210. export function assignColumnKeys(columns: Record<string, any>[], childrenColumnName = 'children', level = 0) {
  211. const sameLevelCols: Record<string, any>[] = [];
  212. each(columns, (column, index) => {
  213. if (column.key == null) {
  214. // if user give column a dataIndex, use it for backup
  215. const _index = column.dataIndex || index;
  216. column.key = `${level}-${_index}`;
  217. }
  218. if (Array.isArray(column[childrenColumnName]) && column[childrenColumnName].length) {
  219. sameLevelCols.push(...column[childrenColumnName]);
  220. }
  221. });
  222. if (sameLevelCols.length) {
  223. assignColumnKeys(sameLevelCols, childrenColumnName, level + 1);
  224. }
  225. return columns;
  226. }
  227. export function sliceColumnsByLevel(columns: any[], targetLevel = 0, childrenColumnName = 'children', currentLevel = 0) {
  228. const slicedColumns: any[] = [];
  229. if (Array.isArray(columns) && columns.length && currentLevel <= targetLevel) {
  230. columns.forEach(column => {
  231. const children = column[childrenColumnName];
  232. if (Array.isArray(children) && children.length && currentLevel < targetLevel) {
  233. slicedColumns.push(...sliceColumnsByLevel(children, targetLevel, childrenColumnName, currentLevel + 1));
  234. } else {
  235. slicedColumns.push(column);
  236. }
  237. });
  238. }
  239. return slicedColumns;
  240. }
  241. export function getColumnsByLevel(
  242. columns: Record<string, any>[],
  243. targetLevel = 0,
  244. targetColumns: Record<string, any>[] = [],
  245. currentLevel = 0,
  246. childrenColumnName = 'children'
  247. ) {
  248. if (Array.isArray(columns) && columns.length) {
  249. if (targetLevel === currentLevel) {
  250. targetColumns.push(...columns);
  251. } else {
  252. columns.forEach(column => {
  253. getColumnsByLevel(
  254. column[childrenColumnName],
  255. targetLevel,
  256. targetColumns,
  257. currentLevel + 1,
  258. childrenColumnName
  259. );
  260. });
  261. }
  262. }
  263. return targetColumns;
  264. }
  265. export function getAllLevelColumns(columns: Record<string, any>[], childrenColumnName = 'children') {
  266. const all = [];
  267. if (Array.isArray(columns) && columns.length) {
  268. all.push([...columns]);
  269. const sameLevelColumns: Record<string, any>[] = [];
  270. columns.forEach(column => {
  271. const children = column[childrenColumnName];
  272. if (Array.isArray(children) && children.length) {
  273. sameLevelColumns.push(...children);
  274. }
  275. });
  276. if (sameLevelColumns.length) {
  277. all.push(sameLevelColumns);
  278. }
  279. }
  280. return all;
  281. }
  282. export function getColumnByLevelIndex(columns: Record<string, any>[], index: number, level = 0, childrenColumnName = 'children') {
  283. const allLevelColumns = getAllLevelColumns(columns, childrenColumnName);
  284. return allLevelColumns[level][index];
  285. }
  286. export function findColumn(columns: Record<string, any>[], column: Record<string, any>, childrenColumnName = 'children') {
  287. let found: any;
  288. each(columns, item => {
  289. if (item && item.key != null && !found) {
  290. if (item.key === column.key) {
  291. found = item;
  292. }
  293. }
  294. if (item && Array.isArray(item[childrenColumnName]) && !found) {
  295. found = findColumn(item[childrenColumnName], column, childrenColumnName);
  296. }
  297. if (found) {
  298. return false;
  299. }
  300. return undefined;
  301. });
  302. return found;
  303. }
  304. export function expandBtnShouldInRow(props: ExpandBtnShouldInRowProps) {
  305. const { expandedRowRender, dataSource, hideExpandedColumn, childrenRecordName, rowExpandable } = props;
  306. const hasExpandedRowRender = typeof expandedRowRender === 'function';
  307. return (
  308. (hideExpandedColumn && hasExpandedRowRender) ||
  309. (!hasExpandedRowRender && dataSource.some(record => {
  310. const children = get(record, childrenRecordName);
  311. if ((Array.isArray(children) && children.length) || rowExpandable(record)) {
  312. return true;
  313. } else {
  314. return false;
  315. }
  316. }))
  317. );
  318. }
  319. export type ExpandBtnShouldInRowProps = {
  320. expandedRowRender: (record?: Record<string, any>, index?: number, expanded?: boolean) => any;
  321. dataSource: Record<string, any>[];
  322. hideExpandedColumn: boolean;
  323. childrenRecordName: string;
  324. rowExpandable: (record?: Record<string, any>) => boolean
  325. };
  326. /**
  327. * merge query
  328. * @param {*} query
  329. * @param {*} queries
  330. */
  331. export function mergeQueries(query: Record<string, any>, queries: Record<string, any>[] = []) {
  332. let _mergedQuery;
  333. const idx = queries.findIndex(item => {
  334. if (query.dataIndex === item.dataIndex) {
  335. _mergedQuery = { ...item, ...query };
  336. return true;
  337. }
  338. return false;
  339. });
  340. if (idx > -1) {
  341. queries.splice(idx, 1, _mergedQuery);
  342. } else {
  343. queries.push(_mergedQuery);
  344. }
  345. return [...queries];
  346. }
  347. /**
  348. * Replace the width of the newColumns column with the width of the column after resize
  349. * @param {Object[]} columns columns retain the column width after resize
  350. * @param {Object[]} newColumns
  351. */
  352. export function withResizeWidth(columns: Record<string, any>[], newColumns: Record<string, any>[]) {
  353. const _newColumns = { ...newColumns };
  354. for (const column of columns) {
  355. if (!isNullOrUndefined(column.width)) {
  356. const currentColumn = column.key;
  357. const columnIndex = findIndex(_newColumns, item => (item as any).key === currentColumn);
  358. if (columnIndex !== -1) {
  359. _newColumns[columnIndex].width = get(column, 'width');
  360. }
  361. }
  362. }
  363. return _newColumns;
  364. }
  365. /**
  366. * Pure function version of the same function in table foundation
  367. * This is not accessible in getDerivedStateFromProps, so fork one out
  368. */
  369. export function getAllDisabledRowKeys({ dataSource, getCheckboxProps, childrenRecordName, rowKey }: GetAllDisabledRowKeysProps): (string | number)[] {
  370. const disabledRowKeys = [];
  371. if (Array.isArray(dataSource) && dataSource.length && typeof getCheckboxProps === 'function') {
  372. for (const record of dataSource) {
  373. const props = getCheckboxProps(record);
  374. const recordKey = typeof rowKey === 'function' ? rowKey(record) : get(record, rowKey);
  375. if (props && props.disabled) {
  376. disabledRowKeys.push(recordKey);
  377. }
  378. const children = get(record, childrenRecordName);
  379. if (Array.isArray(children) && children.length) {
  380. const keys = getAllDisabledRowKeys({ dataSource: children, getCheckboxProps });
  381. disabledRowKeys.push(...keys);
  382. }
  383. }
  384. }
  385. return disabledRowKeys;
  386. }
  387. export interface GetAllDisabledRowKeysProps {
  388. dataSource: Record<string, any>[];
  389. getCheckboxProps: (record?: Record<string, any>) => any;
  390. childrenRecordName?: string;
  391. rowKey?: string | number | ((record: Record<string, any>) => string | number)
  392. }
  393. export function warnIfNoDataIndex(column: Record<string, any>) {
  394. if (typeof column === 'object' && column !== null) {
  395. const { filters, sorter, dataIndex, onFilter } = column;
  396. const logger = new Logger('[@douyinfe/semi-ui Table]');
  397. if ((Array.isArray(filters) || isFunction(onFilter) || isFunction(sorter)) && isNullOrUndefined(dataIndex) ) {
  398. logger.warn(`The column with sorter or filter must pass the 'dataIndex' prop`);
  399. }
  400. }
  401. }
  402. /**
  403. * Whether is tree table
  404. */
  405. export function isTreeTable({ dataSource, childrenRecordName = 'children' }: { dataSource: Record<string, any>; childrenRecordName?: string }) {
  406. let flag = false;
  407. if (Array.isArray(dataSource)) {
  408. for (const data of dataSource) {
  409. const children = get(data, childrenRecordName);
  410. if (Array.isArray(children) && children.length) {
  411. flag = true;
  412. break;
  413. }
  414. }
  415. }
  416. return flag;
  417. }
  418. export function getRTLAlign(align: typeof strings.ALIGNS[number], direction?: 'ltr' | 'rtl'): typeof strings.ALIGNS[number] {
  419. if (direction === 'rtl') {
  420. switch (align) {
  421. case 'left':
  422. return 'right';
  423. case 'right':
  424. return 'left';
  425. default:
  426. return align;
  427. }
  428. }
  429. return align;
  430. }