Skip to content

Subtotals, lazy loading, row heights and detail panels ​

These five features build on Tree, grouping and aggregation. They all ship in the hierarchy bundle. In a modular build, add features: [hierarchy] (Pick your features).

You want toUse
End every group with a subtotal rowgrouping.summary
Show child totals on tree parent rowstree.parentAggregates
Load children when a folder openstree.loadChildren
Give rows different heightsa function in rowHeight
Open more detail under a rowdetail

Add a subtotal row to each group ​

grouping.summary decides where the group totals appear.

ValueResult
'header' (default)Totals show on the group row only
'footer'A subtotal row ends each group, and the group row shows just a name
'both'Totals show on the group row and on the subtotal row
Live demo — drawn by the real renderer
  • A subtotal row hides when you collapse its group. A group that the filter empties has no subtotal either.
  • You cannot select or edit a subtotal row. It follows the same rule as the total row.
  • getDisplayRow(i) returns it as kind: 'summary' with scope: 'group', and groupKey holds the key of its group.
  • The first cell reads "group name Subtotal". Change the wording of the numbers with aggregateFormat(value, ctx). ctx.scope is 'group' on the group row and the subtotal row, and 'total' on the grand total.
  • setGroupBy keeps the summary mode.

Show child totals on tree parents ​

A tree parent shows its own value by default. With tree.parentAggregates: true, the aggregate columns of every parent that has children show the total of its descendants. Leaf rows keep their own values.

Live demo — drawn by the real renderer
  • Put aggregate on the columns you want to total. To count a parent's own value too, use aggregate: { fn: 'sum', includeSelf: true }.
  • The hierarchy column and columns with a cellRenderer stay as they are. You can also read the values from getDisplayRow(i).aggregates.

Load children when a folder opens ​

tree.loadChildren runs once when you open a folder that has no children yet. Use it with hasChildren. The tree starts fully collapsed, because expandDepth defaults to 0 here.

ts
tree: {
  parentKey: 'parentId',
  hasChildren: (row) => row.folder,
  loadChildren: async (row, { key, signal }) => {
    const response = await fetch(`/api/folders/${key}`, { signal });
    return response.json(); // each row's parentId must equal key
  },
},
Live demo — drawn by the real renderer
  • The rows you return go in through the same path as addRows. A duplicate key fails the load and leaves the data untouched.
  • While loading, the toggle shows … and the row gets aria-busy. getDisplayRow(i).loadState is 'loading'.
  • Closing the folder aborts signal and the grid drops a late answer. setRows and destroy cancel pending requests too.
  • A failure turns the toggle into ⚠ and sends an error event with the code children-load-failed. Close and open the folder to try again.
  • Return an empty array and the toggle disappears.
  • Follow progress with the childrenLoadChanged event (loading, loaded, error, cancelled).

Limits: expandAll(), expandToDepth() and rows that start open do not load anything, so a bulk open cannot flood your server. Server-side sorting and aggregation are not supported yet.

Give rows different heights ​

Pass a function instead of a number to rowHeight to size each data row.

ts
rowHeight: (row) => (row.priority === 'high' ? 64 : 32),
Live demo — drawn by the real renderer
  • Group rows and the total row keep the default 32px.
  • If the function returns a non-number (or less than 1) or throws, the row is 32px and the grid sends one error event (callback-error).
  • The height is the value you declare. The grid does not measure content.
  • Heights are recalculated when the rows change. If the function reads an outside value, change that value and then call api.refresh().
  • The function runs once per line, so keep it cheap.

Open a detail panel under a row ​

With detail, each master row gets a ▸ button. It opens one panel line right under that row.

ts
detail: {
  renderer: () => ({
    mount(element, { row }) { element.textContent = `Order ${row.id}`; },
    update({ row }) { /* runs when the master row changes */ },
    destroy() { /* clean up listeners and timers */ },
  }),
  height: (row) => 56 + row.items * 22,
  canExpand: (row) => row.items > 0,
  expanded: [1001],
},
Live demo — drawn by the real renderer
OptionDefaultMeaning
rendererrequiredA function that creates the panel adapter, like a cell renderer
height160Panel height in px, or (row) => height
columnfirst visibleThe column that holds the ▸ button
expandednoneKeys of master rows that start open
canExpandall rowsRows that return false get no button
  • The API is expandDetail(key), collapseDetail(key), toggleDetail(key) and isDetailExpanded(key). An unknown key, or a row that canExpand refuses, throws invalid-option. A change sends a detailChanged event.
  • Press Alt+↓ to open and Alt+↑ to close. On a detail line, Alt+↑ closes its master row.
  • Only master rows take part in sorting, filtering, grouping and trees. A panel follows its master. A row inside a collapsed tree parent or a closed group shows no panel. With pagination, a master and its panel never land on different pages.
  • A detail line is not selectable or editable, and it is left out of exports, aggregates and getVisibleRows().
  • A panel is destroyed when it scrolls out of view and mounted again when it returns. Keep input state outside the adapter if you need it back.
  • Keys and clicks inside a panel do not reach the grid, so typing in an input does not move or select grid rows.
  • If the adapter throws, only that panel shows an error and the grid keeps working.

Keep panels, lock on unsaved edits, fill keys, save per master row ​

Since 1.6.0

The options and APIs below were added in 1.6.0. Unused, nothing changes.

These extensions are for screens that put a grid or a form inside the detail panel (an order and its lines). All of them go inside the detail option.

OptionDefaultMeaning
keepAlivefalseKeeps panels that were collapsed or scrolled away instead of destroying them. Re-expanding reuses the same element and adapter, so typed input and the inner grid's scroll and sort stay
maxKeepAlive20How many panels to keep. Beyond that the oldest is destroyed
dirtyLockfalsetrue blocks changing the master's sort, filter, page or grouping while a detail has unsaved edits. Use { sort, filter, page, group } to pick
isDirtynone(rowKey) => boolean. Lets a detail that is not a grid, such as a form, report unsaved values
keyFillnoneFills the empty foreign key of rows newly added in a detail grid from the master: { orderId: 'id' } (detail field: master field) or (masterRow) => ({ ... })
splitSavenone{ save({ masterRow, rowKey, changes }) }. saveDetails() calls it for each master row

Attach the grid inside the panel to its master row so change tracking, dirtyLock, keyFill and splitSave know about it. In the adapter's mount, call attachGrid(grid) on the context (same as api.attachDetailGrid(rowKey, grid)).

ts
detail: {
  keepAlive: true,
  dirtyLock: true,
  keyFill: { orderId: 'id' },
  splitSave: {
    async save({ masterRow, changes }) {
      await fetch(`/api/orders/${masterRow.id}/lines`, { method: 'PUT', body: JSON.stringify(changes) });
    },
  },
  renderer: () => {
    let grid;
    return {
      mount(element, ctx) {
        grid = createGrid(element, { columns, rows: linesOf(ctx.row), rowKey: 'id', saveMode: 'batch' });
        ctx.attachGrid(grid); // once attached, the master sees this grid's changes
      },
      update() {},
      destroy() { grid.destroy(); },
    };
  },
},
  • getDetailState(key) returns { expanded, mounted, dirty }. mounted includes kept panels.
  • destroyDetail(key) destroys that row's panel (kept ones too). If the row is expanded it is built again from scratch.
  • When dirtyLock blocks a change it emits detailDirtyBlocked { rowKeys, action }; show a message there. The check runs at beforeSort, beforeFilter, beforePageChange and beforeGroup, before your own hooks.
  • saveDetails(key?) without a key saves every row that has unsaved edits. On success it clears that grid's change marks and emits detailSaved; on failure it keeps the marks and emits detailSaveFailed. The result is { saved, failed }.
  • An unknown key, or calling it without splitSave, throws invalid-option.

Change the expand icons ​

Expand buttons on trees, group rows and detail panels are arrows (▸ ▾) by default. Use toggleIcon to change them. It works the same on tree.toggleIcon, grouping.toggleIcon and detail.toggleIcon.

ValueCollapsedExpandedLeaf (no children)
'arrow' (default)▸▾empty slot
'folder'closed folderopen folderfile
'plusMinus'+−empty slot
'plusMinusCircle'⊕⊖empty slot
Live demo — drawn by the real renderer

Pass an object to override a few parts of a set.

ts
tree: {
  parentKey: 'parentId',
  toggleIcon: { preset: 'folder', leaf: false },          // turn the leaf icon off
},
// Your own: a character, an emoji, an SVG string or a CSS class name (`folder` and `plusMinusCircle` are SVG)
toggleIcon: { expanded: '🟢', collapsed: '⚪', leaf: '·' },
toggleIcon: { expanded: { svg: '<svg viewBox="0 0 10 10">…</svg>' }, collapsed: { className: 'my-closed' } },
Live demo — drawn by the real renderer
  • One icon is a string (1 to 16 characters), { text }, { className } or { svg }. Giving two at once throws invalid-option.
  • Values are never parsed as HTML. A string goes in as text, and className only sets the class of an empty <span>. A class name takes letters, digits, - and _.
  • An SVG string must start with <svg> and be at most 4000 characters. The grid reads it as XML and keeps only svg, g, path, circle, ellipse, rect, line, polyline, polygon and their shape attributes. Scripts, event handlers, style, href and url(...) are dropped. An SVG that cannot be read leaves the slot empty. Use fill="currentColor" to follow the text color.
  • Change color and size with the CSS variables --mxg-toggle-color and --mxg-toggle-size. Without them the button follows the surrounding text color and size, so it fits the dark theme and all three densities. The folder and circled plus/minus sets are SVG, so they look the same on every operating system and follow the text color. A closed folder is drawn filled and an open one with its lid raised.
  • Icons are aria-hidden. The row's aria-expanded carries the state.
  • The loading (…) and failed (⚠) markers stay the same in every set.
  • leaf does not apply to group rows.
Live demo — drawn by the real renderer

Indent guides ​

Rows under a tree or a group get guide lines. The default is branches: each node hangs off its parent with a ├ or └ line, and a column keeps its vertical line while the parent still has siblings below. The vertical line ends at └ for the last child, and a column whose ancestor was a last child stays empty. The line runs right up to the expand icon.

ValueLook
'dotted' (default)Dotted line
'solid'Solid line
falseNo guides
guideStyle valueLook
'branch' (default)├ └ branches plus continuing vertical lines
'vertical'Vertical lines only, in every depth column
ts
tree: { parentKey: 'parentId', guides: 'solid' },
tree: { parentKey: 'parentId', guideStyle: 'vertical' },
grouping: { by: ['region'], guides: false },
Live demo — drawn by the real renderer

Use the folder icons and branch lines together to get an org chart like this.

Live demo — drawn by the real renderer
  • Use the same options on tree.guides, tree.guideStyle, grouping.guides and grouping.guideStyle. Any other value throws invalid-option. With guides: false, guideStyle is ignored.
  • Change the color with --mxg-guide-color and the thickness with --mxg-guide-width. The default color keeps at least 3:1 against the background in the light and dark themes. The column width is --mxg-indent (16px by default).
  • Each indent column gets one <span> that fills the cell height and is drawn with CSS borders. The lines stay joined to the rows above and below when row heights differ, and it works with virtual scrolling. 'vertical' adds no nodes.
  • The theme CSS (@maxgrid/themes or maxgrid.css) must be loaded to draw it.
  • Total rows, subtotal rows and detail panel lines have no guides, so the line pauses on them. A hierarchy column with a cellRenderer has none either.

Tree queries and options ​

With tree on you can ask for a row's family from code. Every call reads the whole data, including collapsed rows. Without tree, or with an unknown key, it throws invalid-option.

MethodReturns
getAncestors(key)Ancestor keys, root first, parent last
getDescendants(key)Descendant keys, depth-first in data order
getDepth(key)Depth; a top-level row is 0
getParentRow(key)The parent row, or null for a top-level row
isBranch(key)Whether it has children, counting lazy rows announced by hasChildren
getTreeRows({ filtered? })Nested { key, row, children }; filtered keeps only rows that pass the filter plus their ancestors
getMaxDepth()The depth of the deepest row
isChildrenLoaded(key)true, false, 'loading' or 'error'; rows without lazy loading are true
resetChildren(key)Drop the loaded child rows and collapse, so they can load again

addRows(rows, { parent, index }) sets the parent field of the new rows to parent (a row key, or null for the top level) and reads index as the position among that parent's children. It only works when tree.parentKey is a field name.

OptionDefaultWhat it does
tree.expandRecursivefalseExpanding spreads to all descendants; collapsing affects only that row
tree.checkCascadefalseSelecting selects the descendants, deselecting deselects them. With checkboxes a parent shows a mixed state when only some descendants are selected
tree.expandWhen(row, level)noneInitial expansion per row; an answer that is not true or false follows expandDepth

expandWhen is asked once, when a row first appears. What the user expanded or collapsed always wins, and a throwing callback is reported as error (callback-error) while that row follows expandDepth. See Tree and grouping for more.

Not available yet ​

  • Measuring panel height from its content, and moving keyboard focus into a panel with Enter and back with Esc.
  • Server-side sorting and aggregation, and block-based lazy loading.
  • Using a tree and grouping together, pivoting, and dragging tree nodes.