笔记信息, 历史记录, 提示, 附件优化

https://github.com/leanote/leanote/issues/224
This commit is contained in:
lealife
2015-10-10 16:10:54 +08:00
parent 274875c6c4
commit 320263eefa
58 changed files with 2078 additions and 5398 deletions

View File

@ -0,0 +1,144 @@
// upload attachment
// 依赖note
var urlPrefix = UrlPrefix;
define('attachment_upload', ['jquery.ui.widget', 'fileupload'], function(){
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
function setDropStyle(dropzoneId, formId) {
// drag css
var dropZone = $(dropzoneId);
$(formId).bind('dragover', function (e) {
e.preventDefault();
var timeout = window.dropZoneTimeoutAttach;
if(timeout) {
clearTimeout(timeout);
}
var found = false,
node = e.target;
do {
if (node === dropZone[0]) {
found = true;
break;
}
node = node.parentNode;
} while (node != null);
if (found) {
dropZone.addClass('hover');
} else {
dropZone.removeClass('hover');
}
window.dropZoneTimeoutAttach = setTimeout(function () {
window.dropZoneTimeoutAttach = null;
dropZone.removeClass('in hover');
}, 100);
});
}
setDropStyle("#dropAttach", "#uploadAttach");
var initUploader = function() {
$('.dropzone .btn-choose-file').click(function() {
$(this).parent().find('input').click();
});
var $msg = $('#attachUploadMsg');
// Initialize the jQuery File Upload plugin
$('#uploadAttach').fileupload({
dataType: 'json',
pasteZone: '', // 不能通过paste来上传图片
// This element will accept file drag/drop uploading
dropZone: $('#dropAttach'),
formData: function(form) {
return [{name: 'noteId', value: Note.curNoteId}] // 传递笔记本过去
},
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function(e, data) {
var note = Note.getCurNote();
if(!note || note.IsNew) {
alert("This note hasn't saved, please save it firstly!")
return;
}
var tpl = $('<div class="alert alert-info"><img class="loader" src="/tinymce/plugins/leaui_image/public/images/ajax-loader.gif"> <a class="close" data-dismiss="alert">×</a></div>');
// Append the file name and file size
tpl.append(data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small>');
// Add the HTML to the UL element
$msg.html(tpl);
data.context = $msg;
// 检查文件大小
var size = data.files[0].size;
var maxFileSize = +GlobalConfigs["uploadAttachSize"] || 100;
if(typeof size == 'number' && size > 1024 * 1024 * maxFileSize) {
tpl.find("img").remove();
tpl.removeClass("alert-info").addClass("alert-danger");
tpl.append(" Warning: File size is bigger than " + maxFileSize + "M");
setTimeout((function(tpl) {
return function() {
tpl.remove();
}
})(tpl), 3000);
return;
}
// Automatically upload the file once it is added to the queue
var jqXHR;
setTimeout(function() {
jqXHR = data.submit();
}, 10);
},
/*
progress: function (e, data) {
},
*/
done: function(e, data) {
if (data.result.Ok == true) {
data.context.html("");
Attach.addAttach(data.result.Item);
} else {
var re = data.result;
data.context.html("");
var tpl = $('<div class="alert alert-danger"><a class="close" data-dismiss="alert">×</a></div>');
tpl.append('<b>Error:</b> ' + data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small> ' + data.result.Msg);
data.context.html(tpl);
setTimeout((function(tpl) {
return function() {
tpl.remove();
}
})(tpl), 3000);
}
$("#uploadAttachMsg").scrollTop(1000);
},
fail: function(e, data) {
data.context.html("");
var tpl = $('<div class="alert alert-danger"><a class="close" data-dismiss="alert">×</a></div>');
tpl.append('<b>Error:</b> ' + data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small> ' + data.errorThrown);
data.context.html(tpl);
setTimeout((function(tpl) {
return function() {
tpl.remove();
}
})(tpl), 3000);
$("#uploadAttachMsg").scrollTop(1000);
}
});
};
initUploader();
});

View File

@ -0,0 +1,404 @@
// for editor.
// drag image to editor
var urlPrefix = UrlPrefix; // window.location.protocol + "//" + window.location.host;
define('editor_drop_paste', ['jquery.ui.widget', 'fileupload'], function(){
function Process(editor) {
var id = '__mcenew' + (new Date()).getTime();
var str = '<div contenteditable="false" id="' + id + '" class="leanote-image-container">' +
'<img class="loader" src="/images/ajax-loader.gif">' +
'<div class="progress">' +
'<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="2" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">' +
'0%' +
'</div>' +
'</div>' +
'</div>';
this.containerStr = str;
editor.insertContent(str);
var container = $('#' + id);
this.container = container;
this.id = id;
this.processBar = container.find('.progress-bar');
}
Process.prototype.update = function(process) {
var me = this;
// 98%, 不要小数
process = Math.ceil(process * 100);
if(process >= 100) {
process = 99;
}
process += "%";
$('#' + me.id + ' .progress-bar').html(process).css('width', process);
}
Process.prototype.replace = function(src) {
var me = this;
getImageSize(src, function() {
$('#' + me.id).replaceWith('<img src="' + src + '" />');
});
}
Process.prototype.remove = function() {
var me = this;
$('#' + me.id).remove();
}
// 当url改变时, 得到图片的大小
function getImageSize(url, callback) {
var img = document.createElement('img');
function done(width, height) {
img.parentNode.removeChild(img);
callback({width: width, height: height});
}
img.onload = function() {
done(img.clientWidth, img.clientHeight);
};
img.onerror = function() {
done();
};
img.src = url;
var style = img.style;
style.visibility = 'hidden';
style.position = 'fixed';
style.bottom = style.left = 0;
style.width = style.height = 'auto';
document.body.appendChild(img);
}
var i = 1;
function insertImage(data) {
var editor = tinymce.activeEditor;
var dom = editor.dom;
var renderImage = function(data2) {
// 这里, 如果图片宽度过大, 这里设置成500px
var d = {};
var imgElm;
// 先显示loading...
d.id = '__mcenew' + (i++);
d.src = "http://leanote.com/images/loading-24.gif";
imgElm = dom.createHTML('img', d);
tinymce.activeEditor.insertContent(imgElm);
imgElm = dom.get(d.id);
function callback (wh) {
dom.setAttrib(imgElm, 'src', data2.src);
// dom.setAttrib(imgElm, 'width', data2.width);
if(data2.title) {
dom.setAttrib(imgElm, 'title', data2.title);
}
dom.setAttrib(imgElm, 'id', null);
};
getImageSize(data.src, callback);
}
//-------------
// outputImage?fileId=123232323
var fileId = "";
fileIds = data.src.split("fileId=")
if(fileIds.length == 2 && fileIds[1].length == "53aecf8a8a039a43c8036282".length) {
fileId = fileIds[1];
}
if(fileId) {
// 得到fileId, 如果这个笔记不是我的, 那么肯定是协作的笔记, 那么需要将图片copy给原note owner
var curNote = Note.getCurNote();
if(curNote && curNote.UserId != UserInfo.UserId) {
(function(data) {
ajaxPost("/file/copyImage", {userId: UserInfo.UserId, fileId: fileId, toUserId: curNote.UserId}, function(re) {
if(reIsOk(re) && re.Id) {
var urlPrefix = window.location.protocol + "//" + window.location.host;
data.src = urlPrefix + "/file/outputImage?fileId=" + re.Id;
}
renderImage(data);
});
})(data);
} else {
renderImage(data);
}
} else {
renderImage(data);
}
}
var initUploader = function() {
var ul = $('#upload ul');
$('#drop a').click(function() {
// trigger to show file select
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
dataType: 'json',
pasteZone: '', // 不允许paste
acceptFileTypes: /(\.|\/)(gif|jpg|jpeg|png|jpe)$/i,
maxFileSize: 210000,
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
formData: function(form) {
return [{name: 'albumId', value: ""}]
},
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function(e, data) {
var tpl = $('<li><div class="alert alert-info"><img class="loader" src="/tinymce/plugins/leaui_image/public/images/ajax-loader.gif"> <a class="close" data-dismiss="alert">×</a></div></li>');
// Append the file name and file size
tpl.find('div').append(data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// data.form[0].action += "&album_id=" + $("#albumsForUpload").val();
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
done: function(e, data) {
if (data.result.Ok == true) {
data.context.remove();
// life
var data2 = {src: urlPrefix + "/file/outputImage?fileId=" + data.result.Id}
insertImage(data2);
} else {
data.context.empty();
var tpl = $('<li><div class="alert alert-danger"><a class="close" data-dismiss="alert">×</a></div></li>');
tpl.find('div').append('<b>Error:</b> ' + data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small> ' + data.result.Msg);
data.context.append(tpl);
setTimeout((function(tpl) {
return function() {
tpl.remove();
}
})(tpl), 2000);
}
$("#uploadMsg").scrollTop(1000);
},
fail: function(e, data) {
data.context.empty();
var tpl = $('<li><div class="alert alert-danger"><a class="close" data-dismiss="alert">×</a></div></li>');
tpl.find('div').append('<b>Error:</b> ' + data.files[0].name + ' <small>[<i>' + formatFileSize(data.files[0].size) + '</i>]</small> ' + data.errorThrown);
data.context.append(tpl);
setTimeout((function(tpl) {
return function() {
tpl.remove();
}
})(tpl), 2000);
$("#uploadMsg").scrollTop(1000);
}
});
// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function(e) {
e.preventDefault();
});
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
function showUpload() {
$("#upload").css("z-index", 12);
var top = +$("#mceToolbar").css("height").slice(0, -2); // px
$("#upload").css("top", top - 8);
$("#upload").show();
}
function hideUpload() {
$("#upload").css("z-index", 0).css("top", "auto").hide();
}
// drag css
$(document).bind('dragover', function (e) {
var dropZone = $('#drop'),
timeout = window.dropZoneTimeout;
if (!timeout) {
dropZone.addClass('in');
showUpload();
} else {
clearTimeout(timeout);
}
var found = false,
node = e.target;
do {
if (node === dropZone[0]) {
found = true;
break;
}
node = node.parentNode;
} while (node != null);
if (found) {
dropZone.addClass('hover');
} else {
dropZone.removeClass('hover');
}
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null;
dropZone.removeClass('in hover');
hideUpload();
}, 100);
});
};
var lastTime = 0;
// pasteImage
var pasteImageInit = function() {
var curNote;
// Initialize the jQuery File Upload plugin
var dom, editor;
// 2015/4/17 添加wmd-input markdown paste image
$('#editorContent, #wmd-input .editor-content').fileupload({
dataType: 'json',
pasteZone: $('#editorContent, #wmd-input .editor-content'),
dropZone: '', // 只允许paste
maxFileSize: 210000,
url: "/file/pasteImage",
paramName: 'file',
formData: function(form) {
return [{name: 'from', value: 'pasteImage'}, {name: 'noteId', value: Note.curNoteId}]
},
/*
paste: function(e, data) {
var jqXHR = data.submit();
},
*/
progress: function(e, data) {
if(curNote && !curNote.IsMarkdown) {
data.process.update(data.loaded / data.total);
}
},
// 调用了两次
// 不知道为什么会触发两次
add: function(e, data) {
// 防止两次
var now = (new Date()).getTime();
console.log(now - lastTime);
if (now - lastTime < 500) {
// console.log('haha');
return;
}
// console.log('nono');
lastTime = now;
var note = Note.getCurNote();
curNote = note;
if(!note || note.IsNew) {
alert("This note hasn't saved, please save it firstly!")
return;
}
// 先显示loading...
editor = tinymce.EditorManager.activeEditor;
if(!note.IsMarkdown) {
var process = new Process(editor);
}
data.process = process;
var jqXHR = data.submit();
/*
d.id = '__mcenew' + (new Date()).getTime();
d.src = "http://leanote.com/images/loading-24.gif"; // 写死了
var img = '<img src="' + d.src + '" id="' + d.id + '" />';
editor.insertContent(img);
var imgElm = $(d.id);
data.imgId = d.id;
data.context = imgElm;
*/
/*
// 上传之
var c = new FormData;
c.append("from", "pasteImage");
// var d;
// d = $.ajaxSettings.xhr();
// d.withCredentials = i;var d = {};
// 先显示loading...
var editor = tinymce.EditorManager.activeEditor;
var dom = editor.dom;
var d = {};
d.id = '__mcenew';
d.src = "http://leanote.com/images/loading-24.gif"; // 写死了
editor.insertContent(dom.createHTML('img', d));
var imgElm = dom.get('__mcenew');
$.ajax({url: "/file/pasteImage", contentType:false, processData:false , data: c, type: "POST"}
).done(function(re) {
if(!re || typeof re != "object" || !re.Ok) {
// 删除
dom.remove(imgElm);
return;
}
// 这里, 如果图片宽度过大, 这里设置成500px
var urlPrefix = UrlPrefix; // window.location.protocol + "//" + window.location.host;
var src = urlPrefix + "/file/outputImage?fileId=" + re.Id;
getImageSize(src, function(wh) {
// life 4/25
if(wh && wh.width) {
if(wh.width > 600) {
wh.width = 600;
}
d.width = wh.width;
dom.setAttrib(imgElm, 'width', d.width);
}
dom.setAttrib(imgElm, 'src', src);
});
dom.setAttrib(imgElm, 'id', null);
});
};
reader.readAsDataURL(blob);
*/
},
done: function(e, data) {
if (data.result.Ok == true) {
// 这里, 如果图片宽度过大, 这里设置成500px
var re = data.result;
var urlPrefix = UrlPrefix; // window.location.protocol + "//" + window.location.host;
var src = urlPrefix + "/file/outputImage?fileId=" + re.Id;
if(curNote && !curNote.IsMarkdown) {
data.process.replace(src);
} else {
MD && MD.insertLink(src, 'title', true);
}
/*
getImageSize(src, function() {
$img.attr('src', src);
$img.removeAttr('id');
});
*/
} else {
data.process.remove();
}
},
fail: function(e, data) {
if(curNote && !curNote.IsMarkdown) {
data.process.remove();
}
}
});
};
initUploader();
pasteImageInit();
});

View File

@ -0,0 +1,161 @@
/**
* @file 历史记录
* @author life
*
*/
define('history', [], function() {
var tpl = ['<div class="modal fade history-modal" tabindex="-1" role="dialog" aria-hidden="true">',
'<div class="modal-dialog modal-lg ">',
'<div class="modal-content">',
'<div class="modal-header">',
'<h4 class="modal-title" class="modalTitle">' + + '</h4>',
'</div>',
'<div class="modal-body clearfix">',
'<div class="history-list-wrap pull-left">',
'<div class="history-list-header">' + getMsg('history') +' (<span class="history-num"></span>)</div>',
'<div class="history-list list-group"></div>',
'</div>',
'<div class="history-content-wrap pull-left">',
'<div class="history-content-header">',
'<a class="btn btn-primary back">' + getMsg('restoreFromThisVersion') + '</a>',
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>',
'</div>',
'<div class="history-content"></div>',
'</div>',
'</div>',
'<div class="modal-footer hide">',
'<button type="button" class="btn btn-default" data-dismiss="modal">' + getMsg('close') + '</button>',
'</div>',
'</div>',
'</div>',
'</div>'].join('');
var $tpl = $(tpl);
var $historyContent = $tpl.find('.history-content');
var $historyList = $tpl.find('.history-list');
var $historyNum = $tpl.find('.history-num');
var view = {
note: null,
list: [],
curIndex: 0,
renderContent: function (i) {
var content = this.list[i].Content;
this.curIndex = i;
var wrap = '<div>';
var wrapEnd = '</div>';
if (this.note.IsMarkdown) {
wrap = '<pre>';
wrapEnd = '</pre>';
}
$historyContent.html(wrap + content + wrapEnd);
var as = $historyList.find('a');
as.removeClass('active');
as.eq(i).addClass('active');
},
render: function (list) {
var navs = '';
this.list = list;
if (list) {
for(var i = 0; i < list.length; ++i) {
var content = list[i];
navs += '<a class="list-group-item" data-index="' + i + '"><span class="badge">#' + (i+1)+ '</span>' + goNowToDatetime(content.UpdatedTime) + '</a>';
}
}
$historyList.html(navs);
this.renderContent(0);
$historyNum.html(list.length);
// show
$tpl.modal({show: true});
},
bind: function () {
var me = this;
$("#contentHistory").click(function() {
me.getHistories();
});
$historyList.on('click', 'a', function () {
var index = $(this).data('index');
me.renderContent(index);
});
// 还原
$tpl.find('.back').click(function() {
if(confirm(getMsg("confirmBackup"))) {
// 保存当前版本
Note.curChangedSaveIt(true);
// 设置之
note = Note.cache[Note.curNoteId];
setEditorContent(me.list[me.curIndex].Content, note.IsMarkdown);
$tpl.modal('hide');
// 保存
Note.curChangedSaveIt(true);
}
});
},
getHistories: function () {
var me = this;
var note = Note.getCurNote();
me.note = note;
ajaxGet("/noteContentHistory/listHistories", {noteId: Note.curNoteId}, function(re) {
if(!isArray(re)) {
alert(getMsg('noHistories'));
return;
}
me.render(re);
return;
// 组装成一个tab
var str = "<p>" + getMsg("historiesNum") + '</p><div id="historyList"><table class="table table-hover">';
note = Note.cache[Note.curNoteId];
var s = "div"
if(note.IsMarkdown) {
s = "pre";
}
for (i in re) {
var content = re[i]
content.Ab = Note.genAbstract(content.Content, 200);
// 为什么不用tt(), 因为content可能含??
str += '<tr><td seq="' + i + '">#' + (i+1) +'<' + s + ' class="each-content">' + content.Ab + '</' + s + '> <div class="btns">' + getMsg("datetime") + ': <span class="label label-default">' + goNowToDatetime(content.UpdatedTime) + '</span> <button class="btn btn-default all">' + getMsg("unfold") + '</button> <button class="btn btn-primary back">' + getMsg('restoreFromThisVersion') + '</button></div></td></tr>';
}
str += "</table></div>";
$content.html(str);
$("#historyList .all").click(function() {
$p = $(this).parent().parent();
var seq = $p.attr("seq");
var $c = $p.find(".each-content");
var info = re[seq];
if(!info.unfold) { // 默认是折叠的
$(this).text(getMsg("fold")); // 折叠
$c.html(info.Content);
info.unfold = true;
} else {
$(this).text(getMsg("unfold")); // 展开
$c.html(info.Ab);
info.unfold = false
}
});
});
},
init: function () {
var me = this;
this.bind();
}
};
view.init();
});

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
!function(t){"use strict";t(window.jQuery)}(function(t){"use strict";var e=0;t.ajaxTransport("iframe",function(r){if(r.async){var a,n,p;return{send:function(o,i){a=t('<form style="display:none;"></form>'),a.attr("accept-charset",r.formAcceptCharset),p=/\?/.test(r.url)?"&":"?","DELETE"===r.type?(r.url=r.url+p+"_method=DELETE",r.type="POST"):"PUT"===r.type?(r.url=r.url+p+"_method=PUT",r.type="POST"):"PATCH"===r.type&&(r.url=r.url+p+"_method=PATCH",r.type="POST"),n=t('<iframe src="javascript:false;" name="iframe-transport-'+(e+=1)+'"></iframe>').bind("load",function(){var e,p=t.isArray(r.paramName)?r.paramName:[r.paramName];n.unbind("load").bind("load",function(){var e;try{if(e=n.contents(),!e.length||!e[0].firstChild)throw new Error}catch(r){e=void 0}i(200,"success",{iframe:e}),t('<iframe src="javascript:false;"></iframe>').appendTo(a),a.remove()}),a.prop("target",n.prop("name")).prop("action",r.url).prop("method",r.type),r.formData&&t.each(r.formData,function(e,r){t('<input type="hidden"/>').prop("name",r.name).val(r.value).appendTo(a)}),r.fileInput&&r.fileInput.length&&"POST"===r.type&&(e=r.fileInput.clone(),r.fileInput.after(function(t){return e[t]}),r.paramName&&r.fileInput.each(function(e){t(this).prop("name",p[e]||r.paramName)}),a.append(r.fileInput).prop("enctype","multipart/form-data").prop("encoding","multipart/form-data")),a.submit(),e&&e.length&&r.fileInput.each(function(r,a){var n=t(e[r]);t(a).prop("name",n.prop("name")),n.replaceWith(a)})}),a.append(n).appendTo(document.body)},abort:function(){n&&n.unbind("load").prop("src","javascript".concat(":false;")),a&&a.remove()}}}}),t.ajaxSetup({converters:{"iframe text":function(e){return e&&t(e[0].body).text()},"iframe json":function(e){return e&&t.parseJSON(t(e[0].body).text())},"iframe html":function(e){return e&&t(e[0].body).html()},"iframe script":function(e){return e&&t.globalEval(t(e[0].body).text())}}})});

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,188 @@
/*
* jQuery Iframe Transport Plugin 1.6.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
/*
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
*/
factory(window.jQuery);
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async) {
var form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
(counter += 1) + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
form.remove();
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, and script:
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));

View File

@ -0,0 +1,534 @@
/*
* jQuery UI Widget 1.10.1+amd
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function (factory) {
/* 需要jquery, 会重新加载jquery, slimScroll会覆盖
if (typeof define === "function" && define.amd) {
// Register as an anonymous AMD module:
define(["jquery"], factory);
} else {
// Browser globals:
factory(jQuery);
}
*/
factory(jQuery);
}(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
}));

38
public/js/plugins/main.js Normal file
View File

@ -0,0 +1,38 @@
// 插件, 不是立刻就需要的功能
// 1. 上传, 粘贴图片2
// 2. 笔记信息
// 3. 历史记录
// 4. 附件
requirejs.config({
paths: {
// life
'editor_drop_paste': 'js/plugins/editor_drop_paste',
'attachment_upload': 'js/plugins/attachment_upload',
'jquery.ui.widget': 'js/plugins/libs-min/jquery.ui.widget',
'fileupload': 'js/plugins/libs-min/jquery.fileupload',
'iframe-transport': 'js/plugins/libs-min/jquery.iframe-transport',
'note_info': 'js/plugins/note_info',
'tips': 'js/plugins/tips',
'history': 'js/plugins/history',
},
shim: {
// life
'fileupload': {deps: ['jquery.ui.widget', 'iframe-transport']},
}
});
// 异步加载
setTimeout(function () {
// 小异步
require(["editor_drop_paste", "attachment_upload"]);
require(['note_info']);
// 大异步
setTimeout(function () {
require(['tips']);
require(['history']);
}, 10);
});

6
public/js/plugins/main.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,123 @@
/**
* @file 笔记信息
* @author life
*
*/
define('note_info', [], function() {
var tpl = ['<table>',
'<tr><th>' + getMsg('Create Time') + '</th><td id="noteInfoCreatedTime"></td></tr>',
'<tr><th>' + getMsg('Update Time') + '</th><td id="noteInfoUpdatedTime"></td></tr>',
'<tr class="post-url-tr">',
'<th>' + getMsg('Post Url') + '</th>',
'<td>',
'<div class="post-url-wrap">',
'<span class="post-url-base">http://blog.leanote.com/life/post/</span><span><span class="post-url-text">life-life-life-a-leanote</span>',
'<input type="text" class="form-control">',
'</span>',
' <a class="post-url-pencil" title="' + getMsg('update') + '"><i class="fa fa-pencil"></i></a>',
'</div>',
'</td>',
'</tr>',
'</table>'].join('');
var $tpl = $(tpl);
var $noteInfoCreatedTime = $tpl.find('#noteInfoCreatedTime');
var $noteInfoUpdatedTime = $tpl.find('#noteInfoUpdatedTime');
var $noteInfoPostUrl = $tpl.find('#noteInfoPostUrl');
var $noteInfoPostUrlTr = $tpl.find('.post-url-tr');
var $postUrlWrap = $tpl.find('.post-url-wrap');
var $input = $tpl.find('input');
var $postUrlBase = $tpl.find('.post-url-base');
var $postUrlText = $tpl.find('.post-url-text');
var view = {
$noteInfo: $('#noteInfo'),
note: null,
bind: function () {
var me = this;
$('#noteInfoDropdown').click(function () {
me.render();
});
$tpl.find('.post-url-pencil').click(function () {
$postUrlWrap.addClass('post-url-edit');
$input.val(decodeURI(me.note.UrlTitle));
$input.focus();
});
$input.keydown(function (e) {
if(e.keyCode === 13) {
$input.blur();
}
});
$input.blur(function () {
$postUrlWrap.removeClass('post-url-edit');
var val = $input.val();
if (!val) {
return;
}
ajaxPost("/member/blog/updateBlogUrlTitle", {noteId: me.note.NoteId, urlTitle: val}, function(re) {
if(reIsOk(re)) {
var encodedUrl = encodeURI(re.Item);
me.note.UrlTitle = encodedUrl;
$postUrlText.text(decodeURI(me.note.UrlTitle));
} else {
alert(re.Msg || "error");
}
});
});
// 当笔记Change时, 重新render
LEA.on('noteChanged', function (note) {
me.render(note);
});
},
getPostUrl: function (note) {
return '';
},
rendered: false,
render: function (note) {
var me = this;
if (!note) {
note = Note.getCurNote();
}
if (!note) {
return;
}
me.note = note;
$noteInfoCreatedTime.html(goNowToDatetime(note.CreatedTime));
$noteInfoUpdatedTime.html(goNowToDatetime(note.UpdatedTime));
if (!note.IsBlog) {
$noteInfoPostUrlTr.addClass('hide');
}
else {
$noteInfoPostUrlTr.removeClass('hide');
// post-url
$postUrlBase.text(UserInfo.PostUrl + '/');
$postUrlText.text(decodeURI(note.UrlTitle));
}
if (!me.rendered) {
me.$noteInfo.html($tpl);
me.rendered = true;
}
},
init: function () {
this.bind();
}
};
view.init();
});

32
public/js/plugins/tips.js Normal file
View File

@ -0,0 +1,32 @@
/**
* @file 提示帮助
* @author life
*
*/
define('tips', [], function() {
var tpl = ['<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">',
'<div class="modal-dialog modal-sm">',
'<div class="modal-content">',
'<div class="modal-header">',
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>',
'<h4 class="modal-title" class="modalTitle">' + getMsg('editorTips') + '</h4>',
'</div>',
'<div class="modal-body">' + getMsg('editorTipsInfo') + '</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-default" data-dismiss="modal">' + getMsg('close') + '</button>',
'</div>',
'</div>',
'</div>',
'</div>'].join('');
var $tpl = $(tpl);
var view = {
init: function () {
$("#tipsBtn").click(function() {
$tpl.modal({show: true});
});
}
};
view.init();
});