Files
TasGrid/src/lib/extensions/file-upload.ts
T
2026-03-12 17:23:28 -05:00

74 lines
2.8 KiB
TypeScript

import { Extension } from '@tiptap/core';
import { activeTaskId, uploadTaskAttachment, activeNoteId, uploadNoteAttachment } from "@/store";
import { toast } from "solid-sonner";
declare module '@tiptap/core' {
interface Commands<ReturnType> {
fileUpload: {
uploadFile: () => ReturnType;
};
}
}
export const FileUpload = Extension.create({
name: 'fileUpload',
addCommands() {
return {
uploadFile: () => ({ editor }) => {
const taskId = activeTaskId();
const noteId = activeNoteId();
if (!taskId && !noteId) {
toast.error("Cannot upload a file outside of a task or note.");
return false;
}
const input = document.createElement("input");
input.type = "file";
// Accept any file type for generic attachments
input.accept = "*/*";
input.onchange = async () => {
if (input.files?.length) {
const file = input.files[0];
const filesize = file.size.toString();
toast.promise(
(async () => {
if (taskId) {
return uploadTaskAttachment(taskId, file);
} else {
return uploadNoteAttachment(noteId!, file);
}
})(),
{
loading: "Uploading file...",
success: ({ url, filename: pbFilename }) => {
// Insert file attchment UI card
editor.chain()
.focus()
.insertFileAttachment({ src: url, filename: pbFilename, filesize })
.run();
// Manually force a new paragraph at the end so the user can keep typing
// Add paragraph after insertion
editor.chain()
.focus('end')
.insertContent('<p></p>')
.run();
return "File uploaded successfully.";
},
error: "Failed to upload file."
}
);
}
};
input.click();
return true;
},
};
},
});