-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathuseLoadSpectra.ts
More file actions
148 lines (126 loc) · 4.49 KB
/
useLoadSpectra.ts
File metadata and controls
148 lines (126 loc) · 4.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import type {
CoreReadReturn,
NmriumState,
ParsingOptions,
ViewState,
} from '@zakodium/nmrium-core';
import { CURRENT_EXPORT_VERSION } from '@zakodium/nmrium-core';
import init from '@zakodium/nmrium-core-plugins';
import { FifoLogger } from 'fifo-logger';
import { FileCollection } from 'file-collection';
import { useCallback, useMemo, useState } from 'react';
import events from '../events/event.js';
import { getFileNameFromURL } from '../utilities/getFileNameFromURL.js';
import { isArrayOfString } from '../utilities/isArrayOfString.js';
type LoadOptions =
| { nmrium: object; activeTab?: string }
| { urls: string[]; activeTab?: string }
| { files: File[]; activeTab?: string };
// CoreReadReturn with `state.view` made optional to allow partial injection.
export type NMRiumData = Omit<CoreReadReturn, 'state'> & {
state: Omit<CoreReadReturn['state'], 'view'> & { view?: ViewState };
};
interface UseLoadSpectraResult {
data: NMRiumData | null;
load: (options: LoadOptions) => Promise<void>;
isLoading: boolean;
setActiveTab: (input: { tab: string }) => void;
}
const core = init();
const logger = new FifoLogger();
logger.addEventListener('change', ({ detail: { logs } }) => {
const log = logs.at(-1);
if (!log || !['error', 'fatal', 'warn'].includes(log.levelLabel)) return;
const error = log.error ?? new Error(log.message);
events.trigger('error', error);
// eslint-disable-next-line no-console
console.log(error);
});
const PARSING_OPTIONS: Partial<ParsingOptions> = {
onLoadProcessing: { autoProcessing: true },
experimentalFeatures: true,
selector: { general: { dataSelection: 'preferFT' } },
logger,
};
async function loadSpectraFromNMRium(nmrium: object): Promise<CoreReadReturn> {
return core.readNMRiumObject(nmrium, PARSING_OPTIONS);
}
async function loadSpectraFromFiles(files: File[]): Promise<CoreReadReturn> {
const fileCollection = await new FileCollection().appendFileList(files);
return core.read(fileCollection, PARSING_OPTIONS);
}
async function loadSpectraFromURLs(urls: string[]): Promise<CoreReadReturn> {
const entries = urls.map((url) => {
const refURL = new URL(url);
const name = getFileNameFromURL(url);
let path = refURL.pathname;
if (!name?.includes('.')) {
path = `${path}.zip`;
}
return { relativePath: path, baseURL: refURL.origin };
});
return core.readFromWebSource({ entries }, PARSING_OPTIONS);
}
export function useLoadSpectra(): UseLoadSpectraResult {
const [result, setResult] = useState<CoreReadReturn | null>(null);
const [activeTab, setActiveTab] = useState<{ tab: string } | undefined>();
const [isLoading, setLoading] = useState(false);
const load = useCallback(async (options: LoadOptions) => {
setLoading(true);
try {
let loadedResult: CoreReadReturn;
let resolvedActiveTab: string | undefined;
if ('nmrium' in options) {
loadedResult = await loadSpectraFromNMRium(options.nmrium);
resolvedActiveTab =
options.activeTab ?? loadedResult.state.view?.spectra?.activeTab;
} else if ('urls' in options) {
if (!isArrayOfString(options.urls)) {
throw new Error('The input must be a valid urls array of string[]');
}
loadedResult = await loadSpectraFromURLs(options.urls);
resolvedActiveTab = options.activeTab;
} else {
loadedResult = await loadSpectraFromFiles(options.files);
resolvedActiveTab = options.activeTab;
}
setResult(loadedResult);
setActiveTab({ tab: resolvedActiveTab ?? '' });
const state = {
...loadedResult.state,
data: {
spectra: [],
molecules: [],
...loadedResult.state.data,
actionType: 'INITIATE',
},
};
events.trigger('data-change', {
source: 'data',
state: state as NmriumState,
});
} catch (error: unknown) {
events.trigger('error', error as Error);
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoading(false);
}
}, []);
return useMemo(() => {
const view = {
spectra: { activeTab: activeTab?.tab },
} as unknown as ViewState;
const data: NMRiumData | null = result
? {
...result,
state: {
version: result.state.version ?? CURRENT_EXPORT_VERSION,
...result.state,
view,
},
}
: null;
return { data, load, isLoading, setActiveTab };
}, [activeTab, result, isLoading, load, setActiveTab]);
}