49 lines
2.4 KiB
TypeScript
49 lines
2.4 KiB
TypeScript
import { ConnectorInfo, SourceType } from '../api/api.types';
|
|
import { DataConnection } from './data-source';
|
|
import { DocumentConnection } from './document-source';
|
|
import { EegConnection } from './eeg-source';
|
|
import { FileConnection } from './file-source';
|
|
import { PdfConnection } from './pdf-source';
|
|
|
|
/** Turns the files chosen for one source kind into workspace connections. */
|
|
type ConnectionFactory = (files: File[]) => DataConnection[];
|
|
|
|
// Adding a file source on the client is one `DataConnection` subclass and one entry here.
|
|
const FACTORIES = new Map<SourceType, ConnectionFactory>([
|
|
['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))],
|
|
['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))],
|
|
['json', (files) => files.map((file) => new FileConnection(file, 'json'))],
|
|
['pdf', (files) => files.map((file) => new PdfConnection(file))],
|
|
// Several recordings or documents are read together: one connection, one table.
|
|
['edf', (files) => [new EegConnection(files)]],
|
|
['document', (files) => [new DocumentConnection(files)]],
|
|
]);
|
|
|
|
export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] {
|
|
const factory = FACTORIES.get(kind);
|
|
return factory && files.length ? factory(files) : [];
|
|
}
|
|
|
|
/** First connector (in the server's order) that reads this extension, like the server does. */
|
|
export function kindForFile(fileName: string, connectors: ConnectorInfo[]): SourceType | null {
|
|
const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
|
|
return connectors.find((c) => FACTORIES.has(c.kind) && c.extensions.includes(extension))?.kind ?? null;
|
|
}
|
|
|
|
export function acceptedExtensions(connectors: ConnectorInfo[]): string[] {
|
|
return [...new Set(connectors.filter((c) => FACTORIES.has(c.kind)).flatMap((c) => c.extensions))];
|
|
}
|
|
|
|
/** Dropped files grouped by kind; unsupported ones come back in `rejected`. */
|
|
export function connectionsForFiles(files: File[], connectors: ConnectorInfo[]): { connections: DataConnection[]; rejected: File[] } {
|
|
const byKind = new Map<SourceType, File[]>();
|
|
const rejected: File[] = [];
|
|
for (const file of files) {
|
|
const kind = kindForFile(file.name, connectors);
|
|
if (kind) byKind.set(kind, [...(byKind.get(kind) ?? []), file]);
|
|
else rejected.push(file);
|
|
}
|
|
const connections = [...byKind].flatMap(([kind, group]) => connectionsFor(kind, group));
|
|
return { connections, rejected };
|
|
}
|