feat(export): modal becomes X / Data / Group by pickers, subjects as columns

This commit is contained in:
Experiments DB Dev
2026-07-19 15:05:38 -04:00
parent 39a5a4ec0c
commit 6f23f83bc8
2 changed files with 89 additions and 151 deletions
+54 -93
View File
@@ -2,10 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
import { experimentsApi } from '../api/client'; import { experimentsApi } from '../api/client';
import Button from './ui/Button'; import Button from './ui/Button';
import Alert from './ui/Alert'; import Alert from './ui/Alert';
import { import { listExportableParams, buildSubjectSeriesMatrix, toCSV, csvFilename } from '../lib/dataExport';
EXPORT_DIMENSIONS, dimLabel, otherDimension,
listDimensionMembers, buildMatrix, toCSV, csvFilename,
} from '../lib/dataExport';
const PARAM_GROUP_LABELS = { metrics: 'Session metrics', daily: 'Daily record fields' }; const PARAM_GROUP_LABELS = { metrics: 'Session metrics', daily: 'Daily record fields' };
@@ -28,9 +25,8 @@ export default function ExportDataModal({
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [statuses, setStatuses] = useState([]); const [statuses, setStatuses] = useState([]);
const [rowDim, setRowDim] = useState('date'); const [xField, setXField] = useState('__date__');
const [colDim, setColDim] = useState('subject'); const [dataId, setDataId] = useState(null);
const [pinnedId, setPinnedId] = useState(null);
const [groupBy, setGroupBy] = useState(() => { const [groupBy, setGroupBy] = useState(() => {
const valid = groupField === '__none__' || groupField === '__name__' || groupField === '__id__' const valid = groupField === '__none__' || groupField === '__name__' || groupField === '__id__'
|| subjectTemplate.some((f) => f.active && f.fieldId === groupField); || subjectTemplate.some((f) => f.active && f.fieldId === groupField);
@@ -48,42 +44,38 @@ export default function ExportDataModal({
return () => { alive = false; }; return () => { alive = false; };
}, [experimentId]); }, [experimentId]);
const pinnedDim = otherDimension(rowDim, colDim); const params = useMemo(() => listExportableParams(dailyTemplate, statuses), [dailyTemplate, statuses]);
const subjectIsAxis = rowDim === 'subject' || colDim === 'subject'; const effDataId = dataId ?? params[0]?.id ?? null;
const effGroup = subjectIsAxis ? groupBy : '__none__'; const dataParam = params.find((p) => p.id === effDataId) ?? params[0] ?? null;
const ctx = useMemo(() => ({ statuses, animals, dailyTemplate }), [statuses, animals, dailyTemplate]);
// Members of the pinned dimension populate its value dropdown. const activeDaily = useMemo(() => (dailyTemplate ?? []).filter((f) => f.active), [dailyTemplate]);
const pinnedMembers = useMemo( const xOptions = useMemo(() => [
() => listDimensionMembers(pinnedDim, { ...ctx, groupField: effGroup }), { id: '__date__', label: 'Date' },
[pinnedDim, ctx, effGroup], { id: '__days__', label: '# Days Reach' },
); ...activeDaily.map((f) => ({ id: f.fieldId, label: f.label })),
const effPinnedId = pinnedId ?? pinnedMembers[0]?.id ?? null; ], [activeDaily]);
const pinnedMember = pinnedMembers.find((m) => m.id === effPinnedId) ?? pinnedMembers[0] ?? null;
const matrix = useMemo( const matrix = useMemo(
() => (pinnedMember () => (dataParam
? buildMatrix({ rowDim, colDim, pinnedMember, groupField: effGroup }, ctx) ? buildSubjectSeriesMatrix({ xField, dataParam, groupField: groupBy }, { statuses, animals, dailyTemplate })
: { columns: [], rows: [], context: { label: '', value: '' }, corner: '', groupAxis: null }), : { columns: [], rows: [], context: { label: 'Data', value: '' }, corner: '', groupAxis: null }),
[rowDim, colDim, pinnedMember, effGroup, ctx], [xField, dataParam, groupBy, statuses, animals, dailyTemplate],
); );
const hasData = matrix.rows.length > 0; const hasData = matrix.rows.length > 0;
// When the user changes an axis, keep the two distinct and reset the pinned pick. const groupedParams = useMemo(() => {
function changeRowDim(next) { const out = [];
setRowDim(next); for (const p of params) {
if (colDim === next) setColDim(otherDimension(next, null) ?? EXPORT_DIMENSIONS.find((d) => d.dim !== next).dim); let g = out.find((x) => x.group === p.group);
setPinnedId(null); if (!g) { g = { group: p.group, items: [] }; out.push(g); }
} g.items.push(p);
function changeColDim(next) { }
setColDim(next); return out;
if (rowDim === next) setRowDim(EXPORT_DIMENSIONS.find((d) => d.dim !== next).dim); }, [params]);
setPinnedId(null);
}
function handleExport() { function handleExport() {
if (!hasData || !pinnedMember) return; if (!hasData || !dataParam) return;
triggerDownload(csvFilename(experimentTitle, pinnedMember.label), toCSV(matrix)); triggerDownload(csvFilename(experimentTitle, dataParam.label), toCSV(matrix));
onClose(); onClose();
} }
@@ -96,66 +88,46 @@ export default function ExportDataModal({
); );
const selectCls = 'w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-white focus:outline-none focus:ring-1 focus:ring-indigo-400'; const selectCls = 'w-full border border-gray-200 rounded px-2 py-1.5 text-sm bg-white focus:outline-none focus:ring-1 focus:ring-indigo-400';
const colOptions = EXPORT_DIMENSIONS.filter((d) => d.dim !== rowDim);
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<p className="text-sm text-gray-500"> <p className="text-sm text-gray-500">
Choose what goes on the rows and columns. The remaining dimension is fixed to one value, shown at the top of the file. One value per subject over an X axis each column is a subject, each row an X value. Blank where a subject has no value.
</p> </p>
<div className="grid grid-cols-2 gap-3">
<div>
<label htmlFor="export-rows" className="block text-xs font-medium text-gray-500 mb-1">Rows</label>
<select id="export-rows" value={rowDim} onChange={(e) => changeRowDim(e.target.value)} className={selectCls}>
{EXPORT_DIMENSIONS.map((d) => <option key={d.dim} value={d.dim}>{d.label}</option>)}
</select>
</div>
<div>
<label htmlFor="export-cols" className="block text-xs font-medium text-gray-500 mb-1">Columns</label>
<select id="export-cols" value={colDim} onChange={(e) => changeColDim(e.target.value)} className={selectCls}>
{colOptions.map((d) => <option key={d.dim} value={d.dim}>{d.label}</option>)}
</select>
</div>
</div>
<div> <div>
<label htmlFor="export-pinned" className="block text-xs font-medium text-gray-500 mb-1"> <label htmlFor="export-x" className="block text-xs font-medium text-gray-500 mb-1">X axis (rows)</label>
Fixed: {dimLabel(pinnedDim)} <select id="export-x" value={xField} onChange={(e) => setXField(e.target.value)} className={selectCls}>
</label> {xOptions.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}
<select
id="export-pinned"
value={effPinnedId ?? ''}
onChange={(e) => setPinnedId(e.target.value)}
className={selectCls}
>
{pinnedDim === 'parameter'
? groupParamMembers(pinnedMembers).map((g) => (
<optgroup key={g.group} label={PARAM_GROUP_LABELS[g.group] ?? g.group}>
{g.items.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</optgroup>
))
: pinnedMembers.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</select> </select>
</div> </div>
{subjectIsAxis && ( <div>
<div> <label htmlFor="export-data" className="block text-xs font-medium text-gray-500 mb-1">Data (cells)</label>
<label htmlFor="export-group" className="block text-xs font-medium text-gray-500 mb-1">Group by</label> <select id="export-data" value={effDataId ?? ''} onChange={(e) => setDataId(e.target.value)} className={selectCls}>
<select id="export-group" value={groupBy} onChange={(e) => setGroupBy(e.target.value)} className={selectCls}> {groupedParams.map((g) => (
<option value="__none__"> None </option> <optgroup key={g.group} label={PARAM_GROUP_LABELS[g.group] ?? g.group}>
<option value="__name__">Name</option> {g.items.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}
<option value="__id__">Subject ID</option> </optgroup>
{subjectTemplate.filter((f) => f.active).map((f) => ( ))}
<option key={f.fieldId} value={f.fieldId}>{f.label}</option> </select>
))} </div>
</select>
</div> <div>
)} <label htmlFor="export-group" className="block text-xs font-medium text-gray-500 mb-1">Group by</label>
<select id="export-group" value={groupBy} onChange={(e) => setGroupBy(e.target.value)} className={selectCls}>
<option value="__none__"> None </option>
<option value="__name__">Name</option>
<option value="__id__">Subject ID</option>
{subjectTemplate.filter((f) => f.active).map((f) => (
<option key={f.fieldId} value={f.fieldId}>{f.label}</option>
))}
</select>
</div>
<p className="text-xs text-gray-400"> <p className="text-xs text-gray-400">
{hasData {hasData
? `${matrix.rows.length} ${matrix.corner.toLowerCase()}${matrix.rows.length !== 1 ? 's' : ''} × ${matrix.columns.length} ${dimLabel(colDim).toLowerCase()}${matrix.columns.length !== 1 ? 's' : ''}` ? `${matrix.rows.length} row${matrix.rows.length !== 1 ? 's' : ''} × ${matrix.columns.length} subject${matrix.columns.length !== 1 ? 's' : ''}`
: 'No data for this selection yet.'} : 'No data for this selection yet.'}
</p> </p>
@@ -166,14 +138,3 @@ export default function ExportDataModal({
</div> </div>
); );
} }
// Group parameter members by their .group for <optgroup> rendering, preserving order.
function groupParamMembers(members) {
const out = [];
for (const m of members) {
let g = out.find((x) => x.group === m.group);
if (!g) { g = { group: m.group, items: [] }; out.push(g); }
g.items.push(m);
}
return out;
}
+35 -58
View File
@@ -12,8 +12,9 @@ const animals = [
{ id: 'a2', animal_name: 'Beta', animal_id_string: 'R-002', subject_info: { grp: 'Drug' } }, { id: 'a2', animal_name: 'Beta', animal_id_string: 'R-002', subject_info: { grp: 'Drug' } },
]; ];
const statuses = [ const statuses = [
{ animal_id: 'a1', date: '2026-07-01T00:00:00.000Z', analysis_summary: { total: 5 } }, { animal_id: 'a1', date: '2026-07-01T00:00:00Z', analysis_summary: { total: 5, success_rate: 0.5 } },
{ animal_id: 'a2', date: '2026-07-01T00:00:00.000Z', analysis_summary: { total: 9 } }, { animal_id: 'a1', date: '2026-07-02T00:00:00Z', analysis_summary: { total: 7, success_rate: 0.7 } },
{ animal_id: 'a2', date: '2026-07-01T00:00:00Z', analysis_summary: { total: 9, success_rate: 0.9 } },
]; ];
const subjectTemplate = [{ fieldId: 'grp', label: 'Group', active: true }]; const subjectTemplate = [{ fieldId: 'grp', label: 'Group', active: true }];
@@ -22,12 +23,9 @@ beforeEach(() => {
client.experimentsApi.getDailyStatuses.mockResolvedValue(statuses); client.experimentsApi.getDailyStatuses.mockResolvedValue(statuses);
}); });
// Intercepts the Blob passed to URL.createObjectURL during handleExport so tests // Intercept the Blob handed to URL.createObjectURL so tests can read the real CSV.
// can inspect the actual CSV text produced, rather than inferring it from the // Also stub anchor.click() — jsdom treats a click on <a href="blob:..."> as an
// <select>'s DOM value (which can be misleading — see the coercion test below). // unimplemented navigation that throws async and can flake a later test.
// Also stubs anchor .click() — jsdom treats a real click on an <a href="blob:...">
// as a navigation attempt, which it doesn't implement; that throws asynchronously
// (after the test has moved on) and can flakily fail an unrelated later test.
function mockDownload() { function mockDownload() {
let blob = null; let blob = null;
const origCreate = global.URL.createObjectURL; const origCreate = global.URL.createObjectURL;
@@ -38,12 +36,8 @@ function mockDownload() {
window.HTMLAnchorElement.prototype.click = jest.fn(); window.HTMLAnchorElement.prototype.click = jest.fn();
return { return {
getBlob: () => blob, getBlob: () => blob,
// handleExport schedules `setTimeout(() => URL.revokeObjectURL(url), 0)`; flush
// that pending macrotask before unmocking, or it fires after restore() has put
// back the (non-existent, in jsdom) original revokeObjectURL and throws async —
// an error jest attributes to whatever test happens to run next.
restore: async () => { restore: async () => {
await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0)); // flush handleExport's setTimeout revoke
global.URL.createObjectURL = origCreate; global.URL.createObjectURL = origCreate;
global.URL.revokeObjectURL = origRevoke; global.URL.revokeObjectURL = origRevoke;
window.HTMLAnchorElement.prototype.click = origClick; window.HTMLAnchorElement.prototype.click = origClick;
@@ -76,61 +70,44 @@ function renderModal(props = {}) {
} }
describe('ExportDataModal', () => { describe('ExportDataModal', () => {
it('defaults to Rows=Date, Columns=Subject and shows the preview', async () => { it('renders X / Data / Group by pickers; X defaults to Date', async () => {
renderModal(); renderModal();
expect(await screen.findByLabelText('Rows')).toHaveValue('date'); expect(await screen.findByLabelText('X axis (rows)')).toHaveValue('__date__');
expect(screen.getByLabelText('Columns')).toHaveValue('subject'); expect(screen.getByLabelText('Data (cells)')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText(/1 date.*2 subjects/i)).toBeInTheDocument());
});
it('hides the Group by control until Subject is an axis', async () => {
renderModal();
await screen.findByLabelText('Rows');
// subject is a column by default -> Group by visible
expect(screen.getByLabelText('Group by')).toBeInTheDocument();
// move subject off both axes: Rows=Date, Columns=Parameter -> subject pinned
fireEvent.change(screen.getByLabelText('Columns'), { target: { value: 'parameter' } });
await waitFor(() => expect(screen.queryByLabelText('Group by')).not.toBeInTheDocument());
});
it('keeps row and column dimensions distinct', async () => {
renderModal();
const rows = await screen.findByLabelText('Rows');
fireEvent.change(rows, { target: { value: 'subject' } }); // collides with column=subject
await waitFor(() => expect(screen.getByLabelText('Columns')).not.toHaveValue('subject'));
});
it('defaults Group by to None when groupField is __none__, and the exported CSV has no Group row (Issue-1 regression guard: default export reproduces today\'s export)', async () => {
const dl = mockDownload();
renderModal({ groupField: '__none__' });
await screen.findByLabelText('Rows');
expect(screen.getByLabelText('Group by')).toHaveValue('__none__'); expect(screen.getByLabelText('Group by')).toHaveValue('__none__');
await waitFor(() => expect(screen.getByText(/1 date/i)).toBeInTheDocument()); await waitFor(() => expect(screen.getByText(/2 rows × 2 subjects/i)).toBeInTheDocument());
});
it('default export (X=Date, Data=Total attempts) has subject columns, date rows, blank where missing', async () => {
const dl = mockDownload();
renderModal();
await screen.findByLabelText('X axis (rows)');
await waitFor(() => expect(screen.getByText(/2 rows/i)).toBeInTheDocument());
fireEvent.click(screen.getByText('Export CSV')); fireEvent.click(screen.getByText('Export CSV'));
const text = await readBlobText(dl.getBlob()); const text = await readBlobText(dl.getBlob());
expect(text).not.toMatch(/^Group,/m); expect(text).toBe('Data,Total attempts\n\nDate,Alpha,Beta\n2026-07-01,5,9\n2026-07-02,7,');
await dl.restore(); await dl.restore();
}); });
it('defaults Group by to the saved field when it is a valid active subject field', async () => { it('switching X to # Days Reach makes rows the day ordinals', async () => {
renderModal({ groupField: 'grp' });
await screen.findByLabelText('Rows');
expect(screen.getByLabelText('Group by')).toHaveValue('grp');
});
it('coerces Group by to None when the saved field no longer exists in subjectTemplate, so the export carries no stray Group row (Issue-2 guard)', async () => {
// Note: asserting the <select>'s DOM .value here would be misleading — React's
// controlled <select> falls back to selecting the first <option> ("__none__")
// whenever the given value matches no option, regardless of whether the
// component actually validated/coerced its internal state. So we assert the
// real behavioral effect (the exported CSV) instead.
const dl = mockDownload(); const dl = mockDownload();
renderModal({ groupField: 'ghost-field' }); renderModal();
await screen.findByLabelText('Rows'); fireEvent.change(await screen.findByLabelText('X axis (rows)'), { target: { value: '__days__' } });
await waitFor(() => expect(screen.getByText(/1 date/i)).toBeInTheDocument()); await waitFor(() => expect(screen.getByText(/2 rows/i)).toBeInTheDocument());
fireEvent.click(screen.getByText('Export CSV')); fireEvent.click(screen.getByText('Export CSV'));
const text = await readBlobText(dl.getBlob()); const text = await readBlobText(dl.getBlob());
expect(text).not.toMatch(/^Group,/m); expect(text).toBe('Data,Total attempts\n\n# Days Reach,Alpha,Beta\n1,5,9\n2,7,');
await dl.restore();
});
it('a valid group field adds a Group row and clusters subjects', async () => {
const dl = mockDownload();
renderModal({ groupField: 'grp' });
await screen.findByLabelText('X axis (rows)');
await waitFor(() => expect(screen.getByText(/2 rows/i)).toBeInTheDocument());
fireEvent.click(screen.getByText('Export CSV'));
const text = await readBlobText(dl.getBlob());
expect(text).toMatch(/^Group,Control,Drug$/m);
await dl.restore(); await dl.restore();
}); });
}); });