@vincjo/datatables

repository·main·Indexed 20 days ago

https://github.com/vincjo/datatables

A powerful toolkit for building datatable components in Svelte, designed to streamline data workflows and reduce code complexity. Version 2.8.1 provides a suite of Svelte components (Datatable, Search, Pagination, etc.) and handler classes like TableHandler to manage table state, sorting, filtering, and pagination. It includes utilities for data manipulation such as match(), sift(), and deepEmphasize() for highlighting matching values.

Tokens
17.6K
Snippets
84
Records
97
Agent score
69%

What's inside @vincjo/datatables

  1. Structure of the Table State object

    main

    The table state is a structured object used to track the current configuration of the data table, including pagination, searching, sorting, and filtering. This state can be used to synchronize the UI with backend API requests.

    Key properties include:

    • currentPage: The current active page number.
    • rowsPerPage: The number of rows to display per page.
    • offset: The starting index for the current view (calculated as (currentPage - 1) * rowsPerPage).
    • search: The full-text search string.
    • sort: An object containing the field being sorted and the direction (asc or desc).
    • filters: An array of objects, where each object contains a field and a value to filter by.
    state = {
        currentPage: 3,
        rowsPerPage: 10,
        offset: 20,
        search: 'michel',
        sort: { field: 'age', direction: 'desc' },
        filters: [ { field: 'city', value: 'limoge' } ]
    }
  2. Define field accessors using the Field type

    main

    A Field defines how to extract a value from a data row. It can be specified in two ways:

    1. Object Key: A simple string representing the property name on the row object (e.g., 'first_name').
    2. Expression Function: A function that takes the entire row as an argument and returns the desired value. This is useful for computed values or accessing nested properties (e.g., (row) => row.user.id).

    Important Constraint: If you are using TableHandler in server-side pagination mode, the Field must be an object key. You cannot use expression functions in this mode because the server-side logic requires a direct key to perform data fetching or sorting.

    // Using an object key
    const fieldKey = 'first_name';
    
    // Using an expression function for computed values
    const expression = (row) => row.first_name + row.last_name;
    
    // Using an expression function for nested properties
    const nested = (row) => row.user.login_count.value;
  3. Enable row selection with TableHandler

    main

    To enable row selection in a TableHandler instance, you must specify which property in your data objects serves as the unique identifier by providing the selectBy parameter in the configuration object. This allows the handler to track which rows are selected based on their unique keys.

    const table = new TableHandler(data, { selectBy: 'id' })
  4. Use the isLoading property to show loading states

    main

    The isLoading property on the table object is a boolean that becomes true whenever the invalidate() method is running (e.g., during data fetching or refreshing). You can use this property to conditionally render loading spinners or progress indicators in your Svelte components.

    <Datatable {table}>
        <div class="spinner" class={{ active: table.isLoading }}></div
        <table>
            [...]
        </table>
    </Datatable>
  5. Migrate from v1 to v2

    main

    To facilitate a progressive upgrade, version 1 functionality is available under the legacy namespace. You can migrate your existing components by updating your import paths from the main package to the legacy subpaths.

    - @vincjo/datatables
    + @vincjo/datatables/legacy
    
    - @vincjo/datatables/remote
    + @vincjo/datatables/legacy/remote
  6. Translate showcase component text using table.i18n

    main

    You can localize the text used in the datatables showcase components (such as search placeholders, pagination labels, and row count descriptions) by providing an object to the table.i18n property.

    Use the following keys to define your translations:

    • search: The placeholder text for the search input.
    • show: The label for showing entries.
    • entries: The unit used for entries (e.g., 'lines', 'rows', 'items').
    • filter: The label for the filter input.
    • rowCount: The template string for the row count display. Use {start}, {end}, and {total} as placeholders for the current range and total count.
    • noRows: The message displayed when no results are found.
    • previous: The label for the previous page button.
    • next: The label for the next page button.
    table.i18n = {
        search: 'Search...',
        show: 'Show', 
        entries: 'lines',
        filter: 'Filter',
        rowCount: 'Showing {start} to {end} of {total} entries',
        noRows: 'No entries found',
        previous: 'Previous', 
        next: 'Next'
    }
  7. Configure Internationalization (i18n)

    main

    You can customize the text used in various datatable components using the Internationalization type. The available keys are:

    • search: Label for the search input.
    • show: Label for showing entries.
    • entries: Label for entries.
    • filter: Label for filtering.
    • rowCount: Label for the row count display.
    • noRows: Label for when no results are found.
    • previous: Label for the previous page button.
    • next: Label for the next page button.
  8. Handle row selection using table.selected and table.select()

    main

    To manage row selection in a Svelte component, use the table.selected array to track which row identifiers are currently active and the table.select(id) method to toggle or set selection.

    When rendering rows, you can check if a row is selected by verifying if its identifier exists within table.selected using .includes(row.id). This allows you to apply conditional CSS classes (like active) and manage the state of checkbox inputs.

    <tr class={{ active: table.selected.includes(row.id) }}>
        <td>
            <input type="checkbox" 
                checked={table.selected.includes(row.id)}
                onclick={() => table.select(row.id)}
            >
        </td>
        <td>{row.first_name}</td>
        <td>{row.last_name}</td>
    </tr>
  9. Render table rows using the table.rows property

    main

    To render the data in a Svelte component, iterate over the table.rows array using an {#each} block. Each row object in the array contains the data for a single record. You can access individual fields (e.g., row.first_name, row.last_name) to populate your table cells (<td>).

    <tbody
    >
        {#each table.rows as row}
            <tr>
                <td>{row.first_name}</td> 
                <td>{row.last_name}</td>
                <td>{row.address}</td>
            </tr>
        {/each}
    </tbody
    >