Skip to content

Commit fe309bc

Browse files
committed
refactor: use papa parse to interpret tsv data
1 parent 51cc8ff commit fe309bc

1 file changed

Lines changed: 31 additions & 11 deletions

File tree

apps/web/src/hooks/useInstrumentVisualization.ts

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { useEffect, useMemo, useState } from 'react';
22

3+
import { toBasicISOString } from '@douglasneuroinformatics/libjs';
34
import { useDownload, useNotificationsStore, useTranslation } from '@douglasneuroinformatics/libui/hooks';
45
import type { AnyUnilingualScalarInstrument, InstrumentKind } from '@opendatacapture/runtime-core';
56
import { omit } from 'lodash-es';
@@ -64,18 +65,21 @@ export function useInstrumentVisualization({ params }: UseInstrumentVisualizatio
6465
instrument.internal.edition
6566
}_${new Date().toISOString()}`;
6667

67-
const exportRecords = records.map((record) => omit(record, ['__date__', '__time__']));
68+
const exportRecords = records.map((record) => omit(record, ['__time__']));
6869

6970
switch (option) {
7071
case 'CSV':
7172
void download(`${baseFilename}.csv`, () => {
7273
const columnNames = Object.keys(exportRecords[0]!);
7374

74-
//fill object array with export record items
7575
const rows = exportRecords.map((item) => {
7676
const obj: { [key: string]: any } = {};
7777
for (const key of columnNames) {
7878
const val = item[key];
79+
if (key === '__date__') {
80+
obj.Date = toBasicISOString(val as Date);
81+
continue;
82+
}
7983
obj[key] = typeof val === 'object' ? JSON.stringify(val) : val;
8084
}
8185
return obj;
@@ -98,15 +102,31 @@ export function useInstrumentVisualization({ params }: UseInstrumentVisualizatio
98102
break;
99103
case 'TSV':
100104
void download(`${baseFilename}.tsv`, () => {
101-
const columnNames = Object.keys(exportRecords[0]!).join('\t');
102-
const rows = exportRecords
103-
.map((item) =>
104-
Object.values(item)
105-
.map((val) => JSON.stringify(val))
106-
.join('\t')
107-
)
108-
.join('\n');
109-
return columnNames + '\n' + rows;
105+
const columnNames = Object.keys(exportRecords[0]!);
106+
107+
const rows = exportRecords.map((item) => {
108+
const obj: { [key: string]: any } = {};
109+
for (const key of columnNames) {
110+
const val = item[key];
111+
if (key === '__date__') {
112+
obj.Date = toBasicISOString(val as Date);
113+
continue;
114+
}
115+
obj[key] = typeof val === 'object' ? JSON.stringify(val) : val;
116+
}
117+
return obj;
118+
});
119+
120+
const tsv = unparse(rows, {
121+
delimiter: '\t',
122+
escapeChar: '"',
123+
header: true,
124+
quoteChar: '"',
125+
quotes: false,
126+
skipEmptyLines: true
127+
});
128+
129+
return tsv;
110130
});
111131
break;
112132
}

0 commit comments

Comments
 (0)