# ia-table

A powerful, feature-rich React data table component for enterprise applications.

[![NPM](https://img.shields.io/npm/v/ia-table.svg)](https://www.npmjs.com/package/ia-table)

## Installation

```bash
npm install --save ia-table
```

## Development Setup

If you're contributing to this project or have cloned the repository, follow these steps:

### 1. Install Dependencies

```bash
npm install
```

### 2. ESLint Configuration

This project uses **ESLint 9+ with Flat Config** format. The configuration is in `eslint.config.js`.

#### Running ESLint

```bash
# Check for linting errors
npm run lint

# Auto-fix linting errors
npm run lint:fix
```

#### IDE Integration

**VS Code:**

1. Install the [ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
2. Install the [Prettier extension](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
3. Create `.vscode/settings.json` in the project root with:

```json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ]
}
```

This configuration enables:

- Auto-format on save with Prettier
- Auto-fix ESLint errors on save
- Consistent formatting across all file types

**Other IDEs:**

- Most modern IDEs support ESLint flat config format
- Ensure your IDE's ESLint plugin is updated to the latest version

#### What's Configured

- **React Hooks Rules**: Enforces React hooks best practices
- **React Refresh**: Warns about components that can't be hot-reloaded
- **React Compiler**: Optimizations for React 19+
- **TypeScript Support**: Full TypeScript linting with `typescript-eslint`
- **Ignored Paths**: Automatically ignores `dist/`, `build/`, `node_modules/`, config files, and example files

#### Customizing Rules

To modify linting rules, edit `eslint.config.js`:

```javascript
{
  rules: {
    "your-rule": "error", // or "warn" or "off"
  }
}
```

### 3. Prettier Configuration

This project uses **Prettier** for consistent code formatting across the team.

#### Running Prettier

```bash
# Format all files
npm run format

# Check if files are formatted (useful for CI)
npm run format:check
```

#### IDE Integration

The `.vscode/settings.json` configuration shown in the ESLint section above already includes Prettier integration. No additional setup needed if you've already configured VS Code for ESLint.

**Other IDEs:**

- Most modern IDEs have Prettier plugins available
- Configuration is automatically detected from `.prettierrc`

#### ESLint + Prettier Integration

The project is configured so that:

- **ESLint** handles code quality rules (bugs, best practices)
- **Prettier** handles code formatting (spacing, line breaks, quotes)
- `eslint-config-prettier` disables conflicting ESLint formatting rules

### 4. Available Scripts

```bash
# Development server
npm start

# Build library for production
npm run build:lib

# Run tests
npm test

# Linting
npm run lint          # Check for linting errors
npm run lint:fix      # Auto-fix linting errors

# Formatting
npm run format        # Format all files with Prettier
npm run format:check  # Check if files are formatted

# Storybook for component development
npm run storybook

# Build Storybook
npm run build:storybook
```

## Quick Start

```jsx
import IATable from "ia-table";

const App = () => {
  const data = [
    { id: 1, name: "Product A", price: 100 },
    { id: 2, name: "Product B", price: 200 },
  ];

  const columns = [
    { field: "id", headerName: "ID" },
    { field: "name", headerName: "Name" },
    { field: "price", headerName: "Price" },
  ];

  return (
    <IATable data={data} columns={columns} height="400px" uniqueIdField="id" />
  );
};
```

<!-- For detailed documentation on publishing this package, see [PUBLISHING.md](./PUBLISHING.md). -->

## Features

### Core Table Features

- **Data Display**:
  - Renders tabular data with fully customizable columns
  - Supports complex data objects and nested properties
  - Handles large datasets efficiently with virtualization
  - Displays empty state and loading indicators

- **Responsive Layout**:
  - Adapts to container size with proper overflow handling
  - Horizontal scrolling for tables wider than their container
  - Maintains header alignment with body cells during scroll
  - Supports fixed height or auto-expanding layouts

- **Dynamic Column Configuration**:
  - Configure width, alignment, sorting, filtering, and resizing per column
  - Support for complex column hierarchies with nested column groups
  - Custom cell renderers for advanced content formatting
  - Header customization with custom renderers
  - Column freezing/pinning for better navigation of wide tables
  - Show/hide columns via the column toggle menu

### Data Management

- **Sorting**:
  - Sort data by any column in ascending or descending order
  - Visual indicators for sort direction
  - Support for custom sort functions
  - Multi-column sorting capability
  - Maintains sort state between renders

- **Pagination**:
  - Built-in pagination with customizable page size
  - Page navigation controls (previous, next, first, last)
  - Dynamic calculation of total pages
  - Efficient page switching without re-rendering the entire table
  - Customizable page size options

- **Filtering**:
  - Global search functionality across all columns or specific columns
  - Column-specific filtering with custom filter inputs
  - Advanced filter panel with multiple filter conditions
  - Filter operators include: contains, equals, startsWith, endsWith, etc.
  - Support for numeric filters (greater than, less than)
  - Date filtering capabilities
  - Boolean filters (is/is not)
  - Empty/not empty filters

### Row Features

- **Row Selection**:
  - Single or multi-row selection with checkbox support
  - Select all/deselect all functionality
  - Selection persistence between page changes
  - Selection state callbacks for external state management
  - Visual indication of selected rows
  - Access to selection data through context

- **Row Expansion**:
  - Expandable rows with custom content
  - Expand/collapse indicators with animation
  - Customizable expanded content renderer
  - Independent expansion state for each row
  - Context-aware expansion tracking

- **Row Grouping**:
  - Support for hierarchical data with parent-child relationships
  - Configurable grouping fields
  - Visual indicators for grouped data
  - Expand/collapse functionality for group items
  - Custom renderers for group rows
  - Supports multiple levels of nesting

- **Row Virtualization**:
  - Performance optimization for large datasets (>100 rows)
  - Only renders visible rows and a small buffer
  - Seamless scrolling through thousands of rows
  - Dynamic height calculation for varying row heights
  - Memory efficient for very large datasets
  - Maintains scroll position during updates

### UI Components

- **Table Header**:
  - Customizable with sort indicators
  - Support for multi-level column groups
  - Column resizing via drag handles
  - Fixed positioning during scroll
  - Context menu for column operations
  - Support for custom header cell renderers

- **Table Body**:
  - Efficient rendering with virtualization for large datasets
  - Custom cell renderers for complex content
  - Row and cell event handlers (click, hover, etc.)
  - Support for keyboard navigation
  - Proper handling of null/undefined values
  - Type-aware cell formatting

- **Table Footer**:
  - Optional with pagination controls
  - Summary row capabilities
  - Aggregate function support (sum, average, count, etc.)
  - Fixed positioning for easy access
  - Custom footer renderers

- **Toolbar**:
  - Search functionality with debounced input
  - Column visibility toggle
  - Export options (CSV, Excel, etc.)
  - Custom action buttons
  - Responsive design for mobile compatibility

- **Column Toggle Menu**:
  - Show/hide columns dynamically
  - Drag and drop column reordering
  - Reset to default option
  - Search columns functionality
  - Column group management

- **Filter Panel**:
  - Complex filtering interface
  - Add/remove filter conditions
  - Combine multiple filters
  - Filter operator selection
  - Type-aware filter inputs
  - Save filter presets

### Visual Customization

- **Column Resizing**:
  - Drag handles to adjust column widths
  - Visual feedback during resize operation
  - Minimum/maximum width constraints
  - Double-click to auto-size based on content
  - Persist column width preferences

- **Styling**:
  - Comprehensive CSS for enterprise appearance
  - Support for theming and custom styles
  - Responsive design principles
  - Accessible color schemes
  - Row alternating colors
  - Hover and selection styles

- **Custom Cell Rendering**:
  - Format cell content with custom renderers
  - Support for complex components within cells
  - Cell editor integration
  - Conditional formatting based on cell values
  - Support for images, icons, and rich content

### Performance Optimizations

- **Virtualized Rendering**:
  - Only renders visible rows for large datasets
  - Significantly improves performance for tables with thousands of rows
  - Dynamic buffer size calculation
  - Smooth scrolling experience
  - Efficient DOM reuse

- **Memoization**:
  - Efficient re-rendering using React.useMemo
  - Prevents unnecessary calculations during renders
  - Smart component updates based on changed props
  - Optimized context usage to prevent re-renders

- **Optimized Filtering**:
  - Smart filter application for large datasets
  - Debounced search input to prevent excessive filtering
  - Cached filter results when possible
  - Progressive filtering for complex conditions
  - Background processing for non-blocking UX

## Usage

```jsx
import IATable from "ia-table";

// Sample data
const data = [
  { id: 1, name: "Product A", category: "Electronics", price: 299.99 },
  { id: 2, name: "Product B", category: "Furniture", price: 599.99 },
  // ...more rows
];

// Column definitions
const columns = [
  {
    field: "id",
    headerName: "ID",
    width: 80,
    sortable: true,
  },
  {
    field: "name",
    headerName: "Product Name",
    width: 200,
    sortable: true,
    filterable: true,
  },
  {
    field: "category",
    headerName: "Category",
    width: 150,
    sortable: true,
    filterable: true,
  },
  {
    field: "price",
    headerName: "Price",
    width: 120,
    align: "right",
    sortable: true,
    filterable: true,
    cellRenderer: ({ value }) => `$${value.toFixed(2)}`,
  },
];

// Component implementation
const MyTable = () => {
  return (
    <IATable
      data={data}
      columns={columns}
      height="500px"
      uniqueIdField="id"
      selectable={true}
      pagination={true}
      pageSize={10}
    />
  );
};
```

## Props

| Prop              | Type    | Default         | Description                                        |
| ----------------- | ------- | --------------- | -------------------------------------------------- |
| `data`            | Array   | `[]`            | Array of data objects to display                   |
| `columns`         | Array   | `[]`            | Column definitions                                 |
| `height`          | String  | `'auto'`        | Table height                                       |
| `uniqueIdField`   | String  | `'store_code'`  | Field to use as unique row identifier              |
| `childKeyField`   | String  | `'status_obj1'` | Field containing child items for hierarchical data |
| `showHeader`      | Boolean | `true`          | Whether to show the table header                   |
| `showFooter`      | Boolean | `false`         | Whether to show the table footer                   |
| `showToolbar`     | Boolean | `true`          | Whether to show the toolbar                        |
| `selectable`      | Boolean | `false`         | Enable row selection                               |
| `expandable`      | Boolean | `false`         | Enable row expansion                               |
| `pagination`      | Boolean | `false`         | Enable pagination                                  |
| `defaultPageSize` | Number  | `10`            | Items per page when pagination is enabled          |

## Column Definition

```typescript
interface ColumnDefinition {
  field: string; // The field name in the data object
  headerName: string; // The display name for the column header
  width?: number; // The width of the column in pixels (default: 100)
  isSortable?: boolean; // Whether the column is sortable (default: true)
  filterable?: boolean; // Whether the column is filterable (default: true)
  resizable?: boolean; // Whether the column can be resized (default: true)
  cellRenderer?: Function; // Custom cell renderer function
  align?: "left" | "center" | "right"; // Text alignment (default: 'left')
  pinned?: boolean | "left"; // Whether the column is pinned (true = right, 'left' = left)
  is_hidden?: boolean; // Whether the column is initially hidden
}
```
