2.0.5 • Published 2 months ago

data-grid-component v2.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

Data Grid Web Component

NPM Downloads

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.

NameTypeDescription
idStringCustom id for the grid
urlStringAn URL with data to display in JSON format
debugBooleanLog actions in DevTools console
filterBooleanAllows a filtering functionality
sortBooleanAllows a sort by column functionality
defaultSortStringDefault sort field if sorting is enabled
serverBooleanIs a server side powered grid
serverParamsServerParamsDescribe keys passed to the server backend
dirStringDir
perPageValuesArrayAvailable per page options
hidePerPageBooleanHides the page size select element
columnsArray.<Column>Available columns
defaultPageNumberStarting page
perPageNumberNumber of records displayed per page (page size)
expandBooleanAllow cell content to spawn over multiple lines
actionsArray.<Action>Row actions (RowActions module)
collapseActionsBooleanGroup actions (RowActions module)
resizableBooleanMake columns resizable (ColumnResizer module)
selectableBooleanAllow selecting rows with a checkbox (SelectableRows module)
selectVisibleOnlyBooleanSelect all only selects visible rows (SelectableRows module)
autosizeBooleanCompute column sizes based on given data (Autosize module)
autoheightBooleanAdjust height so that it matches table size (FixedHeight module)
autohidePagerBooleanauto-hides the pager when number of records falls below the selected page size
menuBooleanRight click menu on column headers (ContextMenu module)
reorderBooleanAllows a column reordering functionality (DraggableHeaders module)
responsiveBooleanChange display mode on small screens (ResponsiveGrid module)
responsiveToggleBooleanShow toggle column (ResponsiveGrid module)
filterOnEnterBooleanToggles the ability to filter column data by pressing the Enter or Return key
spinnerClassStringSets a space-delimited string of css class(es) for a spinner (use spinner-border css class for bootstrap 5 spinner)

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.

NameTypeDescription
fieldStringthe key in the data
titleStringthe title to display in the header (defaults to "field" if not set)
widthNumberthe width of the column (auto otherwise)
classStringclass to set on the column (target body or header with th.class or td.class)
attrStringdon't render the column and set a matching attribute on the row with the value of the field
hiddenBooleanhide the column
noSortBooleanallow disabling sort for a given column
formatString | functioncustom data formatting, either by a string of HTML template or by a function with an object parameter consisting of column, rowData, cellData, td, tr.
transformStringcustom value transformation
editableBooleanreplace with input (EditableColumn module)
responsiveNumberthe higher the value, the sooner it will be hidden, disable with 0 (ResponsiveGrid module)
responsiveHiddenBooleanhidden through responsive module (ResponsiveGrid module)
filterTypeStringdefines a filter field type ("text" or "select" - defaults to "text")
filterListArraydefines a custom array to populate a filter select field in the format of [{value: "", text: ""},...].When defined, it overrides the default behaviour where the filter select elements are populated by the unique values from the corresponding column records.
firstFilterOptionObjectdefines an object for the first option element of the filter select field. defaults to {value: "", text: ""}

Action

NameTypeDescription
titleStringthe title of the button
nameStringthe name of the action
classStringthe class for the button
urlStringlink for the action
htmlStringcustom button data
confirmBooleanneeds confirmation
defaultBooleanis 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.

NameTypeDescription
ColumnResizerColumnResizerresize handlers in the headers
ContextMenuContextMenumenu to show/hide columns
DraggableHeadersDraggableHeadersdraggable headers columns
EditableColumnEditableColumndraggable headers columns
TouchSupportTouchSupporttouch swipe
SelectableRowsSelectableRowscreate a column with checkboxes to select rows
FixedHeightFixedHeightallows having fixed height tables
AutosizeColumnAutosizeColumncompute ideal width based on column content
ResponsiveGridResponsiveGridhide/show column on the fly
RowActionsRowActionsadd action on rows
SpinnerSupportSpinnerSupportinserts a spinning icon element to indicate grid loading.

ServerParams

NameType
serverParams.startString
serverParams.lengthString
serverParams.searchString
serverParams.sortString
serverParams.sortDirString
serverParams.dataKeyString
serverParams.metaKeyString
serverParams.metaTotalKeyString
serverParams.metaFilteredKeyString
serverParams.optionsKeyString
serverParams.paramsKeyString

Other attributes

OptionRequiredTypeDefaultDescription
stickyNoBooleanfalseSticky headers
pageNoNumber1Current 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>
NameType
itemsPerPageString
gotoPageString
gotoFirstPageString
gotoPrevPageString
gotoNextPageString
gotoLastPageString
ofString
itemsString
resizeColumnString
noDataString
areYouSureString
networkErrorString

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

NameDescription
getFirstgoes to first page
getLastgoes to last page
getPrevgoes to previous page
getNextgoes to next page
getSelectiongets selected data
clearDataclears loaded data
preloadpreloads the data intended to bypass the initial fetch operation, allowing for faster intial page load time.
refreshclears and reloads data from url
reloadreloads data from url
clearFilterclears current filters
addRowadds a new row
removeRowremoves a row
getDatagets data

Events

NameTrigger
editA row is edited
actionAn action is performed
connectedThe grid is connected
disconnectedThe grid is disconnected
columnResizedA column is resized
columnVisibilityA column is hidden/shown
columnReorderedA column is dragged
rowsSelectedAny or all rows are selected
headerRenderedColumn header (thead) render is complete
bodyRenderedTable 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.

2.0.5

2 months ago

2.0.3

10 months ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.5.1

2 years ago

1.5.0

2 years ago

1.2.0

2 years ago

1.1.0

2 years ago

1.4.3

2 years ago

1.4.2

2 years ago

1.4.1

2 years ago

1.4.0

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago