Skip to content
This repository has been archived by the owner on Jan 20, 2022. It is now read-only.

feat: Attachment of Files to Documents using S3. #603

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions src/commands/insertAllFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { ToastType } from "../types";


// function findPlaceholderLink(doc, href) {
// let result;

// function findLinks(node, pos = 0) {
// // get text nodes
// if (node.type.name === "text") {
// // get marks for text nodes
// node.marks.forEach(mark => {
// // any of the marks links?
// if (mark.type.name === "link") {
// // any of the links to other docs?
// if (mark.attrs.href === href) {
// result = { node, pos };
// if (result) return false;
// }
// }
// });
// }

// if (!node.content.size) {
// return;
// }

// node.descendants(findLinks);
// }

// findLinks(doc);
// return result;
// }

const insertAllFiles = function(view, event, pos, files, options) {
if (files.length === 0) return;

const {
dictionary,
uploadFile,
onFileUploadStart,
onFileUploadStop,
onShowToast,
} = options;

if (!uploadFile) {
console.warn("uploadFile callback must be defined to handle file uploads.");
return;
}

// okay, we have some dropped files and a handler – lets stop this
// event going any further up the stack
event.preventDefault();

// let the user know we're starting to process the files
if (onFileUploadStart) onFileUploadStart();

// we'll use this to track of how many files have succeeded or failed
let complete = 0;

const { state } = view;
const { from, to } = state.selection;

console.log("state.selection: " + state.selection + "," + from + "," + to);

// the user might have dropped multiple files at once, we need to loop
for (const file of files) {

// Insert a placeholder link
var placeholder = `[${file.name} uploading...]`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This type of placeholder isn't sufficient as the text document can change while the file is uploading – in that case the text will be replaced incorrectly. Instead it should work like the image placeholder with a widget decoration that is then searched for again to find it's current position once the file upload is complete

// const phref = `#uploading_${file.name}`;
view.dispatch(
view.state.tr
.insertText(placeholder, from, to-1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 is a bit strange here

);
// start uploading the file file to the server. Using "then" syntax
// to allow all placeholders to be entered at once with the uploads
// happening in the background in parallel.
uploadFile(file)
.then(src => {
const title = file.name;
const href = src;

// const result = findPlaceholderLink(view.state.doc, phref);
// console.log("placeholder: " + result + "," + result.pos + "," + result.node.nodeSize);
// if (result) {
// view.dispatch(
// view.state.tr
// .removeMark(
// result.pos,
// result.pos + result.node.nodeSize,
// state.schema.marks.link
// )
// );
// }

view.dispatch(
view.state.tr
.delete(from, to + placeholder.length)
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
})
.catch(error => {
console.error(error);
if (onShowToast) {
onShowToast(dictionary.fileUploadError, ToastType.Error);
}
})
// eslint-disable-next-line no-loop-func
.finally(() => {
complete++;

// once everything is done, let the user know
if (complete === files.length) {
if (onFileUploadStop) onFileUploadStop();
}
});
}
};

export default insertAllFiles;
61 changes: 60 additions & 1 deletion src/components/CommandMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import VisuallyHidden from "./VisuallyHidden";
import getDataTransferFiles from "../lib/getDataTransferFiles";
import filterExcessSeparators from "../lib/filterExcessSeparators";
import insertFiles from "../commands/insertFiles";
import insertAllFiles from "../commands/insertAllFiles";
import baseDictionary from "../dictionary";

const SSR = typeof window === "undefined";
Expand All @@ -29,8 +30,11 @@ export type Props<T extends MenuItem = MenuItem> = {
view: EditorView;
search: string;
uploadImage?: (file: File) => Promise<string>;
uploadFile?: (file: File) => Promise<string>;
onImageUploadStart?: () => void;
onImageUploadStop?: () => void;
onFileUploadStart?: () => void;
onFileUploadStop?: () => void;
onShowToast?: (message: string, id: string) => void;
onLinkToolbarOpen?: () => void;
onClose: () => void;
Expand Down Expand Up @@ -61,6 +65,7 @@ type State = {
class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
menuRef = React.createRef<HTMLDivElement>();
inputRef = React.createRef<HTMLInputElement>();
fileInputRef = React.createRef<HTMLInputElement>();

state: State = {
left: -1000,
Expand Down Expand Up @@ -177,6 +182,8 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
switch (item.name) {
case "image":
return this.triggerImagePick();
case "file":
return this.triggerFilePick();
case "embed":
return this.triggerLinkInput(item);
case "link": {
Expand Down Expand Up @@ -254,6 +261,12 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
}
};

triggerFilePick = () => {
if (this.fileInputRef.current) {
this.fileInputRef.current.click();
}
};

triggerLinkInput = item => {
this.setState({ insertItem: item });
};
Expand Down Expand Up @@ -294,6 +307,38 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
this.props.onClose();
};

handleFilePicked = event => {
const files = getDataTransferFiles(event);

const {
view,
uploadFile,
onFileUploadStart,
onFileUploadStop,
onShowToast,
} = this.props;
const { state } = view;
const parent = findParentNode(node => !!node)(state.selection);

this.clearSearch();

if (parent) {
insertAllFiles(view, event, parent.pos, files, {
uploadFile,
onFileUploadStart,
onFileUploadStop,
onShowToast,
dictionary: this.props.dictionary,
});
}

if (this.inputRef.current) {
this.inputRef.current.value = "";
}

this.props.onClose();
};

clearSearch = () => {
this.props.onClearSearch();
};
Expand Down Expand Up @@ -400,6 +445,7 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
embeds = [],
search = "",
uploadImage,
uploadFile,
commands,
filterable = true,
} = this.props;
Expand All @@ -425,6 +471,9 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
const filtered = items.filter(item => {
if (item.name === "separator") return true;

// If file upload callback has been passed, filter the file block in
if (uploadFile && item.name === "file") return true;

// Some extensions may be disabled, remove corresponding menu items
if (
item.name &&
Expand Down Expand Up @@ -454,7 +503,7 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
}

render() {
const { dictionary, isActive, uploadImage } = this.props;
const { dictionary, isActive, uploadImage, uploadFile } = this.props;
const items = this.filtered;
const { insertItem, ...positioning } = this.state;

Expand Down Expand Up @@ -522,6 +571,16 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
/>
</VisuallyHidden>
)}
{uploadFile && (
<VisuallyHidden>
<input
type="file"
ref={this.fileInputRef}
onChange={this.handleFilePicked}
accept="*"
/>
</VisuallyHidden>
)}
</Wrapper>
</Portal>
);
Expand Down
1 change: 1 addition & 0 deletions src/dictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const base = {
alignImageDefault: "Center large",
em: "Italic",
embedInvalidLink: "Sorry, that link won’t work for this embed type",
file: "File",
findOrCreateDoc: "Find or create a doc…",
h1: "Big heading",
h2: "Medium heading",
Expand Down
13 changes: 13 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export type Props = {
| "heading"
| "hr"
| "image"
| "file"
| "list_item"
| "container_notice"
| "ordered_list"
Expand All @@ -135,13 +136,16 @@ export type Props = {
[name: string]: (view: EditorView, event: Event) => boolean;
};
uploadImage?: (file: File) => Promise<string>;
uploadFile?: (file: File) => Promise<string>;
onBlur?: () => void;
onFocus?: () => void;
onSave?: ({ done: boolean }) => void;
onCancel?: () => void;
onChange?: (value: () => string) => void;
onImageUploadStart?: () => void;
onImageUploadStop?: () => void;
onFileUploadStart?: () => void;
onFileUploadStop?: () => void;
onCreateLink?: (title: string) => Promise<string>;
onSearchLink?: (term: string) => Promise<SearchResult[]>;
onClickLink: (href: string, event: MouseEvent) => void;
Expand Down Expand Up @@ -180,6 +184,12 @@ class RichMarkdownEditor extends React.PureComponent<Props, State> {
onImageUploadStop: () => {
// no default behavior
},
onFileUploadStart: () => {
// no default behavior
},
onFileUploadStop: () => {
// no default behavior
},
onClickLink: href => {
window.open(href, "_blank");
},
Expand Down Expand Up @@ -805,9 +815,12 @@ class RichMarkdownEditor extends React.PureComponent<Props, State> {
search={this.state.blockMenuSearch}
onClose={this.handleCloseBlockMenu}
uploadImage={this.props.uploadImage}
uploadFile={this.props.uploadFile}
onLinkToolbarOpen={this.handleOpenLinkMenu}
onImageUploadStart={this.props.onImageUploadStart}
onImageUploadStop={this.props.onImageUploadStop}
onFileUploadStart={this.props.onFileUploadStart}
onFileUploadStop={this.props.onFileUploadStop}
onShowToast={this.props.onShowToast}
embeds={this.props.embeds}
/>
Expand Down
7 changes: 7 additions & 0 deletions src/menus/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
TableIcon,
TodoListIcon,
ImageIcon,
NotepadIcon,
StarredIcon,
WarningIcon,
InfoIcon,
Expand Down Expand Up @@ -115,6 +116,12 @@ export default function blockMenuItems(
icon: ImageIcon,
keywords: "picture photo",
},
{
name: "file",
title: dictionary.file,
icon: NotepadIcon,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd use the DocumentIcon for now, it looks like a file

keywords: "doc pdf",
},
{
name: "link",
title: dictionary.link,
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@
"dist",
"node_modules"
]
}
}