Implement editor.uploadFile syscall (#570)

* Implement editor.attachFile syscall

* Refactor attachFile to uploadFile

returns a promise with an UploadFile now

* Fix style

* Reject promise with errors

* Another code style fix

---------

Co-authored-by: prcrst <p-github@prcr.st>
This commit is contained in:
prcrst
2023-11-22 15:33:25 +01:00
committed by GitHub
co-authored by prcrst
parent 9b89330ec9
commit ae1561ac90
3 changed files with 51 additions and 0 deletions
+41
View File
@@ -12,6 +12,7 @@ import {
} from "../deps.ts";
import { SysCallMapping } from "../../plugos/system.ts";
import type { FilterOption } from "../types.ts";
import { UploadFile } from "../../plug-api/types.ts";
export function editorSyscalls(editor: Client): SysCallMapping {
const syscalls: SysCallMapping = {
@@ -61,6 +62,46 @@ export function editorSyscalls(editor: Client): SysCallMapping {
link.download = filename;
link.click();
},
"editor.uploadFile": (
_ctx,
accept?: string,
capture?: string
): Promise<UploadFile> => {
return new Promise<UploadFile>((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
if (accept) {
input.accept = accept;
}
if (capture) {
input.capture = capture;
}
input.onchange = () => {
const file = input.files?.item(0);
if (!file) {
reject(new Error("No file found"));
} else {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = async (evt) => {
if (evt.target?.readyState == FileReader.DONE) {
const arrayBuffer = evt.target.result;
resolve({
name: file.name,
content: new Uint8Array(await file.arrayBuffer())
});
}
};
reader.onabort = (e) => { reject(e) };
reader.onerror = (e) => { reject(e) };
}
}
input.onabort = (e) => { reject(e) };
input.click();
});
},
"editor.flashNotification": (
_ctx,
message: string,