silverbullet/plugs/editor/upload.ts

62 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

import { editor, space, system } from "@silverbulletmd/silverbullet/syscalls";
import type { UploadFile } from "@silverbulletmd/silverbullet/types";
2024-05-28 02:33:41 +08:00
import {
defaultLinkStyle,
maximumAttachmentSize,
} from "../../web/constants.ts";
import { resolvePath } from "@silverbulletmd/silverbullet/lib/resolve";
import { encodePageURI } from "@silverbulletmd/silverbullet/lib/page_ref";
2024-05-28 02:33:41 +08:00
export async function saveFile(file: UploadFile) {
const maxSize = await system.getSpaceConfig(
2024-05-28 02:33:41 +08:00
"maximumAttachmentSize",
maximumAttachmentSize,
);
if (typeof maxSize !== "number") {
await editor.flashNotification(
2024-05-28 02:33:41 +08:00
"The setting 'maximumAttachmentSize' must be a number",
"error",
);
}
if (file.content.length > maxSize * 1024 * 1024) {
editor.flashNotification(
`Attachment is too large, maximum is ${maxSize}MiB`,
"error",
);
return;
}
const finalFileName = await editor.prompt(
"File name for pasted attachment",
file.name,
);
if (!finalFileName) {
return;
}
2024-05-28 02:33:41 +08:00
const attachmentPath = resolvePath(
await editor.getCurrentPage(),
finalFileName,
);
2024-05-28 02:33:41 +08:00
await space.writeAttachment(attachmentPath, file.content);
const linkStyle = await system.getSpaceConfig(
2024-05-28 02:33:41 +08:00
"defaultLinkStyle",
defaultLinkStyle,
);
let attachmentMarkdown = "";
if (linkStyle === "wikilink") {
attachmentMarkdown = `[[${attachmentPath}]]`;
} else {
attachmentMarkdown = `[${finalFileName}](${encodePageURI(finalFileName)})`;
2024-05-28 02:33:41 +08:00
}
if (file.contentType.startsWith("image/")) {
attachmentMarkdown = "!" + attachmentMarkdown;
}
editor.insertAtCursor(attachmentMarkdown);
}
export async function uploadFile(_ctx: any, accept?: string, capture?: string) {
const uploadFile = await editor.uploadFile(accept, capture);
await saveFile(uploadFile);
}