This commit is contained in:
life
2014-05-07 13:06:24 +08:00
parent fac05a7b6c
commit 476ade10e7
1085 changed files with 259628 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,458 @@
/*!
* ZeroClipboard
* The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
* Copyright (c) 2013 Jon Rohan, James M. Greene
* Licensed MIT
* http://zeroclipboard.org/
* v1.2.0-beta.4
*/
(function() {
"use strict";
var _camelizeCssPropName = function() {
var matcherRegex = /\-([a-z])/g, replacerFn = function(match, group) {
return group.toUpperCase();
};
return function(prop) {
return prop.replace(matcherRegex, replacerFn);
};
}();
var _getStyle = function(el, prop) {
var value, camelProp, tagName, possiblePointers, i, len;
if (window.getComputedStyle) {
value = window.getComputedStyle(el, null).getPropertyValue(prop);
} else {
camelProp = _camelizeCssPropName(prop);
if (el.currentStyle) {
value = el.currentStyle[camelProp];
} else {
value = el.style[camelProp];
}
}
if (prop === "cursor") {
if (!value || value === "auto") {
tagName = el.tagName.toLowerCase();
possiblePointers = [ "a" ];
for (i = 0, len = possiblePointers.length; i < len; i++) {
if (tagName === possiblePointers[i]) {
return "pointer";
}
}
}
}
return value;
};
var _elementMouseOver = function(event) {
if (!ZeroClipboard.prototype._singleton) return;
if (!event) {
event = window.event;
}
var target;
if (this !== window) {
target = this;
} else if (event.target) {
target = event.target;
} else if (event.srcElement) {
target = event.srcElement;
}
ZeroClipboard.prototype._singleton.setCurrent(target);
};
var _addEventHandler = function(element, method, func) {
if (element.addEventListener) {
element.addEventListener(method, func, false);
} else if (element.attachEvent) {
element.attachEvent("on" + method, func);
}
};
var _removeEventHandler = function(element, method, func) {
if (element.removeEventListener) {
element.removeEventListener(method, func, false);
} else if (element.detachEvent) {
element.detachEvent("on" + method, func);
}
};
var _addClass = function(element, value) {
if (element.addClass) {
element.addClass(value);
return element;
}
if (value && typeof value === "string") {
var classNames = (value || "").split(/\s+/);
if (element.nodeType === 1) {
if (!element.className) {
element.className = value;
} else {
var className = " " + element.className + " ", setClass = element.className;
for (var c = 0, cl = classNames.length; c < cl; c++) {
if (className.indexOf(" " + classNames[c] + " ") < 0) {
setClass += " " + classNames[c];
}
}
element.className = setClass.replace(/^\s+|\s+$/g, "");
}
}
}
return element;
};
var _removeClass = function(element, value) {
if (element.removeClass) {
element.removeClass(value);
return element;
}
if (value && typeof value === "string" || value === undefined) {
var classNames = (value || "").split(/\s+/);
if (element.nodeType === 1 && element.className) {
if (value) {
var className = (" " + element.className + " ").replace(/[\n\t]/g, " ");
for (var c = 0, cl = classNames.length; c < cl; c++) {
className = className.replace(" " + classNames[c] + " ", " ");
}
element.className = className.replace(/^\s+|\s+$/g, "");
} else {
element.className = "";
}
}
}
return element;
};
var _getZoomFactor = function() {
var rect, physicalWidth, logicalWidth, zoomFactor = 1;
if (typeof document.body.getBoundingClientRect === "function") {
rect = document.body.getBoundingClientRect();
physicalWidth = rect.right - rect.left;
logicalWidth = document.body.offsetWidth;
zoomFactor = Math.round(physicalWidth / logicalWidth * 100) / 100;
}
return zoomFactor;
};
var _getDOMObjectPosition = function(obj) {
var info = {
left: 0,
top: 0,
width: 0,
height: 0,
zIndex: 999999999
};
var zi = _getStyle(obj, "z-index");
if (zi && zi !== "auto") {
info.zIndex = parseInt(zi, 10);
}
if (obj.getBoundingClientRect) {
var rect = obj.getBoundingClientRect();
var pageXOffset, pageYOffset, zoomFactor;
if ("pageXOffset" in window && "pageYOffset" in window) {
pageXOffset = window.pageXOffset;
pageYOffset = window.pageYOffset;
} else {
zoomFactor = _getZoomFactor();
pageXOffset = Math.round(document.documentElement.scrollLeft / zoomFactor);
pageYOffset = Math.round(document.documentElement.scrollTop / zoomFactor);
}
var leftBorderWidth = document.documentElement.clientLeft || 0;
var topBorderWidth = document.documentElement.clientTop || 0;
info.left = rect.left + pageXOffset - leftBorderWidth;
info.top = rect.top + pageYOffset - topBorderWidth;
info.width = "width" in rect ? rect.width : rect.right - rect.left;
info.height = "height" in rect ? rect.height : rect.bottom - rect.top;
}
return info;
};
var _noCache = function(path, options) {
var useNoCache = !(options && options.useNoCache === false);
if (useNoCache) {
return (path.indexOf("?") === -1 ? "?" : "&") + "nocache=" + new Date().getTime();
} else {
return "";
}
};
var _vars = function(options) {
var str = [];
var origins = [];
if (options.trustedOrigins) {
if (typeof options.trustedOrigins === "string") {
origins = origins.push(options.trustedOrigins);
} else if (typeof options.trustedOrigins === "object" && "length" in options.trustedOrigins) {
origins = origins.concat(options.trustedOrigins);
}
}
if (options.trustedDomains) {
if (typeof options.trustedDomains === "string") {
origins = origins.push(options.trustedDomains);
} else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
origins = origins.concat(options.trustedDomains);
}
}
if (origins.length) {
str.push("trustedOrigins=" + encodeURIComponent(origins.join(",")));
}
if (typeof options.amdModuleId === "string" && options.amdModuleId) {
str.push("amdModuleId=" + encodeURIComponent(options.amdModuleId));
}
if (typeof options.cjsModuleId === "string" && options.cjsModuleId) {
str.push("cjsModuleId=" + encodeURIComponent(options.cjsModuleId));
}
return str.join("&");
};
var _inArray = function(elem, array) {
if (array.indexOf) {
return array.indexOf(elem);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === elem) {
return i;
}
}
return -1;
};
var _prepGlue = function(elements) {
if (typeof elements === "string") throw new TypeError("ZeroClipboard doesn't accept query strings.");
if (!elements.length) return [ elements ];
return elements;
};
var _dispatchCallback = function(func, element, instance, args, async) {
if (async) {
window.setTimeout(function() {
func.call(element, instance, args);
}, 0);
} else {
func.call(element, instance, args);
}
};
var ZeroClipboard = function(elements, options) {
if (elements) (ZeroClipboard.prototype._singleton || this).glue(elements);
if (ZeroClipboard.prototype._singleton) return ZeroClipboard.prototype._singleton;
ZeroClipboard.prototype._singleton = this;
this.options = {};
for (var kd in _defaults) this.options[kd] = _defaults[kd];
for (var ko in options) this.options[ko] = options[ko];
this.handlers = {};
if (ZeroClipboard.detectFlashSupport()) _bridge();
};
var currentElement, gluedElements = [];
ZeroClipboard.prototype.setCurrent = function(element) {
currentElement = element;
this.reposition();
var titleAttr = element.getAttribute("title");
if (titleAttr) {
this.setTitle(titleAttr);
}
var useHandCursor = this.options.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
_setHandCursor.call(this, useHandCursor);
};
ZeroClipboard.prototype.setText = function(newText) {
if (newText && newText !== "") {
this.options.text = newText;
if (this.ready()) this.flashBridge.setText(newText);
}
};
ZeroClipboard.prototype.setTitle = function(newTitle) {
if (newTitle && newTitle !== "") this.htmlBridge.setAttribute("title", newTitle);
};
ZeroClipboard.prototype.setSize = function(width, height) {
if (this.ready()) this.flashBridge.setSize(width, height);
};
ZeroClipboard.prototype.setHandCursor = function(enabled) {
enabled = typeof enabled === "boolean" ? enabled : !!enabled;
_setHandCursor.call(this, enabled);
this.options.forceHandCursor = enabled;
};
var _setHandCursor = function(enabled) {
if (this.ready()) this.flashBridge.setHandCursor(enabled);
};
ZeroClipboard.version = "1.2.0-beta.4";
var _defaults = {
moviePath: "ZeroClipboard.swf",
trustedOrigins: null,
text: null,
hoverClass: "zeroclipboard-is-hover",
activeClass: "zeroclipboard-is-active",
allowScriptAccess: "sameDomain",
useNoCache: true,
forceHandCursor: false
};
ZeroClipboard.setDefaults = function(options) {
for (var ko in options) _defaults[ko] = options[ko];
};
ZeroClipboard.destroy = function() {
ZeroClipboard.prototype._singleton.unglue(gluedElements);
var bridge = ZeroClipboard.prototype._singleton.htmlBridge;
bridge.parentNode.removeChild(bridge);
delete ZeroClipboard.prototype._singleton;
};
ZeroClipboard.detectFlashSupport = function() {
var hasFlash = false;
if (typeof ActiveXObject === "function") {
try {
if (new ActiveXObject("ShockwaveFlash.ShockwaveFlash")) {
hasFlash = true;
}
} catch (error) {}
}
if (!hasFlash && navigator.mimeTypes["application/x-shockwave-flash"]) {
hasFlash = true;
}
return hasFlash;
};
var _amdModuleId = null;
var _cjsModuleId = null;
var _bridge = function() {
var client = ZeroClipboard.prototype._singleton;
var container = document.getElementById("global-zeroclipboard-html-bridge");
if (!container) {
var opts = {};
for (var ko in client.options) opts[ko] = client.options[ko];
opts.amdModuleId = _amdModuleId;
opts.cjsModuleId = _cjsModuleId;
var flashvars = _vars(opts);
var html = ' <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="global-zeroclipboard-flash-bridge" width="100%" height="100%"> <param name="movie" value="' + client.options.moviePath + _noCache(client.options.moviePath, client.options) + '"/> <param name="allowScriptAccess" value="' + client.options.allowScriptAccess + '"/> <param name="scale" value="exactfit"/> <param name="loop" value="false"/> <param name="menu" value="false"/> <param name="quality" value="best" /> <param name="bgcolor" value="#ffffff"/> <param name="wmode" value="transparent"/> <param name="flashvars" value="' + flashvars + '"/> <embed src="' + client.options.moviePath + _noCache(client.options.moviePath, client.options) + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="100%" height="100%" name="global-zeroclipboard-flash-bridge" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" scale="exactfit"> </embed> </object>';
container = document.createElement("div");
container.id = "global-zeroclipboard-html-bridge";
container.setAttribute("class", "global-zeroclipboard-container");
container.setAttribute("data-clipboard-ready", false);
container.style.position = "absolute";
container.style.left = "-9999px";
container.style.top = "-9999px";
container.style.width = "15px";
container.style.height = "15px";
container.style.zIndex = "9999";
container.innerHTML = html;
document.body.appendChild(container);
}
client.htmlBridge = container;
client.flashBridge = document["global-zeroclipboard-flash-bridge"] || container.children[0].lastElementChild;
};
ZeroClipboard.prototype.resetBridge = function() {
this.htmlBridge.style.left = "-9999px";
this.htmlBridge.style.top = "-9999px";
this.htmlBridge.removeAttribute("title");
this.htmlBridge.removeAttribute("data-clipboard-text");
_removeClass(currentElement, this.options.activeClass);
currentElement = null;
this.options.text = null;
};
ZeroClipboard.prototype.ready = function() {
var ready = this.htmlBridge.getAttribute("data-clipboard-ready");
return ready === "true" || ready === true;
};
ZeroClipboard.prototype.reposition = function() {
if (!currentElement) return false;
var pos = _getDOMObjectPosition(currentElement);
this.htmlBridge.style.top = pos.top + "px";
this.htmlBridge.style.left = pos.left + "px";
this.htmlBridge.style.width = pos.width + "px";
this.htmlBridge.style.height = pos.height + "px";
this.htmlBridge.style.zIndex = pos.zIndex + 1;
this.setSize(pos.width, pos.height);
};
ZeroClipboard.dispatch = function(eventName, args) {
ZeroClipboard.prototype._singleton.receiveEvent(eventName, args);
};
ZeroClipboard.prototype.on = function(eventName, func) {
var events = eventName.toString().split(/\s/g);
for (var i = 0; i < events.length; i++) {
eventName = events[i].toLowerCase().replace(/^on/, "");
if (!this.handlers[eventName]) this.handlers[eventName] = func;
}
if (this.handlers.noflash && !ZeroClipboard.detectFlashSupport()) {
this.receiveEvent("onNoFlash", null);
}
};
ZeroClipboard.prototype.addEventListener = ZeroClipboard.prototype.on;
ZeroClipboard.prototype.off = function(eventName, func) {
var events = eventName.toString().split(/\s/g);
for (var i = 0; i < events.length; i++) {
eventName = events[i].toLowerCase().replace(/^on/, "");
for (var event in this.handlers) {
if (event === eventName && this.handlers[event] === func) {
delete this.handlers[event];
}
}
}
};
ZeroClipboard.prototype.removeEventListener = ZeroClipboard.prototype.off;
ZeroClipboard.prototype.receiveEvent = function(eventName, args) {
eventName = eventName.toString().toLowerCase().replace(/^on/, "");
var element = currentElement;
var performCallbackAsync = true;
switch (eventName) {
case "load":
if (args && parseFloat(args.flashVersion.replace(",", ".").replace(/[^0-9\.]/gi, "")) < 10) {
this.receiveEvent("onWrongFlash", {
flashVersion: args.flashVersion
});
return;
}
this.htmlBridge.setAttribute("data-clipboard-ready", true);
break;
case "mouseover":
_addClass(element, this.options.hoverClass);
break;
case "mouseout":
_removeClass(element, this.options.hoverClass);
this.resetBridge();
break;
case "mousedown":
_addClass(element, this.options.activeClass);
break;
case "mouseup":
_removeClass(element, this.options.activeClass);
break;
case "datarequested":
var targetId = element.getAttribute("data-clipboard-target"), targetEl = !targetId ? null : document.getElementById(targetId);
if (targetEl) {
var textContent = targetEl.value || targetEl.textContent || targetEl.innerText;
if (textContent) this.setText(textContent);
} else {
var defaultText = element.getAttribute("data-clipboard-text");
if (defaultText) this.setText(defaultText);
}
performCallbackAsync = false;
break;
case "complete":
this.options.text = null;
break;
}
if (this.handlers[eventName]) {
var func = this.handlers[eventName];
if (typeof func === "string" && typeof window[func] === "function") {
func = window[func];
}
if (typeof func === "function") {
_dispatchCallback(func, element, this, args, performCallbackAsync);
}
}
};
ZeroClipboard.prototype.glue = function(elements) {
elements = _prepGlue(elements);
for (var i = 0; i < elements.length; i++) {
if (_inArray(elements[i], gluedElements) == -1) {
gluedElements.push(elements[i]);
_addEventHandler(elements[i], "mouseover", _elementMouseOver);
}
}
};
ZeroClipboard.prototype.unglue = function(elements) {
elements = _prepGlue(elements);
for (var i = 0; i < elements.length; i++) {
_removeEventHandler(elements[i], "mouseover", _elementMouseOver);
var arrayIndex = _inArray(elements[i], gluedElements);
if (arrayIndex != -1) gluedElements.splice(arrayIndex, 1);
}
};
if (typeof define === "function" && define.amd) {
define([ "require", "exports", "module" ], function(require, exports, module) {
_amdModuleId = module && module.id || null;
return ZeroClipboard;
});
} else if (typeof module !== "undefined" && module) {
_cjsModuleId = module.id || null;
module.exports = ZeroClipboard;
} else {
window.ZeroClipboard = ZeroClipboard;
}
})();

File diff suppressed because one or more lines are too long

Binary file not shown.

2
public/js/all.js Normal file

File diff suppressed because one or more lines are too long

85
public/js/app/blog/nav.js Normal file
View File

@ -0,0 +1,85 @@
function scrollTo(self, tagName, text) {
var iframe = $("#content");
var target = iframe.find(tagName + ":contains(" + text + ")");
// 找到是第几个
// 在nav是第几个
var navs = $('#blogNavContent [data-a="' + tagName + '-' + encodeURI(text) + '"]');
var len = navs.size();
for(var i = 0; i < len; ++i) {
if(navs[i] == self) {
break;
}
}
if (target.size() >= i+1) {
target = target.eq(i);
// 之前插入, 防止多行定位不准
var top = target.offset().top;
var nowTop = $(document).scrollTop();
// 用$("body").scrllTop(10)没反应 firefox下
$('html,body').animate({scrollTop: top}, 200);
return;
}
}
function genNav() {
var $con = $("#content");
var html = $con.html();
// 构造一棵树
// {"h1-title":{h2-title:{}}}
var tree = [];//[{title: "xx", children:[{}]}, {title:"xx2"}];
var hs = $con.find("h1,h2,h3,h4,h5,h6").toArray();
var titles = '<ul>';
for(var i = 0; i < hs.length; ++i) {
var text = $(hs[i]).text();
var tagName = hs[i].tagName.toLowerCase();
// scrollTo在page.js中定义
titles += '<li class="nav-' + tagName + '"><a data-a="' + tagName + '-' + encodeURI(text)+'" onclick="scrollTo(this, \'' + tagName + '\', \'' + text + '\')">' + text + '</a></li>';
}
titles += "</ul>";
$("#blogNavContent").html(titles);
if(!hs.length) {
$("#blogNavContent").html("&nbsp; 无");
return false;
}
return true;
}
function initNav() {
var hasNav = genNav();
if(!hasNav) {
return;
}
var $title = $(".title");
var titlePos = $title.offset();
var top = titlePos.top + 10;// - $title.height();
if(top < 0) {
top = 10;
}
var left = $title.width() + titlePos.left - 100;
$("#blogNav").css("top", top).css("left", left);
$("#blogNav").show();
$("#blogNavNav").click(function() {
var $o = $("#blogNavContent");
if($o.is(":hidden")) {
$o.show();
} else {
$o.hide();
}
});
var $d = $(document);
function reNav() {
var vtop = $d.scrollTop();
if(vtop <= top) {
$("#blogNav").css("top", top-vtop);
} else {
// 差距很磊了
$("#blogNav").css("top", 10);
}
}
reNav();
$(window).scroll(reNav);
}

1
public/js/app/note-min.js vendored Normal file

File diff suppressed because one or more lines are too long

1334
public/js/app/note.js Normal file

File diff suppressed because it is too large Load Diff

1
public/js/app/notebook-min.js vendored Normal file

File diff suppressed because one or more lines are too long

594
public/js/app/notebook.js Normal file
View File

@ -0,0 +1,594 @@
Notebook.curNotebookId = "";
Notebook.cache = {}; // notebookId => {};
Notebook.notebooks = []; // 按次序
// <li role="presentation"><a role="menuitem" tabindex="-1" href="#">CSS</a></li>
Notebook.notebookNavForListNote = ""; // html 为了note list上面和新建时的ul
Notebook.notebookNavForNewNote = ""; // html 为了note list上面和新建时的ul
// 设置缓存
Notebook.setCache = function(notebook) {
var notebookId = notebook.NotebookId;
if(!notebookId) {
return;
}
if(!Notebook.cache[notebookId]) {
Notebook.cache[notebookId] = {};
}
$.extend(Notebook.cache[notebookId], notebook);
}
Notebook.getCurNotebookId = function() {
return Notebook.curNotebookId;
};
// 得到notebook标题, 给note显示其notebook标题用
// called by Note
Notebook.getNotebook = function(notebookId) {
return Notebook.cache[notebookId];
}
// called by Note
Notebook.getNotebookTitle = function(notebookId) {
var notebook = Notebook.cache[notebookId];
if(notebook) {
return notebook.Title;
} else {
return "未知";
}
}
/**
* 我的notebooks
<ul class="folderBody" id="notebookList">
<li><a class="active">所有</a></li>
<li><a class="active">Hadoop</a></li>
<li><a>August 13, 2013</a></li>
</ul>
*/
// TODO 层级
Notebook.allNotebookId = "0";
Notebook.trashNotebookId = "-1";
Notebook.curNotebookIsTrashOrAll = function() {
return Notebook.curNotebookId == Notebook.trashNotebookId || Notebook.curNotebookId == Notebook.allNotebookId ;
}
Notebook.renderNotebooks = function(notebooks) {
if(!notebooks || typeof notebooks != "object" || notebooks.length < 0) {
notebooks = [];
}
notebooks = [{NotebookId: Notebook.allNotebookId, Title: getMsg("all")}].concat(notebooks);
notebooks.push({NotebookId: Notebook.trashNotebookId, Title: getMsg("trash")});
Notebook.notebooks = notebooks; // 缓存之
var $notebookList = $("#notebookList");
var nav = "";
for(var i in notebooks) {
var notebook = notebooks[i];
Notebook.cache[notebook.NotebookId] = notebook;
var classes = "";
if(i == 0) {
classes = "active";
Notebook.curNotebookId = notebook.NotebookId;
}
$notebookList.append(t('<li><a class="?" notebookId="?">?</a></li>', classes, notebook.NotebookId, notebook.Title))
}
// 渲染nav
Notebook.renderNav();
// 渲染第一个notebook作为当前
Notebook.changeNotebookNavForNewNote(notebooks[0].NotebookId);
}
// RenderNotebooks调用,
// nav 为了新建, 快速选择, 移动笔记
// 这些在添加,修改,删除notebooks都要变动!!!
Notebook.renderNav = function(nav) {
var navForListNote = "";
var navForNewNote = "";
var navForMoveNote = "";
var len = Notebook.notebooks.length-1;
var contextmenu = [];
for(var i in Notebook.notebooks) {
var notebook = Notebook.notebooks[i];
var each = t('<li role="presentation"><a role="menuitem" tabindex="-1" href="#" notebookId="?">?</a></li>', notebook.NotebookId, notebook.Title);
var eachForNew = t('<li role="presentation" class="clearfix"><div class="new-note-left pull-left" title="为该笔记本新建笔记" href="#" notebookId="?">?</div><div title="为该笔记本新建markdown笔记" class="new-note-right pull-left" notebookId="?">Markdown</div></li>', notebook.NotebookId, notebook.Title, notebook.NotebookId);
navForListNote += each;
if(i != 0 && i != len) {
navForMoveNote += each;
navForNewNote += eachForNew;
}
}
$("#notebookNavForListNote").html(navForListNote);
$("#notebookNavForNewNote").html(navForNewNote);
$("#notebookNavForMoveNote").html(navForMoveNote);
}
// 修改,添加,删除notebook后调用
// 改变nav
// 直接从html中取!
Notebook.changeNav = function() {
var navForListNote = "";
var navForNewNote = "";
var i = 0;
var $list = $("#notebookList li a");
var len = $list.length - 1;
$list.each(function() {
var notebookId = $(this).attr("notebookId");
var notebook = Notebook.cache[notebookId];
var each = t('<li role="presentation"><a role="menuitem" tabindex="-1" href="#" notebookId="?">?</a></li>', notebook.NotebookId, notebook.Title);
var eachForNew = t('<li role="presentation" class="clearfix"><div class="new-note-left pull-left" title="为该笔记本新建笔记" href="#" notebookId="?">?</div><div title="为该笔记本新建markdown笔记" class="new-note-right pull-left" notebookId="?">Markdown</div></li>', notebook.NotebookId, notebook.Title, notebook.NotebookId);
navForListNote += each;
var isActive = $(this).hasClass('active'); // 万一修改的是已选择的, 那么...
if(isActive) {
$("#curNotebookForListNote").html(notebook.Title);
}
if(i != 0 && i != len) {
navForNewNote += eachForNew;
if(isActive) {
$("#curNotebookForNewNote").html(notebook.Title);
}
}
i++;
});
$("#notebookNavForListNote").html(navForListNote);
$("#notebookNavForNewNote").html(navForNewNote);
$("#notebookNavForMoveNote").html(navForNewNote);
// 移动, 复制重新来, 因为nav变了, 移动至-----的notebook导航也变了
Note.initContextmenu();
}
/**
* 我的共享notebooks
<div id="shareNotebooks">
<div class="folderNote closed">
<div class="folderHeader">
<a>
<h1>
<i class="fa fa-angle-right"></i>
Life's</h1>
</a>
</div>
<ul class="folderBody">
<li><a>Hadoop</a></li>
<li><a>Node webkit</a></li>
<li><a>Hadoop</a></li>
<li><a>Node webkit</a></li>
</ul>
</div>
*/
// TODO 层级
Notebook.renderShareNotebooks = function(sharedUserInfos, shareNotebooks) {
if(isEmpty(sharedUserInfos)) {
return;
}
if(!shareNotebooks || typeof shareNotebooks != "object" || shareNotebooks.length < 0) {
return;
}
var $shareNotebooks = $("#shareNotebooks");
var user2ShareNotebooks = {};
for(var i in shareNotebooks) {
var userNotebooks = shareNotebooks[i];
user2ShareNotebooks[userNotebooks.UserId] = userNotebooks;
}
for(var i in sharedUserInfos) {
var userInfo = sharedUserInfos[i];
var userNotebooks = user2ShareNotebooks[userInfo.UserId] || {ShareNotebooks:[]};
userNotebooks.ShareNotebooks = [{NotebookId: "-2", Title: "默认共享"}].concat(userNotebooks.ShareNotebooks)
var username = userInfo.Username || userInfo.Email;
var header = t('<div class="folderNote closed"><div class="folderHeader"><a><h1 title="? 的共享"><i class="fa fa-angle-right"></i>?</h1></a></div>', username, username);
var body = '<ul class="folderBody">';
for(var j in userNotebooks.ShareNotebooks) {
var notebook = userNotebooks.ShareNotebooks[j];
body += t('<li><a notebookId="?">?</a></li>', notebook.NotebookId, notebook.Title)
}
body += "</ul>";
$shareNotebooks.append(header + body + "</div>")
}
}
// 左侧导航, 选中某个notebook
Notebook.selectNotebook = function(target) {
$("#notebook li a").removeClass("active");
$(target).addClass("active");
};
// 新建笔记导航
Notebook.changeNotebookNavForNewNote = function(notebookId, title) {
// 没有notebookId, 则选择第1个notebook
// 第一个是全部笔记
if(!notebookId) {
var notebook = Notebook.notebooks[0];
notebookId = notebook.NotebookId;
title = notebook.Title;
}
if(!title) {
var notebook = Notebook.cache[0];
title = notebook.Title;
}
if(!Notebook.isAllNotebookId(notebookId) && !Notebook.isTrashNotebookId(notebookId)) {
$("#curNotebookForNewNote").html(title).attr("notebookId", notebookId);
} else if(!$("#curNotebookForNewNote").attr("notebookId")) {
// 但又没有一个笔记, 默认选第一个吧
// 这里很可能会死循环, 万一用户没有其它笔记呢?
// 服务端肯定要在新建一个用户时给他创建一个默认笔记本的
if(Notebook.notebooks.length > 2) {
var notebook = Notebook.notebooks[1];
notebookId = notebook.NotebookId;
title = notebook.Title;
Notebook.changeNotebookNavForNewNote(notebookId, title);
}
}
}
// 改变导航, 两处
// 单击左侧, 单击新建下拉时调用
// 1 选中左侧导航,
// 2 notelist上面 >
// 3 新建笔记 - js >
// 转成我的nav <-> 共享
Notebook.toggleToMyNav = function(userId, notebookId) {
$("#sharedNotebookNavForListNav").hide();
$("#myNotebookNavForListNav").show();
$("#newMyNote").show();
$("#newSharedNote").hide();
// 搜索tag隐藏
$("#tagSearch").hide();
}
Notebook.changeNotebookNav = function(notebookId) {
Notebook.toggleToMyNav();
// 1
Notebook.selectNotebook($(t('#notebookList [notebookId="?"]', notebookId)));
var notebook = Notebook.cache[notebookId];
if(!notebook) {
return;
}
// 2
$("#curNotebookForListNote").html(notebook.Title);
// 3
Notebook.changeNotebookNavForNewNote(notebookId, notebook.Title);
}
Notebook.isAllNotebookId = function(notebookId) {
return notebookId == Notebook.allNotebookId;
}
Notebook.isTrashNotebookId = function(notebookId) {
return notebookId == Notebook.trashNotebookId;
}
// 当前选中的笔记本是否是"所有"
// called by Note
Notebook.curActiveNotebookIsAll = function() {
return Notebook.isAllNotebookId($("#notebookList .active").attr("notebookId"));
}
// 改变笔记本
// 0. 改变样式
// 1. 改变note, 此时需要先保存
// 2. ajax得到该notebook下的所有note
// 3. 使用Note.RederNotes()
Notebook.changeNotebook = function(notebookId) {
Notebook.changeNotebookNav(notebookId);
Notebook.curNotebookId = notebookId;
// 1
Note.curChangedSaveIt();
// 2 先清空所有
Note.clearAll();
var url = "/note/ListNotes/";
var param = {notebookId: notebookId};
// 废纸篓
if(Notebook.isTrashNotebookId(notebookId)) {
url = "/note/listTrashNotes";
param = {};
} else if(Notebook.isAllNotebookId(notebookId)) {
param = {};
// 得到全部的...
cacheNotes = Note.getNotesByNotebookId();
if(!isEmpty(cacheNotes)) { // 万一真的是没有呢?
Note.renderNotesAndFirstOneContent(cacheNotes);
return;
}
} else {
cacheNotes = Note.getNotesByNotebookId(notebookId);
if(!isEmpty(cacheNotes)) { // 万一真的是没有呢?
Note.renderNotesAndFirstOneContent(cacheNotes);
return;
}
}
// 2 得到笔记本
// 这里可以缓存起来, note按notebookId缓存
ajaxGet(url, param, Note.renderNotesAndFirstOneContent);
}
// 是否是当前选中的notebookId
// 还包括共享
// called by Note
Notebook.isCurNotebook = function(notebookId) {
return $(t('#notebookList [notebookId="?"], #shareNotebooks [notebookId="?"]', notebookId, notebookId)).attr("class") == "active";
}
// 改变nav, 为了新建note
// called by Note
Notebook.changeNotebookForNewNote = function(notebookId) {
// 废纸篓
if(Notebook.isTrashNotebookId(notebookId) || Notebook.isAllNotebookId(notebookId)) {
return;
}
Notebook.changeNotebookNav(notebookId);
Notebook.curNotebookId = notebookId;
var url = "/note/ListNotes/";
var param = {notebookId: notebookId};
// 2 得到笔记本
// 这里可以缓存起来, note按notebookId缓存
ajaxGet(url, param, function(ret) {
// note 导航
Note.renderNotes(ret, true);
});
};
//---------------------------
// 显示共享信息
Notebook.listNotebookShareUserInfo = function(target) {
var notebookId = $(target).attr("notebookId");
showDialogRemote("share/listNotebookShareUserInfo", {notebookId: notebookId});
}
// 共享笔记本
Notebook.shareNotebooks= function(target) {
var title = $(target).text();
showDialog("dialogShareNote", {title: "分享笔记本给好友-" + title});
setTimeout(function() {
$("#friendsEmail").focus();
}, 500);
var notebookId = $(target).attr("notebookId");
shareNoteOrNotebook(notebookId, false);
}
//-----------------------------
// 设为blog/unset
Notebook.setNotebook2Blog = function(target) {
var notebookId = $(target).attr("notebookId");
var notebook = Notebook.cache[notebookId];
var isBlog = true;
if(notebook.IsBlog != undefined) {
isBlog = !notebook.IsBlog;
}
// 那么, 如果当前是该notebook下, 重新渲染之
if(Notebook.curNotebookId == notebookId) {
if(isBlog) {
$("#noteList .item-blog").show();
} else {
$("#noteList .item-blog").hide();
}
// 如果当前在所有笔记本下
} else if(Notebook.curNotebookId == Notebook.allNotebookId){
$("#noteItemList .item").each(function(){
var noteId = $(this).attr("noteId");
var note = Note.cache[noteId];
if(note.NotebookId == notebookId) {
if(isBlog) $(this).find(".item-blog").show();
else $(this).find(".item-blog").hide();
}
});
}
ajaxPost("blog/setNotebook2Blog", {notebookId: notebookId, isBlog: isBlog}, function(ret) {
if(ret) {
// 这里要设置notebook下的note的blog状态
Note.setAllNoteBlogStatus(notebookId, isBlog);
Notebook.setCache({NotebookId: notebookId, IsBlog: isBlog});
}
});
}
// 添加, 修改完后都要对notebook的列表重新计算 TODO
// 修改笔记本标题
Notebook.updateNotebookTitle = function(target) {
var notebookTitle = $(target).text();
var id = "editNotebookTitle";
$(target).html(t('<input type="text" value="?" everValue="?" id="?" notebookId="?"/>', notebookTitle, notebookTitle, id, $(target).attr("notebookId")));
$("#" + id).focus();
}
Notebook.doUpdateNotebookTitle = function() {
var title = $(this).val();
var everTitle = $(this).attr("everTitle");
var notebookId = $(this).attr("notebookId");
if(!title) {
title = everTitle;
}
$(this).parent().html(title);
if(title != everTitle) {
ajaxPost("/notebook/updateNotebookTitle", {notebookId: notebookId, title: title}, function(ret) {
// 修改缓存
Notebook.cache[notebookId].Title = title;
// 改变nav
Notebook.changeNav();
});
}
}
//-----------
// 添加笔记本
// 1 确保是展开的
// 2 在所有后面添加<li></li>
Notebook.addNotebookSeq = 1; // inputId
Notebook.addNotebook = function() {
if($("#myNotebooks").hasClass("closed")) {
$("#myNotebooks .folderHeader").trigger("click");
}
var inputId = "newNotebookInput" + Notebook.addNotebookSeq;
Notebook.addNotebookSeq++;
$("#notebookList li").eq(0).after(t('<li><a><input id="?"/></a></li>', inputId));
$("#" + inputId).focus();
// 回车调用blur
enterBlur("#" + inputId);
$("#" + inputId).blur(function() {
// 为防多次发生blur
$(this).unbind("blur");
var title = $(this).val();
if(!title) {
$(this).parent().parent().remove();
} else {
// 添加之
var notebookId = getObjectId();
var $a = $(this).parent();
ajaxPost("/notebook/addNotebook", {notebookId: notebookId, title: title}, function(ret) {
if(ret.NotebookId) {
Notebook.cache[ret.NotebookId] = ret;
$a.attr("notebookId", notebookId);
$a.html(title);
// 选中之
Notebook.changeNotebook(notebookId);
// 改变nav
Notebook.changeNav();
}
});
}
});
}
//-------------
// 删除
Notebook.deleteNotebook = function(target) {
var notebookId = $(target).attr("notebookId");
if(!notebookId) {
return;
}
ajaxGet("/notebook/deleteNotebook", {notebookId: notebookId}, function(ret) {
if(ret.Ok) {
$(target).parent().remove();
delete Notebook.cache[notebookId];
// 改变nav
Notebook.changeNav();
} else {
alert(ret.Msg);
}
});
}
$(function() {
//-------------------
// 点击notebook
$("#myNotebooks").on("click", "ul.folderBody li a", function() {
var notebookId = $(this).attr("notebookId");
Notebook.changeNotebook(notebookId);
});
// min
$("#minNotebookList").on("click", "li", function() {
var notebookId = $(this).find("a").attr("notebookId");
Notebook.changeNotebook(notebookId);
});
//-------------------
// 右键菜单
var notebookListMenu = {
width: 150,
items: [
{ text: "分享给好友", alias: 'shareToFriends', icon: "", faIcon: "fa-share-square-o", action: Notebook.listNotebookShareUserInfo},
{ type: "splitLine" },
{ text: "公开为博客", alias: 'set2Blog', icon: "", action: Notebook.setNotebook2Blog },
{ text: "取消公开为博客", alias: 'unset2Blog', icon: "", action: Notebook.setNotebook2Blog }, // Unset
{ type: "splitLine" },
{ text: "重命名", icon: "", action: Notebook.updateNotebookTitle },
{ text: "删除", icon: "", alias: 'delete', faIcon: "fa-trash-o", action: Notebook.deleteNotebook }
],
onShow: applyrule,
onContextMenu: beforeContextMenu,
parent: "#notebookList ",
children: "li a"
}
// 修改笔记本标题, blur后修改标题之
enterBlur("#notebookList", "input#editNotebookTitle");
$("#notebookList").on("blur", "input#editNotebookTitle", Notebook.doUpdateNotebookTitle);
function applyrule(menu) {
var notebookId = $(this).attr("notebookId");
var notebook = Notebook.cache[notebookId];
if(!notebook) {
return;
}
var items = [];
// 是否已公开为blog
if(!notebook.IsBlog) {
items.push("unset2Blog");
} else {
items.push("set2Blog");
}
// 是否还有笔记
if(Note.notebookHasNotes(notebookId)) {
items.push("delete");
}
menu.applyrule({
name: "target2",
disable: true,
items: items
});
}
// 哪个不能
function beforeContextMenu() {
var notebookId = $(this).attr("notebookId");
return !Notebook.isTrashNotebookId(notebookId) && !Notebook.isAllNotebookId(notebookId);
}
$("#notebookList li a").contextmenu(notebookListMenu);
//------------------
// 添加notebook
// 右键菜单
var addNotebookContextmenu = {
width: 150,
items: [
{ text: "添加笔记本", icon: "", action: Notebook.addNotebook },
],
parent: "#myNotebooks",
children: ""
}
$("#myNotebooks").contextmenu(addNotebookContextmenu);
//---------------
// 点击中部notebook nav
$("#notebookNavForListNote").on("click", "li", function() {
var notebookId = $(this).find("a").attr("notebookId");
Notebook.changeNotebook(notebookId);
});
// 添加笔记本
$("#addNotebookPlus").click(function(e) {
e.stopPropagation();
Notebook.addNotebook();
});
});

1
public/js/app/page-min.js vendored Normal file

File diff suppressed because one or more lines are too long

682
public/js/app/page.js Normal file
View File

@ -0,0 +1,682 @@
// 主页渲染
// ifr 的高度, 默认是小20px, 启动1s后运行resizeEditor()调整之
// 鼠标拖动改变宽度
var lineMove = false;
var target = null;
function stopResize3Columns() {
if (lineMove) {
// ajax保存
ajaxGet("/user/updateColumnWidth", {notebookWidth: UserInfo.NotebookWidth, noteListWidth: UserInfo.NoteListWidth}, function() {
});
}
lineMove = false;
$(".noteSplit").css("background", "none");
}
// 最终调用该方法
function resize3ColumnsEnd(notebookWidth, noteListWidth) {
if(notebookWidth < 150 || noteListWidth < 100) {
// return;
}
var noteWidth = $("body").width() - notebookWidth - noteListWidth;
if(noteWidth < 400) {
// return;
}
$("#leftNotebook").width(notebookWidth);
$("#notebookSplitter").css("left", notebookWidth);
$("#noteAndEditor").css("left", notebookWidth);
$("#noteList").width(noteListWidth);
$("#noteSplitter").css("left", noteListWidth);
$("#note").css("left", noteListWidth);
UserInfo.NotebookWidth = notebookWidth;
UserInfo.NoteListWidth = noteListWidth;
}
function resize3Columns(event, isFromeIfr) {
if (isFromeIfr) {
event.clientX += $("body").width() - $("#note").width();
}
var notebookWidth, noteListWidth;
if (lineMove == true) {
if (target == "notebookSplitter") {
notebookWidth = event.clientX;
noteListWidth = $("#noteList").width();
resize3ColumnsEnd(notebookWidth, noteListWidth);
} else {
notebookWidth = $("#leftNotebook").width();
noteListWidth = event.clientX - notebookWidth;
resize3ColumnsEnd(notebookWidth, noteListWidth);
}
resizeEditor();
}
}
// editor
$(function() {
// 高度设置
// $("#editor").css("top", $("#noteTop").height());
$(".noteSplit").bind("mousedown", function(event) {
event.preventDefault(); // 防止选择文本
lineMove = true;
$(this).css("background-color", "#ccc");
target = $(this).attr("id");
// 防止iframe捕获不了事件
$("#noteMask").css("z-index", 99999); // .css("background-color",
// "#ccc");
});
$("body").bind("mouseup", function(event) {
stopResize3Columns();
// 取消遮罩
$("#noteMask").css("z-index", -1);
});
$("body").bind("mousemove", function(event) {
if(lineMove) { // 如果没有这个if会导致不能选择文本
event.preventDefault();
resize3Columns(event);
}
});
// toolbar 下拉扩展, 也要resizeEditor
$("#moreBtn").click(function() {
saveBookmark();
var height = $("#mceToolbar").height();
if (height < $("#popularToolbar").height()) {
$("#mceToolbar").height($("#popularToolbar").height());
$(this).find("i").removeClass("fa-angle-down").addClass("fa-angle-up");
} else {
$("#mceToolbar").height(30);
$(this).find("i").removeClass("fa-angle-up").addClass("fa-angle-down");
}
// 新加 3.12
var mceToolbarHeight = $("#mceToolbar").height();
$("#editorContent").css("top", mceToolbarHeight);
// 新加3/22
$("#leanoteNav").css("top", mceToolbarHeight + 2);
$("#editor").css("top", $("#noteTop").height());
resizeEditor();
restoreBookmark();
});
// 窗口缩放时
$(window).resize(function() {
resizeEditor();
});
// 左侧, folder 展开与关闭
$(".folderHeader").click(
function() {
var body = $(this).next();
var p = $(this).parent();
if (!body.is(":hidden")) {
$(".folderNote").removeClass("opened").addClass("closed");
// body.hide();
p.removeClass("opened").addClass("closed");
$(this).find(".fa-angle-down").removeClass("fa-angle-down").addClass("fa-angle-right");
} else {
$(".folderNote").removeClass("opened").addClass("closed");
// body.show();
p.removeClass("closed").addClass("opened");
$(this).find(".fa-angle-right").removeClass("fa-angle-right").addClass("fa-angle-down");
}
});
tinymce.init({
setup: function(ed) {
ed.on('keydown', Note.saveNote);
// indent outdent
ed.on('keydown', function(e) {
var num = e.which ? e.which : e.keyCode;
if (num == 9) { // tab pressed
if(!e.shiftKey) {
// ed.execCommand('Indent');
// 如果在pre下就加tab
var node = ed.selection.getNode();
if(node.nodeName == "PRE") {
ed.execCommand('mceInsertRawHTML', false, '\x09'); // inserts tab
} else {
ed.execCommand('mceInsertRawHTML', false, "&nbsp;&nbsp;&nbsp;&nbsp;"); // inserts 空格
}
} else {
// delete 4 个空格
// ed.execCommand('Outdent');
}
e.preventDefault();
e.stopPropagation();
return false;
}
});
// 为了把下拉菜单关闭
ed.on("click", function(e) {
$("body").trigger("click");
});
// 鼠标移上时
ed.on("click", function() {
log(ed.selection.getNode())
});
},
selector : "#editorContent",
// height: 100,//这个应该是文档的高度, 而其上层的高度是$("#content").height(),
// parentHeight: $("#content").height(),
content_css : ["css/bootstrap.css", "css/editor.css"],
skin : "custom",
language: "zh_CN",
plugins : [
"autolink link leanote_image lists charmap hr", "paste",
"searchreplace leanote_nav leanote_code tabfocus",
"table directionality textcolor codemirror" ], // nonbreaking
toolbar1 : "formatselect | forecolor backcolor | bold italic underline strikethrough | leanote_image | leanote_code | bullist numlist | alignleft aligncenter alignright alignjustify",
toolbar2 : "outdent indent blockquote | link unlink | table | hr removeformat | subscript superscript |searchreplace | code | pastetext | fontselect fontsizeselect",
// 使用tab键: http://www.tinymce.com/wiki.php/Plugin3x:nonbreaking
// http://stackoverflow.com/questions/13543220/tiny-mce-how-to-allow-people-to-indent
// nonbreaking_force_tab : true,
menubar : false,
toolbar_items_size : 'small',
statusbar : false,
url_converter: false,
font_formats : "Arial=arial,helvetica,sans-serif;"
+ "Arial Black=arial black,avant garde;"
+ "Times New Roman=times new roman,times;"
+ "Courier New=courier new,courier;"
+ "Tahoma=tahoma,arial,helvetica,sans-serif;"
+ "Verdana=verdana,geneva;" + "宋体=SimSun;"
+ "新宋体=NSimSun;" + "黑体=SimHei;"
+ "微软雅黑=Microsoft YaHei",
block_formats : "Header 1=h1;Header 2=h2;Header 3=h3; Header 4=h4;Pre=pre;Paragraph=p",
codemirror: {
indentOnInit: true, // Whether or not to indent code on init.
path: 'CodeMirror', // Path to CodeMirror distribution
config: { // CodeMirror config object
//mode: 'application/x-httpd-php',
lineNumbers: true
},
jsFiles: [ // Additional JS files to load
// 'mode/clike/clike.js',
//'mode/php/php.js'
]
},
// This option specifies whether data:url images (inline images) should be removed or not from the pasted contents.
// Setting this to "true" will allow the pasted images, and setting this to "false" will disallow pasted images.
// For example, Firefox enables you to paste images directly into any contentEditable field. This is normally not something people want, so this option is "false" by default.
paste_data_images: true
});
// 刷新时保存 参考autosave插件
window.onbeforeunload = function(e) {
Note.curChangedSaveIt();
}
// 全局ctrl + s
$("body").on('keydown', Note.saveNote);
});
// ie下拒绝访问
// 有兼容性问题
// 不能设置iframe src
var random = 1;
function scrollTo(self, tagName, text) {
var iframe = $("#editorContent_ifr").contents();
var target = iframe.find(tagName + ":contains(" + text + ")");
random++;
// 找到是第几个
// 在nav是第几个
var navs = $('#leanoteNavContent [data-a="' + tagName + '-' + encodeURI(text) + '"]');
// alert('#leanoteNavContent [data-a="' + tagName + '-' + encodeURI(text) + '"]')
var len = navs.size();
for(var i = 0; i < len; ++i) {
if(navs[i] == self) {
break;
}
}
if (target.size() >= i+1) {
target = target.eq(i);
// 之前插入, 防止多行定位不准
var top = target.offset().top;
var nowTop = iframe.scrollTop();
// iframe.scrollTop(top);
// $(iframe).animate({scrollTop: top}, 300); // 有问题
var d = 200; // 时间间隔
for(var i = 0; i < d; i++) {
setTimeout(
(function(top) {
return function() {
iframe.scrollTop(top);
}
})(nowTop + 1.0*i*(top-nowTop)/d), i);
}
// 最后必然执行
setTimeout(function() {
iframe.scrollTop(top);
}, d+5);
return;
/*
$(target).prepend(
'<a class="r-' + random + '" name="' + random + '"></a>')
$("#editorContent_ifr").attr("src", "#" + random);
iframe.find(".r-" + random).remove();
*/
}
}
$(function() {
// 导航隐藏与显示
$("#leanoteNav h1").on("click", function(e) {
if (!$("#leanoteNav").hasClass("unfolder")) {
$("#leanoteNav").addClass("unfolder");
} else {
$("#leanoteNav").removeClass("unfolder");
}
});
// 打开设置
function openSetInfoDialog(whichTab) {
showDialog("dialogSetInfo", {title: "帐户设置", postShow: function() {
$('#myTabs a').eq(whichTab).tab('show');
$("#username").val(UserInfo.Username);
}});
}
// 帐号设置
$("#setInfo").click(function() {
if(UserInfo.Email) {
openSetInfoDialog(0);
} else {
showDialog("thirdDialogSetInfo", {title: "帐户设置", postShow: function() {
$('#thirdMyTabs a').eq(0).tab('show');
}});
}
});
$("#setTheme").click(function() {
showDialog2("#setThemeDialog", {title: "主题设置", postShow: function() {
if (!UserInfo.Theme) {
UserInfo.Theme = "default";
}
$("#themeForm input[value='" + UserInfo.Theme + "']").attr("checked", true);
}});
});
//---------
// 主题
$("#themeForm").on("click", "input", function(e) {
var val = $(this).val();
$("#themeLink").attr("href", "/css/theme/" + val + ".css");
ajaxPost("/user/updateTheme", {theme: val}, function(re) {
if(reIsOk(re)) {
UserInfo.Theme = val
}
});
});
//--------------
// 第三方账号设置
$("#leanoteDialog").on("click", "#accountBtn", function(e) {
e.preventDefault();
var email = $("#thirdEmail").val();
var pwd = $("#thirdPwd").val();
var pwd2 = $("#thirdPwd2").val();
if(!email) {
showAlert("#thirdAccountMsg", "请输入邮箱", "danger", "#thirdEmail");
return;
} else {
var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
if(!myreg.test(email)) {
showAlert("#thirdAccountMsg", "请输入正确的邮箱", "danger", "#thirdEmail");
return;
}
}
if(!pwd) {
showAlert("#thirdAccountMsg", "请输入密码", "danger", "#thirdPwd");
return;
} else {
if(pwd.length < 6) {
showAlert("#thirdAccountMsg", "密码长度至少6位", "danger", "#thirdPwd");
return;
}
}
if(!pwd2) {
showAlert("#thirdAccountMsg", "请重复输入密码", "danger", "#thirdPwd2");
return;
} else {
if(pwd != pwd2) {
showAlert("#thirdAccountMsg", "两次密码输入不一致", "danger", "#thirdPwd2");
return;
}
}
hideAlert("#thirdAccountMsg");
post("/user/addAccount", {email: email, pwd: pwd}, function(ret) {
if(ret.Ok) {
showAlert("#thirdAccountMsg", "添加成功!", "success");
UserInfo.Email = email;
$("#curEmail").html(email);
hideDialog(1000);
} else {
showAlert("#thirdAccountMsg", ret.Msg || "添加失败!", "danger");
}
}, this);
});
//-------------
$("#leanoteDialog").on("click", "#usernameBtn", function(e) {
e.preventDefault();
var username = $("#leanoteDialog #username").val();
if(!username) {
showAlert('#usernameMsg', "请输入用户名", "danger");
return;
} else if(username.length < 4) {
showAlert('#usernameMsg', "用户名长度至少4位", "danger");
return;
} else if(/[^0-9a-zzA-Z_\-]/.test(username)) {
// 是否含特殊字段?
showAlert('#usernameMsg', "用户名不能含除数字,字母之外的字符", "danger");
return;
}
hideAlert("#usernameMsg");
post("/user/updateUsername", {username: username}, function(ret) {
if(ret.Ok) {
UserInfo.UsernameRaw = username;
UserInfo.Username = username.toLowerCase();
$(".username").html(username);
showAlert('#usernameMsg', "用户名修改成功!", "success");
} else {
showAlert('#usernameMsg', re.Msg || '该用户名已存在', "danger");
}
}, "#usernameBtn");
});
// 修改邮箱
$("#leanoteDialog").on("click", "#emailBtn", function(e) {
e.preventDefault();
var email = isEmailFromInput("#email", "#emailMsg");
if(!email) {
return;
}
hideAlert("#emailMsg");
post("/user/updateEmailSendActiveEmail", {email: email}, function(e) {
if(e.Ok) {
var url = getEmailLoginAddress(email);
showAlert("#emailMsg", "验证邮件已发送, 请及时查阅邮件并验证. <a href='" + url + "' target='_blank'>立即验证</a>", "success");
} else {
showAlert("#emailMsg", e.Msg || "邮件发送失败", "danger");
}
}, "#emailBtn");
});
// 修改密码
$("#leanoteDialog").on("click", "#pwdBtn", function(e) {
e.preventDefault();
var oldPwd = $("#oldPwd").val();
var pwd = $("#pwd").val();
var pwd2 = $("#pwd2").val();
if(!oldPwd) {
showAlert("#pwdMsg", "请输入旧密码", "danger", "#oldPwd");
return;
} else {
if(oldPwd.length < 6) {
showAlert("#pwdMsg", "密码长度至少6位", "danger", "#oldPwd");
return;
}
}
if(!pwd) {
showAlert("#pwdMsg", "请输入新密码", "danger", "#pwd");
return;
} else {
if(pwd.length < 6) {
showAlert("#pwdMsg", "密码长度至少6位", "danger", "#pwd");
return;
}
}
if(!pwd2) {
showAlert("#pwdMsg", "请重复输入新密码", "danger", "#pwd2");
return;
} else {
if(pwd != pwd2) {
showAlert("#pwdMsg", "两次密码输入不一致", "danger", "#pwd2");
return;
}
}
hideAlert("#pwdMsg");
post("/user/updatePwd", {oldPwd: oldPwd, pwd: pwd}, function(e) {
if(e.Ok) {
showAlert("#pwdMsg", "修改密码成功", "success");
} else {
showAlert("#pwdMsg", e.Msg, "danger");
}
}, "#pwdBtn");
});
//-------------
//-------------
// 邮箱验证
if(!UserInfo.Verified) {
// $("#leanoteMsg").hide();
// $("#verifyMsg").show();
}
// 帐号设置
$("#wrongEmail").click(function() {
openSetInfoDialog(1);
});
// 重新发送
$("#leanoteDialog").on("click", ".reSendActiveEmail", function() {
// 弹框出来
showDialog("reSendActiveEmailDialog", {title: "发送验证邮件", postShow: function() {
ajaxGet("/user/reSendActiveEmail", {}, function(ret) {
if (typeof ret == "object" && ret.Ok) {
$("#leanoteDialog .text").html("发送成功!")
$("#leanoteDialog .viewEmailBtn").removeClass("disabled");
$("#leanoteDialog .viewEmailBtn").click(function() {
hideDialog();
var url = getEmailLoginAddress(UserInfo.Email);
window.open(url, "_blank");
});
} else {
$("#leanoteDialog .text").html("发送失败")
}
});
}});
});
// 现在去验证
$("#leanoteDialog").on("click", ".nowToActive", function() {
var url = getEmailLoginAddress(UserInfo.Email);
window.open(url, "_blank");
});
// 禁止双击选中文字
$("#notebook, #newMyNote, #myProfile, #topNav, #notesAndSort", "#leanoteNavTrigger").bind("selectstart", function(e) {
e.preventDefault();
return false;
});
// 左侧隐藏或展示
function updateLeftIsMin(is) {
ajaxGet("/user/updateLeftIsMin", {leftIsMin: is})
}
function minLeft(save) {
$("#leftNotebook").width(30);
$("#notebook").hide();
// 左侧
$("#noteAndEditor").css("left", 30)
$("#notebookSplitter").hide();
// $("#leftSwitcher").removeClass("fa-angle-left").addClass("fa-angle-right");
// logo
$("#logo").hide();
$("#leftSwitcher").hide();
$("#leftSwitcher2").show();
if(save) {
updateLeftIsMin(true);
}
}
function maxLeft(save) {
$("#noteAndEditor").css("left", UserInfo.NotebookWidth);
$("#leftNotebook").width(UserInfo.NotebookWidth);
$("#notebook").show();
$("#notebookSplitter").show();
// $("#leftSwitcher").removeClass("fa-angle-right").addClass("fa-angle-left");
$("#leftSwitcher2").hide();
$("#logo").show();
$("#leftSwitcher").show();
if(save) {
updateLeftIsMin(false);
}
}
$("#leftSwitcher2").click(function() {
maxLeft(true);
});
$("#leftSwitcher").click(function() {
minLeft(true);
/*
if(!$("#notebook").is(":hidden")) {
} else {
maxLeft(true);
}
*/
});
// 得到最大dropdown高度
function getMaxDropdownHeight(obj) {
var offset = $(obj).offset();
var maxHeight = $(document).height()-offset.top;
maxHeight -= 70;
if(maxHeight < 0) {
maxHeight = 0;
}
var preHeight = $(obj).find("ul").height();
return preHeight < maxHeight ? preHeight : maxHeight;
}
// mini版
$("#notebookMin div.minContainer").hover(function() {
var target = $(this).attr("target");
// show的时候要计算高度, 防止过高
// 先show再计算, 不然高度有偏差
$(this).find("ul").html($(target).html()).show().height(getMaxDropdownHeight(this));
}, function() {
$(this).find("ul").hide();
}
);
//------------------------
// 界面设置, 左侧是否是隐藏的
UserInfo.NotebookWidth = UserInfo.NotebookWidth || $("#notebook").width();
UserInfo.NoteListWidth = UserInfo.NoteListWidth || $("#noteList").width();
if(LEA.isMobile) {
UserInfo.NoteListWidth = 101;
}
resize3ColumnsEnd(UserInfo.NotebookWidth, UserInfo.NoteListWidth);
if (UserInfo.LeftIsMin) {
minLeft(false);
}
// end
$("#mainMask").html("");
$("#mainMask").hide(100);
// 4/25 防止dropdown太高
// dropdown
$('.dropdown').on('shown.bs.dropdown', function () {
var $ul = $(this).find("ul");
$ul.height(getMaxDropdownHeight(this));
});
//--------
// 编辑器帮助
$("#tipsBtn").click(function() {
showDialog2("#tipsDialog");
});
//--------
// 建议
$("#yourSuggestions").click(function() {
showDialog2("#suggestionsDialog");
});
$("#suggestionBtn").click(function(e) {
e.preventDefault();
var suggestion = $.trim($("#suggestionTextarea").val());
if(!suggestion) {
$("#suggestionMsg").html("请输入您的建议, 谢谢!").show().addClass("alert-warning").removeClass("alert-success");
$("#suggestionTextarea").focus();
return;
}
$("#suggestionBtn").html("正在处理...").addClass("disabled");
$("#suggestionMsg").html("正在处理...");
$.post("/suggestion", {suggestion: suggestion}, function(ret) {
$("#suggestionBtn").html("提交").removeClass("disabled");
if(ret.Ok) {
$("#suggestionMsg").html("谢谢反馈, 我们会第一时间处理, 祝您愉快!").addClass("alert-success").removeClass("alert-warning").show();
} else {
$("#suggestionMsg").html("出错了").show().addClass("alert-warning").removeClass("alert-success");
}
});
});
// slimScroll
//---
setTimeout(function() {
$("#notebook").slimScroll({
height: "100%", // $("#leftNotebook").height()+"px"
});
$("#noteItemList").slimScroll({
height: "100%", // ($("#leftNotebook").height()-42)+"px"
});
$("#wmd-input").slimScroll({
height: "100%", // $("#wmd-input").height()+"px"
});
$("#wmd-input").css("width", "100%");
$("#wmd-panel-preview").slimScroll({
height: "100%", // $("#wmd-panel-preview").height()+"px"
});
$("#wmd-panel-preview").css("width", "100%");
}, 10);
});

1
public/js/app/share-min.js vendored Normal file

File diff suppressed because one or more lines are too long

540
public/js/app/share.js Normal file
View File

@ -0,0 +1,540 @@
//------------------------------------
// 共享, notbeook, note
//------------------------------------
// 默认共享notebook id
Share.defaultNotebookId = "share0";
Share.defaultNotebookTitle = "默认共享";
Share.sharedUserInfos = {}; // userId => {}
// 在render时就创建, 以后复用之
Share.userNavs = {}; // userId => {"forList":html, "forNew":html}
// 缓存都不要, 统一放在Note.cache中
// 放在这里, 只是为了debug, 分离
Share.notebookCache = {}; // notebooks 的cache
Share.cache = {}; // note的cache
// 分享的弹出框是note的
Share.dialogIsNote = true;
// 设置缓存 note
Share.setCache = function(note) {
if(!note || !note.NoteId) {
return;
}
Share.cache[note.NoteId] = note;
}
/**
* 我的共享notebooks
<div id="shareNotebooks">
<div class="folderNote closed">
<div class="folderHeader">
<a>
<h1>
<i class="fa fa-angle-right"></i>
Life's</h1>
</a>
</div>
<ul class="folderBody">
<li><a>Hadoop</a></li>
<li><a>Node webkit</a></li>
<li><a>Hadoop</a></li>
<li><a>Node webkit</a></li>
</ul>
</div>
*/
// TODO 层级
// shareNotebooks = {userId => {}}
Share.renderShareNotebooks = function(sharedUserInfos, shareNotebooks) {
if(isEmpty(sharedUserInfos)) {
return;
}
if(!shareNotebooks || typeof shareNotebooks != "object" || shareNotebooks.length < 0) {
return;
}
var $shareNotebooks = $("#shareNotebooks");
// render每一个用户的share给我的笔记本, 之前先建一个默认共享
for(var i in sharedUserInfos) {
var userInfo = sharedUserInfos[i];
var userNotebooks = shareNotebooks[userInfo.UserId] || [];
userNotebooks = [{NotebookId: Share.defaultNotebookId, Title: Share.defaultNotebookTitle}].concat(userNotebooks)
var username = userInfo.Username || userInfo.Email;
userInfo.Username = username;
Share.sharedUserInfos[userInfo.UserId] = userInfo;
var userId = userInfo.UserId;
var header = t('<li class="each-user"><div class="" fromUserId="?"><i class="fa fa-angle-down"></i><span>?</span></div>', userInfo.UserId, username);
var friendId = "friendContainer" + i;
var body = '<ul class="" id="' + friendId + '">';
var forList = ""; // 全部
var forNew = ""; // 必须要有权限的
for(var j in userNotebooks) {
var notebook = userNotebooks[j];
// 缓存起来, 像Note
notebook.IsShared = true;
notebook.UserId = userId;
Share.notebookCache[notebook.NotebookId] = notebook;
// notebook的cache也缓存一份, 为了显示标题
Notebook.cache[notebook.NotebookId] = notebook;
body += t('<li><a notebookId="?" fromUserId="?">?</a></li>', notebook.NotebookId, userId, notebook.Title)
//
var each = t('<li role="presentation"><a role="menuitem" tabindex="-1" href="#" userId="?" notebookId="?">?</a></li>', userId, notebook.NotebookId, notebook.Title);
forList += each;
if(j != 0 && notebook.Perm) {
forNew += t('<li role="presentation" class="clearfix" userId="?" notebookId="?"><div class="new-note-left pull-left">?</div><div class="new-note-right pull-left">Markdown</div></li>', userId, notebook.NotebookId, notebook.Title);
}
}
body += "</ul>";
Share.userNavs[userId] = {"forList": forList, "forNew": forNew};
$shareNotebooks.append(header + body + "</div>")
// mainShare
$("#minShareNotebooks").append('<div class="minContainer" target="#' + friendId + '" title="' + username + ' 的分享"><i class="fa fa-user"></i><ul class="dropdown-menu"></ul></li>')
}
};
Share.isDefaultNotebookId = function(notebookId) {
return Share.defaultNotebookId == notebookId;
}
// 转成共享的nav
// for list和for new
// 如果forNew没有, 那么还是保持我的nav
Share.toggleToSharedNav = function(userId, notebookId) {
// for list
$("#sharedNotebookNavForListNote").html(Share.userNavs[userId].forList);
$("#sharedNotebookNavForListNav").show();
$("#curSharedNotebookForListNote").html(Share.notebookCache[notebookId].Title + '(' + Share.sharedUserInfos[userId].Username + ")");
$("#myNotebookNavForListNav").hide();
// for new
var forNew = Share.userNavs[userId].forNew;
if(forNew) {
$("#notebookNavForNewSharedNote").html(forNew);
// 新建之, 可能当前选择的没有权限新建. 此时需要得到第一个
var curNotebookId = "";
var curNotebookTitle = "";
if(Share.notebookCache[notebookId].Perm) {
curNotebookId = notebookId;
curNotebookTitle = Share.notebookCache[notebookId].Title;
} else {
// 得到第一个
var $f = $("#notebookNavForNewSharedNote li").eq(0);
curNotebookId = $f.attr("notebookId");
curNotebookTitle = $f.text();
}
$("#curNotebookForNewSharedNote").html(curNotebookTitle + '(' + Share.sharedUserInfos[userId].Username + ')');
$("#curNotebookForNewSharedNote").attr("notebookId", curNotebookId);
$("#curNotebookForNewSharedNote").attr("userId", userId);
$("#newSharedNote").show();
$("#newMyNote").hide();
}
// 隐藏tag
$("#tagSearch").hide();
}
//改变笔记本
//0. 改变样式
//1. 改变note, 此时需要先保存
//2. ajax得到该notebook下的所有note
//3. 使用Note.RederNotes()
Share.changeNotebook = function(userId, notebookId) {
// 选中
Notebook.selectNotebook($(t('#shareNotebooks a[notebookId="?"]', notebookId)));
// 改变nav!!!! TODO
Share.toggleToSharedNav(userId, notebookId);
// 1
Note.curChangedSaveIt();
// 2 先清空所有
Note.clearAll();
var url = "/share/ListShareNotes/";
var param = {userId: userId};
if(!Share.isDefaultNotebookId(notebookId)) {
param.notebookId = notebookId;
}
// 2 得到笔记本
// 这里可以缓存起来, note按notebookId缓存
ajaxGet(url, param, function(ret) {
// note 导航
//
// 如果是特定笔记本下的notes, 那么传过来的没有权限信息, 此时权限由notebookId决定
if(param.notebookId) {
}
Note.renderNotes(ret, false, true);
// 渲染第一个
// 这里, 有点小复杂, 还要判断权限...
if(!isEmpty(ret)) {
// 定位
Note.changeNote(ret[0].NoteId, true);
} else {
}
});
}
// 是否有更新权限
// called by Note
Share.hasUpdatePerm = function(notebookId) {
var note = Share.cache[notebookId];
if(!note || !note.Perm) {
return false;
}
return true;
}
//---------------------------
// 我删除别人共享给我的笔记本
Share.deleteShareNotebook = function(target) {
var notebookId = $(target).attr("notebookId");
var fromUserId = $(target).attr("fromUserId"); // 谁共享给了我 from
ajaxGet("/share/DeleteShareNotebookBySharedUser", {notebookId: notebookId, fromUserId: fromUserId}, function(ret) {
if(ret) {
$(target).parent().remove();
}
});
}
Share.deleteShareNote = function(target) {
var noteId = $(target).attr("noteId");
var fromUserId = $(target).attr("fromUserId"); // 谁共享给了我 from
ajaxGet("/share/DeleteShareNoteBySharedUser", {noteId: noteId, fromUserId: fromUserId}, function(ret) {
if(ret) {
$(target).remove();
}
});
}
Share.deleteUserShareNoteAndNotebook = function(target) {
var fromUserId = $(target).attr("fromUserId"); // 谁共享给了我 from
ajaxGet("/share/deleteUserShareNoteAndNotebook", {fromUserId: fromUserId}, function(ret) {
if(ret) {
$(target).parent().remove();
}
});
}
// 新建shared note
Share.changeNotebookForNewNote = function(notebookId) {
// 改变nav for list, for new
Notebook.selectNotebook($(t('#shareNotebooks [notebookId="?"]', notebookId)));
var userId = Share.notebookCache[notebookId].UserId;
Share.toggleToSharedNav(userId, notebookId);
// 得到笔记本
var url = "/share/ListShareNotes/";
var param = {userId: userId, notebookId: notebookId};
// 2 得到笔记本
// 这里可以缓存起来, note按notebookId缓存
ajaxGet(url, param, function(ret) {
// note 导航
Note.renderNotes(ret, true, true);
});
}
// 删除笔记, 我有权限, 且是我创建的笔记
Share.deleteSharedNote = function(target, contextmenuItem) {
Note.deleteNote(target, contextmenuItem, true);
}
Share.copySharedNote = function(target, contextmenuItem) {
Note.copyNote(target, contextmenuItem, true);
}
Share.contextmenu = null;
Share.initContextmenu = function() {
if(Share.contextmenu) {
Share.contextmenu.unbind("contextmenu");
}
// 得到可移动的notebook
var notebooksCopy = [];
// 到时这个可以缓存起来
$("#notebookNavForNewNote li .new-note-left").each(function() {
var notebookId = $(this).attr("notebookId");
var title = $(this).text();
var copy = {text: title, notebookId: notebookId, action: Share.copySharedNote}
notebooksCopy.push(copy);
});
//---------------------
// context menu
//---------------------
var noteListMenu = {
width: 170,
items: [
{ text: "复制到我的笔记本", alias: "copy", icon: "",
type: "group",
width: 150,
items: notebooksCopy
},
{ type: "splitLine" },
{ text: "删除", alias: "delete", icon: "", faIcon: "fa-trash-o", action: Share.deleteSharedNote }
],
onShow: applyrule,
parent: "#noteItemList",
children: ".item-shared",
}
function applyrule(menu) {
var noteId = $(this).attr("noteId");
var note = Share.cache[noteId];
if(!note) {
return;
}
var items = [];
if(!(note.Perm && note.CreatedUserId == UserInfo.UserId)) {
items.push("delete");
}
// 不是自己的创建的不能删除
menu.applyrule({
name: "target...",
disable: true,
items: items
});
}
Share.contextmenu = $("#noteItemList .item-shared").contextmenu(noteListMenu);
}
$(function() {
// 点击notebook
$("#shareNotebooks").on("click", "ul li a", function() {
var notebookId = $(this).attr("notebookId");
var userId = $(this).attr("fromUserId");
Share.changeNotebook(userId, notebookId);
});
// min
$("#minShareNotebooks").on("click", "li", function() {
var self = $(this).find("a");
var notebookId = $(self).attr("notebookId");
var userId = $(self).attr("fromUserId");
Share.changeNotebook(userId, notebookId);
});
//-----------------------------
// contextmenu shareNotebooks
// 删除共享笔记本
var shareNotebookMenu = {
width: 150,
items: [
{ text: "删除共享笔记本", icon: "", faIcon: "fa-trash-o", action: Share.deleteShareNotebook }
],
onShow: applyrule,
onContextMenu: beforeContextMenu,
parent: "#shareNotebooks .folderBody",
children: "li a",
};
function applyrule(menu) {
return;
}
// 默认共享不能删除
function beforeContextMenu() {
var notebookId = $(this).attr("notebookId");
return !Share.isDefaultNotebookId(notebookId);
}
$("#shareNotebooks").contextmenu(shareNotebookMenu);
//---------------------------
// contextmenu shareNotebooks
// 删除某用户所有的
var shareUserMenu = {
width: 150,
items: [
{ text: "删除所有共享", icon: "", faIcon: "fa-trash-o", action: Share.deleteUserShareNoteAndNotebook }
],
parent: "#shareNotebooks",
children: ".folderHeader",
};
$("#shareNotebooks").contextmenu(shareUserMenu);
//---------------------------
// 新建笔记
// 1. 直接点击新建 OR
// 2. 点击nav for new note
$("#newSharedNoteBtn").click(function() {
var notebookId = $("#curNotebookForNewSharedNote").attr('notebookId');
var userId = $("#curNotebookForNewSharedNote").attr('userId');
Note.newNote(notebookId, true, userId);
});
$("#newShareNoteMarkdownBtn").click(function() {
var notebookId = $("#curNotebookForNewSharedNote").attr('notebookId');
var userId = $("#curNotebookForNewSharedNote").attr('userId');
Note.newNote(notebookId, true, userId, true);
});
$("#notebookNavForNewSharedNote").on("click", "li div", function() {
var notebookId = $(this).parent().attr("notebookId");
var userId = $(this).parent().attr("userId");
if($(this).text() == "Markdown") {
Note.newNote(notebookId, true, userId, true);
} else {
Note.newNote(notebookId, true, userId);
}
});
//------------------
Share.initContextmenu();
//------------------
// 添加共享
$("#leanoteDialogRemote").on("click", ".change-perm", function() {
var self = this;
var perm = $(this).attr("perm");
var noteOrNotebookId = $(this).attr("noteOrNotebookId");
var toUserId = $(this).attr("toUserId");
var toHtml = "可编辑";
var toPerm = "1";
if(perm == "1") {
toHtml = "只读";
toPerm = "0";
}
var url = "/share/UpdateShareNotebookPerm";
var param = {perm: toPerm, toUserId: toUserId};
if(Share.dialogIsNote) {
url = "/share/UpdateShareNotePerm";
param.noteId = noteOrNotebookId;
} else {
param.notebookId = noteOrNotebookId;
}
ajaxGet(url, param, function(ret) {
if(ret) {
$(self).html(toHtml);
$(self).attr("perm", toPerm);
}
});
});
$("#leanoteDialogRemote").on("click", ".delete-share", function() {
var self = this;
var noteOrNotebookId = $(this).attr("noteOrNotebookId");
var toUserId = $(this).attr("toUserId");
var url = "/share/DeleteShareNotebook";
var param = {toUserId: toUserId};
if(Share.dialogIsNote) {
url = "/share/DeleteShareNote";
param.noteId = noteOrNotebookId;
} else {
param.notebookId = noteOrNotebookId;
}
ajaxGet(url, param, function(ret) {
if(ret) {
$(self).parent().parent().remove();
}
});
});
// 添加共享
var seq = 1;
$("#leanoteDialogRemote").on("click", "#addShareNotebookBtn", function() {
seq++;
var tpl = '<tr id="tr' + seq + '"><td>#</td><td><input id="friendsEmail" type="text" class="form-control" style="width: 200px" placeholder="好友邮箱"/></td>';
tpl += '<td><label for="readPerm' + seq + '"><input type="radio" name="perm' + seq + '" checked="checked" value="0" id="readPerm' + seq + '"> 只读</label>';
tpl += ' <label for="writePerm' + seq + '"><input type="radio" name="perm' + seq + '" value="1" id="writePerm' + seq + '"> 可编辑</label></td>';
tpl += '<td><button class="btn btn-success" onclick="addShareNoteOrNotebook(' + seq + ')">分享</button>';
tpl += ' <button class="btn btn-warning" onclick="deleteShareNoteOrNotebook(' + seq + ')">删除</button>';
tpl += "</td></tr>";
$("#shareNotebookTable tbody").prepend(tpl);
$("#tr" + seq + " #friendsEmail").focus();
});
//-------------------
// 发送邀请邮件
$("#registerEmailBtn").click(function() {
var content = $("#emailContent").val();
var toEmail = $("#toEmail").val();
if(!content) {
showAlert("#registerEmailMsg", "邮件内容不能为空", "danger");
return;
}
post("/user/sendRegisterEmail", {content: content, toEmail: toEmail}, function(ret) {
showAlert("#registerEmailMsg", "发送成功!", "success");
hideDialog2("#sendRegisterEmailDialog", 1000);
}, this);
});
});
// trSeq 1,2,3...
function addShareNoteOrNotebook(trSeq) {
var trId = "#tr" + trSeq;
var id = Share.dialogNoteOrNotebookId;
var emails = isEmailFromInput(trId + " #friendsEmail", "#shareMsg", "请输入好友邮箱");
if(!emails) {
return;
}
var shareNotePerm = $(trId + ' input[name="perm' + trSeq + '"]:checked').val() || 0;
var perm = shareNotePerm;
// emails = emails.split(";");
var url = "share/addShareNote";
var data = {noteId: id, emails: [emails], perm: shareNotePerm};
if(!Share.dialogIsNote) {
url = "share/addShareNotebook";
data = {notebookId: id, emails: [emails], perm: shareNotePerm};
}
hideAlert("#shareMsg");
post(url, data, function(ret) {
var ret = ret[emails];
if(ret) {
// 成功
// 成功了则去掉输入框
if(ret.Ok) {
var tpl = t('<td>?</td>', '#');
tpl += t('<td>?</td>', emails);
tpl += t('<td><a href="#" noteOrNotebookId="?" perm="?" toUserId="?" title="点击改变权限" class="btn btn-default change-perm">?</a></td>', id, perm, ret.Id, !perm || perm == '0' ? "只读" : "可编辑");
tpl += t('<td><a href="#" noteOrNotebookId="?" toUserId="?" class="btn btn-warning delete-share">删除</a></td>', id, ret.Id);
$(trId).html(tpl);
} else {
var shareUrl = 'http://leanote/register?from=' + UserInfo.Username;
showAlert("#shareMsg", "该用户还没有注册, 复制邀请链接发送给Ta一起来体验leanote, 邀请链接: " + shareUrl + ' <a id="shareCopy" data-clipboard-target="copyDiv">点击复制</a> <span id="copyStatus"></span> <br /> 或者发送邀请邮件给Ta, <a href="#" onclick="sendRegisterEmail(\'' + emails + '\')">点击发送', "warning");
$("#copyDiv").text(shareUrl);
initCopy("shareCopy", function(args) {
if(args.text) {
showMsg2("#copyStatus", "复制成功", 1000);
} else {
showMsg2("#copyStatus", "对不起, 复制失败, 请自行复制", 1000);
}
});
}
}
}, trId + " .btn-success");
}
// 发送邀请邮件
function sendRegisterEmail(email) {
showDialog2("#sendRegisterEmailDialog", {postShow: function() {
$("#emailContent").val("Hi, 我是" + UserInfo.Username + ", leanote非常好用, 快来注册吧!");
setTimeout(function() {
$("#emailContent").focus();
}, 500);
$("#toEmail").val(email);
}});
}
function deleteShareNoteOrNotebook(trSeq) {
$("#tr" + trSeq).remove();
}

1
public/js/app/tag-min.js vendored Normal file
View File

@ -0,0 +1 @@
Tag.classes={"蓝色":"label label-blue","红色":"label label-red","绿色":"label label-green","黄色":"label label-yellow",blue:"label label-blue",red:"label label-red",green:"label label-green",yellow:"label label-yellow"};Tag.mapCn2En={"蓝色":"blue","红色":"red","绿色":"green","黄色":"yellow"};Tag.mapEn2Cn={blue:"蓝色",red:"红色",green:"绿色",yellow:"黄色"};Tag.t=$("#tags");Tag.getTags=function(){var tags=[];Tag.t.children().each(function(){var text=$(this).text();text=text.substring(0,text.length-1);text=Tag.mapCn2En[text]||text;tags.push(text)});return tags};Tag.clearTags=function(){Tag.t.html("")};Tag.renderTags=function(tags){Tag.t.html("");if(isEmpty(tags)){return}for(var i=0;i<tags.length;++i){var tag=tags[i];Tag.appendTag(tag)}};function revertTagStatus(){$("#addTagTrigger").show();$("#addTagInput").hide()}function hideTagList(event){$("#tagDropdown").removeClass("open");if(event){event.stopPropagation()}}function showTagList(event){$("#tagDropdown").addClass("open");if(event){event.stopPropagation()}}Tag.renderReadOnlyTags=function(tags){$("#noteReadTags").html("");if(isEmpty(tags)){$("#noteReadTags").html("无标签")}var i=true;function getNextDefaultClasses(){if(i){return"label label-default";i=false}else{i=true;return"label label-info"}}for(var i in tags){var text=tags[i];text=Tag.mapEn2Cn[text]||text;var classes=Tag.classes[text];if(!classes){classes=getNextDefaultClasses()}tag=t('<span class="?">?</span>',classes,text);$("#noteReadTags").append(tag)}};Tag.appendTag=function(tag){var isColor=false;var classes,text;if(typeof tag=="object"){classes=tag.classes;text=tag.text;if(!text){return}}else{tag=$.trim(tag);text=tag;if(!text){return}var classes=Tag.classes[text];if(classes){isColor=true}else{classes="label label-default"}}text=Tag.mapEn2Cn[text]||text;tag=t('<span class="?">?<i title="删除">X</i></span>',classes,text);$("#tags").children().each(function(){if(isColor){var tagHtml=$("<div></div>").append($(this).clone()).html();if(tagHtml==tag){$(this).remove()}}else if(text+"X"==$(this).text()){$(this).remove()}});$("#tags").append(tag);hideTagList();if(!isColor){reRenderTags()}};function reRenderTags(){var defautClasses=["label label-default","label label-info"];var i=0;$("#tags").children().each(function(){var thisClasses=$(this).attr("class");if(thisClasses=="label label-default"||thisClasses=="label label-info"){$(this).removeClass(thisClasses).addClass(defautClasses[i%2]);i++}})}Tag.renderTagNav=function(tags){tags=tags||[];for(var i in tags){var tag=tags[i];if(tag=="red"||tag=="blue"||tag=="yellow"||tag=="green"){continue}var text=Tag.mapEn2Cn[tag]||tag;var classes=Tag.classes[tag]||"label label-default";$("#tagNav").append(t('<li><a> <span class="?">?</span></li>',classes,text))}};$(function(){$("#addTagTrigger").click(function(){$(this).hide();$("#addTagInput").show().focus().val("")});$("#addTagInput").click(function(event){showTagList(event)});$("#addTagInput").blur(function(){var val=$(this).val();if(val){Tag.appendTag(val,true)}return;$("#addTagTrigger").show();$("#addTagInput").hide()});$("#addTagInput").keydown(function(e){if(e.keyCode==13){hideTagList();if($("#addTagInput").val()){$(this).trigger("blur");$("#addTagTrigger").trigger("click")}else{$(this).trigger("blur")}}});$("#tagColor li").click(function(event){var a;if($(this).attr("role")){a=$(this).find("span")}else{a=$(this)}Tag.appendTag({classes:a.attr("class"),text:a.text()})});$("#tags").on("click","i",function(){$(this).parent().remove();reRenderTags()});function searchTag(){var tag=$.trim($(this).text());tag=Tag.mapCn2En[tag]||tag;Note.curChangedSaveIt();Note.clearAll();$("#tagSearch").html($(this).html()).show();showLoading();ajaxGet("/note/searchNoteByTags",{tags:[tag]},function(notes){hideLoading();if(notes){Note.renderNotes(notes);if(!isEmpty(notes)){Note.changeNote(notes[0].NoteId)}}})}$("#myTag .folderBody").on("click","li",searchTag);$("#minTagNav").on("click","li",searchTag)});

299
public/js/app/tag.js Normal file
View File

@ -0,0 +1,299 @@
// Tag
// 蓝色, 红色怎么存到数据库中? 直接存蓝色
Tag.classes = {
"蓝色": "label label-blue",
"红色": "label label-red",
"绿色": "label label-green",
"黄色": "label label-yellow",
"blue": "label label-blue",
"red": "label label-red",
"green": "label label-green",
"yellow": "label label-yellow"
}
// 数据库中统一存En
Tag.mapCn2En = {
"蓝色": "blue",
"红色": "red",
"绿色": "green",
"黄色": "yellow",
}
Tag.mapEn2Cn = {
"blue": "蓝色",
"red": "红色",
"green": "绿色",
"yellow": "黄色",
}
Tag.t = $("#tags");
// called by Note
Tag.getTags = function() {
var tags = [];
Tag.t.children().each(function(){
var text = $(this).text();
text = text.substring(0, text.length - 1); // 把X去掉
text = Tag.mapCn2En[text] || text;
tags.push(text);
});
// 需要去重吗? 正常情况下不会重复
return tags;
}
// called by Note
Tag.clearTags = function() {
Tag.t.html("");
}
// 设置tags
// called by Note
Tag.renderTags = function(tags) {
Tag.t.html("");
if(isEmpty(tags)) {
return;
}
// TODO 重构, 这样不高效
for(var i = 0; i < tags.length; ++i) {
var tag = tags[i];
Tag.appendTag(tag);
}
}
// tag最初状态
function revertTagStatus() {
$("#addTagTrigger").show();
$("#addTagInput").hide();
// hideTagList();
}
function hideTagList(event) {
$("#tagDropdown").removeClass("open");
if (event) {
event.stopPropagation()
}
}
function showTagList(event) {
$("#tagDropdown").addClass("open");
if (event) {
event.stopPropagation()
}
}
// 只读模式下显示tags
// called by Note
Tag.renderReadOnlyTags = function(tags) {
// 先清空
$("#noteReadTags").html("");
if(isEmpty(tags)) {
$("#noteReadTags").html("无标签");
}
var i = true;
function getNextDefaultClasses() {
if (i) {
return "label label-default";
i = false
} else {
i = true;
return "label label-info";
}
}
for(var i in tags) {
var text = tags[i];
text = Tag.mapEn2Cn[text] || text;
var classes = Tag.classes[text];
if(!classes) {
classes = getNextDefaultClasses();
}
tag = t('<span class="?">?</span>', classes, text);
$("#noteReadTags").append(tag);
}
}
// 添加tag
// tag = {classes:"label label-red", text:"红色"}
// tag = life
Tag.appendTag = function(tag) {
var isColor = false;
var classes, text;
if (typeof tag == "object") {
classes = tag.classes;
text = tag.text;
if(!text) {
return;
}
} else {
tag = $.trim(tag);
text = tag;
if(!text) {
return;
}
var classes = Tag.classes[text];
if(classes) {
isColor = true;
} else {
classes = "label label-default";
}
}
text = Tag.mapEn2Cn[text] || text;
tag = t('<span class="?">?<i title="删除">X</i></span>', classes, text);
// 避免重复
$("#tags").children().each(function() {
if (isColor) {
var tagHtml = $("<div></div>").append($(this).clone()).html();
if (tagHtml == tag) {
$(this).remove();
}
} else if (text + "X" == $(this).text()) {
$(this).remove();
}
});
$("#tags").append(tag);
hideTagList();
if (!isColor) {
reRenderTags();
}
}
// 为了颜色间隔, add, delete时调用
function reRenderTags() {
var defautClasses = [ "label label-default", "label label-info" ];
var i = 0;
$("#tags").children().each(
function() {
var thisClasses = $(this).attr("class");
if (thisClasses == "label label-default"
|| thisClasses == "label label-info") {
$(this).removeClass(thisClasses).addClass(
defautClasses[i % 2]);
i++;
}
});
}
//-----------
// 左侧nav en -> cn
Tag.renderTagNav = function(tags) {
tags = tags || [];
for(var i in tags) {
var tag = tags[i];
if(tag == "red" || tag == "blue" || tag == "yellow" || tag == "green") {
continue;
}
var text = Tag.mapEn2Cn[tag] || tag;
var classes = Tag.classes[tag] || "label label-default";
$("#tagNav").append(t('<li><a> <span class="?">?</span></li>', classes, text));
}
}
// 事件
$(function() {
// tag
$("#addTagTrigger").click(function() {
$(this).hide();
$("#addTagInput").show().focus().val("");
});
$("#addTagInput").click(function(event) {
showTagList(event);
});
$("#addTagInput").blur(function() {
var val = $(this).val();
if(val) {
Tag.appendTag(val, true);
}
return;
// 下面不能有, 有就有问题
$("#addTagTrigger").show();
$("#addTagInput").hide();
// revertTagStatus();
});
$('#addTagInput').keydown(function(e) {
if (e.keyCode == 13) {
hideTagList();
// 如果有值, 再生成, 没值直接隐藏
if ($("#addTagInput").val()) {
$(this).trigger("blur");
$("#addTagTrigger").trigger("click");
} else {
$(this).trigger("blur");
}
}
});
// 点击下拉时也会触发input的blur事件
$("#tagColor li").click(function(event) {
var a;
if($(this).attr("role")) {
a = $(this).find("span");
} else {
a = $(this);
}
Tag.appendTag({
classes : a.attr("class"),
text : a.text()
});
});
// 这是个问题, 为什么? 捕获不了事件?, input的blur造成
/*
$(".label").click(function(event) {
var a = $(this);
Tag.appendTag({
classes : a.attr("class"),
text : a.text()
});
// event.stopPropagation();
});
*/
$("#tags").on("click", "i", function() {
$(this).parent().remove();
reRenderTags();
});
//-------------
// nav 标签搜索
function searchTag() {
var tag = $.trim($(this).text());
tag = Tag.mapCn2En[tag] || tag;
// 学习changeNotebook
// 1
Note.curChangedSaveIt();
// 2 先清空所有
// 也会把curNoteId清空
Note.clearAll();
$("#tagSearch").html($(this).html()).show();
showLoading();
ajaxGet("/note/searchNoteByTags", {tags: [tag]}, function(notes) {
hideLoading();
if(notes) {
// 和note搜索一样
// 设空, 防止发生上述情况
// Note.curNoteId = "";
Note.renderNotes(notes);
if(!isEmpty(notes)) {
Note.changeNote(notes[0].NoteId);
}
}
});
}
$("#myTag .folderBody").on("click", "li", searchTag);
$("#minTagNav").on("click", "li", searchTag);
});

2
public/js/bootstrap-min.js vendored Normal file

File diff suppressed because one or more lines are too long

2016
public/js/bootstrap.js vendored Normal file

File diff suppressed because it is too large Load Diff

9
public/js/bootstrap.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
= modal =
bootstrap.js modal 缓存修改, 不缓存remote的数据
添加postShow

1
public/js/common-min.js vendored Normal file

File diff suppressed because one or more lines are too long

818
public/js/common.js Normal file
View File

@ -0,0 +1,818 @@
// --------------------- 命名空间
// 最上级变量
var LEA = {};
// 命名空间
var Notebook = {
cache: {}, // notebookId => {Title, Seq}
}
var Note = {
cache: {}, // noteId => {Title, Tags, Content, Desc}
};
// var UserInfo = {}; // 博客有问题, 会覆盖
var Tag = {};
var Notebook = {};
var Share = {};
// markdown
var Converter;
var MarkdownEditor;
var ScrollLink;
//---------------------
// 公用方法
function trimLeft(str, substr) {
if(!substr || substr == " ") {
return $.trim(str);
}
while(str.indexOf(substr) == 0) {
str = str.substring(substr.length);
}
return str;
}
function json(str) {
return eval("(" + str + ")")
}
// '<div id="?" class="?" onclick="?">'
function t() {
var args = arguments;
if(args.length <= 1) {
return args[0];
}
var text = args[0];
if(!text) {
return text;
}
// 先把所有的?替换成, 很有可能替换的值有?会造成循环,没有替换想要的
var pattern = "LEAAEL"
text = text.replace(/\?/g, pattern);
// args[1] 替换第一个?
for(var i = 1; i <= args.length; ++i) {
text = text.replace(pattern, args[i]);
}
return text;
}
// 判断数组是否相等
function arrayEqual(a, b) {
a = a || [];
b = b || [];
return a.join(",") == b.join(",");
}
//是否是数组
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* 是否为空
* 可判断任意类型string array
*/
function isEmpty(obj) {
if(!obj) {
return true;
}
if(isArray(obj)) {
if(obj.length == 0) {
return true;
}
}
return false;
}
//------------
//得到form的数据
//返回json
function getFormJsonData(formId) {
var data = formArrDataToJson($('#' + formId).serializeArray());
return data;
}
//$('#form').serializeArray()的数据[{name: a, value: b}, {name: "c[]", value: d}]
//转成{a:b}
function formArrDataToJson(arrData) {
var datas = {};
var arrObj= {}; // {a:[1, 2], b:[2, 3]};
for(var i in arrData) {
var attr = arrData[i].name;
var value = arrData[i].value;
// 判断是否是a[]形式
if(attr.substring(attr.length-2, attr.length) == '[]') {
attr = attr.substring(0, attr.length-2);
if(arrObj[attr] == undefined) {
arrObj[attr] = [value];
} else {
arrObj[attr].push(value);
}
continue;
}
datas[attr] = value;
}
return $.extend(datas, arrObj);
}
//将serialize的的form值转成json
function formSerializeDataToJson(formSerializeData) {
var arr = formSerializeData.split("&");
var datas = {};
var arrObj= {}; // {a:[1, 2], b:[2, 3]};
for(var i = 0; i < arr.length; ++i) {
var each = arr[i].split("=");
var attr = decodeURI(each[0]);
var value = decodeURI(each[1]);
// 判断是否是a[]形式
if(attr.substring(attr.length-2, attr.length) == '[]') {
attr = attr.substring(0, attr.length-2);
if(arrObj[attr] == undefined) {
arrObj[attr] = [value];
} else {
arrObj[attr].push(value);
}
continue;
}
datas[attr] = value;
}
return $.extend(datas, arrObj);
}
// ajax请求返回结果后的操作
// 用于ajaxGet(), ajaxPost()
function _ajaxCallback(ret, successFunc, failureFunc) {
// 总会执行
if(ret === true || ret == "true" || typeof ret == "object") {
// 是否是NOTELOGIN
if(ret && typeof ret == "object") {
if(ret.Msg == "NOTLOGIN") {
alert("你还没有登录, 请先登录!");
return;
}
}
if(typeof successFunc == "function") {
successFunc(ret);
}
} else {
if(typeof failureFunc == "function") {
failureFunc(ret);
} else {
alert("error!")
}
}
}
function _ajax(type, url, param, successFunc, failureFunc, async) {
log("-------------------ajax:");
log(url);
log(param);
if(typeof async == "undefined") {
async = true;
} else {
async = false;
}
$.ajax({
type: type,
url: url,
data: param,
async: async, // 是否异步
success: function(ret) {
_ajaxCallback(ret, successFunc, failureFunc);
},
error: function(ret) {
_ajaxCallback(ret, successFunc, failureFunc);
}
});
}
/**
* 发送ajax get请求
* @param url
* @param param
* @param successFunc
* @param failureFunc
* @param hasProgress
* @param async 是否异步
* @returns
*/
function ajaxGet(url, param, successFunc, failureFunc, async) {
_ajax("GET", url, param, successFunc, failureFunc, async);
}
/**
* 发送post请求
* @param url
* @param param
* @param successFunc
* @param failureFunc
* @param hasProgress
* @param async 是否异步, 默认为true
* @returns
*/
function ajaxPost(url, param, successFunc, failureFunc, async) {
_ajax("POST", url, param, successFunc, failureFunc, async);
}
function ajaxPostJson(url, param, successFunc, failureFunc, async) {
log("-------------------ajaxPostJson:");
log(url);
log(param);
// 默认是异步的
if(typeof async == "undefined") {
async = true;
} else {
async = false;
}
$.ajax({
url : url,
type : "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
async: async,
data : JSON.stringify(param),
success : function(ret, stats) {
_ajaxCallback(ret, successFunc, failureFunc);
},
error: function(ret) {
_ajaxCallback(ret, successFunc, failureFunc);
}
});
}
function findParents(target, selector) {
if($(target).is(selector)) {
return $(target);
}
var parents = $(target).parents();
for(var i = 0; i < parents.length; ++i) {
log(parents.eq(i))
if(parents.eq(i).is(selector)) {
return parents.seq(i);
}
}
return null;
}
/*
ajaxPostJson(
"http://localhost:9000/notebook/index?i=100&name=life",
{Title: "you can", UserId:"52a9e409f4ea49d6576fdbca", Subs:[{title: "xxxxx", Seq:11}, {title:"life..."}]},
function(e) {
log(e);
});
*/
//-----------------
//切换编辑器
function switchEditor(isMarkdown) {
// 富文本永远是2
if(!isMarkdown) {
$("#editor").show();
$("#mdEditor").css("z-index", 1);
} else {
$("#mdEditor").css("z-index", 3).show();
}
}
// editor 设置内容
// 可能是tinymce还没有渲染成功
var previewToken = "<div style='display: none'>FORTOKEN</div>"
function setEditorContent(content, isMarkdown, preview) {
if(!content) {
content = "";
}
if(!isMarkdown) {
$("#editorContent").html(content);
var editor = tinymce.activeEditor;
if(editor) {
editor.setContent(content);
editor.undoManager.clear(); // 4-7修复BUG
} else {
// 等下再设置
setTimeout(function() {
setEditorContent(content, false);
}, 100);
}
} else {
$("#wmd-input").val(content);
if(!content || preview) { // 没有内容就不要解析了
$("#wmd-preview").html(preview).css("height", "auto");
ScrollLink.onPreviewFinished(); // 告诉scroll preview结束了
} else {
// 还要清空preview
if(MarkdownEditor) {
$("#wmd-preview").html(previewToken + "<div style='text-align:center; padding: 10px 0;'><img src='http://leanote.com/images/loading-24.gif' /> 正在转换...</div>");
MarkdownEditor.refreshPreview();
} else {
// 等下再设置
setTimeout(function() {
setEditorContent(content, true, preview);
}, 200);
}
}
}
}
// preview是否为空
function previewIsEmpty(preview) {
if(!preview || preview.substr(0, previewToken.length) == previewToken) {
return true;
}
return false;
}
// 有tinymce得到的content有<html>包围
function getEditorContent(isMarkdown) {
if(!isMarkdown) {
var editor = tinymce.activeEditor;
if(editor) {
var content = $(editor.getBody());
// 去掉恶心的花瓣注入
// <pinit></pinit>
// 把最后的<script>..</script>全去掉
content.find("pinit").remove();
content.find(".thunderpin").remove();
content.find(".pin").parent().remove();
content = $(content).html();
if(content) {
while(true) {
var lastEndScriptPos = content.lastIndexOf("</script>");
if (lastEndScriptPos == -1) {
return content;
}
var length = content.length;
// 证明</script>在最后, 去除之
if(length - 9 == lastEndScriptPos) {
var lastScriptPos = content.lastIndexOf("<script ");
if(lastScriptPos == -1) {
lastScriptPos = content.lastIndexOf("<script>");
}
if(lastScriptPos != -1) {
content = content.substring(0, lastScriptPos);
} else {
return content;
}
} else {
// 不在最后, 返回
return content;
}
}
}
return content;
}
} else {
return [$("#wmd-input").val(), $("#wmd-preview").html()]
}
}
// 禁用编辑
LEA.editorStatus = true;
function disableEditor() {
var editor = tinymce.activeEditor;
if(editor) {
editor.hide();
LEA.editorStatus = false;
$("#mceTollbarMark").show().css("z-index", 1000);
}
// toolbar 来个遮着...
}
function enableEditor() {
if(LEA.editorStatus) {
return;
}
$("#mceTollbarMark").css("z-index", -1).hide();
var editor = tinymce.activeEditor;
if(editor) {
editor.show();
}
}
//---------------
// notify
$(function() {
if($.pnotify) {
$.pnotify.defaults.delay = 1000;
}
})
function notifyInfo(text) {
$.pnotify({
title: '通知',
text: text,
type: 'info',
styling: 'bootstrap'
});
}
function notifyError(text) {
$.pnotify.defaults.delay = 2000
$.pnotify({
title: '通知',
text: text,
type: 'error',
styling: 'bootstrap'
});
}
//-----------
// dialog
//-----------
function showDialog(id, options) {
$("#leanoteDialog #modalTitle").html(options.title);
$("#leanoteDialog .modal-body").html($("#" + id + " .modal-body").html());
$("#leanoteDialog .modal-footer").html($("#" + id + " .modal-footer").html());
delete options.title;
options.show = true;
$("#leanoteDialog").modal(options);
}
function hideDialog(timeout) {
if(!timeout) {
timeout = 0;
}
setTimeout(function() {
$("#leanoteDialog").modal('hide');
}, timeout);
}
// 更通用
function closeDialog() {
$(".modal").modal('hide');
}
// 原生的
function showDialog2(id, options) {
options = options || {};
options.show = true;
$(id).modal(options);
}
function hideDialog2(id, timeout) {
if(!timeout) {
timeout = 0;
}
setTimeout(function() {
$(id).modal('hide');
}, timeout);
}
// 远程
function showDialogRemote(url, data) {
data = data || {};
url += "?";
for(var i in data) {
url += i + "=" + data[i] + "&";
}
$("#leanoteDialogRemote").modal({remote: url});
}
function hideDialogRemote() {
$("#leanoteDialogRemote").modal('hide');
}
//---------------
// notify
$(function() {
if($.pnotify) {
$.pnotify.defaults.delay = 1000;
}
})
function notifyInfo(text) {
$.pnotify({
title: '通知',
text: text,
type: 'info',
styling: 'bootstrap'
});
}
function notifyError(text) {
$.pnotify.defaults.delay = 2000
$.pnotify({
title: '通知',
text: text,
type: 'error',
styling: 'bootstrap'
});
}
function notifySuccess(text) {
$.pnotify({
title: '通知',
text: text,
type: 'success',
styling: 'bootstrap'
});
}
// 对Date的扩展将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
//年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
//例子:
//(new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
//(new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.format = function(fmt) { //author: meizz
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}
//2014-01-06T18:29:48.802+08:00
function goNowToDatetime(goNow) {
if(!goNow) {
return "";
}
return goNow.substr(0, 10) + " " + goNow.substr(11, 8);
}
function getCurDate() {
return (new Date()).format("yyyy-M-d");
}
// 回车键的动作
function enter(parent, children, func) {
if(!parent) {
parent = "body";
}
$(parent).on("keydown", children, function(e) {
if (e.keyCode == 13) {
func.call(this);
}
});
}
// 回车则blue
function enterBlur(parent, children) {
if(!parent) {
parent = "body";
}
if(!children) {
children = parent;
parent = "body";
}
$(parent).on("keydown", children, function(e) {
if (e.keyCode == 13) {
$(this).trigger("blur");
}
});
}
// 生成mongodb ObjectId
function getObjectId() {
return ObjectId();
}
//-----------------------------------------
function resizeEditor(second) {
var ifrParent = $("#editorContent_ifr").parent();
ifrParent.css("overflow", "auto");
var height = $("#editorContent").height();
ifrParent.height(height);
// log(height + '---------------------------------------')
$("#editorContent_ifr").height(height);
/*
// 第一次时可能会被改变
if(!second) {
setTimeout(function() {
resizeEditorHeight(true);
}, 1000);
}
*/
}
//----------
// msg位置固定
function showMsg(msg, timeout) {
$("#msg").html(msg);
if(timeout) {
setTimeout(function() {
$("#msg").html("");
}, timeout)
}
}
function showMsg2(id, msg, timeout) {
$(id).html(msg);
if(timeout) {
setTimeout(function() {
$(id).html("");
}, timeout)
}
}
//--------------
// type == danger, success, warning
function showAlert(id, msg, type, id2Focus) {
$(id).html(msg).removeClass("alert-danger").removeClass("alert-success").removeClass("alert-warning").addClass("alert-" + type).show();
if(id2Focus) {
$(id2Focus).focus();
}
}
function hideAlert(id, timeout) {
if(timeout) {
setTimeout(function() {
$(id).hide();
}, timeout);
} else {
$(id).hide();
}
}
//-------------------
// for leanote ajax
// post
// return {Ok, Msg, Data}
// btnId 是按钮包括#
function post(url, param, func, btnId) {
var btnPreText;
if(btnId) {
btnPreText = $(btnId).html();
$(btnId).html("正在处理").addClass("disabled");
}
ajaxPost(url, param, function(ret) {
if(btnPreText) {
$(btnId).html(btnPreText).removeClass("disabled");
}
if (typeof ret == "object") {
if(typeof func == "function") {
func(ret);
}
} else {
alert("leanote出现了错误!");
}
});
}
// 是否是正确的email
function isEmail(email) {
var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[0-9a-zA-Z]{2,3}$/;
return myreg.test(email);
}
// 正确返回该email
function isEmailFromInput(inputId, msgId, selfBlankMsg, selfInvalidMsg) {
var val = $(inputId).val();
var msg = function() {};
if(msgId) {
msg = function(msgId, msg) {
showAlert(msgId, msg, "danger", inputId);
}
}
if(!val) {
msg(msgId, selfBlankMsg || "请输入邮箱");
} else if(!isEmail(val)) {
msg(msgId, selfInvalidMsg || "请输入正确的邮箱");
} else {
return val;
}
}
// 复制文本
function initCopy(aId, postFunc) {
// 定义一个新的复制对象
var clip = new ZeroClipboard(document.getElementById(aId), {
moviePath: "/js/ZeroClipboard/ZeroClipboard.swf"
});
// 复制内容到剪贴板成功后的操作
clip.on('complete', function(client, args) {
postFunc(args);
});
}
function showLoading() {
$("#loading").css("visibility", "visible");
}
function hideLoading() {
$("#loading").css("visibility", "hidden");
}
// 注销, 先清空cookie
function logout() {
$.removeCookie("REVEL_SESSION");
location.href = "/logout?id=1";
}
// 得到图片width, height, callback(ret); ret = {width:11, height:33}
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);
}
// 插件中使用
function hiddenIframeBorder() {
$('.mce-window iframe').attr("frameborder", "no").attr("scrolling", "no");
}
var email2LoginAddress = {
'qq.com': 'http://mail.qq.com',
'gmail.com': 'http://mail.google.com',
'sina.com': 'http://mail.sina.com.cn',
'163.com': 'http://mail.163.com',
'126.com': 'http://mail.126.com',
'yeah.net': 'http://www.yeah.net/',
'sohu.com': 'http://mail.sohu.com/',
'tom.com': 'http://mail.tom.com/',
'sogou.com': 'http://mail.sogou.com/',
'139.com': 'http://mail.10086.cn/',
'hotmail.com': 'http://www.hotmail.com',
'live.com': 'http://login.live.com/',
'live.cn': 'http://login.live.cn/',
'live.com.cn': 'http://login.live.com.cn',
'189.com': 'http://webmail16.189.cn/webmail/',
'yahoo.com.cn': 'http://mail.cn.yahoo.com/',
'yahoo.cn': 'http://mail.cn.yahoo.com/',
'eyou.com': 'http://www.eyou.com/',
'21cn.com': 'http://mail.21cn.com/',
'188.com': 'http://www.188.com/',
'foxmail.coom': 'http://www.foxmail.com'
};
function getEmailLoginAddress(email) {
if(!email) {
return;
}
var arr = email.split('@');
if(!arr || arr.length < 2) {
return;
}
var addr = arr[1];
return email2LoginAddress[addr] || "http://mail." + addr;
}
// 返回是否是re.Ok == true
function reIsOk(re) {
return re && typeof re == "object" && re.Ok;
}
// marker
// 下拉扩展工具栏用, 点击文档导航用
LEA.bookmark = null;
function saveBookmark() {
try {
bookmark = tinymce.activeEditor.selection.getBookmark(); // 光标, 为了处理后重新定位到那个位置
} catch(e) {
}
}
function restoreBookmark() {
try {
// 必须要focus()!!!
var editor = tinymce.activeEditor;
editor.focus();
editor.selection.moveToBookmark(LEA.bookmark);
} catch(e) {
}
}
// 是否是手机浏览器
var u = navigator.userAgent;
LEA.isMobile = /Mobile|Android|iPhone/i.test(u);
// LEA.isMobile = u.indexOf('Android')>-1 || u.indexOf('Linux')>-1;
// LEA.isMobile = false;
//if($("body").width() < 600) {
// location.href = "/mobile/index";
//}
// 国际化 i18n
function getMsg(key) {
return MSG[key] || key;
}

View File

@ -0,0 +1,60 @@
.b-m-mpanel {
background: #fff url(images/contextmenu/menu_bg.gif) left repeat-y; /* F0f0f0*/
border: 1px solid #ccc;
position: absolute;
padding: 2px 0;
z-index: 99997;
left:0px;
top:0px;
/*shaddow*/
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
background-clip: padding-box;
}
.b-m-split {
height: 6px;
background: url(images/contextmenu/m_splitLine.gif) center repeat-x;
font-size: 0px;
margin: 0 2px;
}
.b-m-item, .b-m-idisable, .b-m-ifocus
{
padding: 4px 10px 4px 4px;
cursor: default;
line-height:100%;
}
.b-m-idisable
{
color:#808080;
}
.b-m-ibody, .b-m-arrow {
overflow: hidden;
text-overflow: ellipsis;
}
.b-m-arrow {
background: url(images/contextmenu/m_arrow.gif) right no-repeat;
}
.b-m-idisable .b-m-arrow
{
background:none;
}
.b-m-item img, .b-m-ifocus img, .b-m-idisable img {
margin-right: 8px;
width: 16px;
}
.b-m-ifocus {
/*background: url(images/contextmenu/m_item.gif) repeat-x bottom;*/
background-color: #CDE3F6;
}
.b-m-idisable img {
visibility:hidden;
}
.c-text{
display: inline-block;
padding-left:3px;
}
.b-m-icon {
width: 23px;
padding-left: 3px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 B

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,250 @@
LEA.cmroot = 1;
(function($) {
function returnfalse() { return false; };
$.fn.contextmenu = function(option) {
var cmroot = "contextmenu" + LEA.cmroot; //Math.floor((Math.random() + Math.random()) * 10000);
LEA.cmroot++;
option = $.extend({ alias: cmroot, width: 150 }, option);
var ruleName = null, target = null,
groups = {}, mitems = {}, actions = {}, showGroups = [],
itemTpl = '<div class="b-m-$[type]" unselectable="on"><div class="clearfix"><div class="b-m-icon pull-left"><i class="fa $[faIcon]"></i>$[imgIcon]</div><div class="pull-left"><span class="c-text" unselectable="on">$[text]</span></div></div></div>';
itemNoIconTpl = "<div class='b-m-$[type]' unselectable=on><nobr unselectable=on><span align='absmiddle'></span><span class='c-text' unselectable=on>$[text]</span></nobr></div>";
var gTemplet = $("<div/>").addClass("b-m-mpanel").attr("unselectable", "on").css("display", "none");
var iTemplet = $("<div/>").addClass("b-m-item").attr("unselectable", "on");
var sTemplet = $("<div/>").addClass("b-m-split");
//build group item, which has sub items
var buildGroup = function(obj) {
groups[obj.alias] = this;
this.gidx = obj.alias;
this.id = obj.alias;
if (obj.disable) {
this.disable = obj.disable;
this.className = "b-m-idisable";
}
$(this).width(obj.width).click(returnfalse).mousedown(returnfalse).appendTo($("body"));
obj = null;
return this;
};
var buildItem = function(obj) {
var T = this;
T.title = obj.text;
T.idx = obj.alias;
T.gidx = obj.gidx;
T.data = obj;
var imgIcon = "";
if(obj.icon) {
imgIcon = '<img src="' + obj.icon + '"/>';
}
obj.imgIcon = imgIcon;
if(obj.icon) {
T.innerHTML = itemTpl.replace(/\$\[([^\]]+)\]/g, function() {
return obj[arguments[1]];
});
} else {
T.innerHTML = itemTpl.replace(/\$\[([^\]]+)\]/g, function() {
return obj[arguments[1]];
});
}
if (obj.disable) {
T.disable = obj.disable;
T.className = "b-m-idisable";
}
obj.items && (T.group = true);
obj.action && (actions[obj.alias] = obj.action);
mitems[obj.alias] = T;
T = obj = null;
return this;
};
//add new items
var addItems = function(gidx, items, parentAlias) {
var tmp = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type == "splitLine") {
//split line
tmp = sTemplet.clone()[0];
} else {
// life, alias可以不需要, 从text取, 但必须唯一
if(!items[i].alias) {
if(parentAlias) {
items[i].alias = parentAlias + "." + items[i].text; // 移动.Hadoop
} else {
items[i].alias = items[i].text;
}
// log(items[i].alias);
}
items[i].gidx = gidx;
if (items[i].type == "group") {
//group
buildGroup.apply(gTemplet.clone()[0], [items[i]]);
arguments.callee(items[i].alias, items[i].items, items[i].alias); // life 传上级的alias, 避免重复
items[i].type = "arrow";
tmp = buildItem.apply(iTemplet.clone()[0], [items[i]]);
} else {
//normal item
items[i].type = "ibody";
tmp = buildItem.apply(iTemplet.clone()[0], [items[i]]);
//
var thisItem = items[i];
// 用闭包来存储变量
(function(thisItem, tmp) {
$(tmp).click(function(e) {
if (!this.disable) {
// console.log(target);
// 调用...
if ($.isFunction(actions[this.idx])) {
actions[this.idx].call(this, target, thisItem);
}
hideMenuPane();
// life
$(target).removeClass("contextmenu-hover");
}
return false;
});
}(thisItem, tmp));
} //end if
$(tmp).bind("contextmenu", returnfalse).hover(overItem, outItem);
}
groups[gidx].appendChild(tmp);
tmp = items[i] = items[i].items = null;
} //end for
gidx = items = null;
};
var overItem = function(e) {
//menu item is disabled
if (this.disable)
return false;
hideMenuPane.call(groups[this.gidx]);
//has sub items
if (this.group) {
var pos = $(this).offset();
var width = $(this).outerWidth();
showMenuGroup.apply(groups[this.idx], [pos, width]);
}
this.className = "b-m-ifocus";
return false;
};
//menu loses focus
var outItem = function(e) {
//disabled item
if (this.disable )
return false;
if (!this.group) {
//normal item
this.className = "b-m-item";
} //Endif
return false;
};
//show menu group at specified position
var showMenuGroup = function(pos, width) {
var bwidth = $("body").width();
var bheight = document.documentElement.clientHeight;
var mwidth = $(this).outerWidth();
var mheight = $(this).outerHeight();
pos.left = (pos.left + width + mwidth > bwidth) ? (pos.left - mwidth < 0 ? 0 : pos.left - mwidth) : pos.left + width;
pos.top = (pos.top + mheight > bheight) ? (pos.top - mheight + (width > 0 ? 25 : 0) < 0 ? 0 : pos.top - mheight + (width > 0 ? 25 : 0)) : pos.top;
$(this).css(pos).show();
showGroups.push(this.gidx);
};
//to hide menu
var hideMenuPane = function() {
var alias = null;
for (var i = showGroups.length - 1; i >= 0; i--) {
if (showGroups[i] == this.gidx)
break;
alias = showGroups.pop();
groups[alias].style.display = "none";
mitems[alias] && (mitems[alias].className = "b-m-item");
} //Endfor
//CollectGarbage();
};
function applyRule(rule) {
/*
if (ruleName && ruleName == rule.name)
return false;
*/
for (var i in mitems)
disable(i, !rule.disable);
for (var i = 0; i < rule.items.length; i++)
disable(rule.items[i], rule.disable);
ruleName = rule.name;
};
function disable(alias, disabled) {
var item = mitems[alias];
if(!item || !item.lastChild) {
return;
}
item.className = (item.disable = item.lastChild.disabled = disabled) ? "b-m-idisable" : "b-m-item";
};
/* to show menu */
function showMenu(e, menutarget) {
target = menutarget;
showMenuGroup.call(groups[cmroot], { left: e.pageX, top: e.pageY }, 0);
// life
if(!$(target).hasClass("item-active")) {
$(target).addClass("contextmenu-hover");
}
$(document).one('mousedown', function() {
hideMenuPane();
// life
$(target).removeClass("contextmenu-hover");
})
}
// 初始化
var $root = $("#" + option.alias);
var root = null;
if ($root.length == 0) {
root = buildGroup.apply(gTemplet.clone()[0], [option]);
root.applyrule = applyRule;
root.showMenu = showMenu;
addItems(option.alias, option.items);
}
else {
root = $root[0];
}
/*
var me = $(this).each(function() {
return $(this).bind('contextmenu', function(e) {
var bShowContext = (option.onContextMenu && $.isFunction(option.onContextMenu)) ? option.onContextMenu.call(this, e) : true;
if (bShowContext) {
if (option.onShow && $.isFunction(option.onShow)) {
option.onShow.call(this, root);
}
root.showMenu(e, this);
}
return false;
});
});
*/
var me = $(option.parent).on('contextmenu', option.children, function(e) {
var bShowContext = (option.onContextMenu && $.isFunction(option.onContextMenu)) ? option.onContextMenu.call(this, e) : true;
if (bShowContext) {
if (option.onShow && $.isFunction(option.onShow)) {
option.onShow.call(this, root);
}
root.showMenu(e, this);
}
return false;
});
//to apply rule
if (option.rule) {
applyRule(option.rule);
}
gTemplet = iTemplet = sTemplet = itemTpl = buildGroup = buildItem = null;
addItems = overItem = outItem = null;
//CollectGarbage();
return me;
}
})(jQuery);

3074
public/js/ever/common.js Normal file

File diff suppressed because it is too large Load Diff

1
public/js/i18n/msg.en.js Normal file
View File

@ -0,0 +1 @@
var MSG = {"3th":"Third-party accounts","a":"a","aboutLeanote":"About Leanote","accountSetting":"Account","addNotebook":"Add Notebook","all":"Newest","basicInfo":"Basic","blog":"Blog","blogInfo":"You can public your knowledge and Leanote is your blog!","blue":"blue","cancel":"Cancel","checkEmai":"Check email","clickAddTag":"Click to add Tag","close":"Close","confirmPassword":"Please confirm your password","cooperation":"Cooperation","cooperationInfo":"Collaborate with friends to improve your knowledge.","create":"Create","curUser":"Email","default":"Default","defaultShare":"Default sharing","demoRegister":"您现在使用的是体验帐号, \u003ca href=\"/register\"\u003e立即注册?\u003c/a\u003e","editorTips":"Editor Tips","editorTipsInfo":"\u003ch4\u003e1. Short Cuts\u003c/h4\u003ectrl+shift+c Toggle code \u003cbr /\u003e ctrl+shift+i Insert/edit image \u003ch4\u003e2. shift+enter Get out of current block\u003c/h4\u003e eg. \u003cimg src=\"/images/outofcode.png\" style=\"width: 90px\"/\u003e in this situation you can use shift+enter to get out of current code block.","email":"Email","emailOrOthers":"Email or other contact way","findPassword":"Find password","findPasswordSendEmailOver":"We have already send the find password link to your email, please check out your email","findPasswordTimeout":"time out","forgetPassword ":" Forget password?","green":"green","hi":"Hi","history":"Histories","home":"Home","ing":"processing","inputEmail":"Email is required","inputPassword":"Password is required","inputPassword2":"Please input your password again","inputUsername":"Username(email) is required","knowledge":"Knowledge","knowledgeInfo":"Use leanote as a note, manage your knowledge in Leanote.","leanoteBlog":"Blog","leftHidden":"Hidden slide bar","leftShow":"Show slide bar","login":"Login","loginSuccess":"login success","logining":"login","logout":"Logout","moto":"Not just a note!","myBlog":"Blog","myNote":"Enter to my note","myNotebook":"My Notebook","myTag":"My Tag","nav":"Note Nav","newMarkdown":"New Markdown Note","newNote":"New Note","newPassword":"New Password","notGoodPassword":"Tt's not a good password, the length is at least 6","notebook":"Notebook","oldPassword":"Old Password","or":"or","password":"Password","password2":"Confirm your password","passwordTips":"The length is at least 6","reFindPassword":"find password again","red":"red","register":"Register","registerSuccessAndRdirectToNote":"register success, now redirect to my note...","save":"Save","send":"Send","share":"Share","shareInfo":"Share your knowledge to your friends in Leanote.","simple":"Simple","submit":"submit","suggestions":"Suggestions","suggestionsInfo":"help us to improve our service.","tag":"Tag","themeSetting":"Theme","trash":"Trash","try":"Try it","unTitled":"UnTitled","update":"Update","updateEmail":"Update Email","updatePassword":"Update password","updatePasswordSuccessRedirectToLogin":"update password success and redirect to login page...","uploadImage":"Upload Image","usernameOrEmail":"Username or email","usernameSetting":"Update Username","welcomeUseLeanote":"Welcome!","wrongEmail":"Wrong email","wrongPassword":"Wrong password","wrongUsernameOrPassword":"Wrong username or password","yellow":"yellow","yourContact":"Your contact"};

1
public/js/i18n/msg.zh.js Normal file
View File

@ -0,0 +1 @@
var MSG = {"3th":"第三方登录","aboutLeanote":"关于Leanote","accountSetting":"帐户设置","addNotebook":"添加笔记本","all":"最新","basicInfo":"基本信息","blog":"博客","blogInfo":"将笔记公开, 让知识传播的更远!","blue":"蓝色","cancel":"取消","checkEmai":"查收邮箱","clickAddTag":"点击添加标签","close":"关闭","confirmPassword":"两次密码输入不一致","cooperation":"协作","cooperationInfo":"分享给好友的同时也可以让你的好友和你一起来完善它.","create":"创建","curUser":"当前登录帐户","default":"默认","defaultShare":"默认共享","demoRegister":"您现在使用的是体验帐号, \u003ca href=\"/register\"\u003e立即注册?\u003c/a\u003e","editorTips":"帮助","editorTipsInfo":"\u003ch4\u003e1. 快捷键\u003c/h4\u003ectrl+shift+c 代码块切换 \u003cbr /\u003e ctrl+shift+i 插入/修改图片\u003ch4\u003e2. shift+enter 跳出当前区域\u003c/h4\u003e比如在代码块中\u003cimg src=\"/images/outofcode.png\" style=\"width: 90px\"/\u003e按shift+enter可跳出当前代码块.","email":"Email","emailOrOthers":"Email或其它联系方式","findPassword":"找回密码","findPasswordSendEmailOver":"已经将修改密码的链接发送到您的邮箱, 请查收邮件.","findPasswordTimeout":"链接已过期","forgetPassword ":" 忘记密码?","green":"绿色","hi":"Hi","history":"历史记录","home":"主页","ing":"正在处理","inputEmail":"请输入Email","inputPassword":"请输入密码","inputPassword2":"请再次输入密码","inputUsername":"请输入用户名或Email","knowledge":"知识","knowledgeInfo":"leanote是一个笔记, 你可以用它来管理自己的知识.","leanoteBlog":"官方博客","leftHidden":"隐藏左侧","leftShow":"展开左侧","login":"登录","loginSuccess":"登录成功, 正在跳转","logining":"正在登录","logout":"退出","moto":"不一样的笔记!","myBlog":"我的博客","myNote":"进入我的笔记","myNotebook":"我的笔记本","myTag":"我的标签","nav":"文档导航","newMarkdown":"新建Markdown笔记","newNote":"新建笔记","newPassword":"新密码","notGoodPassword":"密码至少6位","notebook":"笔记本","oldPassword":"旧密码","or":"或","password":"密码","password2":"确认密码","passwordTips":"密码至少6位","reFindPassword":"重新找回密码","red":"红色","register":"注册","registerSuccessAndRdirectToNote":"注册成功, 正在转至我的笔记...","save":"保存","send":"发送","share":"分享","shareInfo":"你也可以将知识分享给你的好友.","simple":"简约","submit":"提交","suggestions":"您的建议","suggestionsInfo":"帮助我们完善leanote","tag":"标签","themeSetting":"主题设置","trash":"废纸篓","try":"体验一下","unTitled":"无标题","update":"更新","updateEmail":"修改Email","updatePassword":"修改密码","updatePasswordSuccessRedirectToLogin":"修改成功, 正在跳转到登录页","uploadImage":"上传图片","usernameOrEmail":"用户名或Email","usernameSetting":"用户名设置","welcomeUseLeanote":"欢迎使用Leanote","wrongEmail":"Email格式有误","wrongPassword":"密码有误","wrongUsernameOrPassword":"用户名或密码有误","yellow":"黄色","yourContact":"您的联系方式"};

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,467 @@
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.3.0
*
*/
(function($) {
jQuery.fn.extend({
slimScroll: function(options) {
var defaults = {
// width in pixels of the visible scroll area
width : 'auto',
// height in pixels of the visible scroll area
height : '250px',
// width in pixels of the scrollbar and rail
size : '7px',
// scrollbar color, accepts any hex/color value
color: '#000',
// scrollbar position - left/right
position : 'right',
// distance in pixels between the side edge and the scrollbar
distance : '1px',
// default scroll position on load - top / bottom / $('selector')
start : 'top',
// sets scrollbar opacity
opacity : .4,
// enables always-on mode for the scrollbar
alwaysVisible : false,
// check if we should hide the scrollbar when user is hovering over
disableFadeOut : false,
// sets visibility of the rail
railVisible : false,
// sets rail color
railColor : '#333',
// sets rail opacity
railOpacity : .2,
// whether we should use jQuery UI Draggable to enable bar dragging
railDraggable : true,
// defautlt CSS class of the slimscroll rail
railClass : 'slimScrollRail',
// defautlt CSS class of the slimscroll bar
barClass : 'slimScrollBar',
// defautlt CSS class of the slimscroll wrapper
wrapperClass : 'slimScrollDiv',
// check if mousewheel should scroll the window if we reach top/bottom
allowPageScroll : false,
// scroll amount applied to each mouse wheel step
wheelStep : 20,
// scroll amount applied when user is using gestures
touchScrollStep : 200,
// sets border radius
borderRadius: '7px',
// sets border radius of the rail
railBorderRadius : '7px'
};
var o = $.extend(defaults, options);
// do it for every element that matches selector
this.each(function(){
var isOverPanel, isOverBar, isDragg, queueHide, touchDif,
barHeight, percentScroll, lastScroll,
divS = '<div></div>',
minBarHeight = 30,
releaseScroll = false;
// used in event handlers and for better minification
var me = $(this);
// ensure we are not binding it again
if (me.parent().hasClass(o.wrapperClass))
{
// start from last bar position
var offset = me.scrollTop();
// find bar and rail
bar = me.parent().find('.' + o.barClass);
rail = me.parent().find('.' + o.railClass);
getBarHeight();
// check if we should scroll existing instance
if ($.isPlainObject(options))
{
// Pass height: auto to an existing slimscroll object to force a resize after contents have changed
if ( 'height' in options && options.height == 'auto' ) {
me.parent().css('height', 'auto');
me.css('height', 'auto');
var height = me.parent().parent().height();
me.parent().css('height', height);
me.css('height', height);
}
if ('scrollTo' in options)
{
// jump to a static point
offset = parseInt(o.scrollTo);
}
else if ('scrollBy' in options)
{
// jump by value pixels
offset += parseInt(o.scrollBy);
}
else if ('destroy' in options)
{
// remove slimscroll elements
bar.remove();
rail.remove();
me.unwrap();
return;
}
// scroll content by the given offset
// options.onlyScrollBar 仅仅是移动bar而不移动内容
scrollContent(offset, false, true, options.onlyScrollBar);
}
return;
}
// optionally set height to the parent's height
o.height = (o.height == 'auto') ? me.parent().height() : o.height;
// wrap content
var wrapper = $(divS)
.addClass(o.wrapperClass)
.css({
position: 'relative',
overflow: 'hidden',
width: o.width,
height: o.height
});
// update style for the div
me.css({
overflow: 'hidden',
width: o.width,
height: o.height
});
// create scrollbar rail
var rail = $(divS)
.addClass(o.railClass)
.css({
width: o.size,
height: '100%',
position: 'absolute',
top: 0,
display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none',
'border-radius': o.railBorderRadius,
background: o.railColor,
opacity: o.railOpacity,
zIndex: 90
});
// create scrollbar
var bar = $(divS)
.addClass(o.barClass)
.css({
background: o.color,
width: o.size,
position: 'absolute',
top: 0,
opacity: o.opacity,
display: o.alwaysVisible ? 'block' : 'none',
'border-radius' : o.borderRadius,
BorderRadius: o.borderRadius,
MozBorderRadius: o.borderRadius,
WebkitBorderRadius: o.borderRadius,
zIndex: 99
});
// set position
var posCss = (o.position == 'right') ? { right: o.distance } : { left: o.distance };
rail.css(posCss);
bar.css(posCss);
// wrap it
me.wrap(wrapper);
// append to parent div
me.parent().append(bar);
me.parent().append(rail);
// make it draggable and no longer dependent on the jqueryUI
if (o.railDraggable){
bar.bind("mousedown", function(e) {
var $doc = $(document);
isDragg = true;
t = parseFloat(bar.css('top'));
pageY = e.pageY;
$doc.bind("mousemove.slimscroll", function(e){
currTop = t + e.pageY - pageY;
bar.css('top', currTop);
scrollContent(0, bar.position().top, false);// scroll content
});
$doc.bind("mouseup.slimscroll", function(e) {
isDragg = false;hideBar();
$doc.unbind('.slimscroll');
});
return false;
}).bind("selectstart.slimscroll", function(e){
e.stopPropagation();
e.preventDefault();
return false;
});
}
// on rail over
rail.hover(function(){
showBar();
}, function(){
hideBar();
});
// on bar over
bar.hover(function(){
isOverBar = true;
}, function(){
isOverBar = false;
});
// show on parent mouseover
me.hover(function(){
isOverPanel = true;
showBar();
hideBar();
}, function(){
isOverPanel = false;
hideBar();
});
// support for mobile
me.bind('touchstart', function(e,b){
if (e.originalEvent.touches.length)
{
// record where touch started
touchDif = e.originalEvent.touches[0].pageY;
}
});
me.bind('touchmove', function(e){
// prevent scrolling the page if necessary
if(!releaseScroll)
{
e.originalEvent.preventDefault();
}
if (e.originalEvent.touches.length)
{
// see how far user swiped
var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep;
// scroll content
scrollContent(diff, true);
touchDif = e.originalEvent.touches[0].pageY;
}
});
// set up initial height
getBarHeight();
// check start position
if (o.start === 'bottom')
{
// scroll content to bottom
bar.css({ top: me.outerHeight() - bar.outerHeight() });
scrollContent(0, true);
}
else if (o.start !== 'top')
{
// assume jQuery selector
scrollContent($(o.start).position().top, null, true);
// make sure bar stays hidden
if (!o.alwaysVisible) { bar.hide(); }
}
// attach scroll events
attachWheel();
function _onWheel(e)
{
// use mouse wheel only when mouse is over
if (!isOverPanel) { return; }
var e = e || window.event;
var delta = 0;
if (e.wheelDelta) { delta = -e.wheelDelta/120; }
if (e.detail) { delta = e.detail / 3; }
var target = e.target || e.srcTarget || e.srcElement;
if ($(target).closest('.' + o.wrapperClass).is(me.parent())) {
// scroll content
scrollContent(delta, true);
}
// stop window scroll
if (e.preventDefault && !releaseScroll) { e.preventDefault(); }
if (!releaseScroll) { e.returnValue = false; }
}
function scrollContent(y, isWheel, isJump, onlyScrollBar)
{
releaseScroll = false;
var delta = y;
var maxTop = me.outerHeight() - bar.outerHeight();
if (isWheel)
{
// move bar with mouse wheel
delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight();
// move bar, make sure it doesn't go out
delta = Math.min(Math.max(delta, 0), maxTop);
// if scrolling down, make sure a fractional change to the
// scroll position isn't rounded away when the scrollbar's CSS is set
// this flooring of delta would happened automatically when
// bar.css is set below, but we floor here for clarity
delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta);
// scroll the scrollbar
bar.css({ top: delta + 'px' });
}
// calculate actual scroll amount
percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight());
delta = percentScroll * (me[0].scrollHeight - me.outerHeight());
if (isJump)
{
delta = y;
var offsetTop = delta / me[0].scrollHeight * me.outerHeight();
offsetTop = Math.min(Math.max(offsetTop, 0), maxTop);
bar.css({ top: offsetTop + 'px' });
}
if(!onlyScrollBar) {
// scroll content
me.scrollTop(delta);
}
// fire scrolling event
me.trigger('slimscrolling', ~~delta);
// ensure bar is visible
showBar();
// trigger hide when scroll is stopped
hideBar();
}
function attachWheel()
{
if (window.addEventListener)
{
this.addEventListener('DOMMouseScroll', _onWheel, false );
this.addEventListener('mousewheel', _onWheel, false );
this.addEventListener('MozMousePixelScroll', _onWheel, false );
}
else
{
document.attachEvent("onmousewheel", _onWheel)
}
}
function getBarHeight()
{
// calculate scrollbar height and make sure it is not too small
barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight);
bar.css({ height: barHeight + 'px' });
// hide scrollbar if content is not long enough
var display = barHeight == me.outerHeight() ? 'none' : 'block';
bar.css({ display: display });
}
function showBar()
{
// recalculate bar height
getBarHeight();
clearTimeout(queueHide);
// when bar reached top or bottom
if (percentScroll == ~~percentScroll)
{
//release wheel
releaseScroll = o.allowPageScroll;
// publish approporiate event
if (lastScroll != percentScroll)
{
var msg = (~~percentScroll == 0) ? 'top' : 'bottom';
me.trigger('slimscroll', msg);
}
}
else
{
releaseScroll = false;
}
lastScroll = percentScroll;
// show only when required
if(barHeight >= me.outerHeight()) {
//allow window scroll
releaseScroll = true;
return;
}
bar.stop(true,true).fadeIn('fast');
if (o.railVisible) { rail.stop(true,true).fadeIn('fast'); }
}
function hideBar()
{
// only hide when options allow it
if (!o.alwaysVisible)
{
queueHide = setTimeout(function(){
if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg)
{
bar.fadeOut('slow');
rail.fadeOut('slow');
}
}, 1000);
}
}
});
// maintain chainability
return this;
}
});
jQuery.fn.extend({
slimscroll: jQuery.fn.slimScroll
});
})(jQuery);

View File

@ -0,0 +1,16 @@
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.3.0
*
*/
(function(f){jQuery.fn.extend({slimScroll:function(h){var a=f.extend({width:"auto",height:"250px",size:"7px",color:"#000",position:"right",distance:"1px",start:"top",opacity:0.4,alwaysVisible:!1,disableFadeOut:!1,railVisible:!1,railColor:"#333",railOpacity:0.2,railDraggable:!0,railClass:"slimScrollRail",barClass:"slimScrollBar",wrapperClass:"slimScrollDiv",allowPageScroll:!1,wheelStep:20,touchScrollStep:200,borderRadius:"7px",railBorderRadius:"7px"},h);this.each(function(){function r(d){if(s){d=d||
window.event;var c=0;d.wheelDelta&&(c=-d.wheelDelta/120);d.detail&&(c=d.detail/3);f(d.target||d.srcTarget||d.srcElement).closest("."+a.wrapperClass).is(b.parent())&&m(c,!0);d.preventDefault&&!k&&d.preventDefault();k||(d.returnValue=!1)}}function m(d,f,h){k=!1;var e=d,g=b.outerHeight()-c.outerHeight();f&&(e=parseInt(c.css("top"))+d*parseInt(a.wheelStep)/100*c.outerHeight(),e=Math.min(Math.max(e,0),g),e=0<d?Math.ceil(e):Math.floor(e),c.css({top:e+"px"}));l=parseInt(c.css("top"))/(b.outerHeight()-c.outerHeight());
e=l*(b[0].scrollHeight-b.outerHeight());h&&(e=d,d=e/b[0].scrollHeight*b.outerHeight(),d=Math.min(Math.max(d,0),g),c.css({top:d+"px"}));b.scrollTop(e);b.trigger("slimscrolling",~~e);v();p()}function C(){window.addEventListener?(this.addEventListener("DOMMouseScroll",r,!1),this.addEventListener("mousewheel",r,!1),this.addEventListener("MozMousePixelScroll",r,!1)):document.attachEvent("onmousewheel",r)}function w(){u=Math.max(b.outerHeight()/b[0].scrollHeight*b.outerHeight(),D);c.css({height:u+"px"});
var a=u==b.outerHeight()?"none":"block";c.css({display:a})}function v(){w();clearTimeout(A);l==~~l?(k=a.allowPageScroll,B!=l&&b.trigger("slimscroll",0==~~l?"top":"bottom")):k=!1;B=l;u>=b.outerHeight()?k=!0:(c.stop(!0,!0).fadeIn("fast"),a.railVisible&&g.stop(!0,!0).fadeIn("fast"))}function p(){a.alwaysVisible||(A=setTimeout(function(){a.disableFadeOut&&s||(x||y)||(c.fadeOut("slow"),g.fadeOut("slow"))},1E3))}var s,x,y,A,z,u,l,B,D=30,k=!1,b=f(this);if(b.parent().hasClass(a.wrapperClass)){var n=b.scrollTop(),
c=b.parent().find("."+a.barClass),g=b.parent().find("."+a.railClass);w();if(f.isPlainObject(h)){if("height"in h&&"auto"==h.height){b.parent().css("height","auto");b.css("height","auto");var q=b.parent().parent().height();b.parent().css("height",q);b.css("height",q)}if("scrollTo"in h)n=parseInt(a.scrollTo);else if("scrollBy"in h)n+=parseInt(a.scrollBy);else if("destroy"in h){c.remove();g.remove();b.unwrap();return}m(n,!1,!0)}}else{a.height="auto"==a.height?b.parent().height():a.height;n=f("<div></div>").addClass(a.wrapperClass).css({position:"relative",
overflow:"hidden",width:a.width,height:a.height});b.css({overflow:"hidden",width:a.width,height:a.height});var g=f("<div></div>").addClass(a.railClass).css({width:a.size,height:"100%",position:"absolute",top:0,display:a.alwaysVisible&&a.railVisible?"block":"none","border-radius":a.railBorderRadius,background:a.railColor,opacity:a.railOpacity,zIndex:90}),c=f("<div></div>").addClass(a.barClass).css({background:a.color,width:a.size,position:"absolute",top:0,opacity:a.opacity,display:a.alwaysVisible?
"block":"none","border-radius":a.borderRadius,BorderRadius:a.borderRadius,MozBorderRadius:a.borderRadius,WebkitBorderRadius:a.borderRadius,zIndex:99}),q="right"==a.position?{right:a.distance}:{left:a.distance};g.css(q);c.css(q);b.wrap(n);b.parent().append(c);b.parent().append(g);a.railDraggable&&c.bind("mousedown",function(a){var b=f(document);y=!0;t=parseFloat(c.css("top"));pageY=a.pageY;b.bind("mousemove.slimscroll",function(a){currTop=t+a.pageY-pageY;c.css("top",currTop);m(0,c.position().top,!1)});
b.bind("mouseup.slimscroll",function(a){y=!1;p();b.unbind(".slimscroll")});return!1}).bind("selectstart.slimscroll",function(a){a.stopPropagation();a.preventDefault();return!1});g.hover(function(){v()},function(){p()});c.hover(function(){x=!0},function(){x=!1});b.hover(function(){s=!0;v();p()},function(){s=!1;p()});b.bind("touchstart",function(a,b){a.originalEvent.touches.length&&(z=a.originalEvent.touches[0].pageY)});b.bind("touchmove",function(b){k||b.originalEvent.preventDefault();b.originalEvent.touches.length&&
(m((z-b.originalEvent.touches[0].pageY)/a.touchScrollStep,!0),z=b.originalEvent.touches[0].pageY)});w();"bottom"===a.start?(c.css({top:b.outerHeight()-c.outerHeight()}),m(0,!0)):"top"!==a.start&&(m(f(a.start).position().top,null,!0),a.alwaysVisible||c.hide());C()}});return this}});jQuery.fn.extend({slimscroll:jQuery.fn.slimScroll})})(jQuery);

View File

@ -0,0 +1,2 @@
添加属性 onlyScrollBar 仅仅是移动bar而不移动内容, 用于markdow编辑器
line 141, 330, 366

3
public/js/jquery-1.9.0.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
public/js/jquery-cookie-min.js vendored Normal file
View File

@ -0,0 +1 @@
(function(factory){if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else{factory(jQuery)}})(function($){var pluses=/\+/g;function encode(s){return config.raw?s:encodeURIComponent(s)}function decode(s){return config.raw?s:decodeURIComponent(s)}function stringifyCookieValue(value){return encode(config.json?JSON.stringify(value):String(value))}function parseCookieValue(s){if(s.indexOf('"')===0){s=s.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\")}try{s=decodeURIComponent(s.replace(pluses," "));return config.json?JSON.parse(s):s}catch(e){}}function read(s,converter){var value=config.raw?s:parseCookieValue(s);return $.isFunction(converter)?converter(value):value}var config=$.cookie=function(key,value,options){if(value!==undefined&&!$.isFunction(value)){options=$.extend({},config.defaults,options);if(typeof options.expires==="number"){var days=options.expires,t=options.expires=new Date;t.setTime(+t+days*864e5)}return document.cookie=[encode(key),"=",stringifyCookieValue(value),options.expires?"; expires="+options.expires.toUTCString():"",options.path?"; path="+options.path:"",options.domain?"; domain="+options.domain:"",options.secure?"; secure":""].join("")}var result=key?undefined:{};var cookies=document.cookie?document.cookie.split("; "):[];for(var i=0,l=cookies.length;i<l;i++){var parts=cookies[i].split("=");var name=decode(parts.shift());var cookie=parts.join("=");if(key&&key===name){result=read(cookie,value);break}if(!key&&(cookie=read(cookie))!==undefined){result[name]=cookie}}return result};config.defaults={};$.removeCookie=function(key,options){if($.cookie(key)===undefined){return false}$.cookie(key,"",$.extend({},options,{expires:-1}));return!$.cookie(key)}});

114
public/js/jquery-cookie.js vendored Normal file
View File

@ -0,0 +1,114 @@
/*!
* jQuery Cookie Plugin v1.4.0
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setTime(+t + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
}));

1
public/js/object_id-min.js vendored Normal file
View File

@ -0,0 +1 @@
var ObjectId=function(){var increment=0;var pid=Math.floor(Math.random()*32767);var machine=Math.floor(Math.random()*16777216);if(typeof localStorage!="undefined"){var mongoMachineId=parseInt(localStorage["mongoMachineId"]);if(mongoMachineId>=0&&mongoMachineId<=16777215){machine=Math.floor(localStorage["mongoMachineId"])}localStorage["mongoMachineId"]=machine;document.cookie="mongoMachineId="+machine+";expires=Tue, 19 Jan 2038 05:00:00 GMT"}else{var cookieList=document.cookie.split("; ");for(var i in cookieList){var cookie=cookieList[i].split("=");if(cookie[0]=="mongoMachineId"&&cookie[1]>=0&&cookie[1]<=16777215){machine=cookie[1];break}}document.cookie="mongoMachineId="+machine+";expires=Tue, 19 Jan 2038 05:00:00 GMT"}function ObjId(){if(!(this instanceof ObjectId)){return new ObjectId(arguments[0],arguments[1],arguments[2],arguments[3]).toString()}if(typeof arguments[0]=="object"){this.timestamp=arguments[0].timestamp;this.machine=arguments[0].machine;this.pid=arguments[0].pid;this.increment=arguments[0].increment}else if(typeof arguments[0]=="string"&&arguments[0].length==24){this.timestamp=Number("0x"+arguments[0].substr(0,8)),this.machine=Number("0x"+arguments[0].substr(8,6)),this.pid=Number("0x"+arguments[0].substr(14,4)),this.increment=Number("0x"+arguments[0].substr(18,6))}else if(arguments.length==4&&arguments[0]!=null){this.timestamp=arguments[0];this.machine=arguments[1];this.pid=arguments[2];this.increment=arguments[3]}else{this.timestamp=Math.floor((new Date).valueOf()/1e3);this.machine=machine;this.pid=pid;this.increment=increment++;if(increment>16777215){increment=0}}}return ObjId}();ObjectId.prototype.getDate=function(){return new Date(this.timestamp*1e3)};ObjectId.prototype.toArray=function(){var strOid=this.toString();var array=[];var i;for(i=0;i<12;i++){array[i]=parseInt(strOid.slice(i*2,i*2+2),16)}return array};ObjectId.prototype.toString=function(){var timestamp=this.timestamp.toString(16);var machine=this.machine.toString(16);var pid=this.pid.toString(16);var increment=this.increment.toString(16);return"00000000".substr(0,8-timestamp.length)+timestamp+"000000".substr(0,6-machine.length)+machine+"0000".substr(0,4-pid.length)+pid+"000000".substr(0,6-increment.length)+increment};

105
public/js/object_id.js Normal file
View File

@ -0,0 +1,105 @@
/*
*
* Copyright (c) 2011 Justin Dearing (zippy1981@gmail.com)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) version 2 licenses.
* This software is not distributed under version 3 or later of the GPL.
*
* Version 1.0.1-dev
*
*/
/**
* Javascript class that mimics how WCF serializes a object of type MongoDB.Bson.ObjectId
* and converts between that format and the standard 24 character representation.
*/
var ObjectId = (function () {
var increment = 0;
var pid = Math.floor(Math.random() * (32767));
var machine = Math.floor(Math.random() * (16777216));
if (typeof (localStorage) != 'undefined') {
var mongoMachineId = parseInt(localStorage['mongoMachineId']);
if (mongoMachineId >= 0 && mongoMachineId <= 16777215) {
machine = Math.floor(localStorage['mongoMachineId']);
}
// Just always stick the value in.
localStorage['mongoMachineId'] = machine;
document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT'
}
else {
var cookieList = document.cookie.split('; ');
for (var i in cookieList) {
var cookie = cookieList[i].split('=');
if (cookie[0] == 'mongoMachineId' && cookie[1] >= 0 && cookie[1] <= 16777215) {
machine = cookie[1];
break;
}
}
document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT';
}
function ObjId() {
if (!(this instanceof ObjectId)) {
return new ObjectId(arguments[0], arguments[1], arguments[2], arguments[3]).toString();
}
if (typeof (arguments[0]) == 'object') {
this.timestamp = arguments[0].timestamp;
this.machine = arguments[0].machine;
this.pid = arguments[0].pid;
this.increment = arguments[0].increment;
}
else if (typeof (arguments[0]) == 'string' && arguments[0].length == 24) {
this.timestamp = Number('0x' + arguments[0].substr(0, 8)),
this.machine = Number('0x' + arguments[0].substr(8, 6)),
this.pid = Number('0x' + arguments[0].substr(14, 4)),
this.increment = Number('0x' + arguments[0].substr(18, 6))
}
else if (arguments.length == 4 && arguments[0] != null) {
this.timestamp = arguments[0];
this.machine = arguments[1];
this.pid = arguments[2];
this.increment = arguments[3];
}
else {
this.timestamp = Math.floor(new Date().valueOf() / 1000);
this.machine = machine;
this.pid = pid;
this.increment = increment++;
if (increment > 0xffffff) {
increment = 0;
}
}
};
return ObjId;
})();
ObjectId.prototype.getDate = function () {
return new Date(this.timestamp * 1000);
};
ObjectId.prototype.toArray = function () {
var strOid = this.toString();
var array = [];
var i;
for(i = 0; i < 12; i++) {
array[i] = parseInt(strOid.slice(i*2, i*2+2), 16);
}
return array;
};
/**
* Turns a WCF representation of a BSON ObjectId into a 24 character string representation.
*/
ObjectId.prototype.toString = function () {
var timestamp = this.timestamp.toString(16);
var machine = this.machine.toString(16);
var pid = this.pid.toString(16);
var increment = this.increment.toString(16);
return '00000000'.substr(0, 8 - timestamp.length) + timestamp +
'000000'.substr(0, 6 - machine.length) + machine +
'0000'.substr(0, 4 - pid.length) + pid +
'000000'.substr(0, 6 - increment.length) + increment;
};