### Install svelte-dnd-action Source: https://github.com/vincjo/datatables/blob/main/src/routes/examples/client/column-ordering/Client.svx This command installs the svelte-dnd-action library, which is required for implementing drag-and-drop functionality in the Svelte Datatable example. ```bash npm i -D svelte-dnd-action ``` -------------------------------- ### Sample Date Data Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/dates/content.svx This is an example of data with date strings in 'MM/dd/yyyy hh:mm:ss a' format. ```javascript const data = [ { user: 'John Doe', created_at: '12/01/2024 11:04:23 AM' }, { user: 'Tobie Vint', created_at: '09/30/2020 01:43:06 PM' }, { user: 'Zacharias Cerman', created_at: '04/26/2023 05:02:21 PM' }, { user: 'Gérianna Bunn', created_at: '03/13/2021 07:58:33 AM' }, { user: 'Bee Saurin', created_at: '11/08/2019 03:21:54 PM' }, { user: 'Méyère Granulette', created_at: '07/27/2022 08:12:16 PM' }, { user: 'Jane Doe', created_at: '01/18/2017 11:38:47 AM' }, { user: 'Michel Trapu', created_at: '04/02/2025 04:19:46 PM' }, ] ``` -------------------------------- ### Pagination Navigation Markup Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/navigation/content.svx Example Svelte markup for creating pagination controls. ```svelte ``` -------------------------------- ### Install Datatables Package Source: https://github.com/vincjo/datatables/blob/main/README.md Install the datatables package as a development dependency using npm. ```bash npm i -D @vincjo/datatables ``` -------------------------------- ### Initialize DataHandler in Svelte 4 (v1) Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Example of initializing and using DataHandler from v1 in a Svelte 4 environment. ```ts import { DataHandler } from '@vincjo/datatables/legacy' const handler = new DataHandler(data) const rows = handler.getRows() const currentPage = handler.getPageNumber() // $rows, $currentPage ``` -------------------------------- ### API Query Parameters Example Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/overview/content.svx Illustrates the parameters available for querying data from an external API, including pagination, search, filtering, and sorting. ```bash https://api.mysite.com/users? limit=10 # rows per page &offset=20 # offset (20 = page number 3) &q=michel # full text search &city=limoge # column filter: where "city" = 'limoge' &sort=age &order=desc # order by "age" descending ``` -------------------------------- ### Full Svelte Component Example Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/input/content.svx A complete Svelte component demonstrating filter creation and input binding, including necessary imports. ```svelte filter.set()}> ``` -------------------------------- ### Filter Count Example Output Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.filterCount.md An example showing the expected value for the `filterCount` property when filters are applied. ```typescript table.filterCount = 2 ``` -------------------------------- ### Sample Data Structure Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/hello-world/Client.svx This is an example of the data structure expected by the `TableHandler`. Ensure your data is an array of objects with consistent keys. ```ts const data = [ { id: 1, first_name: 'Tobie', last_name: 'Vint', email: 'tvint0@fotki.com' }, { id: 2, first_name: 'Zacharias', last_name: 'Cerman', email: 'zcerman1@sciencedirect.com' }, { id: 3, first_name: 'Gérianna', last_name: 'Bunn', email: 'gbunn2@foxnews.com' }, { id: 4, first_name: 'Bee', last_name: 'Saurin', email: 'bsaurin3@live.com' }, ... ] ``` -------------------------------- ### Initialize TableHandler in Svelte 5 (v2) Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Example of initializing and accessing properties of TableHandler from v2 in a Svelte 5 environment. ```ts import { TableHandler } from '@vincjo/datatables' const table = new TableHandler(data) // table.rows, table.currentPage ``` -------------------------------- ### Create Sort Instance Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Example of creating a sort instance for a specific column using the TableHandler API. ```ts const sort = table.createSort('first_name') ``` -------------------------------- ### Full Sortable Table Header Example Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/button/content.svx A complete Svelte component demonstrating a sortable table header, including necessary imports and sort instance creation. ```svelte ``` -------------------------------- ### Basic Svelte Datatable Setup Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/hello-world/Client.svx Use this snippet to initialize a Svelte Datatable with basic features like row count, global search, and pagination. Ensure you import necessary components and have your data handler set up. ```svelte First NameLast NameEmail {#each table.rows as row} {/each}
{row.first_name} {row.last_name} {row.email}
``` -------------------------------- ### pagesWithEllipsis Output Examples Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.pagesWithEllipsis.md Demonstrates the output of `pagesWithEllipsis` based on the `currentPage` value. Observe how the `null` values dynamically represent ellipses in the pagination. ```typescript // table.currentPage = 1 table.pagesWithEllipsis = [ 1, 2, 3, 4, 5, null, 18 ] ``` ```typescript // table.currentPage = 7 table.pagesWithEllipsis = [1, null, 6, 7, 8, null, 18] ``` ```typescript // table.currentPage = 15 table.pagesWithEllipsis = [1, null, 14, 15, 16, 17, 18] ``` -------------------------------- ### Bind Search Input in Svelte Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Example of binding a Svelte input element to the search value and triggering a search update. ```svelte search.set()}> filter.set()}> ``` -------------------------------- ### Table Page Navigation Buttons Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.setPage.md Provides examples of creating UI buttons for navigating table pages, including first, previous, ellipsis, next, and last page options. ```svelte {#each table.pagesWithEllipsis as page} {/each} ``` -------------------------------- ### Instantiate TableHandler Source: https://github.com/vincjo/datatables/blob/main/src/routes/api/[mode]/content.svx Initialize a new TableHandler instance with an empty array of rows. This is the starting point for using the API. ```typescript import { TableHandler } from '@vincjo/datatables' const table = new TableHandler([]) ``` -------------------------------- ### Svelte 4 DataHandler Usage (v1) Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/migration/content.svx Example of using the legacy DataHandler in Svelte 4, including state management and event handling. ```typescript import { DataHandler } from '@vincjo/datatables/legacy/remote' const handler = new DataHandler([], { rowsPerPage: 5 }) handler.onChange((state: State) => myLoadFunction(state): Promise) handler.invalidate() const rows = handler.getRows() const currentPage = handler.getPageNumber() // $rows, $currentPage ``` -------------------------------- ### Svelte 5 TableHandler Usage (v2) Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/migration/content.svx Example of using the new TableHandler in Svelte 5, demonstrating its API for data loading and state invalidation. ```typescript import { TableHandler } from '@vincjo/datatables/server' const table = new TableHandler([], { rowsPerPage: 5 }) table.load((state: State) => myFunction(state): Promise ) table.invalidate() // table.rows, table.currentPage ``` -------------------------------- ### Implementing a data fetching function Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/server/methods.load.md This example shows a practical implementation of the data fetching function. It uses the `rowsPerPage` and `offset` from the state to construct an API request and returns the JSON response. ```typescript table.load(async ({ rowsPerPage, offset }: State) => { const response = await fetch(`https://myapi.com?limit=${rowsPerPage}&offset=${offset}`) return response.json() }) ``` -------------------------------- ### Field Type Examples Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/types.Field.md Illustrates the different ways the Field type can be defined: as a string key, a function returning a concatenated string, or a function accessing nested properties. ```typescript // keyof Row: 'first_name' ``` ```typescript // expression: (row) => row.first_name + row.last_name ``` ```typescript // nested prop (row) => row.user.login_count.value ``` -------------------------------- ### Get View Instance Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.getView.md Call the `getView()` method on the table instance to retrieve the view. This is useful for accessing component methods or properties directly. ```typescript table.getView() ``` -------------------------------- ### Get Applied Filters Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/properties.filters.md Retrieves all filters currently applied to the dataset. Use this to inspect the active filtering conditions. ```typescript const list = table.filters.map(({ key, comparator, value }) => `${key} ${comparator.name} ${value}`) ``` -------------------------------- ### API Response for Total Row Count Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/pagination/pages/content.svx Example of a typical API response structure that includes the total count of data rows, used for setting pagination. ```json // api response: { count: 150, data: [...] } ``` -------------------------------- ### Example Row Count Output Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.rowCount.md Illustrates the structure and typical values for the table.rowCount object when rows per page is 10, the dataset has 150 rows, no filter is applied, and no row is selected. ```typescript const table.rowCount = { start: 1, end: 10, total: 150, selected: 0 } // rowsPerPage = 10, dataset has 150 rows, no filter applied, no selected row ``` -------------------------------- ### Example Structure of table.rows Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.rows.md Illustrates the expected data structure for the `table.rows` property, which is an array of objects. Each object represents a row and contains properties such as `id`, `frist_name`, and `last_name`. ```typescript table.rows = [ { id: 1, frist_name: 'Jane', last_name: 'Doe' }, ... { id: 150, first_name: 'John', last_name: 'Doe' } ] ``` -------------------------------- ### Clear Selection Button Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.clearSelection.md Use the clearSelection method to deselect all rows. This example shows a button that calls the method when clicked. ```svelte ``` -------------------------------- ### Get Table State Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/server/methods.getState.md Call `table.getState()` to retrieve the current state of the table, including pagination, search, sort, and filter information. ```typescript table.getState() // returns: { currentPage: 3, rowsPerPage: 10, offset: 20, search: 'michel', sort: { field: 'age', direction: 'desc' }, filters: [ { field: 'city', value: 'limoge' } ], setTotalRows: (value: number) => void } ``` -------------------------------- ### Wrapper Function for API Request Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/overview/content.svx An example wrapper function that translates the client-side state into a URL query string for an API request and processes the response. It sets the total number of rows and returns the data rows. ```typescript import type { State } from '@vincjo/datatables/server' export const myFunction = async (state: State) => { const response = await fetch( `https://api.mysite.com/users?${getParams(state)}` ) const json = await response.json() state.setTotalRows(json.count) return json.rows } const getParams = ({ offset, rowsPerPage, search, sort, filters }: State) => { let params = `offset=${offset}&limit=${rowsPerPage}` if (search) params += `&q=${search}` if (sort) params += `&sort=${sort.field}&order=${sort.direction}` if (filters) params += filters.map(({ field, value }) => `&${field}=${value}`).join() return params } ``` -------------------------------- ### Clear Filters Button Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.clearFilters.md Use the clearFilters method to remove all column filters. This example shows a button that calls the method when clicked. ```svelte ``` -------------------------------- ### Server-side Data Fetching Function Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/data/load/content.svx An example of a data fetching function that uses the state (rowsPerPage, offset) to build an API request and parse the JSON response. It also demonstrates how to potentially use `setRowsPerPage` if needed. ```typescript import type { State } from '@vincjo/datatables/server' table.load(async ({ rowsPerPage, offset, setRowsPerPage }: State) => { const response = await fetch(`https://myapi.com?limit=${rowsPerPage}&offset=${offset}`) return response.json() }) ``` -------------------------------- ### Accessing clientWidth in Datatable Component Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.clientWidth.md When using the Datatable component, you can access the clientWidth property directly. This example shows how to apply a CSS class based on the table's width. ```svelte
[...]
``` -------------------------------- ### Accessing Row Count Data Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/row-count/content.svx Derive the start, end, and total row counts from the table instance. This is useful for displaying pagination information. ```typescript const { start, end, total } = $derived(table.rowCount) ``` -------------------------------- ### Use TableHandler Methods Source: https://github.com/vincjo/datatables/blob/main/src/routes/api/[mode]/content.svx Call setter methods on the TableHandler instance to manage data events with minimal boilerplate. Examples include setting rows per page, selecting rows, and navigating pages. ```typescript table.setRowsPerPage(10) table.select(row.id) table.setPage('previous') table.createSort() ... ``` -------------------------------- ### Displaying Pagination and Selection in Svelte Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.rowCount.md Use the derived row count properties to render pagination information and the number of selected rows in a Svelte component. Assumes 'start', 'end', 'total', and 'selected' are available in the component's scope. ```svelte

Showing {start} to {end} of {total} entries

{selected} of {total} row(s) selected

``` -------------------------------- ### Get Selected Rows Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.getSelectedRows.md Use this method to retrieve the complete row objects for all currently selected rows in the table. No setup or imports are required if you have a table instance. ```typescript table.getSelectedRows() ``` -------------------------------- ### Create Search and Filter Instances Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Demonstrates how to create search and column filter instances using the TableHandler API. ```ts const search = table.createSearch() const filter = table.createFilter('first_name') // column filter ``` -------------------------------- ### Basic Svelte Datatable Implementation Source: https://github.com/vincjo/datatables/blob/main/README.md Initialize a TableHandler with data and display it in a Svelte table. Configure rows per page during initialization. ```svelte {#each table.rows as row} {/each}
First name Last name
{row.first_name} {row.last_name}
``` -------------------------------- ### Define a Filter Object Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/server/types.Filter.md An example of how to define a filter object to specify a field and its corresponding value for filtering data. ```typescript filter = { field: 'name', value: 'john' } ``` -------------------------------- ### Bind Data Fetching Function to TableHandler Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/overview/content.svx Shows how to instantiate a TableHandler and bind a custom data fetching function using the `load` method. The data fetching function receives the client-side state and returns a Promise resolving to an array of rows. ```svelte ``` -------------------------------- ### Create Table View with Initial Visibility Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/view/visible/content.svx Defines a table view with specific column configurations, including initial visibility settings. Use this to set up which columns are visible by default when the table is initialized. ```typescript const view = table.createView([ { index: 0, name: 'ID', isVisible: false }, { index: 1, name: 'First name' }, { index: 2, name: 'Last name' }, { index: 3, name: 'Email' }, ]) ``` -------------------------------- ### Basic Sum Calculation Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/sum/code.svx Demonstrates how to create a basic sum calculation for a 'price' column. Use this for simple aggregations. ```typescript const sum = $derived(table.createCalculation('price').sum()) ``` ```html

Total: {sum}

``` -------------------------------- ### Initialize TableHandler with Pagination Options Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/pagination/pages/content.svx Initialize the TableHandler with the total number of rows and the desired number of rows per page to enable pagination. ```typescript const table = new TableHandler(initialData, { rowsPerPage: 10, totalRows: 150 }) ``` -------------------------------- ### Column Calculations with createCalculation Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.createCalculation.md Demonstrates various aggregation functions that can be applied to a column using the createCalculation method. Ensure the column exists and contains appropriate data for the chosen calculation. ```typescript table.createCalculation('price').distinct() // distinct values table.createCalculation('price').avg() // average table.createCalculation('price').sum() // sum table.createCalculation('price').median() // median table.createCalculation('price').bound() // bounds [min, max] ``` -------------------------------- ### Accessing Row Count Properties Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.rowCount.md Derive the start, end, total, and selected row counts from the table object. These values update reactively. ```typescript const { start, end, total, selected } = $derived(table.rowCount) ``` -------------------------------- ### Download CSV Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/add-on/csv-export/content.svx Provides a button to trigger the CSV download. The 'csv' variable from the previous step is used here. ```svelte ``` -------------------------------- ### Basic load method signature Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/server/methods.load.md The `load` method accepts a callback function that receives the table's current state. This function should return a Promise that resolves to an array of rows. ```typescript table.load((state: State) => myLoadFunction(state): Promise ) ``` -------------------------------- ### Accessing pagesWithEllipsis Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.pagesWithEllipsis.md Access the `pagesWithEllipsis` property to get an array representing the pagination links with dynamic ellipses. The ellipses are represented by `null` values. ```typescript console.log(table.pagesWithEllipsis) ``` -------------------------------- ### Freeze Columns using createView Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/view/freeze/content.svx Use the `createView` method to specify which columns should be frozen. Set the `isFrozen` property to `true` for the desired column indices. ```typescript table.createView([ { index: 0, isFrozen: true }, { index: 1, isFrozen: true }, ]) ``` -------------------------------- ### Initialize Search Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/search/recursive/content.svx Create a new search instance from the table object. ```typescript const search = table.createSearch() ``` -------------------------------- ### Get Calculation Bounds Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/bounds/code.svx Retrieves the minimum and maximum values for a calculated column named 'model_year'. This is useful for displaying value ranges or setting up filters. ```typescript const [min, max] = $derived(table.createCalculation('model_year').bounds()) ``` -------------------------------- ### Basic Datatable Structure in Svelte Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/overview/content.svx Use the Datatable component with pre-built header and footer snippets for search, rows per page, row count, and pagination. ```svelte {#snippet header()} {/snippet} [...]
{#snippet footer()} {/snippet}
``` -------------------------------- ### Basic Table Load Method Signature Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/data/load/content.svx This snippet shows the basic signature for the table load method, accepting a state object and returning a Promise of rows. ```typescript table.load((state: State) => myFunction(state): Promise ) ``` -------------------------------- ### Import Pre-built Components Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/overview/content.svx Import necessary components from the Datatables library for building your data table interface. ```typescript import { Datatable, Search, RowsPerPage, RowCount, Pagination } from '@vincjo/datatables' ``` -------------------------------- ### Create Sort Function for Nested Property Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/nested/content.svx Example of creating a sort function for a nested property within the DataTables library. This allows sorting based on deeply nested data. ```typescript const sort = table.createSort((row) => row.user.login_count) ``` -------------------------------- ### Enable Pagination with rowsPerPage Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/pages/content.svx Initialize the TableHandler with the `rowsPerPage` option to enable pagination. This option determines how many rows are displayed per page. ```typescript const table = new TableHandler(data, { rowsPerPage: 20 }) ``` -------------------------------- ### Display and Navigate Current Page Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/pages/content.svx Render a button for the current page, highlighting it if it's active. Includes an `onclick` handler to navigate to the selected page using `table.setPage(page)`. ```svelte ``` -------------------------------- ### Provide Check Parameter for Client-Side Filtering Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.createFilter.md Utilize the 'check' parameter with a specific check function (e.g., isEqualTo) for client-side data processing. Ensure the 'check' module is imported. ```svelte ``` -------------------------------- ### clearSort() Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.clearSort.md Removes all active sorting configurations from the datatable. This method is useful when you want to reset the table to its default unsorted state, for example, before applying new data that should not be sorted by previous configurations. ```APIDOC ## clearSort() ### Description Removes all active sorting configurations from the datatable. This method is useful when you want to reset the table to its default unsorted state, for example, before applying new data that should not be sorted by previous configurations. ### Method `table.clearSort()` ### Parameters This method does not accept any parameters. ### Usage Example ```ts table.clearSort() ``` ### Related Methods - `table.setRows(data)`: Updates the table with new data, potentially restoring previous sorts if `clearSort()` is not called beforehand. ### Example Scenario ```svelte ``` ``` -------------------------------- ### Render Page Numbers Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/pages/content.svx Iterate over the `table.pages` array to render buttons for each page number. This is a basic implementation for displaying page navigation. ```svelte {#each table.pages as page} {/each} ``` -------------------------------- ### Select All Rows Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/select/scope/content.svx Use the `selectAll` method with the `scope: 'all'` option to select all rows in the table, regardless of the current pagination. This is useful for bulk actions that need to apply to the entire dataset. ```javascript table.selectAll({ scope: 'all' }) ``` ```svelte table.selectAll({ scope: 'all' })}> ``` -------------------------------- ### Get selected rows by identifier Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.selected.md Use this snippet to conditionally apply an 'active' class to table rows based on whether their ID is included in the selected list. It also handles checkbox selection and deselection. ```svelte table.select(row.id)} > {row.first_name} {row.last_name} ``` -------------------------------- ### Create a Filter Instance Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/input/content.svx Instantiate a filter for a specific table field. This is the initial step before binding it to an input element. ```typescript const filter = table.createFilter('last_name') ``` -------------------------------- ### Create Sort with Date Callback Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/dates/content.svx Use the `table.createSort` method with a callback to sort date fields by their ISO String representation. ```javascript const sort = table.createSort(row => new Date(row.created_at).toISOString()) ``` -------------------------------- ### Create a Record Filter in Svelte Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.createRecordFilter.md Demonstrates how to use the createRecordFilter method to create a filter for a list of distinct values in a Svelte component. This is useful for interactive filtering of data displayed in lists or tables. ```svelte
    {#each filter.records as record}
  • {record.value} - {record.count}
  • {/each}
``` -------------------------------- ### Calculate Distinct Values and Counts Source: https://github.com/vincjo/datatables/blob/main/src/routes/examples/client/distinct/code.svx This snippet demonstrates how to create a calculation to find distinct values and their counts for a specific column ('make'). It then iterates over the results to display each distinct value and its occurrence count. ```svelte
    {#each distinct as { value, count }}
  • {value} has {count} occurrences
  • {/each}
``` -------------------------------- ### getView() Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.getView.md Retrieves the view instance from a remote component. This method is useful for accessing component views without prop drilling. ```APIDOC ## getView() ### Description Retrieves the view instance from a remote component without the need of passing props. ### Method `getView()` ### Usage ```ts table.getView() ``` ``` -------------------------------- ### Display Calculation Bounds Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/bounds/code.svx Renders the minimum and maximum bounds obtained from a calculation into an unordered list in Svelte. ```svelte
  • Minimum value: {min}
  • Maximum value: {max}
``` -------------------------------- ### Configure i18n for TableHandler Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/i18n/doc.svx Instantiate TableHandler with custom i18n strings for UI elements like search, pagination, and row counts. This is useful for localizing the datatable interface. ```typescript import { TableHandler } from '@vincjo/datatables' const table = new TableHandler(data, { rowsPerPage: 10, i18n: { search: 'Rechercher...', show: 'Afficher', entries: 'lignes', filter: 'Filtrer', rowCount: 'Lignes {start} à {end} sur {total}', noRows: 'Aucun résultat', previous: 'Précédent', next: 'Suivant' } }) ``` -------------------------------- ### Bind Input and Trigger Regex Search Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/search/regex/content.svx Connects a text input field to the search value and a button to trigger the regex search functionality. Ensure the 'search' object is properly initialized before use. ```svelte ``` -------------------------------- ### Create Filter with StartsWith Check Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/check/content.svx Use the `check.startsWith` function to create a filter that matches values beginning with a specific string. This reduces boilerplate code when defining simple filters. ```typescript import { check } from '@vincjo/datatables' const filter = table.createFilter('last_name', check.startsWith) ``` -------------------------------- ### Initialize Multiple Criteria Filter Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/criteria/content.svx Initializes an advanced filter for a specific column ('priority') using an 'isEqualTo' check. This filter can manage multiple criteria simultaneously. ```typescript const filter = table.createAdvancedFilter('priority', check.isEqualTo) ``` -------------------------------- ### createCSV Method Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.createCSV.md This method generates a CSV representation of the table data. It returns an object with a download method to save the CSV file. ```APIDOC ## createCSV() ### Description Generates a CSV representation of the table data and returns an object with a `download` method. ### Method Signature ```ts createCSV(): CSVExportObject ``` ### Return Value An object with a `download` method. ### Usage Example ```ts const csv = table.createCSV() csv.download('filename.csv') ``` ### Related Methods #### download(filename: string) ##### Description Initiates the download of the generated CSV file with the specified filename. ##### Parameters - **filename** (string) - Required - The name for the downloaded CSV file. ``` -------------------------------- ### getState() Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/server/methods.getState.md Retrieves the current state of the data table. This includes information about the current page, rows per page, offset, search query, sorting configuration, and active filters. ```APIDOC ## getState() ### Description Retrieves the current state of the data table. This includes information about the current page, rows per page, offset, search query, sorting configuration, and active filters. ### Method ```ts table.getState() ``` ### Response #### Success Response - **currentPage** (number) - The current page number. - **rowsPerPage** (number) - The number of rows displayed per page. - **offset** (number) - The current offset for data retrieval. - **search** (string) - The current search query string. - **sort** (object) - An object detailing the current sort configuration. - **field** (string) - The field by which the data is sorted. - **direction** (string) - The direction of the sort ('asc' or 'desc'). - **filters** (array) - An array of filter objects applied to the table. - **field** (string) - The field to which the filter is applied. - **value** (any) - The value of the filter. - **setTotalRows** (function) - A function to set the total number of rows in the table. ``` -------------------------------- ### Displaying Basic Median Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/median/code.svx Renders the calculated median value in an H1 tag. Ensure the `median` variable is correctly computed before display. ```svelte

Median: {median}

``` -------------------------------- ### Create a Text Filter Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/filters/input/content.svx Use `table.createFilter()` to initialize a text filter. This filter can then be bound to an input element. ```typescript const filter = table.createFilter('completed') ``` -------------------------------- ### Select All Rows Checkbox Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/select/all/content.svx This snippet shows a checkbox that reflects the selection state of all rows and allows toggling it. ```svelte table.selectAll()} > ``` -------------------------------- ### Date Field Callback for Sorting Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/dates/content.svx Define a callback function to convert a date string to ISO String format for natural sorting. ```javascript const field = (row) => new Date(row.created_at).toISOString() ``` -------------------------------- ### Enable Row Selection with selectBy Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Instantiate TableHandler with the 'selectBy' option to enable row selection functionality, specifying the unique identifier for rows. ```ts const table = new TableHandler(data, { selectBy: 'id' }) // selectBy param is mandatory to enable row selection at the TableHandler instanciation level. ``` -------------------------------- ### Recursive Search Input and Button Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/search/recursive/content.svx Bind an input field to the search value and trigger a recursive search with a button click. ```svelte ``` -------------------------------- ### Update Import Path Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/migration/content.svx Modify import paths from '@vincjo/datatables/remote' to '@vincjo/datatables/legacy/remote' for progressive upgrades. ```diff - @vincjo/datatables/remote + @vincjo/datatables/legacy/remote ``` -------------------------------- ### Displaying Row Count Information Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/row-count/content.svx Render the derived row count data into a user-friendly string. This is typically used in a pagination component. ```svelte

Showing {start} to {end} of {total} rows

``` -------------------------------- ### setPage Method Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.setPage.md The setPage method allows users to navigate to a specific page, the previous or next page, or the last page of the table. It accepts a page number (integer) or a string representing the desired navigation action. ```APIDOC ## setPage Method ### Description Navigates the table to a specified page. ### Method Signature `setPage(page: number | 'previous' | 'next' | 'last'): void` ### Parameters - **page** (number | 'previous' | 'next' | 'last') - Required - The target page to navigate to. Can be a specific page number (e.g., 5), or a string indicating relative or boundary navigation ('previous', 'next', 'last'). ### Usage Examples ```ts table.setPage(5) // Navigates to page 5. table.setPage('previous') // Navigates to the previous page. table.setPage('next') // Navigates to the next page. table.setPage('last') // Navigates to the last page. ``` ``` -------------------------------- ### Create Sort Instance Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/sort/button/content.svx Instantiate a sort object for a specific column named 'name'. This object will manage sorting state and actions. ```typescript const sort = table.createSort('name') ``` -------------------------------- ### Import Check Utility Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/check/content2.svx Import the `check` function from the @vincjo/datatables library to utilize its filtering capabilities. ```typescript import { check } from '@vincjo/datatables' ``` -------------------------------- ### Displaying a Loading Spinner with isLoading State Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/data/is-loading/content.svx Use the `isLoading` state property to conditionally show a loading spinner. The spinner is displayed when `table.isLoading` is true. ```svelte
[...]
``` -------------------------------- ### Create Record Filter Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/add-on/record-filter/content.svx Creates a new record filter instance. Use this to initialize filtering capabilities for your table. ```typescript const filter = table.createRecordFilter(distinct) ``` -------------------------------- ### Create a Scoped Search Filter Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/methods.createSearch.md Initializes a search filter that is limited to specific fields. Use this to restrict search input to only affect designated columns, improving search precision. ```typescript const search = table.createSearch(['last_name', 'first_name']) ``` -------------------------------- ### Advanced Sum Calculation with Custom Logic Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/sum/code.svx Shows how to perform an advanced sum calculation by defining custom logic to calculate area from 'width' and 'length' and converting it to yd². Use this for complex aggregations requiring row data. ```typescript // calc area from 'width' and 'length' row props and conversion to yd² const calc = table.createCalculation(({ width, length }) => width * length * 1.196) const sum = $derived(calc.sum({ precision: 3 })) ``` ```html

Total area: {sum} yd²

``` -------------------------------- ### Advanced Average Calculation with Custom Logic Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/avg/code.svx Perform an average calculation based on custom row properties ('width', 'length') and unit conversion. It demonstrates how to define a calculation function and control the output precision. ```typescript // calc area from 'width' and 'length' row props and conversion to yd² const calc = table.createCalculation(({ width, length }) => width * length * 1.196) const avg = $derived(calc.avg({ precision: 3 })) ``` ```svelte

Average area: {$avg} yd²

``` -------------------------------- ### Svelte Datatable Markup Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/hello-world/content.svx Integrates the server-side TableHandler with Svelte components to render a sortable and paginatable table. Includes custom header and footer snippets for UI controls. ```svelte {#snippet header()}
{/snippet} IDNameEmailComment {#each table.rows as row} {/each}
{row.id} {row.name} {row.email}

{row.body.substring(0, 60) + '...'}

{#snippet footer()} {/snippet}
``` -------------------------------- ### Render Page Numbers with Ellipsis Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/pagination/pages/content.svx Use `table.pagesWithEllipsis` to render page numbers, automatically including ellipsis ('...') for large sets of pages. This improves user experience by not overwhelming them with too many page links. ```svelte {#each table.pagesWithEllipsis as page} {/each} ``` -------------------------------- ### Migrate from v1 to v2 Source: https://github.com/vincjo/datatables/blob/main/README.md Update import paths to migrate from v1 to v2 of the datatables package. This allows for progressive upgrades. ```diff - @vincjo/datatables + @vincjo/datatables/legacy - @vincjo/datatables/remote + @vincjo/datatables/legacy/remote ``` -------------------------------- ### Create Sort Instance Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/sort/button/content.svx Instantiate a sort handler for a specific table field. ```typescript const sort = table.createSort('last_name') ``` -------------------------------- ### Enable Highlighting in TableHandler Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/filters/highlight/content.svx Set 'highlight' to true in the TableHandler constructor to add `` tags around matching string or number values. Requires {@html} in templates. ```typescript const table = new TableHandler(data, { highlight: true }) ``` -------------------------------- ### createCalculation Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/client/methods.createCalculation.md Applies calculations on specific columns of the table. This method returns a chainable object that allows for various aggregate functions to be applied. ```APIDOC ## createCalculation ### Description Creates a calculation object for a specified column, allowing for aggregate functions like distinct count, average, sum, median, and bounds. ### Method `table.createCalculation(columnName)` ### Parameters #### Path Parameters - **columnName** (string) - Required - The name of the column on which to perform calculations. ### Available Calculations - **distinct()**: Returns the count of distinct values in the column. - **avg()**: Returns the average value of the column. - **sum()**: Returns the sum of values in the column. - **median()**: Returns the median value of the column. - **bound()**: Returns the bounds (minimum and maximum) of the values in the column. ### Usage Examples ```javascript table.createCalculation('price').distinct() table.createCalculation('price').avg() table.createCalculation('price').sum() table.createCalculation('price').median() table.createCalculation('price').bound() ``` ``` -------------------------------- ### Server-Side Table Handler Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/hello-world/content.svx Initializes a TableHandler for server-side data. It defines how to load data based on the current state (pagination, sorting) and invalidates the table to trigger a refresh. ```typescript import { TableHandler, type State } from '@vincjo/datatables/server' const table = new TableHandler([], { rowsPerPage: 5, totalRows: 500 }) table.load((state: State) => { const { currentPage, rowsPerPage, sort } = state let params = `_page=${currentPage}` if (rowsPerPage) params += `&_limit=${rowsPerPage}` if (sort) params += `&_sort=${sort.field}&_order=${sort.direction}` const response = await fetch(`https://jsonplaceholder.typicode.com/comments?${params}`) return response.json() }) table.invalidate() ``` -------------------------------- ### Configure Row Selection by ID Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/select/row/content.svx To enable row selection, ensure your data has a unique 'id' field and configure `TableHandler` with the `selectBy` option set to 'id'. ```typescript const table = new TableHandler(data, { selectBy: 'id' }) ``` -------------------------------- ### Checkbox for All Selected State Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.isAllSelected.md Use this snippet to bind a checkbox to the `isAllSelected` property of the table. Clicking the checkbox calls the `selectAll` function. ```svelte table.selectAll()} /> ``` -------------------------------- ### Displaying Table Rows in Svelte Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.rows.md Iterates over the `table.rows` array to render each row's data within `` elements. Assumes `table.rows` is an array of objects, each containing properties like `first_name`, `last_name`, and `address`. ```svelte {#each table.rows as row} {row.first_name} {row.last_name} {row.address} {/each} ``` -------------------------------- ### Row Selection Checkbox and Styling in Svelte Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/getting-started/migration/content.svx Svelte code for rendering a table row with a checkbox for selection, dynamically applying an 'active' class based on selection state and handling selection events. ```svelte table.select(row.id)}> ``` -------------------------------- ### Record Filter Input and Display Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/add-on/record-filter/content.svx Binds an input element's value to the filter and displays the filtered records. The filter is updated on input. ```svelte filter.set()}>
    {#each filter.records as record}
  • {record.count} {record.value}
  • {/each}
``` -------------------------------- ### Server-Side Datatable Integration Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/server/getting-started/intro/content.svx Integrates server-side data fetching and manipulation into a Svelte Datatable component. Ensure all necessary imports are correctly placed under '@vincjo/datatables/server'. ```svelte First NameLast NameEmail {#each table.rows as row} {/each}
{row.first_name} {row.last_name} {row.email}
``` -------------------------------- ### Basic Median Calculation Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/median/code.svx Calculate the median of a specific column. Use this for simple aggregations on existing data columns. ```typescript const median = $derived(table.createCalculation('price').median()) ``` -------------------------------- ### Accessing Page Numbers Source: https://github.com/vincjo/datatables/blob/main/static/documents/markdown/properties.pages.md Log the current page numbers and page numbers with ellipsis to the console. This is useful for debugging or displaying pagination information. ```typescript console.log(table.pages) console.log(table.pagesWithEllipsis) ``` -------------------------------- ### Basic Distinct Calculation Source: https://github.com/vincjo/datatables/blob/main/src/routes/docs/client/calculation/distinct/code.svx Calculates distinct values from the 'make' column and sorts them by count in descending order. Use this for simple distinct value retrieval. ```typescript const distinct = $derived.by(() => { return table.createCalculation('make').distinct({ sort: ['count', 'desc'] }) }) ```