All files / src/stories EditableTableV2.stories.tsx

58.22% Statements 46/79
49.15% Branches 29/59
32.5% Functions 13/40
66.12% Lines 41/62

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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387                                      1x                                           1x                               1x 2x 55x 28x                   27x 9x                     18x                           1x                         1x 1x 1x 1x 1x           1x                                         5x                                                                     8x       8x     1x                                       12x                                                                     1x   1x 1x   1x   1x   1x                     17x     1x                     1x                                                           1x   1x   1x   1x   1x       1x                                                                                                                           1x             1x 1x 1x 1x  
import React, { useMemo, useState } from 'react';
 
import { Box, Button } from '@mui/material';
import { StoryFn } from '@storybook/react';
import { userEvent, within } from 'storybook/test';
 
import { isMrtTable } from '../components/EditableTable/tableSettings';
import EditableTableV2, { EditableTableColumnV2 } from '../components/EditableTableV2';
import {
  EditableTableShowHideColumnsButtonV2,
  EditableTableToggleDensePaddingButtonV2,
  EditableTableToggleFiltersButtonV2,
  EditableTableToggleFullScreenButtonV2,
  EditableTableToggleGlobalFilterButtonV2,
} from '../components/EditableTableV2/ToolbarButtons';
import EditableTableExportButton from './EditableTableExportButton';
 
export default { title: 'Editable Table V2', component: EditableTableV2 };
 
export const WithOversizedPinnedContent: StoryFn = () => (
  <EditableTableV2
    clearAllFiltersLabel='Clear'
    enableColumnPinning
    enablePagination={false}
    columns={[
      { id: 'leftA', header: 'Left A', accessorKey: 'leftA', size: 120 },
      { id: 'leftB', header: 'Left B', accessorKey: 'leftB', size: 120 },
      { id: 'center', header: 'Center', accessorKey: 'center', size: 700 },
      { id: 'rightA', header: 'Right A', accessorKey: 'rightA', size: 120 },
      {
        id: 'rightB',
        header: 'Right B',
        accessorKey: 'rightB',
        size: 120,
        Cell: () => <div style={{ width: 240 }}>Oversized content</div>,
      },
    ]}
    data={[{ leftA: 'LongUnbrokenPinnedContent'.repeat(2), leftB: 'B', center: 'Center', rightA: 'D', rightB: 'E' }]}
    tableOptions={{ initialState: { columnPinning: { left: ['leftA', 'leftB'], right: ['rightA', 'rightB'] } } }}
  />
);
WithOversizedPinnedContent.tags = ['no-screenshot'];
 
type RowData = {
  id: string;
  name: string;
  middlename: string;
  lastname: string;
  occupation: string;
  available: string;
  date: string;
  pets: number;
  previousStudies?: string;
};
 
type Scenario = 'default' | 'filters' | 'clearAllFilters' | 'occupationFilter' | 'withoutPagination';
 
const createRows = (rowCount: number): RowData[] =>
  Array.from({ length: rowCount }, (_, index) => {
    if (index % 2 === 0) {
      return {
        id: String(index),
        name: `Constanza_${index}`,
        middlename: '',
        lastname: 'Uanini',
        occupation: 'Artist',
        date: '2023-02-03',
        pets: 5,
        available: 'yes',
      };
    } else if (index % 3 === 0) {
      return {
        id: String(index),
        name: `Carlos_${index}`,
        middlename: '--',
        lastname: 'Thurber',
        occupation: 'Freelancer',
        available: 'no',
        date: '2023-04-12',
        pets: 10,
      };
    } else {
      return {
        id: String(index),
        name: `Jane${index}`,
        middlename: 'John',
        lastname: 'Doe',
        occupation: 'Business analyst',
        available: 'yes',
        date: '2023-04-27',
        pets: 12,
        previousStudies: 'Natural Sciences, Social Sciences',
      };
    }
  });
 
const EditableTableWithStateV2 = ({
  rowCount = 50,
  scenario = 'default',
  showTopToolbar = false,
  columnDragging = false,
  pinnedColumns = false,
}: {
  rowCount?: number;
  scenario?: Scenario;
  showTopToolbar?: boolean;
  columnDragging?: boolean;
  pinnedColumns?: boolean;
}) => {
  const [data, setData] = useState(() => createRows(rowCount));
  const filtered = scenario === 'filters' || scenario === 'clearAllFilters' || showTopToolbar;
  const withoutPagination = scenario === 'withoutPagination';
  const columns = useMemo<EditableTableColumnV2<RowData>[]>(() => {
    const onSave = (row: RowData, value: unknown, columnId: string) => {
      const nextValue = columnId === 'pets' ? parseInt(String(value), 10) : value;
      if (typeof nextValue !== 'number' || !isNaN(nextValue)) {
        setData((previous) => previous.map((item) => (item.id === row.id ? { ...item, [columnId]: nextValue } : item)));
      }
    };
    const occupations = ['Artist', 'Freelancer', 'Business analyst', 'Developer', 'Designer'];
    const allColumns: EditableTableColumnV2<RowData>[] = [
      {
        id: 'name',
        header: 'Name',
        accessorKey: 'name',
        size: 150,
        filterVariant: filtered ? 'text' : undefined,
        editConfig: { onSave },
      },
      { id: 'middlename', header: 'Middle Name', accessorKey: 'middlename', size: 150, editConfig: { onSave } },
      { id: 'lastname', header: 'Last Name', accessorKey: 'lastname', size: 150, editConfig: { onSave } },
      {
        id: 'occupation',
        header: 'Occupation',
        accessorKey: 'occupation',
        size: 180,
        filterVariant: filtered || scenario === 'occupationFilter' ? 'select' : undefined,
        filterSelectOptions: occupations,
        editConfig: {
          editVariant: 'select',
          selectOptions: (withoutPagination ? occupations.slice(0, 3) : occupations).map((value) => ({
            label: value,
            value,
          })),
          onSave,
        },
      },
      {
        id: 'available',
        header: 'Available',
        accessorKey: 'available',
        size: 120,
        filterVariant: filtered ? 'select' : undefined,
        filterSelectOptions: ['yes', 'no'],
        editConfig: {
          editVariant: 'select',
          selectOptions: [
            { label: 'Yes', value: 'yes' },
            { label: 'No', value: 'no' },
          ],
          onSave,
        },
      },
      { id: 'date', header: 'Date', accessorKey: 'date', size: 130, editConfig: { onSave } },
      { id: 'pets', header: 'Pets', accessorKey: 'pets', size: 100, editConfig: { onSave } },
      {
        id: 'previousStudies',
        header: 'Previous Studies',
        accessorKey: 'previousStudies',
        size: 200,
        editConfig: { onSave },
      },
    ];
    const columnIds =
      scenario === 'default'
        ? allColumns.map((column) => column.id)
        : withoutPagination
          ? ['name', 'lastname', 'occupation']
          : ['name', 'occupation', 'available'];
    return allColumns.filter((column) => columnIds.includes(column.id));
  }, [filtered, scenario, withoutPagination]);
 
  return (
    <EditableTableV2
      clearAllFiltersLabel={scenario === 'clearAllFilters' ? 'Clear All Filters' : 'Clear all filters'}
      columns={columns}
      data={data}
      enableEditing={scenario !== 'clearAllFilters'}
      enableSorting
      enablePagination={!withoutPagination}
      enableBottomToolbar={!withoutPagination}
      enableGlobalFilter={filtered || showTopToolbar}
      enableColumnDragging={columnDragging}
      enableColumnOrdering={columnDragging}
      showColumnsButton={showTopToolbar}
      showGlobalFilterButton={showTopToolbar}
      showColumnFiltersButton={filtered || scenario === 'occupationFilter'}
      showDensityButton={showTopToolbar}
      showFullScreenButton={showTopToolbar}
      renderToolbarInternalActions={
        showTopToolbar
          ? ({ table }) =>
              !isMrtTable(table) && (
                <>
                  <EditableTableExportButton
                    getRows={() => [
                      table.getVisibleLeafColumns().map((column) => column.columnDef.header),
                      ...table
                        .getPrePaginatedRowModel()
                        .rows.map((row) => row.getVisibleCells().map((cell) => cell.getValue())),
                    ]}
                  />
                  <EditableTableToggleGlobalFilterButtonV2 table={table} />
                  {(filtered || scenario === 'occupationFilter') && (
                    <EditableTableToggleFiltersButtonV2 table={table} />
                  )}
                  <EditableTableShowHideColumnsButtonV2 table={table} />
                  <EditableTableToggleDensePaddingButtonV2 table={table} />
                  <EditableTableToggleFullScreenButtonV2 table={table} />
                </>
              )
          : undefined
      }
      enableColumnFilters={filtered || scenario === 'occupationFilter'}
      initialSorting={scenario === 'default' && !pinnedColumns ? [{ id: 'name', desc: false }] : undefined}
      enableColumnPinning={pinnedColumns}
      sx={pinnedColumns ? { maxWidth: 900 } : undefined}
      tableOptions={
        pinnedColumns
          ? { initialState: { columnPinning: { left: ['name', 'middlename'], right: ['pets', 'previousStudies'] } } }
          : undefined
      }
      onClearAllFilters={scenario === 'clearAllFilters' ? () => console.log('All filters cleared') : undefined}
    />
  );
};
 
const Template: StoryFn<{ rowCount: number }> = (args) => <EditableTableWithStateV2 {...args} />;
 
export const Default = Template.bind({});
Default.args = { rowCount: 50 };
 
export const WithTopToolbar = () => <EditableTableWithStateV2 rowCount={50} showTopToolbar />;
 
export const WithColumnDragging = () => <EditableTableWithStateV2 rowCount={10} showTopToolbar columnDragging />;
 
export const WithCustomToolbarOrder = () => (
  <EditableTableV2
    clearAllFiltersLabel='Clear filters'
    columns={[
      { id: 'name', header: 'Name', accessorKey: 'name', filterVariant: 'text' },
      { id: 'occupation', header: 'Occupation', accessorKey: 'occupation', filterVariant: 'text' },
    ]}
    data={createRows(5)}
    enableGlobalFilter
    enableColumnFilters
    renderToolbarInternalActions={({ table }) =>
      !isMrtTable(table) && (
        <Box display='flex' alignItems='center'>
          <EditableTableToggleFiltersButtonV2 table={table} />
          <Button onClick={() => table.resetColumnFilters()}>Reset filters</Button>
          <EditableTableShowHideColumnsButtonV2 table={table} />
          <EditableTableToggleDensePaddingButtonV2 table={table} />
          <EditableTableToggleFullScreenButtonV2 table={table} />
          <EditableTableToggleGlobalFilterButtonV2 table={table} />
        </Box>
      )
    }
  />
);
 
export const WithMrtProps = () => (
  <EditableTableV2
    clearAllFiltersLabel='Clear filters'
    columns={[
      { id: 'name', header: 'Name', accessorKey: 'name' },
      { id: 'occupation', header: 'Occupation', accessorKey: 'occupation' },
      { id: 'available', header: 'Available', accessorKey: 'available' },
    ]}
    data={createRows(5)}
    enableGlobalFilter
    positionGlobalFilter='right'
    enableShowAllColumnsMenuItem={false}
    enableColumnPinning
    renderTopToolbarCustomActions={({ table }) => (
      <Button variant='outlined' onClick={() => table.setGlobalFilter('')}>
        Reset view ({table.getRowModel().rows.length})
      </Button>
    )}
    muiTableHeadCellProps={({ column }) => ({
      title: column.columnDef.header as string,
      sx: { padding: '8px', height: '56px', '& .Mui-TableHeadCell-Content-Wrapper': { whiteSpace: 'normal' } },
    })}
    muiTableBodyCellProps={({ cell }) => ({
      title: String(cell.getValue()),
      sx: { padding: '12px', '&[data-pinned="true"]': { filter: 'brightness(0.97)' } },
    })}
    tableOptions={{ initialState: { columnPinning: { left: ['name'], right: [] } } }}
  />
);
 
export const WithFilters = () => <EditableTableWithStateV2 scenario='filters' />;
 
export const WithPinnedColumns = () => <EditableTableWithStateV2 rowCount={50} pinnedColumns />;
 
export const WithClearAllFilters = () => <EditableTableWithStateV2 scenario='clearAllFilters' />;
 
export const WithOccupationFilter = () => <EditableTableWithStateV2 scenario='occupationFilter' />;
 
export const WithoutPagination = () => <EditableTableWithStateV2 scenario='withoutPagination' rowCount={20} />;
 
type Item = { id: string; name: string; status: string; target: number };
 
export const Editable = () => {
  const [data, setData] = useState<Item[]>(
    Array.from({ length: 30 }, (_, index) => ({
      id: String(index),
      name: `Indicator ${index}`,
      status: 'Active',
      target: index,
    }))
  );
  const columns = useMemo<EditableTableColumnV2<Item>[]>(() => {
    const onSave = (row: Item, value: unknown, id: string) =>
      setData((previous) =>
        previous.map((item) => (item.id === row.id ? { ...item, [id]: id === 'target' ? Number(value) : value } : item))
      );
    return [
      { id: 'name', header: 'Indicator', accessorKey: 'name', filterVariant: 'text', editConfig: { onSave } },
      {
        id: 'status',
        header: 'Status',
        accessorKey: 'status',
        filterVariant: 'select',
        filterSelectOptions: ['Active', 'Complete'],
        editConfig: {
          onSave,
          editVariant: 'select',
          selectOptions: [
            { label: 'Active', value: 'Active' },
            { label: 'Complete', value: 'Complete' },
          ],
        },
      },
      {
        id: 'target',
        header: 'Target',
        accessorKey: 'target',
        filterVariant: 'range',
        Cell: ({ cell }) => <strong>{Number(cell.getValue()).toFixed(2)}</strong>,
        editConfig: { onSave },
      },
    ];
  }, []);
  return (
    <EditableTableV2
      columns={columns}
      data={data}
      clearAllFiltersLabel='Clear all filters'
      enableEditing
      enableGlobalFilter
      enableColumnFilters
      showColumnFiltersButton
      enableColumnOrdering
      enableColumnPinning
      stickyFilters
      storageKey='editable-table-v2-story'
      tableOptions={{
        getRowId: (row) => row.id,
        initialState: { columnPinning: { left: ['name'], right: ['target'] } },
      }}
    />
  );
};
 
const openFilters = async ({ canvasElement }: { canvasElement: HTMLElement }) => {
  const button = within(canvasElement).getByRole('button', { name: 'Show/Hide filters' });
  await userEvent.click(button);
  await userEvent.unhover(button);
  button.blur();
};
 
WithFilters.play = openFilters;
WithClearAllFilters.play = openFilters;
WithOccupationFilter.play = openFilters;
Editable.play = openFilters;