All files / src/components/admin/DataTable ColumnVisibility.tsx

0% Statements 0/142
100% Branches 0/0
0% Functions 0/1
0% Lines 0/142

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                                                                                                                                                                                                                                                                                             
'use client';

import { useState, useRef, useEffect } from 'react';
import { Table } from '@tanstack/react-table';
import { Icon } from '@/components/ui/icons';
import { cn } from '@/lib/core';

interface ColumnVisibilityDropdownProps<TData> {
  /** Table instance from useReactTable */
  table: Table<TData>;
}

/**
 * Column visibility toggle dropdown for DataTable.
 *
 * Allows users to show/hide table columns dynamically.
 */
export function ColumnVisibilityDropdown<TData>({
  table,
}: ColumnVisibilityDropdownProps<TData>) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close on click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  // Close on Escape
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen]);

  const columns = table.getAllColumns().filter((column) => column.getCanHide());

  if (columns.length === 0) return null;

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={cn(
          'p-2 rounded-md transition-colors',
          'hover:bg-gray-100 dark:hover:bg-gray-800',
          isOpen && 'bg-gray-100 dark:bg-gray-800'
        )}
        aria-label="Toggle column visibility"
        aria-expanded={isOpen}
        aria-haspopup="menu"
      >
        <Icon name="columns" className="h-4 w-4 text-gray-500 dark:text-gray-400" />
      </button>

      {isOpen && (
        <div
          className={cn(
            'absolute right-0 top-full mt-1 z-50',
            'min-w-[180px] max-h-[300px] overflow-y-auto',
            'bg-white dark:bg-gray-900',
            'border border-gray-200 dark:border-gray-700',
            'rounded-md shadow-lg',
            'py-1'
          )}
          role="menu"
        >
          <div className="px-3 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide border-b border-gray-200 dark:border-gray-700">
            Toggle Columns
          </div>
          {columns.map((column) => {
            const columnId = column.id;
            const columnName =
              typeof column.columnDef.header === 'string'
                ? column.columnDef.header
                : columnId.charAt(0).toUpperCase() + columnId.slice(1).replace(/([A-Z])/g, ' $1');

            return (
              <label
                key={columnId}
                className={cn(
                  'flex items-center gap-2 px-3 py-2 cursor-pointer',
                  'hover:bg-gray-100 dark:hover:bg-gray-800',
                  'transition-colors'
                )}
                role="menuitemcheckbox"
                aria-checked={column.getIsVisible()}
              >
                <input
                  type="checkbox"
                  checked={column.getIsVisible()}
                  onChange={(e) => column.toggleVisibility(e.target.checked)}
                  className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">{columnName}</span>
              </label>
            );
          })}

          {/* Reset button */}
          <div className="border-t border-gray-200 dark:border-gray-700 mt-1 pt-1">
            <button
              onClick={() => table.resetColumnVisibility()}
              className={cn(
                'w-full px-3 py-2 text-left text-sm',
                'text-gray-600 dark:text-gray-400',
                'hover:bg-gray-100 dark:hover:bg-gray-800',
                'transition-colors'
              )}
            >
              Reset to default
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

export default ColumnVisibilityDropdown;