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>pull/573/head
parent
621c21d26c
commit
ae9c8dcb4c
|
@ -143,5 +143,6 @@ export type LintDiagnostic = {
|
||||||
|
|
||||||
export type UploadFile = {
|
export type UploadFile = {
|
||||||
name: string;
|
name: string;
|
||||||
|
contentType: string;
|
||||||
content: Uint8Array;
|
content: Uint8Array;
|
||||||
}
|
}
|
|
@ -222,3 +222,7 @@ functions:
|
||||||
command:
|
command:
|
||||||
name: "Account: Logout"
|
name: "Account: Logout"
|
||||||
|
|
||||||
|
uploadFileCommand:
|
||||||
|
path: ./upload.ts:uploadFile
|
||||||
|
command:
|
||||||
|
name: "Upload: 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 = `})`;
|
||||||
|
}
|
||||||
|
editor.insertAtCursor(attachmentMarkdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadFile() {
|
||||||
|
const uploadFile = await editor.uploadFile();
|
||||||
|
await saveFile(uploadFile);
|
||||||
|
}
|
|
@ -88,6 +88,7 @@ export function editorSyscalls(editor: Client): SysCallMapping {
|
||||||
if (evt.target?.readyState == FileReader.DONE) {
|
if (evt.target?.readyState == FileReader.DONE) {
|
||||||
resolve({
|
resolve({
|
||||||
name: file.name,
|
name: file.name,
|
||||||
|
contentType: file.type,
|
||||||
content: new Uint8Array(await file.arrayBuffer()),
|
content: new Uint8Array(await file.arrayBuffer()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue