--- url: https://akinozgen.github.io/datagrids/guide/getting-started.md description: >- Install datagrids, load the stylesheet, turn a table into a grid, then point it at a server endpoint. --- # Getting started datagrids turns a plain `` into a sortable, searchable, paged grid. It has no runtime dependencies, works with any framework (or none), and keeps the table you gave it: `destroy()` hands it back exactly as it was. ## Install ::: code-group ```sh [npm] npm i @akinozgen17/datagrids ``` ```sh [pnpm] pnpm add @akinozgen17/datagrids ``` ```sh [yarn] yarn add @akinozgen17/datagrids ``` ::: ```js import { Datagrid, column } from "@akinozgen17/datagrids"; import "@akinozgen17/datagrids/css"; ``` The stylesheet is required: without it the grid has no layout. It contains the design tokens and every module's styles in one file. If you only want the tokens (to theme your own markup with the same values), import `@akinozgen17/datagrids/css/tokens`. ### Without a bundler The package ships an IIFE build that exposes everything on `window.Datagrids`: ```html ``` Pin a version in production (`@akinozgen17/datagrids@0.1.0/dist/…`). ## Your first grid A grid is a table plus columns. Everything else — data sources, buttons, export, saved state — is a [module](/guide/concepts#modules) you attach with `use`. ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; new Datagrid("#first-grid", { label: "Field agents", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], data: agents(120), sort: [["date", "desc"]], pageSize: 10, }); ``` ```html [HTML]
``` ::: What you get without asking: * **Search** across searchable columns, accent- and case-insensitive (`isik` finds `Işık`). * **Sorting** on every typed column, with a permanent sort icon and `aria-sort` on the header. * **Paging** with a page-size menu, a page jump field and a "1–10 / 120 records" summary. * **Typed cells**: money and dates are formatted, right-aligned where it matters, and exported as real numbers and dates later. * **Accessibility**: a native ``, header buttons, a "Skip table" link and polite announcements for search results and page changes. ::: tip Give every grid a name `label` (or `labelledBy`, or a ``, adopts the existing `` elements (cell HTML, links and widgets survive) and runs search, sort and paging in the browser. ```html
`) is the grid's accessible name. Without one you get the [DG002](/errors/DG002) warning in the console. ::: ## Enhance an existing table If the server already renders the rows, don't pass `columns` or `data`: datagrids reads `
Unit inventory
Code Item Qty
INV-001Green Herb42
INV-002Red Herb7
``` See [Data sources → DOM](/guide/data-sources#dom-progressive-enhancement) for the `data-dg-*` header attributes. ## Point it at a server Large lists page on the server. Attach a `serverSide` source with the protocol your endpoint speaks. This one talks to a Laravel controller that returns [yajra/laravel-datatables](https://yajrabox.com/docs/laravel-datatables) JSON — the demo server runs inside this page, so open the **Request** and **Response** tabs to see the exact wire format. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; new Datagrid("#first-server", { label: "Field agents", columns: [ column.index(), // plain columns follow the protocol: yajra escapes strings on the server, so they render as HTML { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date", time: true }), ], sort: [["date", "desc"]], pageSize: 10, use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true })], }); ``` ```html [HTML]
``` ::: The endpoint receives the classic `draw/start/length/search/order/columns[]` form body and never needs to change. See [Server protocols](/guide/server-protocols) for the other two protocols (Laravel's paginator JSON and the datagrids protocol). ## Next steps * [Concepts](/guide/concepts): grid, columns, modules, pipelines — read this before anything else. * [Columns](/guide/columns): typed factories, HTML opt-in, export values. * [Modules](/modules/): saved state, column menu, selection, row actions, export… * Coming from another grid library? [Migration](/migration/from-datatables). --- --- url: https://akinozgen.github.io/datagrids/guide/concepts.md description: >- The mental model behind datagrids — a small grid core, typed columns, and independent modules that plug into well-defined pipelines. --- # Concepts: grid, columns, modules, pipelines datagrids has no giant options object. A grid is **a table plus columns**. Everything else — where the rows come from, buttons, saved state, selection, export — is a **module** you create on its own and attach with `use`. Modules plug into a handful of **pipelines** whose order is documented. ::: code-group ```js [JavaScript] import { Datagrid, column, colVis, stateSave, button } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const out = document.querySelector("#guide-concepts-log"); const log = (line) => (out.textContent = line + "\n" + out.textContent); // columns: what to show and how const columns = [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.date("date", { title: "Date" }), ]; // modules: immutable definitions, attached per grid const grid = new Datagrid("#guide-concepts", { label: "Agents", columns, data: agents(80), pageSize: 5, use: [colVis(), button.reload(), stateSave()], }); // events: react to what happened grid.on("sort", ({ sort }) => log(`sort → ${sort.map((s) => s.key + " " + s.dir).join(", ")}`)); grid.on("search", ({ search }) => log(`search → "${search}"`)); grid.on("page", ({ page }) => log(`page → ${page}`)); grid.on("columnchange", ({ columns }) => log(`columnchange → ${columns.filter((c) => c.visible).length} visible`)); ``` ```html [HTML]
Sort, search, page or hide a column…
``` ::: ## The grid ```js const grid = new Datagrid("#agents", { label: "Agents", columns, use: [/* modules */] }); ``` * **One instance per ``.** The constructor wraps the table you pass (by element or by a selector that matches exactly one table) and keeps its identity: your event listeners and references stay valid. Constructing again on the same table returns the existing grid. * **`Datagrid.get(table)` returns the instance or `null`.** It never creates a grid as a side effect. Grids with a `name` can also be found with `find(name)` and reloaded with `reload(name)`. * **Loading is explicit:** `load: "eager"` (default), `"visible"` (first request when the grid scrolls into view or its tab opens) or `"manual"` (a "Load" button / `grid.load()`). See [Lifecycle](/guide/lifecycle). * **Methods work immediately.** There is no async init: `grid.search("jill")` right after the constructor is fine. * **`destroy()` restores the original table** — classes, attributes, ``, rows — so you can re-initialize safely. The grid core owns searching, sorting, paging, the pager, the loading/empty/error states, the live region and the toolbar slots. Everything else is a module. ## Columns ```js const columns = [ column.text("name", { title: "Name" }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date", time: true }), column.html("notes", { title: "Notes", sortable: false }), // explicit HTML opt-in ]; ``` Typed factories (`column.text`, `number`, `money`, `date`, `badge`, `link`, `phone`, `html`, `index`, `select`, `actions`) know how to render, align, sort, search and export their value. A money column sorts numerically, right-aligns, renders `1,234.50 $` and exports a real number to Excel. **Cells are text by default; HTML is an explicit opt-in** (`column.html()` or `html: true`). The one exception is a protocol whose server already escapes values — see [Columns](/guide/columns#text-and-html). ## Modules ```js import { serverSide, yajra, stateSave, colVis, excel } from "@akinozgen17/datagrids"; const source = serverSide({ url: "/agents/data", protocol: yajra(), csrf: true }); new Datagrid("#agents", { label: "Agents", columns, use: [source, stateSave(), colVis(), excel()], }); ``` * **A module is an immutable definition** created by a factory (`stateSave({ ttl })`). It carries its own options and is set up per grid, so one definition can serve many grids. * **Attach modules with `use: [...]`** in the options. Arrays nest, so a **preset** is just an array: `use: [listPage("/agents/data"), selection()]`. You can also attach later with `grid.use(module)` (a data source attached this way replaces the default one; see [Gotchas](#gotchas)). * **What a module adds appears on the grid** under its name: `grid.state.reset()`, `grid.selection.payload()`, `grid.excel.download()`. In TypeScript use `grid.module(stateSave)` for a typed handle. * **Modules you don't import are not in your bundle.** The core does not know about any module. * **Wiring mistakes throw.** A module that `requires` another one that is missing ([DG007](/errors/DG007)), two data sources ([DG008](/errors/DG008)) or the same module twice ([DG009](/errors/DG009)) throw an `Error` instead of half-working. * **`can: false`** on any module is the permission flag: the module is attached but contributes nothing (no button, no menu item). It only manages visibility — your endpoints still authorize. See the [module catalog](/modules/). ### Data sources are modules too Exactly one module fills the `source` slot. When you attach none, the grid picks one for you: an array source when you pass `data: [...]`, a DOM source when the `` already has rows, otherwise an empty array. | Source | Mode | Use it for | |---|---|---| | `data: [...]` / `arraySource(rows)` | client | rows you already have | | `domSource()` (automatic) | client | enhancing a server-rendered table | | `fetchAll({ url })` | client | one JSON request, then search/sort/page locally | | `serverSide({ url, protocol })` | server | paging, sorting and searching on the server | | `customSource({ mode, load })` | either | anything else (GraphQL, IndexedDB, …) | ## Pipelines Modules don't patch the grid. They contribute to named pipelines through the context they receive in `setup(ctx)`: ```text user action ─► state change ─► beforeLoad (cancelable) ─► request middleware chain ─► protocol encode ─► fetch ─► protocol decode ─► response / load events ─► render rows ─► row mutators ─► render event ``` | Pipeline | Runs | Contributed with | Used by | |---|---|---|---| | request | before every server request | `ctx.request((req, next) => next(req), "pre" \| "post")` | CSRF, Laravel headers, filterPanel, softDeletes | | row | after a row is rendered | `ctx.row((tr, row, key) => …)` | selection, actions, softDeletes; grid options `rowClass`, `rowAttrs`, `rowTone` | | toolbar | at setup | `ctx.toolbar({ slot: "start" \| "end" \| "filters", order, el })` | colVis, export menu, buttons, column filter chips | | state | on save and restore | `ctx.state({ key, save, load })` | stateSave collects every contribution | | export | while exporting | column `exportValue`, `exportType`, `exportFormat` | excel, csv, print, footer | | lifecycle | setup, first load, destroy | `setup()` → `{ api, destroy }`, `ctx.ready(fn)` | every module | **Request middleware order** is fixed: the built-ins (`X-Requested-With`, then CSRF) run first, then middleware registered with `"pre"`, then the rest in registration order, then `"post"`. There are no numeric priorities. Each middleware receives a neutral request (`url`, `method`, `headers`, `query`, `params`) and calls `next(req)` once; the protocol turns it into the wire format at the end. See [Writing a module](/reference/modules) for the full context API. ## Events or pipelines? **Use a pipeline to change what happens. Use an event to react to what happened.** ```js grid.on("load", ({ result }) => console.log(result.total)); // react grid.on("beforeSort", (e) => { if (busy) e.cancel(); }); // veto grid.delegate("click", ".open", (e, { row }) => open(row.id)); // row-aware DOM events ``` `on()` returns an unsubscribe function. Events whose name starts with `before` are cancelable. Every event is also dispatched on the grid root as a DOM `CustomEvent` named `dg:`. The full list is in the [events reference](/reference/events). ## Global defaults `configure({ ... })` (on the IIFE build: `Datagrids.configure`) sets host-wide defaults — CSRF, a confirm dialog adapter, a toast adapter, messages, page sizes. It is the only global switch. Most keys are read when a grid is created, so call it first; `errorMode`, `maxPageSize` and `warnings` are read when needed and also reach existing grids that don't set their own ([details](/reference/static#configure)). ```js import { configure } from "@akinozgen17/datagrids"; configure({ csrf: true, notify: (kind, message) => toast[kind](message), confirm: (message, o) => myDialog.ask(message, o), // returns Promise }); ``` ## Gotchas * A data source chained with `grid.use(serverSide(...))` replaces the default source the grid picked; a second explicit source throws [DG008](/errors/DG008). * `remount()` re-creates the grid from its options plus every module attached later with `grid.use()`. * Without the stylesheet the grid has no layout: import `@akinozgen17/datagrids/css`. ## Coming from DataTables? The [migration guide](/migration/from-datatables) maps each DataTables (1.10 / 2.x / 3.x) option, event and API call to its module or method here. --- --- url: https://akinozgen.github.io/datagrids/guide/columns.md description: >- Typed column factories, render functions, the text-by-default rule, export values, widths in CSS and per-column permissions. --- # Columns A column says **what** to show (`key`, or a dotted `data` path) and **how**: render, alignment, sorting, searching and export. The typed factories under the `column` namespace set all of that for common value types; any option can still be overridden. ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const rows = agents(40).map((r) => ({ ...r, // trusted markup from your own code; shown only through column.html() notes: r.status === "cancelled" ? "Cancelled by HQ" : "", })); // a render function may return a Node: build it with DOM APIs (no HTML parsing) const person = (name, row) => { const wrap = document.createElement("div"); wrap.className = "dg-user"; const avatar = document.createElement("span"); avatar.className = "dg-avatar"; avatar.textContent = name.split(" ").map((p) => p[0]).slice(0, 2).join(""); const body = document.createElement("div"); body.className = "dg-user-body"; const link = document.createElement("a"); link.className = "dg-link dg-user-name"; link.href = `#agent-${row.id}`; link.textContent = name; const sub = document.createElement("span"); sub.className = "dg-sub"; sub.textContent = row.unit; body.append(link, sub); wrap.append(avatar, body); return wrap; }; new Datagrid("#guide-columns", { label: "Column types", pageSize: 6, data: rows, columns: [ column.index(), column.text("ref", { title: "Ref", render: (v) => Object.assign(document.createElement("span"), { className: "dg-id", textContent: v }) }), column.text("name", { title: "Agent", render: person, searchText: (v, row) => `${v} ${row.unit}` }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date", time: true }), column.link("place", { title: "Place", href: "/places/{place}" }), column.html("notes", { title: "Notes", sortable: false }), ], }); ``` ```html [HTML]
``` ::: ## Factories ```js import { column } from "@akinozgen17/datagrids"; ``` | Factory | Renders | Sorts | Exports as | Notes | |---|---|---|---|---| | `column.text(key)` | text, always | locale collation | string | forces text even when the source defaults to HTML — don't use it for yajra strings (see [below](#text-and-html)) | | `column.number(key, { decimals, locale, source })` | `.dg-num`, end-aligned, negative in red | numerically | number (`#,##0`) | `source: "number"` (default) reads data strings as machine numbers (`"0.125"`, `"1.500"` from a DECIMAL column = 1.5); `source: "tr"` for formatted text (`"1.234,5"`, `"1.500"` = 1500) | | `column.money(key, { currency, decimals, locale, source })` | `.dg-money` + currency suffix | numerically | number with currency format | `source: "number" \| "tr" \| "html"` reads numbers, formatted strings or server HTML | | `column.date(key, { time, timeZone, locale, source })` | `.dg-date` (+ time) | chronologically | real date | `source: "iso" \| "local" \| "dmy"` | | `column.badge(key, { labels, tones })` | `.dg-chip` with a tone dot | by label | label text | tones: `ok`, `warn`, `bad`, `info`, `neutral`, `muted`, `accent` | | `column.link(key, { href, target })` | `a.dg-link` | as text | text | `href: "/agents/{id}"` (values URL-encoded) or a function; only http(s), relative, `#`, `mailto:` and `tel:` URLs render as links | | `column.html(key)` | raw HTML (opt-in) | as text | text with tags stripped | search ignores markup | | `column.phone(key, { country, whatsapp })` | `tel:` link (+ optional WhatsApp link) | as text | text | digits normalized for the link; `country` defaults to `"90"` | | `column.boolean(key, { labels, showFalse })` | `.dg-bool`: ✓/✕ icon + text | false before true | label text | reads `1/0`, `true/false`, `"evet"/"hayır"`, `"yes"/"no"`, `"on"/"off"`; `labels: { true: "Active", false: "Passive" }` (default by page language); `showFalse: false` leaves false cells empty | | `column.index()` | row number (page offset aware) | — | number | not sortable or searchable | | `column.select()` | checkbox column | — | — | placeholder for the [selection](/modules/selection) module | | `column.actions()` | action buttons / menu, sticky end | — | — | placeholder for the [actions](/modules/actions) module | ::: tip Formatting locale `number`, `money` and `date` format with the grid's `locale` unless the column gets its own, and `money` uses `TRY` unless you pass `currency`: `column.money("amount", { currency: "USD", locale: "en-US" })`. ::: Every factory takes the [column options](/reference/columns) as its second argument: ```js column.text("name", { title: "Agent", name: "agents.name", // server-side column name (sent as columns[i][name]) data: "agent.full_name", // dotted path into the row; defaults to the key sortable: true, searchable: true, visible: true, hideable: true, // false: always visible, locked in the column menu exportable: true, align: "start", // "start" | "end" | "center" className: "col-name", defaultContent: "n/a", // shown for null / "" (default: a muted dash) }); ``` ## Render functions ```js column.text("name", { render: (value, row, ctx) => `${value} (${row.unit})`, // string → written as text }); ``` `render(value, row, ctx)` may return a **string or number** (written as text unless the column is HTML), a **DOM Node** (appended as is — build it with DOM APIs), or `null`/`""` (shows `defaultContent` or a muted dash). `ctx` has `row`, `key`, `index` (in the current view), `position` (absolute, page offset included) and the cell `td`. Rendering does not change sorting, searching or export. Override those separately: | Option | Purpose | |---|---| | `value(row)` | compute the cell value instead of reading `data` | | `compare(a, b)` | client-side sort comparator | | `sortKey` | sort by another row field (client mode) | | `searchText(value, row)` | text the search matches against | | `exportValue(row)`, `exportType`, `exportFormat` | what Excel/CSV/print receive | | `labels` | value → label map (badges; used by filters and export) | ## Text and HTML **Cells are text by default; HTML is an explicit opt-in.** A string value or a string returned from `render` is written with `textContent`, so `` shows up as ``. To render HTML, opt in per column: ```js column.html("notes") // raw HTML from the row column.text("notes", { html: true, render }) // a render function that returns markup ``` The default for **untyped** columns (plain `{ key }` objects) comes from the data source: | Source | Untyped columns render | Why | |---|---|---| | `data` / `arraySource`, `fetchAll`, `ssp()`, `dgp()`, `laravelPaginator()` | text | the values are data | | `yajra()` | HTML | yajra/laravel-datatables escapes every non-raw column on the server and sends `rawColumns` as markup | | DOM source (enhanced ``) | the existing cells are adopted untouched | they are already markup | `column.text()` always forces text. That is what you want for raw data — and exactly what you **don't** want for a yajra endpoint, whose strings arrive already escaped (`O'Brien`): written as text, the entities would show. With `yajra()`, leave string columns untyped (`{ key: "name", title: "Name" }`) and use typed factories for numbers, money, dates and badges, which parse the value instead of printing it. ## Widths live in CSS The grid never writes inline widths (one exception: while [virtual rows](/guide/performance#virtual-rows) are on, measured widths are locked in a ``). Size columns with CSS, keyed by `data-key`: ```css #agents th[data-key="ref"] { inline-size: 7rem; } #agents :is(th, td)[data-key="task"] { min-inline-size: 18rem; } ``` Long text wraps by default (`top`-aligned rows); typed values (numbers, money, dates, chips) never wrap. `wrap: false` on the grid keeps every cell on one line; `.dg-clamp` clamps a block to two lines (`--dg-clamp` changes it). ## Cell primitives The stylesheet ships small, themeable building blocks you can return from `render`: | Class | Use | |---|---| | `.dg-id` | monospace identifier pill | | `.dg-link` | link with a permanent underline hint | | `.dg-chip[data-tone]` | status badge (`column.badge` uses it) | | `.dg-user` › `.dg-avatar` + `.dg-user-body` › `.dg-user-name` + `.dg-sub` | person cell | | `.dg-num`, `.dg-money` › `.dg-money-cur`, `.dg-date` › `.dg-date-time` | typed values (bidi-isolated) | | `.dg-phone` | phone number, never wraps | | `.dg-clamp` | clamp to `--dg-clamp` lines | | `.dg-sub` | secondary line | | `.dg-empty-value` | the muted dash for empty cells | ## Permissions and visibility * `can: false` — the column **does not exist**: it is not rendered, not in the column menu, not exported, not saved in state and not sent to the server. Use it for role-based columns (`can: user.isAdmin`). * `visible: false` — the column exists but starts hidden; users can show it from the [column menu](/modules/colvis). Hidden columns are still sent to the server (in definition order). * `hideable: false` — always visible. ## Changing columns at runtime `grid.setColumns(defs)` swaps the column set without destroying the grid: the header is rebuilt, sorts on removed columns are dropped, `columnchange` fires and the data reloads. `grid.setColumnVisible(key, bool)` toggles one column. ## Related * [Column options reference](/reference/columns) * [Export](/modules/export) — how typed columns become real Excel numbers and dates * [Server protocols](/guide/server-protocols) — how columns are sent to the server --- --- url: https://akinozgen.github.io/datagrids/guide/data-sources.md description: >- Client mode (array, existing DOM rows, fetch once) versus server mode (serverSide with a protocol), plus custom sources and row keys. --- # Data sources Every grid has exactly one data source, attached like any other module. The source decides the **mode**: * **client** — all rows are in the browser; search, sort, filters and paging run in memory (Turkish-aware collation and accent-folding search included). * **server** — the server pages, sorts and searches; the grid sends a query per change, keeps only the current page and lets the latest request win (earlier ones are aborted). | Source | Mode | Typical use | |---|---|---| | `data: rows` (shorthand) / `arraySource(rows)` | client | rows you already have | | DOM source (automatic) / `domSource()` | client | a server-rendered `` | | `fetchAll({ url, dataSrc, method, csrf, body })` | client | one JSON request, then local search/sort/paging | | `serverSide({ url, protocol, … })` | server | large lists; see [Server protocols](/guide/server-protocols) | | `customSource({ mode, load })` | either | anything else | If you attach no source, the grid uses `data` when given, otherwise the DOM source when the table already has body rows, otherwise an empty array. ::: tip Chaining works too `new Datagrid(el, { columns }).use(serverSide(...))` replaces the default source the grid picked, as long as no source was given explicitly. A second explicit source throws [DG008](/errors/DG008). ::: ## Arrays ```js new Datagrid("#agents", { label: "Agents", columns, data: rows }); // same as: use: [arraySource(rows)] ``` Change the rows later without re-creating the grid: | Method | Effect | |---|---| | `grid.setData(rows)` | replace every row | | `grid.addRows(rows, { keepPage })` | append (jumps to the last page unless `keepPage`); ignored on a server source | | `grid.removeRow(key)` | remove by row key | | `grid.refreshRow(key, row?)` | re-render one row (optionally with a new object) | ## DOM (progressive enhancement) Give the grid a table that already has rows and nothing else. `` becomes the column list and the existing `` elements are **adopted**, not re-created: cell HTML, links, inputs and event listeners survive. Search, sort and paging run in the browser. ::: code-group ```js [JavaScript] import { Datagrid } from "@akinozgen17/datagrids"; // no columns, no data: becomes the columns, the existing s are adopted const init = () => new Datagrid("#guide-dom", { pageSize: 5 }); init(); document.querySelector("#guide-dom-destroy").addEventListener("click", () => { Datagrid.get("#guide-dom")?.destroy(); // the original table is back, byte for byte }); document.querySelector("#guide-dom-init").addEventListener("click", () => { if (!Datagrid.get("#guide-dom")) init(); // get() returns null; it never creates a grid }); ``` ```html [HTML]
Unit inventory
Code Item Qty Place Note
INV-001Green Herb42Spencer MansionCritical stock
INV-002Red Herb7Raccoon City—
INV-003Ink Ribbon120R.P.D.Record
INV-004First Aid Spray15Light TowerShelf 3
INV-005Blue Herb3Arklay Mountains—
INV-006Umbrella badge1NESTEvidence
INV-007Playing card2Spencer Mansion—
INV-008Flashlight11Rockfort IslandNo battery
``` ::: Header attributes refine each column: | Attribute on `` | Effect | |---|---| | `data-dg-key="qty"` | column key (default: a slug of the header text) | | `data-dg-type="number"` / `"money"` | numeric sorting, end alignment | | `data-dg-sortable="false"` | not sortable | | `data-dg-searchable="false"` | not searched | | `data-dg-visible="false"` | starts hidden | | `data-dg-hideable="false"` | locked in the column menu | | `data-dg-export="false"` | left out of exports | | `data-dg-align="end"` / `"center"` | alignment | On cells, `data-order="42"` gives the value used for sorting and searching instead of the visible text; a row's `id` becomes its key. `destroy()` puts every adopted row back, attributes included. To initialize tables declaratively (``), see [Lifecycle → upgrade()](/guide/lifecycle#declarative-init-upgrade). ## Fetch once `fetchAll` loads one JSON document and then works in client mode — good for lists of a few thousand rows that should feel instant. ::: code-group ```js [JavaScript] import { Datagrid, column, fetchAll } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; // one GET, then search / sort / paging happen in the browser new Datagrid("#guide-fetchall", { label: "Agents (fetched once)", pageSize: 5, columns: [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], use: [fetchAll({ url: "/api/all/agents?limit=200" })], }); ``` ```html [HTML]
``` ::: | Option | Default | Description | |---|---|---| | `url` | — | endpoint | | `method` | `"GET"` (`"POST"` with `body`) | | | `dataSrc` | `data` key, or the body itself when it is an array | path or `(json) => rows` | | `csrf` | `configure().csrf` | send `X-CSRF-TOKEN` from `` | | `body` | — | JSON body | `reload()` fetches again. ## Server ```js import { serverSide, yajra } from "@akinozgen17/datagrids"; use: [serverSide({ url: "/agents/data", protocol: yajra(), csrf: true })] ``` The transport (fetch, abort, timeout, CSRF, Laravel headers, error normalization) is shared; the **protocol** decides the wire format. Three ship with the library — the classic SSP wire (`ssp()`, and its `yajra()` preset), Laravel's paginator JSON (`laravelPaginator()`) and the datagrids protocol (`dgp()`). See [Server protocols](/guide/server-protocols). ## Custom sources `customSource` takes a `mode` and a `load(query, ctx)` function and returns `{ rows, total, filtered, hasMore?, meta? }`. In server mode you receive the neutral [query](/reference/methods#query) for the current page; in client mode return every row once. ::: code-group ```js [JavaScript] import { Datagrid, column, customSource } from "@akinozgen17/datagrids"; import { agents } from "./data.js"; const all = agents(300); // a server-mode source: you receive the neutral query and return one page const source = customSource({ mode: "server", async load(query, { signal }) { await new Promise((r) => setTimeout(r, 200)); // pretend this is GraphQL / IndexedDB / a worker if (signal.aborted) throw new DOMException("aborted", "AbortError"); let rows = all.filter((r) => r.name.toLowerCase().includes(query.search.toLowerCase())); const [s] = query.sort; if (s) rows = [...rows].sort((a, b) => (a[s.key] > b[s.key] ? 1 : -1) * (s.dir === "asc" ? 1 : -1)); const start = (query.page - 1) * query.pageSize; return { rows: rows.slice(start, start + query.pageSize), total: all.length, filtered: rows.length }; }, }); new Datagrid("#guide-custom", { label: "Custom source", pageSize: 5, columns: [column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("place", { title: "Place" })], use: [source], }); ``` ```html [HTML]
``` ::: Throw (or reject with) an object shaped like `{ kind, status, message, retryable }` to show the error state; honor `ctx.signal` so superseded loads stop early. ## Row keys Selection, row actions, `refreshRow` and focus keeping need a stable key per row. The grid uses, in order: the `rowKey` option (a field name or `(row) => string`), `row.id`, `row.DT_RowId`. Without any of them it falls back to the row index and prints [DG003](/errors/DG003). ```js new Datagrid("#agents", { columns, data, rowKey: "uuid" }); ``` ## Related * [Server protocols](/guide/server-protocols) * [Lifecycle](/guide/lifecycle) — load modes, reload, destroy * [Grid options](/reference/options) --- --- url: https://akinozgen.github.io/datagrids/guide/server-protocols.md description: >- serverSide transport options, the three built-in protocols (classic SSP wire with the yajra preset, Laravel paginator, datagrids protocol v1), CSRF, Laravel headers, error normalization and session expiry. --- # Server protocols A server grid is `serverSide({ url, protocol })`: one **transport** (fetch, abort, timeout, CSRF, Laravel headers, error normalization) plus one **protocol** that turns the grid's neutral query into a request and the response back into rows. ```js import { serverSide, yajra, ssp, dgp, laravelPaginator } from "@akinozgen17/datagrids"; use: [serverSide({ url: "/agents/data", protocol: yajra(), csrf: true })] ``` ## Which protocol? | | `ssp()` | `yajra()` | `laravelPaginator()` | `dgp()` | |---|---|---|---|---| | Server side | any server speaking the classic `draw/start/length/columns[]` wire | yajra/laravel-datatables | `paginate()`, `simplePaginate()`, API resources | the [datagrids protocol v1](/protocol/v1/) | | Method / body | GET query (POST form with `method`) | POST, form-encoded | GET query | POST JSON (GET optional) | | Untyped cells | text | **HTML** (server escapes) | text | text | | Sorting | column index | column index | first sort key (`-date`) | keys, multiple | | Search | `search[value]` | `search[value]` | `search` | `q` | | Column filters | equality as anchored regex in `columns[i][search]`; typed: ColumnControl `columns[i][columnControl]` (no `between` / `notIn`) | same | plain params (`eq`, `in` only) | typed `{ op, value }` | | Counting | always | always | `paginate` yes, `simplePaginate` no | `exact`, `estimate` or `none` | | Errors | Laravel/HTTP shapes, `error` key | same | Laravel/HTTP shapes | RFC 9457 problem details | Use `yajra()` (or `ssp()`) to keep an existing endpoint untouched. Use `laravelPaginator()` for plain Eloquent pagination and API resources. Use `dgp()` for new endpoints: typed filters, optional counting, real error documents. ## Transport options | Option | Type | Default | Description | |---|---|---|---| | `url` | `string \| (query) => string` | — | endpoint | | `protocol` | `Protocol` | — | `ssp()`, `yajra()`, `laravelPaginator()`, `dgp()` or your own | | `method` | `"GET" \| "POST"` | protocol's | overrides the protocol default | | `params` | `object \| (query) => object` | — | extra parameters on every request (page filters) | | `headers` | `Record` | — | extra headers | | `csrf` | `boolean` | `configure().csrf` (`false`) | `X-CSRF-TOKEN` from ``, plus `_token` in form bodies | | `timeout` | `number` (ms) | `30000` | then a `timeout` error with Retry | | `fetch` | `typeof fetch` | `configure().fetch` → `globalThis.fetch` | custom transport (resolved at call time, so stubs work) | | `seed` | response body | — | rendered as the first page **without** a request (server-embedded first page) | `serverSide(...).params(fn)` returns a **new** definition with an extra params function — module definitions are immutable, so the original stays reusable: ```js const agents = serverSide({ url: "/agents/data", protocol: yajra(), csrf: true }); const active = agents.params(() => ({ status: "open" })); ``` ### What the transport adds * `X-Requested-With: XMLHttpRequest` on every request (Laravel's `$request->ajax()`), unless `configure({ laravel: false })`. * With `csrf`: `X-CSRF-TOKEN` and, for non-GET form bodies, `_token`. * `credentials: "same-origin"`, an abort signal (a newer request aborts the older one) and the timeout. * Debug keys some servers leak in development (`queries`, `input`) are deleted from the response before any event or module sees it. * Responses are matched to requests by an internal sequence number — never by `draw` — so a stale response can't overwrite a newer page. ## The classic SSP wire: `ssp()` and `yajra()` The endpoint receives the full parameter set on every request, encoded exactly like jQuery's `$.param`: `draw`, `start`, `length`, `search[value]`, `search[regex]`, `order[i][column|dir]` and `columns[i][data|name|searchable|orderable|search][value|regex]` — columns in **definition order, hidden ones included**. The demo sends an extra `unit` parameter from the select; open the **Request** tab. ::: code-group ```js [JavaScript] import { Datagrid, serverSide, yajra } from "@akinozgen17/datagrids"; new Datagrid("#guide-yajra", { label: "Agents (yajra)", pageSize: 5, sort: [["name", "asc"]], columns: [ { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, // untyped columns follow the protocol default: yajra escapes values on the server and sends raw HTML columns { key: "status_html", title: "Status", sortable: false, searchable: false }, ], use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true, params: () => ({ unit: document.querySelector("#guide-yajra-unit").value }), // ajax.data style extra parameter }), ], }); document.querySelector("#guide-yajra-unit").addEventListener("change", () => { void Datagrid.get("#guide-yajra").reload(); }); ``` ```html [HTML]
``` ::: `yajra()` is `ssp()` with two defaults changed: `method: "POST"` and **untyped cells render as HTML**, because yajra escapes every value on the server and sends `rawColumns` as markup. That is why every string column in the demo is a plain `{ key, title }` object, including the server-rendered status badge. Typed columns that parse their value (`column.money`, `date`, `badge`) work as usual; avoid `column.text()` here — it would print the server's entities (`&`) literally. | `ssp()` / `yajra()` option | Default | Description | |---|---|---| | `data` | — | extra payload: an object (deep-merged) or `(d) => void \| object` (mutate `d` or return a replacement) | | `dataSrc` | `"data"` | path to the rows, `""` for a bare array, or `(json) => rows` | | `cells` | `"text"` / `"html"` | default render mode for untyped columns | | `method` | `"GET"` / `"POST"` | | | `allowAll` | `false` | allow `length=-1` ("All" in `pageSizes`); otherwise sizes are capped by `maxPageSize` | Extra top-level response keys (yajra's `->with([...])`) arrive in `grid.lastResponse()`, in the `response` event's `raw`, and can be bound to page elements with [metaBind](/modules/meta-bind). A response `error` string shows a non-blocking banner (rows that did arrive stay visible). The exact rules, with the tests that pin them, are in the [SSP wire reference](/protocol/ssp). ## Laravel paginator: `laravelPaginator()` ```php return AgentResource::collection( Agent::query()->search($request->search)->sortBy($request->sort)->paginate($request->integer('per_page', 25)) ); ``` ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, laravelPaginator } from "@akinozgen17/datagrids"; new Datagrid("#guide-paginator", { label: "Agents (Laravel paginator)", pageSize: 5, sort: [["date", "desc"]], columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("place", { title: "Place" }), column.date("date", { title: "Date" }), ], // GET /api/paginator/agents?page=1&per_page=5&sort=-date&search=… use: [serverSide({ url: "/api/paginator/agents", protocol: laravelPaginator() })], }); ``` ```html [HTML]
``` ::: The response shape is detected automatically: `paginate()` (`total`, `last_page`), `simplePaginate()` (no total — the pager switches to "total unknown" and enables *Next* from `next_page_url`), `cursorPaginate()` (the next page's `cursor` is learned from `next_cursor`, so pages are reached in order) and `JsonResource::collection()` (`data` + `meta` + `links`). | Option | Default | Description | |---|---|---| | `query` | `{ page: "page", perPage: "per_page", sort: "sort", search: "search", cursor: "cursor" }` | parameter names | | `sortFormat` | `"-key"` | or `"key:dir"` (`date:desc`) | Page filters (`grid.filters()` keys that are not columns, `params`) are sent as plain query parameters. Details: [Laravel paginator reference](/protocol/laravel-paginator). ## datagrids protocol: `dgp()` ```json { "v": 1, "page": { "size": 25, "number": 1 }, "sort": [{ "key": "amount", "dir": "desc" }], "q": "jill", "filters": { "status": { "op": "in", "value": ["open", "pending"] } }, "fields": ["name", "status", "amount", "date"], "count": "exact", "requestId": "r-3" } ``` ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, dgp } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#guide-dgp", { label: "Agents (datagrids protocol)", pageSize: 5, sort: [["amount", "desc"]], columns: [ column.text("name", { title: "Name" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], use: [serverSide({ url: "/api/dgp/agents", protocol: dgp(), csrf: true })], }); // typed filters travel as { key: { op, value } } document.querySelector("#guide-dgp-open").addEventListener("click", () => grid.filters({ status: { op: "in", value: ["open", "pending"] } })); document.querySelector("#guide-dgp-big").addEventListener("click", () => grid.filters({ amount: { op: "gte", value: 15000 } })); document.querySelector("#guide-dgp-clear").addEventListener("click", () => grid.filters({ status: null, amount: null })); ``` ```html [HTML]
``` ::: A JSON request with key-based sorting, typed filters (`eq ne gt gte lt lte between in notIn contains notContains starts ends empty notEmpty`), the field list, and a `count` mode. Switch the demo to `count: none` and the pager stops showing totals; *Next* follows `page.hasMore`. Errors are `application/problem+json` (RFC 9457) with `code`, `retryable` and field `errors`. | Option | Default | Description | |---|---|---| | `method` | `"POST"` | `"GET"` sends `page[size]`, `sort=-amount`, `filter[status][in]=open,pending` | | `count` | `"exact"` | `"estimate"` or `"none"` | The normative spec and JSON Schemas: [datagrids protocol v1](/protocol/v1/). ## Errors and session expiry Every failure — network, timeout, HTTP status, an `error` key in a 200 response, unreadable JSON — becomes one `DatagridError`: ```ts { kind, status, message, detail?, retryable, raw? } // kind: network | timeout | abort | http | server | session | forbidden | validation | parse | protocol ``` | Server says | kind | Shown message | Retry | |---|---|---|---| | network failure | `network` | "The server could not be reached…" | yes | | no answer in `timeout` | `timeout` | "The server took too long to respond." | yes | | 419 or 401, or a redirect to a login page | `session` | "Your session has expired…" | no | | 403, or a redirect elsewhere | `forbidden` | server message or "You are not allowed…" | no | | 422 | `validation` | the first validation message | no | | 429 | `http` | server message | yes | | 5xx | `http` | "The server returned an error (500)." | yes | | 200 with `error` | `server` | "The server returned an error (200)." | yes | The grid shows it in place (blocking error state when there are no rows, a banner when rows are already on screen), fires `error`, and for `session` also fires `sessionexpired` and calls `configure({ onSessionExpired })`. Server-provided details (an exception message, SQL) are never shown to users; they go to the console as [DG012](/errors/DG012) and appear in a collapsed "Details" block only while warnings are enabled. `errorMode: "silent" | "throw"` changes the in-place behaviour per grid. See [States & errors](/guide/states-and-errors). ```js configure({ csrf: true, onSessionExpired: () => location.assign("/login"), }); ``` ## Writing your own protocol A protocol is an object with `name`, `cells`, `encode(req, query, grid)` → `{ url, init, params? }` and `decode(body, query, grid)` → `{ rows, total, filtered, hasMore?, meta? }`. The transport keeps doing CSRF, headers, abort, timeout and error handling for you. `grid` is the grid the request belongs to (keep per-grid state, such as cursors, in a `WeakMap` keyed by it). Optional fields: | Field | Description | |---|---| | `method` | default HTTP method (`"GET"` or `"POST"`); `serverSide({ method })` overrides it | | `filterOps` | column filter operators the wire can carry; the [column filter](/modules/column-filters) menu offers only these (omitted: all) | | `allowAll` | `true`: page size `-1` ("All") is accepted | To send a server default order when the sort is empty, check `query.sortDefault` in `encode`: it is `false` only when the grid was created with `sort: []`. `encode` may also return `params`: the page parameters that actually reached the wire beyond the protocol's own fields. `grid.lastRequestParams()` (and with it the "all matching" payload of [selection](/modules/selection)) reports them; without it, the request's `params` are reported. The built-in `ssp` / `yajra` return everything on the top level except `draw`, `columns`, `order`, `start`, `length` and `search`, so additions of a `data` function count too. ## Related * [Protocol reference](/protocol/) — exact wire formats * [Laravel + yajra recipe](/recipes/laravel-yajra) * [CSRF & session expiry recipe](/recipes/csrf-and-session) --- --- url: https://akinozgen.github.io/datagrids/guide/lifecycle.md description: >- Load modes (eager, visible, manual), reload, accessing grids (get, find, reload by name), destroy and remount, runtime column changes and declarative init with upgrade() and presets. --- # Lifecycle ## Create ```js const grid = new Datagrid("#agents", { label: "Agents", columns, use: [source, colVis()] }); ``` * The target is a `` element or a selector matching **exactly one** table ([DG005](/errors/DG005) otherwise). * Constructing on a table that already has a grid returns that grid. * Construction is synchronous: methods, events and module APIs are usable on the next line. The first load starts in a microtask, so listeners you add right away still see it. ## Load modes | `load` | First request | Use for | |---|---|---| | `"eager"` (default) | right after construction | normal pages | | `"visible"` | when the grid first comes within 200 px of the viewport (IntersectionObserver) | tabs, accordions, modals, long pages | | `"manual"` | only on `grid.load()` or the built-in **Load** button | expensive reports, search-first screens | ::: code-group ```js [JavaScript] import { Datagrid, serverSide, yajra } from "@akinozgen17/datagrids"; const grid = new Datagrid("#guide-manual", { label: "Agents (manual load)", load: "manual", // no request until the user (or your code) asks pageSize: 5, columns: [{ key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }], use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true })], }); document.querySelector("#guide-manual-load").addEventListener("click", () => grid.load()); ``` ```html [HTML]
``` ::: There is no "adjust columns" call to remember: a ResizeObserver keeps the layout (and the narrow / wide breakpoint stored in `data-bp`) correct when a hidden grid becomes visible. ## Reload ```js await grid.reload(); // page 1 await grid.reload({ keepPage: true }); // stay on the current page (after an edit) await grid.reload({ silent: true }); // no busy card, only aria-busy (polling) ``` In server mode a reload sends a fresh request; the previous one, if still running, is aborted. Array and DOM sources re-run search, sort and paging over the current rows, so `setData()`, `addRows()` and `removeRow()` changes stay; `fetchAll` re-fetches. For periodic reloads use the [autoRefresh](/modules/auto-refresh) module. ## Find a grid | Call | Returns | |---|---| | `Datagrid.get(tableOrSelector)` | the grid on that table (or the table around an element), or `null` | | `get(target)` | same, as a named export / `Datagrids.get` | | `find(name)` | the grid created with `name`, or `null` | | `reload(name, { keepPage, silent })` | reloads it and returns `true`; `false` and [DG006](/errors/DG006) if there is none | `get()` **never** creates a grid. Code that runs before initialization gets `null` instead of silently creating a second, unconfigured grid. ```js import { find, reload } from "@akinozgen17/datagrids"; // e.g. after saving a record in a modal on another part of the page reload("agents", { keepPage: true }); ``` ## Batch state changes `grid.batch(fn)` applies several changes (sort, page size, filters…) without intermediate loads or announcements; call `grid.load()` afterwards if you need a load. ## Change columns `grid.setColumns(defs)` replaces the column set in place: the header is rebuilt, sorts on removed columns are dropped, `columnchange` fires and the data reloads (keeping the page). No destroy needed. ## Destroy and remount ```js grid.destroy(); // idempotent const fresh = grid.remount(); // destroy + new Datagrid(same table, same options) ``` `destroy()` aborts requests, lets every module clean up (in reverse order), removes listeners and observers, and **restores the original table**: its classes and attributes, ``, ``, the original `` rows (adopted rows included) and its position in the document. The grid is unregistered, so `Datagrid.get()` returns `null` and a new grid can be created on the same table. `remount(table?)` is for DOM-morphing frameworks (Livewire, Turbo, htmx swaps): it re-creates the grid from its constructor options plus every module attached later with `grid.use()`, optionally on a replacement table. ## Declarative init: `upgrade()` Server templates can mark tables instead of writing JavaScript per page. Register a **preset** (a function returning the module list for a table) once, then call `upgrade()`: ::: code-group ```js [JavaScript] import { preset, upgrade, reload, fetchAll, colVis, button } from "@akinozgen17/datagrids"; const log = (line) => (document.querySelector("#guide-upgrade-log").textContent += line + "\n"); // the module list for every preset("agent-list", (table) => [fetchAll({ url: table.dataset.url }), colVis(), button.reload()]); log(`upgrade() → ${upgrade().length} grid(s) created`); document.querySelector("#guide-upgrade-again").addEventListener("click", () => { log(`upgrade() → ${upgrade().length} grid(s) created (idempotent)`); }); document.querySelector("#guide-upgrade-reload").addEventListener("click", () => { log(`reload("upgraded") → ${reload("upgraded")}`); }); ``` ```html [HTML]
Ref Name Unit Amount Date
``` ::: * `upgrade(root = document)` initializes every `table[data-datagrid]` under `root` that has no grid yet and returns the new grids — calling it again is harmless (idempotent). Call it after inserting HTML (AJAX partials, Turbo frames). * `data-datagrid="name"` picks the preset registered with `preset(name, (table) => modules)`. * Only a small whitelist of scalar attributes is read on the table: `data-dg-name`, `data-dg-label`, `data-dg-load`, `data-dg-page-size`, `data-dg-sort="key:desc"`, `data-dg-theme`, `data-dg-size`, `data-dg-density`. Columns come from `` and its [`data-dg-*` header attributes](/guide/data-sources#dom-progressive-enhancement) (plus `data-dg-type="number|money|date|html|text"` and `data-dg-sort-key`). * There is deliberately no JSON configuration attribute: behaviour lives in presets (JavaScript), templates only name the preset and set a few scalars. ## Related * [Grids in tabs & modals](/recipes/tabs-and-modals) * [Destroy, re-init & Livewire](/recipes/destroy-and-reinit) * [Instance methods](/reference/methods) · [Static API](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/guide/states-and-errors.md description: >- The loading, empty, no-match, error and manual states, the busy indicator on reloads, error banners, retry, errorMode and the data-state attribute. --- # States & errors A grid is always in exactly one state, shown in the table body and mirrored on the root as `data-state`. You never write "Processing…" markup or call `alert()`. ::: code-group ```js [JavaScript] import { Datagrid, column, customSource } from "@akinozgen17/datagrids"; import { agents } from "./data.js"; const columns = [column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" })]; // loading: a source that never answers new Datagrid("#guide-state-loading", { label: "Loading", columns, use: [customSource({ mode: "server", load: () => new Promise(() => {}) })], }); // empty: no rows at all new Datagrid("#guide-state-empty", { label: "Empty", columns, data: [] }); // error: the first load fails with a retryable error, "Retry" succeeds let fail = true; new Datagrid("#guide-state-error", { label: "Error", columns, pageSize: 3, use: [ customSource({ mode: "server", async load() { if (fail) { fail = false; throw { kind: "http", status: 500, message: "The server returned an error (500).", detail: "SQLSTATE[42S22]: Column not found", retryable: true }; } const rows = agents(3); return { rows, total: 3, filtered: 3 }; }, }), ], }); ``` ```html [HTML]


``` ::: | `data-state` | When | What the user sees | |---|---|---| | `loading` | first load, no rows yet | a centered "Loading…" card in the body | | `ready` | rows are shown | the rows | | `empty` | loaded, nothing to show | "No records" — or "No matching records" + **Clear search** when a search or filter is active | | `error` | a load failed and there are no rows to keep | the error message + **Retry** (when retryable) and, while warnings are on, a collapsed **Details** block | | `idle` | `load: "manual"` before the first load | "List not loaded yet" + **Load** | **Reloading does not change `data-state`.** The rows stay, `aria-busy="true"` goes on the table and, after 300 ms (so fast responses don't flash), the frame gets `data-busy="visible"`: the rows dim and a floating "Loading…" card appears in the visible part of the body. `reload({ silent: true })` skips the visual part and only sets `aria-busy`. ## Errors Any failure — network, timeout, HTTP status, an `error` key in a 200 response, unreadable JSON, or a custom source that throws — is normalized into one shape: ```ts interface DatagridError { kind: "network" | "timeout" | "abort" | "http" | "server" | "session" | "forbidden" | "validation" | "parse" | "protocol"; status: number | null; message: string; // safe to show detail?: string; // server internals: console + Details block only retryable: boolean; raw?: unknown; // the response body } ``` ::: code-group ```js [JavaScript] import { Datagrid, serverSide, yajra } from "@akinozgen17/datagrids"; const out = document.querySelector("#guide-errors-log"); const log = (line) => (out.textContent = line + "\n" + out.textContent); const grid = new Datagrid("#guide-errors", { label: "Agents", pageSize: 5, columns: [{ key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }], use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true })], }); grid.on("error", ({ error }) => log(`error → kind=${error.kind} status=${error.status} retryable=${error.retryable}`)); grid.on("sessionexpired", () => log("sessionexpired → send the user to the login page")); grid.on("loadingchange", ({ loading }) => loading && log("loading…")); ``` ```html [HTML]
Use the Simulate buttons: the next response fails.
``` ::: * **No rows on screen:** the body shows the error state with **Retry**. * **Rows already on screen** (a reload or page change failed): the rows stay and a dismissible banner (`role="alert"`) appears above the table with **Retry**. * **Every error** fires `error` on the grid. Session errors (419, 401, redirect to a login page) also fire `sessionexpired` and call `configure({ onSessionExpired })`. * **Server details** (`detail`: an exception message, SQL) are printed once to the console as [DG012](/errors/DG012) and shown in the collapsed Details block only while warnings are enabled. Turn them off in production with `configure({ warnings: false })` — wire it to your app's debug flag. The timeout fault above needs the default 30-second timeout to elapse; pass `serverSide({ timeout: 5000 })` to try it faster. ### `errorMode` | `errorMode` | Behaviour | |---|---| | `"inline"` (default) | the error state / banner described above | | `"silent"` | no UI; listen to `error` yourself (the grid returns to `ready`) | | `"throw"` | the error is thrown from the load (as an `Error` with the `DatagridError` fields) | Set it per grid (`errorMode`) or globally (`configure({ errorMode })`). The global value is read when an error happens, so it also applies to existing grids that don't set their own. ## Status in code ```js grid.status(); // { status: "idle" | "loading" | "reloading" | "ready" | "error", // loaded, total, filtered, hasMore, error } grid.on("loadingchange", ({ loading }) => spinner.hidden = !loading); ``` ## Styling states States are attributes, so host CSS can target them without fighting class names: ```css .dg[data-state="error"] { outline: 1px solid var(--dg-tone-bad); } .dg-table[aria-busy="true"] { cursor: progress; } ``` Messages come from the [message pack](/reference/messages) (`loading`, `empty`, `noMatch`, `error`, `retry`, `errSession`, …) and can be overridden per grid or globally. ## Related * [Server protocols → errors](/guide/server-protocols#errors-and-session-expiry) * [CSRF & session expiry recipe](/recipes/csrf-and-session) * [Accessibility](/guide/accessibility) — how states are announced --- --- url: https://akinozgen.github.io/datagrids/guide/theming.md description: >- Component-scoped --dg-* tokens, one-line rebranding with an inherited --dg-accent, --dg-rem scaling, dark mode via the host color-scheme, size and density axes, header style, card surface and a high-contrast recipe. --- # Theming The grid styles itself with **component-scoped design tokens** (`--dg-*` custom properties defined on the grid root, never on `:root`), a low-specificity reset and state carried in attributes. Your page CSS can't accidentally restyle it, and you can deliberately restyle it with a few tokens. ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#guide-theme", { surface: "card", title: "Field assignments", description: "Open tasks by unit", count: true, striped: true, pageSize: 5, columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: agents(40), }); // every appearance option is a root attribute or an inherited token — no re-render needed const $ = (id) => document.querySelector(id); $("#guide-theme-accent").addEventListener("input", (e) => $("#guide-theme-host").style.setProperty("--dg-accent", e.target.value)); $("#guide-theme-density").addEventListener("change", (e) => grid.root.setAttribute("data-density", e.target.value)); $("#guide-theme-size").addEventListener("change", (e) => grid.root.setAttribute("data-size", e.target.value)); $("#guide-theme-head").addEventListener("change", (e) => e.target.value === "sentence" ? grid.root.setAttribute("data-dg-head", "sentence") : grid.root.removeAttribute("data-dg-head")); $("#guide-theme-theme").addEventListener("change", (e) => e.target.value ? grid.root.setAttribute("data-dg-theme", e.target.value) : grid.root.removeAttribute("data-dg-theme")); ``` ```html [HTML]
``` ::: ## Rebrand with one line `--dg-accent` is an **input token**: the library reads it but never defines it, so it inherits from anywhere above the grid. ```css body { --dg-accent: #0f766e; } ``` Every accent color — checkbox fill, current page, focus ring, sort icon, links, selection tint — is derived from it with `color-mix()` and relative color syntax. Text and icon accents are clamped to a lightness that keeps ≥ 4.5:1 contrast on white, and the text on accent fills flips between black and white automatically, so any brand color stays readable. In dark mode the accent is lifted one or two steps. Design systems that store colors as RGB triplets work as is: ```css body { --dg-accent: rgb(var(--brand-rgb)); } ``` ## Scale with `--dg-rem` All sizes derive from the second input token, `--dg-rem` (default `1rem`), so the grid follows the user's font size. If your layout shrinks `html { font-size }` on small screens and the grid should not shrink with it, pin the base: ```css @media (max-width: 970px) { body { --dg-rem: 16px; } } ``` ## Dark mode The palette is written with `light-dark()`: the grid follows the **`color-scheme` of your page** (inherited), not the operating system. This site sets `color-scheme: dark` on `` in dark mode, which is why every demo switches with the theme toggle — no bridge code. | `theme` option | Root attribute | Result | |---|---|---| | (none) | — | follow the inherited `color-scheme` (light when the page declares none) | | `"light"` / `"dark"` | `data-dg-theme="light"` / `"dark"` | force | | `"system"` | `data-dg-theme="system"` | follow the operating system | ## Size and density Two independent axes, both token-only: | | `size: "sm"` | `"md"` (default) | `"lg"` | |---|---|---|---| | body text | 12px | 13px | 14px | | controls | 30px | 34px | 40px | | | `density: "compact"` | `"normal"` (default) | `"comfortable"` | |---|---|---|---| | row height | 28px | 36px | 44px | Values are at a 16px `--dg-rem`. On touch screens (`pointer: coarse`) controls grow to 44px while row density stays as chosen. Rows are top-aligned so multi-line cells stay readable. ## Header style, surface and stripes | Option | Default | Alternatives | |---|---|---| | `head` | `"caps"` — 11px, bold, uppercase, tracked | `"sentence"` (`data-dg-head="sentence"`) | | `surface` | `"plain"` — no box, blends into the page | `"card"` (`data-dg-surface="card"`): own background, radius and shadow; `title`, `description` and the `count` move into a header | | `striped` | `false` | `true` (`data-dg-striped`) | | `wrap` | `true` | `false` (`data-dg-nowrap`): single-line cells | | `rowTone` | — | `(row) => "ok" \| "warn" \| "bad" \| "info" \| "muted"` tints whole rows (`data-tone` on the ``) | ::: tip Uppercase headers and Turkish Uppercasing uses the document language: in Turkish `i` must become `İ`. Set ``; without it the grid warns with [DG011](/errors/DG011). ::: ## Overriding tokens Input tokens (`--dg-accent`, `--dg-rem`) inherit from any ancestor. **All other tokens are defined on the grid root**, so set them on the root itself, with a selector that is more specific than `.dg`: ```css /* one grid */ #agents-page .dg { --dg-head-bg: #eef2ff; --dg-row-h: 2rem; } /* every grid in your app */ .app .dg { --dg-radius-surface: 4px; --dg-tone-ok: #047857; } ``` The full list with defaults is in the [CSS token reference](/reference/css). Variables named `--dg-_*` are internal and may change without notice. ## What host CSS can and can't change The grid is built for hostile pages (CSS frameworks, admin themes, global `* {}` rules). Its own rules use a `.dg-` class reset with specificity (0,1,0), cell rules at (0,1,3), and never exceed (0,2,0) elsewhere; state lives in attributes (`data-state`, `aria-sort`, `data-selected`), so host classes like `.active` or `.selected` mean nothing to it. Row separators are painted as backgrounds, not borders, so `table td { border: none }` style rules can't erase them. | Host CSS | Effect | |---|---| | element rules (`table`, `td`, `button`, `input`) and single-class rules | no effect on the grid's layout | | framework table classes (`.table td`, `.table-striped tr:nth-child(odd)`) | no effect | | a more specific selector that targets the grid's elements | wins — that's your deliberate override | | `!important` rules | win; the library never joins an `!important` race (it only uses it for reduced motion) | | font family | inherited on purpose — the grid uses your typeface | This documentation site is a test of that claim: the demos run inside VitePress' content area with its own table, zebra-row and link styles, without isolation. ## High contrast **Windows High Contrast / `forced-colors: active`** is supported by the library: borders, focus outlines and states switch to system colors. **App-level high-contrast themes** that force colors with `!important` (e.g. `body.high-contrast * { color: #000 !important }`) also hit the grid's icons and filled buttons. Bridge them once: ```css body.high-contrast .dg { --dg-accent: #000; --dg-border: #000; --dg-border-strong: #000; --dg-line: #000; --dg-line-strong: #000; --dg-muted-fg: #000; --dg-head-fg: #000; } body.high-contrast .dg :is(.dg-btn, .dg-pager-btn, .dg-cellbtn, .dg-sort, .dg-textbtn, .dg-search-clear, .dg-panel-item) { background-color: transparent !important; color: #000 !important; border-width: 1px !important; } body.high-contrast .dg :is(.dg-sort, .dg-textbtn, .dg-search-clear, .dg-panel-item) { border-width: 0 !important; } body.high-contrast .dg :is([data-variant="primary"], [aria-current="page"]) { background-color: #000 !important; color: #fff !important; } body.high-contrast .dg :is([data-variant="primary"], [aria-current="page"], .dg-check-box) :is(svg, span) { color: #fff !important; } body.high-contrast .dg .dg-search-input { border: 0 !important; } ``` ## Motion Panel and spinner animations are short (100–220 ms) and turn off under `prefers-reduced-motion: reduce`. ## Related * [CSS token reference](/reference/css) * [Anatomy (DOM contract)](/guide/anatomy) — the stable classes and attributes to target * [Localization & RTL](/guide/i18n) --- --- url: https://akinozgen.github.io/datagrids/guide/i18n.md description: >- Message packs (en, tr), locale resolution, overriding strings, locale-aware search and sorting, number and date formats, and right-to-left layouts. --- # Localization & RTL ## Messages The library ships two complete message packs, `en` and `tr`. Every user-visible string — the search placeholder, pager labels, state texts, error messages, screen-reader announcements — comes from the pack; modules (column menu, selection, export, row actions…) carry their own small packs in the same two languages. ```js import { Datagrid, configure, en } from "@akinozgen17/datagrids"; // one grid new Datagrid("#agents", { columns, messages: { empty: "No agents yet", retry: "Try again" } }); // every new grid configure({ messages: { search: "Find…" } }); ``` Overrides are partial and merged over the pack; `undefined` values never replace a string. Some messages are functions because they include numbers, e.g. `info: (from, to, filtered, total) => string`. The complete key list is in the [messages reference](/reference/messages). Module strings are overridden with each module's own `messages` option. ## Which language? The grid resolves its locale once, at construction: 1. the `locale` option, 2. `configure({ locale })`, 3. ``, 4. the browser's language (`navigator.language`), 5. otherwise `"en"`. Empty values are skipped. A value the `Intl` APIs reject (``) is skipped too, with a [DG015](/errors/DG015) warning, instead of breaking number formatting. Locales starting with `tr` use the Turkish pack, everything else the English one. Set `` (you should anyway — it also drives correct uppercasing of headers) or pass `locale`. ::: code-group ```js [JavaScript] import { Datagrid, column, tr } from "@akinozgen17/datagrids"; import { turkishRecords } from "./data.js"; // Turkish UI + Turkish collation and search folding: try searching "isik" or "ISIK" new Datagrid("#guide-i18n-tr", { label: "Görev kayıtları", locale: "tr", messages: tr, // optional: "tr*" locales pick the Turkish pack automatically pageSize: 5, columns: [ column.text("kayit", { title: "Kayıt" }), column.text("ad", { title: "Personel" }), column.text("mekan", { title: "Mekân" }), column.money("tutar", { title: "Tutar" }), // tr-TR, TRY column.date("tarih", { title: "Tarih" }), ], data: turkishRecords(60, 3), }); ``` ```html [HTML]
``` ::: ## Search and sort follow the locale * **Search** folds case and accents with the grid's locale: `isik` finds `Işık`, `ISIK` finds `ışık`; every word must match (`raccoon north` → rows containing both). * **Sorting** uses `Intl.Collator(locale, { numeric: true })`: `İ` sorts after `I`, `item 10` after `item 9`. * **Numbers, money and dates** are formatted with the grid locale unless the column gets its own `locale`; money uses `TRY` unless you pass `currency`. Pager and info numbers use the grid locale. ## Right-to-left The stylesheet uses logical properties only (`margin-inline-start`, `inset-inline-end`…), so a grid inside `dir="rtl"` mirrors itself: toolbar, sort icons, sticky action column (moves to the left), pager arrows and panels. ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents } from "./data.js"; // the grid inherits dir="rtl" from its container: logical properties mirror the layout and the pager new Datagrid("#guide-i18n-rtl", { label: "RTL layout", locale: "en", pageSize: 5, columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), // "S.T.A.R.S. Alpha" keeps its dots in place (dir="auto") column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: agents(30), }); ``` ```html [HTML]
``` ::: Text cells are written with `dir="auto"`, so Latin data inside an RTL page keeps its punctuation in place (`S.T.A.R.S.` doesn't become `.S.T.A.R.S`), and formatted numbers, money and dates are bidi-isolated left-to-right blocks. ## Related * [Messages reference](/reference/messages) * [Theming → header style](/guide/theming#header-style-surface-and-stripes) --- --- url: https://akinozgen.github.io/datagrids/guide/anatomy.md description: >- The public DOM contract — stable classes, attributes and state selectors you can target from CSS and tests, and what is covered by semantic versioning. --- # Anatomy (DOM contract) The markup below is a **public contract**: the classes (`.dg-*`), attributes (`data-*`, `data-dg-*`, ARIA) and their values are covered by semantic versioning. Target them from your CSS and end-to-end tests. Internal custom properties (`--dg-_*`) and undocumented elements are not. ```html
data-density="compact|normal|comfortable" data-dg-theme="light|dark|system" data-dg-head="sentence" data-dg-surface="card" data-dg-striped data-dg-nowrap data-dg-sticky-head data-dg-virtual data-bp="xs|sm|md|lg">
…
…
…
…
Skip table
…
…
… Actions
12,450.00$ …
…
…
…
``` ## Rules 1. **State is an attribute, never a class.** Root: `data-state`. Rows: `data-selected`, `data-tone`, `aria-busy`. Headers: `aria-sort`. Controls: `aria-expanded`, `aria-disabled`, `aria-pressed`, `aria-current`. Toolbars and bars: `data-active`, `data-has-value`. 2. **`data-state` values:** `loading` (first load, no rows), `ready` (rows shown), `empty` (no rows, or no match), `error` (blocking error), `idle` (`load: "manual"`, not loaded yet). Reloads don't change it; the reload signal is `.dg-frame[data-busy]` plus `table[aria-busy]`. 3. **Toolbar slots** are `start`, `end` and `filters`. Items are ordered by their `order`, then by registration. 4. **Your table stays your table.** The root wraps it and adds the `dg-table` class; `` is regenerated (the original is kept and restored); with the DOM source the original ``s are adopted. `destroy()` undoes all of it. 5. **Cells** are styled through `.dg-table > :is(thead, tbody, tfoot) > tr > :is(td, th)` (specificity (0,1,3)). The grid never sets font size or weight on cells — they inherit from the table, so your typography applies evenly. Row separators are painted backgrounds, not borders. 6. **Alignment** is `data-align="end|center"` on cells — never `:nth-child`. Special columns carry `data-col="select|actions|rownum|go|label"`. 7. **Column identity** is `data-key` on `th`/`td`; **row identity** is `data-key` on `tr` (the row key). 8. **RTL:** text cells get `dir="auto"`; number, money and date blocks are isolated LTR. 9. **Virtual rows** (≥ 300 rows in view): the root gets `data-dg-virtual`, `.dg-scroll` scrolls vertically (`max-block-size: var(--dg-max-h, 70vh)`), the header is sticky, off-screen rows are replaced by two `tr.dg-spacer` rows and the table carries `aria-rowcount` / rows `aria-rowindex`. 10. **Width lock:** while virtual rows are on, measured widths are written to `` with `table-layout: fixed` — the only inline widths the grid ever writes. They are removed when the mode ends. 11. **Skip link:** `a.dg-skip` sits before the scroll container, is visible only on focus and jumps to the `[tabindex="-1"]` anchor after the table. 12. **Loading:** the first load shows `.dg-state[data-kind="loading"]` in the body; reloads show a floating `.dg-loading` card after 300 ms (`.dg-frame[data-busy="visible"]`), centered in the visible area of wide tables; silent reloads only set `aria-busy`. 13. **Panels** (column menu, column filter, row action menu, reason notes) are children of the root, opened in the top layer with `popover="manual"` and positioned by script — no z-index fights. 14. **Affordance:** every clickable thing has a permanent indicator (icon, checkbox or chevron), a hover background and `cursor: pointer`. Sortable headers show their ↕ icon even when unsorted. 15. **Tooltips:** the grid's own controls never carry a native `title`. Their tooltip text is in `data-dg-tip` and shows in the single `.dg-tip` element (top layer) on hover after 500 ms or at once on keyboard focus; it hides on pointer leave, click, scroll, blur and `Escape`. A page-wide `[title]` tooltip plugin therefore finds nothing in the grid to take over, and nothing is left behind when a control under the pointer re-renders or turns disabled. The accessible name stays in `aria-label`; where the tooltip adds information it is also the `aria-description`. 16. **Never emitted:** `dataTable` or `dt-*` classes and events, inline widths (except rule 10), `@layer`, `!important` (except for reduced motion), tokens on `:root`, `title` on grid controls. ## Safe customization examples ```css /* a column width (widths live in CSS) */ #agents th[data-key="ref"] { inline-size: 7rem; } /* highlight failed rows */ .dg-table > tbody > tr[data-tone="bad"] { font-weight: 600; } /* dim the toolbar while the grid reloads */ .dg:has(.dg-table[aria-busy="true"]) .dg-toolbar { opacity: .6; } ``` In end-to-end tests wait for state, not for time, and prefer `data-state`, `aria-sort`, `data-selected` and `data-key` over visible text: ```js // Playwright const grid = page.locator(".dg", { has: page.locator("#agents") }); await expect(grid).toHaveAttribute("data-state", "ready"); await expect(page.locator('#agents th[data-key="amount"]')).toHaveAttribute("aria-sort", "descending"); ``` ## Related * [Theming](/guide/theming) · [CSS tokens](/reference/css) * [Accessibility](/guide/accessibility) --- --- url: https://akinozgen.github.io/datagrids/guide/accessibility.md description: >- Accessibility statement — native table semantics, sortable header buttons with aria-sort, skip link, live announcements, keyboard support, focus handling, contrast, reduced motion, forced colors and known limitations. --- # Accessibility **Target:** the grid component conforms to WCAG 2.2 level AA when it is given an accessible name and used with the default stylesheet. Your page around it is your part of the bargain. ## The pattern: a real table datagrids keeps a native `` with ``, `` — the structure every screen reader already knows how to navigate (table navigation keys, header announcements). It does **not** turn the table into an ARIA `grid` by default, so screen-reader table commands keep working and Tab moves through the interactive things (sort buttons, links, checkboxes, action buttons) as it does on any page. Spreadsheet-style navigation is opt-in: the [keyboardGrid](/modules/keyboard-grid) module applies the APG grid pattern (`role="grid"`, one tab stop, arrow keys between cells). | Feature | How | |---|---| | Accessible name | `label`, `labelledBy`, `title` or the table's `` so columns don't jump while scrolling; * `aria-rowcount` / `aria-rowindex` keep the real size and positions available to assistive tech; * printing renders every row (the window is switched off for `beforeprint`). ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const rows = agents(5000); const t0 = performance.now(); const grid = new Datagrid("#guide-virtual", { label: "5,000 agents, one page", paging: false, // every row in one view → virtual rows switch on (≥ 300) maxHeight: "420px", columns: [ column.index(), column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("task", { title: "Task" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: rows, }); grid.on("render", () => { const rendered = grid.table.tBodies[0].rows.length; document.querySelector("#guide-virtual-info").textContent = `${grid.viewRows().length} rows in view · ${rendered} in the DOM · first render ${Math.round(performance.now() - t0)} ms`; }); ``` ```html [HTML]
` and `
` names the scroll region (`role="region"`); missing → [DG002](/errors/DG002) | | Sorting | each sortable header holds a real `
``` ::: | `virtual` | Effect | |---|---| | (default) | automatic at ≥ 300 rows in view | | `false` | never — render every row of the view | | a number, e.g. `150` | your own threshold | Below the threshold (any normal page size) rendering is plain and complete. See [Accessibility → known limitations](/guide/accessibility#known-limitations) for the screen-reader trade-off. ## Measurements Numbers from the rendering prototype the v1 renderer is based on — not marketing numbers; they will be re-measured for each release with the method below. **Method:** headless Brave 155 (Chromium) via Playwright on an Intel i5-12400F, plus a 4× CPU slowdown run through the DevTools protocol. Data: 1000 rows × 12 columns of server-rendered cells (avatar, badge, key-value block, phone link, formatted money, clamped note and a hidden 10-item action menu per row) — about 79 DOM nodes per row, sticky header. Metric: time until the next frame (`requestAnimationFrame` + `setTimeout`), median of 7 runs. | Scenario | 1× CPU | 4× CPU | |---|---|---| | 1000 rows, first frame (template clone / `innerHTML` / `createElement`) | 346 / 388 / 407 ms | ~1.74 s | | same 1000 rows, a jQuery-based grid (DataTables 1.10.24), client init | 599 ms | 2.84 s | | 1000 rows without the per-row hidden menu (47 nodes/row) | 277 ms | 1.28 s | | 50 rows (the size of a virtual window) | 25 ms | 89 ms | | `refreshRow` (one row) | 24 ms | 83 ms | | hide a column (cell `hidden`) | 56 ms | 291 ms | | sort 10,000 rows in memory (cached `Intl.Collator`) | 25 ms | 89 ms | | accent-folding search over 10,000 rows | 5 ms | 23 ms | | scroll frame time p50 / p95 after render | 16.7 / 17.3 ms | 17 / 50 ms | Takeaways: the renderer is not the bottleneck (±15 % between techniques), node count is; and the same 1000-row page renders roughly 35–40 % faster than the jQuery-based grid it was compared with. ## Bundle size Measured on the first working build (min + gzip), before release tuning: | Part | Size | |---|---| | core (grid, columns, sources, protocols) | 18.6 KB | | core + a typical list setup (server source, state, column menu, buttons, export) + row actions | 33.6 KB | | everything (IIFE build) | 41.1 KB | | CSS (tokens + core + all module styles) | 9.8 KB | Modules you don't import are tree-shaken away from ESM builds. The IIFE build always contains everything. ## Advice for large lists * **Page on the server** above a few thousand rows ([serverSide](/guide/server-protocols)); client mode is comfortable up to ~10,000 rows for sorting and search. * **Keep page sizes under 300** unless users need to scroll huge pages; then virtual rows take over. * **"All" is guarded**: `maxPageSize` (default 1000) caps page sizes, including `pageSize(-1)` unless a protocol explicitly allows it (`ssp({ allowAll: true })`). * **Fewer nodes per row**: prefer typed columns over heavy server-rendered markup; use the [actions](/modules/actions) module instead of rendering a dropdown in every row. * **Silent polling**: [autoRefresh](/modules/auto-refresh) reloads silently and keeps the page (or call `reload({ silent: true, keepPage: true })` yourself). ## Related * [Accessibility](/guide/accessibility) * [Data sources](/guide/data-sources) --- --- url: https://akinozgen.github.io/datagrids/modules.md description: >- Catalog of every datagrids module — what it does, how to import it, where its API lives on the grid and which pipelines it plugs into. --- # Modules Everything beyond "a table with columns" is a module: saved state, the column menu, filters, selection, row actions, export, summaries, toolbar buttons — and the data sources themselves. A module is an **immutable definition** created by a factory function (`colVis()`, `excel({ … })`) and attached with `use`. The same definition can be shared by many grids; each grid binds its own copy when it is created. ```js import { Datagrid, serverSide, yajra, colVis, stateSave, excel } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns: [{ key: "name", title: "Name" }], use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), colVis(), stateSave(), excel()], }); ``` (String columns on yajra grids are plain `{ key, title }` objects: the server already escapes the values — see [Server protocols](/guide/server-protocols).) Modules are separate exports, so a bundler drops the ones you never import (tree-shaking). Read [Concepts → Modules](/guide/concepts#modules) for the mental model; this page is the catalog. ## Catalog Each module's API is added to the grid under the name in the "Grid API" column (`grid.state.reset()`, `grid.selection.payload()`). In TypeScript, `grid.module(stateSave)` returns the typed API. | Module | Import | What it does | Grid API | Pipelines | |---|---|---|---|---| | [stateSave](/modules/state-save) | `stateSave()` | Remembers sort, page size, hidden columns | `state` | state | | [colVis](/modules/colvis) | `colVis()` | Show / hide columns menu | `colVis` | toolbar | | [colReorder](/modules/col-reorder) | `colReorder()` | Drag or move columns | `colReorder` | header, state | | [multiSort](/modules/multi-sort) | `multiSort()` | Shift+click sorts by several columns | `multiSort` | header | | [columnFilters](/modules/column-filters) | `columnFilters()` | Typed filter in each header | `columnFilters` | filters, toolbar | | [filterPanel](/modules/filter-panel) | `filterPanel()` | Binds your own filter form | `filterPanel` | request, filters | | [urlSync](/modules/url-sync) | `urlSync()` | View state in the query string | `urlSync` | lifecycle | | [responsive](/modules/responsive) | `responsive()` | Collapse columns on narrow screens | `responsive` | render, header | | [lazyColumns](/modules/lazy-columns) | `lazyColumns()` | Request costly columns only when visible | `lazyColumns` | request | | [stickyHeader](/modules/sticky-header) | `stickyHeader()` | Header stays visible while the page scrolls | `stickyHeader` | lifecycle | | [filterPresets](/modules/filter-presets) | `filterPresets()` | Named filter chips | `filterPresets` | filters, toolbar, state | | [autoRefresh](/modules/auto-refresh) | `autoRefresh()` | Silent reload on an interval | `autoRefresh` | toolbar, lifecycle | | [softDeletes](/modules/soft-deletes) | `softDeletes()` | "Show deleted" toggle | `softDeletes` | request, row, toolbar | | [actions](/modules/actions) | `actions()` | Row buttons and `⋯` menu | `actions` | row | | [selection](/modules/selection) | `selection()` | Checkboxes, select all, bulk bar | `selection` | row | | [rowReorder](/modules/row-reorder) | `rowReorder()` | Drag or keyboard-move rows, save in `onEnd` | `rowReorder` | row | | [keyboardGrid](/modules/keyboard-grid) | `keyboardGrid()` | Arrow-key cell navigation, one tab stop | `keyboardGrid` | lifecycle | | [excel](/modules/export) | `excel()` | `.xlsx` download | `excel` | toolbar, export | | [csv](/modules/export) | `csv()` | `.csv` download | `csv` | toolbar, export | | [print](/modules/export) | `print()` | Print view (and PDF) | `print` | toolbar, export | | [footer](/modules/footer) | `footer()` | Summary row in `` | `footer` | render, export | | [metaBind](/modules/meta-bind) | `metaBind()` | Response fields → page elements | `metaBind` | render | | [button.reload](/modules/buttons#button-reload) | `button.reload()` | Reload button | `reloadButton` | toolbar | | [button.resetState](/modules/buttons#button-resetstate) | `button.resetState()` | Reset the saved view | `resetStateButton` | toolbar | | [button.custom](/modules/buttons#button-custom) | `button.custom()` | Your own toolbar button | its `name` | toolbar | | [button.group](/modules/buttons#button-group) | `button.group()` | Toolbar dropdown | its `name` | toolbar | Pipelines: **request** = request middleware (adds parameters to server requests) · **filters** = writes the grid's filter state, which the protocol encodes · **row** = row mutator (runs after each row renders) · **toolbar** = toolbar slot · **state** = saved-state contribution · **export** = feeds the export sheet · **render** = repaints after each render · **header** = decorates the header row · **lifecycle** = init / load / destroy hooks. Data sources (`serverSide`, `arraySource`, `domSource`, `fetchAll`, `customSource`) are modules too, with exactly one per grid — see [Data sources](/guide/data-sources). ### Toolbar order Toolbar modules place themselves in a named slot with an `order` (lower first). colVis, the `button.*` modules, softDeletes, autoRefresh and filterPresets accept `slot` and `order` to move them. The shared Export menu (`start`, 40) moves with `slot` / `order` on the first export module attached (`excel({ slot: "end" })`); the column filter chips (`filters`, 100) have a fixed place. | Slot | Default contents (order) | |---|---| | `start` | search box (0) · colVis (10) · button.reload (20) · button.resetState (30) · Export menu (40) · button.custom (50) · button.group (60) | | `end` | autoRefresh (−20) · softDeletes (−10) · record count (`count: true`, 0) | | `filters` | filterPresets (−20) · columnFilters chips (100) | ## Presets A preset is just an array of modules. Put your house standard in one function and every list page becomes one line; arrays nest, so a preset can be mixed with page-specific modules. ```js import { serverSide, yajra, colVis, button, stateSave, excel, print } from "@akinozgen17/datagrids"; export const listPage = (url) => [ serverSide({ url, protocol: yajra(), csrf: true }), colVis(), button.reload(), stateSave(), excel(), print(), ]; ``` ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, colVis, button, stateSave, excel, print } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; // one array = one house standard for every list page const listPage = (url) => [ serverSide({ url, protocol: yajra(), csrf: true }), colVis(), button.reload(), stateSave(), excel(), print(), ]; new Datagrid("#mod-preset", { label: "Field agents (preset)", columns: [ { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], pageSize: 10, use: [listPage("/api/agents")], }); ``` ```html [HTML]
``` ::: Add page-specific modules next to it: `use: [listPage("/api/agents"), selection()]`. For declarative markup (`table[data-datagrid="list"]`), register the same array with [`preset()`](/reference/static). ## Permission flag `can` Every module accepts `can`. With `can: false` the module is still attached (so code that calls its API keeps working — the calls do nothing) but it contributes nothing: no button, no menu item, no request parameter, no state. ```js use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), excel({ can: user.canExport }), softDeletes({ can: user.isAdmin }), ]; ``` * **Columns** take the same flag: a column with `can: false` does not exist at all — it is not rendered, not in the column menu, not exported, not saved in state and not sent to the server. * **Row actions** are the only place where `can` may be a function of the row: `{ id: "delete", can: (row) => row.status !== "done" }`. See [actions](/modules/actions). * `can` is a UX flag. Your endpoints must still authorize every request. ## Module rules * One instance per module per grid: attaching the same module twice throws [DG009](/errors/DG009); two data sources throw [DG008](/errors/DG008). * A module that depends on another (`button.resetState` → `stateSave`) throws [DG007](/errors/DG007) when the dependency is missing. * Request middleware runs in attach order. See [Writing a module](/reference/modules) for the full module contract. --- --- url: https://akinozgen.github.io/datagrids/modules/state-save.md description: >- Remember each user's sort, page size and hidden columns per grid in localStorage, with versioning, a sliding expiry and a one-call reset. --- # stateSave Remembers how a user left the grid — sort, page size, hidden columns — and restores it on the next visit, before the first request. ::: code-group ```js [JavaScript] import { Datagrid, column, stateSave, colVis, button } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#mod-state-save-basic", { label: "Field agents (saved view)", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.text("task", { title: "Task", visible: false }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: agents(80), pageSize: 10, use: [stateSave(), colVis(), button.resetState()], }); const out = document.querySelector("#mod-state-save-out"); document.querySelector("#mod-state-save-show").addEventListener("click", () => { const saved = grid.state.read(); out.textContent = saved ? `${grid.state.key}\n${JSON.stringify(saved)}` : "Nothing stored yet."; }); ``` ```html [HTML]
Sort a column, change the page size or hide a column, then reload the page.
``` ::: ## When to use it Use it on list pages people return to every day and tune to their taste (hidden columns, a favourite sort). Skip it when the view must always open the same way (dashboards, embedded widgets), or when the state belongs in a shareable link — that is [urlSync](/modules/url-sync). Search text and the current page are **not** saved by default: a list that reopens filtered or on page 7 looks broken. Opt in per part with `include`. ## Usage ```js import { Datagrid, serverSide, yajra, stateSave } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), stateSave()], }); ``` Also keep the search text and the filter values: ```js stateSave({ include: ["search", "filters"] }); ``` Drop every stored state after you changed the columns in a way old states should not survive: ```js stateSave({ version: 2 }); ``` Per browser tab instead of per browser, and expire after a day of inactivity: ```js stateSave({ storage: sessionStorage, ttl: 24 * 60 * 60 * 1000 }); ``` ## Options | Option | Type | Default | Description | |---|---|---|---| | `key` | `string` | grid `name`, then the table `id`, then `"grid"` | Id part of the storage key. The full key is `dg:1::`. | | `version` | `number` | `1` | A stored state with another version is discarded (and removed). | | `ttl` | `number` (ms) | 90 days | Maximum age. Restoring refreshes the timestamp, so the expiry slides with use. `0` never expires. | | `include` | `Array<"search" \| "filters" \| "page">` | `[]` | Extra parts to save. Sort, page size and hidden columns are always saved. | | `storage` | `Storage \| null` | `localStorage` | Any Web Storage object; `null` disables persistence (the API still works). | | `delay` | `number` (ms) | `250` | Write debounce. Pending writes are flushed on `pagehide` and `destroy()`. | | `can` | `boolean` | `true` | Permission flag: `false` attaches the module but saves and restores nothing. | ## API added to the grid Available as `grid.state` (typed: `grid.module(stateSave)`). | Member | Returns | Description | |---|---|---| | `key` | `string` | The storage key in use. | | `save()` | `void` | Writes the current state now (skips the debounce). | | `read()` | `StatePayload \| null` | The stored payload; `null` when missing, expired, from another version or unreadable. | | `clear()` | `void` | Removes the stored state. The current view stays as it is. | | `reset()` | `Promise` | Removes the stored state, restores the initial view (columns, sort, page size, opted-in parts) and reloads once. Never reloads the page. | The stored payload is `{ v, t, fp, core: { sort, pageSize, hidden, search?, filters?, page? }, modules }` — `fp` is the list of column keys at save time, `modules` holds what other modules contributed. ## Events None of its own. It saves after `sort`, `pagesize` and `columnchange` (plus `search`, `page` and `load` for the opted-in parts). ## Pipelines it plugs into * **State**: owns the state pipeline. Other modules contribute their own part (`ctx.state({ key, save, load })`), stored under `modules`. * **Lifecycle**: restores in the grid's ready phase, after the columns are resolved and before the first load — the first request already carries the restored sort and page size. ## Works with * **Enhanced by** [button.resetState](/modules/buttons#button-resetstate) (a toolbar button for `grid.state.reset()`) and [colVis](/modules/colvis) (hidden columns are saved). * **With [urlSync](/modules/url-sync)**: the URL wins over the stored state at init, so a shared link always opens what it says. * **With [filterPanel](/modules/filter-panel)**: `include: ["filters"]` also saves the panel's control values and sets the controls back on restore (and on `reset()`), next to filters set through `grid.filters()` or [columnFilters](/modules/column-filters). ## Accessibility No UI of its own. Restoring happens before the first render, so assistive technology hears no extra sort or page announcements. ## Replaces in DataTables | DataTables (1.10 / 2.x / 3.x) | datagrids | |---|---| | `stateSave: true` | `stateSave()` | | `stateDuration` (seconds; `-1` = sessionStorage) | `ttl` (ms), `storage: sessionStorage` | | `stateSaveParams` deleting `search` / `start` | Nothing — search and page are not saved by default | | `stateLoadParams` guarding against changed columns | Nothing — unknown columns and sort keys are dropped automatically | | `table.state.clear()` + `location.reload()` | `grid.state.reset()` | ## Gotchas * **The search box is empty after a reload.** By design; add `include: ["search"]`. * **The same grid on two URLs remembers two different views.** The storage key ends with `location.pathname`; query string and hash are ignored. * **A renamed or removed column lost its saved sort.** Sort keys that no longer exist (or are no longer sortable) are dropped; columns added since the save keep their default visibility. * **Saved page size is smaller than expected.** Restored sizes are clamped to `maxPageSize`. * **Nothing persists in a private window or a sandboxed iframe.** When storage is not writable the module logs one console warning and the grid works without persistence. * **Changes made in the last 250 ms are lost.** They are not: a pending write is flushed on `pagehide` and on `destroy()`. ## Related * [button.resetState](/modules/buttons#button-resetstate) · [colVis](/modules/colvis) · [urlSync](/modules/url-sync) * [Writing a module](/reference/modules) — contributing to the state pipeline --- --- url: https://akinozgen.github.io/datagrids/modules/colvis.md description: >- A "Columns" toolbar menu with native checkboxes to show and hide columns, locked columns, show all and reset to default. --- # colVis Adds a **Columns** button to the toolbar. Its panel lists every column with a checkbox; the badge shows how many are visible. ::: code-group ```js [JavaScript] import { Datagrid, column, colVis } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; new Datagrid("#mod-colvis-basic", { label: "Field agents (column menu)", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name", hideable: false }), column.text("unit", { title: "Unit" }), column.text("task", { title: "Task", visible: false }), column.text("place", { title: "Place", visible: false }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], data: agents(60), pageSize: 10, use: [colVis()], }); ``` ```html [HTML]
``` ::: ## When to use it Use it when a list has more columns than most people need at once: define the rarely used ones with `visible: false` and let users opt in. Combine it with [stateSave](/modules/state-save) so the choice survives the next visit. Skip it on small grids where every column matters. ## Usage ```js import { Datagrid, column, colVis } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns: [ column.text("name", { title: "Name", hideable: false }), // locked: always visible column.text("unit", { title: "Unit" }), column.text("task", { title: "Task", visible: false }), // hidden until the user opts in ], data: rows, use: [colVis()], }); ``` Move the button to the end of the toolbar and rename it: ```js colVis({ slot: "end", messages: { button: "Fields" } }); ``` ## Options | Option | Type | Default | Description | |---|---|---|---| | `searchAbove` | `number` | `12` | Shows a "Find column…" field in the panel when the menu lists more columns than this. | | `slot` | `"start" \| "end"` | `"start"` | Toolbar slot. | | `order` | `number` | `10` | Position inside the slot (lower first). | | `messages` | `Partial` | locale (`en` / `tr`) | `button`, `legend`, `showAll`, `reset`, `search`, `searchLabel`, `noMatch`, `locked`. | | `can` | `boolean` | `true` | Permission flag: `false` → no button. | Column options that matter here: `visible` (initial visibility, also what "Reset to default" restores) and `hideable: false` (the box is disabled and shows a lock). ## API added to the grid Available as `grid.colVis` (typed: `grid.module(colVis)`). | Member | Returns | Description | |---|---|---| | `open()` | `void` | Opens the panel and focuses the first checkbox (or the search field). | | `close()` | `void` | Closes the panel and returns focus to the button. | | `toggle()` | `void` | Opens or closes. | | `reset()` | `void` | Restores the visibility from the column definitions. | | `count()` | `{ visible, total }` | Visible / total of the columns the menu lists. | To change visibility from code, use the core method `grid.setColumnVisible(key, visible)`. ## Events None of its own. Every change emits the core `columnchange` event. ## Pipelines it plugs into * **Toolbar**: `start` slot, order `10`. * **State**: nothing of its own — hidden columns are part of the core state that [stateSave](/modules/state-save) stores. ## Works with * **Enhanced by** [stateSave](/modules/state-save) (remembers the choice) and [button.resetState](/modules/buttons#button-resetstate). * **Export**: [excel, csv and print](/modules/export) include visible columns only. * **Server grids**: hidden columns are still sent in `columns[]`, in their original order, so index-based controllers keep working. ## Accessibility * The button's accessible name includes the count ("Columns 5/6"), even when a narrow grid hides the text. It has `aria-haspopup="dialog"` and `aria-controls`. * The panel is a labelled `role="dialog"` with a `
`/`` of native checkboxes. Locked columns are disabled and say why ("This column can't be hidden"). * Keys: arrows, `Home` and `End` move between checkboxes; `Space` toggles; `↓` in the search field jumps to the list; `Esc` clears the search, then closes; `Tab` past either end closes the panel and returns to the button. ## Replaces in DataTables | DataTables | datagrids | |---|---| | Buttons `colvis` button (1.10 / 2.x / 3.x), the retired ColVis extension (1.10) | `colVis()` | | `columns.visible: false` | `visible: false` on the column | | `className: "noVis"` + `columns: ":not(.noVis)"` | `hideable: false` | | `colvisRestore` button | "Reset to default" in the panel, `grid.colVis.reset()` | ## Gotchas * **A column is missing from the menu.** Columns without a `title`, and the special select / actions / row-number columns, are not listed. * **A checkbox can't be unchecked.** The column has `hideable: false`; the row shows a lock. * **A hidden column is not in the Excel file.** Exports follow what is visible; set the column visible (or use `exportValue` on a visible one). * **Only the icon and "5/6" are visible.** On narrow grids the button text collapses; the accessible name and the tooltip keep the full label. ## Related * [stateSave](/modules/state-save) · [button.resetState](/modules/buttons#button-resetstate) · [Columns](/guide/columns) --- --- url: https://akinozgen.github.io/datagrids/modules/col-reorder.md description: >- Let users reorder columns by dragging a header or with move buttons in the column menu; display order only, requests keep the definition order. --- # colReorder Lets users change the column order: drag a header by its grip, or use the move buttons that appear in the [colVis](/modules/colvis) panel. ::: code-group ```js [JavaScript] import { Datagrid, column, colReorder, colVis, stateSave } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#mod-col-reorder-basic", { label: "Field agents (reorderable columns)", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: agents(60), pageSize: 8, use: [colReorder(), colVis(), stateSave()], }); const out = document.querySelector("#mod-col-reorder-out"); grid.on("columnchange", () => (out.textContent = `grid.colReorder.order() → ${JSON.stringify(grid.colReorder.order())}`)); document.querySelector("#mod-col-reorder-reset").addEventListener("click", () => grid.colReorder.reset()); ``` ```html [HTML]
Drag a header by its grip, or use the arrows in the Columns menu.
``` ::: ## When to use it Use it on wide lists where people have their own idea of which columns belong first. Pair it with [stateSave](/modules/state-save) so the order survives the next visit, and with [colVis](/modules/colvis) so keyboard users can reorder too. Skip it when the column order carries meaning (a fixed report layout). ## Usage ```js import { Datagrid, colReorder, colVis, stateSave } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, data: rows, use: [colReorder(), colVis(), stateSave()], }); ``` Move buttons only (no header dragging), for example on touch-heavy screens: ```js colReorder({ drag: false }); ``` Set the order from code. Special columns (select, actions, row number) and `sticky` columns keep their slots; only the others move: ```js grid.colReorder.move("amount", 0); // first among the movable columns grid.colReorder.reset(); // back to the definition order ``` ## Options | Option | Type | Default | Description | |---|---|---|---| | `drag` | `boolean` | `true` | Header dragging. The move buttons in the colVis panel are available either way. | | `messages` | `Partial` | locale (`en` / `tr`) | `earlier(col)`, `later(col)` (move button names), `moved(col, pos, total)` (announcement), `hint` (grip tooltip). | | `can` | `boolean` | `true` | Permission flag: `false` → no grips, no move buttons, no saved order. | ## API added to the grid Available as `grid.colReorder` (typed: `grid.module(colReorder)`). | Member | Returns | Description | |---|---|---| | `order()` | `string[]` | Current display order of all column keys. | | `move(key, to)` | `void` | Moves a column to index `to` among the movable columns (0-based). | | `reset()` | `void` | Restores the definition order. | | `movable()` | `ResolvedColumn[]` | Columns that can move (not special, not sticky). | | `messages` | `ColReorderMessages` | The resolved messages (colVis uses them for its buttons). | The core method behind it is `grid.columnOrder(keys?)`. ## Events None of its own. Every move emits the core `columnchange` event. ## Pipelines it plugs into * **Header**: a grip in each movable header; pointer dragging shows a drop line between headers. * **State**: contributes `colReorder` (the movable column keys in order) to [stateSave](/modules/state-save); `grid.state.reset()` restores the definition order. * **Display only**: server requests keep the definition order — `columns[i]` indexes never change, so index-based controllers keep working. Exports follow the display order. ## Works with * **Enhanced by** [colVis](/modules/colvis) (move buttons next to each checkbox) and [stateSave](/modules/state-save) (remembers the order). * **Sticky and special columns** (`column.select()`, `column.actions()`, `sticky`) stay where they are. ## Accessibility * Dragging is pointer-only, so the keyboard alternative lives in the colVis panel: "Move Amount earlier" / "Move Amount later" buttons on every row. Attach [colVis](/modules/colvis) whenever you attach colReorder. * Each move is announced in the grid's live region: "Amount moved to position 3 of 5." * On touch screens a drag starts only from the grip, so the header can still scroll the table sideways. `Esc` cancels a drag in progress; a finished drag never triggers the header's sort. ## Replaces in DataTables | DataTables | datagrids | |---|---| | ColReorder extension, `colReorder: true` (1.10 / 2.x / 3.x) | `colReorder()` | | `colReorder.order()` / `colReorder.reset()` | `grid.colReorder.order()` / `grid.colReorder.reset()` | | `stateSave` with ColReorder | `stateSave()` stores the order automatically | ## Gotchas * **A column has no grip and doesn't move.** It is a special or `sticky` column; those keep their slots. * **Keyboard users can't reorder.** Attach [colVis](/modules/colvis); its panel carries the move buttons. * **"Reset to default" in the Columns menu kept my order.** That button resets visibility only; use `grid.colReorder.reset()` or [button.resetState](/modules/buttons#button-resetstate). * **The server still sees the old order.** By design: requests always use the definition order. ## Related * [colVis](/modules/colvis) · [stateSave](/modules/state-save) · [Columns](/guide/columns) --- --- url: https://akinozgen.github.io/datagrids/modules/responsive.md description: >- When the table is wider than its frame, collapse the least important columns and show their values in an expandable detail row. --- # responsive When the table no longer fits its frame, the least important columns collapse one by one, and every row gets an expand button that shows the collapsed values in a detail row. ::: code-group ```js [JavaScript] import { Datagrid, column, responsive } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#mod-responsive", { label: "Field agents (responsive)", columns: [ column.text("name", { title: "Name" }), column.text("ref", { title: "Ref" }), column.text("unit", { title: "Unit" }), column.text("task", { title: "Task" }), column.text("place", { title: "Place" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date", time: true }), ], data: agents(40), pageSize: 6, use: [responsive({ priority: { name: 1, status: 2, amount: 3 } })], }); const out = document.querySelector("#mod-responsive-out"); grid.on("collapse", ({ columns }) => (out.textContent = `collapsed: ${columns.join(", ") || "none"}`)); ``` ```html [HTML]
collapsed: none
``` ::: ## When to use it Use it for lists that must stay readable on phones and narrow panels without horizontal scrolling. Skip it when people compare many columns side by side — horizontal scrolling with a [sticky](/guide/columns) first column is better there. ## Usage ```js import { Datagrid, responsive } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, use: [responsive({ priority: { name: 1, status: 2, amount: 3 } })], }); ``` Columns collapse from the **highest** priority number down; columns without a priority come after the listed ones, last column first. The first data column never collapses — it carries the expand button — and neither do `sticky` columns or the ones in `keep`: ```js responsive({ keep: ["status"] }); // never collapse Status responsive({ details: false }); // just drop columns, no expand buttons ``` The grid measures its frame with a `ResizeObserver`, after every render and after column changes. If your layout changes in a way the frame does not notice, call `grid.responsive.refit()`. ## Options | Option | Type | Default | Description | |---|---|---|---| | `priority` | `Record` | definition order | Lower numbers are kept longer. | | `keep` | `string[]` | `[]` | Columns that never collapse (the first data column and sticky columns never do). | | `details` | `boolean` | `true` | Expand buttons and detail rows with the collapsed values. | | `messages` | `{ show, hide }` | locale (`en` / `tr`) | Expand button names: "Show hidden columns" / "Hide hidden columns". | | `can` | `boolean` | `true` | Permission flag: `false` → nothing collapses. | ## API added to the grid Available as `grid.responsive` (typed: `grid.module(responsive)`). | Member | Returns | Description | |---|---|---| | `collapsed()` | `string[]` | Keys of the columns collapsed right now. | | `refit()` | `void` | Measures again. | | `toggle(rowKey, open?)` | `void` | Opens or closes a row's detail. | ## Events | Event | Payload | When | |---|---|---| | `collapse` | `{ columns: string[] }` | The set of collapsed columns changed. | ## Pipelines it plugs into * **Render**: after each render it marks collapsed cells (`data-dg-collapsed`, hidden by the stylesheet), adds the expand button to the first data cell and re-creates open detail rows. * **Header**: header cells of collapsed columns are hidden the same way. * **Lifecycle**: a `ResizeObserver` on the frame; everything is removed on `destroy()`. ## Works with * **With [colVis](/modules/colvis)**: independent. colVis decides which columns exist on screen; responsive only collapses visible ones and never changes the user's choices. * **Export**: collapsed columns are still visible columns, so [exports](/modules/export) include them. * **Virtual rows** (`virtual: true`): collapsing is switched off while rows are virtualized. ## Accessibility * The expand button is a native `
``` ::: On a client grid the same module writes the values into the grid's filter state instead. A `format` function can turn a raw value into a typed filter (`{ op, value }`) or `null`: ::: code-group ```js [JavaScript] import { Datagrid, column, filterPanel } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const grid = new Datagrid("#mod-filter-panel-client", { label: "Field agents (filter panel, in the browser)", columns: [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), ], data: agents(120), pageSize: 10, use: [ filterPanel({ fields: { unit: "#mod-fpc-unit", amount: { el: "#mod-fpc-min", format: (v) => (v ? { op: "gte", value: Number(v) } : null) }, }, }), ], }); const out = document.querySelector("#mod-fpc-out"); grid.on("load", () => (out.textContent = `grid.filters() → ${JSON.stringify(grid.filters())}`)); ``` ```html [HTML]
``` ::: ## When to use it Use it for page-level filters that live outside the table: a unit select, a date range, "only my records". It replaces the hand-written "read the form in `ajax.data`, reload on change" glue. For a filter attached to one column header, use [columnFilters](/modules/column-filters). ## Usage Map each request parameter (server) or filter key (client) to a control. A selector string is resolved on every read, so controls that your framework re-renders keep working. ```js import { Datagrid, serverSide, yajra, filterPanel } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), filterPanel({ fields: { unit: "#unit", // → an array name: "#name", // text input, debounced mine: { el: "#mine", value: "1", unchecked: null }, // checkbox: "1" or left out }, }), ], }); ``` The server receives `unit=R.P.D.&status[]=open&status[]=pending&name=wong&mine=1` next to the protocol parameters. ### Field spec A field is a selector, an element, or a `FilterField` object: | Property | Type | Description | |---|---|---| | `el` | `string \| Element` | The control, or a container of it. Selectors are resolved on every read. | | `value` | `string` | Checkbox: the value while checked. Default `"1"`. | | `unchecked` | `string \| null` | Checkbox: the value while unchecked. Default `"0"` on server grids, no filter on client grids; `null` leaves the parameter out. | | `format` | `(v, el) => unknown` | Maps the raw value to what is sent / filtered. `null` or `undefined` leaves it out. | | `subscribe` | `(el, notify) => void \| (() => void)` | For widgets that don't fire native `change` events: call `notify()` when the value changed; return a cleanup function. | Controls are read like jQuery's `.val()`: a `
``` ::: ## When to use it Use it when people share or bookmark list views ("send me the link to the open R.P.D. records"), or when the browser's reload and back button must keep the view. It works the same on client and server grids. For per-user preferences that are not part of a link (hidden columns, page size), use [stateSave](/modules/state-save); both can run together. ## Usage ```js import { Datagrid, serverSide, yajra, filterPanel, urlSync } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), filterPanel({ fields: { unit: "#unit", status: "#status" } }), urlSync(), ], }); // → /agents?q=wong&sort=-amount&page=3&f.unit=R.P.D.&f.status=open&f.status=pending ``` | Key | Holds | Example | |---|---|---| | `q` | Search text | `q=wong` | | `sort` | Sort keys, `-` for descending, comma-separated. Written only when it differs from the configured `sort`; an empty `sort=` means "no sort" | `sort=-amount,name` | | `page` | Page number, only when > 1 | `page=3` | | `f.` | A filter value; repeated for arrays | `f.status=open&f.status=pending` | Two grids on one page, or keys that must not clash with your own parameters — use a namespace: ```js urlSync({ namespace: "agents" }); // agents.q, agents.sort, agents.page, agents.f.unit urlSync({ namespace: true }); // the grid's name (or table id) as the namespace ``` Add a history entry per change, so the back button walks through earlier views: ```js urlSync({ mode: "push" }); ``` Sync filters set with `grid.filters()` instead of (or besides) filterPanel fields: ```js urlSync({ keys: ["unit", "status"] }); ``` ## Options | Option | Type | Default | Description | |---|---|---|---| | `keys` | `string[]` | the [filterPanel](/modules/filter-panel) field keys | Filter keys written as `f.`. | | `namespace` | `string \| boolean` | none | Key prefix (`.q`); `true` = the grid's name or table id. A second grid without one is prefixed automatically (with a console warning). | | `mode` | `"replace" \| "push"` | `"replace"` | `replace` rewrites the current history entry; `push` adds one per change and follows back / forward. | | `can` | `boolean` | `true` | Permission flag: `false` → the URL is neither read nor written. | ## API added to the grid Available as `grid.urlSync` (typed: `grid.module(urlSync)`). | Member | Returns | Description | |---|---|---| | `link()` | `string` | Absolute URL of the current view (other query parameters and the hash are kept). | ## Events None of its own. ## Pipelines it plugs into * **Lifecycle (init)**: reads the URL in the grid's ready phase, before the first load, so the first request already carries the linked view. The URL wins over a state restored by [stateSave](/modules/state-save). * **Lifecycle (changes)**: writes after `search`, `sort`, `page` and every load. Writing starts after the first load, so opening a page never adds a history entry. * **History**: in `push` mode it listens to `popstate` and restores the view of that entry. ## Works with * **Enhances** [filterPanel](/modules/filter-panel): the panel's controls are set from the URL (and their `change` events fire, so widgets follow). * **With [stateSave](/modules/state-save)**: both can be attached; the link decides, stored state fills in the rest (hidden columns, page size). * **With [columnFilters](/modules/column-filters)**: typed `{ op, value }` filters are not written to the URL — only plain values and arrays of plain values are. ## Accessibility No UI of its own. In `push` mode the browser's back and forward buttons (and their keyboard shortcuts) move between views, which is what most users expect from a filtered list. ## Replaces in DataTables No direct equivalent in 1.10, 2.x or 3.x. The usual approach was reading `location.search` into `search.search`, `order` and `displayStart` by hand and writing it back from a `draw` handler. ## Gotchas * **The back button leaves the page instead of going to the previous view.** The default mode is `replace`; use `mode: "push"`. * **The link has no `sort`.** The configured default sort is never written; only a different one is. * **`?page=40` opened page 12.** A page past the end is corrected once the row count is known. * **A second grid's search ended up in the first grid.** Give each grid a `namespace` (a grid without one is prefixed automatically after the first). * **Column filters are missing from the shared link.** Typed filters are not written; use a filterPanel field for filters that must be shareable. ## Related * [filterPanel](/modules/filter-panel) · [stateSave](/modules/state-save) · [Lifecycle](/guide/lifecycle) --- --- url: https://akinozgen.github.io/datagrids/modules/soft-deletes.md description: >- A "Show deleted" toolbar toggle that sends _deleted=1 to the server (or filters in the browser) and mutes deleted rows. --- # softDeletes Adds a **Show deleted** toggle to the toolbar. While it is on, server requests carry `_deleted=1` and deleted rows are shown muted; while it is off, they are hidden. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, softDeletes } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; new Datagrid("#mod-soft-deletes", { label: "Field agents (soft deletes)", columns: [ { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.date("deleted_at", { title: "Deleted", time: true }), ], sort: [["deleted_at", "desc"]], pageSize: 10, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), softDeletes(), ], }); ``` ```html [HTML]
``` ::: ## When to use it Use it on lists backed by soft-deleted records (Laravel's `SoftDeletes`) where admins sometimes need to see — and restore — what was deleted. Skip it when deleted records have their own page. ## Usage ```js import { Datagrid, serverSide, yajra, softDeletes } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Field agents", columns, use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), softDeletes()], }); ``` The controller decides what `_deleted=1` means: ```php $query = Agent::query()->when($request->boolean('_deleted'), fn ($q) => $q->withTrashed()); ``` Start switched on when the page was opened with `?deleted=1`, and only for admins: ```js softDeletes({ initial: new URLSearchParams(location.search).has("deleted"), can: user.isAdmin, }); ``` On a client grid (array, DOM, fetchAll) the toggle filters in the browser: deleted rows are hidden until it is switched on. ## Options | Option | Type | Default | Description | |---|---|---|---| | `param` | `string` | `"_deleted"` | Request parameter sent while on (server grids). On client grids, the filter key. | | `value` | `unknown` | `1` | Its value. | | `field` | `string` | `deleted`, then `deleted_at` | Row field (dotted path allowed) that marks a deleted row; any truthy value counts. | | `label` | `string` | "Show deleted" | Button text and accessible name. | | `initial` | `boolean` | `false` | Start switched on. | | `messages` | `{ label }` | locale (`en` / `tr`) | Translations. | | `slot` | `"start" \| "end"` | `"end"` | Toolbar slot. | | `order` | `number` | `-10` | Position inside the slot (before the record count). | | `can` | `boolean` | `true` | Permission flag: `false` → no button, no parameter. | ## API added to the grid Available as `grid.softDeletes` (typed: `grid.module(softDeletes)`). | Member | Returns | Description | |---|---|---| | `active()` | `boolean` | `true` while deleted rows are shown. | | `toggle(on?)` | `void` | Switches (or sets) the mode and reloads (server) or re-filters (client). | ## Events None of its own. Toggling reloads a server grid (`beforeLoad`, `load`). ## Pipelines it plugs into * **Request middleware**: adds `param=value` while on. * **Filters** (client grids): a row predicate under the `param` key; functions never reach the wire. * **Row mutator**: sets `data-tone="muted"` on deleted rows. * **Toolbar**: `end` slot, order `-10`. ## Works with * **Enhances** [actions](/modules/actions): show a "Restore" action only on deleted rows with `can: (row) => !!row.deleted_at`. * **With [filterPanel](/modules/filter-panel)**: independent; both add their parameters. * The toggle is not saved by [stateSave](/modules/state-save) or written by [urlSync](/modules/url-sync); use `initial` to restore it. ## Accessibility The toggle is a real `
``` ::: Change the filters and look at the address bar: `?f.status=pending&f.unit=R.P.D.&f.name=redfield`. Reload the page with that URL and the form, the search box and the grid come back in the same state. ## Steps ### 1. Write the form as plain HTML Any native control works: ``, text inputs, checkboxes, radio groups. The demo's **HTML** tab has the markup. Nothing in it is grid-specific. ### 2. Map request parameters to controls with `filterPanel` ```js filterPanel({ fields: { status: "#status", // → unit[]=R.P.D.&unit[]=B.S.A.A. name: "#name", // text input → name=redfield (debounced) }, }), ``` The keys are the request parameter names. On a server grid the values are read **when each request is built** (the same moment an old `ajax.data` function ran) and added as top-level parameters next to the protocol's own. Changing a `` and fire `change` need nothing extra; `filterPanel.set()` dispatches `change` so they repaint. * **Two grids with `urlSync()` on one page:** give each its own key prefix with `urlSync({ namespace: "orders" })` (`orders.q=…`), or `namespace: true` for the grid's `name`. Without one, the second grid falls back to its name (or table id) and logs a warning. * **History:** `urlSync()` replaces the current history entry by default. `urlSync({ mode: "push" })` adds entries and follows the back/forward buttons. ## Related * [filterPanel module](/modules/filter-panel) — every option and API method * [urlSync module](/modules/url-sync) * [Laravel + yajra list](/recipes/laravel-yajra#extra-page-parameters) — `params` for one or two values * [Selection + bulk action](/recipes/bulk-actions) — applying an action to "all matching" rows --- --- url: https://akinozgen.github.io/datagrids/recipes/bulk-actions.md description: >- Select rows across pages or all rows matching the current search, then send one POST that handles both payload shapes. --- # Selection + bulk action **Goal:** users tick rows on any page — or pick "all matching" without loading thousands of rows — and one button sends a single request the server can act on. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, selection } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; const out = document.querySelector("#rcp-bulk-payload"); const note = document.querySelector("#rcp-bulk-note"); const grid = new Datagrid("#rcp-bulk", { label: "Field agents (bulk)", columns: [ column.select(), { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), ], pageSize: 5, // demo only: show notifications on the page (usually configure({ notify }) once, see Row actions) host: { notify: (kind, message) => (note.textContent = `${kind}: ${message}`) }, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), selection({ bulk: { actions: [ { id: "remind", label: "Send reminder", icon: "send", // the returned promise keeps the button busy until the request settles onClick: async (payload, grid, sel) => { const result = await grid.action("/api/action/agents/bulk/remind", { body: payload, // { all: false, keys } or { all: true, except, query } confirm: `Send a reminder to ${sel.count()} agents?`, success: "Reminders queued.", reload: false, // nothing in the list changed }); if (result !== undefined) sel.clear(); // undefined = the user cancelled }, }, ], }, }), ], }); grid.on("selectionchange", () => (out.textContent = JSON.stringify(grid.selection.payload(), null, 2))); ``` ```html [HTML]
Notifications appear here.
Select rows to see the payload.
``` ::: Try both shapes: tick two rows on different pages, then tick the header checkbox and press **Select all 941 matching** and untick one row. The payload under the grid is exactly what **Send reminder** posts; the **Request** tab shows it on the wire. ## Steps ### 1. Add the checkbox column and the selection module ```js columns: [column.select(), /* … */], use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), selection({ bulk: { actions: [/* … */] } }), ], ``` `column.select()` places the checkbox column; `selection()` fills it, adds the header checkbox and the bulk bar above the table. Selection survives paging, sorting and searching: rows are tracked by key (`id`, else `DT_RowId`, or your `rowKey`). ### 2. Post the payload with `grid.action()` Each bulk action gets `(payload, grid, selection)`. Hand the payload to [`grid.action()`](/reference/methods) — it asks for confirmation, sends JSON with the CSRF header, reports the result and reloads the grid (keeping the page) unless you say `reload: false`: ```js onClick: async (payload, grid, sel) => { const result = await grid.action("/agents/bulk/remind", { body: payload, confirm: `Send a reminder to ${sel.count()} agents?`, }); if (result !== undefined) sel.clear(); // undefined = the user cancelled }, ``` Return the promise (an `async` function does): the bar keeps its buttons disabled until it settles, so nobody double-submits. ### 3. Handle both shapes on the server | `payload` | Meaning | |---|---| | `{ all: false, keys: ["1998", "2000"] }` | exactly these rows | | `{ all: true, except: ["1999"], query: { search, sort, filters, params } }` | every row matching `query`, minus `except` | Keys are strings. `query` is the grid's state when "all matching" was chosen — paging left out. `query.params` holds the page parameters of the request behind the rows on screen at that moment ([`grid.lastRequestParams()`](/reference/methods)): values from a [filter panel](/recipes/filter-panel), [softDeletes](/modules/soft-deletes) or the source's `params`, without `_token`. ```php // routes/web.php Route::post('/agents/bulk/remind', [AgentBulkController::class, 'remind']); ``` ```php // app/Http/Controllers/AgentBulkController.php public function remind(Request $request) { $data = $request->validate([ 'all' => ['required', 'boolean'], 'keys' => ['exclude_if:all,true', 'required', 'array', 'max:1000'], 'keys.*' => ['integer'], 'except' => ['array'], 'except.*' => ['integer'], 'query.search' => ['nullable', 'string', 'max:200'], ]); $agents = $data['all'] ? Agent::query()->listSearch($data['query']['search'] ?? null)->whereKeyNot($data['except'] ?? []) : Agent::query()->whereKey($data['keys']); $count = 0; $agents->chunkById(500, function ($chunk) use (&$count) { foreach ($chunk as $agent) { $this->authorize('remind', $agent); SendReminder::dispatch($agent); $count++; } }); return response()->json(['message' => "Reminder queued for {$count} agents."]); } ``` ```php // app/Models/Agent.php — one search definition, used by the list endpoint and the bulk endpoint public function scopeListSearch(Builder $query, ?string $term): void { $query->when($term, fn ($q) => $q->where(fn ($q) => $q ->where('name', 'like', "%{$term}%") ->orWhere('ref', 'like', "%{$term}%"))); } ``` Rebuild "all matching" with the **same** search and filter code the list uses. If the bulk endpoint searches differently, it acts on rows the user never saw. ## Notes * **Page filters are in `payload.query.params`.** Rebuild "all matching" from them on the server together with `search` and `filters`; no need to send the form values separately. * **"All matching" resets itself** when the search, filters or page parameters change, or when the matching count changes on reload, and the live region says so. A stale "all" never reaches your endpoint. * **The success message:** `grid.action()` shows `success` if you pass it, else the `message` of the JSON response, else a generic "Done.". Pass `success: false` to stay silent. The demo passes `success` because its server returns no message. * **Notifications** go to your `notify` adapter (toast library) when one is configured; without one they are announced to screen readers and errors also appear as a banner. See [Row actions](/recipes/row-actions#host-confirm-and-notify-adapters). * **`can: false`** on a bulk action removes its button — for the UI only; the endpoint must still authorize every row, as above. * Only the current page is in the browser on a server grid: `grid.selection.get()` returns the rows it has seen, `payload()` is what describes the whole selection. ## Related * [selection module](/modules/selection) — modes, options, API and events * [Row actions with confirm](/recipes/row-actions) * [Page filter panel](/recipes/filter-panel) --- --- url: https://akinozgen.github.io/datagrids/recipes/row-actions.md description: >- A per-row action menu with links, server requests, confirmation, permission flags and disabled reasons — plus your own confirm and toast libraries. --- # Row actions with confirm **Goal:** every row gets the same, predictable set of actions — open, approve, delete — with confirmation for destructive ones, permission-aware visibility, and a reason when an action is not available for that row. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, actions } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; const table = document.querySelector("#rcp-row-actions"); const can = JSON.parse(table.dataset.can); // permissions rendered by Blade const note = document.querySelector("#rcp-row-actions-note"); new Datagrid(table, { label: "Field agents (row actions)", columns: [ { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.actions({ title: "Actions" }), ], pageSize: 5, // demo only: show notifications on the page (usually configure({ notify }) once, see below) host: { notify: (kind, message) => (note.textContent = `${kind}: ${message}`) }, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), actions({ items: [ { id: "view", label: "View", icon: "eye", primary: true, href: "#agent-{id}" }, { id: "approve", label: "Approve", icon: "check", can: can.approve, request: { url: "/api/action/agents/{id}/approve" }, // POST + CSRF → notify → reload disabled: (row) => row.status === "done" ? "Already approved." : row.status === "cancelled" ? "Cancelled records can't be approved." : false, }, { id: "delete", label: "Delete", icon: "trash", tone: "danger", can: can.delete, confirm: "Delete {name}? This cannot be undone.", request: { url: "/api/action/agents/{id}", method: "DELETE" }, }, ], }), ], }); ``` ```html [HTML]
Notifications appear here.
``` ::: Open the **⋯** menu on a cancelled row: **Approve** is visible but inactive and says why. Approve a pending row, or delete one: the request goes out with the CSRF header, the result is reported, and the grid reloads on the same page. ## Steps ### 1. Place the column ```js columns: [/* … */, column.actions({ title: "Actions" })], ``` `column.actions()` is a placeholder the module fills. It is sticky at the end of a wide table, not sortable, not exported and never hidden by the column menu. ### 2. Describe the actions once Each item has **one** behavior: | Behavior | Item | What happens | |---|---|---| | link | `href: "/agents/{id}"` | navigates (`target: "_blank"` opens a new tab); `{field}` values are URL-encoded | | request | `request: { url: "/agents/{id}/approve", method: "POST" }` | runs [`grid.action()`](/reference/methods): confirm → request with CSRF → notify → reload on the same page | | handler | `handler: (row, { grid, key }) => openDrawer(row)` | your function; a returned promise keeps the row busy | With two actions or fewer they render as buttons in the cell. With more, the item marked `primary` stays a button and the rest move into a **⋯** menu (without a `primary`, one **Actions** menu button holds them all). `tone: "danger"` items always sink to the end, behind a separator. ### 3. Pass permissions from Blade ```blade @php($can = [ 'approve' => auth()->user()->can('approve', App\Models\Agent::class), 'delete' => auth()->user()->can('delete', App\Models\Agent::class), ])
``` ```js const can = JSON.parse(table.dataset.can); // … { id: "delete", label: "Delete", can: can.delete, /* … */ } ``` `@json` escapes quotes and `<`, so the attribute is safe. If your page script is inline in the Blade view, write the boolean directly: `can: @json(auth()->user()->can('delete', App\Models\Agent::class))`. `can` also takes a function of the row: `can: (row) => row.owner_id === userId`. ### 4. Explain row-state restrictions with `disabled` ```js disabled: (row) => (row.status === "cancelled" ? "Cancelled records can't be approved." : false), ``` `can: false` removes an action. `disabled` keeps it in place but inactive, with the reason next to it (and in its accessible name). Return `true` for "inactive, no reason". ### 5. Authorize on the server `can` is UX only: it hides what the user can't do. The endpoint must authorize every request. ```php // routes/web.php Route::post('/agents/{agent}/approve', [AgentController::class, 'approve'])->can('approve', 'agent'); Route::delete('/agents/{agent}', [AgentController::class, 'destroy'])->can('delete', 'agent'); ``` ```php public function approve(Agent $agent) { abort_if($agent->status === 'cancelled', 422, "Cancelled records can't be approved."); $agent->update(['status' => 'done']); return response()->json(['message' => "{$agent->name} approved."]); } public function destroy(Agent $agent) { $agent->delete(); return response()->json(['message' => 'Agent deleted.']); } ``` The JSON `message` becomes the success notification. A `403` or `422` becomes an error notification with the server's `message` (a `5xx` with a generic text), and the row stays as it was. ## Host confirm and notify adapters Without adapters the grid uses its own `` for confirmation and announces results to screen readers (errors also get a banner). To use your page's dialog and toast libraries everywhere, register them once, before any grid is created: ```js // resources/js/app.js import Swal from "sweetalert2"; import toastr from "toastr"; import { configure } from "@akinozgen17/datagrids"; configure({ confirm: async (message, o) => { const result = await Swal.fire({ title: o.title ?? "Are you sure?", text: message, // text, not html icon: o.tone === "danger" ? "warning" : "question", showCancelButton: true, confirmButtonText: o.confirmLabel ?? "OK", cancelButtonText: o.cancelLabel ?? "Cancel", }); return result.isConfirmed; }, notify: (kind, message) => toastr[kind](message), // kind: "success" | "error" | "info" }); ``` `confirm` receives the message and `{ title, tone, confirmLabel, cancelLabel, subject }`; a danger action passes `tone: "danger"` and its own label (**Delete**) as `confirmLabel`. Row actions, bulk actions and `grid.confirm()` / `grid.notify()` all go through these adapters. The demo sets `notify` per grid with the `host` option only to print messages on this page. ## Item reference | Option | Type | Description | |---|---|---| | `id` | `string` | unique per grid; `data-action` on the button | | `label` | `string` | visible text and accessible name | | `icon` | built-in icon name | e.g. `eye`, `check`, `edit`, `trash`, `send`, `copy` | | `tone` | `"danger" \| "warning" \| "success"` | `danger`: red, last in the menu, danger confirm | | `group` | `string` | menu section heading | | `primary` | `boolean` | stays a button when the rest collapse into the menu | | `can` | `boolean \| (row) => boolean` | permission; `false` removes the action | | `disabled` | `(row) => boolean \| string` | inactive for this row; a string is the reason shown | | `href` / `target` | `string` | link template (`{field}`, URL-encoded) | | `request` | `{ url, method?, body? }` | `grid.action()` call; `body` may be a function of the row | | `handler` | `(row, { grid, key }) => unknown` | custom behavior | | `confirm` | `string \| { title?, message, confirmLabel?, cancelLabel? }` | `{field}` placeholders allowed | | `success` | `string \| false` | overrides the server's `message`; `false` = silent | | `reload` | `false \| { keepPage? }` | after a request; default reloads on the same page | Module options (`inline`, `sticky`, `field` for a per-row permission map from the server, `reasons`, `rowLabel`) are on the [actions module](/modules/actions) page. ## Notes * **Events:** `beforeAction` (cancelable), `action` after success, `actionerror` with the error. * **Busy rows:** while a request runs, the row is `aria-busy` and its action buttons are disabled, so a double click can't send twice. * **Same origin only:** `grid.action()` refuses URLs on another origin. * **Redirects:** a redirect to a page that is not a login page (a controller answering with `return back()`) counts as success; a redirect to the login page is a session error. * **Session expiry** during an action: see [CSRF & session expiry](/recipes/csrf-and-session). ## Related * [actions module](/modules/actions) * [Selection + bulk action](/recipes/bulk-actions) * [Instance methods: action, confirm, notify](/reference/methods) --- --- url: https://akinozgen.github.io/datagrids/recipes/export.md description: >- Add Excel, CSV and print to a server grid, choose between the current page and all filtered rows, and hand huge exports to the server with grid.query(). --- # Export **Goal:** an **Export** menu on a server-paged list that produces real spreadsheets (numbers stay numbers, dates stay dates), exports exactly what the user filtered, and still works when the list is far too big to download through the browser. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, excel, csv, print } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; const today = () => new Date().toISOString().slice(0, 10); const grid = new Datagrid("#rcp-export", { label: "Field agents (export)", columns: [ { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], sort: [["date", "desc"]], pageSize: 10, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), excel({ scope: "all", filename: () => `agents-${today()}` }), // every filtered row, one request csv({ scope: "all", filename: () => `agents-${today()}` }), print(), // the current page ], }); // Too many rows for the browser? Let the server build the file for the current query. const out = document.querySelector("#rcp-export-url"); grid.on("load", () => { const { search, sort, filters } = grid.query(); const params = new URLSearchParams({ ...grid.lastRequestParams(), // page parameters as last sent (none in this demo) ...filters, search, sort: sort.map((s) => (s.dir === "desc" ? "-" : "") + s.key).join(","), }); out.textContent = `/agents/export.csv?${params}`; }); ``` ```html [HTML]
Server export link:
``` ::: Search for something, then open **Export → CSV**: the file holds every matching row, not just the visible page. The link under the grid is what a server-side export would receive for the same view. ## Steps ### 1. Attach the export modules ```js use: [ serverSide({ url: "/agents/data", protocol: yajra(), csrf: true }), excel({ scope: "all", filename: () => `agents-${today()}` }), csv({ scope: "all", filename: () => `agents-${today()}` }), print(), ], ``` The three modules share one **Export** menu in the toolbar. Attach only the ones you want. Excel files are written by the library itself (no spreadsheet dependency). ### 2. Pick the scope | `scope` | Exports | Default for | |---|---|---| | `"page"` | the rows on screen | server grids | | `"all"` | every row matching the current search, sort, filters and page parameters | client grids | On a server grid, `"all"` makes **one** extra request with the current query and `pageSize = maxPageSize` (1000 by default). If more rows match, the file holds the first 1000 and the user is told how many were left out. Raise the cap per grid with `maxPageSize` only if your endpoint can answer that many rows quickly; otherwise use step 4. ### 3. Check what each column exports * Typed columns export typed values: `column.money()` and `column.number()` real numbers, `column.date()` real dates, `column.badge()` its label. * HTML cells (the yajra default, `column.html()`) are exported as their plain text. * Leave a column out with `exportable: false`; override a value with `exportValue: (row) => …`. Selection and action columns are never exported. * CSV uses `,` (`;` for Turkish locales), adds a UTF-8 byte order mark so spreadsheet apps detect the encoding, and prefixes cells that start with `=`, `+`, `-` or `@` with `'` so they can't run as formulas. ### 4. Export huge lists on the server For tens of thousands of rows, don't page through the API from the browser. Send the current query to an export endpoint and let it stream the file: ```js document.querySelector("#export-all").addEventListener("click", () => { const { search, sort, filters } = grid.query(); const params = new URLSearchParams({ ...grid.lastRequestParams(), // page parameters (filter panel, params…) as last sent ...filters, search, sort: sort.map((s) => (s.dir === "desc" ? "-" : "") + s.key).join(","), }); location.assign(`/agents/export.csv?${params}`); }); ``` `grid.query()` returns the grid's current state: `{ page, pageSize, sort, search, filters, columns }`. Page parameters (a [filter panel](/recipes/filter-panel), `softDeletes()`, the source's `params`) are not part of it: `grid.lastRequestParams()` returns the ones actually sent for the rows on screen, without `_token`. ```php // routes/web.php Route::get('/agents/export.csv', [AgentExportController::class, 'csv']); ``` ```php public function csv(Request $request) { $query = Agent::query()->listSearch($request->search); // the list's own search/filter code foreach (array_filter(explode(',', (string) $request->sort)) as $s) { $column = ltrim($s, '-'); abort_unless(in_array($column, ['ref', 'name', 'unit', 'status', 'amount', 'date'], true), 422); $query->orderBy($column, str_starts_with($s, '-') ? 'desc' : 'asc'); } return response()->streamDownload(function () use ($query) { $out = fopen('php://output', 'w'); fputcsv($out, ['Ref', 'Name', 'Unit', 'Status', 'Amount', 'Date']); foreach ($query->cursor() as $a) { fputcsv($out, [$a->ref, $a->name, $a->unit, $a->status, $a->amount, $a->date]); } fclose($out); }, 'agents-'.now()->toDateString().'.csv'); } ``` A plain link navigation keeps the session cookie, needs no CSRF token (it's a `GET`) and lets the browser show its own download progress. ## Your own buttons Each module adds its API to the grid, so you can trigger exports from anywhere: | Call | Does | |---|---| | `grid.excel.download()` | builds and downloads the `.xlsx` | | `grid.excel.blob()` | builds it and returns a `Blob` (upload, attach to a mail…) | | `grid.csv.download()` / `grid.csv.text()` | the same for CSV | | `grid.print.open()` | opens the print view | ## Notes * **Print** renders a light, text-only copy of the table (no page CSS, no cell HTML) in a hidden frame and opens the browser's print dialog — "Save as PDF" turns it into a PDF. Listen to `beforePrint` to adjust the document or cancel. * **File names** default to `{grid name}-{date}`; `filename` accepts a string or a function. * **Footer rows** (``, the [footer module](/modules/footer)) are included with `footer: true`. * **Permissions:** `excel({ can: false })` removes the menu item; enforce the same rule on the export endpoint. ## Related * [export modules](/modules/export) — every option * [Columns](/guide/columns) — `exportValue`, `exportType`, `exportable` * [Page filter panel](/recipes/filter-panel) --- --- url: https://akinozgen.github.io/datagrids/recipes/custom-toolbar.md description: >- Drive a grid from your own search box, sort and page-size controls through its methods and events, or place your own elements into the toolbar slots with a tiny module. --- # Custom toolbar (headless) **Goal:** the page's design calls for its own controls — a search field in the page header, a sort dropdown, a "New" button next to the search box. Two ways, pick by where the controls live: | Your controls live… | Use | |---|---| | anywhere on the page, styled by your app | the grid's **methods and events** (headless) | | inside the grid's toolbar, next to its own controls | a small **toolbar module** that fills a slot | ## Your own controls, the grid's state ::: code-group ```js [JavaScript] import { Datagrid, column, colVis } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; const $ = (sel) => document.querySelector(sel); const grid = new Datagrid("#rcp-headless", { label: "Field agents (own controls)", data: agents(80), columns: [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], search: false, // no built-in search box sort: [["date", "desc"]], pageSize: 10, use: [colVis()], }); // your controls → grid methods let timer; $("#rcp-hl-q").addEventListener("input", (e) => { clearTimeout(timer); timer = setTimeout(() => grid.search(e.target.value), 250); }); $("#rcp-hl-sort").addEventListener("change", (e) => grid.sort([e.target.value.split(":")])); $("#rcp-hl-size").addEventListener("change", (e) => grid.pageSize(Number(e.target.value))); $("#rcp-hl-cols").addEventListener("click", () => grid.colVis.open()); // grid events → your controls (a header click also sorts) grid.on("sort", ({ sort }) => ($("#rcp-hl-sort").value = sort.map((s) => `${s.key}:${s.dir}`)[0] ?? "")); const log = (line) => ($("#rcp-hl-log").textContent = `${line}\n${$("#rcp-hl-log").textContent}`); grid.on("search", ({ search }) => log(`search "${search}"`)); grid.on("sort", ({ sort }) => log(`sort ${JSON.stringify(sort)}`)); grid.on("page", ({ page }) => log(`page ${page}`)); grid.on("pagesize", ({ pageSize }) => log(`pagesize ${pageSize}`)); grid.on("columnchange", ({ columns }) => log(`columnchange visible: ${columns.filter((c) => c.visible).map((c) => c.key)}`)); ``` ```html [HTML]
Events appear here.
``` ::: Type in **Search**, change **Sort** and **Rows**, then click a column header: the header click also updates the **Sort** dropdown, because the page listens to the grid's `sort` event. ### Steps 1. **Turn the built-in search box off** with `search: false`. Everything else (header sorting, pager, page-size menu) stays; hide what you replace with CSS on the [documented classes](/reference/css) if needed. 2. **Call the grid's methods from your controls.** Each one updates the state, resets to page 1 where that makes sense, and loads: | Your control | Call | |---|---| | search field | `grid.search("redfield")` — debounce typing yourself (the demo waits 250 ms) | | sort dropdown | `grid.sort([["amount", "desc"]])`; `grid.sort([])` clears it | | page size | `grid.pageSize(25)` (capped by `maxPageSize`) | | page buttons | `grid.page(3)` | | column chooser | `grid.colVis.open()` (with the [colVis](/modules/colvis) module) | Called without an argument, each method returns the current value: `grid.search()`, `grid.sort()`, `grid.page()`, `grid.pageSize()`. 3. **Listen to the grid's events to keep your controls in sync** — the header, the pager, saved state or a shared URL can change the same state: | Event | Detail | |---|---| | `search` | `{ search }` | | `sort` | `{ sort: [{ key, dir }] }` | | `page` | `{ page }` | | `pagesize` | `{ pageSize }` | | `columnchange` | `{ columns }` — visibility or order changed | | `load` | after every load: read `grid.status()` for `{ total, filtered }` | `beforeSort` and `beforePage` can be cancelled (`e.cancel()`). Several changes at once (for example a "Reset view" button) should go into `grid.batch()` so they cause one request instead of three: ```js grid.batch(() => { grid.search(""); grid.sort([["date", "desc"]]); grid.pageSize(10); }); grid.load(); ``` ## Your elements inside the toolbar ::: code-group ```js [JavaScript] import { Datagrid, column } from "@akinozgen17/datagrids"; import { agents, statusLabels, statusTones } from "./data.js"; /** A tiny module: puts one element into a toolbar slot. */ const toolbarItem = (name, slot, order, el) => ({ name, kind: "toolbar", setup(ctx) { ctx.toolbar({ slot, order, el }); return { api: { el } }; }, }); const status = document.createElement("select"); status.className = "dg-select"; // the grid's own control style status.setAttribute("aria-label", "Status"); status.append(new Option("Any status", ""), ...Object.entries(statusLabels).map(([v, l]) => new Option(l, v))); const add = document.createElement("button"); add.type = "button"; add.className = "dg-btn"; add.dataset.variant = "primary"; add.textContent = "New agent"; const summary = document.createElement("span"); const grid = new Datagrid("#rcp-toolbar-slots", { label: "Field agents (toolbar slots)", data: agents(60), columns: [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), ], pageSize: 5, use: [ toolbarItem("statusFilter", "start", 10, status), // after the search box toolbarItem("newAgent", "end", 10, add), toolbarItem("summary", "filters", 10, summary), // full-width row under the toolbar ], }); status.addEventListener("change", () => grid.filters({ status: status.value || null })); add.addEventListener("click", () => grid.addRows([{ id: Date.now(), name: "New agent", unit: "R.P.D.", status: "draft" }])); grid.on("load", () => { const { filtered, total } = grid.status(); summary.textContent = `${filtered} of ${total} agents${status.value ? ` · ${statusLabels[status.value]}` : ""}`; }); ``` ```html [HTML]
``` ::: The toolbar has three slots. A module puts an element into one with `ctx.toolbar()`: ```js const toolbarItem = (name, slot, order, el) => ({ name, // unique per grid; becomes grid[name] kind: "toolbar", setup(ctx) { ctx.toolbar({ slot, order, el }); return { api: { el } }; }, }); use: [toolbarItem("statusFilter", "start", 15, statusSelect)]; ``` | Slot | Where | Built-in items (order) | |---|---|---| | `start` | left, grows | search box (0), column menu (10), reload (20), reset state (30), export menu (40), custom buttons (50), button groups (60) | | `end` | right | auto-refresh toggle (−20), show deleted (−10), record count | | `filters` | full-width row under the toolbar | filter presets (−20), column filter chips (100) | Items are sorted by `order` inside their slot (ties keep registration order). Give your element the grid's own classes — `dg-btn` (with `data-variant="primary"` or `"ghost"`) and `dg-select` — and it matches the toolbar, including dark mode and density. The module's `name` must not clash with a grid method or another module. For a plain button, you don't need a module of your own: `button.custom({ label, onClick, slot, order })` does this, plus a disabled state derived from the last response — see [buttons](/modules/buttons). ## Notes * **colVis always renders its own toolbar button**; its panel opens next to it, also when you call `grid.colVis.open()` from elsewhere. Use `open()` for an extra entry point (a shortcut, a menu item), not to replace the button. * **Server grids** work the same: the methods change the query and the next request carries it. * **Accessibility:** your controls need their own labels (`
` with the cell value as text | ## column.phone(key, options?) | Extra option | Type | Default | Description | |---|---|---|---| | `country` | `string` | `"90"` | Country calling code added when the number lacks it (a leading `0` is dropped). | | `whatsapp` | `boolean` | `false` | Adds a second "WA" link to `https://wa.me/`. | Renders the value as a `tel:` link (`type: "text"`). ## column.boolean(key, options?) Yes / no with a permanent icon and text (colour is never the only signal). | Extra option | Type | Default | Description | |---|---|---|---| | `labels` | `{ true?: string, false?: string }` | `Evet` / `Hayır` or `Yes` / `No` | Texts; the default follows the page language (``). | | `showFalse` | `boolean` | `true` | `false` leaves false cells empty. | Values are read as booleans: `1` / `0`, `true` / `false`, `"on"` / `"off"`, `"evet"` / `"hayır"`, `"yes"` / `"no"`; anything else is empty. | Sets | Value | |---|---| | `type` / `align` | `"boolean"` / `"center"` | | `compare` | false before true; empty values first | | `searchText` / `exportValue` | the label | | render | `` with an icon and `.dg-bool-text` | ## column.parseDate(), column.parseBool() The readers behind `column.date()` and `column.boolean()`, exported for your own `render`, `value` or `compare` functions: ```js column.parseDate("05.01.2026 14:30", "dmy"); // Date (local time) or null column.parseBool("evet"); // true, false or null ``` ## column.index(options?) Row number that continues across pages (page offset + position). | Sets | Value | |---|---| | `key` / `col` | `"__index"` / `"rownum"` | | `title` | `"#"` | | `sortable` / `searchable` | `false` | ## column.actions(options?) Placeholder for the [actions](/modules/actions) module, which fills it with the row menu. | Sets | Value | |---|---| | `key` / `col` | `"__actions"` / `"actions"` | | `align` / `sticky` | `"end"` / `"end"` | | `sortable`, `searchable`, `exportable`, `hideable` | `false` | ## column.select(options?) Placeholder for the [selection](/modules/selection) module, which fills it with checkboxes. | Sets | Value | |---|---| | `key` / `col` | `"__select"` / `"select"` | | `title` | `""` | | `sortable`, `searchable`, `exportable`, `hideable` | `false` | ## Header attributes (DOM source) When a server-rendered table is enhanced without `columns`, these attributes on the `` cells define the columns. See [Data sources](/guide/data-sources#dom-progressive-enhancement). | Attribute | Effect | |---|---| | `data-dg-key` | Column key (default: a slug of the header text). | | `data-dg-type` | Column type; `number` and `money` also right-align and sort numerically. Cells keep their server markup. | | `data-dg-align` | `start`, `end` or `center`. | | `data-dg-sortable="false"` | Not sortable. | | `data-dg-searchable="false"` | Not searchable. | | `data-dg-visible="false"` | Hidden initially. | | `data-dg-hideable="false"` | Not offered in the column menu. | | `data-dg-export="false"` | Left out of exports. | A `data-order` attribute on a `` is used as that cell's value for sorting and search instead of its text. ## Gotchas * **A string from `render` shows tags literally**: strings are text unless the column has `html: true`. Return a `Node`, or opt in with `html: true`. * **`"1.250"` became 1.25 (or 1250)**: with the default `source: "number"` a machine-style string is read as a JS number (`"1.250"` = 1.25, as a DECIMAL column sends it). For formatted Turkish text (`"1.250"` meaning one thousand two hundred fifty) pass `source: "tr"`. Send numbers as JSON numbers when you can. * **A date-only ISO string shows the previous day** in time zones west of UTC: `new Date("2026-01-05")` is UTC midnight. Use `source: "local"` for `YYYY-MM-DD` values. * **The money symbol follows the amount** in every locale (`1,234.50 $`). * **`column.index()` is never exported**; add a regular column if the export needs a number. ## Related * [Columns guide](/guide/columns) · [Grid options](/reference/options) · [Export](/modules/export) --- --- url: https://akinozgen.github.io/datagrids/reference/methods.md description: >- Every member of a grid instance (DatagridApi) with signature, return value and behaviour, plus the API each module adds to the grid. --- # Instance methods A grid instance (`new Datagrid(…)`, `Datagrid.get(el)`, `find(name)`) implements `DatagridApi`. Methods that change state (`search`, `page`, `sort`, `filters`…) load data themselves; you never call `refresh()` or `draw()`. ```js const grid = Datagrid.get("#agents"); grid.batch(() => { grid.sort([["date", "desc"]]); grid.filters({ unit: "R.P.D." }); }); await grid.reload(); ``` ## Data loading | Member | Returns | Description | |---|---|---| | `load()` | `Promise` | Loads with the current query. Fires `beforeLoad` (cancelable). The last request wins: a running request is aborted and stale responses are dropped (matched by sequence, never by the server's `draw`). In client mode, once data is loaded, it recomputes the view locally without a request. | | `reload({ keepPage?, silent? })` | `Promise` | Loads again. Goes back to page 1 unless `keepPage: true`. `silent: true` skips the busy overlay. Array and DOM sources re-run search, sort and paging over the current rows, keeping `setData()` / `addRows()` / `removeRow()` changes; `fetchAll` refetches. With `errorMode: "throw"` the promise rejects on failure. | | `setData(rows)` | `void` | Client mode: replaces the rows and re-renders. | | `addRows(rows, { keepPage? })` | `void` | Client mode: appends rows and jumps to the last page unless `keepPage: true`. Ignored in server mode (a development notice is printed); change the data on the server and `reload()`. | | `removeRow(key)` | `void` | Removes the row with this key: from the data (client) or from the current page until the next load (server). | | `refreshRow(key, row?)` | `void` | Re-renders one row in place, optionally replacing its data object first. Row mutators run again. | | `exportRows(scope?)` | `Promise` | Rows for an export. `"page"` (default): the current view. `"all"`: every filtered row; client mode computes them locally, server mode sends one request with `pageSize = maxPageSize` (request middleware included). | | `lastResponse()` | `unknown` | Raw JSON body of the last load (server sources and `fetchAll`); `null` for array and DOM sources. | | `lastRequestParams()` | `object` | Page parameters of the request behind the rows on screen, as they reached the wire: filter panel, toggles, `params`, after every middleware. With `ssp` / `yajra` also non-column `filters()` and whatever a `data` function added; the protocol's own fields (`draw`, `columns`, `order`, `start`, `length`, `search`) and `_token` are left out. `{}` for local sources. Use it to rebuild "all matching" on the server. | ## State: getters and setters Each setter returns the current value, so calling it without an argument reads it. | Member | Returns | Description | |---|---|---| | `search(text?)` | `string` | Sets the search text, goes to page 1, loads and announces the result count. Fires `search`. Also updates the toolbar box. | | `page(n?)` | `number` | Goes to page `n` (1-based), clamped to the page count (open-ended when the total is unknown). Fires `beforePage` (cancelable) and `page`; scrolls the table to the top. Before the first load it only stores the value. | | `pageSize(n?)` | `number` | Sets rows per page and goes to page 1. Values above `maxPageSize` or below 0 are clamped ([DG013](/errors/DG013)); `-1` is "All" where the protocol allows it. `0` means paging is off. Fires `pagesize`. | | `sort(spec?)` | `SortSpec[]` | Sets the sort: `[["date", "desc"]]` or `[{ key: "date", dir: "desc" }]`; `[]` clears it. Goes to page 1, announces the new order. Fires `beforeSort` (cancelable) and `sort`. | | `filters(patch?)` | `Readonly>` | Merges `patch` into the filters (`null`, `""` or `[]` removes a key), goes to page 1 and loads. See [Filters](#filters). | | `query()` | `Query` | The current request payload, see [Query](#query). | | `status()` | `GridStatus` | Loading status, totals and the last error, see [GridStatus](#gridstatus). | | `batch(fn)` | `void` | Runs `fn` with loads and sort announcements suppressed, so several setters don't each fire a request. Nothing loads afterwards on its own: call `reload()` once `fn` returns. | | `stateContributions()` | `ReadonlyArray` | Parts registered with `ctx.state()` by modules (what `stateSave` persists). | ### Filters `filters()` is the one filter store for every filter UI (filter panels, column filters, your own code). | Value | Client mode | |---|---| | string / number / boolean | equals (compared as strings) | | array | any of the values | | `{ op, value }` | typed operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `between`, `in`, `notIn`, `contains`, `notContains`, `starts`, `ends`, `empty`, `notEmpty` | | `(value, row) => boolean` | predicate | In client mode a key that is a column key compares the cell value; any other key reads that path of the row. On a server source the protocol encodes the filters (functions are never sent): | Protocol | How filters travel | |---|---| | `ssp()` / `yajra()` | Keys that are not column keys: extra form parameters (`unit=R.P.D.`). `{ op, value }` on a searchable column: `columns[i][columnControl]` (no `between` / `notIn`). A plain value on a column key is an equality: an anchored, escaped regex in `columns[i][search][value]` (`^R\.P\.D\.$`, `regex=true`; an array becomes `^a$\|^b$`). Filters on columns with `searchable: false` are not sent (development notice). | | `dgp()` | `filters: { key: { op, value } }`; a plain value becomes `eq`, an array `in`. | | `laravelPaginator()` | Query parameters `key=value`; typed filters send their `value`, so only `eq` and `in` mean what they say (the column filter menu offers only those). | ### Query | Field | Type | Description | |---|---|---| | `page` | `number` | 1-based page. | | `pageSize` | `number` | Rows per page; `0` = paging off, `-1` = all. | | `sort` | `SortSpec[]` | `{ key, dir }` entries. | | `search` | `string` | Toolbar search text. | | `filters` | `Record` | Copy of the filter store. | | `columns` | `ResolvedColumn[]` | Columns in **definition** order (the wire order), with resolved `title`, `sortable`, `searchable`, `visible`, `hideable`, `exportable`, `defaultVisible`, `index`. | | `sortDefault` | `boolean` | `false` only when the grid was created with an explicit `sort: []`. While it is `true`, an empty sort on the SSP wire sends the first column ascending — also after the sort was cleared at runtime. | | `pristine` | `boolean` | The query is still the one the grid was configured with (nothing restored or changed yet). | ### GridStatus | Field | Type | Description | |---|---|---| | `status` | `"idle" \| "loading" \| "reloading" \| "ready" \| "error"` | `idle`: `load: "manual"` before the first load. `loading`: first load. `reloading`: later loads (the rows stay on screen). | | `loaded` | `boolean` | At least one load succeeded. | | `total` | `number \| null` | Records before filtering; `null` when the server doesn't count. | | `filtered` | `number \| null` | Records after search and filters. | | `hasMore` | `boolean \| null` | Next page exists (servers that don't count, e.g. `simplePaginate`). | | `error` | `DatagridError \| null` | Last error: `{ kind, status, message, detail?, retryable, raw? }`. Cleared by the next successful load. | ## Rows | Member | Returns | Description | |---|---|---| | `rows()` | `Row[]` | Client mode: every row. Server mode: the current page. | | `viewRows()` | `Row[]` | The rows currently rendered (after client search, filters, sort and paging; or the server page). | | `keyOf(row)` | `string` | The row's key (`rowKey`, else `id`, else `DT_RowId`, else a position key with [DG003](/errors/DG003)). | | `rowByKey(key)` | `Row \| undefined` | Row object for a key, among the loaded rows. | ## Columns | Member | Returns | Description | |---|---|---| | `columns()` | `ReadonlyArray` | Columns in **display** order (after reordering). `query().columns` keeps the definition order. | | `setColumns(defs)` | `void` | Replaces the column definitions, drops sort entries for missing keys, re-renders the header, fires `columnchange` and reloads keeping the page. | | `setColumnVisible(key, visible)` | `void` | Shows or hides a column without a request. Hiding a column with `hideable: false` is refused. Fires `columnchange`. | | `columnOrder(keys?)` | `string[]` | Sets the display order (keys not listed keep their relative order at the end; special and sticky columns keep their slots) and returns the full order. The request keeps the definition order. Fires `columnchange`. | ## Events | Member | Returns | Description | |---|---|---| | `on(type, fn)` | `() => void` | Subscribes to a grid event; returns the unsubscribe function. See [Events](/reference/events). | | `emit(type, detail)` | `boolean` | Fires an event (listeners + a `dg:` DOM event on the root). Returns `false` when a listener cancelled it; events whose name starts with `before` get a `cancel()` method. For modules that publish their own events. | | `delegate(type, selector, fn)` | `() => void` | DOM event delegation on the root with row context: `fn(event, { row, key, tr, td, column })`. Only fires for rows of this grid. Returns the remover. | ## Actions and host adapters | Member | Returns | Description | |---|---|---| | `action(url, options?)` | `Promise` | Row action helper: optional confirm → same-origin request with `X-CSRF-TOKEN` (from `meta[name=csrf-token]`), `Accept: application/json` and `X-Requested-With` → success notification (the response's `message`, else `messages.actionDone`) → `reload({ keepPage: true })`. Resolves with the parsed response, `undefined` when the confirm was declined. Errors are notified and rethrown; 401/419 or a redirect to a login page also fire `sessionexpired` and call the `onSessionExpired` adapter. A redirect to any other page (a classic `return back()`) counts as success. A 2xx whose body reports a failure counts only through an `isError` rule (below). | | `notify(kind, message)` | `void` | Uses the `notify` host adapter; without one it announces the message in the live region and shows errors as a banner above the table. `kind`: `"success" \| "error" \| "info"`. | | `confirm(message, options?)` | `Promise` | Uses the `confirm` host adapter, else the built-in ``. Options: `title`, `tone` (`"danger" \| "default"`), `confirmLabel`, `cancelLabel`, `subject`. | `action()` options: | Option | Type | Default | Description | |---|---|---|---| | `method` | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE"` | `"POST"` | Anything else throws. | | `body` | `Record \| FormData \| null` | — | Objects are sent as JSON (not for GET); `FormData` as is. | | `confirm` | `string \| { message, title?, tone?, confirmLabel?, cancelLabel?, subject? }` | — | Ask first. | | `success` | `string \| false` | response `message` | Success text; `false` = no notification. | | `reload` | `false \| { keepPage?, silent? }` | `{ keepPage: true }` | Reload after success. | | `headers` | `Record` | — | Extra request headers. | | `isError` | `(body, res) => boolean \| string \| null` | `configure({ isError })` | Decides whether a 2xx response failed after all (`{ status: false, error }`). Truthy = failure: the error is notified and thrown (`kind: "server"`, the body in `raw`) and nothing reloads; a string is the message, `true` uses `messages.actionFailed`. Without a rule every 2xx is a success. | The URL must be same-origin http(s). ## Modules and lifecycle | Member | Returns | Description | |---|---|---| | `use(module \| modules[])` | `this` | Attaches modules after construction and re-renders. A data source here replaces the default one; a second explicit source throws [DG008](/errors/DG008). `remount()` keeps chained modules. | | `module(factoryOrDef)` | API or `null` | Typed access to a module's API: `grid.module(stateSave)`. `null` when the module is not attached. | | `destroy()` | `void` | Aborts requests, destroys modules (in reverse order), fires `destroy` and restores the table exactly as it was (``, `` rows, attributes, position). Idempotent. | | `remount(table?)` | `DatagridApi` | `destroy()` + a new grid with the same constructor options, on the same or another table (for DOM morphing frameworks). Modules attached later with `use()` come along. | ## Properties | Property | Type | Description | |---|---|---| | `root` | `HTMLElement` | The `.dg` wrapper around the table. | | `table` | `HTMLTableElement` | Your table (same element, enhanced in place). | | `name` | `string \| undefined` | The `name` option. | | `messages` | `Messages` | The merged UI strings. | | `locale` | `string` | Resolved locale. | | `mode` | `"client" \| "server"` | From the data source. | | `maxPageSize` | `number` | Resolved limit. | ## Module APIs Each module installs its API on the grid under its module name. In TypeScript, `grid.module(factory)` returns the typed API. | Module | Property | API | |---|---|---| | [`stateSave()`](/modules/state-save) | `grid.state` | `key` (storage key), `save()`, `read()` → stored payload or `null`, `clear()`, `reset()` → `Promise` (initial view + reload) | | [`colVis()`](/modules/colvis) | `grid.colVis` | `open()`, `close()`, `toggle()`, `reset()`, `count()` → `{ visible, total }` | | [`colReorder()`](/modules/col-reorder) | `grid.colReorder` | `order()` → keys, `move(key, to)`, `reset()`, `movable()` → columns, `messages` | | [`columnFilters()`](/modules/column-filters) | `grid.columnFilters` | `open(key)`, `current` (key of the open filter or `null`) | | [`filterPanel()`](/modules/filter-panel) | `grid.filterPanel` | `values()`, `raw()`, `set(patch, { reload? })`, `reset()`, `apply()` | | [`urlSync()`](/modules/url-sync) | `grid.urlSync` | `link()` → shareable URL of the current view | | [`softDeletes()`](/modules/soft-deletes) | `grid.softDeletes` | `active()`, `toggle(on?)` | | [`actions()`](/modules/actions) | `grid.actions` | `run(id, key)`, `open(key)` (row menu), `items(key)` → resolved items with disabled reasons | | [`selection()`](/modules/selection) | `grid.selection` | `get()`, `keys()`, `payload()`, `count()`, `isAll()`, `isSelected(key)`, `select(keys)`, `deselect(keys)`, `toggle(key)`, `clear()`, `selectPage()`, `deselectPage()`, `selectAllMatching()` | | [`excel()`](/modules/export) | `grid.excel` | `download()`, `blob()` | | [`csv()`](/modules/export) | `grid.csv` | `download()`, `text()` | | [`print()`](/modules/export) | `grid.print` | `open()` | | [`responsive()`](/modules/responsive) | `grid.responsive` | `collapsed()` → keys of collapsed columns, `refit()`, `toggle(rowKey, open?)` (detail row) | | [`lazyColumns()`](/modules/lazy-columns) | `grid.lazyColumns` | `requested()` → lazy keys sent with the last request, `visible()` → lazy keys visible now, `param` (the request parameter name) | | `stickyHeader()` | `grid.stickyHeader` | `stuck()`, `refresh()` | | [`keyboardGrid()`](/modules/keyboard-grid) | `grid.keyboardGrid` | `position()`, `focus(row, col)` | | [`rowReorder()`](/modules/row-reorder) | `grid.rowReorder` | `enabled()`, `move(key, to)` → `Promise` | | [`multiSort()`](/modules/multi-sort) | `grid.multiSort` | `toggle(key)` | | [`autoRefresh()`](/modules/auto-refresh) | `grid.autoRefresh` | `running()`, `start()`, `stop()`, `tick()` | | [`filterPresets()`](/modules/filter-presets) | `grid.filterPresets` | `active()` → id of the matching preset or `null`, `apply(id, { reload? })` | | [`metaBind()`](/modules/meta-bind) | `grid.metaBind` | `refresh()` | | [`footer()`](/modules/footer) | `grid.footer` | `values()`, `refresh()` | | [`button.reload()`](/modules/buttons) | `grid.reloadButton` | `el` (the button) | | [`button.resetState()`](/modules/buttons) | `grid.resetStateButton` | `el` | | [`button.custom()` / `button.group()`](/modules/buttons) | `grid[name]` | `el`; `name` defaults to `button` / `buttonGroup` | A module attached with `can: false` still answers on its property: every call is a no-op. ## Gotchas * **`reload()` keeps local edits**: on array and DOM sources it re-runs search, sort and paging over the current rows (including `setData()` / `addRows()` / `removeRow()` changes). Only `fetchAll` fetches again. * **`batch()` loads nothing**: follow it with `reload()`. * **`grid.module(button.custom)` returns `null`**: custom buttons and groups are registered under their `name`; read them as `grid[name]`. * **`addRows()` and `setData()` are for client mode**; `addRows()` is ignored on a server source. Change the data on the server and `reload({ keepPage: true })`. ## Related * [Grid options](/reference/options) · [Events](/reference/events) · [Static API](/reference/static) * [Writing a module](/reference/modules) · [Lifecycle](/guide/lifecycle) --- --- url: https://akinozgen.github.io/datagrids/reference/events.md description: >- Every grid event with its payload, whether it can be cancelled and exactly when it fires, plus the dg:* DOM events and delegate(). --- # Events ```js const off = grid.on("load", ({ result }) => console.log(result.total)); grid.on("beforeSort", (e) => { if (busy) e.cancel(); }); off(); // unsubscribe ``` * `grid.on(name, fn)` returns an unsubscribe function. Listeners are removed on `destroy()`. * Events whose name starts with `before` are **cancelable**: call `e.cancel()` in a listener. * A listener that throws is logged with `console.error`; the grid and the other listeners carry on. * Use events to react. To change what is requested or rendered, use a [pipeline](/guide/concepts#pipelines) (request middleware, row mutator) instead. ## Core events | Event | Payload | Cancelable | Fires when | |---|---|---|---| | `init` | `{ grid }` | — | Once, in a microtask after the constructor returns (an eager grid has already started its first load). | | `beforeLoad` | `{ query, cancel() }` | yes | Before every `load()`: the first load, `reload()`, `search()`, `sort()`, `page()`, `pageSize()` and server-side filter changes. Cancelling leaves everything as it is. | | `loadingchange` | `{ loading }` | — | On every status change: `true` when a load starts, `false` when the grid becomes ready, empty, idle or errored. The value can repeat (client-side recomputes report `false` only). | | `render` | `{ keys, rows }` | — | After the body was rendered with new data: every successful load and every client-side recompute. `keys` and `rows` are the rendered view (empty arrays for an empty result). Not fired for the loading and error states. | | `response` | `{ raw, result }` | — | After the data source answered, right before `load`. `raw` is the parsed response body (extra server keys such as `summary` live here); `undefined` for array and DOM sources. Not fired for client-side recomputes. | | `load` | `{ result, query }` | — | After data arrived and was rendered. In client mode also after every local recompute: search, sort, page, filters, `setData()`, `addRows()`, `removeRow()`. `result` is `{ rows, total, filtered, hasMore?, meta?, raw?, error? }`. | | `error` | `{ error }` | — | A load failed (in every `errorMode`), or the server returned rows together with an error message. `error` is `{ kind, status, message, detail?, retryable, raw? }`. Aborted requests are not errors. | | `sessionexpired` | `{ error }` | — | A load, a server-side export or `grid.action()` got 401 or 419, or was redirected to a login page. The `onSessionExpired` host adapter is called too. | | `beforeSort` | `{ sort, cancel() }` | yes | Before a sort change (header click or `sort()`). | | `sort` | `{ sort }` | — | After the sort changed, before the data loads. | | `beforePage` | `{ page, cancel() }` | yes | Before a page change (pager or `page(n)`). Not fired when search, sort or filters reset to page 1. | | `page` | `{ page }` | — | After the page changed, before the data loads. | | `pagesize` | `{ pageSize }` | — | After the page size changed (menu or `pageSize(n)`). | | `search` | `{ search }` | — | After the search text changed (debounced typing, Enter, Escape, clear button or `search()`). | | `columnchange` | `{ columns }` | — | After `setColumns()`, `setColumnVisible()` or a display-order change (`columnOrder()`, column menu, drag). `columns` is in display order. | | `headrender` | `{ tr }` | — | After the header row was built: at construction, on `setColumns()`, `columnOrder()` and `use()`. Modules decorate header cells here. | | `destroy` | `{}` | — | During `destroy()`, after the modules were torn down and before the table is restored. | ## Module events | Event | Module | Payload | Cancelable | Fires when | |---|---|---|---|---| | `selectionchange` | [selection](/modules/selection) | `{ count, keys, all }` | — | After the selection changed (checkbox, page checkbox, "select all matching", API calls, clearing on a query change). `all` is `true` while every matching row is selected. | | `beforeAction` | [actions](/modules/actions) | `{ id, key, row, cancel() }` | yes | A row action was chosen, before its confirm dialog. | | `action` | [actions](/modules/actions) | `{ id, key, row }` | — | The action's request or handler finished without an error (not for `href` actions, which navigate). | | `actionerror` | [actions](/modules/actions) | `{ id, key, row, error }` | — | The action's request or handler threw. Request errors were already shown through `notify`. | | `beforeReorder` | [rowReorder](/modules/row-reorder) | `{ row, key, from, to, offset, prevKey, nextKey, rows, cancel() }` | yes | A row was dropped (drag or keyboard), before `onEnd` runs. Cancelling puts the row back. | | `reorder` | [rowReorder](/modules/row-reorder) | `{ row, key, from, to, offset, prevKey, nextKey, rows }` | — | `onEnd` resolved; the new order stays. `from` / `to` are page-local; `offset + index` is the absolute position. | | `reordererror` | [rowReorder](/modules/row-reorder) | the same + `error` | — | `onEnd` rejected; the row went back to its place. | | `collapse` | [responsive](/modules/responsive) | `{ columns }` | — | The set of collapsed columns changed (after a resize or a column change). `columns` are their keys. | | `window` | core | `{}` | — | Virtual mode only: a new window of rows was drawn while scrolling (rows are re-inserted, so focus inside them is lost). | | `beforePrint` | [print](/modules/export) | `{ document, window, cancel() }` | yes | The print document is ready in a hidden frame, before the browser's print dialog. Decorate `document`, or cancel to skip the dialog. | ## Order of a load An eager client grid: ```text beforeLoad → loadingchange(true) → init → loadingchange(false) → render → response → load ``` A later server load (`reload()`, a sort, a page change): ```text beforeSort → sort → beforeLoad → loadingchange(true) → … request … → loadingchange(false) → render → response → load ``` On failure the tail is `error` → (`sessionexpired` for 401/419) → `loadingchange(false)` instead of `loadingchange(false) → render → response → load`. ## DOM events Every event is also dispatched on `grid.root` as a `CustomEvent` named `dg:` whose `detail` is the payload, after the `on()` listeners ran: ```js grid.root.addEventListener("dg:selectionchange", (e) => { bulkBar.hidden = e.detail.count === 0; }); ``` The DOM events do **not bubble**. To listen higher up the tree (for grids created later), use the capture phase: ```js document.addEventListener("dg:load", (e) => console.log(e.target, e.detail.result), true); ``` To cancel a `before…` event from a DOM listener, call `e.detail.cancel()`; `preventDefault()` has no effect. ## delegate() ```ts grid.delegate(type: string, selector: string, fn: (event, ctx: RowContext) => void): () => void ``` Listens for DOM events on the grid root and calls `fn` only when the target matches `selector` inside one of this grid's rows. Rows are re-rendered freely, so attach row behaviour here instead of binding listeners to cells. | `ctx` field | Type | Description | |---|---|---| | `row` | `Row` | The row's data object. | | `key` | `string` | The row key. | | `tr` | `HTMLTableRowElement` | The row element. | | `td` | `HTMLTableCellElement \| null` | The cell the event happened in. | | `column` | `ResolvedColumn \| null` | That cell's column. | ```js grid.delegate("click", ".open-agent", (e, { row }) => openAgent(row.id)); ``` Returns the remover. Events from the toolbar, header and footer don't reach `fn`. ## Related * [Instance methods](/reference/methods) · [Writing a module](/reference/modules) * [Concepts: events or pipelines?](/guide/concepts#events-or-pipelines) --- --- url: https://akinozgen.github.io/datagrids/reference/static.md description: >- Package-level exports — Datagrid.get, get, find, reload, configure() with every global key and default, upgrade() and its data attributes, preset(), VERSION, message packs and config. --- # Static API & configure() Everything is a named export of the package. The IIFE build exposes the same names on `window.Datagrids`: ::: code-group ```js [ESM] import { Datagrid, column, configure, find, reload, upgrade } from "@akinozgen17/datagrids"; ``` ```html [IIFE] ``` ::: ## Exports | Export | Kind | See | |---|---|---| | `Datagrid` | class (`new Datagrid(table, options)`, `Datagrid.get()`) | [Grid options](/reference/options), [Instance methods](/reference/methods) | | `column` | namespace: `text`, `html`, `number`, `money`, `date`, `badge`, `link`, `phone`, `boolean`, `index`, `actions`, `select`; helpers `parseDate`, `parseBool` | [Column options](/reference/columns) | | `arraySource`, `domSource`, `fetchAll`, `customSource`, `sourceModule` | data source modules | [Data sources](/guide/data-sources) | | `serverSide`, `ssp`, `yajra`, `dgp`, `laravelPaginator` | server source and protocols | [Server protocols](/guide/server-protocols) | | `stateSave`, `colVis`, `colReorder`, `columnFilters`, `filterPanel`, `filterPresets`, `urlSync`, `softDeletes`, `actions`, `selection`, `excel`, `csv`, `print`, `footer`, `metaBind`, `responsive`, `lazyColumns`, `stickyHeader`, `keyboardGrid`, `rowReorder`, `multiSort`, `autoRefresh` | feature modules | [Modules](/modules/) | | `reorderColumn`, `REORDER_KEY` | the drag-handle column for `rowReorder()` and its key (`"__reorder"`) | [rowReorder](/modules/row-reorder) | | `button` | namespace: `reload`, `resetState`, `custom`, `group` | [Buttons](/modules/buttons) | | `configure`, `config` | global defaults | [below](#configure) | | `get`, `find`, `reload` | grid lookup | [below](#get) | | `upgrade`, `preset` | declarative init | [below](#upgrade) | | `en`, `tr` | message packs | [Messages](/reference/messages) | | `VERSION` | `string` | the package version | | `SelectionModel` | class | the selection state model used by `selection()` | All TypeScript types (`DatagridOptions`, `ColumnDef`, `ModuleDef`, `Query`, `Messages`, …) are exported too. ## get() ```ts Datagrid.get(target: Element | string | null): Datagrid | null get(target: Element | string | null): Datagrid | null ``` Returns the grid of a table, or `null`. `target` is the table, any element inside it, or a selector. It **never creates** a grid, so `get()` is safe to call anywhere. ## find() ```ts find(name: string): Datagrid | null ``` Returns the live grid created with `name`, or `null`. Names are registered at construction and removed on `destroy()`. ## reload() ```ts reload(name: string, options?: { keepPage?: boolean; silent?: boolean }): boolean ``` Reloads the grid called `name` (for example after a dialog in another tab saved a record). Returns `false` and warns [DG006](/errors/DG006) when there is no such grid. ## configure() ```ts configure(patch: GlobalConfig): GlobalConfig ``` Sets host-wide defaults and returns the resulting config. Keys you leave out (or pass as `undefined`) keep their value. A grid's own options always win over these. | Key | Default | Description | |---|---|---| | `confirm` | built-in `` | `(message, options) => Promise`. Confirmation adapter for `grid.confirm()`, row actions and `grid.action({ confirm })`. `options`: `title`, `tone`, `confirmLabel`, `cancelLabel`, `subject`. | | `notify` | live region + error banner | `(kind, message) => void`. Toast adapter for `grid.notify()`, action results and export failures; `kind` is `success`, `error` or `info`. | | `csrf` | `false` | Server sources and `fetchAll` send `X-CSRF-TOKEN` from ``; non-GET server requests also carry a `_token` parameter. `grid.action()` always sends the token when the meta tag exists. | | `laravel` | `true` | Sends `X-Requested-With: XMLHttpRequest` with server requests, `fetchAll` and `grid.action()`, so Laravel answers with JSON. | | `timeout` | `30000` | Server request timeout in ms; `serverSide({ timeout })` overrides it. | | `onSessionExpired` | — | `(error) => void`. Called when a load gets 401, 419 or a redirect to a login page; the `sessionexpired` event fires as well. | | `fetch` | `globalThis.fetch` | Replaces `fetch` for server sources, `fetchAll` and `grid.action()` (tests, auth wrappers). | | `isError` | — | `(body, res) => boolean \| string \| null`. For `grid.action()` (and row actions with `request`): a 2xx response whose parsed body still reports a failure. Truthy = failed, a string is the message. Example: `(b) => b?.status === false && (b.error ?? true)`. | | `messages` | — | `Partial`: UI string overrides for every grid, merged over the language pack. | | `locale` | ``, else the browser's language, else `"en"` | Default locale of every grid. | | `pageSize` | `25` | Default rows per page. | | `pageSizes` | `[10, 25, 50, 100]` | Default page-size menu. | | `maxPageSize` | `1000` | Default page size limit and server "export all" row limit. | | `warnings` | `true` | Development messages: coded console warnings, module warnings and the server error "Details" disclosure. Turn off in production. | | `errorMode` | `"inline"` | `"inline"`, `"silent"` or `"throw"`; see [Grid options](/reference/options#loading). | **When a grid reads them:** the host adapters (`confirm`, `notify`, `csrf`, `laravel`, `timeout`, `onSessionExpired`, `fetch`, `isError`), `messages`, `locale`, `pageSize` and `pageSizes` are read when a grid is created, so call `configure()` before creating grids. `errorMode`, `maxPageSize` and `warnings` are read when they are needed and also affect existing grids. ```js import { configure } from "@akinozgen17/datagrids"; configure({ csrf: true, notify: (kind, message) => toast[kind](message), confirm: (message, o) => dialogs.ask({ message, title: o.title, danger: o.tone === "danger" }), onSessionExpired: () => location.assign("/login"), warnings: import.meta.env.DEV, }); ``` ## config The live global config object that `configure()` writes to. Read it for the current defaults; don't assign to it directly (warnings are only switched through `configure()`). ## upgrade() ```ts upgrade(root?: ParentNode): Datagrid[] ``` Creates a grid for every `table[data-datagrid]` under `root` (default `document`) that doesn't have one yet and returns the new grids. Calling it again (after injecting HTML) is safe: existing grids are skipped. | Table attribute | Becomes | |---|---| | `data-datagrid` | Marker. Its value is a [preset](#preset) name whose modules are attached; empty for none. | | `data-dg-name` | `name` | | `data-dg-label` | `label` | | `data-dg-load` | `load` (`eager`, `visible`, `manual`) | | `data-dg-page-size` | `pageSize` | | `data-dg-sort` | `sort`, as `key:dir` (`date:desc`; any other dir is ascending) | | `data-dg-theme` | `theme` | | `data-dg-size` | `size` | | `data-dg-density` | `density` | Only these attributes are read; there is no JSON configuration attribute. Columns come from the `` [header attributes](/reference/columns#header-attributes-dom-source), rows from the existing ``, and everything else from the preset. ```html
NameDate
``` ## preset() ```ts preset(name: string, factory: (table: HTMLTableElement) => ModuleInput[]): void ``` Registers modules for `upgrade()`. The factory runs once per table and receives it, so it can read the table's own attributes: ```js import { preset, upgrade, serverSide, yajra, stateSave, colVis, excel } from "@akinozgen17/datagrids"; preset("list", (table) => [ serverSide({ url: table.dataset.url, protocol: yajra(), csrf: true }), stateSave(), colVis(), excel(), ]); upgrade(); ``` A preset is just an array of modules: the same array works in `use: [...]`. An unknown preset name attaches nothing and does not warn. ## VERSION `VERSION: string`, the library version, e.g. for bug reports. ## en, tr The English and Turkish [message packs](/reference/messages) (`Messages` objects). Spread one to start a new language: ```js import { en } from "@akinozgen17/datagrids"; const de = { ...en, search: "Suchen…", searchLabel: "Suchen", retry: "Erneut versuchen" }; new Datagrid("#agents", { label: "Agenten", locale: "de", messages: de, columns }); ``` ## Related * [Concepts: global defaults](/guide/concepts#global-defaults) · [Lifecycle](/guide/lifecycle) * [Grid options](/reference/options) · [Messages](/reference/messages) --- --- url: https://akinozgen.github.io/datagrids/reference/modules.md description: >- The ModuleDef shape, every ModuleContext member, the request middleware model and the wiring errors, with a complete toolbar module and request middleware example. --- # Writing a module A module is an immutable definition object with a `setup(ctx)` function. The grid calls `setup` once per grid with a context that lets the module contribute to the grid's [pipelines](/guide/concepts#pipelines): toolbar slots, row mutators, request middleware, saved state. The built-in modules use exactly this API. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; // Toolbar module: a badge with the row count of the last load. function rowBadge({ slot = "end", order = 5 } = {}) { return Object.freeze({ name: "rowBadge", kind: "toolbar", setup(ctx) { const el = document.createElement("span"); el.className = "dg-chip"; el.dataset.tone = "info"; ctx.toolbar({ slot, order, el }); const off = ctx.on("load", ({ result }) => { el.textContent = `${result.rows.length} of ${result.filtered ?? "?"} rows`; }); return { api: { el }, destroy: () => (off(), el.remove()) }; }, }); } rowBadge.moduleName = "rowBadge"; // Request middleware module: tags every request this grid sends. const clientTag = (client) => Object.freeze({ name: "clientTag", kind: "feature", setup(ctx) { ctx.request((req, next) => { req.headers["X-Client"] = client; req.params.client = client; return next(req); }); }, }); new Datagrid("#ref-module", { label: "Agents with a custom module", columns: [ { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), ], pageSize: 5, use: [serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), rowBadge(), clientTag("docs")], }); ``` ```html [HTML]
``` ::: Open the **Request** tab: every request carries `client: "docs"`, added by the `clientTag` middleware (the `X-Client` header travels too). ## Rules * **A factory returns a frozen definition.** Options live in the factory's closure; `setup` runs per grid, so one definition can be shared by several grids. * **Everything a module adds, it removes** in `destroy()`. Use `ctx.signal` for DOM listeners and the functions returned by `ctx.on()`. * **The API is installed on the grid under `name`** (`grid.rowBadge.el`). Pick a name that is not a grid member ([DG010](/errors/DG010)) and set `factory.moduleName = name` so `grid.module(factory)` keeps working after your bundler renames functions. * **Don't patch the grid.** Contribute through the context; react through events. ## ModuleDef | Field | Type | Description | |---|---|---| | `name` | `string` | Unique per grid ([DG009](/errors/DG009)); also the property the API is installed under. | | `kind` | `"source" \| "feature" \| "toolbar" \| "export"` | `"source"` marks a data source module (it must carry `source`). The other kinds describe the module; they don't change how it is wired. | | `slot` | `string` | Single-slot claim. `"source"` is the only single slot today: a second claimant throws [DG008](/errors/DG008). | | `requires` | `string[]` | Names of modules that must be attached too, e.g. `["state"]` ([DG007](/errors/DG007)). | | `enforce` | `"pre" \| "post"` | Default position for this module's request middleware. | | `can` | `boolean` | Permission flag. `false` attaches the module without calling `setup`; its API is a no-op stand-in. | | `source` | `DataSource` | Data source modules only: `{ mode, cells?, load(query, ctx), … }`. Wrap one with `sourceModule()` or `customSource()`. | | `setup(ctx)` | `(ctx) => { api?, destroy? } \| void` | Called when the module is attached. Return the API object and a teardown function. | TypeScript: `ModuleDef<"rowBadge", { el: HTMLElement }>` types `grid.module(rowBadge)`. ## When setup runs Modules in `use: [...]` are set up inside the constructor, **before** the columns are resolved and the header is built. So in `setup`: * `ctx.grid.columns()` is still empty: read columns in `ctx.ready(fn)`. * The header doesn't exist yet: decorate header cells in a `headrender` listener (it fires on every header rebuild). * `ctx.toolbar()`, `ctx.row()`, `ctx.request()`, `ctx.state()` and `ctx.on()` can all be called. Modules attached later with `grid.use()` are set up immediately; their `ready` callbacks run at once. ## ModuleContext | Member | Type | Description | |---|---|---| | `grid` | `DatagridApi` | The grid ([instance methods](/reference/methods)). | | `root` | `HTMLElement` | The `.dg` wrapper. | | `table` | `HTMLTableElement` | The host table. | | `messages` | `Messages` | The grid's merged UI strings. Modules keep their own strings in a `messages` option. | | `host` | `HostAdapters` | Resolved host adapters (`confirm`, `notify`, `csrf`, `laravel`, `timeout`, `onSessionExpired`, `fetch`, `isError`). | | `locale` | `string` | The grid's locale (`ctx.locale.startsWith("tr")` picks a language pack). | | `signal` | `AbortSignal` | Aborted when the grid is destroyed: `el.addEventListener("click", fn, { signal: ctx.signal })`. | | `on(type, fn)` | `() => void` | `grid.on`; returns the unsubscribe function. | | `toolbar({ slot, order?, el })` | `void` | Places `el` in the toolbar slot `"start"`, `"end"` or `"filters"`, sorted by `order` (default `0`; equal orders keep registration order). | | `row(fn)` | `void` | Row mutator `fn(tr, row, key)`: runs after a row is built and again when a kept row is re-rendered, so make it idempotent. | | `request(mw, enforce?)` | `void` | Adds request middleware, see [below](#request-middleware). | | `state({ key, save, load, part? })` | `void` | State contribution: `save()` returns a JSON-safe value, `load(value)` restores it. [stateSave](/modules/state-save) stores it under `key`. With `part: "filters" \| "search" \| "page"` it belongs to that opt-in part and is saved only when stateSave's `include` lists it. | | `above(el)` | `void` | Mounts `el` between the toolbar and the table (bulk bars, banners). | | `layer(el)` | `void` | Mounts `el` inside the root, for panels and dialogs (popovers render in the top layer). | | `announce(message)` | `void` | Polite live-region announcement. | | `requestRender()` | `void` | Re-renders the body from the current rows without loading. | | `ready(fn)` | `void` | Runs `fn` once the columns are resolved, before the first load (restore state here; it won't trigger extra requests). | Built-in toolbar orders, to place your item between them: | Slot | Order | Item | |---|---|---| | `start` | `0` | search box | | `start` | `10` | column menu (`colVis`) | | `start` | `20` | reload button | | `start` | `30` | reset button | | `start` | `40` | export menu (`excel`, `csv`, `print`) | | `start` | `50` / `60` | `button.custom()` / `button.group()` | | `end` | `-20` | auto-refresh toggle (`autoRefresh`) | | `end` | `-10` | soft-deletes toggle | | `end` | `0` | record count (`count: true`) | | `filters` | `-20` | filter preset chips (`filterPresets`) | | `filters` | `100` | active column filter chips | ## Request middleware ```ts type RequestMiddleware = (req: WireRequest, next: (req: WireRequest) => Promise) => Promise; ``` Each server request passes through a chain of middleware before the protocol encodes it. A middleware changes the neutral request and calls `next(req)` **once** (twice throws), or returns a `Response` itself to short-circuit (cache, mock). | `WireRequest` field | Type | Description | |---|---|---| | `url` | `string` | Endpoint. | | `method` | `string` | `GET` or `POST`. | | `headers` | `Record` | Request headers. | | `query` | `Query` | The neutral query (page, sort, search, filters, columns). Read it; change state through the grid. | | `params` | `Record` | Extra parameters the protocol adds to the wire (form fields, JSON `params`, query string). | Order, fixed and without numeric priorities: 1. built-ins: `X-Requested-With` (`laravel`), then CSRF (`csrf`) 2. middleware registered with `"pre"` 3. middleware without `enforce`, in registration order 4. middleware registered with `"post"` 5. protocol `encode` → `fetch` `enforce` comes from the `ctx.request(mw, enforce)` argument, else from the definition's `enforce`. Middleware runs for `serverSide` sources (including the one-off request of `exportRows("all")`); `fetchAll` and array sources don't run it. ```js ctx.request(async (req, next) => { req.headers["X-Tenant"] = tenant.id; const res = await next(req); if (res.status === 409) ctx.grid.notify("info", "The list changed, reloading…"); return res; }, "post"); ``` ## Wiring errors Wiring mistakes throw instead of half-working: | Code | Thrown when | |---|---| | [DG007](/errors/DG007) | A name in `requires` is not attached (checked after the constructor's `use`, or in a microtask after `grid.use()`). | | [DG008](/errors/DG008) | A second module claims the `source` slot after a source was given explicitly (in `use` or with `data`), also through `grid.use()`. Without one, a chained `.use(serverSide(…))` replaces the default source (the table's rows or an empty array) instead of throwing. | | [DG009](/errors/DG009) | The same module name is attached twice. | | [DG010](/errors/DG010) | `name` is a core grid member (`reload`, `columns`, `status`, …) or another existing grid property. | ## A data source module A data source is a module with `kind: "source"` and a `source`. `customSource()` builds one: ```js import { customSource } from "@akinozgen17/datagrids"; const fromIndexedDb = customSource({ mode: "client", async load(query, ctx) { const rows = await db.getAll("agents"); return { rows, total: rows.length, filtered: rows.length }; }, }); ``` `mode: "server"` sources receive the full `query` and return one page; they get the middleware chain as `ctx.middlewares`. See [Data sources](/guide/data-sources#custom-sources). ## Related * [Concepts](/guide/concepts) · [Events](/reference/events) · [Instance methods](/reference/methods) * [Recipe: custom toolbar](/recipes/custom-toolbar) --- --- url: https://akinozgen.github.io/datagrids/reference/messages.md description: >- Every UI string key of the grid with its English and Turkish default, how to override them, and the message keys of each module. --- # Messages Every visible or announced string comes from a `Messages` object. The grid picks a pack by locale (locales starting with `tr` get Turkish, all others English) and merges overrides over it: ```text language pack → configure({ messages }) → grid option messages ``` Keys you leave out, or set to `undefined`, keep the value from the layer below. ```js import { configure, Datagrid } from "@akinozgen17/datagrids"; configure({ messages: { empty: "Nothing here yet" } }); // every grid created afterwards new Datagrid("#agents", { label: "Agents", messages: { found: (n) => `${n} agents found`, records: "agents" }, // this grid only columns, }); ``` Function keys keep their signature. Numbers arrive **already formatted** for the grid's locale (`"1,234"` / `"1.234"`), so a function only places them. Both packs are exported as `en` and `tr` for starting a new language; see [Static API](/reference/static#en-tr) and [Localization](/guide/i18n). ## Toolbar and states | Key | English | Turkish | |---|---|---| | `search` | Search… | Ara… | | `searchLabel` | Search | Ara | | `clear` | Clear | Temizle | | `loading` | Loading… | Yükleniyor… | | `empty` | No records | Kayıt yok | | `emptyText` | There is nothing to show yet. | Henüz gösterilecek kayıt yok. | | `noMatch` | No matching records | Eşleşen kayıt bulunamadı | | `noMatchText` | Try a different search term. | Farklı bir arama deneyin. | | `clearSearch` | Clear search | Aramayı temizle | | `error` | Couldn't load the list | Liste yüklenemedi | | `errorText` | Something went wrong while loading. You can try again. | Yüklenirken bir sorun oluştu. Yeniden deneyebilirsiniz. | | `retry` | Retry | Yeniden dene | | `errorDetail` | Details | Ayrıntı | | `manual` | List not loaded yet | Liste henüz yüklenmedi | | `manualText` | Load the list when you need it. | Listeyi gerektiğinde yükleyin. | | `load` | Load | Yükle | | `records` | records | kayıt | `search` is the placeholder, `searchLabel` the accessible name of the search box. `empty` / `emptyText` show when there are no rows at all, `noMatch` / `noMatchText` when a search or filter matches nothing. `manual*` and `load` belong to `load: "manual"`. ## Footer and pager | Key | English (example output) | Turkish (example output) | |---|---|---| | `info(from, to, filtered, total)` | 51–75 / 340 records (total 1,234) | 51–75 / 340 kayıt (toplam 1.234) | | `infoUnknown(from, to)` | 51–75 shown | 51–75 gösteriliyor | | `totalUnknown` | total unknown | toplam bilinmiyor | | `pageSize` | Per page | Sayfa başına | | `page` | Page | Sayfa | | `pageOf(total)` | of 14 | / 14 | | `pagination` | Pagination | Sayfalama | | `first` | First page | İlk sayfa | | `prev` | Previous page | Önceki sayfa | | `next` | Next page | Sonraki sayfa | | `last` | Last page | Son sayfa | | `all` | All | Tümü | `info` gets `total = null` when nothing is filtered out (then the parenthesis is left out). `infoUnknown` and `totalUnknown` are used when the server doesn't count. `pagination` names the pager landmark (followed by the grid's label), `all` is the `-1` page size. ## Announcements and landmarks | Key | English (example output) | Turkish (example output) | |---|---|---| | `skip` | Skip table | Tabloyu atla | | `regionLabel` | Data table | Veri tablosu | | `sortedAsc(col)` | Sorted by Name, ascending | Sıralama: Name, artan | | `sortedDesc(col)` | Sorted by Name, descending | Sıralama: Name, azalan | | `sortCleared` | Sorting cleared | Sıralama kaldırıldı | | `found(n)` | 12 records found | 12 kayıt bulundu | | `pageAnnounce(page, pages)` | Page 2 of 14 | Sayfa 2 / 14 | | `openRow` | Open row | Satırı aç | `skip` is the "skip table" link text; `regionLabel` the fallback name of an unnamed grid ([DG002](/errors/DG002)); `openRow` the hidden header of the `rowClick` chevron column. ## Errors | Key | English | Turkish | |---|---|---| | `errNetwork` | The server could not be reached. Check your connection. | Sunucuya ulaşılamadı. Bağlantınızı kontrol edin. | | `errTimeout` | The server took too long to respond. | Sunucu zamanında yanıt vermedi. | | `errSession` | Your session has expired. Please sign in again. | Oturumunuz sona erdi. Lütfen yeniden giriş yapın. | | `errForbidden` | You are not allowed to view this list. | Bu listeyi görüntüleme yetkiniz yok. | | `errServer(status)` | The server returned an error (500). | Sunucu bir hata döndürdü (500). | | `errParse` | The server response could not be read. | Sunucu yanıtı okunamadı. | A server's own message (JSON `message`, a validation error) is shown instead of `errForbidden` and `errServer` for 403, 410, 422 and 429 responses. ## Dialogs and actions | Key | English | Turkish | |---|---|---| | `confirmTitle` | Are you sure? | Emin misiniz? | | `confirmOk` | Confirm | Onayla | | `confirmCancel` | Cancel | Vazgeç | | `actionDone` | Done. | İşlem tamamlandı. | Used by the built-in confirm dialog and `grid.action()` when the response has no `message`. ## Module messages Modules keep their own strings. Each takes a `messages` option (partial, merged over its pack) and picks Turkish or English by the grid's locale like the core. ```js colVis({ messages: { button: "Fields" } }); excel({ messages: { excel: "Spreadsheet (.xlsx)" } }); ``` ### colVis | Key | English | |---|---| | `button` | Columns | | `legend` | Show / hide columns | | `showAll` | Show all | | `reset` | Reset to default | | `search` | Find column… | | `searchLabel` | Find column | | `noMatch` | No matching columns | | `locked` | This column can't be hidden | ### colReorder | Key | English (example output) | |---|---| | `earlier(col)` | Move Name earlier | | `later(col)` | Move Name later | | `moved(col, pos, total)` | Name moved to position 2 of 6. | | `hint` | Drag to move | ### columnFilters | Key | English (example output) | |---|---| | `filter(col)` | Filter: Name | | `apply` | Apply | | `clear` | Clear | | `clearAll` | Clear filters | | `value` | Value | | `and` | and | | `active(n)` | 2 filters | | `ops` | operator labels, see below | `ops` maps every operator to its label: `eq` equals, `ne` not equal, `gt` greater than, `gte` at least, `lt` less than, `lte` at most, `between` between, `in` is any of, `notIn` is none of, `contains` contains, `notContains` does not contain, `starts` starts with, `ends` ends with, `empty` is empty, `notEmpty` is not empty. Override the whole `ops` object when you change it. ### selection | Key | English (example output) | |---|---| | `selected` | selected | | `idle` | Select rows to enable actions | | `selectAll(n)` | Select all 340 matching | | `allSelected` | All matching records are selected. | | `clear` | Clear selection | | `hidden(n)` | 3 not shown | | `row(label)` | Select: Jill Valentine | | `page` | Select all on this page | | `column` | Select | | `bar` | Selection | | `announce(n)` | 3 rows selected | | `announceAll(n)` | All 340 matching rows selected | | `cleared` | Selection cleared | | `reset` | The filter changed; select-all was cleared | ### actions | Key | English (example output) | |---|---| | `actions` | Actions | | `more` | More actions | | `forRow(label)` | Actions: Jill Valentine | ### excel, csv, print The export modules share one menu and one message object. | Key | English (example output) | |---|---| | `menu` | Export | | `excel` | Excel (.xlsx) | | `csv` | CSV | | `print` | Print | | `yes` | Yes | | `no` | No | | `records` | records | | `done(n)` | 340 records exported | | `failed` | Export failed | | `truncated(n, total)` | Only the first 1,000 of 4,200 records were exported | ### button.reload, button.resetState | Key | English | |---|---| | `reload` | Reload | | `resetState` | Reset | | `resetStateTitle` | Reset the view to its defaults | `button.custom()` and `button.group()` take their text from `label`. ### softDeletes | Key | English | |---|---| | `label` | Show deleted | ### footer | Key | English | |---|---| | `page` | Page total | | `total` | Total | ### responsive | Key | English | |---|---| | `show` | Show hidden columns | | `hide` | Hide hidden columns | ## Related * [Localization & RTL](/guide/i18n) · [Grid options](/reference/options#localization) · [Static API](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/reference/css.md description: >- Every public --dg-* design token with its default and meaning, the two input tokens, the root attributes that switch size, density, theme and states, and the host hooks. --- # CSS tokens All styling is driven by custom properties named `--dg-*`. They are defined on the grid root `.dg` (and on `.dg-portal`, the fallback root panels use when the browser has no Popover API), never on `:root`, and without `@layer`. Pixel values below assume the default `--dg-rem` of 16 px. ```css /* rebrand every grid on the page */ :root { --dg-accent: #0f766e; } /* one grid: set tokens on its root */ #agents-page .dg { --dg-head-bg: #eef2ff; --dg-row-h: 2rem; } ``` * **Input tokens** (`--dg-accent`, `--dg-rem`) are only read, never defined, so they inherit: set them on `:root`, `body`, any wrapper or `.dg`. * **All other tokens** are defined on `.dg`: override them with a selector that matches the root and is more specific than `.dg` (`.my-page .dg`). The `data-size` and `data-density` variants use `.dg[data-…]`, so overriding a size or density token needs at least that specificity. * Tokens starting with **`--dg-_`** (underscore) are private row-state variables: don't set or read them. See [Theming](/guide/theming) for the how-to. ## Input tokens | Token | Default | Meaning | |---|---|---| | `--dg-accent` | `#3d63dd` (read as `var(--dg-accent, #3d63dd)`) | Brand color. Every accent token below derives from it, with legibility guarded in modern browsers. | | `--dg-rem` | `1rem` | Base unit; every size, space and radius is a multiple of it. If the host shrinks `html { font-size }` for its own layout, pin it: `body { --dg-rem: 16px; }`. | ## Palette Light values are the static defaults; dark values apply under a dark `color-scheme` in browsers with `light-dark()`. | Token | Light | Dark | Meaning | |---|---|---|---| | `--dg-bg` | `#ffffff` | `#17191d` | Cell and body background. | | `--dg-fg` | `#1c2024` | `#e6e8eb` | Primary text. | | `--dg-muted` | `#f2f3f5` | `#26292f` | Control hover background, neutral surface. | | `--dg-muted-fg` | `#667085` | `#9aa2b1` | Secondary text. | | `--dg-border` | `#d5d9e0` | `#3a3f47` | Control border. | | `--dg-border-hover` | `#b6bcc8` | `#4d535d` | Control border on hover. | | `--dg-border-strong` | `#858d9b` | `#737b89` | Checkbox box, neutral sort icon (≥ 3:1). | | `--dg-head-bg` | `#f6f7f9` | `#1f2227` | Header row, ``, card header. | | `--dg-head-fg` | `#596579` | `#a3abb9` | Header text. | | `--dg-panel-bg` | `#ffffff` | `#212429` | Column menu, row menu, popovers. | | `--dg-panel-border` | `#e4e7ec` | `#3a3f47` | Panel border. | | `--dg-surface` | `#ffffff` | `#1b1d22` | Background of `surface: "card"`. | | `--dg-danger` | `#d93843` | `#f0656e` | Destructive actions. | ## Tones Used by badge chips, row tones, banners and states. | Token | Light | Dark | Meaning | |---|---|---|---| | `--dg-tone-neutral` | `#475467` | `#a0afc5` | Neutral chip. | | `--dg-tone-info` | `#1d63c8` | `#66adff` | Info chip and notes. | | `--dg-tone-ok` | `#15803d` | `#67c67f` | Success chip. | | `--dg-tone-warn` | `#b45309` | `#f78f54` | Warning chip and banner. | | `--dg-tone-bad` | `#c0262d` | `#ff756f` | Error chip, banner and state. | | `--dg-row-ok` | `#edf8f1` | `#15281c` | Row background for `rowTone` `"ok"`. | | `--dg-row-warn` | `#fff6dc` | `#2b2312` | Row background for `"warn"`. | | `--dg-row-bad` | `#fdeeee` | `#2e1719` | Row background for `"bad"`. | | `--dg-row-info` | `#edf3fd` | `#162133` | Row background for `"info"`. | ## Accent derivatives Component rules never use `--dg-accent` directly, only these. Static fallbacks are listed; modern browsers derive them with `color-mix()` and relative color syntax. | Token | Default | Meaning | |---|---|---| | `--dg-accent-solid` | `var(--dg-accent)` | Filled surfaces: checked checkbox, current page. Lightened in dark mode. | | `--dg-accent-fg` | `#ffffff` | Text and glyphs on `--dg-accent-solid`; modern browsers pick black or white by the accent's lightness. | | `--dg-accent-ink` | `var(--dg-accent)` | Accent as text, icon and focus border; modern browsers cap its lightness so it keeps ≥ 4.5:1 on white. | | `--dg-accent-weak` | `#ecf1fe` | Tinted surface (9 % accent). | | `--dg-ring` | `rgba(61, 99, 221, 0.24)` | Focus halo. | ## Derived neutrals | Token | Default | Meaning | |---|---|---| | `--dg-line` | `#e5e6e7` | Row separator. | | `--dg-line-strong` | `#d6d7d9` | Line under the header and above ``. | | `--dg-row-alt` | `#f9f9f9` | Zebra row (`striped`). | | `--dg-veil-hover` | `rgba(28, 32, 36, 0.04)` | Row hover veil. | | `--dg-veil-selected` | `rgba(61, 99, 221, 0.10)` | Selected row veil. | | `--dg-veil-selected-hover` | `rgba(61, 99, 221, 0.14)` | Selected row on hover. | | `--dg-scrollbar-thumb` | `rgba(28, 32, 36, 0.18)` | Scrollbar thumb. | | `--dg-skeleton` | `#eceef1` | Loading placeholders. | | `--dg-overlay` | `rgba(255, 255, 255, 0.55)` | Veil over the body while reloading. | ## Spacing and radius | Token | Default | Meaning | |---|---|---| | `--dg-space-1` | `0.25 × rem` (4 px) | Spacing scale on a 4 px grid. | | `--dg-space-2` | 8 px | | | `--dg-space-3` | 12 px | | | `--dg-space-4` | 16 px | | | `--dg-space-5` | 20 px | | | `--dg-space-6` | 24 px | | | `--dg-space-8` | 32 px | | | `--dg-radius-xs` | 4 px | Checkbox, skeleton. | | `--dg-radius-sm` | 6 px | Menu item, id pill, cell button. | | `--dg-radius-md` | 8 px | Controls. | | `--dg-radius-panel` | 10 px | Panels (item radius + panel padding). | | `--dg-radius-surface` | 12 px | Card surface. | | `--dg-radius-full` | `999px` | Badges, counters. | ## Typography The font family is inherited from the host. | Token | Default | Meaning | |---|---|---| | `--dg-font-size-xs` | 11 px | Chips, caps headers. | | `--dg-font-size-sm` | 12 px | Sentence headers, footer info, captions. | | `--dg-font-size-md` | 13 px | Body text at `size: "md"`. | | `--dg-font-size-lg` | 14 px | Body text at `size: "lg"`. | | `--dg-line-height` | `1.45` | Cells. | | `--dg-line-height-tight` | `1.25` | Controls, chips. | | `--dg-weight-regular` | `400` | | | `--dg-weight-medium` | `500` | | | `--dg-weight-strong` | `600` | | | `--dg-font-mono` | `ui-monospace, SFMono-Regular, Menlo, Consolas, monospace` | Monospace text. | | `--dg-head-font-size` | `var(--dg-font-size-xs)` · sentence: `var(--dg-font-size-sm)` | Header text size. | | `--dg-head-weight` | `700` · sentence: `600` | Header weight. | | `--dg-head-transform` | `uppercase` · sentence: `none` | Header case. | | `--dg-head-tracking` | `0.06em` · sentence: `normal` | Header letter spacing. | ## Shadows | Token | Meaning | |---|---| | `--dg-shadow-xs` | Small controls. | | `--dg-shadow-panel` | Menus and popovers (layered, low alpha; weaker in dark mode). | | `--dg-shadow-surface` | Card surface. | | `--dg-shadow-edge-start` | Overflow shadow of a column pinned to the start. | | `--dg-shadow-edge-end` | Overflow shadow of a column pinned to the end. | | `--dg-shadow-stuck` | Sticky header while scrolled. | ## Motion All motion is turned off under `prefers-reduced-motion: reduce`. | Token | Default | Meaning | |---|---|---| | `--dg-dur-1` | `100ms` | Exits, micro feedback. | | `--dg-dur-2` | `160ms` | Entrances, panel opening. | | `--dg-dur-3` | `220ms` | Chevron rotation. | | `--dg-ease-out` | `cubic-bezier(0.22, 1, 0.36, 1)` | | | `--dg-ease-in` | `cubic-bezier(0.4, 0, 1, 1)` | | | `--dg-ease-inout` | `cubic-bezier(0.65, 0, 0.35, 1)` | | ## Stacking Inside the table only; panels and dialogs use the browser's top layer and need no z-index. | Token | Default | Meaning | |---|---|---| | `--dg-z-sticky-col` | `2` | Pinned columns. | | `--dg-z-sticky-head` | `3` | Sticky header. | | `--dg-z-sticky-corner` | `4` | Header cell of a pinned column. | | `--dg-z-overlay` | `5` | Reload veil. | ## Size `md` defaults; `data-size="sm"` / `"lg"` override them. On touch screens (`pointer: coarse`) controls grow to 44 px unless the size is already `lg`. | Token | sm | md (default) | lg | Meaning | |---|---|---|---|---| | `--dg-font-size` | 12 px | 13 px | 14 px | Body text. | | `--dg-control-h` | 30 px | 34 px | 40 px | Buttons, inputs, selects (44 px on touch). | | `--dg-control-pad-x` | 8 px | 10 px | 12 px | Control padding. | | `--dg-control-radius` | | `var(--dg-radius-md)` | | Control radius. | | `--dg-icon-size` | 14 px | 16 px | 18 px | Icons. | | `--dg-check-size` | 14 px | 16 px | 18 px | Checkboxes (18 px on touch). | | `--dg-cell-btn-h` | 24 px | 28 px | 32 px | Buttons inside cells. | ## Density Independent of size: `data-density="compact"` / `"comfortable"` override the `normal` defaults. | Token | compact | normal (default) | comfortable | Meaning | |---|---|---|---|---| | `--dg-row-h` | 28 px | 36 px | 44 px | Row height (acts as the cells' minimum height). | | `--dg-cell-pad-y` | 4 px | 8 px | 12 px | Vertical cell padding. | | `--dg-cell-pad-x` | 8 px | 12 px | 14 px | Horizontal cell padding. | | `--dg-cell-btn-h` | 22 px | (size) | (size) | Cell buttons in compact rows. | | `--dg-cell-valign` | | `top` | | Vertical alignment; keeps multi-line rows aligned. | | `--dg-head-h` | | `var(--dg-row-h)` | | Header row height. | ## Panels | Token | Default | Meaning | |---|---|---| | `--dg-panel-pad` | 4 px | Panel padding. | | `--dg-panel-offset` | 6 px | Gap between a trigger and its panel. | | `--dg-panel-max-h` | `min(24 × rem, 70dvh)` | Panel height limit (scrolls beyond). | | `--dg-menu-item-h` | 32 px | Menu item height (44 px on touch). | ## Host hooks Variables the stylesheet reads but doesn't define: | Variable | Default | Meaning | |---|---|---| | `--dg-row-bg` | — | Background for specific rows, set from your own CSS (`.dg-table tr.vip { --dg-row-bg: … }`); wins over row tones and zebra. | | `--dg-max-h` | `70vh` | Height limit of the scroll area with `maxHeight` (set by that option) and with virtual rows. | | `--dg-clamp` | `2` | Line count for content wrapped in `` (multi-line truncation). | ## Root attributes The grid writes these on its root `.dg`; style against them, never against classes the grid toggles. | Attribute | Values | Set by | |---|---|---| | `data-state` | `loading`, `ready`, `empty`, `error`, `idle` | Load status (`idle` = `load: "manual"` before loading). | | `data-size` | `sm`, `lg` (absent = `md`) | `size` option. | | `data-density` | `compact`, `comfortable` (absent = `normal`) | `density` option. | | `data-dg-theme` | `light`, `dark`, `system` (absent = inherit) | `theme` option. | | `data-dg-head` | `sentence` (absent = caps) | `head` option. | | `data-dg-surface` | `card` | `surface` option. | | `data-dg-striped` | present | `striped: true`. | | `data-dg-nowrap` | present | `wrap: false`. | | `data-dg-sticky-head` | present | `maxHeight` (sticky header). | | `data-dg-virtual` | present | Virtual rows are active. | | `data-bp` | `xs` (< 480 px), `sm` (< 768 px), `md` (< 1024 px), `lg` | Width of the grid root (not the viewport). At `xs` the toolbar and footer stack and the pager becomes a select. | The scroll frame also carries `data-overflow="start end"` while the table scrolls horizontally, and `data-busy="visible"` while a reload runs longer than 300 ms. The full DOM contract is in [Anatomy](/guide/anatomy). ## Related * [Theming](/guide/theming) · [Anatomy](/guide/anatomy) · [Grid options: appearance](/reference/options#appearance) --- --- url: https://akinozgen.github.io/datagrids/errors.md description: >- Every coded datagrids console warning and thrown error (DG001–DG015) with its message, cause and fix, plus the uncoded module messages. --- # Warning codes datagrids reports mistakes with a code in the message, `[datagrids DG0xx] …`. Each code has its own page (`/errors/DG008`); this page lists them all. | Kind | How it surfaces | Codes | |---|---|---| | Console warning | `console.warn`, printed **once per distinct message** | DG001, DG002, DG003, DG004, DG006, DG011, DG012, DG013, DG014, DG015 | | Thrown error | `throw new Error(message)` — wiring mistakes never half-work | DG005, DG007, DG008, DG009, DG010 | Warnings are on by default. `configure({ warnings: false })` silences every coded warning (and the module messages below that respect it); thrown errors are never silenced. ```js import { configure } from "@akinozgen17/datagrids"; configure({ warnings: import.meta.env.DEV }); // keep them in development only ``` ## DG001 **Unknown grid option** · console warning ```text [datagrids DG001] Unknown option `{name}`.{hint} ``` **When:** the options object passed to `new Datagrid()` has a key that is not a grid option. The key is ignored. The message adds a hint: for a well-known legacy option name (compared case-insensitively) it names the replacement; for anything within two typing edits of a real option it suggests that option (`pagesize` → ``Did you mean `pageSize`?``). **Fix:** rename or remove the key. The [grid options](/reference/options) are the only accepted keys; every other capability is a column option or a [module](/modules/) in `use: [...]`. | Key you passed | Hint printed | |---|---| | `serverSide` | Server mode is a module: use `serverSide({ url, protocol: yajra() })`. | | `ajax` | Use the `serverSide({ url, … })` module. | | `dom` | Use toolbar slots (`start`, `end`, `filters`). | | `buttons` | Attach button modules (`button.reload()`, `excel()`…). | | `language` | Use `messages`. | | `stateSave` | Use the `stateSave()` module. | | `lengthMenu` | Use `pageSizes`. | | `pageLength` | Use `pageSize`. | | `order` | Use `sort: [['key', 'desc']]`. | | `deferLoading` | Use `load: 'manual'`. | | `columnDefs` | Put options on the column definitions. | The [migration guide](/migration/from-datatables) maps every legacy option. ## DG002 **Grid has no accessible name** · console warning ```text [datagrids DG002] Grid has no accessible name; pass `label` or `labelledBy`. ``` **When:** the grid was created without `label`, `labelledBy` or `title`, and the table has no ``. Assistive technology then announces the scroll region with the generic `messages.regionLabel` ("Data table"), the same name for every grid on the page. **Fix:** name every grid after what it lists: `new Datagrid("#agents", { label: "Field agents", columns })`. Or point at a visible heading with `labelledBy: "agents-heading"`, or keep a ``. `title` names the grid only together with `surface: "card"`; `label` works everywhere. ## DG003 **Rows have no key** · console warning ```text [datagrids DG003] No row key found (rowKey/id/DT_RowId); falling back to index. Selection and focus keeping are disabled. ``` **When:** a row has no key: `rowKey` is not set and the row has neither `id` nor `DT_RowId`, or the `rowKey` path or function returned `null` or `""`. The grid falls back to the row's position (`__i0`, `__i1`, …). **Fix:** tell the grid which field identifies a row — a path (`rowKey: "uuid"`) or a function (``rowKey: (row) => `${row.unit}-${row.ref}` ``). Position keys change whenever the data changes, so selection, `refreshRow(key)`, `removeRow(key)`, row actions and focus restoration cannot follow a row across pages or reloads. ## DG004 **Unknown column key** · console warning ```text [datagrids DG004] Unknown column key `{name}`. ``` **When:** reserved for calls that name a column key the grid does not have. **The current version does not print DG004**: `setColumnVisible()` and `columnOrder()` ignore unknown keys silently, and the footer module prints its own message (see [below](#other-console-messages)). **Fix:** check the key against `grid.columns().map((c) => c.key)`. A column with `can: false` does not exist at all, so its key is unknown too. ## DG005 **Selector must match exactly one table** · thrown error ```text [datagrids DG005] `{name}` needs a selector that matches exactly one ; matched {count}. ``` **When:** `new Datagrid(selector)` or `grid.remount(selector)` got a CSS selector that matched no element, more than one element, or a single element that is not a `
` (reported as "matched 0"). Thrown synchronously by the constructor. **Fix:** use a unique selector (`"#agents"`) or pass the `HTMLTableElement` itself, and create the grid after the table is in the document (for example after a tab or modal has rendered its content). `Datagrid.get()` and `get()` never throw; they return `null`. ## DG006 **No grid with that name** · console warning ```text [datagrids DG006] Datagrids.reload(`{name}`): no grid with that name. ``` **When:** `reload(name)` found no live grid registered under `name`; it returns `false` and does nothing. A grid registers its `name` option when it is created and unregisters on `destroy()`. **Fix:** give the grid a `name` (`{ name: "agents", … }`) and make sure it exists when you reload it. Use `find(name)` to check for a grid without a warning. ## DG007 **Required module is missing** · thrown error ```text [datagrids DG007] Module `{name}` requires `{dep}`, which is not attached. ``` **When:** a module declares `requires: ["…"]` and no module with that name is attached. The check runs after all modules from the constructor's `use` are attached (thrown by the constructor) and, for `grid.use()`, in a microtask afterwards (an uncaught error in the console). Built-in case: `button.resetState()` requires `state`, the module name of `stateSave()`. **Fix:** attach the dependency in the same `use` array; the order inside the array does not matter: `use: [stateSave(), button.resetState()]`. ## DG008 **Two modules claim one slot** · thrown error ```text [datagrids DG008] Two modules claim the single `{slot}` slot (`{a}` and `{b}`). ``` **When:** two modules claim the `source` slot, the only single slot. Every data source occupies it: `serverSide`, `arraySource`, `domSource`, `fetchAll`, `customSource`. Thrown when `use` contains two sources, or when a source is attached with `grid.use()` after construction: by then the grid has already picked its default source (array, DOM or empty). `{a}` is the source in place, `{b}` the one being attached. **Fix:** attach exactly one source, in `use: [...]` at construction: ```js new Datagrid("#agents", { label: "Agents", columns, use: [serverSide({ url: "/api/agents", protocol: yajra() })], }); ``` To switch sources, `destroy()` the grid and create a new one. Note that `data: [...]` is ignored, without an error, when `use` already contains a source. ## DG009 **Module attached twice** · thrown error ```text [datagrids DG009] Module `{name}` is attached twice. ``` **When:** a module name is attached a second time: the same factory twice (`colVis()` in a preset and again on the page) or two modules with the same `name`, such as two `button.custom({ name: "approve", … })`. **Fix:** attach each module once per grid. When a [preset](/reference/static#preset) already contains a module, don't repeat it; give custom buttons distinct names, or leave `name` out to get an automatic one. ## DG010 **Module name collides with a grid member** · thrown error ```text [datagrids DG010] Module name `{name}` collides with a core grid member. ``` **When:** a module's `name` is a core grid member (`reload`, `columns`, `search`, `status`, …) or another property the grid instance already has. A module's API is installed on the grid under its name, so the name must be free. Data source modules are exempt. **Fix:** rename the module, for example `name: "reloadButton"` instead of `"reload"`. The built-in modules already use free names (`state`, `colVis`, `selection`, …). See [Writing a module](/reference/modules). ## DG011 **Document has no language** · console warning ```text [datagrids DG011] is missing; uppercase headers may render Turkish i wrong (TARIH). ``` **When:** the page's `` element has no `lang` attribute while the grid uses uppercase headers (the default `head: "caps"`). Uppercasing in CSS depends on the language: in Turkish `i` becomes `İ`, elsewhere `I`, so a header can come out wrong. Without `lang`, and without a `locale` option or `configure({ locale })`, the grid also takes the browser's language (English when that is unusable). **Fix:** declare the page language: ``. Or switch to sentence-case headers with `head: "sentence"`. Set `locale` when a grid's language differs from the page's. ## DG012 **Server error details** · console warning ```text [datagrids DG012] Server error: {detail} ``` **When:** a load failed and the error carries a `detail` the grid keeps out of the visible message: the exception message of an HTTP error response (JSON `message` / `error`, or up to 500 characters of a text body), the `error` string of an HTTP 200 SSP response (debug output), or the browser's message for a network failure. The grid shows a generic message; the detail goes to the console. **Fix:** fix the server-side problem the detail describes. While `warnings` is on (the default) the error state also shows the detail in a "Details" disclosure. In production turn both off with `configure({ warnings: false })`. The full error object is on the `error` event: `grid.on("error", ({ error }) => report(error.kind, error.status, error.detail))`. See [States & errors](/guide/states-and-errors). ## DG013 **Page size above maxPageSize** · console warning ```text [datagrids DG013] Page size {size} exceeds maxPageSize {max}; clamped. ``` **When:** `grid.pageSize(n)` (also used by the page-size menu) got a value above `maxPageSize` (default 1000) or a negative value; the size is clamped to `maxPageSize`. `-1` ("All") is accepted only when the protocol allows it (`ssp({ allowAll: true })`). The initial `pageSize` option is not checked. **Fix:** keep `pageSizes` within `maxPageSize`, or raise the limit for this grid with `maxPageSize: 5000`. For lists that must show everything, prefer client mode (`fetchAll`) and a server-side export. ## DG014 **Grid state could not be saved** · console warning ```text [datagrids DG014] Could not write grid state to storage ({reason}). ``` **When:** reserved for state storage write failures (blocked storage, a full quota, some private browsing modes). **The current version prints an uncoded message instead**: `[datagrids] stateSave: storage is not writable (…); state is not persisted.`, once per page. **Fix:** nothing breaks: the grid works, the view is just not remembered. Pass another `Storage` (`stateSave({ storage: sessionStorage })`) or `storage: null` to turn persistence off deliberately. ## DG015 **Invalid locale** · console warning ```text [datagrids DG015] `{tag}` is not a valid locale; it is ignored. ``` **When:** the `locale` option, `configure({ locale })` or `` holds a value the `Intl` APIs reject (``, `locale: "tr_TR"`). Number and date formatting would throw on it, so the grid skips it and takes the next candidate: the browser's language, then `"en"`. **Fix:** use a BCP 47 tag (`tr`, `tr-TR`, `en-GB`). When the value comes from user settings, validate it on the server before writing it into the page. ## Other console messages Modules print a few messages without a code. All start with `[datagrids]`. | Message | When | Fix | Silenced by `warnings: false` | |---|---|---|---| | ``actions(): add `column.actions()` to the columns to place the action column.`` | [`actions()`](/modules/actions) is attached but the columns have no `column.actions()`. | Add `column.actions()` to `columns`. | no | | ``selection(): add `column.select()` to the columns to place the checkbox column.`` | [`selection()`](/modules/selection) is attached without `column.select()`. | Add `column.select()` (usually first). | yes | | `selection(): rows have no key (rowKey / id / DT_RowId); selections will not survive paging.` | Rows fall back to position keys (see [DG003](#dg003)). | Set `rowKey`. | yes | | `filterPanel: no element for "".` | A [`filterPanel`](/modules/filter-panel) field's selector matched nothing at setup. | Fix the selector, or create the grid after the form exists. | yes | | `footer: unknown column "".` | A [`footer`](/modules/footer) `cols` key is not a column of the grid (or has `can: false`). | Use an existing column key. | yes | | `urlSync: URL keys "" are taken; using namespace "".` | A second [`urlSync`](/modules/url-sync) on the page would reuse the same URL keys. | Give each grid its own `namespace`. | yes | | `lazyColumns: the data source is not in server mode; every column is already loaded.` | [`lazyColumns()`](/modules/lazy-columns) is attached to a client-mode grid. | Remove it, or use a `serverSide` source. | yes | | `stateSave: storage is not writable (); state is not persisted.` | Writing to storage threw (see [DG014](#dg014)). | Pass another `storage`, or `storage: null`. | yes | Errors are logged with `console.error`, never swallowed silently: | Logged | When | |---|---| | the listener's exception | An event listener added with `grid.on()` threw. The grid keeps running and the remaining listeners still run. | | `[datagrids] export failed` + the error | An excel / csv / print export failed. The user also gets the export's failure message (`notify` adapter and live region). | | the callback's exception | A custom footer aggregate, a `metaBind` value function or a module's state `save`/`load` threw; that one value is skipped. | A few calls throw plain errors (no code) for invalid input: | Error | When | |---|---| | `datagrids: method is not allowed` | `grid.action(url, { method })` with a method other than GET, POST, PUT, PATCH, DELETE. | | `datagrids: action URL must be same-origin` | `grid.action()` with a URL on another origin or a non-http(s) scheme. | | `datagrids: next() called multiple times` | A request middleware called `next()` more than once. | --- --- url: https://akinozgen.github.io/datagrids/protocol.md description: >- Which wire protocol to use between a datagrids grid and your server (SSP via ssp() or yajra(), Laravel paginator JSON, or the datagrids protocol v1) and how they differ. --- # Server protocols A server-side grid sends one request per page, sort, search or filter change. What that request and its response look like is the **protocol**. datagrids speaks three, all through the same `serverSide()` source: ```js import { Datagrid, serverSide, yajra } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Agents", columns, use: [serverSide({ url: "/agents/data", protocol: yajra(), csrf: true })], }); ``` ## Which one? | You have… | Use | Page | |---|---|---| | An endpoint written for DataTables' server-side processing, in any language | `ssp()` | [SSP wire](/protocol/ssp) | | A Laravel endpoint built with yajra/laravel-datatables | `yajra()` | [SSP wire](/protocol/ssp) | | A Laravel endpoint returning `paginate()`, `simplePaginate()`, `cursorPaginate()` or an API resource collection | `laravelPaginator()` | [Laravel paginator](/protocol/laravel-paginator) | | A new endpoint, or one you are free to change | `dgp()` | [datagrids protocol v1](/protocol/v1/) | Keep an existing endpoint as it is: the SSP and paginator adapters exist so that you can move the front end first and touch the back end later (or never). For new endpoints, prefer the datagrids protocol: sorting by key, typed filters, optional counting and one error format. ## How they differ | | `ssp()` / `yajra()` | `laravelPaginator()` | `dgp()` | |---|---|---|---| | Method | `ssp`: GET + `_=` timestamp; `yajra`: POST form body | GET | POST JSON (GET optional) | | Untyped cells | `ssp`: text; `yajra`: **HTML** (yajra escapes values) | text | text | | Sort | column index, several keys | first key only (`sort=-date`) | key, several keys | | Search | `search[value]` | `search` | `q` | | Page filters | plain parameters | plain parameters | `params` | | Typed column filters | `columns[i][columnControl]` (no `between`, `notIn`) | value only (operator dropped) | `filters`, 15 operators | | Counting | always | `paginate()`: yes; simple and cursor: next page only | `exact`, `estimate` or `none` | | "All" (`length=-1`) | opt-in (`allowAll: true`) | no | no | | Errors | HTTP status, or `error` in a 200 | HTTP status | RFC 9457 problem details | | Side data | extra top-level keys | `meta`, `links` | `meta.aggregates`, `facets`, `warnings` | "Untyped cells" are columns without a type: plain `{ key, title }` objects. Typed columns (`column.text()`, `column.money()`, `column.date()`, `column.badge()`…) always render the same way, whatever the protocol. Cells are text by default; HTML is an explicit opt-in (`column.html()`), and `yajra()` is the one protocol whose untyped cells are HTML, because yajra escapes every non-raw value on the server. ## What every protocol shares These come from `serverSide()`, not from the protocol: | Option | Default | What it does | |---|---|---| | `url` | required | Endpoint. A function `(query) => url` builds it per request | | `protocol` | required | `ssp()`, `yajra()`, `laravelPaginator()` or `dgp()` | | `method` | the protocol's | Overrides the method (`"GET"` or `"POST"`) | | `csrf` | `configure({ csrf })`, else `false` | Reads ``: `X-CSRF-TOKEN` header, plus `_token` in non-GET bodies | | `params` | none | Extra request parameters: an object, or a function of the query called per request | | `headers` | none | Extra request headers | | `timeout` | `30000` ms | Aborts the request and shows the timeout error | | `seed` | none | A response body rendered as the first page without a request (server-rendered first page) | | `fetch` | `globalThis.fetch` | Custom transport | And on every request: * **Headers:** `X-Requested-With: XMLHttpRequest` (turn it off with `configure({ laravel: false })`) and an `Accept` header that fits the protocol. Cookies are sent (`credentials: "same-origin"`). * **Last request wins:** a new request aborts the previous one, and responses are matched to requests by an internal sequence number, never by `draw` or `requestId`. * **Debug keys:** `queries` and `input` members (Laravel debug output, which can hold SQL and personal data) are deleted from the response before any event, module or `lastResponse()` sees it. * **Errors:** every failure becomes one `DatagridError` with a `kind`, a user-safe `message` and a `retryable` flag. See the [error table](/protocol/ssp#errors). * **Session expiry:** `401`, `419` and redirects to a login page fire the `sessionexpired` event. ## Related * [Server protocols guide](/guide/server-protocols): attaching a source, page filters, reloading. * [Data sources](/guide/data-sources): client-side sources (`data`, DOM, `fetchAll`) and `customSource`. * [States and errors](/guide/states-and-errors): loading, empty and error states in the grid. * [Migrating from DataTables](/migration/from-datatables). --- --- url: https://akinozgen.github.io/datagrids/protocol/ssp.md description: >- The exact request and response format datagrids uses with DataTables-style server-side processing endpoints (ssp() and yajra()), including encoding rules, column filters and error normalization. --- # SSP wire: `ssp()` and `yajra()` Endpoints written for DataTables' server-side processing (SSP) keep working unchanged: datagrids sends the parameter set DataTables 1.10 sends, encoded byte for byte like jQuery's `$.param`, and reads the same response. Two factories speak this wire: | | `ssp()` | `yajra()` | |---|---|---| | For | any SSP endpoint (PHP, .NET, Python, Node…) | Laravel + [yajra/laravel-datatables](https://yajrabox.com/docs/laravel-datatables) | | Default method | `GET` | `POST` | | Untyped cells | text | HTML | | Everything else | identical | identical | `yajra()` renders untyped cells as HTML because yajra escapes every value that is not in `rawColumns` on the server; rendering those as text would print `&`. Any other SSP server may send raw text, so `ssp()` keeps cells as text. Cells are text by default; HTML is an explicit opt-in everywhere else. Change the status, sort, search or page, then read the **Request** and **Response** tabs. The **Simulate** buttons make the next response fail. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, filterPanel, metaBind } from "@akinozgen17/datagrids"; const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }); new Datagrid("#proto-ssp", { label: "Agents (SSP wire)", columns: [ column.index(), { key: "ref", title: "Ref" }, { key: "name", title: "Name" }, { key: "unit", title: "Unit", visible: false }, // hidden columns still travel in columns[] column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), { key: "status_html", title: "Status", sortable: false, searchable: false }, // server HTML ], sort: [["amount", "desc"]], pageSize: 5, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), filterPanel({ fields: { status: "#proto-ssp-status" } }), // page filter → plain `status` parameter metaBind({ "#proto-ssp-sum": { value: "summary.total", format: (v) => usd.format(v) } }), ], }); ``` ```html [HTML]
summary.total (extra response key)—
``` ::: ## Options ```js serverSide({ url: "/agents/data", protocol: yajra({ allowAll: true }) }) ``` | Option | Type | Default | Description | |---|---|---|---| | `data` | object | `(d) => unknown` | none | DataTables `ajax.data`: an object is deep-merged into the parameters; a function may mutate `d` or return a replacement (an object, or a ready-made string) | | `dataSrc` | string | `(json) => rows` | `data`, then `aaData` | DataTables `ajax.dataSrc`: a dotted path to the rows (`""` = the body is the array) or a function | | `method` | `"GET"` | `"POST"` | `ssp`: GET, `yajra`: POST | `serverSide({ method })` overrides it too | | `cells` | `"text"` | `"html"` | `ssp`: text, `yajra`: html | Render mode of untyped columns | | `allowAll` | boolean | `false` | Lets a `-1` page size ("All") reach the server as `length=-1` | Extra parameters belong in [`serverSide({ params })`](/protocol/#what-every-protocol-shares) or a [filter panel](/modules/filter-panel); keep `data` for porting an existing `ajax.data` function. ## Request ### Transport | | `yajra()` / `POST` | `ssp()` / `GET` | |---|---|---| | Where | form body | query string, plus `_=` (jQuery's `cache: false`) | | `Content-Type` | `application/x-www-form-urlencoded; charset=UTF-8` | none | | `Accept` | `application/json, text/javascript, */*; q=0.01` | same | | `X-Requested-With` | `XMLHttpRequest` | same | | CSRF (`csrf: true`) | `X-CSRF-TOKEN` header and a `_token` field | `X-CSRF-TOKEN` header | A `_token` already present in the parameters is left alone. No JSON body is ever sent. ### Parameters Every request carries the full set, in this order, whatever the user did: ```text draw=1 columns[0][data]= columns[0][name]= columns[0][searchable]=false columns[0][orderable]=false columns[0][search][value]= columns[0][search][regex]=false columns[1][data]=name columns[1][name]= columns[1][searchable]=true columns[1][orderable]=true columns[1][search][value]= columns[1][search][regex]=false … order[0][column]=3 order[0][dir]=desc start=10 length=10 search[value]=leon kennedy search[regex]=false unit=R.P.D. _token=… ``` | Parameter | Value | |---|---| | `draw` | Counter starting at 1, incremented per request of this protocol instance. Sent, never trusted | | `columns[i][data]` | The column's `data` path, else its `key`. Empty for the index, select and actions columns | | `columns[i][name]` | The column's `name` option, else empty | | `columns[i][searchable]` | `true`/`false` from the column (`searchable`, default `true` for data columns) | | `columns[i][orderable]` | `true`/`false` from the column's `sortable` | | `columns[i][search][value]`, `[regex]` | A plain `grid.filters({ key: value })` on a searchable column: an anchored, escaped regex for equality (`^R\.P\.D\.$`, `regex: true`); an array becomes `^a$\|^b$`. A filter on a non-searchable column is not sent (dev notice). Otherwise empty / `false` (typed column filters use `columnControl`, below; `between` and `notIn` are not offered on this protocol) | | `order[i][column]`, `order[i][dir]` | Index into `columns[]` and `asc`/`desc`, one entry per sort key | | `start` | `(page - 1) × pageSize` | | `length` | Page size, or `-1` (see below) | | `search[value]`, `search[regex]` | The global search text; `regex` is always `false` | | page filters, `_token` | Plain top-level parameters, after the protocol's own | Rules: 1. **`columns[]` is in definition order and includes hidden columns.** Hiding a column (`visible: false`, the column menu) or reordering columns on screen never changes the indexes the server sees. A column with `can: false` does not exist at all: it is not sent. 2. **Default order.** While no sort is active the grid sends `order[0][column]=0&order[0][dir]=asc`, like DataTables' default `order: [[0, 'asc']]`. That includes clearing the sort at runtime (a header click, `grid.sort([])`, a state reset, `?sort=`), even when a `sort` option was given. Only an explicit `sort: []` option sends no `order` parameters (the server's own order). Once the user sorts, the chosen key is sent. 3. **`length=-1`** is sent when paging is off (`paging: false`), or when the user picks "All" (`-1` in `pageSizes`) and the protocol has `allowAll: true`. Without `allowAll`, "All" is clamped to `maxPageSize` (1000 by default) with the [DG013](/errors/DG013) warning. 4. **Page filters are plain parameters.** Values from `serverSide({ params })`, [`filterPanel()`](/modules/filter-panel), [`softDeletes()`](/modules/soft-deletes) (`_deleted=1`), `lazyColumns()` (`lazy[]=key` for each visible lazy column) and `grid.filters()` keys that are not column keys are appended as `name=value` (arrays as `name[]=a&name[]=b`). Your controller reads them like any request input. 5. **`data`** (the `ajax.data` port) runs last, after page filters, so it can still change `start`, `length` or `search`. 6. **DataTables 2.x and 3.x** additionally send `order[i][name]`. datagrids sends the 1.10 set; a server that reads `order[i][name]` should fall back to `columns[order[i][column]][name]`. ### Encoding The body (or query string) is identical to jQuery 3's `$.param` output: | Value | Encoded as | |---|---| | `true` / `false` | `k=true` / `k=false` | | `null`, `undefined` | `k=` | | `[]`, `{}` (empty) | nothing: the key is omitted | | `["a", "b"]` | `k[]=a&k[]=b` | | `[{ x: 1 }]` | `k[0][x]=1` | | `{ a: { b: 1 } }` | `k[a][b]=1` | | a function | called; its result is encoded | | characters | `encodeURIComponent`; in POST bodies `%20` becomes `+` | ### Typed column filters (`columnControl`) A typed filter on a column (`grid.filters({ amount: { op: "gte", value: 100 } })` or the [`columnFilters()`](/modules/column-filters) header UI) travels in that column's entry, in the DataTables ColumnControl format that yajra/laravel-datatables 12.7+ reads: ```text columns[3][columnControl][search][value]=100 columns[3][columnControl][search][logic]=greaterOrEqual columns[3][columnControl][search][type]=num ``` | `op` | Sent as | |---|---| | `eq`, `ne` | `logic=equal`, `notEqual` | | `gt`, `gte`, `lt`, `lte` | `logic=greater`, `greaterOrEqual`, `less`, `lessOrEqual` | | `contains`, `notContains`, `starts`, `ends` | same names | | `empty`, `notEmpty` | same names, empty `value` | | `in` | `columns[i][columnControl][list][]=a&…[list][]=b` | | `between`, `notIn` | not sent: ColumnControl has no equivalent | `type` is `num` for number and money columns, `date` for date columns, `text` otherwise. Filters on columns with `searchable: false` are never sent (yajra would apply them anyway). Older yajra versions ignore `columnControl`; filter with page parameters there. ## Response ```json { "draw": 1, "recordsTotal": 1000, "recordsFiltered": 941, "data": [ { "DT_RowId": "row_1993", "id": 1993, "name": "Ada Wong", "amount": 3121.74, "status_html": "Cancelled" } ], "summary": { "total": 7617927.4 } } ``` | Member | Read as | |---|---| | `data` (or `aaData`, or `dataSrc`) | The rows. Anything that is not an array becomes an empty page | | `recordsTotal` / `recordsFiltered` (or `iTotalRecords` / `iTotalDisplayRecords`) | Parsed as base-10 integers, so numeric strings work. Missing: the row count is used, and `recordsFiltered` falls back to `recordsTotal` | | `draw` | Ignored (see sequencing) | | `error` (or `sError`) | A string or `true`: the rows still render and a non-blocking error banner appears (see [Errors](#errors)) | | `DT_RowId` | The `` `id`, and the row key when the row has no `id` | | `DT_RowClass` | Classes added to the `` | | `DT_RowData`, `DT_RowAttr` | Not applied. Use the grid's `rowAttrs(row)` option | | `queries`, `input` | Deleted before anything else sees the body (Laravel debug output) | | any other top-level key | Kept: `result.meta` in the `response` event, the raw body in `grid.lastResponse()`, and bindable with [`metaBind()`](/modules/meta-bind) (`summary.total` in the demo) | ### Cells | Column | `ssp()` | `yajra()` | |---|---|---| | Untyped (`{ key: "name" }`) | text | HTML | | `column.text()` | text | text: escaped values show as `&`, so prefer untyped columns for strings | | `column.html()` | HTML | HTML | | `column.number()`, `money()`, `date()`, `badge()`, `link()` | rendered from the value | rendered from the value | | `render` returning a string | text, unless the column is `column.html()` | same | ### Sequencing `draw` can arrive as a string, be missing or come back stale from a cache. datagrids doesn't depend on it: every new request aborts the one in flight, and a response is used only if it belongs to the latest request. A slow, stale or `draw`-less response can't freeze the grid in "Processing…". ## Errors Every failure, on any protocol, becomes one `DatagridError` `{ kind, status, message, detail?, retryable }`. The grid fires the `error` event, then shows the message: as a banner above the rows when rows are already on screen, otherwise in place of the body. Server text (which may contain SQL) goes only into `detail`: the console ([DG012](/errors/DG012)) and a collapsed "Details" field while warnings are on. | Response | `kind` | Message shown | Retry | |---|---|---|---| | `200` with `error` / `sError` (string or `true`) | `server` | "The server returned an error (200)." (rows still render) | yes | | `200` with `status: "error"` and a `message` | `server` | that message | yes | | `200` whose body is not JSON | `parse` | "The server response could not be read." | no | | redirect to a non-JSON page whose URL looks like a login page | `session` | "Your session has expired. Please sign in again." | no | | redirect to any other non-JSON page | `forbidden` | "You are not allowed to view this list." | no | | `401`, `419` | `session` | "Your session has expired. Please sign in again." | no | | `403` | `forbidden` | the body's message, else "You are not allowed to view this list." | no | | `410` | `protocol` | the body's message, else the generic text | no | | `422` | `validation` | the body's message (Laravel's `message`, else the first `errors` entry) | no | | `429` | `http` | the body's message, else the generic text | yes | | other `4xx` | `http` | "The server returned an error (404)." | no | | `5xx` | `http` | "The server returned an error (500)." | yes | | network failure | `network` | "The server could not be reached. Check your connection." | yes | | no answer within `timeout` (30 s) | `timeout` | "The server took too long to respond." | yes | | aborted by a newer request | `abort` | nothing: silently dropped | — | `session` errors also fire `sessionexpired` and call `configure({ onSessionExpired })` when set. The messages come from the grid's [messages](/reference/messages) (English or Turkish, overridable). Per grid, `errorMode: "silent"` keeps the grid quiet (events still fire) and `errorMode: "throw"` rethrows. Nothing ever calls `alert()`. ## Compatibility tests The rules on this page are pinned by unit tests in [`tests/unit/server.test.ts`](https://github.com/akinozgen/datagrids/blob/main/tests/unit/server.test.ts). The encoder is compared byte for byte with the real jQuery `$.param` on a corpus of inputs. | Rule | Test | |---|---| | Encoding equals jQuery `$.param`; `+` for spaces in POST bodies | `case N`, "form body turns %20 into + like jQuery.ajax" | | Full parameter set, DataTables order, hidden columns included | "sends the full parameter set in DataTables order, hidden columns included" | | Default order while no sort is active; only an explicit `sort: []` sends none | "default order \[\[0,'asc']] only when no sort was configured; order:\[] sends nothing", "clearing at runtime keeps the default order on the wire; only an explicit sort:\[] drops it" | | `length=-1` when paging is off | "paging off → length -1" | | `data`: mutate, replace, deep merge | "ajax.data: mutate, return replacement, static deep merge" | | POST form body and `Accept`; GET cache buster | "POST form body + jQuery Accept; GET adds \_= cache buster" | | Numeric strings, ignored `draw`, extra keys | "decode: numbers normalized, draw ignored, extras in meta" | | `dataSrc` | "dataSrc string/function" | | `columnControl` and page filters | "typed column filters become columnControl, page filters plain params" | | Error table | "500 JSON: generic message, server text only in detail", "419 / 401 → session", "302 to HTML → forbidden (login → session)", "422 Laravel and RFC 9457", "403 / 410 / 429", "200 + error / status:error", "network / timeout" | ## Server checklist * Read every parameter defensively; datagrids always sends the full set, other clients may not. * Map `order[i][column]` through `columns[i][data]`/`[name]` and **whitelist** the result before it reaches SQL. * Cap `length` (and decide whether `-1` is allowed). * Answer expired sessions with `401`/`419` JSON and missing permissions with `403` JSON, not with a redirect to an HTML page. * Keep `APP_DEBUG`-style output (`queries`, `input`, exception text in `error`) off in production; datagrids hides it from users, but it still crosses the network. ## Related * [Server protocols overview](/protocol/): choosing between `ssp()`, `yajra()`, `laravelPaginator()` and `dgp()`. * [Laravel + yajra recipe](/recipes/laravel-yajra): controller and page side by side. * [CSRF and session expiry](/recipes/csrf-and-session). * [Migrating from DataTables](/migration/from-datatables). --- --- url: https://akinozgen.github.io/datagrids/protocol/laravel-paginator.md description: >- How laravelPaginator() maps Laravel's paginate(), simplePaginate(), cursorPaginate() and API resource collection JSON to a grid, and which query parameters it sends. --- # Laravel paginator: `laravelPaginator()` Point a grid at any Laravel endpoint that returns a paginator, raw or wrapped in an API resource collection. The format is detected from each response; there is nothing to configure on the server beyond reading the query parameters. ```js import { Datagrid, serverSide, laravelPaginator } from "@akinozgen17/datagrids"; new Datagrid("#agents", { label: "Agents", columns, use: [serverSide({ url: "/api/agents", protocol: laravelPaginator() })], }); ``` Switch between `paginate()` and `simplePaginate()` and watch the pager: with `simplePaginate()` the total is unknown, so the info reads "1–5 shown · total unknown" and **Last** is disabled. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, laravelPaginator } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; new Datagrid("#proto-paginator", { label: "Agents (Laravel paginator)", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], sort: [["date", "desc"]], pageSize: 5, use: [serverSide({ url: "/api/paginator/agents", protocol: laravelPaginator() })], }); ``` ```html [HTML]
``` ::: ## Options | Option | Type | Default | Description | |---|---|---|---| | `query` | `{ page?, perPage?, sort?, search?, cursor? }` | `page`, `per_page`, `sort`, `search`, `cursor` | Query parameter names | | `sortFormat` | `"-key"` | `"key:dir"` | `"-key"` | `sort=-date` or `sort=date:desc` | The method is always `GET`, cells default to text, and the shared [`serverSide()` options](/protocol/#what-every-protocol-shares) (`params`, `headers`, `csrf`, `timeout`…) apply. ## Request ```http GET /api/paginator/agents?page=2&per_page=25&sort=-date&search=kennedy&status=open HTTP/1.1 Accept: application/json X-Requested-With: XMLHttpRequest ``` | Parameter | Value | Sent when | |---|---|---| | `page` | 1-based page number | always (not in cursor mode, see below) | | `per_page` | page size | always | | `sort` | the first sort key: `date` or `-date` (`sortFormat: "key:dir"`: `date:asc` / `date:desc`) | a sort is set | | `search` | the search box text | not empty | | `cursor` | the cursor of the requested page | cursor mode, page 2 onwards | | filters, `params` | plain parameters: `status=open`, arrays as `unit[]=a&unit[]=b` | set | Rules: 1. Only the first sort key is sent; Laravel paginators have no multi-sort convention. 2. Filters from `grid.filters()` travel by value: a typed filter such as `{ op: "gte", value: 100 }` arrives as `amount=100`, without its operator; the column filter menu therefore offers only "equals" and "any of" here. Use operator-free filters (or page filters via [`filterPanel()`](/modules/filter-panel)) with this protocol, and [dgp](/protocol/v1/) when you need operators. 3. Laravel reads only `page` (and `cursor`) by itself. `per_page`, `sort`, `search` and the filters are your controller's job, as is capping `per_page`. ```php public function index(Request $request) { $sortable = ['ref', 'name', 'status', 'amount', 'date']; $sort = $request->string('sort', '-date')->toString(); $column = ltrim($sort, '-'); abort_unless(in_array($column, $sortable, true), 422, 'Unknown sort key.'); $perPage = min(max($request->integer('per_page', 25), 1), 1000); return AgentResource::collection( Agent::query() ->when($request->filled('search'), fn ($q) => $q->where('name', 'like', '%'.$request->string('search').'%')) ->when($request->filled('status'), fn ($q) => $q->where('status', $request->string('status'))) ->orderBy($column, str_starts_with($sort, '-') ? 'desc' : 'asc') ->orderBy('id') ->paginate($perPage) ); } ``` The whitelist matters: never pass `sort` to `orderBy` unchecked. ## Response mapping | Server returns | Detected by | Total | Next page | |---|---|---|---| | `->paginate()` | numeric `total` | `total` | `current_page < last_page` | | `->simplePaginate()` | no `total` | unknown | `next_page_url` | | `->cursorPaginate()` | `next_cursor` / `prev_cursor` | unknown until the last page | `next_cursor` | | Resource collection of `paginate()` | `meta.total` | `meta.total` | `meta.current_page < meta.last_page` | | Resource collection of `simplePaginate()` | `meta` without `total` | unknown | `links.next` | | Resource collection of `cursorPaginate()` | `meta.next_cursor` | unknown until the last page | `meta.next_cursor` | Rows always come from `data`. For resource collections, `result.meta` in the `response` event holds `meta` plus `links`; for raw cursor paginators it holds `path`, `per_page`, the cursors and the page URLs. The whole body stays available as `grid.lastResponse()`, so extra keys added with `->additional([...])` can be bound with [`metaBind()`](/modules/meta-bind). With an unknown total the grid uses the "total unknown" pager: "1–25 shown · total unknown", **Next** while there is a next page, **Last** disabled. ## Cursor pagination `cursorPaginate()` pages by position (a keyset), not by page number, so it stays fast on large tables and never skips or repeats rows while data changes. The grid keeps the familiar page numbers on top: 1. The first request carries no cursor. Each response's `next_cursor` is remembered as the cursor of the following page, so page N+1 is requested as `?cursor=…` instead of `?page=N+1`. 2. Pages are reached in order. A jump past the furthest page seen so far (typing 50 in the page field) lands on that furthest page. 3. When the last page has been seen, the row count is known: the pager shows it and enables **Last**. 4. Changing the sort, search, filters or page size starts again from page 1. Cursors are kept per query, so going back to an earlier query reuses its cursors. The order must be unique for cursor pagination, so end it with `->orderBy('id')`. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, laravelPaginator } from "@akinozgen17/datagrids"; new Datagrid("#proto-cursor", { label: "Agents (cursorPaginate)", columns: [ column.text("ref", { title: "Ref" }), column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.date("date", { title: "Date", time: true }), ], sort: [["date", "desc"]], pageSize: 5, use: [serverSide({ url: "/api/cursor/agents", protocol: laravelPaginator() })], }); ``` ```html [HTML]
``` ::: ## Errors Laravel's usual responses map like on every protocol: `419`/`401` fire `sessionexpired`, `422` shows the validation `message`, `5xx` shows a generic text with Retry. See the [error table](/protocol/ssp#errors). ## Related * [Server protocols overview](/protocol/) * [Laravel paginator recipe](/recipes/laravel-paginator) * [datagrids protocol v1](/protocol/v1/): typed filters, multi-key sort and optional counting. --- --- url: https://akinozgen.github.io/datagrids/protocol/v1.md description: >- Normative specification of the datagrids protocol (dgp) v1, a JSON protocol for paged, sorted and filtered lists with typed filters, optional counting and RFC 9457 errors. --- # datagrids protocol v1 The datagrids protocol (dgp) is a small JSON protocol between a list UI and a server: the client asks for one page of rows with a sort, a search text and typed filters; the server answers with the rows, paging facts, optional counts and aggregates. It is what [`dgp()`](/guide/server-protocols) speaks. | Property | Value | |---|---| | Spec version | 1.0 (2026-10-27) | | Status | Stable. Changes within v1 are additions only | | JSON Schema (draft 2020-12) | [request.schema.json](/protocol/v1/request.schema.json) · [response.schema.json](/protocol/v1/response.schema.json) · [error.schema.json](/protocol/v1/error.schema.json) | | Client | `serverSide({ url, protocol: dgp() })` | Try it: change the sort, search, open a column filter (the funnel icon in a header), switch the count mode, simulate an error, and read the **Request** and **Response** tabs. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, dgp, columnFilters, metaBind } from "@akinozgen17/datagrids"; import { statusLabels, statusTones } from "./data.js"; const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }); new Datagrid("#proto-dgp", { label: "Agents (datagrids protocol v1)", columns: [ column.text("name", { title: "Name" }), column.text("unit", { title: "Unit" }), column.badge("status", { title: "Status", labels: statusLabels, tones: statusTones }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("date", { title: "Date" }), ], sort: [["amount", "desc"]], pageSize: 5, use: [ serverSide({ url: "/api/dgp/agents", protocol: dgp({ count: "exact" }), csrf: true }), columnFilters(), // typed filters → filters: { key: { op, value } } metaBind({ "#proto-dgp-sum": { value: "meta.aggregates.amount.sum", format: (v) => usd.format(v) } }), ], }); ``` ```html [HTML]
Amount (all matching rows)—
``` ::: ## 1. Overview and versioning The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED, MAY and OPTIONAL are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174) when, and only when, they appear in all capitals. Terms: * **Client**: the code that builds requests and renders rows (for example a datagrids grid). * **Server**: the endpoint that answers them. * **Field**: a named value of a row (`name`, `amount`). Sort keys, filter keys and `fields` entries are field keys. * **Schema**: the server's own list of fields it exposes, with their types and which of them are sortable, searchable and filterable. The schema lives on the server; the protocol never sends column definitions, SQL expressions or indexes. Versioning: 1. Every request body MUST contain `"v": 1`. Every successful response body MUST contain `"v": 1`. 2. A server that receives a `v` it does not support MUST answer `400` with `code: "unsupported_version"`. 3. The spec version is independent of the datagrids library version. A library release states which protocol versions it speaks; this one speaks v1. 4. Within v1 the spec only grows: new OPTIONAL members, new error codes, new warning codes. A change that would make a conforming v1 peer fail is a new major version (`"v": 2`, a new `/protocol/v2/` page). 5. Both sides MUST ignore members they do not know, in every object. The JSON Schemas allow additional properties for this reason. ## 2. Transport ### 2.1 POST JSON (default) * The client sends `POST ` with `Content-Type: application/json` and a [request](#_3-request) body. * The client SHOULD send `Accept: application/json, application/problem+json`. * A successful answer is `200` with `Content-Type: application/json` and a [response](#_4-response) body. * An error is a 4xx/5xx status with `Content-Type: application/problem+json` and an [error](#_5-errors) body. * When the endpoint authenticates with cookies, the server SHOULD require a CSRF token header (`X-CSRF-TOKEN` in Laravel). The reference client sends it with `csrf: true`, together with `X-Requested-With: XMLHttpRequest`. ### 2.2 GET form (optional) A server MAY also accept the same request as query parameters (`dgp({ method: "GET" })`), which makes responses cacheable and links shareable. The mapping is flat: | Request member | Query parameter | Example | |---|---|---| | `page.size`, `page.number` | `page[size]`, `page[number]` | `page[size]=25&page[number]=2` | | `sort` | `sort`: comma list, `-` prefix = descending | `sort=-amount,name` | | `q` | `q` | `q=kennedy` | | `fields` | `fields`: comma list | `fields=name,unit,amount` | | `count` | `count` | `count=none` | | `filters.` | `filter[][]=`; list values comma-joined | `filter[status][in]=open,pending` | | `params.` | `` (top level) | `_deleted=1` | * Parameters are form-encoded (brackets and commas percent-encoded on the wire). `v` and `requestId` are not sent in the GET form; the endpoint path implies v1. * All values arrive as strings. The server coerces them by the field's type in its schema. * List values MUST NOT contain commas in the GET form. A client that needs them MUST use POST. * `empty` and `notEmpty` carry an empty value: `filter[deleted_at][empty]=`. ## 3. Request ```json { "v": 1, "page": { "size": 25, "number": 1 }, "sort": [{ "key": "amount", "dir": "desc" }], "q": "kennedy", "filters": { "status": { "op": "in", "value": ["open", "pending"] } }, "fields": ["name", "unit", "status", "amount", "date"], "count": "exact", "requestId": "r-12", "params": { "_deleted": 1 } } ``` | Member | Type | Required | Meaning | |---|---|---|---| | `v` | `1` | REQUIRED | Protocol major version | | `page` | `{ size, number }` | REQUIRED | `size`: integer ≥ 1. `number`: 1-based integer ≥ 1 | | `sort` | `[{ key, dir }]` | OPTIONAL | Sort keys in priority order; `dir` is `asc` or `desc`. Missing or empty: the server's default order. See [Sorting](#_7-sorting) | | `q` | string | OPTIONAL | Global search text. The client omits it when empty | | `filters` | `{ : { op, value } }` | OPTIONAL | Typed filters, combined with AND. See [Filtering](#_8-filtering) | | `fields` | string\[] | OPTIONAL | The fields the client renders. Missing: the server's default field set | | `count` | `exact` | `estimate` | `none` | OPTIONAL | Counting the client asks for; missing means `exact`. See [Counting](#_6-counting) | | `requestId` | string | OPTIONAL | Correlation id for logs. The server MAY echo it | | `params` | object | OPTIONAL | Page-specific parameters that are not typed filters. Their meaning is server-defined | Rules: 1. Servers MUST accept a request in which every OPTIONAL member is missing. 2. Servers MUST enforce a maximum page size. When `page.size` exceeds it, the server MUST either answer `422` with `code: "page_size_exceeded"`, or clamp the size, report the size it used in the response's `page.size` and add a `page_size_clamped` warning. A maximum of 1000 matches the reference client's default `maxPageSize`. 3. `fields` entries the server does not know SHOULD be ignored (and MAY be reported as a warning). `fields` never widens what the server exposes: see [Response](#_4-response) rule 3. 4. A `page.number` past the last page is not an error: the server answers `200` with an empty `rows` array and `hasMore: false`. What the reference client puts where: | Grid input | Request member | |---|---| | `grid.page()`, `grid.pageSize()` | `page.number`, `page.size` | | `sort` option, header clicks, `grid.sort()` | `sort` (column keys) | | The search box, `grid.search()` | `q` | | `grid.filters({ status: "open" })` | `filters.status = { op: "eq", value: "open" }` | | `grid.filters({ unit: ["R.P.D.", "U.B.C.S."] })` | `filters.unit = { op: "in", value: [...] }` | | `grid.filters({ amount: { op: "gte", value: 100 } })`, `columnFilters()` | `filters.amount` as given | | Columns (except index, select and actions columns) | `fields`: each column's `data` path, else its key | | `dgp({ count })` | `count` (default `exact`) | | `serverSide({ params })`, `filterPanel()`, `softDeletes()`, `lazyColumns()` | `params` (e.g. `params._deleted`, `params.lazy`) | | `csrf: true` | `X-CSRF-TOKEN` header, and `_token` in `params` | Function filters (`grid.filters({ key: (value, row) => … })`) are client-only and never sent. Filters set to `null`, `""` or `[]` are removed and never sent. ### 3.1 Export requests (informative) An export of "all matching rows" (`grid.exportRows("all")`, `excel({ scope: "all" })`) sends the same request with `page: { size: , number: 1 }` (1000 by default). Servers SHOULD allow that size. Larger exports belong to a separate endpoint: the page posts `grid.query()` there and the server runs the same query in a job. ## 4. Response ```json { "v": 1, "rows": [ { "id": "1737", "name": "Cindy Lennox", "status": "pending", "amount": 19991.51 } ], "page": { "size": 25, "number": 1, "hasMore": true }, "count": { "mode": "exact", "total": 1000, "filtered": 375 }, "meta": { "aggregates": { "amount": { "sum": 3094860.95 } }, "facets": {}, "warnings": [] } } ``` | Member | Type | Required | Meaning | |---|---|---|---| | `v` | `1` | REQUIRED | Protocol major version | | `rows` | object\[] | REQUIRED | The page, in the requested order. May be empty | | `page` | `{ size, number, hasMore }` | REQUIRED | The page actually returned. `hasMore` is `true` when a next page exists | | `count` | `{ mode, total?, filtered? }` | REQUIRED | See [Counting](#_6-counting) | | `meta` | `{ aggregates?, facets?, warnings? }` | OPTIONAL | Side data, see below | | `requestId` | string | OPTIONAL | Echo of the request's `requestId` | Rules: 1. Every row MUST have an `id` (string or integer) that is unique within the result and stable across requests. Clients compare ids as strings. Selection, row actions and row refreshes depend on it. 2. Values are typed data, not presentation: numbers as JSON numbers (or decimal strings such as `"1234.50"` when precision matters), dates and times as ISO 8601 strings with an offset (`"2026-09-01T10:00:00+03:00"`), booleans as `true`/`false`, missing values as `null`. Servers SHOULD NOT send HTML. Clients render cells as text unless a column opts in to HTML. 3. A row MUST NOT contain fields outside the server's schema. A server SHOULD return exactly the requested `fields` it knows, plus `id`. Never serialize whole models: what is not in the schema never leaves the server. 4. `meta.aggregates` holds raw numbers over every filtered row (not just the page), by field key and function: `{ "amount": { "sum": 3094860.95, "avg": 8252.96 } }`. Well-known functions: `sum`, `avg`, `min`, `max`, `count`. 5. `meta.facets` holds filter options by field key: `{ "unit": [{ "value": "rpd", "label": "R.P.D.", "count": 12 }] }`. 6. `meta.warnings` holds non-fatal notes as `{ code, message? }` objects, e.g. `{ "code": "page_size_clamped", "message": "Page size limited to 500." }`. The reference client exposes the whole body as `grid.lastResponse()` and in the `response` event (`result.meta` carries `meta` plus `countMode`), so [`metaBind()`](/modules/meta-bind) can write `meta.aggregates.amount.sum` into the page, as the demo above does. ## 5. Errors Every error is a [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details object, sent with the matching HTTP status and `Content-Type: application/problem+json`. ```json { "type": "about:blank", "title": "Invalid filter", "status": 422, "code": "validation_failed", "retryable": false, "errors": { "filters.date": ["The date range is invalid."] } } ``` | Member | Type | Required | Meaning | |---|---|---|---| | `type` | URI reference | OPTIONAL | Problem type; `about:blank` when omitted | | `title` | string | REQUIRED | Short summary, safe to show to end users | | `status` | integer | REQUIRED | Same as the HTTP status | | `detail` | string | OPTIONAL | Occurrence-specific diagnostics. Clients MUST NOT show it to end users | | `instance` | URI reference | OPTIONAL | Identifies this occurrence (e.g. a log reference) | | `code` | string | REQUIRED | Machine-readable, `snake_case` (extension member) | | `retryable` | boolean | RECOMMENDED | Whether repeating the same request may succeed (extension member) | | `errors` | `{ : string[] }` | OPTIONAL | Validation messages by request path: `filters.date`, `sort.0.key`, `page.size` (extension member) | Server rules: 1. Use the right status. Never answer an API request with a `302` redirect to an HTML login or "forbidden" page: answer `401` (or `419` for an expired CSRF session) or `403` with a problem body. 2. Never put stack traces, SQL or personal data in `title`. Prefer to keep them out of `detail` too. 3. Validation failures (unknown sort key, unsupported operator, malformed value, page too large) are `422` with `errors` keyed by request path. Recommended codes: | Status | `code` | `retryable` | |---|---|---| | 400 | `invalid_request`, `unsupported_version` | `false` | | 401 / 419 | `session_expired` | `false` | | 403 | `forbidden` | `false` | | 422 | `validation_failed`, `unknown_sort_key`, `unknown_filter`, `unsupported_filter`, `page_size_exceeded` | `false` | | 429 | `rate_limited` (with `Retry-After`) | `true` | | 500 | `server_error` | `true` | | 503 | `unavailable` | `true` | How the reference client handles them (the same normalization applies to every protocol, see [SSP → Errors](/protocol/ssp#errors)): | Response | Error `kind` | Shown message | Retry button | |---|---|---|---| | `401`, `419` | `session` (+ `sessionexpired` event) | "Your session has expired…" | no | | `302` to a non-JSON page | `session` if the URL looks like a login page, else `forbidden` | session / "You are not allowed…" | no | | `403` | `forbidden` | problem message, else "You are not allowed…" | no | | `422` | `validation` | problem message | no | | `410` | `protocol` | problem message | no | | `429` | `http` | problem message | yes | | other 4xx | `http` | "The server returned an error (404)." | no | | 5xx | `http` | "The server returned an error (500)." (server text only in `error.detail`) | yes | | `200` with a body that is not JSON | `parse` | "The server response could not be read." | no | | network failure, timeout | `network`, `timeout` | connection / timeout text | yes | "Problem message" is `title` when the problem also has a `detail`, otherwise the first message in `errors`, otherwise the generic text. The reference client decides retries from the status; it does not read `retryable` or `code` yet. If the grid already shows rows, the error appears as a banner above them; otherwise it replaces the body. ## 6. Counting Counting a filtered result can cost more than fetching the page. The client says what it needs; the server says what it did. | `count.mode` | `total` | `filtered` | Meaning | |---|---|---|---| | `exact` | OPTIONAL | REQUIRED | Exact numbers. `filtered`: rows matching `q` and `filters`. `total`: rows before them | | `estimate` | OPTIONAL | REQUIRED | Approximations (e.g. from the query planner) | | `none` | absent | absent | Not counted | 1. The server MAY answer with a cheaper mode than requested (`exact` → `estimate` → `none`), never a more expensive one it was not asked for. `count.mode` MUST state what was done. 2. Clients MUST read `count.mode` from the response, not assume the requested one. 3. `page.hasMore` MUST be accurate in every mode. Without counts it is the only paging signal. Servers usually fetch `size + 1` rows to know it. 4. `total` and `filtered` are integers ≥ 0. Omit `total` when it costs an extra query you don't want. How the reference client shows each mode: | Mode | Info text | Pager | |---|---|---| | `exact` | "1–25 / 375 records (total 1,000)" | page field "of N", Last enabled | | `estimate` | same as `exact` (numbers are not marked as approximate yet) | same as `exact` | | `none` | "1–25 shown · total unknown" | Next while `hasMore`, Last disabled | Switch **count: none** in the demo above to see the third row. ## 7. Sorting 1. `sort` is an ordered list; the first entry has the highest priority. 2. `key` is a field key from the server's schema, never a column index or an SQL expression. 3. The server MUST reject keys that are unknown or not sortable with `422` (`code: "unknown_sort_key"`, `errors["sort..key"]`). Never splice a key into SQL unchecked. 4. The server MUST produce a deterministic order and SHOULD append a unique tiebreaker (usually `id`) so rows don't move between pages. 5. A missing or empty `sort` means the server's default order (which also MUST be deterministic). 6. Where nulls sort is server-defined but MUST be consistent. The reference client sends one key when a user clicks a header; a `sort` option with several entries (`sort: [["unit", "asc"], ["amount", "desc"]]`) sends them all. ## 8. Filtering `filters` maps a field key to one filter object `{ op, value }`. All filters MUST match (AND); v1 has no OR groups and no nesting. `in` and `notIn` express "any of" within one field. `q` and `filters` combine with AND. | `op` | `value` | Matches rows whose field… | |---|---|---| | `eq` | scalar | equals the value | | `ne` | scalar | does not equal the value (empty fields match) | | `gt` / `gte` | number or date string | is greater than / at least the value | | `lt` / `lte` | number or date string | is less than / at most the value | | `between` | `[min, max]` | lies in the closed range `min ≤ field ≤ max` | | `in` | non-empty array of scalars | equals any of the values | | `notIn` | non-empty array of scalars | equals none of the values (empty fields match) | | `contains` | string | contains the text | | `notContains` | string | does not contain the text (empty fields match) | | `starts` | string | starts with the text | | `ends` | string | ends with the text | | `empty` | none | is `null` or `""` | | `notEmpty` | none | is neither `null` nor `""` | Rules: 1. Scalars are strings, numbers or booleans. Dates are ISO 8601 strings: a date (`2026-09-01`) or a date-time with an offset. 2. Text operators (`contains`, `notContains`, `starts`, `ends`) SHOULD be case-insensitive and SHOULD ignore diacritics, so `isik` finds `Işık`. `eq` compares exactly after coercion to the field's type. 3. Negative operators (`ne`, `notIn`, `notContains`) MUST include rows whose field is empty. In SQL that means adding `OR field IS NULL`. 4. Comparison operators (`gt`, `gte`, `lt`, `lte`, `between`) never match an empty field. 5. A date-only value compared with a date-time field SHOULD cover the whole day in the server's business time zone: `eq 2026-09-01` matches that day, `between ["2026-09-01", "2026-09-30"]` includes all of September 30. 6. `empty` and `notEmpty` take no value; servers MUST ignore one if present. 7. The server MUST validate every filter against its schema: an unknown key is `422` with `code: "unknown_filter"`, an operator the field doesn't support or a malformed value is `422` with `code: "unsupported_filter"` or `"validation_failed"`, with `errors["filters."]`. 8. `q` is matched against server-chosen fields. It SHOULD follow rule 2 and MAY require a minimum length. [`columnFilters()`](/modules/column-filters) offers these operators per column type: text columns `contains`, `notContains`, `starts`, `ends`, `eq`, `ne`, `empty`, `notEmpty`; number and money columns `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `between`, `empty`, `notEmpty`; dates `eq`, `gt`, `lt`, `between`, `empty`, `notEmpty`; badges `in`, `notIn`. ## 9. Conformance A **conforming client**: * \[ ] sends `v: 1` and a `page` with `size ≥ 1` and a 1-based `number`; * \[ ] sorts by field key and filters with the operators of [§8](#_8-filtering) only; * \[ ] omits empty filters and never sends client-only predicates; * \[ ] ignores unknown members in responses and errors; * \[ ] reads `count.mode` and `page.hasMore` from the response and pages without counts when needed; * \[ ] matches each response to the latest request it sent (abort or sequence numbers), not to `requestId`; * \[ ] renders values as text unless a column explicitly opts in to HTML; * \[ ] shows `title`/`errors` messages to users and keeps `detail` for developers; * \[ ] sends a CSRF header when the endpoint authenticates with cookies. A **conforming server**: * \[ ] accepts `POST` with a JSON body (the GET form is optional); * \[ ] answers `400 unsupported_version` for any `v` other than `1`; * \[ ] ignores unknown request members and accepts requests without the OPTIONAL ones; * \[ ] whitelists sort keys, filter keys, operators and fields against its schema (`422` otherwise); * \[ ] enforces a maximum page size (`422` or clamp + warning); * \[ ] returns a stable, unique `id` on every row and no field outside its schema; * \[ ] orders deterministically, with a unique tiebreaker; * \[ ] returns accurate `page.hasMore` and states `count.mode` truthfully; * \[ ] answers past-the-end pages with `200` and empty `rows`; * \[ ] reports errors as `application/problem+json` with the right status, never as a redirect to HTML; * \[ ] keeps SQL, stack traces and personal data out of `title`. ## 10. Examples The examples below come from the in-page demo server that also backs the demo at the top. Rows are shortened where marked. Each body validates against the JSON Schemas. ### 10.1 First page, exact count Request: ```http POST /api/dgp/agents HTTP/1.1 Content-Type: application/json Accept: application/json, application/problem+json X-Requested-With: XMLHttpRequest ``` ```json { "v": 1, "page": { "size": 3, "number": 1 }, "sort": [{ "key": "amount", "dir": "desc" }], "filters": { "status": { "op": "in", "value": ["open", "pending"] } }, "fields": ["name", "unit", "status", "amount", "date"], "count": "exact", "requestId": "r-1" } ``` Response (`200`, `application/json`): ```json { "v": 1, "rows": [ { "id": "1737", "name": "Cindy Lennox", "unit": "U.B.C.S.", "status": "pending", "amount": 19991.51, "date": "2026-06-16T21:40:00.000Z" }, { "id": "1911", "name": "Sheva Alomar", "unit": "S.T.A.R.S. Bravo", "status": "pending", "amount": 19849.61, "date": "2026-08-02T02:40:00.000Z" }, { "id": "1342", "name": "Ethan Winters", "unit": "S.T.A.R.S. Bravo", "status": "open", "amount": 19753.5, "date": "2025-10-07T13:40:00.000Z" } ], "page": { "size": 3, "number": 1, "hasMore": true }, "count": { "mode": "exact", "total": 1000, "filtered": 375 }, "meta": { "aggregates": { "amount": { "sum": 3094860.95 } }, "facets": {}, "warnings": [] } } ``` ### 10.2 Search, range filter, no count Request: ```json { "v": 1, "page": { "size": 2, "number": 4 }, "sort": [{ "key": "date", "dir": "desc" }], "q": "kennedy", "filters": { "amount": { "op": "between", "value": [1000, 20000] } }, "fields": ["name", "amount", "date"], "count": "none", "requestId": "r-7" } ``` Response: ```json { "v": 1, "rows": [ { "id": "1686", "name": "Leon S. Kennedy", "amount": 17456.45, "date": "2026-06-30T15:40:00.000Z" }, { "id": "1878", "name": "Leon S. Kennedy", "amount": 6111.1, "date": "2026-06-26T09:40:00.000Z" } ], "page": { "size": 2, "number": 4, "hasMore": true }, "count": { "mode": "none" }, "meta": { "aggregates": { "amount": { "sum": 422607.33 } }, "facets": {}, "warnings": [] } } ``` ### 10.3 The same as 10.1, GET form ```http GET /api/dgp/agents?page%5Bsize%5D=3&page%5Bnumber%5D=1&sort=-amount&fields=name%2Cunit%2Cstatus%2Camount%2Cdate&count=exact&filter%5Bstatus%5D%5Bin%5D=open%2Cpending HTTP/1.1 Accept: application/json, application/problem+json ``` Decoded: `page[size]=3 & page[number]=1 & sort=-amount & fields=name,unit,status,amount,date & count=exact & filter[status][in]=open,pending`. The response is the same as in 10.1. ### 10.4 Validation error ```http HTTP/1.1 422 Unprocessable Content Content-Type: application/problem+json ``` ```json { "type": "about:blank", "title": "Invalid filter", "status": 422, "code": "validation_failed", "retryable": false, "errors": { "filters.date": ["The date range is invalid."] } } ``` The grid shows "The date range is invalid." without a Retry button. ### 10.5 Server error ```http HTTP/1.1 500 Internal Server Error Content-Type: application/problem+json ``` ```json { "type": "about:blank", "title": "Server error", "status": 500, "detail": "SQLSTATE[42S22]: Column not found: 'unitt'", "code": "server_error", "retryable": true } ``` The grid shows "The server returned an error (500)." with Retry. The `detail` text reaches only the developer console (and a collapsed "Details" field while warnings are on), which is why it must never be needed by end users. ## 11. Changelog | Version | Date | Changes | |---|---|---| | 1.0 | 2026-10-27 | First release: request, response, errors (RFC 9457), counting, sorting, 15 filter operators, GET form, JSON Schemas | ## Related * [Server protocols overview](/protocol/): when to choose dgp over the SSP wire or Laravel's paginator. * [Data sources](/guide/data-sources) and [Server protocols guide](/guide/server-protocols): attaching `serverSide({ protocol: dgp() })`. * [columnFilters](/modules/column-filters): the header filter UI that produces typed filters. * [States and errors](/guide/states-and-errors): how errors look in the grid. --- --- url: https://akinozgen.github.io/datagrids/migration.md description: >- Guides for moving existing tables from other grid libraries to datagrids, one page at a time. --- # Migration | Coming from | Guide | Covers | |---|---|---| | DataTables | [Migrating from DataTables](/migration/from-datatables) | 1.10, 2.x and 3.x (plus legacy 1.9 names): options, events, API calls, server endpoints | Whatever you migrate from, the approach is the same: 1. **Keep the server.** datagrids speaks the DataTables server-side protocol, Laravel paginator JSON and its own protocol, so endpoints don't have to change first. See [Server protocols](/protocol/). 2. **Move one page at a time.** datagrids has no global state that clashes with other grid libraries, so old and new grids can live on the same page while you migrate. 3. **Turn repeated configuration into a preset.** The options most pages copy (data source, column menu, export, saved state) become one array you put in `use`. See [Concepts → Modules](/guide/concepts#modules). --- --- url: https://akinozgen.github.io/datagrids/migration/from-datatables.md description: >- Map DataTables 1.10, 2.x and 3.x options, events and API calls to datagrids, keep your server endpoints, and migrate one page at a time. --- # Migrating from DataTables This guide covers DataTables 1.10, 2.x and 3.x. Legacy 1.9-style (Hungarian) names are listed in the [appendix](#appendix-legacy-1-9-names). The short version: your server endpoints stay as they are, each DataTables option becomes a grid option, a column option or a module, and pages move over one at a time. ## Why migrate (and what you give up) DataTables 3 no longer needs jQuery, so "drop jQuery" is not a reason on its own. These are: * **You gain:** * A small core plus modules you import only where you use them; nothing global to configure first. * Styling the host page can't deform: component-scoped `--dg-*` tokens, a low-specificity reset, states as attributes. One `--dg-accent` rebrands it. * Accessible defaults: a native ``, real `` | Nothing to do | The DOM source is automatic; see [Data sources](/guide/data-sources#dom-progressive-enhancement) | | `deferLoading` with a server-rendered first page (removed in 2.0, back in 2.1) | `serverSide({ seed })` | `seed` is the first response body, rendered without a request | | `deferLoading` to wait for the user | `load: "manual"` | Or `load: "visible"`: loads when scrolled into view | | `processing: true` | Built in | Loading state with `aria-busy` | | `rowId` | `rowKey` | Default: `id`, then `DT_RowId` | ### Layout, buttons and paging | DataTables | datagrids | Notes | |---|---|---| | `dom: '…'`2.x+: `layout: {…}` (`dom` deprecated) | Toolbar slots | No layout strings; see [custom toolbar](/recipes/custom-toolbar) | | `buttons: ['colvis']` | `colVis()` | | | `buttons: ['excel']` / `'excelHtml5'` | `excel({ filename })` | No JSZip. Numbers and dates come from typed columns and `exportValue` | | `buttons: ['csv']` / `'csvHtml5'` | `csv()` | | | `buttons: ['print']` | `print()` | | | `buttons: ['pdf']` / `'pdfHtml5'` | — | `print()` and the browser's "Save as PDF" | | `buttons: ['copy']` | — | Not in v1 | | `{ text, action }` button | `button.custom({ label, onClick })` | `disabled(raw)` derives the state from the last response | | `{ extend: 'collection', buttons }` | `button.group({ label, items })` | | | A "reload" button | `button.reload()` | | | `pageLength` | `pageSize` | Default 25 | | `lengthMenu` | `pageSizes` | Default `[10, 25, 50, 100]` | | `-1` in `lengthMenu` ("All") | `-1` in `pageSizes` + `yajra({ allowAll: true })` | Without `allowAll` "All" is capped at `maxPageSize` (1000) | | `paging: false` | `paging: false` | | | `info`, `lengthChange` | — | The info text and page-size menu are part of the pager | | `pagingType` | — | One pager: first/last, page field, native select on narrow screens | | `scrollX` | Built in | The pager stays outside the horizontal scroll area | | `scrollY` | `maxHeight: "60vh"` | Bounded body with a sticky header | | `fixedHeader` | `stickyHeader()`, or `maxHeight` | `stickyHeader()` keeps a header copy at the top of the page; with `maxHeight` the body scrolls under a CSS-sticky header | | `fixedColumns: { leftColumns: 1 }`2.x+: `fixedColumns: { start: 1 }` | `sticky: "start"` on that column | One column per side (`"start"` / `"end"`) | | `deferRender` (the default in 2.x+), Scroller | Built in | Pages of 300+ rows switch to virtual rows (`virtual` option) | ### Sorting, searching and columns | DataTables | datagrids | Notes | |---|---|---| | `order: [[3, 'desc']]`2.x+: also `[{ name, dir }]` | `sort: [["amount", "desc"]]` | By column key, not index | | `order: []` | `sort: []` | Keeps the server's order. Otherwise, while no sort is active (no `sort` option, or the sort cleared at runtime), the SSP wire sends DataTables' default `[[0, 'asc']]` | | `ordering: false` | `sortable: false` on each column | No grid-level switch | | `searching: false` | `search: false` | | | `searchDelay` | `search: { delay }` | Default 400 ms on server grids, 200 ms in the browser | | `columns[].data` | the column `key` | Plus `data: "unit.name"` for a dotted path | | `columns[].name` | `name` | Sent as `columns[i][name]` | | `columns[].title`, `visible`, `searchable`, `className` | same names | | | `columns[].orderable` (1.10 also accepts `sortable`) | `sortable` | | | `columns[].width`, `autoWidth` | CSS | No inline widths; headers realign with a ResizeObserver | | `columns[].defaultContent` | `defaultContent` | Text | | `columns[].render(data, type, row, meta)` | `render(value, row, ctx)` | Return a string or a Node. Cells are text by default; HTML is an explicit opt-in (`column.html()`) | | `render` branching on `type === 'export'` / `'sort'`, `orthogonal` | `exportValue(row)`, `value(row)`, `compare` | | | `$.fn.dataTable.render.text()`2.x+: `DataTable.render.text()` | Default behavior | | | `$.fn.dataTable.render.number(…)`2.x+: `DataTable.render.number(…)` | `column.number()`, `column.money()` | Formatted, right-aligned, exported as numbers. Data strings are read as machine numbers (`"1.500"` = 1.5); use `source: "tr"` for Turkish-formatted text (`"1.500"` = 1500), and `source: "html"` on `money()` for server-rendered HTML | | `columns[].type` | Typed factories | `column.date()`, `column.badge()`, `column.link()`, `column.phone()`… | | — | `lazy: true` on a column + `lazyColumns()` | Costly server columns are requested only while visible (`lazy[]=key`) | | `columnDefs` | Options on each column | | | `columns[].orderData` | `sortKey` | Browser sorting; on server grids the server decides | | `columns[].createdCell` | `render(value, row, ctx)` | `ctx.td` is the cell | | `data: null` + `defaultContent: '` | `footer({ cols: { amount: "sum" } })` | | | `language` | `messages`, `locale` | English and Turkish bundled; [messages](/reference/messages) | | `language.url` | — | No remote language files | ### Extensions and instance options | DataTables | datagrids | Notes | |---|---|---| | `stateSave: true` | `stateSave()` | Sort, page size, visible columns (and column order with `colReorder()`) | | `stateSaveParams`, `stateLoadParams` | `stateSave({ include })` | Search and page are not saved by default; `include: ["search", "filters", "page"]` opts in | | `stateDuration` (seconds; `-1` = session) | `stateSave({ ttl })` (milliseconds) / `stateSave({ storage: sessionStorage })` | Default 90 days. A changed column set drops the saved state | | Select extension | `column.select()` + `selection()` | Selection survives paging; "select all matching" | | `colReorder` | `colReorder()` | Display order only; requests keep the definition order | | `responsive` | `responsive()` | Collapsed columns move to a detail row | | ColumnControl extension (2.3+) | `columnFilters()` | Sends ColumnControl's wire format to yajra | | `rowReorder` | `rowReorder({ onEnd })` + `reorderColumn()` | Drag or keyboard; `onEnd` saves the order, a rejection reverts it | | `keys` (KeyTable) | `keyboardGrid()` | APG grid navigation: one tab stop, arrow keys between cells | | Saved search presets (SearchBuilder / StateRestore style) | `filterPresets({ presets })` | Named filter sets in the toolbar | | `setInterval(() => table.ajax.reload(null, false), …)` | `autoRefresh({ every })` | Silent reload that keeps the page; pauses while the tab is hidden or the user is busy | | `rowGroup`, `searchPanes`, `searchBuilder`, child rows | — | Not in v1 | | `orderCellsTop` with a filter row | — | Not in v1; use `columnFilters()` | | `destroy: true` | `Datagrid.get(el)?.destroy()` before creating, or `grid.remount()` | | | `retrieve: true` | `Datagrid.get(el)` | | | `$.fn.dataTable.defaults`2.x+: `DataTable.defaults` | `configure({ … })` + presets | `configure()` affects grids created afterwards | ## Event mapping `grid.on(name, fn)` returns an unsubscribe function (there is no `off`). Every event is also dispatched on the grid root as a DOM event named `dg:`. | DataTables (1.10 / 2.x / 3.x) | datagrids | Notes | |---|---|---| | `init.dt` | `init` | After setup, before data. Data arrives with `load` | | `preXhr.dt` | `beforeLoad` | Cancelable (`e.cancel()`); `e.query` is the neutral query. Change parameters with `params` | | `xhr.dt` | `response` | `{ raw, result }`; `raw` is the JSON body | | `draw.dt` | `render` | `{ keys, rows }` of the rendered page | | `processing.dt` | `loadingchange` | `{ loading }` | | `page.dt` | `page` | `beforePage` is cancelable | | `length.dt` | `pagesize` | | | `order.dt` | `sort` | `beforeSort` is cancelable | | `search.dt` | `search` | | | `column-visibility.dt`, `column-reorder.dt` | `columnchange` | `{ columns }` in display order | | `responsive-resize.dt` | `collapse` | From `responsive()` | | `stateSaveParams.dt`, `stateLoadParams.dt`, `stateLoaded.dt` | — | `stateSave({ include })`; read with `grid.state.read()` | | `error.dt` (1.10), `dt-error.dt` (2.x+) | `error` | `{ error }`: kind, status, message, retryable | | — | `sessionexpired` | 401, 419, or a redirect to a login page | | `destroy.dt` | `destroy` | | | `select.dt`, `deselect.dt` | `selectionchange` | `{ count, keys, all }` | | `pre-row-reorder.dt` / `row-reorder.dt` | `beforeReorder` (cancelable) / `reorder`, `reordererror` | rowReorder module | ## API mapping | DataTables | datagrids | Notes | |---|---|---| | `$('#t').DataTable()`2.x+: also `new DataTable('#t')` | `Datagrid.get('#t')` | Returns `null` when there is no grid. DataTables creates one in that case | | `isDataTable(el)` on `$.fn.dataTable`2.x+: on `DataTable` | `Datagrid.get(el) !== null` | | | A table in another tab or module | `find("agents")`, `reload("agents")` | By the grid's `name` | | `.ajax.reload()` | `grid.reload()` | Returns a Promise | | `.ajax.reload(null, false)` | `grid.reload({ keepPage: true })` | `silent: true` skips the busy overlay | | `.ajax.url(u).load()` | `serverSide({ url: (query) => … })` | The URL function runs per request | | `.ajax.json()` | `grid.lastResponse()` | | | `.ajax.params()` | `grid.lastRequestParams()`, `grid.query()` | `lastRequestParams()`: the page parameters actually sent for the rows on screen (`_token` excluded). `query()`: the neutral query (page, sort, search, filters), not the encoded wire | | `.draw()` | Not needed | State changes re-render the affected region | | `.search(v).draw()` | `grid.search(v)` | | | `.column(i).search(v)` | `grid.filters({ key: v })` | Arrays mean "any of"; `{ op, value }` for typed filters | | `$.fn.dataTable.ext.search`2.x+: `DataTable.ext.search`, `search.fixed()` | `grid.filters({ name: (value, row) => … })` | Browser-side grids; per grid, not global | | `.page(n).draw('page')` | `grid.page(n + 1)` | 1-based | | `.page.info()` | `grid.status()`, `grid.page()`, `grid.pageSize()` | `status()` has `total`, `filtered`, `hasMore` | | `.page.len(n).draw()` | `grid.pageSize(n)` | | | `.order([[i, 'desc']]).draw()` | `grid.sort([["amount", "desc"]])` | | | `.columns.adjust()` | Not needed | ResizeObserver | | `.column(i).visible(b)` | `grid.setColumnVisible("key", b)` | | | `.columns().visible()` (read) | `grid.columns()` | Each column has `visible` | | `.rows().data()` | `grid.rows()` | Server grids: the current page | | `.rows({ page: 'current' }).data()` | `grid.viewRows()` | | | `.rows({ search: 'applied' }).data()` | `await grid.exportRows("all")` | Server grids: one request, up to `maxPageSize` rows | | `.row(tr).data()` | `grid.delegate()` context, `grid.rowByKey(key)` | | | `.row(x).data(d).draw()`, `.row().invalidate()` | `grid.refreshRow(key, row)` | | | `.rows.add(arr).draw()` | `grid.addRows(arr)` | Client grids only; server grids ignore it (with a console notice): `reload()` instead | | `.clear()` + `.rows.add(arr)` | `grid.setData(arr)` | `setData([])` empties the grid | | `.row(x).remove().draw()` | `grid.removeRow(key)` | | | `.destroy()` | `grid.destroy()` | Restores the original table | | `.state.clear()` | `grid.state.reset()` | `clear()` keeps the current view | | `.state.save()`, `.state.loaded()` | `grid.state.save()`, `grid.state.read()` | | | `.rows({ selected: true }).data()` | `grid.selection.get()` | Bulk requests: `payload()` | | `.button(…).trigger()` on an export button | `grid.excel.download()` | Also `grid.csv`, `grid.print` | | `.buttons.exportData()` | `await grid.exportRows("all")` | Every filtered row; `exportRows()` alone returns the current page | | `.settings()` | — | No private settings; use events and module APIs | | A delegated `$(document).on('click', '.archive', …)` reading `.row(tr).data()` | `grid.delegate("click", ".archive", (e, { row }) => …)` | Also gives `key`, `tr`, `td`, `column` | | `$('#t tbody').on('click', 'tr', …)` | `rowClick: (row, event) => …` option | Adds a permanent "open" indicator column | | `$.post(url).done(() => table.ajax.reload(null, false))` | `grid.action(url, { method, confirm })` | Confirm, CSRF, notify, reload keeping the page | ## Your server keeps working `ssp()` and `yajra()` send exactly what DataTables 1.10 sends, so controllers keep working as they are: * The full parameter set on every request: `draw`, `columns[i][data|name|searchable|orderable|search][value|regex]`, `order[i][column|dir]`, `start`, `length`, `search[value|regex]`, then your page parameters. * Encoding identical to jQuery's `$.param`: booleans as `"true"` / `"false"`, `null` as an empty value, empty arrays omitted, `k[]=` for arrays, `k[a][b]=` for objects, `+` for spaces in POST bodies. No JSON body. * `columns[]` in definition order with hidden columns included, so `order[i][column]` indexes never shift when users hide or reorder columns. * While no sort is active (no `sort` option, or the sort cleared at runtime) the default `order[0][column]=0&order[0][dir]=asc` is sent, like DataTables. Only an explicit `sort: []` sends no order. * Headers: `X-Requested-With: XMLHttpRequest` and jQuery's `Accept`. With `csrf: true`, also `X-CSRF-TOKEN` and a `_token` field. * The response is read the same way: `data`, `recordsTotal`, `recordsFiltered` (numeric strings accepted), `error`, `DT_RowId`, `DT_RowClass`, and any extra top-level keys (on the `response` event, in `grid.lastResponse()`, bindable with [`metaBind()`](/modules/meta-bind)). * `draw` is sent but not trusted. The latest request wins; earlier ones are aborted. * With `yajra()`, untyped columns render as HTML because yajra escapes values on the server. `ssp()` renders them as text. * `length=-1` ("All") passes through only with `allowAll: true`; otherwise it is capped by `maxPageSize`. * Not supported: the pre-1.10 request format (`sEcho`, `iDisplayStart`, `iSortCol_0`…). Responses with `aaData`, `iTotalRecords` and `iTotalDisplayRecords` are still read. Every rule, with the error normalization table, is in the [SSP wire reference](/protocol/ssp). ## Step by step: a typical server-side page Before (DataTables 1.10): ```html
#NameUnitAmountStatus
``` After: the same page with datagrids, live against an in-page server that answers like a yajra/laravel-datatables controller. Pick a unit, then open the **Request** tab. ::: code-group ```js [JavaScript] import { Datagrid, column, serverSide, yajra, filterPanel, stateSave, colVis, button, excel, print, } from "@akinozgen17/datagrids"; new Datagrid("#mig-after", { name: "mig-after", label: "Field agents", columns: [ column.index(), { key: "name", title: "Name" }, { key: "unit", title: "Unit" }, column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), { key: "status_html", title: "Status", sortable: false, searchable: false }, ], sort: [["amount", "desc"]], pageSize: 10, use: [ serverSide({ url: "/api/agents", protocol: yajra(), csrf: true }), filterPanel({ fields: { unit: "#mig-after-unit" } }), // sent as `unit`, reloads on change stateSave(), // search and page are not saved by default colVis(), button.reload(), excel(), print(), ], }); ``` ```html [HTML]
``` ::: What changed: | Before | After | |---|---| | `serverSide`, `ajax.url`, `type: 'POST'` | `serverSide({ url, protocol: yajra() })`; POST is `yajra()`'s default | | `d._token = …` | `csrf: true`, or `configure({ csrf: true })` once for every grid | | `d.unit = …` + a `change` handler calling `ajax.reload()` | `filterPanel({ fields: { unit: "#mig-after-unit" } })`: sent as `unit`, reloads on change | | `stateSave` + `stateSaveParams` | `stateSave()`: search and page are never saved by default | | `dom` + `buttons` | `colVis()`, `button.reload()`, `excel()`, `print()`: each places its own control | | `order: [[3, 'desc']]` | `sort: [["amount", "desc"]]` | | `DT_RowIndex` column | `column.index()` numbers rows in the browser | | `render.number(…)`, `className: 'text-end'` | `column.money()`: formatted, right-aligned, exported as a number (the server sends plain numbers) | | `name`, `unit`, `status_html` | Untyped columns: with `yajra()` they render the server's (escaped) HTML | | `processing: true` | Built in | Three things to check on your own pages: * **Numbers the server formats:** `column.number()` and `column.money()` read data strings as machine numbers (`"1500.50"`; `"1.500"` = 1.5). If the controller sends Turkish-formatted text (`number_format($v, 0, ',', '.')` → `"1.500"` for 1500), add `source: "tr"`; for server-rendered money HTML, `column.money(key, { source: "html" })`. * **String columns on yajra endpoints:** keep them untyped (`{ key: "name", title: "Name" }`). `column.text()` always renders text, so a value yajra escaped (`O'Brien`) would show the entity. * **`columns[i][data]` changes for the index column:** `column.index()` sends an empty `data`. If your controller looks columns up by `data`, keep `{ key: "DT_RowIndex", title: "#", sortable: false, searchable: false }` instead. ## Turn repeated configuration into a preset Most pages repeat the same source, buttons and saved state. A preset is a function that returns an array of modules; arrays nest inside `use`: ```js // list-page.js import { serverSide, yajra, stateSave, colVis, button, excel, print } from "@akinozgen17/datagrids"; export const listPage = (url, o = {}) => [ serverSide({ url, protocol: yajra(), csrf: true, ...o }), stateSave(), colVis(), button.reload(), excel(), print(), ]; ``` ```js import { Datagrid, filterPanel } from "@akinozgen17/datagrids"; import { listPage } from "./list-page.js"; new Datagrid("#agents", { label: "Agents", columns, use: [listPage("/api/agents"), filterPanel({ fields: { unit: "#unit-filter" } })], }); ``` For server-rendered pages without a build step, register it with `preset("list-page", (table) => [...])` and mark tables with `data-datagrid="list-page"`; [`upgrade()`](/guide/lifecycle#declarative-init-upgrade) enhances them. Host-wide defaults (CSRF, page sizes, confirm and toast adapters, messages) go into `configure()` once. ## Behavior differences and deliberate decisions 1. `Datagrid.get()` never creates a grid. `$(el).DataTable()` initializes a table with defaults when there is none, and a later "real" initialization is then ignored. 2. Loading is explicit: `load: "eager" | "visible" | "manual"`. In DataTables 1.10, any non-null `deferLoading` value defers the first request, even `false`. 3. Cells are text by default; HTML is a per-column opt-in. `yajra()` is the one exception, for untyped columns, because yajra escapes on the server. 4. Page numbers are 1-based in every API (`grid.page(1)` is the first page). 5. No PDF export. Use the print view and the browser's "Save as PDF". 6. Column widths live in CSS. No inline widths, no `columns.adjust()`: a ResizeObserver keeps headers aligned in tabs and modals. 7. No layout strings. Modules place their controls in named toolbar slots. 8. Errors are per grid: an `error` event plus an inline error state or banner with Retry. No `alert()`, no global error mode. Server error text (SQL, stack traces) never reaches the UI. 9. Responses are matched to requests, not to `draw`. A missing, stale or string `draw` can't freeze the table in "Processing…". 10. Saved state skips search and page by default, carries a version and a TTL, and is dropped when the column set changes. 11. The pager belongs to its table and sits outside the horizontal scroll area. 12. Exports read typed values (`exportValue`), not cell HTML. 13. Session expiry (419, 401, or a redirect to a login page) fires `sessionexpired`. 14. Unknown options print a console warning ([DG001](/errors/DG001)) that names the replacement: passing `ajax`, `dom` or `buttons` tells you which module to use. ## Finding everything to migrate ```bash # Every initialization, jQuery style and DataTables 2+/3 style rg -n -e '\.(DataTable|dataTable)\s*\(\s*\{' -e 'new\s+DataTable\s*\(' . # Accessor calls: DataTables initializes the table here if it isn't yet rg -n -e '\.DataTable\(\s*\)' . # Global defaults and extensions that change behavior site-wide rg -n -e '(dataTable|DataTable)\.(defaults|ext)' . # DataTables event listeners rg -n -e "\.on\(\s*['\"][a-z-]+\.dt" . # Server endpoints that read DataTables parameters (PHP example) rg -n -e "request\(\s*'(draw|start|length|order|columns|search)'" -e 'DataTables::(of|eloquent|query)' . ``` Configurations embedded in server templates (Blade, Twig, ERB, Razor) mix template syntax into JavaScript, so codemods can't parse them reliably. Migrate those by hand with the tables above. ## FAQ * **Can DataTables and datagrids run on the same page?** Yes. datagrids emits no `dataTable` classes and no `.dt` events, so global DataTables plug-ins and listeners don't touch it. Migrate one page at a time. * **Do I have to change my controllers?** No. Keep them and use `yajra()` or `ssp()`. When you write a new endpoint, consider the [datagrids protocol](/protocol/v1/). * **My cells show `&`.** The column renders the server's escaped HTML as text. On yajra endpoints use an untyped column (`{ key: "name" }`) instead of `column.text()`; elsewhere use `column.html()` only for values your server escaped. * **Other scripts call `$('#t').DataTable().ajax.reload()`.** Give the grid a `name` and call `reload("agents")`, or `Datagrid.get('#t')?.reload()`. * **Where are header filter rows, RowGroup and PDF?** Not in v1. See the [deliberate decisions](#behavior-differences-and-deliberate-decisions) above. * **No bundler?** Use the IIFE build: everything is on `window.Datagrids` (`Datagrids.Datagrid`, `Datagrids.serverSide`…). See [Getting started](/guide/getting-started#without-a-bundler). ## Appendix: legacy 1.9 names Map to 1.10 names first, then use the tables above. | 1.9 | 1.10+ | |---|---| | `bServerSide`, `sAjaxSource`, `fnServerParams`, `fnServerData` | `serverSide`, `ajax`, `ajax.data`, `ajax` (function) | | `aaSorting`, `aLengthMenu`, `iDisplayLength`, `sDom`, `oLanguage` | `order`, `lengthMenu`, `pageLength`, `dom`, `language` | | `aoColumns`, `aoColumnDefs`, `mData`, `mRender` | `columns`, `columnDefs`, `columns.data`, `columns.render` | | `sTitle`, `sClass`, `sWidth`, `bVisible`, `bSortable`, `bSearchable`, `sDefaultContent` | `title`, `className`, `width`, `visible`, `orderable`, `searchable`, `defaultContent` | | `bPaginate`, `bFilter`, `bSort`, `bInfo`, `bLengthChange`, `bProcessing`, `bStateSave`, `sPaginationType` | `paging`, `searching`, `ordering`, `info`, `lengthChange`, `processing`, `stateSave`, `pagingType` | | `fnDrawCallback`, `fnRowCallback`, `fnCreatedRow`, `fnInitComplete`, `fnFooterCallback` | `drawCallback`, `rowCallback`, `createdRow`, `initComplete`, `footerCallback` | | `fnClearTable`, `fnAddData`, `fnDeleteRow`, `fnDraw`, `fnFilter`, `fnSort`, `fnGetData`, `fnSettings` | `clear()`, `rows.add()`, `row().remove()`, `draw()`, `search()`, `order()`, `data()`, `settings()` | ## Related * [Concepts](/guide/concepts): grid, columns, modules, pipelines. * [Server protocols](/protocol/) and the [SSP wire reference](/protocol/ssp). * [Laravel + yajra recipe](/recipes/laravel-yajra). * [Module catalog](/modules/). --- --- url: https://akinozgen.github.io/datagrids/errors/DG001.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG001: Unknown grid option ```text [datagrids DG001] Unknown option `{name}`.{hint} ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens The options object passed to `new Datagrid()` has a key that is not a grid option. The key is ignored. The message adds a hint: for a well-known legacy option name (compared case-insensitively) it names the replacement; for anything within two typing edits of a real option it suggests that option (`pagesize` → ``Did you mean `pageSize`?``). ## How to fix it Rename or remove the key. The [grid options](/reference/options) are the only accepted keys; every other capability is a column option or a [module](/modules/) in `use: [...]`. | Key you passed | Hint printed | |---|---| | `serverSide` | Server mode is a module: use `serverSide({ url, protocol: yajra() })`. | | `ajax` | Use the `serverSide({ url, … })` module. | | `dom` | Use toolbar slots (`start`, `end`, `filters`). | | `buttons` | Attach button modules (`button.reload()`, `excel()`…). | | `language` | Use `messages`. | | `stateSave` | Use the `stateSave()` module. | | `lengthMenu` | Use `pageSizes`. | | `pageLength` | Use `pageSize`. | | `order` | Use `sort: [['key', 'desc']]`. | | `deferLoading` | Use `load: 'manual'`. | | `columnDefs` | Put options on the column definitions. | The [migration guide](/migration/from-datatables) maps every legacy option. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG002.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG002: Grid has no accessible name ```text [datagrids DG002] Grid has no accessible name; pass `label` or `labelledBy`. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens The grid was created without `label`, `labelledBy` or `title`, and the table has no ``. Assistive technology then announces the scroll region with the generic `messages.regionLabel` ("Data table"), the same name for every grid on the page. ## How to fix it Name every grid after what it lists: ```js new Datagrid("#agents", { label: "Field agents", columns }); ``` Or point at a visible heading with `labelledBy: "agents-heading"`, or keep a `` in the table. `title` names the grid only together with `surface: "card"`; `label` works everywhere. See [Accessibility](/guide/accessibility). ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG003.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG003: Rows have no key ```text [datagrids DG003] No row key found (rowKey/id/DT_RowId); falling back to index. Selection and focus keeping are disabled. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens A row has no key: `rowKey` is not set and the row has neither `id` nor `DT_RowId`, or the `rowKey` path or function returned `null` or `""`. The grid falls back to the row's position (`__i0`, `__i1`, …). ## How to fix it Tell the grid which field identifies a row: ```js new Datagrid("#agents", { label: "Agents", rowKey: "uuid", columns }); new Datagrid("#stock", { label: "Stock", rowKey: (row) => `${row.unit}-${row.ref}`, columns }); ``` Position keys change whenever the data changes, so selection, `refreshRow(key)`, `removeRow(key)`, row actions and focus restoration cannot follow a row across pages or reloads. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG004.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG004: Unknown column key ```text [datagrids DG004] Unknown column key `{name}`. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens Reserved for calls that name a column key the grid does not have. **The current version does not print DG004**: `setColumnVisible()` and `columnOrder()` ignore unknown keys silently, and the [footer](/modules/footer) module prints its own message (see [Other console messages](/errors/#other-console-messages)). ## How to fix it Check the key against `grid.columns().map((c) => c.key)`. A column with `can: false` does not exist at all, so its key is unknown too. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG005.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG005: Selector must match exactly one table ```text [datagrids DG005] `{name}` needs a selector that matches exactly one ; matched {count}. ``` This is a wiring mistake: the grid throws an `Error` with this message instead of half-working. ## When it happens `new Datagrid(selector)` or `grid.remount(selector)` got a CSS selector that matched no element, more than one element, or a single element that is not a `
` (reported as "matched 0"). Thrown synchronously by the constructor. ## How to fix it Use a unique selector (`"#agents"`) or pass the `HTMLTableElement` itself, and create the grid after the table is in the document (for example after a tab or modal has rendered its content). `Datagrid.get()` and `get()` never throw; they return `null`. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG006.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG006: No grid with that name ```text [datagrids DG006] Datagrids.reload(`{name}`): no grid with that name. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens `reload(name)` found no live grid registered under `name`; it returns `false` and does nothing. A grid registers its `name` option when it is created and unregisters on `destroy()`. ## How to fix it Give the grid a `name` and make sure it exists when you reload it: ```js new Datagrid("#agents", { name: "agents", label: "Agents", columns }); reload("agents", { keepPage: true }); ``` Use `find(name)` to check for a grid without a warning. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG007.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG007: Required module is missing ```text [datagrids DG007] Module `{name}` requires `{dep}`, which is not attached. ``` This is a wiring mistake: the grid throws an `Error` with this message instead of half-working. ## When it happens A module declares `requires: ["…"]` and no module with that name is attached. The check runs after all modules from the constructor's `use` are attached (thrown by the constructor) and, for `grid.use()`, in a microtask afterwards (an uncaught error in the console). Built-in case: `button.resetState()` requires `state`, the module name of `stateSave()`. ## How to fix it Attach the dependency in the same `use` array; the order inside the array does not matter: ```js use: [stateSave(), button.resetState()] ``` ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG008.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG008: Two modules claim one slot ```text [datagrids DG008] Two modules claim the single `{slot}` slot (`{a}` and `{b}`). ``` This is a wiring mistake: the grid throws an `Error` with this message instead of half-working. ## When it happens Two modules claim the `source` slot, the only single slot. Every data source occupies it: `serverSide`, `arraySource`, `domSource`, `fetchAll`, `customSource`. Thrown when `use` contains two sources, or when a source is chained with `grid.use()` while an explicit one is already attached (a chained source replaces only the default array/DOM source). `{a}` is the source in place, `{b}` the one being attached. ## How to fix it Attach exactly one source, in `use: [...]` at construction: ```js new Datagrid("#agents", { label: "Agents", columns, use: [serverSide({ url: "/api/agents", protocol: yajra() })], }); ``` To switch sources, `destroy()` the grid and create a new one. Note that `data: [...]` is ignored, without an error, when `use` already contains a source. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG009.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG009: Module attached twice ```text [datagrids DG009] Module `{name}` is attached twice. ``` This is a wiring mistake: the grid throws an `Error` with this message instead of half-working. ## When it happens A module name is attached a second time: the same factory twice (`colVis()` in a preset and again on the page) or two modules with the same `name`, such as two `button.custom({ name: "approve", … })`. ## How to fix it Attach each module once per grid. When a [preset](/reference/static#preset) already contains a module, don't repeat it; give custom buttons distinct names, or leave `name` out to get an automatic one. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG010.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG010: Module name collides with a grid member ```text [datagrids DG010] Module name `{name}` collides with a core grid member. ``` This is a wiring mistake: the grid throws an `Error` with this message instead of half-working. ## When it happens A module's `name` is a core grid member (`reload`, `columns`, `search`, `status`, …) or another property the grid instance already has. A module's API is installed on the grid under its name, so the name must be free. Data source modules are exempt. ## How to fix it Rename the module, for example `name: "reloadButton"` instead of `"reload"`. The built-in modules already use free names (`state`, `colVis`, `selection`, …). See [Writing a module](/reference/modules). ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG011.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG011: Document has no language ```text [datagrids DG011] is missing; uppercase headers may render Turkish i wrong (TARIH). ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens The page's `` element has no `lang` attribute while the grid uses uppercase headers (the default `head: "caps"`). Uppercasing in CSS depends on the language: in Turkish `i` becomes `İ`, elsewhere `I`, so a header can come out wrong. Without `lang`, and without a `locale` option or `configure({ locale })`, the grid also takes the browser's language (English when that is unusable). ## How to fix it Declare the page language: ``. Or switch to sentence-case headers with `head: "sentence"`. Set `locale` when a grid's language differs from the page's. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG012.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG012: Server error details ```text [datagrids DG012] Server error: {detail} ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens A load failed and the error carries a `detail` the grid keeps out of the visible message: the exception message of an HTTP error response (JSON `message` / `error`, or up to 500 characters of a text body), the `error` string of an HTTP 200 SSP response (debug output), or the browser's message for a network failure. The grid shows a generic message; the detail goes to the console. ## How to fix it Fix the server-side problem the detail describes. While `warnings` is on (the default) the error state also shows the detail in a "Details" disclosure. In production turn both off with `configure({ warnings: false })`. The full error object is on the `error` event: ```js grid.on("error", ({ error }) => report(error.kind, error.status, error.detail)); ``` See [States & errors](/guide/states-and-errors). ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG013.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG013: Page size above maxPageSize ```text [datagrids DG013] Page size {size} exceeds maxPageSize {max}; clamped. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens `grid.pageSize(n)` (also used by the page-size menu) got a value above `maxPageSize` (default 1000) or a negative value; the size is clamped to `maxPageSize`. `-1` ("All") is accepted only when the protocol allows it (`ssp({ allowAll: true })`). The initial `pageSize` option is not checked. ## How to fix it Keep `pageSizes` within `maxPageSize`, or raise the limit for this grid with `maxPageSize: 5000`. For lists that must show everything, prefer client mode (`fetchAll`) and a server-side export. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG014.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG014: Grid state could not be saved ```text [datagrids DG014] Could not write grid state to storage ({reason}). ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens Reserved for state storage write failures (blocked storage, a full quota, some private browsing modes). **The current version prints an uncoded message instead**: `[datagrids] stateSave: storage is not writable (…); state is not persisted.`, once per page. ## How to fix it Nothing breaks: the grid works, the view is just not remembered. Pass another `Storage` (`stateSave({ storage: sessionStorage })`) or `storage: null` to turn persistence off deliberately. See [stateSave](/modules/state-save). ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/errors/DG015.md description: >- One datagrids warning or error code — the message, when it happens and how to fix it. --- # DG015: Invalid locale ```text [datagrids DG015] `{tag}` is not a valid locale; it is ignored. ``` Printed with `console.warn`, once per distinct message. `configure({ warnings: false })` silences it. ## When it happens The `locale` option, `configure({ locale })` or `` holds a value the `Intl` APIs reject (``, `locale: "tr_TR"`). Number and date formatting would throw on it, so the grid skips it and takes the next candidate: the browser's language, then `"en"`. ## How to fix it Use a BCP 47 tag (`tr`, `tr-TR`, `en-GB`). When the value comes from user settings, validate it on the server before writing it into the page. ## Related * [All warning codes](/errors/) * [Grid options](/reference/options) * [Static API & configure()](/reference/static) --- --- url: https://akinozgen.github.io/datagrids/llm.md description: >- The complete datagrids API in one page for AI coding agents — options, columns, modules, methods, events, protocols, tokens, recipes and gotchas. --- # datagrids — AI agent cheat sheet ## What it is Framework-agnostic, zero-dependency, accessible data grid that enhances a plain `
`. A small core (search, sort, paging, pager, states, toolbar slots) plus **typed columns** and **independent modules** attached with `use`. Server protocols: classic SSP wire (`ssp()`, `yajra()` preset), Laravel paginator JSON (`laravelPaginator()`), datagrids protocol v1 (`dgp()`). Styles are scoped under `--dg-*` tokens. npm: `@akinozgen17/datagrids`. Types (`dist/index.d.ts`) are the source of truth. ## Install ```sh npm i @akinozgen17/datagrids ``` ```js import { Datagrid, column, serverSide, yajra } from "@akinozgen17/datagrids"; import "@akinozgen17/datagrids/css"; // REQUIRED (tokens + core + module styles) // "@akinozgen17/datagrids/css/tokens" = tokens only ``` No bundler: `dist/datagrids.css` + `dist/datagrids.global.js` → everything on `window.Datagrids` (`Datagrids.Datagrid`, `Datagrids.column`, `Datagrids.configure`, …). ## Mental model * **Grid** = one `
` + `columns`. `new Datagrid(tableOrSelector, options)`. Never a giant config. * **Columns** = typed factories `column.text/number/money/date/badge/link/phone/boolean/html/index/select/actions`. * **Modules** = immutable definitions from factories (`stateSave()`), attached with `use: [ ... ]`; arrays nest (a preset is an array). Module API appears on the grid under the module's name (`grid.state`). * **Pipelines** modules plug into: request middleware, row mutators, toolbar slots, state contributions, export values, lifecycle. **Events** (`grid.on`) are for reacting. ## Quick start — the ONE canonical way ```js import { Datagrid, column, serverSide, yajra, colVis, stateSave, button, excel, print, configure } from "@akinozgen17/datagrids"; import "@akinozgen17/datagrids/css"; configure({ csrf: true }); // optional global defaults (only affects grids created later) const grid = new Datagrid("#agents", { label: "Agents", // accessible name (or labelledBy / ` | | | `use` | `ModuleInput[]` | `[]` | modules and nested arrays (presets) | | `data` | `Row[]` | — | shorthand for `arraySource(rows)` | | `name` | `string` | — | registry name for `find()` / `reload(name)`; stateSave key | | `label` / `labelledBy` | `string` | caption | accessible name; missing → DG002 | | `title`, `description` | `string` | — | shown in the card header (`surface: "card"`) | | `pageSize` | `number` | 25 | `configure` default | | `pageSizes` | `number[]` | `[10,25,50,100]` | `-1` = "All" (only if the protocol `allowAll`) | | `maxPageSize` | `number` | 1000 | clamps page sizes (DG013) | | `paging` | `boolean` | `true` | `false` = one view with every row | | `sort` | `[["key","asc"\|"desc"]]` or `[{key,dir}]` | none | `[]` = no sort (ssp otherwise sends `[[0,'asc']]`) | | `search` | `boolean \| { delay, minLength, placeholder }` | on; delay 400 ms server / 200 ms client | Enter = now, Esc = clear | | `load` | `"eager" \| "visible" \| "manual"` | `"eager"` | visible = IntersectionObserver | | `rowKey` | `string \| (row) => string` | `id` → `DT_RowId` → index (DG003) | | | `virtual` | `boolean \| number` | auto at ≥300 rows in view | `false` disables | | `maxHeight` | CSS length | — | body scrolls, sticky header | | `errorMode` | `"inline" \| "silent" \| "throw"` | `"inline"` | | | `messages` | `Partial` | locale pack | | | `locale` | `string` | `configure` → `` → `navigator.language` → `"en"` (invalid tags skipped, DG015) | `tr*` → Turkish pack, else English | | `host` | `HostAdapters` | from `configure` | per-grid confirm/notify/csrf/laravel/timeout/fetch | | `surface` | `"plain" \| "card"` | plain | | | `size` | `"sm" \| "md" \| "lg"` | md | | | `density` | `"compact" \| "normal" \| "comfortable"` | normal | rows 28/36/44 px | | `theme` | `"light" \| "dark" \| "system"` | inherit page `color-scheme` | | | `head` | `"caps" \| "sentence"` | caps | caps needs `` (DG011) | | `striped`, `wrap`, `count` | `boolean` | false, true, false | `count` shows "N records" | | `rowTone` | `(row) => "ok"\|"warn"\|"bad"\|"info"\|"muted"\|…` | — | `tr[data-tone]` | | `rowClass`, `rowAttrs` | `(row) => string` / `(row) => Record` | — | | | `rowClick` | `(row, event) => void` | — | adds a permanent `›` column | Unknown options warn (DG001) with hints for legacy names (`ajax`, `serverSide`, `dom`, `buttons`, `language`, `stateSave`, `lengthMenu`, `pageLength`, `order`, `deferLoading`, `columnDefs`). ## Columns (complete) ColumnDef: `key` (required), `data` (dotted path, default key), `name` (server column name), `title`, `type`, `sortable`, `sortKey` (client sort field), `searchable`, `visible`, `hideable`, `exportable`, `align` (`start|end|center`), `className`, `defaultContent`, `can` (false → column does not exist anywhere), `html` / `text` (render mode), `sticky` (`start|end`), `render(value,row,ctx)` → `Node|string|number|null` (`ctx`: `row, key, index, position, td, locale, text(row, path)`; `value` is text already, `ctx.text` decodes other fields of escaped yajra rows), `lazy` (server-computed on demand, see `lazyColumns`), `value(row)`, `compare(a,b)`, `searchText(value,row)`, `exportValue(row)`, `exportType` (`string|number|money|date|boolean`), `exportFormat`, `labels`. | Factory | Extra options | Behaviour | |---|---|---| | `column.text(key)` | — | always text | | `column.html(key)` | — | raw HTML (opt-in); search/export strip tags | | `column.number(key)` | `decimals`, `locale`, `source: "number"\|"tr"` | end-aligned, numeric sort, exports number; `number` (default) reads `"1.500"` as 1.5, `tr` as 1500 | | `column.money(key)` | `currency` (TRY), `decimals` (2), `locale`, `source: "number"\|"tr"\|"html"` | `.dg-money` | | `column.date(key)` | `time`, `timeZone`, `locale`, `source: "iso"\|"local"\|"dmy"` | exports real date | | `column.badge(key)` | `labels`, `tones` | `.dg-chip[data-tone]` | | `column.link(key)` | `href: "/x/{id}" \| (row) => url`, `target` | values URL-encoded; safe schemes only | | `column.phone(key)` | `country` ("90"), `whatsapp` | `tel:` link (+ WhatsApp link), digits normalized | | `column.boolean(key)` | `labels: { true, false }`, `showFalse` (true) | ✓/✕ icon + text; reads 1/0, true/false, evet/hayır, yes/no, on/off | | `column.index()` | — | row number (page offset aware) | | `column.select()` | — | required by `selection()` | | `column.actions()` | — | required by `actions()`; sticky end | **Cells are text by default; HTML is an explicit opt-in.** Untyped columns follow the source: array, fetchAll, ssp, dgp, laravelPaginator → text; `yajra()` → HTML (server escapes); DOM source adopts existing cells. number/money/date format with the grid `locale` (money in `TRY`) unless the column gets `locale`/`currency`. Widths: CSS only (`#t th[data-key="ref"]{inline-size:7rem}`), never inline. ## Data sources | Factory | Mode | Options | |---|---|---| | `arraySource(rows)` / `data: rows` | client | — | | `domSource()` (automatic when `` has rows) | client | ``), `label`, `messages`. All export modules share one "Export" menu. No PDF: print view + the browser's "Save as PDF". `actions` item: `{ id, label, icon?, tone?: "danger"|"warning"|"success", group?, primary?, can?: boolean | (row) => boolean, disabled?: (row) => boolean | reason string, href?: "/a/{id}", target?, request?: { url: "/a/{id}", method, body }, handler?: (row, { grid, key }) => void, confirm?: string | { title, message, confirmLabel, cancelLabel }, success?: string | false, reload?: false | { keepPage } }` — exactly one of href/request/handler; `{field}` is URL-encoded; ≤ `inline` actions render as buttons, more → primary + `⋯` menu. `can` is UX only; endpoints authorize. Every module accepts `can: false` (attached, contributes nothing). Wiring errors throw: missing `requires` DG007, two sources / single slot DG008, same module twice DG009, name clashes with a core member DG010. ## Writing a module ```js const countBadge = () => Object.freeze({ name: "countBadge", kind: "toolbar", setup(ctx) { const el = document.createElement("span"); ctx.toolbar({ slot: "end", order: 5, el }); const off = ctx.on("load", ({ result }) => (el.textContent = `${result.filtered ?? result.rows.length}`)); ctx.request((req, next) => { req.headers["X-Grid"] = "agents"; return next(req); }, "pre"); return { api: { el }, destroy() { off(); el.remove(); } }; }, }); ``` ModuleDef: `name`, `kind` ("source"|"feature"|"toolbar"|"export"), `slot?`, `requires?`, `enforce?` ("pre"|"post"), `can?`, `source?`, `setup(ctx)` → `{ api?, destroy? }`. ctx: `grid`, `root`, `table`, `messages`, `host`, `locale`, `signal`, `on`, `toolbar({slot,order,el})`, `row((tr,row,key)=>…)`, `request(mw, "pre"|"post")`, `state({key,save,load})`, `above(el)`, `layer(el)`, `announce(msg)`, `requestRender()`, `ready(fn)`. Request middleware order: built-ins (X-Requested-With, CSRF) → `pre` → registration order → `post`; call `next(req)` once. ## Instance methods (complete) | Method | Notes | |---|---| | `load()` | loads (used with `load:"manual"`) | | `reload({ keepPage?, silent? })` | default page 1; silent = no busy card | | `search(v?)`, `page(n?)`, `pageSize(n?)`, `sort(spec?)` | getters/setters; setters load | | `filters(patch?)` | `{ key: value \| [any of] \| { op, value } \| (v,row)=>bool \| null }`; non-column keys = page params (server) | | `query()` | `{ page, pageSize, sort, search, filters, columns, sortDefault, pristine }` | | `columns()`, `setColumns(defs)`, `setColumnVisible(key, bool)` | | | `columnOrder(keys?)` | display order (get/set); requests keep definition order | | `rows()`, `viewRows()`, `keyOf(row)`, `rowByKey(key)` | | | `setData(rows)`, `addRows(rows, {keepPage})`, `removeRow(key)`, `refreshRow(key, row?)` | client mode (refreshRow/removeRow also server; addRows is ignored in server mode); `reload()` keeps these edits on array/DOM sources | | `lastResponse()` | raw JSON of the last response | | `lastRequestParams()` | page params of the request behind the rows on screen, as sent: filter panel, toggles, `params`, non-column filters and (ssp/yajra) `data` additions; protocol fields and `_token` excluded | | `exportRows("page"\|"all")` | | | `status()` | `{ status: "idle"\|"loading"\|"reloading"\|"ready"\|"error", loaded, total, filtered, hasMore, error }` | | `on(type, fn)` → unsubscribe; `emit(type, detail)` | DOM `dg:` CustomEvents on `grid.root` too | | `delegate(type, selector, (e, { row, key, tr, td, column }) => …)` → unsubscribe | row-aware DOM events | | `action(url, { method:"POST", body, confirm, success, reload, headers, isError })` | confirm → CSRF fetch → notify → `reload({keepPage:true})`; same-origin, method allow-list; a redirect to a non-login page = success, to a login page = `sessionexpired`; a 2xx body fails only via `isError(body, res)` (truthy, string = message) | | `notify(kind, msg)`, `confirm(msg, opts)` | host adapters, else live region / native `` | | `batch(fn)` | several changes, no intermediate loads | | `use(module)`, `module(factory)` | typed module API access | | `destroy()`, `remount(table?)` | destroy restores the original table; remount keeps options + modules chained with `use()` | | `root`, `table`, `name`, `messages`, `locale`, `mode`, `maxPageSize` | properties | ## Static API `Datagrid.get(el | selector)` → grid or **null** (never creates) · `get` · `find(name)` · `reload(name, opts)` → bool (DG006) · `configure(GlobalConfig)` · `upgrade(root?)` (idempotent, `table[data-datagrid]`, attrs `data-dg-name/label/load/page-size/sort="key:desc"/theme/size/density`) · `preset(name, (table) => modules)` · `en`, `tr` message packs · `VERSION`. `configure` keys: `confirm(msg, opts) → Promise`, `notify(kind, msg)`, `csrf` (false), `laravel` (true), `timeout` (30000), `onSessionExpired(err)`, `fetch`, `isError(body, res)` (action 2xx failure rule), `messages`, `locale`, `pageSize` (25), `pageSizes`, `maxPageSize` (1000), `warnings` (true), `errorMode` ("inline"). Read at grid creation, except `errorMode`, `maxPageSize`, `warnings` (read when needed, so they reach existing grids too). ## Events (complete) | Event | Payload | Cancelable | |---|---|---| | `init` | `{ grid }` | | | `beforeLoad` | `{ query, cancel() }` | ✓ | | `response` | `{ raw, result }` (server/fetch responses) | | | `load` | `{ result, query }` | | | `render` | `{ keys, rows }` (after every body render) | | | `loadingchange` | `{ loading }` | | | `error` | `{ error: DatagridError }` | | | `sessionexpired` | `{ error }` | | | `beforeSort` / `sort` | `{ sort, cancel() }` / `{ sort }` | ✓ / | | `beforePage` / `page` | `{ page, cancel() }` / `{ page }` | ✓ / | | `pagesize` | `{ pageSize }` | | | `search` | `{ search }` | | | `columnchange` | `{ columns }` | | | `headrender` | `{ tr }` | | | `selectionchange` | `{ count, keys, all }` | | | `collapse` | `{ columns }` (responsive module) | | | `beforeReorder` / `reorder` / `reordererror` | rowReorder end event `{ row, key, from, to, … }` (+ `error`) | ✓ / / | | `beforeAction` / `action` / `actionerror` | `{ id, key, row, cancel() }` / `{ id, key, row }` / `+ error` | ✓ / / | | `beforePrint` | `{ document, window, cancel() }` | ✓ | | `destroy` | `{}` | | DatagridError: `{ kind: network|timeout|abort|http|server|session|forbidden|validation|parse|protocol, status, message, detail?, retryable, raw? }`. 419/401/redirect-to-login → `session` (+ `sessionexpired` + `onSessionExpired`); 403 or another redirect → forbidden (but `action()` treats a non-login redirect as success); 422 → validation; 5xx/429 retryable; 200 + `error` → server (banner). ## Server protocols (wire summary) **ssp / yajra:** every request sends the full set `draw, start, length, search[value|regex], order[i][column|dir], columns[i][data|name|searchable|orderable|search][value|regex]`, encoded exactly like jQuery `$.param` (booleans as "true"/"false", empty arrays omitted). `columns[]` in definition order incl. hidden. No sort + no `sort: []` → `[[0,'asc']]`. Clearing the sort at runtime still sends `[[0,'asc']]`; only `sort: []` at construction drops it. Page filters (`params`, non-column `filters()` keys) = top-level params. Plain value on a column key → anchored escaped regex `columns[i][search][value]=^v$` + `regex=true` (arrays `^a$|^b$`). Typed column filters → `columns[i][columnControl]` (no `between`/`notIn`). Both only on searchable columns. Response: `data` (`aaData`), `recordsTotal`, `recordsFiltered` (numeric strings ok), `error`, `DT_RowId`, `DT_RowClass`; other keys → `lastResponse()` / `response` event / metaBind. **laravelPaginator:** GET `?page=&per_page=&sort=-date&search=`; detects `paginate` (total), `simplePaginate` (no total → "total unknown", next from `next_page_url`), `cursorPaginate` (`next_cursor` → `?cursor=`, pages reached in order) and API resources (`data`/`meta`/`links`). **dgp v1:** POST JSON `{ v:1, page:{size,number}, sort:[{key,dir}], q, filters:{key:{op,value}}, fields, count, requestId, params }` → `{ v:1, rows, page:{size,number,hasMore}, count:{mode,total?,filtered?}, meta }`; errors RFC 9457 + `code`, `retryable`, `errors`. Ops: `eq ne gt gte lt lte between in notIn contains notContains starts ends empty notEmpty` (AND only). ## CSS & DOM (summary) Input tokens (inherit from any ancestor): `--dg-accent` (default #3d63dd), `--dg-rem` (1rem). Other tokens live on `.dg` (override with `.app .dg { --dg-row-h: 2rem }`): `--dg-bg --dg-fg --dg-muted --dg-muted-fg --dg-border --dg-head-bg --dg-head-fg --dg-tone-{neutral,info,ok,warn,bad} --dg-accent-{solid,fg,ink,weak} --dg-ring --dg-line --dg-row-alt --dg-space-{1..8} --dg-radius-{xs,sm,md,panel,surface,full} --dg-font-size-{xs,sm,md,lg} --dg-head-{font-size,weight,transform,tracking} --dg-row-h --dg-cell-pad-{x,y} --dg-control-h --dg-dur-{1,2,3}`. `--dg-_*` = private. Root: `.dg[data-state="loading|ready|empty|error|idle"][data-size][data-density][data-dg-theme][data-dg-head][data-dg-surface][data-dg-striped][data-dg-virtual][data-bp]`. Toolbar `.dg-toolbar > .dg-slot[data-slot="start|end|filters"]`; table `table.dg-table` (your element); header `th[data-key][aria-sort] > button.dg-sort`; rows `tr[data-key][data-selected][data-tone]`; cells `td[data-key][data-align][data-col]`; pager `nav.dg-pager`; info `.dg-info`; busy `.dg-frame[data-busy]` + `table[aria-busy]`; never `dt-*` classes. ## Recipes ```js // page filter form → server params (+ shareable URL) use: [serverSide({ url, protocol: yajra(), csrf: true }), filterPanel({ fields: { status: "#status", unit: "#unit" } }), urlSync()] // client filters grid.filters({ status: ["open", "pending"], amount: { op: "gte", value: 1000 } }); // row action → POST with confirm, keeps the page grid.delegate("click", ".approve", (e, { row }) => grid.action(`/agents/${row.id}/approve`, { confirm: "Approve?" })); // bulk action with "select all matching" selection({ bulk: { actions: [{ id: "archive", label: "Archive", onClick: (payload, grid) => grid.action("/agents/bulk-archive", { body: payload }) }] } }) // payload {all:false,keys} | {all:true,except,query} // grid in a tab / modal new Datagrid("#t", { columns, load: "visible", use: [source] }); // reload another grid by name reload("agents", { keepPage: true }); // Livewire / SPA: wire:ignore around the table, or destroy before morph and remount after Datagrid.get("#t")?.destroy(); // declarative preset("list", (t) => [serverSide({ url: t.dataset.url, protocol: yajra(), csrf: true }), colVis()]); upgrade(); //
) columns: [ { key: "name", title: "Name", name: "agents.name" }, // yajra: strings arrive escaped → untyped (HTML) column column.badge("status", { title: "Status", labels: { open: "Open", done: "Done" }, tones: { open: "info", done: "ok" } }), column.money("amount", { title: "Amount", currency: "USD", locale: "en-US" }), column.date("created_at", { title: "Created", time: true }), { key: "actions_html", title: "", sortable: false, searchable: false }, // untyped → yajra default: HTML ], sort: [["created_at", "desc"]], use: [ serverSide({ url: "/agents/data", protocol: yajra(), params: () => ({ unit: unitSelect.value }) }), colVis(), button.reload(), stateSave(), excel(), print(), ], }); unitSelect.addEventListener("change", () => grid.reload()); ``` Put the data source in `use: [...]` (or chain `.use(source)`: it replaces the default source; a second explicit source throws DG008). ## Grid options (complete) | Option | Type | Default | Notes | |---|---|---|---| | `columns` | `ColumnDef[]` | from source / `
`; `td[data-order]` | | `fetchAll({ url, method, dataSrc, csrf, body })` | client | one request | | `serverSide({ url, protocol, method, params, headers, csrf, timeout, fetch, seed })` | server | `.params(fn)` derives a new def | | `customSource({ mode, load(query, { signal, grid, middlewares, host }) })` | either | return `{ rows, total, filtered, hasMore?, meta? }` | Protocols: `ssp({ data, dataSrc, cells:"text", method:"GET", allowAll:false })`, `yajra(same)` (= ssp with `cells:"html"`, `method:"POST"`), `laravelPaginator({ query:{page,perPage,sort,search,cursor}, sortFormat:"-key"|"key:dir" })`, `dgp({ method:"POST", count:"exact"|"estimate"|"none" })`. Custom protocol: `{ name, cells, method?, allowAll?, encode(req, query, grid) → { url, init, params? }, decode(body, query, grid) → LoadResult }` (`params` = page params that reached the wire, for `lastRequestParams()`). Transport adds `X-Requested-With: XMLHttpRequest` (unless `laravel:false`), CSRF (`X-CSRF-TOKEN` from `meta[name=csrf-token]` + `_token` in non-GET form bodies) when `csrf`, timeout 30 s, abort (latest wins, matched by sequence, never by `draw`), `credentials:"same-origin"`, strips `queries`/`input` debug keys. ## Modules (complete) | Factory | Grid API | Requires | Options | |---|---|---|---| | `stateSave()` | `grid.state`: `key`, `save()`, `read()`, `clear()`, `reset()` | — | `key`, `version` (1), `ttl` (90 days, 0 = never), `include: ["search","filters","page"]` (default none), `storage`, `delay` (250) | | `colVis()` | `grid.colVis`: `open/close/toggle/reset()`, `count()` | — | `messages`, `searchAbove` (12), `slot` ("start"), `order` (10) | | `colReorder()` | `grid.colReorder`: `order()`, `move(key,to)`, `reset()`, `movable()` | — | `drag` (true), `messages` — display order only, wire keeps definition order | | `responsive()` | `grid.responsive`: `collapsed()`, `refit()`, `toggle(rowKey, open?)` | — | `priority` ({key: n}, lower = kept longer; default last column collapses first), `keep` (keys), `details` (true: expandable detail rows), `messages`; fires `collapse` `{ columns }` | | `lazyColumns()` | `grid.lazyColumns`: `requested()`, `visible()` | — (server mode) | `keys` (+ columns with `lazy: true`), `param` ("lazy") — only visible lazy columns are requested; showing one reloads in place | | `stickyHeader()` | `grid.stickyHeader`: `stuck()`, `refresh()` | — | `offset` (px or `() => px`, for fixed app bars) — page-level header copy (aria-hidden) for horizontally scrolling tables | | `keyboardGrid()` | `grid.keyboardGrid`: `position()`, `focus(row, col)` | — | opt-in APG grid: `role="grid"`, one tab stop, arrows/Home/End/Ctrl+Home/End/PageUp/PageDown, Enter/F2 into a cell | | `rowReorder({ onEnd })` | `grid.rowReorder` | (`column` from `reorderColumn()` optional) | `onEnd(e)` saves (`e: { row, key, from, to, offset, prevKey, nextKey, rows }`; reject → revert), `handle` (column key), `orderKey`, `label(row)`, `messages`; events `beforeReorder` (cancelable), `reorder`, `reordererror` | | `autoRefresh()` | `grid.autoRefresh`: `running()`, `start()`, `stop()`, `tick()` | — | `every` (30000 ms, min 5000), `initial` (true), `toggle` (true: toolbar switch), `slot`, `order`, `messages` — silent reload keeping the page; skips hidden tabs, running loads, open panels, typing | | `filterPresets({ presets })` | `grid.filterPresets` | — | `presets: [{ id, label, values, default? }]`, `target` ("panel" | "grid"), `label`, `slot`, `order`, `messages` — named filter sets | | `multiSort()` | `grid.multiSort`: `toggle(key)` | — | `max` (3), `messages` — Shift+click / Shift+Enter adds a sort key, again flips, third time removes; rank badges; `laravelPaginator()` sends only the first key | | `columnFilters()` | — | — | `columns` (keys), `options` ({key:\[{value,label}]}), `messages` | | `filterPanel({ fields })` | `grid.filterPanel`: `values()`, `raw()`, `set(patch,{reload})`, `reset()`, `apply()` | — | `fields: { param: "#sel" \| el \| { el, value, unchecked, format(v,el), subscribe(el,notify) } }`, `auto` (true), `debounce` (250) | | `urlSync()` | `grid.urlSync`: `link()` | — | `keys`, `namespace` (string | true), `mode` ("replace" | "push") — `?q= &sort=-date &page= &f.=` | | `softDeletes()` | `grid.softDeletes`: `active()`, `toggle(on?)` | — | `param` ("\_deleted"), `value` (1), `field` (`deleted`/`deleted_at`), `label`, `initial`, `slot` ("end"), `order` (-10) | | `selection()` | `grid.selection`: `get()`, `keys()`, `payload()`, `count()`, `isAll()`, `isSelected(k)`, `select(k)`, `deselect(k)`, `toggle(k)`, `clear()`, `selectPage()`, `deselectPage()`, `selectAllMatching()` | `column.select()` | `mode` ("multi"|"single"), `acrossPages` (true), `selectAllMatching` (true), `label(row)`, `bulk: false \| { actions: [{ id, label, icon, tone, can, onClick(payload, grid, selection) }] }`, `messages` | | `actions({ items })` | `grid.actions`: `run(id,key)`, `open(key)`, `items(key)` | `column.actions()` | `items`, `inline` (2), `buttonGroup` (true: joined group, aligned rows), `sticky` ("end"|false), `field` (server permission map), `reasons`, `rowLabel(row)`, `messages`; enabled `href` items are real `` (plain click → confirm/beforeAction, modified/middle click native) | | `excel()` | `grid.excel`: `download()`, `blob()` | — | `filename`, `sheetName`, + export options | | `csv()` | `grid.csv`: `download()`, `text()` | — | `filename`, `delimiter` (";" for tr, else ","), `bom` (true), + export options | | `print()` | `grid.print`: `open()` | — | `title`, + export options | | `footer({ cols })` | `grid.footer`: `values()`, `refresh()` | — | `cols: { key: "sum"\|"avg"\|"count"\|(rows, raw, grid) => v }`, `label`, `scope` ("page"|"response"), `messages` | | `metaBind(bindings, opts)` | `grid.metaBind`: `refresh()` | — | bindings `{ "#sel": "summary.total" \| (raw, grid) => v \| { value, format } }`; opts `format` ("text"|"money"|"number"|fn), `currency`, `decimals`, `empty` ("—"), `root` | | `button.reload()` | `grid.reloadButton.el` | — | `label`, `silent`, `slot`, `order` (20) | | `button.resetState()` | `grid.resetStateButton.el` | `stateSave()` | `label`, `slot`, `order` (30) | | `button.custom({ label, onClick })` | `grid[name].el` | — | `name` (API key, default `button`), `icon`, `iconOnly`, `variant` ("primary"|"ghost"), `slot`, `order` (50), `disabled(rawResponse)` re-evaluated after each server response (not before the first one; never on array/DOM grids) | | `button.group({ label, items })` | `grid[name].el` | — | toolbar menu; `items: [{ id, label, icon, can, onClick(grid) }]`, `name`, `icon`, `slot`, `order` | Export options (excel/csv/print): `scope: "page"|"all"` (default: client all, server page; server "all" = one request ≤ maxPageSize + truncation notice), `footer` (include `
// server-side export of the current query location.href = "/agents/export?" + new URLSearchParams({ q: JSON.stringify(grid.query()) }); ``` ## DataTables → datagrids (most used) | DataTables 1.10 / 2.x / 3.x | datagrids | |---|---| | `$('#t').DataTable({...})` / `new DataTable('#t', {...})` | `new Datagrid('#t', { columns, use: [...] })` | | `$('#t').DataTable()` (accessor) | `Datagrid.get('#t')` (null if none — never creates) | | `serverSide: true, ajax: { url, type:'POST', data }` | `serverSide({ url, protocol: yajra() /* or ssp({ data }) */, params })` | | `ajax.data: function (d) { d.x = … }` | `params: () => ({ x: … })` or `ssp({ data: (d) => { d.x = … } })` | | `ajax.dataSrc` | `ssp({ dataSrc })` | | `data: [...]` | `data: [...]` | | `columns[].data / name / title / visible / searchable / className / defaultContent` | same names on the column | | `columns[].orderable` | `sortable` | | `columns[].render` | `render(value, row, ctx)` or a typed `column.*` | | `order: [[3,'desc']]` | `sort: [["key","desc"]]` (by key) | | `pageLength`, `lengthMenu` | `pageSize`, `pageSizes` | | `paging: false` / `searching: false` | `paging: false` / `search: false` | | `searchDelay` | `search: { delay }` | | `dom` / `layout` / `buttons` | toolbar slots + modules (`colVis()`, `excel()`, `button.reload()`) | | `stateSave` + `stateSaveParams` | `stateSave()` (search/page not saved by default) | | `stateDuration` | `stateSave({ ttl })` | | `deferLoading` | `load: "manual"` / `"visible"` | | `createdRow` / `rowCallback` | `rowClass`, `rowAttrs`, `rowTone`, or a module `ctx.row` | | `drawCallback` / `initComplete` | `on("render")` / `on("init")` | | `footerCallback` | `footer({ cols })` | | `select` extension | `selection()` + `column.select()` | | `colReorder` | `colReorder()` | | `responsive` | `responsive()` (detail rows, `collapse` event) | | `fixedHeader` | `stickyHeader()` (or `maxHeight` + CSS sticky) | | `keys` (KeyTable) | `keyboardGrid()` | | `rowReorder` / `row-reorder.dt` | `rowReorder({ onEnd })` / `reorder` event | | `buttons: [{ text, action }]` / `extend: 'collection'` | `button.custom({ label, onClick })` / `button.group({ label, items })` | | `language` | `messages` + `en` / `tr` packs | | `$.fn.dataTable.defaults` | `configure()` + presets | | `$.fn.dataTable.ext.errMode` / `error.dt` | per grid `errorMode` + `on("error")` | | `xhr.dt` / `preXhr.dt` | `on("response")` / request middleware, `on("beforeLoad")` | | `.ajax.reload(null, false)` | `grid.reload({ keepPage: true })` | | `.ajax.json()` / `.ajax.params()` | `grid.lastResponse()` / `grid.lastRequestParams()` (page params sent) + `grid.query()` (neutral query) | | `.column(i).visible(b)` | `grid.setColumnVisible(key, b)` | | `.rows.add(a).draw()` / `.clear()` / `.row(x).remove()` | `addRows(a)` / `setData([])` / `removeRow(key)` | | `.state.clear()` | `grid.state.reset()` | | `$(document).on('click', '.x', …)` + `.row(tr).data()` | `grid.delegate("click", ".x", (e, { row }) => …)` | | `buttons: ['pdf']` | `print()` + browser "Save as PDF" | Not in v1: RowGroup, SearchPanes, SearchBuilder, Scroller, FixedColumns, child rows, header filter rows, copy, PDF, 1.9 server protocol (`sEcho`, `iDisplayStart`). ## Gotchas * Without `@akinozgen17/datagrids/css` the grid has no layout. * Give every grid `label` (or `labelledBy` / `
`), else DG002. * `Datagrid.get()` returns `null` before init; it never creates a grid. * One data source per grid: a chained `grid.use(source)` replaces the default one; a second explicit source throws DG008. * `remount()` re-creates the grid from its options plus every module chained later with `grid.use()`. * Plain strings render as text. HTML needs `column.html()`, `html: true`, or untyped columns with `yajra()`. * `column.text()` forces text even under `yajra()` and would show the server's entities (`&`): with `yajra()` write string columns as plain `{ key, title }`; typed money/date/badge columns are fine. * number/money/date format with the grid `locale` (money in TRY): pass `locale`/`currency` per column to differ. * number/money read data strings as machine numbers (`"1.500"` = 1.5); pass `source: "tr"` for formatted Turkish text. * `reload()` on array/DOM sources keeps `setData`/`addRows`/`removeRow` edits; `addRows` is ignored in server mode. * SSP endpoints receive `columns[]` in definition order, hidden included, even after reordering. * Inside tabs/modals use `load: "visible"`; there is no `columns.adjust()` (ResizeObserver handles it). * `selection()` needs `column.select()`; `actions()` needs `column.actions()`; `button.resetState()` needs `stateSave()`. * Session expiry fires `sessionexpired`; handle it once with `configure({ onSessionExpired })`. * Module definitions are immutable: create once, use on many grids; `serverSide(...).params(fn)` returns a new one. * `configure()`: most keys apply to grids created afterwards; `errorMode`, `maxPageSize`, `warnings` also reach existing grids. * ≥300 rows in one view switch to virtual rows (screen readers see rendered rows only); `virtual: false` opts out. ## Version & compatibility Pre-1.0 (`0.x`): breaking changes are still possible between minors. Browsers: Baseline 2024 (Popover API, `light-dark()`, relative color syntax) with a static light fallback. TypeScript ≥ 5.0 for consumers. Docs: https://akinozgen.github.io/datagrids/ · Warning codes: https://akinozgen.github.io/datagrids/errors/