Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/client/lib/FileChooser.ts
1028 views
1
import IFileChooserPrompt from '@secret-agent/interfaces/IFileChooserPrompt';
2
import * as Fs from 'fs';
3
import AwaitedPath, { IJsPath } from 'awaited-dom/base/AwaitedPath';
4
import { createHTMLInputElement } from 'awaited-dom/impl/create';
5
import { IHTMLInputElement } from 'awaited-dom/base/interfaces/official';
6
import * as Path from 'path';
7
import CoreFrameEnvironment from './CoreFrameEnvironment';
8
9
export default class FileChooser {
10
public acceptsMultipleFiles: boolean;
11
public inputElement: IHTMLInputElement;
12
13
readonly #jsPath: IJsPath;
14
readonly #coreFrame: Promise<CoreFrameEnvironment>;
15
16
constructor(coreFrame: Promise<CoreFrameEnvironment>, event: IFileChooserPrompt) {
17
const awaitedPath = new AwaitedPath(null, ...event.jsPath);
18
19
this.inputElement = createHTMLInputElement(awaitedPath, { coreFrame });
20
this.acceptsMultipleFiles = event.selectMultiple;
21
this.#jsPath = event.jsPath;
22
this.#coreFrame = coreFrame;
23
}
24
25
public async chooseFiles(...files: (string | { name: string; data: Buffer })[]): Promise<void> {
26
if (!files.length) throw new Error(`No files were provided to send to this input`);
27
if (files.length > 1 && !this.acceptsMultipleFiles) {
28
throw new Error(
29
`This input only supports a single file input, but ${files.length} files were supplied`,
30
);
31
}
32
const frame = await this.#coreFrame;
33
const finalFiles: { name: string; data: Buffer }[] = [];
34
for (const file of files) {
35
if (typeof file === 'string') {
36
const buffer = await Fs.promises.readFile(file);
37
finalFiles.push({ data: buffer, name: Path.basename(file) });
38
} else {
39
finalFiles.push(file);
40
}
41
}
42
await frame.setFileInputFiles(this.#jsPath, finalFiles);
43
}
44
}
45
46