1
0

Upload file command with copy/paste logic (#571)

Upload: File command

Co-authored-by: prcrst <p-github@prcr.st>
Co-authored-by: Zef Hemel <zef@zef.me>
This commit is contained in:
prcrst 2023-11-23 11:09:48 +00:00 committed by GitHub
parent 621c21d26c
commit ae9c8dcb4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 55 additions and 0 deletions

View File

@ -143,5 +143,6 @@ export type LintDiagnostic = {
export type UploadFile = {
name: string;
contentType: string;
content: Uint8Array;
}

View File

@ -222,3 +222,7 @@ functions:
command:
name: "Account: Logout"
uploadFileCommand:
path: ./upload.ts:uploadFile
command:
name: "Upload: File"

49
plugs/editor/upload.ts Normal file
View File

@ -0,0 +1,49 @@
import { editor, space } from "$sb/silverbullet-syscall/mod.ts";
import { UploadFile } from "$sb/types.ts";
const maximumAttachmentSize = 1024 * 1024 * 10; // 10MB
function folderName(path: string) {
return path.split("/").slice(0, -1).join("/");
}
async function saveFile(file: UploadFile) {
if (file.content.length > maximumAttachmentSize) {
editor.flashNotification(
`Attachment is too large, maximum is ${
maximumAttachmentSize / 1024 / 1024
}MB`,
"error",
);
return;
}
let prefix = folderName(await editor.getCurrentPage()) + "/";
if (prefix === "/") {
// root folder case
prefix = "";
}
const suggestedName = prefix + file.name;
const finalFileName = await editor.prompt(
"File name for pasted attachment",
suggestedName,
);
if (!finalFileName) {
return;
}
await space.writeAttachment(
finalFileName,
file.content,
);
let attachmentMarkdown = `[${finalFileName}](${encodeURI(finalFileName)})`;
if (file.contentType.startsWith("image/")) {
attachmentMarkdown = `![](${encodeURI(finalFileName)})`;
}
editor.insertAtCursor(attachmentMarkdown);
}
export async function uploadFile() {
const uploadFile = await editor.uploadFile();
await saveFile(uploadFile);
}

View File

@ -88,6 +88,7 @@ export function editorSyscalls(editor: Client): SysCallMapping {
if (evt.target?.readyState == FileReader.DONE) {
resolve({
name: file.name,
contentType: file.type,
content: new Uint8Array(await file.arrayBuffer()),
});
}