All files / src/features/transaction/components transaction-table.tsx

90.24% Statements 37/41
88.88% Branches 16/18
86.66% Functions 13/15
90.24% Lines 37/41

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                                                                                3x       27x                               27x     27x     27x     27x   15x             27x     27x 27x 27x 15x     12x         9x         27x   1x 1x                   27x 27x 27x 30x     1x         2x                 27x   30x                 27x                       12x 12x               12x 2x                                                                             10x           80x                                           30x 30x                                             3x       3x     3x                                            
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { Button } from '@/components/button';
import type { MenuItemConfig } from '@/components/action-menu';
import { Heading } from '@/components/heading';
import { Text } from '@/components/text';
import type {
  TRANSACTION_TYPES,
  TRANSACTION_STATUS,
} from '@/constants/transaction';
import {
  TRANSACTION_TABLE_HEADERS,
  TRANSACTION_ACTIONS,
  TRANSACTION_EMPTY_STATE,
} from '@/constants/transaction';
import { useTransactions } from '../hooks/use-transactions';
import { DashboardStateRenderer } from '@/features/dashboard/components/shared/dashboard-state-renderer';
import { useVirtualizer } from '@tanstack/react-virtual';
import { createDeepEqualityFn } from '../utils/memo-utils';
import { TransactionRow } from './transaction-row';
import { useOptimizedTransactions } from '../hooks/use-optimized-transactions';
 
export interface Transaction {
  id: string;
  date: string;
  transactionId: string;
  type: typeof TRANSACTION_TYPES.BITCOIN | typeof TRANSACTION_TYPES.CARD;
  name: string;
  value: string;
  return: string;
  status:
    | typeof TRANSACTION_STATUS.COMPLETED
    | typeof TRANSACTION_STATUS.FAILED
    | typeof TRANSACTION_STATUS.IN_PROGRESS;
}
 
interface TransactionTableProps {
  onCreateNew?: () => void;
  maxTransactions?: number;
}
 
export const TransactionTable = ({
  onCreateNew,
  maxTransactions = 10,
}: TransactionTableProps) => {
  console.log('🔄 TransactionTable component rendering with props:', {
    onCreateNew: onCreateNew?.toString(),
    maxTransactions,
    timestamp: new Date().toISOString(),
  });
 
  // Use transaction fetching hook
  const {
    transactions: rawTransactions,
    isLoading,
    error,
    refresh,
    loadMore,
    hasNextPage,
    isLoadingMore,
    deleteTransaction,
  } = useTransactions(maxTransactions);
 
  // Use optimized transactions hook with react-fast-compare
  const { transactions } = useOptimizedTransactions(rawTransactions);
 
  // Create refs at component level instead of in renderTable
  const parentRef = useRef<HTMLDivElement>(null);
 
  // Initialize virtualizer at component level directly
  const rowVirtualizer = useVirtualizer({
    count: transactions.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 60, // Estimate row height
    gap: 8, // Gap between rows
    overscan: 5, // Number of items to render before/after the visible area
  });
 
  // Get virtual items for effect dependency
  const virtualItems = rowVirtualizer.getVirtualItems();
 
  // Set up infinite loading effect when last items are rendered
  useEffect(() => {
    const lastItem = virtualItems.at(-1);
    if (!lastItem) {
      return;
    }
 
    if (
      lastItem.index >= transactions.length - 1 &&
      hasNextPage &&
      !isLoadingMore
    ) {
      loadMore();
    }
  }, [hasNextPage, isLoadingMore, loadMore, transactions.length, virtualItems]);
 
  // Handle delete function
  const handleDelete = useCallback(
    async (id: string) => {
      try {
        await deleteTransaction(id);
      } catch (error) {
        console.error('Failed to delete transaction:', error);
      }
    },
    [deleteTransaction]
  );
 
  // Define action creation as a stable function that doesn't need frequent recreation
  // useMemo ensures this factory function is only created once unless dependencies change
  const createTransactionActionItems = useMemo(() => {
    console.log('🏭 Creating memoized menu items factory');
    return (transactionId: string): MenuItemConfig[] => {
      return [
        {
          label: TRANSACTION_ACTIONS.CREATE_NEW,
          onClick: () => onCreateNew?.(),
        },
        {
          label: TRANSACTION_ACTIONS.DELETE,
          onClick: () =>
            window.confirm(TRANSACTION_ACTIONS.DELETE_CONFIRMATION) &&
            handleDelete(transactionId),
          variant: 'destructive',
        },
      ];
    };
  }, [onCreateNew, handleDelete]);
 
  // Create a reusable renderRow function for virtualization
  const renderRow = useCallback(
    (transaction: Transaction) => (
      <TransactionRow
        transaction={transaction}
        actionItems={createTransactionActionItems(transaction.id)}
      />
    ),
    [createTransactionActionItems]
  );
 
  // Always render with state handling
  return (
    <DashboardStateRenderer
      loading={isLoading}
      error={error}
      data={transactions}
      onRetry={refresh}
      loadingTitle="Transactions"
      loadingMessage="Loading transactions..."
      errorTitle=""
      className="h-64"
    >
      {transactionData => {
        const typedData = transactionData as Transaction[];
        return renderTable(typedData || []);
      }}
    </DashboardStateRenderer>
  );
 
  // Helper function to render the actual table
  function renderTable(data: Transaction[]) {
    // Show empty state if no transactions
    if (data.length === 0) {
      return (
        <div className="text-center py-12 rounded-lg border border-gray-200">
          <div className="flex flex-col items-center space-y-4">
            <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
              <svg
                className="w-8 h-8 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
                />
              </svg>
            </div>
            <div className="space-y-2">
              <Heading as="h3" size="h5" className="text-gray-900">
                {TRANSACTION_EMPTY_STATE.HEADING}
              </Heading>
              <Text className="text-gray-500">
                {TRANSACTION_EMPTY_STATE.DESCRIPTION}
              </Text>
            </div>
            {onCreateNew && (
              <Button
                className="bg-gradient-vertical text-white px-6 py-2 rounded-full"
                onClick={onCreateNew}
              >
                {TRANSACTION_EMPTY_STATE.BUTTON_TEXT}
              </Button>
            )}
          </div>
        </div>
      );
    }
 
    return (
      <div className="overflow-hidden">
        {/* Fixed Header Row */}
        <div className="sticky top-0 z-10">
          <div className="grid grid-cols-8 gap-4 p-4 min-w-[800px]">
            {TRANSACTION_TABLE_HEADERS.map(header => (
              <div key={header.id} className="text-default font-medium">
                {header.label}
              </div>
            ))}
          </div>
        </div>
 
        {/* Scrollable Transaction Rows with Virtualizer */}
        <div
          ref={parentRef}
          className="overflow-x-auto overflow-y-auto max-h-[600px]"
          style={{ position: 'relative' }}
        >
          {rowVirtualizer && (
            <div
              className="min-w-[800px]"
              style={{
                height: `${rowVirtualizer.getTotalSize()}px`,
                position: 'relative',
              }}
            >
              {rowVirtualizer.getVirtualItems().map((virtualRow, index) => {
                const transaction = data[virtualRow.index];
                return (
                  <div
                    key={transaction.id}
                    className="absolute top-0 left-0 w-full"
                    style={{
                      zIndex: transactions.length - index,
                      height: `${virtualRow.size}px`,
                      transform: `translateY(${virtualRow.start}px)`,
                      padding: '4px 8px',
                    }}
                  >
                    {renderRow(transaction)}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }
};
 
TransactionTable.displayName = 'TransactionTable';
 
// Create a comparison function for memoization
const transactionTableComparison =
  createDeepEqualityFn<TransactionTableProps>();
 
// Enhanced comparison function with detailed logging for testing
const enhancedTransactionTableComparison = (
  prevProps: TransactionTableProps,
  nextProps: TransactionTableProps
): boolean => {
  console.log('🔍 TransactionTable memo comparison:', {
    prevProps: {
      maxTransactions: prevProps.maxTransactions,
      onCreateNew: prevProps.onCreateNew?.toString(),
    },
    nextProps: {
      maxTransactions: nextProps.maxTransactions,
      onCreateNew: nextProps.onCreateNew?.toString(),
    },
    areEqual: transactionTableComparison(prevProps, nextProps),
    timestamp: new Date().toISOString(),
  });
 
  return transactionTableComparison(prevProps, nextProps);
};
 
// Export a memoized version of the TransactionTable component
export default memo(TransactionTable, enhancedTransactionTableComparison);