Needs testing: frontend (javascript) code for image uploads.


Needs testing: frontend (javascript) code for image uploads.

I was trying to create the image upload functionality of *writefreely*. The spec said that after the user drops an image on the textarea a markdown image placeholder should appear [image](file.png), just like it happens on discourse.

However there were a few challenges. *Writefreely* is a blogging platform, not a forum, so longer texts are possible, if not common. Appending the markdown at the end of the text, especially if the text overflows the viewport is bad user interface as the user will have no confirmation whether his action had a result or not (the text would have been appended off-screen). Also, in blog posts we often append larger images which take some time to upload, so a progress indicator would be useful.

Another challenge was multiple uploads. Since additional markup isn't allowed inside the textarea I had to find a way to update the right markdown block when the respective file upload updates or finishes.

Lastly the default action when one hovers a file over a textarea, the browser insinuates that the file will be dropped in a specific place under the mouse cursor by showing a text cursor in the text. However it doesn't give the developers any way to know where that text will be dropped. It does drop the local file:// URI however so we can replace that with our markdown. What if the user had the same file:// uri elsewhere in the text, however? Perhaps he was writing about including local files in markdown documents.

The above function does not work reliably in Chrome on GNOME. Sometimes it inserts the file:// URI under the cursor and sometimes it navigates to the image directly. So I'll probably have to browser-sniff there (bad, I know)

So the solution had to deal with the following stuff:

  1. Insert the image in the last editing position unless the browser allows you to drop at a specific place
  2. If the browser allows you to drop at a specific place, do it.
  3. Update the markdown with progress and when the upload is done go replace the loading thing with the remote filename the server returned

This is simple. You can use textarea.selectionStart and textarea.selectionEnd to get the selection index (if text is selected) or the cursor position if these two values are equal. If text is selected replace with the dropped image.

This was not so simple and despite being able to create a demo this did not work for more than one files (this is fixable) nor it could work in chrome (this doesn't seem fixable, chrome sometimes drops the file:// URI in the textarea and others navigates to it). Thus I'm inclined to drop this functionality as the code for it is dirty anyway. [And then I found out that this doesn't work on Windows/MacOS so yeah...][Now I have dropped this]

<video><source src="http://qwazix.com/shared/firefox%20dropping%20in%20place.webm" type="video/webm"></video>

However I'd like to talk about my solution: in the drop event textarea.value still holds the text without the file:// URI. However ten milliseconds later the text has already updated. Here's why the dirty code: a setTimeout({...},10) that allow us to get to the updated text. We can then iterate over all the occurrences of file://.*?/filename.ext and check if they exist in the previous text. If we find one that doesn't then we can replace that with our markdown. This is the code:

        function insertTextAtDropPoint(text, textarea, filename){
            if (textarea.nodeName == "TEXTAREA") {
                // save cursor position so that we can set it
                // back after the operation on value
                var startingPosition = textarea.selectionStart;
                var rxp = new RegExp('file://.*?/'+filename);
                textarea.value = replaceNewPatternInString(rxp, oldtext, textarea.value, text);
                // set the cursor to its original position
                textarea.selectionStart = textarea.selectionEnd = startingPosition + text.length;
            } else throw "Element is not a textarea"

function replaceNewPatternInString(pattern, oldstring, newstring, replacement){
            var index = 0;
            do {
                // find first occurence of pattern
                var match = newstring.substr(index, newstring.length).match(pattern);
                index += match.index;
                // take the part of the string from the beginning until
                // the end of the pattern
                // and check if you can find it in the old string
                // if you can go to the next occurence of the pattern
                // until you find one
                // that doesn't exist in the old string.
                index += match[0].length;
            } while (oldstring.indexOf(newstring.substr(0, index)) != -1);
            return newstring.substr(0,index-match[0].length) + replacement + newstring.substr(index,newstring.length);

Still, believing that the file will be dropped under the cursor (which is probably the user's expectation when they see the moving I cursor) and then have it dropped in the last edit position is not good UX. Chrome disables that animation if you preventDefault() on dragover but Firefox does not so I'll have to resort to using pointer-events to disable that functionality. [Update: it looks like doing preventDefault() on dragenter resolves this nicely]

We don't have additional markup inside the textarea so if the user drops multiple files we need to know which one to update when the upload progresses or finishes. *Discourse* solves this by using filenames and appending numbers to them if it finds the same filename being already used. I decided that creating a temporary hash is simpler so I prepend one before each filename, making the markdown unique. Then it's a matter of search and replace to update progress.

Replacing text in the textarea entails getting the contents, changing them in javascript and putting them back in. This causes the spellcheck to fire again creating a subtle flicker in the wavy red lines. I was testing with *lorem ipsum* which has wavy red lines everywhere and that flicker quickly became annoying. Updating the progress every 5, or even 10% makes that annoyance a lot less noticeable and I suspect that in regular text with much less misspelled words this will not be an issue.

Finally, after each change we also need to put the cursor back to where it was because updating textarea.value sets the cursor to the end.

This was surprisingly easy. I just copied everything into pad.tmpl and it (almost) just worked. I had to point the xhr endpoint to my upload.php test file and enable CORS there but this was trivial.

  1. Backend

Next step: backend image handling.

Also posted here: https://mixt.qwazix.com/d/naac7l07tr
Individual commits while I developed this: https://github.com/qwazix/minimalist-ajax-upload/commits/dragDrop


qwazixAuthored on Jul 12 2019, 12:03 PM
rWF71fb63580a38: Merge branch 'master' into develop