Skip to content

Commit 4ff56df

Browse files
alistair3149claude
andauthored
feat: CSV export button (csvExport option) (#87)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 0947129 commit 4ff56df

16 files changed

Lines changed: 711 additions & 48 deletions

File tree

‎docs/authoring-grids.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,25 @@ Pass a table to override the button's label:
7272
expand = { label = 'Open full width' },
7373
```
7474

75+
## Downloading as CSV
76+
77+
Set `csvExport = true` to add a button that downloads the grid's rows as a CSV file, named after
78+
the page by default. Pass a table to override the button's label:
79+
80+
```lua
81+
csvExport = { label = 'Download data' },
82+
```
83+
84+
- Columns with a [`format`](formatting.md) spec export their raw values, such as `27` and
85+
`2024-03-09`, rather than `27 kg` and `Mar 9, 2024`.
86+
- Text starting with `=`, `+`, `-` or `@` is exported with a leading `'`, so that spreadsheet
87+
applications do not run it as a formula.
88+
- To change the file name, column separator, and similar settings, set AG Grid's
89+
[`defaultCsvExportParams`](https://www.ag-grid.com/javascript-data-grid/csv-export/) option.
90+
Its `suppressQuotes`, `prependContent` and `appendContent` settings are ignored.
91+
92+
CSV export is not available on [backend source grids](data-sources.md).
93+
7594
## Limits
7695

7796
Inline `rowData` is capped at **5,000 rows**. For larger datasets, use a
@@ -88,6 +107,7 @@ Beyond AG Grid's own options, `gridOptions` accepts these additional ones:
88107

89108
| Option | Type | Default | Description |
90109
| --- | --- | --- | --- |
110+
| `csvExport` | boolean \| table | `false` | [CSV download button](#downloading-as-csv). `{ label = '…' }` overrides its label. |
91111
| `expand` | boolean \| table | `false` | Full-window view button. `{ label = '…' }` overrides its label. |
92112
| `quickSearch` | boolean \| table | `false` | [Quick-search box](filters.md). `{ placeholder = '…', debounceMs = 300 }`. |
93113

‎docs/data-sources.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ filters (set filters and number filters) still work.
173173
| `filterProp` facet | ✅ | — |
174174
| Paging with whole-result-set totals | ✅ | ✅ |
175175
| [`format`](formatting.md) specs | ✅ | ✅ |
176+
| [CSV export](authoring-grids.md#downloading-as-csv) | ❌ | ❌ |
176177

177178
On saved pages the rows are served from a cacheable REST endpoint, so a source grid adds no
178179
weight to the page HTML itself.

‎extension.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@
115115
"ext.aggrid/setFilter.js",
116116
"ext.aggrid/quickSearch.js",
117117
"ext.aggrid/toolbar.js",
118+
"ext.aggrid/csvExport.js",
118119
"ext.aggrid/expand.js",
119120
{
120121
"name": "ext.aggrid/bundle.json",
@@ -136,6 +137,7 @@
136137
"aggrid-setfilter-values-error",
137138
"aggrid-quicksearch-placeholder",
138139
"aggrid-quicksearch-label",
140+
"aggrid-csvexport-label",
139141
"aggrid-expand-label",
140142
"aggrid-expand-collapse-label",
141143
"aggrid-expand-dialog-label"

‎i18n/en.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"aggrid-setfilter-values-error": "Could not load filter values.",
1717
"aggrid-quicksearch-placeholder": "Search…",
1818
"aggrid-quicksearch-label": "Search the table",
19+
"aggrid-csvexport-label": "Download as CSV",
1920
"aggrid-expand-label": "Expand table",
2021
"aggrid-expand-collapse-label": "Collapse table",
2122
"aggrid-expand-dialog-label": "Expanded table view"

‎i18n/qqq.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"aggrid-setfilter-values-error": "Error message shown in the set filter popup when fetching the list of values from the server failed.",
1717
"aggrid-quicksearch-placeholder": "Placeholder text in the quick-search box shown above a data grid when the page author enables the quickSearch grid option. Typing in the box filters the grid's rows across all columns.",
1818
"aggrid-quicksearch-label": "ARIA label (for screen readers) of the quick-search input shown above a data grid when the page author enables the quickSearch grid option.",
19+
"aggrid-csvexport-label": "Accessible name and tooltip of the button that downloads a data grid's rows as a CSV (comma-separated values) file, shown above the grid when the page author enables the csvExport grid option.",
1920
"aggrid-expand-label": "Accessible name and tooltip of the button that opens a data grid in a full-window view, shown above the grid when the page author enables the expand grid option. Used while the grid is not expanded. See also {{msg-mw|aggrid-expand-collapse-label}}.",
2021
"aggrid-expand-collapse-label": "Accessible name and tooltip of the same button once the grid is expanded, when pressing it returns the grid to the page. See also {{msg-mw|aggrid-expand-label}}.",
2122
"aggrid-expand-dialog-label": "Accessible name of the dialog holding the expanded data grid, announced by screen readers when it opens."

‎includes/Scribunto/LuaLibrary.php‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ public function render( $gridOptions = null ): array {
4848
$this->checkType( 'mw.ext.aggrid.render', 1, $gridOptions, 'table' );
4949

5050
$this->validateQuickSearch( $gridOptions['quickSearch'] ?? null );
51-
$this->validateExpand( $gridOptions['expand'] ?? null );
51+
$this->validateButtonOption( 'expand', $gridOptions['expand'] ?? null );
52+
$this->validateButtonOption( 'csvExport', $gridOptions['csvExport'] ?? null );
5253

5354
// A `source` descriptor routes to the backend path (query stored, not rows).
5455
if ( isset( $gridOptions['source'] ) ) {
@@ -148,33 +149,35 @@ private function validateQuickSearch( $quickSearch ): void {
148149
}
149150

150151
/**
151-
* Validate the expand gridOption: boolean, or a table with an optional `label`
152-
* (string) key. Unknown keys are rejected to catch typos, and an invalid shape
153-
* throws rather than being gated away — see validateQuickSearch. An empty table is
154-
* indistinguishable from an empty list and is allowed (the client reads it as true).
152+
* Validate a toolbar-button gridOption (expand, csvExport): boolean, or a table with
153+
* an optional `label` (string) key. Unknown keys are rejected to catch typos, and an
154+
* invalid shape throws rather than being gated away — see validateQuickSearch. An
155+
* empty table is indistinguishable from an empty list and is allowed (the client
156+
* reads it as true).
155157
*
156-
* @param mixed $expand
158+
* @param string $option The gridOption's name, for the error message.
159+
* @param mixed $value
157160
* @throws LuaError If the shape is invalid.
158161
*/
159-
private function validateExpand( $expand ): void {
160-
if ( $expand === null || is_bool( $expand ) ) {
162+
private function validateButtonOption( string $option, $value ): void {
163+
if ( $value === null || is_bool( $value ) ) {
161164
return;
162165
}
163-
if ( !is_array( $expand ) ) {
166+
if ( !is_array( $value ) ) {
164167
throw new LuaError(
165-
'mw.ext.aggrid.render: expand must be a boolean or a table'
168+
"mw.ext.aggrid.render: $option must be a boolean or a table"
166169
);
167170
}
168-
foreach ( $expand as $key => $value ) {
171+
foreach ( $value as $key => $item ) {
169172
if ( $key === 'label' ) {
170-
if ( !is_string( $value ) ) {
173+
if ( !is_string( $item ) ) {
171174
throw new LuaError(
172-
'mw.ext.aggrid.render: expand.label must be a string'
175+
"mw.ext.aggrid.render: $option.label must be a string"
173176
);
174177
}
175178
} else {
176179
throw new LuaError(
177-
'mw.ext.aggrid.render: unknown expand key "' . $key . '"'
180+
"mw.ext.aggrid.render: unknown $option key \"$key\""
178181
);
179182
}
180183
}
@@ -225,6 +228,9 @@ private function renderSource( array $gridOptions ): array {
225228
// would be inert — drop it rather than render a dead control.
226229
unset( $viewConfig['quickSearch'] );
227230
}
231+
// The Infinite Row Model exports only the blocks it has loaded: a partial file
232+
// that looks complete.
233+
unset( $viewConfig['csvExport'] );
228234

229235
$parser = $this->getParser();
230236
$parserOutput = $parser->getOutput();

‎includes/Scribunto/mw.ext.aggrid.lua‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ end
6060
--- because Bucket's query language has no LIKE operator.
6161
---
6262
--- The extension also understands these non-AG-Grid gridOptions:
63+
--- * csvExport boolean|table @opt-in button in the grid's toolbar that downloads
64+
--- the rows as a CSV file named after the page. `true` enables it with
65+
--- an i18n label; a table overrides: { label = 'Download data' }.
66+
--- Columns with a `format` spec export their raw values. Set AG Grid's
67+
--- own `defaultCsvExportParams` for the file name, separator, etc.
68+
--- Works on inline grids; ignored on `source` grids.
6369
--- * expand boolean|table @opt-in button in the grid's toolbar that opens the
6470
--- grid in a full-window view, for wide grids in a narrow content
6571
--- column. `true` enables it with an i18n label; a table overrides:

‎modules/ext.aggrid/csvExport.js‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// The export defaults go on gridOptions.defaultCsvExportParams, not on the button's call,
2+
// so a gadget calling api.exportDataAsCsv() gets them too. Params passed to that call still
3+
// override them (gadget code is trusted); the author's defaultCsvExportParams from Lua is
4+
// not, and cannot switch the formula guard off.
5+
6+
const { setClass, normalizeButtonOption } = require( './toolbar.js' );
7+
8+
// AG Grid's list of leading characters a spreadsheet runs as a formula, plus line feed
9+
// (OWASP). Prefixed with an apostrophe, not OWASP's tab: tab is itself on AG Grid's list.
10+
const FORMULA_START = /^[=+\-@\t\r\n]/;
11+
12+
const UNSAFE_FILE_CHARS = /[\\/:*?"<>|]/g;
13+
14+
// Unquoted, a newline or separator inside a cell starts a new, unchecked cell; prepended
15+
// and appended content is written out verbatim.
16+
const UNSAFE_AUTHOR_KEYS = [ 'suppressQuotes', 'prependContent', 'appendContent' ];
17+
18+
/**
19+
* @param {*} value
20+
* @return {*}
21+
*/
22+
function neutralize( value ) {
23+
return typeof value === 'string' && FORMULA_START.test( value ) ? `'${ value }` : value;
24+
}
25+
26+
/**
27+
* @param {Object} params AG Grid ProcessCellForExportParams.
28+
* @return {*}
29+
*/
30+
function processCell( params ) {
31+
const value = params.value;
32+
if ( params.column.getColDef().useValueFormatterForExport === false ) {
33+
return neutralize( value );
34+
}
35+
const text = params.formatValue( value );
36+
// AG Grid infers a formatter for a plain column that only stringifies (-5 → "-5",
37+
// ['a','b'] → "a,b"): keep such a number a number and join such an array. A column
38+
// type's own formatter is used as it is.
39+
if ( String( text ) === String( value ) ) {
40+
if ( typeof value === 'number' ) {
41+
return value;
42+
}
43+
if ( Array.isArray( value ) ) {
44+
return neutralize( value.join( ', ' ) );
45+
}
46+
}
47+
return neutralize( text );
48+
}
49+
50+
/**
51+
* The export defaults for a grid on the given page.
52+
*
53+
* @param {string|null} pageTitle wgTitle; names the downloaded file.
54+
* @param {*} [authorParams] The author's defaultCsvExportParams, from the placeholder JSON.
55+
* @return {Object} CsvExportParams for gridOptions.defaultCsvExportParams.
56+
*/
57+
function defaultParams( pageTitle, authorParams ) {
58+
const params = {};
59+
if ( pageTitle ) {
60+
// AG Grid appends the extension only to a name with no dot in it.
61+
params.fileName = `${ pageTitle.replace( UNSAFE_FILE_CHARS, '_' ) }.csv`;
62+
}
63+
if ( authorParams && typeof authorParams === 'object' && !Array.isArray( authorParams ) ) {
64+
Object.assign( params, authorParams );
65+
UNSAFE_AUTHOR_KEYS.forEach( ( key ) => delete params[ key ] );
66+
}
67+
// Last: from Lua, the author's callbacks can only be non-functions, which would switch
68+
// the guard off or break the export.
69+
return Object.assign( params, {
70+
processCellCallback: processCell,
71+
// The locations AG Grid's own export reads header names with.
72+
processHeaderCallback: ( p ) => neutralize(
73+
p.api.getDisplayNameForColumn( p.column, 'csv' )
74+
),
75+
processGroupHeaderCallback: ( p ) => neutralize(
76+
p.api.getDisplayNameForColumnGroup( p.columnGroup, 'header' )
77+
)
78+
} );
79+
}
80+
81+
/**
82+
* Build the export button.
83+
*
84+
* @param {Object} api The AG Grid GridApi.
85+
* @param {Object} config Normalized config from normalizeButtonOption().
86+
* @return {HTMLElement} The toolbar item.
87+
*/
88+
function buildItem( api, config ) {
89+
const item = setClass( document.createElement( 'div' ),
90+
'ag-toolbar-item ag-toolbar-button-wrapper ext-aggrid-toolbar__item' );
91+
const button = setClass( document.createElement( 'button' ),
92+
'ag-toolbar-button ext-aggrid-toolbar__button' );
93+
button.type = 'button';
94+
const label = config.label || mw.msg( 'aggrid-csvexport-label' );
95+
button.setAttribute( 'aria-label', label );
96+
button.setAttribute( 'title', label );
97+
const icon = setClass( document.createElement( 'span' ), 'ag-icon ag-icon-csv' );
98+
icon.setAttribute( 'aria-hidden', 'true' );
99+
button.appendChild( icon );
100+
// No params: they would override the author's defaultCsvExportParams.
101+
button.addEventListener( 'click', () => api.exportDataAsCsv() );
102+
item.appendChild( button );
103+
return item;
104+
}
105+
106+
module.exports = { normalize: normalizeButtonOption, defaultParams, buildItem };

‎modules/ext.aggrid/expand.js‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// The grid's CHILDREN move into the dialog, not the .ext-aggrid placeholder, which stays
1010
// in flow carrying whatever height the wiki gave it.
1111

12-
const { setClass } = require( './toolbar.js' );
12+
const { setClass, normalizeButtonOption } = require( './toolbar.js' );
1313

1414
const DIALOG_CLASS = 'ext-aggrid-expand';
1515
const ROOT_CLASS = 'ext-aggrid-expand-root';
@@ -68,26 +68,6 @@ const openStates = new Set();
6868

6969
let overlayRoot = null;
7070

71-
/**
72-
* Normalize the author's expand gridOption into a config, or null when disabled.
73-
*
74-
* Accepted: true; { label? }; and [], an empty Lua table arriving as a JSON array.
75-
* Anything else disables the button — LuaLibrary rejects bad shapes at parse time, but
76-
* parser-cache entries can predate that validation, so this stays defensive.
77-
*
78-
* @param {*} raw gridOptions.expand as parsed from the placeholder JSON.
79-
* @return {Object|null} { label: string|null } or null.
80-
*/
81-
function normalize( raw ) {
82-
if ( raw === true || ( Array.isArray( raw ) && raw.length === 0 ) ) {
83-
return { label: null };
84-
}
85-
if ( !raw || typeof raw !== 'object' || Array.isArray( raw ) ) {
86-
return null;
87-
}
88-
return { label: typeof raw.label === 'string' ? raw.label : null };
89-
}
90-
9171
/**
9272
* Whether this browser can show a modal dialog. Where it cannot, no button is built —
9373
* better than one that does nothing.
@@ -522,7 +502,7 @@ function closeAll( root ) {
522502
*
523503
* @param {HTMLElement} el The .ext-aggrid container (post-createGrid).
524504
* @param {Object} api The AG Grid GridApi.
525-
* @param {Object} config Normalized config from normalize().
505+
* @param {Object} config Normalized config from normalizeButtonOption().
526506
* @return {HTMLElement|null} The toolbar item.
527507
*/
528508
function buildItem( el, api, config ) {
@@ -563,4 +543,4 @@ function buildItem( el, api, config ) {
563543
return item;
564544
}
565545

566-
module.exports = { normalize, isSupported, buildItem, closeAll };
546+
module.exports = { normalize: normalizeButtonOption, isSupported, buildItem, closeAll };

0 commit comments

Comments
 (0)