feat(export): modal gains assignable axes + group-by control
This commit is contained in:
@@ -2,9 +2,12 @@ import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { experimentsApi } from '../api/client';
|
||||
import Button from './ui/Button';
|
||||
import Alert from './ui/Alert';
|
||||
import { listExportableParams, buildMatrix, toCSV, csvFilename } from '../lib/dataExport';
|
||||
import {
|
||||
EXPORT_DIMENSIONS, dimLabel, otherDimension,
|
||||
listDimensionMembers, buildMatrix, toCSV, csvFilename,
|
||||
} from '../lib/dataExport';
|
||||
|
||||
const GROUP_LABELS = { metrics: 'Session metrics', daily: 'Daily record fields' };
|
||||
const PARAM_GROUP_LABELS = { metrics: 'Session metrics', daily: 'Daily record fields' };
|
||||
|
||||
function triggerDownload(filename, text) {
|
||||
const blob = new Blob([text], { type: 'text/csv;charset=utf-8;' });
|
||||
@@ -18,11 +21,17 @@ function triggerDownload(filename, text) {
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
|
||||
export default function ExportDataModal({ experimentTitle, experimentId, dailyTemplate, animals, onClose }) {
|
||||
export default function ExportDataModal({
|
||||
experimentTitle, experimentId, dailyTemplate, animals, subjectTemplate = [], groupField = '__none__', onClose,
|
||||
}) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [statuses, setStatuses] = useState([]);
|
||||
const [selectedId, setSelectedId] = useState(null);
|
||||
|
||||
const [rowDim, setRowDim] = useState('date');
|
||||
const [colDim, setColDim] = useState('subject');
|
||||
const [pinnedId, setPinnedId] = useState(null);
|
||||
const [groupBy, setGroupBy] = useState(groupField ?? '__none__');
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -35,33 +44,42 @@ export default function ExportDataModal({ experimentTitle, experimentId, dailyTe
|
||||
return () => { alive = false; };
|
||||
}, [experimentId]);
|
||||
|
||||
const params = useMemo(() => listExportableParams(dailyTemplate, statuses), [dailyTemplate, statuses]);
|
||||
const pinnedDim = otherDimension(rowDim, colDim);
|
||||
const subjectIsAxis = rowDim === 'subject' || colDim === 'subject';
|
||||
const effGroup = subjectIsAxis ? groupBy : '__none__';
|
||||
const ctx = useMemo(() => ({ statuses, animals, dailyTemplate }), [statuses, animals, dailyTemplate]);
|
||||
|
||||
// Derive the effective selection: the user's pick, else the first parameter.
|
||||
const effectiveId = selectedId ?? params[0]?.id ?? null;
|
||||
const selectedParam = params.find((p) => p.id === effectiveId) ?? null;
|
||||
// Members of the pinned dimension populate its value dropdown.
|
||||
const pinnedMembers = useMemo(
|
||||
() => listDimensionMembers(pinnedDim, { ...ctx, groupField: effGroup }),
|
||||
[pinnedDim, ctx, effGroup],
|
||||
);
|
||||
const effPinnedId = pinnedId ?? pinnedMembers[0]?.id ?? null;
|
||||
const pinnedMember = pinnedMembers.find((m) => m.id === effPinnedId) ?? pinnedMembers[0] ?? null;
|
||||
|
||||
const matrix = useMemo(
|
||||
() => (selectedParam ? buildMatrix(statuses, animals, selectedParam) : { columns: [], rows: [] }),
|
||||
[statuses, animals, selectedParam],
|
||||
() => (pinnedMember
|
||||
? buildMatrix({ rowDim, colDim, pinnedMember, groupField: effGroup }, ctx)
|
||||
: { columns: [], rows: [], context: { label: '', value: '' }, corner: '', groupAxis: null }),
|
||||
[rowDim, colDim, pinnedMember, effGroup, ctx],
|
||||
);
|
||||
|
||||
const hasData = matrix.rows.length > 0;
|
||||
|
||||
// Group params for <optgroup> rendering, preserving order.
|
||||
const grouped = useMemo(() => {
|
||||
const out = [];
|
||||
for (const p of params) {
|
||||
let g = out.find((x) => x.group === p.group);
|
||||
if (!g) { g = { group: p.group, items: [] }; out.push(g); }
|
||||
g.items.push(p);
|
||||
}
|
||||
return out;
|
||||
}, [params]);
|
||||
// When the user changes an axis, keep the two distinct and reset the pinned pick.
|
||||
function changeRowDim(next) {
|
||||
setRowDim(next);
|
||||
if (colDim === next) setColDim(otherDimension(next, null) ?? EXPORT_DIMENSIONS.find((d) => d.dim !== next).dim);
|
||||
setPinnedId(null);
|
||||
}
|
||||
function changeColDim(next) {
|
||||
setColDim(next);
|
||||
if (rowDim === next) setRowDim(EXPORT_DIMENSIONS.find((d) => d.dim !== next).dim);
|
||||
setPinnedId(null);
|
||||
}
|
||||
|
||||
function handleExport() {
|
||||
if (!hasData || !selectedParam) return;
|
||||
triggerDownload(csvFilename(experimentTitle, selectedParam.label), toCSV(matrix));
|
||||
if (!hasData || !pinnedMember) return;
|
||||
triggerDownload(csvFilename(experimentTitle, pinnedMember.label), toCSV(matrix));
|
||||
onClose();
|
||||
}
|
||||
|
||||
@@ -69,38 +87,72 @@ export default function ExportDataModal({ experimentTitle, experimentId, dailyTe
|
||||
if (error) return (
|
||||
<div className="space-y-4">
|
||||
<Alert type="error" message={error} />
|
||||
<div className="flex justify-end">
|
||||
<Button variant="secondary" onClick={onClose}>Close</Button>
|
||||
</div>
|
||||
<div className="flex justify-end"><Button variant="secondary" onClick={onClose}>Close</Button></div>
|
||||
</div>
|
||||
);
|
||||
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
Export one parameter as a CSV file — each row is a date, each column is a subject.
|
||||
Choose what goes on the rows and columns. The remaining dimension is fixed to one value, shown at the top of the file.
|
||||
</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>
|
||||
<label htmlFor="export-param" className="block text-xs font-medium text-gray-500 mb-1">Parameter</label>
|
||||
<label htmlFor="export-pinned" className="block text-xs font-medium text-gray-500 mb-1">
|
||||
Fixed: {dimLabel(pinnedDim)}
|
||||
</label>
|
||||
<select
|
||||
id="export-param"
|
||||
value={effectiveId ?? ''}
|
||||
onChange={(e) => setSelectedId(e.target.value)}
|
||||
className="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"
|
||||
id="export-pinned"
|
||||
value={effPinnedId ?? ''}
|
||||
onChange={(e) => setPinnedId(e.target.value)}
|
||||
className={selectCls}
|
||||
>
|
||||
{grouped.map((g) => (
|
||||
<optgroup key={g.group} label={GROUP_LABELS[g.group] ?? g.group}>
|
||||
{g.items.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}
|
||||
</optgroup>
|
||||
))}
|
||||
{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>
|
||||
</div>
|
||||
|
||||
{subjectIsAxis && (
|
||||
<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">
|
||||
{hasData
|
||||
? `${matrix.rows.length} date${matrix.rows.length !== 1 ? 's' : ''} × ${matrix.columns.length} subject${matrix.columns.length !== 1 ? 's' : ''}`
|
||||
: 'No data for this parameter yet.'}
|
||||
? `${matrix.rows.length} ${matrix.corner.toLowerCase()}${matrix.rows.length !== 1 ? 's' : ''} × ${matrix.columns.length} ${dimLabel(colDim).toLowerCase()}${matrix.columns.length !== 1 ? 's' : ''}`
|
||||
: 'No data for this selection yet.'}
|
||||
</p>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
@@ -110,3 +162,14 @@ export default function ExportDataModal({ experimentTitle, experimentId, dailyTe
|
||||
</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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user