Skip to content

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 appthe grid's methods and events (headless)
inside the grid's toolbar, next to its own controlsa small toolbar module that fills a slot

Your own controls, the grid's state ​

js
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
<div class="demo-form">
  <label>Search
    <input id="rcp-hl-q" type="search" placeholder="Name, unit…">
  </label>
  <label>Sort
    <select id="rcp-hl-sort">
      <option value="date:desc">Newest first</option>
      <option value="date:asc">Oldest first</option>
      <option value="name:asc">Name A–Z</option>
      <option value="amount:desc">Amount, high to low</option>
    </select>
  </label>
  <label>Rows
    <select id="rcp-hl-size">
      <option>5</option>
      <option selected>10</option>
      <option>25</option>
    </select>
  </label>
  <button type="button" id="rcp-hl-cols">Columns…</button>
</div>
<table id="rcp-headless"></table>
<pre class="demo-output" id="rcp-hl-log" aria-live="polite">Events appear here.</pre>

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 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 controlCall
    search fieldgrid.search("redfield") — debounce typing yourself (the demo waits 250 ms)
    sort dropdowngrid.sort([["amount", "desc"]]); grid.sort([]) clears it
    page sizegrid.pageSize(25) (capped by maxPageSize)
    page buttonsgrid.page(3)
    column choosergrid.colVis.open() (with the 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:

    EventDetail
    search{ search }
    sort{ sort: [{ key, dir }] }
    page{ page }
    pagesize{ pageSize }
    columnchange{ columns } — visibility or order changed
    loadafter 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 ​

js
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
<table id="rcp-toolbar-slots"></table>

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)];
SlotWhereBuilt-in items (order)
startleft, growssearch box (0), column menu (10), reload (20), reset state (30), export menu (40), custom buttons (50), button groups (60)
endrightauto-refresh toggle (−20), show deleted (−10), record count
filtersfull-width row under the toolbarfilter 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.

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 (<label> or aria-label). The grid still announces search results and page changes in its live region.

Released under the MIT License.