# All files / src/components data-table.tsx

100% Statements 27/27
84.21% Branches 16/19
100% Functions 10/10
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301

    8x

    8x

    21x

    63x

    1x

    8x

    8x

    300x
    300x

    300x

    8x

    100x
    100x

    300x

    8x

    8x

    21x

    21x

    21x

    21x

    21x

    21x

    21x

    210x
    210x

    8x

    12x
     // Following exception used because of false positives on linting rule:
    // https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md#false-positives-sfc
    /* eslint-disable react/no-unused-prop-types */
    import {
      memo,
      useEffect,
      type ReactNode,
      type HTMLAttributes,
      useMemo,
      type ReactElement,
      useId,
    } from 'react';
    import cn from 'classnames';

    import Loader from './loader';

    import useDataCheckboxes from '../hooks/useDataCheckboxes';

    import withDataLoader, { type WrapperProps } from './data-loader';

    import '../styles/components/data-table.scss';

    type BasicDatum = Record<string, unknown>;

    export type CommonColumn<Datum> = {
      label?: ReactNode;
      name: string;
      render: (datum: Datum) => ReactNode;
      tooltip?: ReactNode;
      width?: string;
    };

    // Either a column is sortable
    export interface SortableColumn<Datum> extends CommonColumn<Datum> {
      sortable?: true;
      sorted?: 'ascend' | 'descend';
    }
    // Or it's not sortable
    export interface NonSortableColumn<Datum> extends CommonColumn<Datum> {
      sortable?: false | undefined;
      sorted?: never;
    }

    type SharedProps<Datum> = {
      /**
       * An array of objects which specifies attributes about each column of your
       * data. Each object has label, name and render attributes.
       */
      columns: Array<SortableColumn<Datum> | NonSortableColumn<Datum>>;
      /**
       * Table fixed layout
       */
      // Note sure why it doesn't detect it as used...
      fixedLayout?: boolean;
    };

    const BLOCK = 'data-table';

    type HeadProps<Datum> = {
      /**
       * Optional event handler called when a sortable column header gets clicked
       * Make sure that it doesn't change unecessarily by wrapping it in useCallback
       */
      onHeaderClick?: (columnName: SortableColumn<Datum>['name']) => void;
    };

    const DataTableHead = <Datum extends BasicDatum>({
      columns,
      onHeaderClick,
      checkbox,
    }: HeadProps<Datum> & SharedProps<Datum> & { checkbox: ReactNode }) => (
      <thead>
        <tr>
          {checkbox && (
            <th className={`${BLOCK}__header-cell--checkbox`}>
              {/* needs a relative wrapper, because the header is sticky */}
              <div className="checkbox-cell">{checkbox}</div>
            </th>
          )}
          {columns.map(({ sorted, name, label, sortable, width }) => (
            <th
              key={name}
              className={cn({
                [`${BLOCK}__header-cell--sortable`]: sortable,
                [`${BLOCK}__header-cell--${sorted || 'ascend'}`]:
                  sortable && sorted,
              })}
              onClick={sortable ? () => onHeaderClick?.(name) : undefined}
              style={width ? { width } : undefined}
              data-column-name={name}
            >
              {typeof label === 'function' ? (label as () => ReactNode)() : label}
            </th>
          ))}
        </tr>
      </thead>
    );
    const MemoizedDataTableHead = memo(DataTableHead) as typeof DataTableHead;

    type CellProp<Datum extends BasicDatum> = {
      column: CommonColumn<Datum>;
      datum: Datum;
      loading?: boolean;
      fixedLayout?: boolean;
      firstColumn: boolean;
    };

    const Cell = <Datum extends BasicDatum>({
      column,
      datum,
      loading,
      fixedLayout,
      firstColumn,
    }: CellProp<Datum>) => {
      let rendered: ReactNode;
      try {
        rendered = column.render(datum);
      } catch (error) {
        /**
         * We get here only if the renderer fails. If the renderer returns null of
         * undefined because of a lack of data, then it will no throw and will not
         * display the loader at all
         */
        /* istanbul ignore next */
        if (!loading) {
          throw error;
        } else {
          rendered = firstColumn && <Loader />;
        }
      }

      return (
        <td className={fixedLayout ? `${BLOCK}__cell--ellipsis` : undefined}>
          {rendered}
        </td>
      );
    };

    type RowProps<Datum extends BasicDatum> = {
      /**
       * The data to be displayed
       */
      datum: Datum;
      loading?: boolean;
      id: string;
      selectable: boolean;
    };

    const DataTableRow = <Datum extends BasicDatum>({
      datum,
      loading,
      columns,
      selectable,
      id,
      fixedLayout,
      firstColumn,
    }: RowProps<Datum> & SharedProps<Datum> & { firstColumn: boolean }) => {
      const labelId = useId();
      return (
        <tr>
          {selectable && (
            <td className="checkbox-cell">
              <input type="checkbox" data-id={id} id={labelId} />
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label
                htmlFor={labelId}
                aria-label={id}
                title="click to select, shift+click for multiple selection"
              />
            </td>
          )}
          {columns.map((column) => (
            <Cell
              key={`${id}-${column.name}`}
              column={column}
              datum={datum}
              loading={loading}
              fixedLayout={fixedLayout}
              firstColumn={firstColumn}
            />
          ))}
        </tr>
      );
    };
    const MemoizedDataTableRow = memo(DataTableRow) as typeof DataTableRow;

    type RowsProps<Datum> = {
      /**
       * The data to be displayed
       */
      data: Datum[];
      loading?: boolean;
      /**
       * A function that returns a unique ID for each of the data objects.
       * Same function signature as a map function.
       */
      getIdKey: (datum: Datum, index: number, data: Datum[]) => string;
      /**
       * A callback that is called whenever a user selects or unselects a row.
       */
      onSelectionChange?: (event: MouseEvent | KeyboardEvent) => void;
    };

    type TableProps = {
      /**
       * Display density of the table (default is 'normal')
       */
      density?: 'normal' | 'compact';
      /**
       * Choose to activate optimised rendering (default: false). Do not use if
       *  - height of row is really tall or variable (scroll bar will jump)
       *  - column width changes (should be fine with "fixedLayout")
       */
      optimisedRendering?: boolean;
    };

    export interface Props<Datum>
      extends
        TableProps,
        RowsProps<Datum>,
        // Omit because 'selectable' is not passed from the top, it is deduced later
        Omit<HeadProps<Datum>, 'selectable'>,
        SharedProps<Datum> {}

    export const DataTable = <Datum extends BasicDatum>({
      data,
      loading,
      columns,
      getIdKey,
      onHeaderClick,
      onSelectionChange,
      density = 'normal',
      fixedLayout,
      optimisedRendering,
      className,
      ...props
    }: Props<Datum> & HTMLAttributes<HTMLTableElement>): ReactElement => {
      const labelId = useId();

      const { selectAllRef, checkboxContainerRef, checkSelectAllSync } =
        useDataCheckboxes(onSelectionChange);

      // We need to update the state of the select-all checkbox when data changes
      useEffect(checkSelectAllSync, [data, checkSelectAllSync]);

      const selectable = Boolean(onSelectionChange);

      const selectAllCheckbox = useMemo(
        () =>
          selectable && (
            <>
              <input type="checkbox" id={labelId} ref={selectAllRef} />
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label
                htmlFor={labelId}
                aria-label="Selection control for all visible items"
              />
            </>
          ),
        [labelId, selectAllRef, selectable]
      );

      return (
        <table
          className={cn(className, BLOCK, {
            [`${BLOCK}--compact`]: density === 'compact',
            [`${BLOCK}--fixed`]: fixedLayout,
            [`${BLOCK}--optimised-rendering`]: optimisedRendering,
          })}
          {...props}
        >
          <MemoizedDataTableHead<Datum>
            columns={columns}
            onHeaderClick={onHeaderClick}
            checkbox={selectAllCheckbox}
          />
          <tbody ref={checkboxContainerRef} translate="no">
            {data.map((datum, index) => {
              const id = getIdKey(datum, index, data);
              return (
                <MemoizedDataTableRow<Datum>
                  key={id}
                  datum={datum}
                  loading={loading}
                  id={id}
                  selectable={selectable}
                  firstColumn={index === 0}
                  columns={columns}
                  fixedLayout={fixedLayout}
                />
              );
            })}
          </tbody>
        </table>
      );
    };

    export const DataTableWithLoader = <Datum extends BasicDatum>(
      props: WrapperProps<Datum> & Props<Datum> & HTMLAttributes<HTMLTableElement>
    ) => <>{withDataLoader<Datum, typeof props>(DataTable)(props)}</>;