All files / src/components ExportsPanel.tsx

85.21% Statements 98/115
66.66% Branches 4/6
16.66% Functions 1/6
85.21% Lines 98/115

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 1801x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x   1x   1x                                 1x 1x 19x   19x 10x 10x 10x     19x   19x 10x 10x 10x 10x 19x   19x       19x 19x       19x       19x 19x               19x     19x 19x               19x 19x 19x 19x 19x   19x   19x 19x 19x 19x 19x 19x 19x   19x         19x 19x 19x 19x 19x   19x     19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x     19x 19x 19x 19x 19x 19x   19x           19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x               19x   1x  
import { downloadBlob } from '@/helpers/exportResults';
import { i18n } from '@/helpers/i18n';
import { formatBytes, formatTimestamp } from '@/helpers/utils';
import {
  clearExports,
  deleteExport,
  type ExportRecord,
  getAllExports,
  IDB_EXPORTS_UPDATED,
} from '@/utils/idbCache';
import DeleteIcon from '@mui/icons-material/Delete';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { Box, IconButton, List, ListItem, ListItemText, Tooltip, Typography } from '@mui/material';
import { FC, useCallback, useEffect, useState } from 'react';
import styles from './ExportsPanel.module.scss';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
 
const logger = new Logger('ExportsPanel');
 
/**
 * ExportsPanel lists the `.xlsx` result exports cached in IndexedDB, newest
 * first, and lets the user re-download or delete each one (or clear them all).
 * The list live-refreshes on the `IDB_EXPORTS_UPDATED` event, so exports created
 * from the results context menu appear without reopening the drawer.
 *
 * @example
 * ```tsx
 * // Rendered inside the History drawer tab's "Exported data" accordion:
 * <ExportsPanel />
 * // Displays:
 * //   2 exports
 * //   chempal-export-acetone-2026-07-21-14-03-22.xlsx
 * //     Jul 21, 2:03 PM — 12 results · 18 KB      [download] [delete]
 * ```
 * @category Components
 * @source
 */
const ExportsPanel: FC = () => {
  const [exports, setExports] = useState<ExportRecord[]>([]);
 
  const loadExports = useCallback(async () => {
    try {
      setExports(await getAllExports());
    } catch (error) {
      logger.warn(`Failed to load exports: ${getErrorMessage(error)}`, { error });
    }
  }, []);
 
  useEffect(() => {
    void loadExports();
    const handler = () => void loadExports();
    window.addEventListener(IDB_EXPORTS_UPDATED, handler);
    return () => window.removeEventListener(IDB_EXPORTS_UPDATED, handler);
  }, [loadExports]);
 
  /**
   * Re-downloads a cached export from its stored Blob.
   * @param record - The export record to download.
   * @source
   */
  const handleDownload = (record: ExportRecord) => {
    downloadBlob(record.blob, record.filename);
  };
 
  /**
   * Deletes one cached export; the list refreshes via `IDB_EXPORTS_UPDATED`.
   * @param id - The export record id to delete.
   * @source
   */
  const handleDelete = async (id: string) => {
    try {
      await deleteExport(id);
    } catch (error) {
      logger.warn(`Failed to delete export: ${getErrorMessage(error)}`, { error });
    }
  };
 
  /**
   * Clears every cached export; the list refreshes via `IDB_EXPORTS_UPDATED`.
   * @source
   */
  const handleClear = async () => {
    try {
      await clearExports();
    } catch (error) {
      logger.warn(`Failed to clear exports: ${getErrorMessage(error)}`, { error });
    }
  };
 
  return (
    <Box className={styles['exports-panel']}>
      <Box className={styles['exports-panel__header']}>
        <Typography variant="caption" color="text.secondary">
          {exports.length === 1
            ? i18n('exports_count_single', [String(exports.length)])
            : i18n('exports_count_plural', [String(exports.length)])}
        </Typography>
        {exports.length > 0 && (
          <Tooltip title={i18n('exports_clear')}>
            <IconButton
              size="small"
              onClick={() => void handleClear()}
              aria-label={i18n('exports_clear')}
              className={styles['exports-panel__clear-btn']}
            >
              <DeleteIcon className={styles['exports-panel__clear-icon']} />
            </IconButton>
          </Tooltip>
        )}
      </Box>
      {exports.length === 0 ? (
        <Typography
          variant="caption"
          color="text.secondary"
          className={styles['exports-panel__empty']}
        >
          {i18n('exports_empty')}
        </Typography>
      ) : (
        <List dense disablePadding>
          {exports.map((record) => (
            <ListItem
              key={record.id}
              divider
              className={styles['exports-panel__list-item']}
              secondaryAction={
                <Box sx={{ display: 'flex', gap: 0.5 }}>
                  <Tooltip title={i18n('exports_download')}>
                    <IconButton
                      edge="end"
                      size="small"
                      onClick={() => handleDownload(record)}
                      aria-label={i18n('exports_download')}
                    >
                      <FileDownloadIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={i18n('exports_delete')}>
                    <IconButton
                      edge="end"
                      size="small"
                      onClick={() => void handleDelete(record.id)}
                      aria-label={i18n('exports_delete')}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </Box>
              }
            >
              <ListItemText
                primary={record.filename}
                secondary={`${formatTimestamp(record.createdAt)} — ${
                  record.rowCount === 1
                    ? i18n('exports_result_single', [String(record.rowCount)])
                    : i18n('exports_result_plural', [String(record.rowCount)])
                } · ${formatBytes(record.sizeBytes)}`}
                slotProps={{
                  primary: {
                    variant: 'body2',
                    className: styles['exports-panel__filename'],
                  },
                  secondary: {
                    variant: 'caption',
                    className: styles['exports-panel__secondary-text'],
                  },
                }}
                className={styles['exports-panel__list-item-text']}
              />
            </ListItem>
          ))}
        </List>
      )}
    </Box>
  );
};
 
export default ExportsPanel;