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 to | Use |
|---|---|
| End every group with a subtotal row | grouping.summary |
| Show child totals on tree parent rows | tree.parentAggregates |
| Load children when a folder opens | tree.loadChildren |
| Give rows different heights | a function in rowHeight |
| Open more detail under a row | detail |
Add a subtotal row to each group
grouping.summary decides where the group totals appear.
| Value | Result |
|---|---|
'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 |
- 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 askind: 'summary'withscope: 'group', andgroupKeyholds the key of its group.- The first cell reads "group name Subtotal". Change the wording of the numbers with
aggregateFormat(value, ctx).ctx.scopeis'group'on the group row and the subtotal row, and'total'on the grand total. setGroupBykeeps 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.
- Put
aggregateon the columns you want to total. To count a parent's own value too, useaggregate: { fn: 'sum', includeSelf: true }. - The hierarchy column and columns with a
cellRendererstay as they are. You can also read the values fromgetDisplayRow(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.
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
},
},- 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 getsaria-busy.getDisplayRow(i).loadStateis'loading'. - Closing the folder aborts
signaland the grid drops a late answer.setRowsanddestroycancel pending requests too. - A failure turns the toggle into
⚠and sends anerrorevent with the codechildren-load-failed. Close and open the folder to try again. - Return an empty array and the toggle disappears.
- Follow progress with the
childrenLoadChangedevent (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.
rowHeight: (row) => (row.priority === 'high' ? 64 : 32),- 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
errorevent (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.
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],
},| Option | Default | Meaning |
|---|---|---|
renderer | required | A function that creates the panel adapter, like a cell renderer |
height | 160 | Panel height in px, or (row) => height |
column | first visible | The column that holds the ▸ button |
expanded | none | Keys of master rows that start open |
canExpand | all rows | Rows that return false get no button |
- The API is
expandDetail(key),collapseDetail(key),toggleDetail(key)andisDetailExpanded(key). An unknown key, or a row thatcanExpandrefuses, throwsinvalid-option. A change sends adetailChangedevent. - Press
Alt+↓to open andAlt+↑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.
| Option | Default | Meaning |
|---|---|---|
keepAlive | false | Keeps 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 |
maxKeepAlive | 20 | How many panels to keep. Beyond that the oldest is destroyed |
dirtyLock | false | true blocks changing the master's sort, filter, page or grouping while a detail has unsaved edits. Use { sort, filter, page, group } to pick |
isDirty | none | (rowKey) => boolean. Lets a detail that is not a grid, such as a form, report unsaved values |
keyFill | none | Fills the empty foreign key of rows newly added in a detail grid from the master: { orderId: 'id' } (detail field: master field) or (masterRow) => ({ ... }) |
splitSave | none | { 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)).
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 }.mountedincludes kept panels.destroyDetail(key)destroys that row's panel (kept ones too). If the row is expanded it is built again from scratch.- When
dirtyLockblocks a change it emitsdetailDirtyBlocked { rowKeys, action }; show a message there. The check runs atbeforeSort,beforeFilter,beforePageChangeandbeforeGroup, 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 emitsdetailSaved; on failure it keeps the marks and emitsdetailSaveFailed. The result is{ saved, failed }.- An unknown key, or calling it without
splitSave, throwsinvalid-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.
| Value | Collapsed | Expanded | Leaf (no children) |
|---|---|---|---|
'arrow' (default) | ▸ | ▾ | empty slot |
'folder' | closed folder | open folder | file |
'plusMinus' | + | − | empty slot |
'plusMinusCircle' | ⊕ | ⊖ | empty slot |
Pass an object to override a few parts of a set.
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' } },- One icon is a string (1 to 16 characters),
{ text },{ className }or{ svg }. Giving two at once throwsinvalid-option. - Values are never parsed as HTML. A string goes in as text, and
classNameonly 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 onlysvg,g,path,circle,ellipse,rect,line,polyline,polygonand their shape attributes. Scripts, event handlers,style,hrefandurl(...)are dropped. An SVG that cannot be read leaves the slot empty. Usefill="currentColor"to follow the text color. - Change color and size with the CSS variables
--mxg-toggle-colorand--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'saria-expandedcarries the state. - The loading (
…) and failed (⚠) markers stay the same in every set. leafdoes not apply to group rows.
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.
| Value | Look |
|---|---|
'dotted' (default) | Dotted line |
'solid' | Solid line |
false | No guides |
guideStyle value | Look |
|---|---|
'branch' (default) | ├ └ branches plus continuing vertical lines |
'vertical' | Vertical lines only, in every depth column |
tree: { parentKey: 'parentId', guides: 'solid' },
tree: { parentKey: 'parentId', guideStyle: 'vertical' },
grouping: { by: ['region'], guides: false },Use the folder icons and branch lines together to get an org chart like this.
- Use the same options on
tree.guides,tree.guideStyle,grouping.guidesandgrouping.guideStyle. Any other value throwsinvalid-option. Withguides: false,guideStyleis ignored. - Change the color with
--mxg-guide-colorand 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/themesormaxgrid.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
cellRendererhas 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.
| Method | Returns |
|---|---|
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.
| Option | Default | What it does |
|---|---|---|
tree.expandRecursive | false | Expanding spreads to all descendants; collapsing affects only that row |
tree.checkCascade | false | Selecting selects the descendants, deselecting deselects them. With checkboxes a parent shows a mixed state when only some descendants are selected |
tree.expandWhen(row, level) | none | Initial 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.
- For the group panel and group display modes (
groupPanel,grouping.hideColumns,hideRows,merged) see Group panel and group display modes.
Not available yet
- Measuring panel height from its content, and moving keyboard focus into a panel with
Enterand back withEsc. - Server-side sorting and aggregation, and block-based lazy loading.
- Using a tree and grouping together, pivoting, and dragging tree nodes.