Эх сурвалжийг харах

Merge pull request #42 from dom111/master-topic-2-entire_page_dropzone

Entire page dropzone and add mobile friendly upload control
Dom Hastings 6 жил өмнө
parent
commit
17b4031c31

+ 1 - 1
.editorconfig

@@ -7,7 +7,7 @@ insert_final_newline = true
 indent_style = space
 indent_size = 4
 
-[{package.json,.travis.yml,Dockerfile}]
+[{package.json,.travis.yml,Dockerfile,*.css,*.scss}]
 indent_style = space
 indent_size = 2
 

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
assets/css/style-min.css


+ 18 - 5
assets/css/style.css

@@ -7,6 +7,15 @@ ul {
   font-family: Helvetica, Arial, Sans-serif;
 }
 
+/* body too small for entire page */
+html {
+  height: 100%;
+}
+
+body {
+  min-height: 100%;
+}
+
 li {
   list-style: none;
 }
@@ -32,6 +41,10 @@ a {
   overflow-x: scroll;
 }
 
+body.active {
+  background: #ffe;
+}
+
 /* Items */
 div.content {
   padding: 20px;
@@ -59,6 +72,11 @@ ul.list li:first-child {
   border-top: 0;
 }
 
+ul.list li.active {
+  background: #ffc;
+  color: #000;
+}
+
 ul.list li.loading {
   background-size: contain;
 }
@@ -187,11 +205,6 @@ div.upload {
   transition: .5s;
 }
 
-div.upload.active {
-  background: #ffc;
-  color: #000;
-}
-
 div.upload a {
   font-size: inherit;
   color: #22a;

+ 17 - 5
assets/scss/style.scss

@@ -7,6 +7,14 @@ ul {
   font-family: Helvetica, Arial, Sans-serif;
 }
 
+/* body too small for entire page */
+html {
+  height: 100%;
+}
+body {
+  min-height: 100%;
+}
+
 li {
   list-style: none;
 }
@@ -32,6 +40,10 @@ a {
   overflow-x: scroll;
 }
 
+body.active {
+  background: #ffe;
+}
+
 /* Items */
 div.content {
   padding: 20px;
@@ -57,6 +69,11 @@ ul.list {
       border-top: 0;
     }
 
+    &.active {
+      background: #ffc;
+      color: #000;
+    }
+
     &.loading {
       background-size: contain;
     }
@@ -188,11 +205,6 @@ div.upload {
   border-radius: 5px;
   transition: .5s;
 
-  &.active {
-    background: #ffc;
-    color: #000;
-  }
-
   a {
     font-size: inherit;
     color: #22a;

+ 1 - 1
index.html

@@ -43,7 +43,7 @@
                     <aside class="options">
                         <h3>Use it</h3>
                         <p>There's a <a href="https://github.com/dom111/webdav-js">github repository</a> where you can download the source that also includes example implementations.</p>
-                        <p>I've also cerated a bookmarklet that you can add to your bookmarks bar:</p>
+                        <p>I've also created a bookmarklet that you can add to your bookmarks bar:</p>
 
                         <p class="text-center">
                             <a href="javascript:!function(){var e;e=[&quot;https://cdn.jsdelivr.net/gh/noelboss/featherlight@1.7.1/release/featherlight.min.js&quot;,&quot;https://cdn.jsdelivr.net/gh/google/code-prettify/loader/run_prettify.js?autorun=false&quot;,&quot;https://cdn.jsdelivr.net/gh/notifyjs/notifyjs/dist/notify.js&quot;,&quot;https://cdn.jsdelivr.net/gh/noelboss/featherlight@1.7.1/release/featherlight.min.css&quot;,&quot;https://cdn.jsdelivr.net/gh/dom111/webdav-js/assets/css/style-min.css&quot;,&quot;https://cdn.jsdelivr.net/gh/dom111/webdav-js/src/webdav-min.js&quot;];var t,n=document.getElementsByTagName(&quot;head&quot;)[0],a=function(e,t){var s=document.createElement(&quot;script&quot;);s.src=e,s.type=&quot;text/javascript&quot;,t&&(s.onload=t),n.appendChild(s)};a(&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js&quot;,function(){e.forEach(function(e){var t,s;e.match(/css$/)?(t=e,(s=document.createElement(&quot;link&quot;)).href=t,s.rel=&quot;stylesheet&quot;,n.appendChild(s)):a(e)})}),(t=document.createElement(&quot;meta&quot;)).name=&quot;viewport&quot;,t.content=&quot;width=device-width, initial-scale=1&quot;,n.appendChild(t)}();" class="btn btn-primary btn-lg">

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
src/webdav-min.js


+ 117 - 54
src/webdav.js

@@ -1,4 +1,4 @@
-(function($) {
+(function($, _decodeURIComponent) {
   if (!('from' in Array)) {
     Array.from = function(arrayLike) {
       return [].slice.call(arrayLike);
@@ -24,7 +24,6 @@
     var _bindEvents = function(file) {
       if (file.directory) {
         file.item.find('.title').on('click', function() {
-          history.pushState(history.state, file.path + file.name, file.path + file.name);
           WebDAV.list(file.path + file.name);
 
           return false;
@@ -77,6 +76,12 @@
                     var deferred = $.Deferred(),
                     $container = $('<pre class="prettyprint"></pre>');
                     $.ajax(url, {
+                      // @url https://decadecity.net/blog/2013/06/21/preventing-script-execution-with-jquerys-ajax-function
+                      converters: {
+                        'text script': function (text) {
+                          return text;
+                        }
+                      },
                       complete: function(response, status) {
                         if (status !== "error") {
                           $container.text(response.responseText);
@@ -203,11 +208,11 @@
       if (file.name) {
         if (file['delete']) {
           file.item.append('<a href="#delete" title="Delete" class="delete">delete</a>');
-          file.item.append('<a href="#move" title="Move" class="move">move</a>');
+          // file.item.append('<a href="#move" title="Move" class="move">move</a>'); // TODO
         }
 
         file.item.append('<a href="#rename" title="Rename" class="rename">rename</a>');
-        file.item.append('<a href="#copy" title="Copy" class="copy">copy</a>');
+        // file.item.append('<a href="#copy" title="Copy" class="copy">copy</a>'); // TODO
 
         if (!file.directory) {
           file.item.append('<a href="' + file.path + file.name + '" download="' + file.title + '" title="Download" class="download">download</a>');
@@ -232,7 +237,7 @@
       return true;
     },
     _makeSafePath = function(path) {
-      return decodeURIComponent(path).replace(/[^\w\/\-\.]/g, function(char) {
+      return _decodeURIComponent(path).replace(/[^\w\/\-\.]/g, function(char) {
         return encodeURIComponent(char);
       });
     },
@@ -385,10 +390,43 @@
       return _files;
     },
     _updateDisplay = function() {
-      document.title = decodeURIComponent(_path) + ' - ' + window.location.host;
+      document.title = _decodeURIComponent(_path) + ' - ' + window.location.host;
 
       _renderFiles();
     },
+    _handleUpload = function(newFiles) {
+      if (newFiles && newFiles.length) {
+        $.each(newFiles, function(i, fileObject) {
+          var existingFile = _checkFile(fileObject)
+          if (existingFile) {
+            if (!confirm('A file called "' + existingFile.name + '" already exists, would you like to overwrite it?')) {
+              return false;
+            }
+            else {
+              delete _files[existingFile.index];
+            }
+          }
+
+          if (typeof FileReader != 'undefined') {
+            var fileReader = new FileReader();
+
+            fileReader.addEventListener('load', function(event) {
+              fileObject.data = event.target.result;
+
+              WebDAV.upload(fileObject);
+            }, false);
+
+            fileReader.context = WebDAV;
+            fileReader.filename = fileObject.name;
+            fileReader.readAsArrayBuffer(fileObject);
+          }
+          else {
+            // TODO: support other browsers - flash fallback?
+            _message('Sorry, your browser isn\'t currently suppored.');
+          }
+        });
+      }
+    },
 
     // private vars
     _busy = false,
@@ -401,69 +439,77 @@
     // exposed API
     WebDAV = {
       init: function() {
-        $('<div class="content"></div><div class="upload">Drop&nbsp;files&nbsp;here to&nbsp;upload&nbsp;or <a href="#createDirectory" class="create-directory">create&nbsp;a&nbsp;new directory</a></div>').appendTo($('body').empty());
-
-        $('div.content').append(_list);
+        $('<div class="content"></div><div class="upload"><span class="droppable">Drop&nbsp;files&nbsp;anywhere to&nbsp;upload</span> or <a href="#createDirectory" class="create-directory">create&nbsp;a&nbsp;new directory</a></div>').appendTo($('body').empty());
 
         _dropper = $('div.upload');
 
+        if ('ontouchstart' in document.body) {
+          $('span.droppable').replaceWith('<span>Upload files <input type="file" multiple/></span>');
+
+          _dropper.find('input[type="file"]').on('change', function(event) {
+            var newFiles = event.originalEvent.target.files || event.originalEvent.dataTransfer.files;
+            _handleUpload(newFiles);
+            this.value = null;
+          });
+        }
+
+        $('div.content').append(_list);
+
         WebDAV.list(_path);
 
         // render the nice list
         _renderFiles();
 
         // drag and drop area
-        _dropper.on('dragover', function() {
-          _dropper.addClass('active');
+        $('body').on('dragover dragenter', '.directory', function(event) {
+          event.stopPropagation();
+
+          $(this).addClass('active');
 
           return false;
         });
 
-        _dropper.on('dragend dragleave', function(event) {
-          _dropper.removeClass('active');
+        $('body').on('dragleave', '.directory', function(event) {
+          $(this).removeClass('active');
 
           return false;
         });
 
-        _dropper.on('drop', function(event) {
-          var newFiles = event.originalEvent.target.files || event.originalEvent.dataTransfer.files;
+        $('body').on('dragover', function(event) {
+          $('body').addClass('active');
 
-          _dropper.removeClass('active');
+          return false;
+        });
 
-          $.each(newFiles, function(i, fileObject) {
-            if (existingFile = _checkFile(fileObject)) {
-              if (!confirm('A file called "' + existingFile.name + '" already exists, would you like to overwrite it?')) {
-                return false;
-              }
-              else {
-                delete _files[existingFile.index];
-              }
-            }
+        $('body').on('dragleave dragend', function(event) {
+          $('body').removeClass('active');
+
+          return false;
+        });
 
-            if (typeof FileReader != 'undefined') {
-              var fileReader = new FileReader();
+        $('body').on('drop', function(event) {
+          var dropFile = $(event.target).data('file');
+          var newFiles = event.originalEvent.target.files || event.originalEvent.dataTransfer.files;
 
-              fileReader.addEventListener('load', function(event) {
-                fileObject.data = event.target.result;
+          if ($('body').hasClass('active')) {
+            $('body').removeClass('active');
+          }
 
-                WebDAV.upload(fileObject);
-              }, false);
+          if (dropFile && dropFile.directory) {
+            var path = dropFile.path + dropFile.name;
+            path = path.match(/\/$/) ? path : path + '/'; // ensure we have a trailing slash for some platforms
 
-              fileReader.context = WebDAV;
-              fileReader.filename = fileObject.name;
-              fileReader.readAsArrayBuffer(fileObject);
-            }
-            else {
-              // TODO: support other browsers - flash fallback?
-              _message('Sorry, your browser isn\'t currently suppored.');
-            }
-          });
+            WebDAV.list(path, false, function() {
+              _handleUpload(newFiles);
+            });
+          }
+          else {
+            _handleUpload(newFiles);
+          }
 
           return false;
         });
 
-        // TODO: if drag/drop unsupported, regular file upload box - also needed for flash fallback of FileReader
-
         // create directory
         $('a.create-directory').on('click', function() {
           var name = prompt('New folder name:'),
@@ -558,9 +604,11 @@
           return true;
         });
       },
-      list: function(path, refresh) {
+      list: function(path, refresh, callback) {
         path = path.match(/\/$/) ? path : path + '/'; // ensure we have a trailing slash for some platforms
 
+        history.pushState(history.state, path, path);
+
         if ((path in _cache) && !refresh) {
           _files = [];
 
@@ -569,7 +617,13 @@
             _files.push(_createListItem(file));
           });
 
-          return _updateDisplay();
+          _updateDisplay();
+
+          if (callback && callback.call) {
+            callback();
+          }
+
+          return;
         }
 
         _listContents(path, {
@@ -613,7 +667,7 @@
               _files.push(_createListItem({
                 directory: !!_getTag(entry, 'collection'),
                 name: name,
-                title: decodeURIComponent(name),
+                title: _decodeURIComponent(name),
                 path: _path,
                 modified: new Date(_getTagContent(entry, 'getlastmodified')),
                 size: _getTagContent(entry, 'getcontentlength'),
@@ -630,6 +684,10 @@
             _cache[_path] = _files;
 
             _updateDisplay();
+
+            if (callback && callback.call) {
+              callback();
+            }
           },
           error: function() {
             _message('There was an error getting details for ' + path + '.');
@@ -647,7 +705,7 @@
         var file = {
           directory: false,
           name: fileObject.name,
-          title: decodeURIComponent(fileObject.name),
+          title: _decodeURIComponent(fileObject.name),
           path: _path,
           modified: new Date(),
           size: fileObject.data.byteLength,
@@ -677,25 +735,30 @@
         }, false);
 
         file.request.addEventListener('load', function(event) {
-          _refreshDisplay();
+          var success = this.status < 400; // basic check for now, could do more with these and print more meaningful error messages...
+
+          if (success) {
+            _message(file.title + ' uploaded successfully.', 'success');
+          }
+          else {
+            delete _files[file.index];
 
-          _message(file.title + ' uploaded successfully.', 'sucess');
+            _message('Error uploading file. (' + this.status + ')');
+          }
+
+          _refreshDisplay(true);
         }, false);
 
         file.request.addEventListener('error', function(event) {
           delete _files[file.index];
 
-          _updateDisplay();
-
           _message('Error uploading file.');
         }, false);
 
         file.request.addEventListener('abort', function(event) {
           delete _files[file.index];
 
-          _updateDisplay();
-
-          _message('Aborted as requested.', 'sucess');
+          _message('Aborted as requested.', 'success');
         }, false);
 
         _files.push(_createListItem(file));
@@ -788,4 +851,4 @@
   $(function() {
     WebDAV.init();
   });
-})(jQuery);
+})(jQuery, decodeURIComponent);

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно