From 744a13418568c6931aee6d14b4ea687daca0ce2a Mon Sep 17 00:00:00 2001 From: Axel Bocciarelli Date: Mon, 3 Jun 2024 09:00:09 +0200 Subject: [PATCH] Add CSV export --- src/LocalFileViewer.tsx | 8 ++++++-- src/RemoteFileViewer.tsx | 9 +++++++-- src/utils.ts | 42 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/LocalFileViewer.tsx b/src/LocalFileViewer.tsx index 2f30a9b..b3a62d3 100644 --- a/src/LocalFileViewer.tsx +++ b/src/LocalFileViewer.tsx @@ -3,7 +3,7 @@ import { H5WasmLocalFileProvider } from '@h5web/h5wasm'; import { getPlugin } from './plugin-utils'; import type { LocalFile } from './stores'; -import { buildMailto, FEEDBACK_MESSAGE } from './utils'; +import { buildMailto, FEEDBACK_MESSAGE, getExportURL } from './utils'; export const CACHE_KEY = Symbol('bufferFetcher'); @@ -16,7 +16,11 @@ function LocalFileViewer(props: Props) { const { resolvedUrl, file: rawFile } = file; return ( - + + To report an issue, please include screenshots, reproduction steps, etc. => To suggest a new feature, please describe the needs this feature would fulfill. >>`; + +export const getExportURL: GetExportURL = ( + format, + dataset, + selection, + value, + // eslint-disable-next-line sonarjs/cognitive-complexity +) => { + if (format !== 'csv') { + return undefined; + } + + return async () => { + // Find dimensions of dataset/slice to export + // Note that there is currently no way to know if the dataset/slice is transposed - https://github.com/silx-kit/h5web/issues/1454 + const dims = selection + ? dataset.shape.filter((_, index) => selection[index * 2] === ':') + : dataset.shape; + + if (dims.length === 0 || dims.length > 2) { + throw new Error( + 'Expected dataset/slice to export to have 1 or 2 dimensions', + ); + } + + let csv = ''; + const [rows, cols = 1] = dims; // export 1D dataset/slice as column (i.e. 1 value per line) + + for (let i = 0; i < rows; i += 1) { + for (let j = 0; j < cols; j += 1) { + csv += `${(value[i * cols + j] as number).toString()}${ + j < cols - 1 ? ',' : '' + }`; + } + + csv += i < rows - 1 ? '\n' : ''; + } + + return new Blob([csv]); + }; +};