useQueryBasedColumnResize.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {useCallback, useMemo} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import type {Location} from 'history';
  4. import dropRightWhile from 'lodash/dropRightWhile';
  5. import {COL_WIDTH_UNDEFINED, GridColumnOrder} from 'sentry/components/gridEditable';
  6. import {decodeInteger, decodeList} from 'sentry/utils/queryString';
  7. interface Props<K extends string> {
  8. columns: GridColumnOrder<K>[];
  9. location: Location;
  10. paramName?: string;
  11. }
  12. export default function useQueryBasedColumnResize<K extends string>({
  13. columns,
  14. location,
  15. paramName = 'width',
  16. }: Props<K>) {
  17. const queryParam = location.query[paramName];
  18. const columnsWidthWidths = useMemo(() => {
  19. const widths = decodeList(queryParam);
  20. return columns.map((column, i) => {
  21. column.width = decodeInteger(widths[i], COL_WIDTH_UNDEFINED);
  22. return column;
  23. });
  24. }, [columns, queryParam]);
  25. const handleResizeColumn = useCallback(
  26. (columnIndex: number, resizedColumn: GridColumnOrder<K>) => {
  27. const widths = columns.map(
  28. (column, i) =>
  29. (i === columnIndex ? resizedColumn.width : column.width) ?? COL_WIDTH_UNDEFINED
  30. );
  31. browserHistory.push({
  32. pathname: location.pathname,
  33. query: {
  34. ...location.query,
  35. [paramName]: dropRightWhile(widths, width => width === COL_WIDTH_UNDEFINED),
  36. },
  37. });
  38. },
  39. [columns, location.pathname, location.query, paramName]
  40. );
  41. return {
  42. columns: columnsWidthWidths,
  43. handleResizeColumn,
  44. };
  45. }