diff --git a/assets/js/app.min.js b/assets/js/app.min.js
index 0aa1adcc..f5d9b6e5 100644
--- a/assets/js/app.min.js
+++ b/assets/js/app.min.js
@@ -1 +1 @@
-$(document).ready(function(){$(document).pjax("a[data-pjax]","#content")}),$(document).on("ready pjax:success",function(){function a(a){this.style.height="5px",this.style.height=this.scrollHeight+"px"}return document.title=document.getElementById("site-title").innerHTML,$("textarea").each(a),$("textarea").keyup(a),$(window).resize(function(){$("textarea").each(a)}),$("#logout").click(function(a){return a.preventDefault(),$.ajax({type:"GET",url:"/admin",async:!1,username:"username",password:"password",headers:{Authorization:"Basic xxx"}}).fail(function(){window.location="/"}),!1}),$("main").hasClass("browse")&&$(document).trigger("page:browse"),$(".editor")[0]&&$(document).trigger("page:editor"),!1}),$(document).on("page:browse",function(){$("body").off("click",".delete").on("click",".delete",function(a){return a.preventDefault(),button=$(this),$.ajax({type:"DELETE",url:button.data("file")}).done(function(a){button.parent().parent().fadeOut(),notification({text:button.data("message"),type:"success",timeout:5e3})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}),$(".new").click(function(a){return a.preventDefault(),$(this).data("opened")?($("#new-file").fadeOut(200),$(this).data("opened",!1)):($("#new-file").fadeIn(200),$(this).data("opened",!0)),!1}),$("#new-file").on("keypress","input",function(a){if(13==a.keyCode){a.preventDefault();var b=$(this).val(),c=b.split(":"),d="",e="";if(""==b)return notification({text:"You have to write something. If you want to close the box, click the button again.",type:"warning",timeout:5e3}),!1;if(1==c.length)d=b;else{if(2!=c.length)return notification({text:"Hmm... I don't understand you. Try writing something like 'name[:archetype]'.",type:"error"}),!1;d=c[0],e=c[1]}var f='{"filename": "'+d+'", "archetype": "'+e+'"}';return $.ajax({type:"POST",url:window.location.pathname,data:f,dataType:"json",encode:!0}).done(function(a){notification({text:"File created successfully.",type:"success",timeout:5e3}),$.pjax({url:window.location.pathname.replace("browse","edit")+d,container:"#content"})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}}),$("#upload").click(function(a){return a.preventDefault(),$('.actions input[type="file"]').click(),!1}),$('input[type="file"]').on("change",function(a){a.preventDefault(),files=a.target.files;var b=new FormData;return $.each(files,function(a,c){b.append(a,c)}),$.ajax({url:window.location.pathname,type:"POST",data:b,cache:!1,dataType:"json",headers:{"X-Upload":"true"},processData:!1,contentType:!1}).done(function(a){notification({text:"File(s) uploaded successfully.",type:"success",timeout:5e3}),$.pjax({url:window.location.pathname,container:"#content"})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1})}),$(document).on("page:editor",function(){var a=$("#source-area").data("mode"),b=ace.edit("source-area");b.getSession().setMode("ace/mode/"+a),b.setOptions({wrap:!0,maxLines:1/0,theme:"ace/theme/github",showPrintMargin:!1,fontSize:"1em"}),preview=$("#preview-area"),textarea=$("#content-area"),$("body").on("keypress","input",function(a){return 13==a.keyCode?(a.preventDefault(),$('input[value="Save"]').focus().click(),!1):void 0}),$("form").submit(function(a){a.preventDefault(),$("#preview-area").html("").fadeOut(),$("#preview").data("previewing","false"),$(".CodeMirror").fadeIn(),"undefined"!=typeof b&&b&&b.save();var c=JSON.stringify($(this).serializeJSON()),d=$(this).find("input[type=submit]:focus");return $.ajax({type:"POST",url:window.location,data:c,headers:{"X-Regenerate":d.data("regenerate"),"X-Schedule":d.data("schedule"),"X-Content-Type":d.data("type")},dataType:"json",encode:!0,contentType:"application/json; charset=utf-8"}).done(function(a){notification({text:d.data("message"),type:"success",timeout:5e3})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}),$("body").on("click",".add",function(a){if(a.preventDefault(),defaultID="lorem-ipsum-sin-dolor-amet",$("#"+defaultID).length)return!1;if(block=$(this).parent().parent(),blockType=block.data("type"),blockID=block.attr("id"),block.is("div")&&block.hasClass("frontmatter")&&(block=$(".blocks"),block.append('
')),"object"==blockType){if(newItem=$("#"+defaultID),newItem.html(''),field=$("#name-"+defaultID),!document.cookie.replace(/(?:(?:^|.*;\s*)placeholdertip\s*\=\s*([^;]*).*$)|^.*$/,"$1")){var b=new Date;b.setDate(b.getDate()+365),document.cookie="placeholdertip=true; expires="+b.toUTCString+"; path=/",notification({text:'Write the field name and then press enter. If you want to create an array or an object, end the name with ":array" or ":object".',type:"information"})}$(field).keypress(function(a){return 13==a.which?(a.preventDefault(),value=field.val(),""==value?(newItem.remove(),!1):(elements=value.split(":"),elements.length>2?(notification({text:"Invalid syntax. It must be 'name[:type]'.",type:"error"}),!1):2==elements.length&&"array"!=elements[1]&&"object"!=elements[1]?(notification({text:"Only arrays and objects are allowed.",type:"error"}),!1):(field.remove(),"undefined"==typeof blockID?blockID=elements[0]:blockID=blockID+"["+elements[0]+"]",1==elements.length?(newItem.attr("id","block-"+blockID),newItem.append(' '),newItem.prepend(' ')):(type="","array"==elements[1]?type="array":type="object",template='',template=template.replace("${blockID}",blockID),template=template.replace("${elements[0]}",elements[0]),template=template.replace("${type}",type),newItem.after(template),newItem.remove(),console.log('"'+blockID+'" block of type "'+type+'" added.')),!1))):void 0})}return!1}),textarea[0]&&(options={mode:textarea.data("mode"),theme:"ttcn",lineWrapping:!0,lineNumbers:!0,scrollbarStyle:null},"markdown"==textarea.data("mode")&&(options.lineNumbers=!1),b=CodeMirror.fromTextArea(textarea[0],options),codemirror=$(".CodeMirror"),$("#preview").click(function(a){if(a.preventDefault(),"true"==$(this).data("previewing"))preview.hide(),codemirror.fadeIn(),$(this).data("previewing","false"),notification({text:"Think, relax and do the better you can!",type:"information",timeout:2e3});else{b.save();var c=new showdown.Converter,d=textarea.val(),e=c.makeHtml(d);codemirror.hide(),preview.html(e).fadeIn(),$(this).data("previewing","true"),notification({text:"This is how your post looks like.",type:"information",timeout:2e3})}return!1})),$("body").on("click",".delete",function(a){return a.preventDefault(),button=$(this),name=button.parent().parent().attr("for")||button.parent().parent().attr("id")||button.parent().parent().parent().attr("id"),name=name.replace(/\[/,"\\["),name=name.replace(/\]/,"\\]"),console.log(name),$('label[for="'+name+'"]').fadeOut().remove(),$("#"+name).fadeOut().remove(),!1})}),$.noty.themes.admin={name:"admin",helpers:{},modal:{css:{position:"fixed",width:"100%",height:"100%",backgroundColor:"#000",zIndex:1e4,opacity:.6,display:"none",left:0,top:0}}},$.noty.defaults={layout:"topRight",theme:"admin",dismissQueue:!0,animation:{open:"animated bounceInRight",close:"animated fadeOut",easing:"swing",speed:500},timeout:!1,force:!1,modal:!1,maxVisible:5,killer:!1,closeWith:["click"],callback:{onShow:function(){},afterShow:function(){},onClose:function(){},afterClose:function(){},onCloseClick:function(){}},buttons:!1},notification=function(a){var b;switch(a.type){case"success":b='';break;case"error":b='';break;case"warning":b='';break;case"information":b='';break;default:b=''}var c={template:'
'+b+'
'};if(a=$.extend({},c,a),noty(a),!document.cookie.replace(/(?:(?:^|.*;\s*)stickynoties\s*\=\s*([^;]*).*$)|^.*$/,"$1")&&!a.timeout){var d=new Date;d.setDate(d.getDate()+365),document.cookie="stickynoties=true; expires="+d.toUTCString+"; path=/",notification({text:"Some notifications are sticky. If it doesn't go away, click to dismiss it.",type:"information"})}};
\ No newline at end of file
+$(document).ready(function(){$(document).pjax("a[data-pjax]","#content")}),$(document).on("ready pjax:success",function(){function a(a){this.style.height="5px",this.style.height=this.scrollHeight+"px"}return document.title=document.getElementById("site-title").innerHTML,$("textarea").each(a),$("textarea").keyup(a),$(window).resize(function(){$("textarea").each(a)}),$("#logout").click(function(a){return a.preventDefault(),$.ajax({type:"GET",url:"/admin",async:!1,username:"username",password:"password",headers:{Authorization:"Basic xxx"}}).fail(function(){window.location="/"}),!1}),$("main").hasClass("browse")&&$(document).trigger("page:browse"),$(".editor")[0]&&$(document).trigger("page:editor"),!1}),$(document).on("page:browse",function(){$("body").off("click",".rename").on("click",".rename",function(a){a.preventDefault(),button=$(this);var b=prompt("New file name:");if(""==b)return!1;"/"!=b.substring(0,1)&&(b=window.location.pathname.replace("/admin/browse/","")+"/"+b);var c='{"filename": "'+b+'"}';return $.ajax({type:"PUT",url:button.data("file"),data:c,dataType:"json",encode:!0}).done(function(a){$.pjax({url:window.location.pathname,container:"#content"}),notification({text:button.data("message"),type:"success",timeout:5e3})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}),$("body").off("click",".delete").on("click",".delete",function(a){return a.preventDefault(),button=$(this),$.ajax({type:"DELETE",url:button.data("file")}).done(function(a){button.parent().parent().fadeOut(),notification({text:button.data("message"),type:"success",timeout:5e3})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}),$(".new").off("click").click(function(a){return a.preventDefault(),$(this).data("opened")?($("#new-file").fadeOut(200),$(this).data("opened",!1)):($("#new-file").fadeIn(200),$(this).data("opened",!0)),!1}),$("#new-file").on("keypress","input",function(a){if(13==a.keyCode){a.preventDefault();var b=$(this).val(),c=b.split(":"),d="",e="";if(""==b)return notification({text:"You have to write something. If you want to close the box, click the button again.",type:"warning",timeout:5e3}),!1;if(1==c.length)d=b;else{if(2!=c.length)return notification({text:"Hmm... I don't understand you. Try writing something like 'name[:archetype]'.",type:"error"}),!1;d=c[0],e=c[1]}var f='{"filename": "'+d+'", "archetype": "'+e+'"}';return $.ajax({type:"POST",url:window.location.pathname,data:f,dataType:"json",encode:!0}).done(function(a){notification({text:"File created successfully.",type:"success",timeout:5e3}),$.pjax({url:window.location.pathname.replace("browse","edit")+d,container:"#content"})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}}),$("#upload").click(function(a){return a.preventDefault(),$('.actions input[type="file"]').click(),!1}),$('input[type="file"]').on("change",function(a){a.preventDefault(),files=a.target.files;var b=new FormData;return $.each(files,function(a,c){b.append(a,c)}),$.ajax({url:window.location.pathname,type:"POST",data:b,cache:!1,dataType:"json",headers:{"X-Upload":"true"},processData:!1,contentType:!1}).done(function(a){notification({text:"File(s) uploaded successfully.",type:"success",timeout:5e3}),$.pjax({url:window.location.pathname,container:"#content"})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1})}),$(document).on("page:editor",function(){var a=$("#source-area").data("mode"),b=ace.edit("source-area");b.getSession().setMode("ace/mode/"+a),b.setOptions({wrap:!0,maxLines:1/0,theme:"ace/theme/github",showPrintMargin:!1,fontSize:"1em"}),preview=$("#preview-area"),textarea=$("#content-area"),$("body").on("keypress","input",function(a){return 13==a.keyCode?(a.preventDefault(),$('input[value="Save"]').focus().click(),!1):void 0}),$("form").submit(function(a){a.preventDefault(),$("#preview-area").html("").fadeOut(),$("#preview").data("previewing","false"),$(".CodeMirror").fadeIn(),"undefined"!=typeof b&&b&&b.save();var c=JSON.stringify($(this).serializeJSON()),d=$(this).find("input[type=submit]:focus");return $.ajax({type:"POST",url:window.location,data:c,headers:{"X-Regenerate":d.data("regenerate"),"X-Schedule":d.data("schedule"),"X-Content-Type":d.data("type")},dataType:"json",encode:!0,contentType:"application/json; charset=utf-8"}).done(function(a){notification({text:d.data("message"),type:"success",timeout:5e3})}).fail(function(a){notification({text:"Something went wrong.",type:"error"}),console.log(a)}),!1}),$("body").on("click",".add",function(a){if(a.preventDefault(),defaultID="lorem-ipsum-sin-dolor-amet",$("#"+defaultID).length)return!1;if(block=$(this).parent().parent(),blockType=block.data("type"),blockID=block.attr("id"),block.is("div")&&block.hasClass("frontmatter")&&(block=$(".blocks"),block.append(''),blockType="object"),"array"==blockType&&(newID=blockID+"[]",input=blockID,input=input.replace(/\[/,"\\["),input=input.replace(/\]/,"\\]"),block.append('
div").length+'" data-type="array-item">
')),"object"==blockType){if(newItem=$("#"+defaultID),newItem.html(''),field=$("#name-"+defaultID),!document.cookie.replace(/(?:(?:^|.*;\s*)placeholdertip\s*\=\s*([^;]*).*$)|^.*$/,"$1")){var b=new Date;b.setDate(b.getDate()+365),document.cookie="placeholdertip=true; expires="+b.toUTCString+"; path=/",notification({text:'Write the field name and then press enter. If you want to create an array or an object, end the name with ":array" or ":object".',type:"information"})}$(field).keypress(function(a){return 13==a.which?(a.preventDefault(),value=field.val(),""==value?(newItem.remove(),!1):(elements=value.split(":"),elements.length>2?(notification({text:"Invalid syntax. It must be 'name[:type]'.",type:"error"}),!1):2==elements.length&&"array"!=elements[1]&&"object"!=elements[1]?(notification({text:"Only arrays and objects are allowed.",type:"error"}),!1):(field.remove(),"undefined"==typeof blockID?blockID=elements[0]:blockID=blockID+"["+elements[0]+"]",1==elements.length?(newItem.attr("id","block-"+blockID),newItem.append(' '),newItem.prepend(' ')):(type="","array"==elements[1]?type="array":type="object",template='',template=template.replace("${blockID}",blockID),template=template.replace("${elements[0]}",elements[0]),template=template.replace("${type}",type),newItem.after(template),newItem.remove(),console.log('"'+blockID+'" block of type "'+type+'" added.')),!1))):void 0})}return!1}),textarea[0]&&(options={mode:textarea.data("mode"),theme:"ttcn",lineWrapping:!0,lineNumbers:!0,scrollbarStyle:null},"markdown"==textarea.data("mode")&&(options.lineNumbers=!1),b=CodeMirror.fromTextArea(textarea[0],options),codemirror=$(".CodeMirror"),$("#preview").click(function(a){if(a.preventDefault(),"true"==$(this).data("previewing"))preview.hide(),codemirror.fadeIn(),$(this).data("previewing","false"),notification({text:"Think, relax and do the better you can!",type:"information",timeout:2e3});else{b.save();var c=new showdown.Converter,d=textarea.val(),e=c.makeHtml(d);codemirror.hide(),preview.html(e).fadeIn(),$(this).data("previewing","true"),notification({text:"This is how your post looks like.",type:"information",timeout:2e3})}return!1})),$("body").on("click",".delete",function(a){return a.preventDefault(),button=$(this),name=button.parent().parent().attr("for")||button.parent().parent().attr("id")||button.parent().parent().parent().attr("id"),name=name.replace(/\[/,"\\["),name=name.replace(/\]/,"\\]"),console.log(name),$('label[for="'+name+'"]').fadeOut().remove(),$("#"+name).fadeOut().remove(),!1})}),$.noty.themes.admin={name:"admin",helpers:{},modal:{css:{position:"fixed",width:"100%",height:"100%",backgroundColor:"#000",zIndex:1e4,opacity:.6,display:"none",left:0,top:0}}},$.noty.defaults={layout:"topRight",theme:"admin",dismissQueue:!0,animation:{open:"animated bounceInRight",close:"animated fadeOut",easing:"swing",speed:500},timeout:!1,force:!1,modal:!1,maxVisible:5,killer:!1,closeWith:["click"],callback:{onShow:function(){},afterShow:function(){},onClose:function(){},afterClose:function(){},onCloseClick:function(){}},buttons:!1},notification=function(a){var b;switch(a.type){case"success":b='';break;case"error":b='';break;case"warning":b='';break;case"information":b='';break;default:b=''}var c={template:'
'+b+'
'};if(a=$.extend({},c,a),noty(a),!document.cookie.replace(/(?:(?:^|.*;\s*)stickynoties\s*\=\s*([^;]*).*$)|^.*$/,"$1")&&!a.timeout){var d=new Date;d.setDate(d.getDate()+365),document.cookie="stickynoties=true; expires="+d.toUTCString+"; path=/",notification({text:"Some notifications are sticky. If it doesn't go away, click to dismiss it.",type:"information"})}};
\ No newline at end of file
diff --git a/assets/src/js/browse.js b/assets/src/js/browse.js
index 6086b263..cecaa808 100644
--- a/assets/src/js/browse.js
+++ b/assets/src/js/browse.js
@@ -1,5 +1,48 @@
$(document).on('page:browse', function() {
- $("body").off('click', '.delete').on('click', '.delete', function(event) {
+ $('body').off('click', '.rename').on('click', '.rename', function(event) {
+ event.preventDefault();
+ button = $(this);
+
+ var filename = prompt("New file name:");
+
+ if (filename == "") {
+ return false;
+ }
+
+ if (filename.substring(0, 1) != "/") {
+ filename = window.location.pathname.replace("/admin/browse/", "") + '/' + filename;
+ }
+
+ var content = '{"filename": "' + filename + '"}';
+
+ $.ajax({
+ type: 'PUT',
+ url: button.data("file"),
+ data: content,
+ dataType: 'json',
+ encode: true
+ }).done(function(data) {
+ $.pjax({
+ url: window.location.pathname,
+ container: '#content'
+ });
+ notification({
+ text: button.data("message"),
+ type: 'success',
+ timeout: 5000
+ });
+ }).fail(function(data) {
+ notification({
+ text: 'Something went wrong.',
+ type: 'error'
+ });
+ console.log(data);
+ });
+
+ return false;
+ });
+
+ $('body').off('click', '.delete').on('click', '.delete', function(event) {
event.preventDefault();
button = $(this);
@@ -24,7 +67,7 @@ $(document).on('page:browse', function() {
return false;
});
- $('.new').click(function(event) {
+ $('.new').off('click').click(function(event) {
event.preventDefault();
if ($(this).data("opened")) {
diff --git a/browse/browse.go b/browse/browse.go
index 38cc31bd..c53adbdf 100644
--- a/browse/browse.go
+++ b/browse/browse.go
@@ -9,7 +9,8 @@ import (
)
// ServeHTTP is used to serve the content of Browse page
-// using Browse middleware from Caddy
+// using Browse middleware from Caddy. It handles the requests
+// for DELETE, POST, GET and PUT related to /browse interface.
func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
// Removes the page main path from the URL
r.URL.Path = strings.Replace(r.URL.Path, "/admin/browse", "", 1)
@@ -21,6 +22,8 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request, c *config.Config) (int, e
return POST(w, r, c)
case "GET":
return GET(w, r, c)
+ case "PUT":
+ return PUT(w, r, c)
default:
return 400, errors.New("Invalid method.")
}
diff --git a/browse/put.go b/browse/put.go
new file mode 100644
index 00000000..a8e3f604
--- /dev/null
+++ b/browse/put.go
@@ -0,0 +1,52 @@
+package browse
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "os"
+ "strings"
+
+ "github.com/hacdias/caddy-hugo/config"
+)
+
+// PUT handles the HTTP PUT request for all /admin/browse related requests.
+// Renames a file and/or a folder.
+func PUT(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
+ // Remove both beginning and trailing slashes
+ old := r.URL.Path
+ old = strings.TrimPrefix(old, "/")
+ old = strings.TrimSuffix(old, "/")
+ old = c.Path + old
+
+ // Get the JSON information sent using a buffer
+ buffer := new(bytes.Buffer)
+ buffer.ReadFrom(r.Body)
+
+ // Creates the raw file "map" using the JSON
+ var info map[string]interface{}
+ json.Unmarshal(buffer.Bytes(), &info)
+
+ // Check if filename and archetype are specified in
+ // the request
+ if _, ok := info["filename"]; !ok {
+ return 400, errors.New("Filename not specified.")
+ }
+
+ // Sanitize the file name path
+ new := info["filename"].(string)
+ new = strings.TrimPrefix(new, "/")
+ new = strings.TrimSuffix(new, "/")
+ new = c.Path + new
+
+ err := os.Rename(old, new)
+
+ if err != nil {
+ return 500, err
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte("{}"))
+ return 200, nil
+}