1
0
silverbullet/plugs/editor/upload.ts
prcrst ae9c8dcb4c
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>
2023-11-23 12:09:48 +01:00

50 lines
1.2 KiB
TypeScript

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);
}