2023-11-23 11:09:48 +00:00
|
|
|
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 finalFileName = await editor.prompt(
|
|
|
|
"File name for pasted attachment",
|
2023-12-19 17:59:12 +00:00
|
|
|
file.name,
|
2023-11-23 11:09:48 +00:00
|
|
|
);
|
|
|
|
if (!finalFileName) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
await space.writeAttachment(
|
2023-12-19 17:59:12 +00:00
|
|
|
prefix + finalFileName,
|
2023-11-23 11:09:48 +00:00
|
|
|
file.content,
|
|
|
|
);
|
|
|
|
let attachmentMarkdown = `[${finalFileName}](${encodeURI(finalFileName)})`;
|
2023-11-25 12:40:27 +00:00
|
|
|
if (file.contentType?.startsWith("image/")) {
|
2023-11-23 11:09:48 +00:00
|
|
|
attachmentMarkdown = `![](${encodeURI(finalFileName)})`;
|
|
|
|
}
|
|
|
|
editor.insertAtCursor(attachmentMarkdown);
|
|
|
|
}
|
|
|
|
|
2023-11-25 17:57:00 +00:00
|
|
|
export async function uploadFile(_ctx: any, accept?: string, capture?: string) {
|
|
|
|
const uploadFile = await editor.uploadFile(accept, capture);
|
2023-11-23 11:09:48 +00:00
|
|
|
await saveFile(uploadFile);
|
2023-12-19 17:59:12 +00:00
|
|
|
}
|