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. #280

Open
wants to merge 7 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
15 changes: 14 additions & 1 deletion example/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ class Example extends React.Component {

handleChange = debounce(value => {
const text = value();
console.log(text);
localStorage.setItem("saved", text);
}, 250);

Expand Down Expand Up @@ -166,6 +165,20 @@ class Example extends React.Component {
);
});
}}
uploadFile={file => {
console.log("File upload triggered: ", file);

// Delay to simulate time taken to upload
return new Promise(resolve => {
setTimeout(
() =>
resolve(
"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
),
1500
);
});
}}
embeds={[
{
title: "YouTube",
Expand Down
70 changes: 70 additions & 0 deletions src/commands/insertAllFiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { ToastType } from "../types";

const insertAllFiles = function(view, event, 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;

// the user might have dropped multiple files at once, we need to loop
for (const file of files) {
// 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)
Copy link
Member

Choose a reason for hiding this comment

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

The delay between the user starting the upload and the files being inserted will result in strange and potentially broken scenarios – the document content can have changed substantially in that time.

With the image extension a placeholder widget is used to hold the position for this reason, but a better comparison might be the logic when creating a document from the link menu – a "placeholder" link is created and then updated when the document has been successfully created. A similar approach seems necessary here.

Copy link
Author

Choose a reason for hiding this comment

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

let me know if I got this right:

You are suggesting that as soon as a user selects a file using the menu option you want me to insert a place holder to the document and save it. And then start the file upload process. Once the file is uploaded just replace the link.

is that what you are suggesting?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, here's the existing code:

const href = `creating#${title}…`;
// Insert a placeholder link
dispatch(
view.state.tr
.insertText(title, from, to)
.addMark(
from,
to + title.length,
state.schema.marks.link.create({ href })
)
);
createAndInsertLink(view, title, href, {
onCreateLink,
onShowToast,
dictionary,
});

A "placeholder" link is created with a temporary url while the document is being created. Once it's uploaded the href is swapped out. We could also target the temporary link in css to maybe fade it out or similar while the upload is happening.

.then(src => {
const title = file.name;
const href = src;

view.dispatch(
view.state.tr
.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;
62 changes: 60 additions & 2 deletions src/components/BlockMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Input from "./Input";
import VisuallyHidden from "./VisuallyHidden";
import getDataTransferFiles from "../lib/getDataTransferFiles";
import insertFiles from "../commands/insertFiles";
import insertAllFiles from "../commands/insertAllFiles";
import getMenuItems from "../menus/block";
import baseDictionary from "../dictionary";

Expand All @@ -22,8 +23,11 @@ type Props = {
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 All @@ -42,6 +46,7 @@ type State = {
class BlockMenu extends React.Component<Props, State> {
menuRef = React.createRef<HTMLDivElement>();
inputRef = React.createRef<HTMLInputElement>();
fileInputRef = React.createRef<HTMLInputElement>();

state: State = {
left: -1000,
Expand Down Expand Up @@ -154,6 +159,8 @@ class BlockMenu extends React.Component<Props, 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 @@ -235,6 +242,12 @@ class BlockMenu extends React.Component<Props, State> {
}
};

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

triggerLinkInput = item => {
this.setState({ insertItem: item });
};
Expand Down Expand Up @@ -273,6 +286,32 @@ class BlockMenu extends React.Component<Props, 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);

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

this.props.onClose();
};

clearSearch() {
const { state, dispatch } = this.props.view;
const parent = findParentNode(node => !!node)(state.selection);
Expand Down Expand Up @@ -344,7 +383,13 @@ class BlockMenu extends React.Component<Props, State> {
}

get filtered() {
const { dictionary, embeds, search = "", uploadImage } = this.props;
const {
dictionary,
embeds,
search = "",
uploadImage,
uploadFile,
} = this.props;
let items: (EmbedDescriptor | MenuItem)[] = getMenuItems(dictionary);
const embedItems: EmbedDescriptor[] = [];

Expand All @@ -370,6 +415,9 @@ class BlockMenu extends React.Component<Props, State> {
// If no image upload callback has been passed, filter the image block out
if (!uploadImage && item.name === "image") return false;

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

const n = search.toLowerCase();
return (
(item.title || "").toLowerCase().includes(n) ||
Expand Down Expand Up @@ -399,7 +447,7 @@ class BlockMenu extends React.Component<Props, 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 @@ -470,6 +518,16 @@ class BlockMenu extends React.Component<Props, State> {
/>
</VisuallyHidden>
)}
{uploadFile && (
<VisuallyHidden>
<input
type="file"
ref={this.fileInputRef}
onChange={this.handleFilePicked}
accept="*"
Copy link
Member

Choose a reason for hiding this comment

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

Makes sense to make this a prop

Copy link
Author

Choose a reason for hiding this comment

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

are you talking about the default accept prop?

/>
</VisuallyHidden>
)}
</Wrapper>
</Portal>
);
Expand Down
12 changes: 12 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,14 @@ export type Props = {
[name: string]: (view: EditorView, event: Event) => boolean;
};
uploadImage?: (file: File) => Promise<string>;
uploadFile?: (file: File) => Promise<string>;
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 @@ -132,6 +135,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 @@ -628,9 +637,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
6 changes: 6 additions & 0 deletions src/menus/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ export default function blockMenuItems(
icon: ImageIcon,
keywords: "picture photo",
},
{
name: "file",
title: "File",
icon: ImageIcon,
Copy link
Member

Choose a reason for hiding this comment

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

Going to need a unique icon here – there isn't a simple "file" icon in the set, but I can get one added.

Copy link
Author

Choose a reason for hiding this comment

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

Yes please get it added will use the same Icon here

keywords: "doc pdf",
},
{
name: "link",
title: dictionary.link,
Expand Down