data-grid-component
v2.0.9
Published
Standalone data grid web component
Downloads
85
Readme
Data Grid Web Component
Autonomous open source grid component with RTL support. Designed for server side paginated content but also work for basic tables.
Key features:
- Server side support
- Inline editing
- Sorting/filtering
- i18n friendly
- Easily themable
How to use
Installation
- Install with npm
$ npm install data-grid-component
Initialization
- HTML way
<data-grid data-url="data.json"></data-grid>
<script type="module" src="./data-grid.js"></script>
Grid customizations are possible via attributes.
- using the DOM API
<script type="module" src="./data-grid.js"></script>
<script>
const grid = document.createElement("data-grid");
grid.dataset.url = "data.json"; // Use setAttribute on existing instance to trigger reload
document.body.appendChild(grid);
</script>
- using the constructor
<script type="module">
import { DataGrid } from "./data-grid.js";
const grid = new DataGrid({
url: "data.json",
});
document.body.appendChild(grid);
</script>
Styling
Data Grid inherits wherever possible from Bootstrap 5 styles (including dark mode support).
You can also override the following variables (see _core.scss).
data-grid {
--padding: 0.5rem;
--header-scale: 1.5;
--color-rgb: var(--bs-primary-rgb, 13, 110, 253);
--color: rgb(var(--color-rgb));
--highlight-color: #fffcee;
--header-background: var(--bs-gray-200, #e9ecef);
--header-color: var(--bs-dark, #212529);
--btn-background: var(--white, #ffffff);
--btn-color: var(--color);
--body-color: var(--bs-body-color, #212529);
}
Options attributes
These are the options accessibles through the components data attributes. Some options only work if the proper plugin is loaded. You can also pass them as a json string in data-config.
| Name | Type | Description | |---------------------|----------------------------------------------|--------------------------------------------------------------------------------| | id | String | Custom id for the grid | | url | String | An URL with data to display in JSON format | | debug | Boolean | Log actions in DevTools console | | filter | Boolean | Allows a filtering functionality | | sort | Boolean | Allows a sort by column functionality | | defaultSort | String | Default sort field if sorting is enabled | | server | Boolean | Is a server side powered grid | | serverParams | ServerParams | Describe keys passed to the server backend | | dir | String | Dir | | perPageValues | Array | Available per page options | | hidePerPage | Boolean | Hides the page size select element | | columns | Array.<Column> | Available columns | | defaultPage | Number | Starting page | | perPage | Number | Number of records displayed per page (page size) | | expand | Boolean | Allow cell content to spawn over multiple lines | | actions | Array.<Action> | Row actions (RowActions module) | | collapseActions | Boolean | Group actions (RowActions module) | | resizable | Boolean | Make columns resizable (ColumnResizer module) | | selectable | Boolean | Allow selecting rows with a checkbox (SelectableRows module) | | selectVisibleOnly | Boolean | Select all only selects visible rows (SelectableRows module) | | autosize | Boolean | Compute column sizes based on given data (Autosize module) | | autoheight | Boolean | Adjust height so that it matches table size (FixedHeight module) | | autohidePager | Boolean | auto-hides the pager when number of records falls below the selected page size | | menu | Boolean | Right click menu on column headers (ContextMenu module) | | reorder | Boolean | Allows a column reordering functionality (DraggableHeaders module) | | responsive | Boolean | Change display mode on small screens (ResponsiveGrid module) | | responsiveToggle | Boolean | Show toggle column (ResponsiveGrid module) | | filterOnEnter | Boolean | Toggles the ability to filter column data by pressing the Enter or Return key | | spinnerClass | String | Sets a space-delimited string of css classes for a spinner | | filterKeypressDelay | Number | Sets a keypress delay time in milliseconds before triggering filter operation. | | saveState | Boolean | Enable/disable save state plugin (SaveState module) |
Column
When using the response data or the JS api, you have the opportunity to pass column definitions. This scenario is not supported using regular attributes to avoid cluttering the node with a very large attribute.
| Name | Type | Description | |----------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------| | field | String | the key in the data | | title | String | the title to display in the header (defaults to "field" if not set) | | [width] | Number | the width of the column (auto otherwise) | | [class] | String | class to set on the column (target body or header with th.class or td.class) | | [attr] | String | don't render the column and set a matching attribute on the row with the value of the field | | [hidden] | Boolean | hide the column | | [noSort] | Boolean | allow disabling sort for a given column | | [format] | String | function | custom data formatting | | [defaultFormatValue] | String | default value to use for formatting | | [transform] | String | custom value transformation | | [editable] | Boolean | replace with input (EditableColumn module) | | [editableType] | String | type of input (EditableColumn module) | | [responsive] | Number | the higher the value, the sooner it will be hidden, disable with 0 (ResponsiveGrid module) | | [responsiveHidden] | Boolean | hidden through responsive module (ResponsiveGrid module) | | [filterType] | String | defines a filter field type ("text" or "select" - defaults to "text") | | [filterList] | Array | defines a custom array to populate a filter select field in the format of [{value: "", text: ""},...] | | [firstFilterOption] | Object | defines an object for the first option element of the filter select field. defaults to {value: "", text: ""} |
Action
| Name | Type | Description | |---------|----------------------|---------------------------| | title | String | the title of the button | | name | String | the name of the action | | class | String | the class for the button | | url | String | link for the action | | html | String | custom button data | | confirm | Boolean | needs confirmation | | default | Boolean | is the default row action |
Plugins
Some features have been extracted as plugins to make base class lighter. You can
find them in the plugins
directory.
| Name | Type | Description | |--------------------|----------------------------------------------------|-----------------------------------------------------------| | [ColumnResizer] | ColumnResizer | resize handlers in the headers | | [ContextMenu] | ContextMenu | menu to show/hide columns | | [DraggableHeaders] | DraggableHeaders | draggable headers columns | | [EditableColumn] | EditableColumn | draggable headers columns | | [TouchSupport] | TouchSupport | touch swipe | | [SelectableRows] | SelectableRows | create a column with checkboxes to select rows | | [FixedHeight] | FixedHeight | allows having fixed height tables | | [AutosizeColumn] | AutosizeColumn | compute ideal width based on column content | | [ResponsiveGrid] | ResponsiveGrid | hide/show column on the fly | | [RowActions] | RowActions | add action on rows | | [SpinnerSupport] | SpinnerSupport | inserts a spinning icon element to indicate grid loading. | | [SaveState] | SaveState | stores grid filter, sort, and paging |
ServerParams
| Name | Type | |------------------------------|---------------------| | serverParams.start | String | | serverParams.length | String | | serverParams.search | String | | serverParams.sort | String | | serverParams.sortDir | String | | serverParams.dataKey | String | | serverParams.metaKey | String | | serverParams.metaTotalKey | String | | serverParams.metaFilteredKey | String | | serverParams.optionsKey | String | | serverParams.paramsKey | String |
Other attributes
| Option | Required | Type | Default | Description | |------------|:--------:|---------|-----------|----------------| | sticky | No | Boolean | false | Sticky headers | | page | No | Number | 1 | Current page |
Responsive
This table provide two ways for responsive data.
- A solution based on resizeObserver that will show/hide columns as needed (TODO: display collapsed content with a toggle)
- A CSS Only solution based on media queries that will change the layout on smaller screens
Translations
You can use when defined to set your own translations with setLabels
<script type="module">
customElements.whenDefined("data-grid").then(() => {
customElements.get("data-grid").setLabels({
items: "rows",
});
});
</script>
| Name | Type | |---------------|---------------------| | itemsPerPage | String | | gotoPage | String | | gotoFirstPage | String | | gotoPrevPage | String | | gotoNextPage | String | | gotoLastPage | String | | of | String | | items | String | | resizeColumn | String | | noData | String | | areYouSure | String | | networkError | String |
Actions
Define your actions as part of the options
...
"actions": [
{
"name": "edit"
},
{
"name": "delete",
"class": "is-danger",
"url": "/delete/{id}"
}
],
...
Then simply listen to them
document.getElementById("demo2-grid").addEventListener("action", (ev) => {
// It contains data and action
console.log(ev.detail);
});
You can add:
- class: custom class
- url: a formaction will be set (data between {} is interpolated)
- title: a custom title
- html: custom html for the button (in order to provide icons, etc)
Inline editing
Set your column as editable
...
{
"field": "email",
"title": "Email",
"width": 200,
"editable": true
},
Then simply listen to changes
document.getElementById("demo2-grid").addEventListener("edit", (ev) => {
// It contains data and value
console.log(ev.detail);
});
You can check demo-server.html
to get a sample usage with saving functionnality
Api
| Name | Description | |------------------|--------------------------------------------------------------------------------------------------------------| | getFirst | goes to first page | | getLast | goes to last page | | getPrev | goes to previous page | | getNext | goes to next page | | getSelection | gets selected data | | clearData | clears loaded data | | preload | preloads the data intended to bypass the initial fetch operation, allowing for faster intial page load time. | | refresh | clears and reloads data from url | | reload | reloads data from url | | clearFilter | clears current filters | | addRow | adds a new row | | removeRow | removes a row | | getData | gets data | | sortAsc | sorts data by column name in ascending order | | sortDesc | sorts data by column name in descending order | | sortNone | resets column sort state |
Events
| Name | Trigger | |----------------------|------------------------------------------| | edit | A row is edited | | action | An action is performed | | connected | The grid is connected | | disconnected | The grid is disconnected | | columnResized | A column is resized | | columnVisibility | A column is hidden/shown | | columnReordered | A column is dragged | | rowsSelected | Any or all rows are selected | | headerRendered | Column header (thead) render is complete | | bodyRendered | Table body (tbody) render is complete |
Server
For large data set, you may need to use the pagination or filtering on the server.
It works just the same way except the response should return a a meta
key with
- total: the total (unfiltered) number of rows (info only).
- filtered: the total value of rows matching the current filter (used for pagination).
Server parameters are sent as query string and are start
, length
and search
.
To enable server mode, use server=true
. These can be changed to your own server
settings with the serverParams
option object.
You can check demo/server.html
and demo-server.php
for an example.
Demo
This way -> https://codepen.io/lekoalabe/pen/NWvLByP
Browser Support
Only modern browsers (anything that supports js modules)
Credits
This component is heavily inspired by https://github.com/riverside/zino-grid
License
data-grid-component is licensed under the MIT license.