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](https://www.discourse.org/).

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](http://qwazix.com/shared/firefox%20dropping%20in%20place.webm) 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:

``` javascript
        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);
                console.log(rxp);
                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.

 ## 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
image-upload-drag
Michael Demetriou 5 years ago
parent 71fb63580a
commit 6cca097de0
  1. 96
      templates/pad.tmpl

@ -357,6 +357,102 @@
} catch (e) {
// whatevs
}
var allowedFileTypes = ["image/png", "image/jpeg"];
// using getElementsByTagName instead of querySelector for
// more backward compatibility (and probably performance)
var dropbox = document.getElementsByTagName("body")[0];
dropbox.addEventListener("drop", drop, true);
dropbox.addEventListener("dragover", function(e){e.preventDefault()}, true)
// firefox needs this too in order to not show the floating cursor on linux
// see [blogpost] for why we don't want this
dropbox.addEventListener("dragenter", function(e){e.preventDefault()}, true)
var textarea = document.getElementsByTagName("textarea")[0];
function drop(e) {
e.preventDefault();
var files = e.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// from https://stackoverflow.com/a/1818400/400257
description = file.name.substr(0, file.name.lastIndexOf('.')) || file.name;
file.identifier = description+"_"+Math.random().toString(36).substring(2, 15);
file.progress = 0;
markdown = " [" + file.identifier + "](00%) ";
// if we drop on a textarea, on firefox, we can get the position of the drop
// by searching for the 'file://' uri that it appends to the textarea by default
insertTextAtCursor(markdown, textarea);
handleFile(file);
}
}
function insertTextAtCursor(text, textarea){
if (textarea.nodeName == "TEXTAREA") {
// save cursor position so that we can set it back after the operation on value
var startingPosition = textarea.selectionStart;
var textBeforeCursor = textarea.value.substring(0, textarea.selectionStart);
var textAfterCursor = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
textarea.value = textBeforeCursor + text + textAfterCursor;
// set the cursor to its original position
textarea.selectionStart = textarea.selectionEnd = startingPosition + text.length;
} else throw "Element is not a textarea"
}
function handleFile(file){
var ok = false;
for (var i in allowedFileTypes){
if (file.type.match(allowedFileTypes[i])) {ok=true; break;}
}
if (!ok) throw "disallowed file type";
// var reader = new FileReader();
// reader.readAsDataURL(file);
var xhr = new XMLHttpRequest();
// progressMgmt(xhr,file,img);
xhr.open("POST", "http://localhost/minimalist-ajax-upload/upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var startingPosition = textarea.selectionStart;
var loaded = Math.ceil((e.loaded / e.total)*100);
if (file.progress + 5 < loaded){
file.progress = loaded;
textarea.value = textarea.value.replace(getMarkdownRegex(file.identifier), "["+ file.identifier +"]("+padLeft(loaded,2)+"%)");
textarea.selectionStart = textarea.selectionEnd = startingPosition;
}
}
}
var formData = new FormData();
formData.append('file', file);
xhr.send(formData);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
processResponse(xhr.responseText, file.identifier);
}
}
}
function processResponse(responseText, identifier){
var response = JSON.parse(responseText);
description = response.name.substr(0, response.name.lastIndexOf('.')) || response.name;
textarea.value = textarea.value.replace(getMarkdownRegex(identifier), "["+ description +"]("+response.url+")");
}
function getMarkdownRegex(identifier){
return new RegExp('\\[' + identifier + '\\]\\(.*?\\)');
}
function padLeft(number, padTo, str){
return Array(padTo-String(number).length+1).join(str||'0')+number;
}
</script>
<link href="/css/icons.css" rel="stylesheet">
</body>

Loading…
Cancel
Save