useWidthColumns.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
  2. import * as React from 'react';
  3. function parseColWidth(totalWidth) {
  4. var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  5. if (typeof width === 'number') {
  6. return width;
  7. }
  8. if (width.endsWith('%')) {
  9. return totalWidth * parseFloat(width) / 100;
  10. }
  11. return null;
  12. }
  13. /**
  14. * Fill all column with width
  15. */
  16. export default function useWidthColumns(flattenColumns, scrollWidth, clientWidth) {
  17. return React.useMemo(function () {
  18. // Fill width if needed
  19. if (scrollWidth && scrollWidth > 0) {
  20. var totalWidth = 0;
  21. var missWidthCount = 0;
  22. // collect not given width column
  23. flattenColumns.forEach(function (col) {
  24. var colWidth = parseColWidth(scrollWidth, col.width);
  25. if (colWidth) {
  26. totalWidth += colWidth;
  27. } else {
  28. missWidthCount += 1;
  29. }
  30. });
  31. // Fill width
  32. var maxFitWidth = Math.max(scrollWidth, clientWidth);
  33. var restWidth = Math.max(maxFitWidth - totalWidth, missWidthCount);
  34. var restCount = missWidthCount;
  35. var avgWidth = restWidth / missWidthCount;
  36. var realTotal = 0;
  37. var filledColumns = flattenColumns.map(function (col) {
  38. var clone = _objectSpread({}, col);
  39. var colWidth = parseColWidth(scrollWidth, clone.width);
  40. if (colWidth) {
  41. clone.width = colWidth;
  42. } else {
  43. var colAvgWidth = Math.floor(avgWidth);
  44. clone.width = restCount === 1 ? restWidth : colAvgWidth;
  45. restWidth -= colAvgWidth;
  46. restCount -= 1;
  47. }
  48. realTotal += clone.width;
  49. return clone;
  50. });
  51. // If realTotal is less than clientWidth,
  52. // We need extend column width
  53. if (realTotal < maxFitWidth) {
  54. var scale = maxFitWidth / realTotal;
  55. restWidth = maxFitWidth;
  56. filledColumns.forEach(function (col, index) {
  57. var colWidth = Math.floor(col.width * scale);
  58. col.width = index === filledColumns.length - 1 ? restWidth : colWidth;
  59. restWidth -= colWidth;
  60. });
  61. }
  62. return [filledColumns, Math.max(realTotal, maxFitWidth)];
  63. }
  64. return [flattenColumns, scrollWidth];
  65. }, [flattenColumns, scrollWidth, clientWidth]);
  66. }