Skip to content

TagSpaces is an offline, open source, document manager with tagging support

Cleaning up js libraries

Iliandd74c71cdaed
diff --git a/.gitignore b/.gitignore
index 91b9f22c3..a44e696ef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,6 @@ data/node-webkit/libffmpegsumo_chrome.so
data/node-webkit/libffmpegsumo.so
data/node-webkit/nw
data/node-webkit/nw.pak
+data/node-webkit/RCEDIT.exe
+data/node-webkit/RCEDIT64.exe
+data/devlibs
diff --git a/build.number b/build.number
index 11f5e54f4..2e9594854 100644
--- a/build.number
+++ b/build.number
@@ -1,4 +1,4 @@
#Build Number for ANT. Do not edit!
-#Fri Jan 17 10:45:57 CET 2014
-build.number=1846
+#Fri Jan 17 11:16:43 CET 2014
+build.number=1852
3=
diff --git a/build.xml b/build.xml
index e43075aa2..bbcfba547 100644
--- a/build.xml
+++ b/build.xml
@@ -88,24 +88,19 @@ found in the LICENSE file.
<fileset dir="data/templates" includes="**/*" />
</copy>
<copy todir="${buildFirefoxExt.dir}/data/js">
- <fileset dir="data/js" includes="**/*">
- <exclude name="ioapi.cordova.js" />
- <exclude name="ioapi.chrome.js" />
- <exclude name="ioapi.node.js" />
- <exclude name="${defaultSettings.file}" />
- </fileset>
+ <fileset dir="data/js" includes="**/*"></fileset>
</copy>
<copy todir="${buildFirefoxExt.dir}/data/assets">
<fileset dir="data/assets" includes="**/*" />
</copy>
- <copy file="default.settings.tmpl.js" tofile="${buildFirefoxExt.dir}/data/js/${defaultSettings.file}" />
+ <!--copy file="default.settings.tmpl.js" tofile="${buildFirefoxExt.dir}/data/js/${defaultSettings.file}" />
<replace file="${buildFirefoxExt.dir}/data/js/${defaultSettings.file}">
<replacefilter token="@VERSION@" value="${version}" />
<replacefilter token="@APPNAME@" value="${appname}" />
<replacefilter token="@BUILD@" value="${build.number}" />
<replacefilter token="@DEFAULTLOCATIONS@" value="" />
<replacefilter token="@PDFVIEWER@" value="viewerBrowser" />
- </replace>
+ </replace-->
<replace file="${buildFirefoxExt.dir}/data/about.html">
<replacefilter token="@@VERSION" value="${version}" />
<replacefilter token="@@APPNAME" value="${appname}" />
@@ -154,24 +149,19 @@ found in the LICENSE file.
<fileset dir="data/templates" includes="**/*" />
</copy>
<copy todir="${buildChrome.dir}/js">
- <fileset dir="data/js" includes="**/*">
- <exclude name="ioapi.cordova.js" />
- <exclude name="ioapi.mozilla.js" />
- <exclude name="ioapi.node.js" />
- <exclude name="${defaultSettings.file}" />
- </fileset>
+ <fileset dir="data/js" includes="**/*"></fileset>
</copy>
<copy todir="${buildChrome.dir}/assets">
<fileset dir="data/assets" includes="**/*" />
</copy>
- <copy file="default.settings.tmpl.js" tofile="${buildChrome.dir}/js/${defaultSettings.file}" />
+ <!--copy file="default.settings.tmpl.js" tofile="${buildChrome.dir}/js/${defaultSettings.file}" />
<replace file="${buildChrome.dir}/js/${defaultSettings.file}">
<replacefilter token="@@VERSION" value="${version}" />
<replacefilter token="@@APPNAME" value="${appname}" />
<replacefilter token="@@BUILD" value="${build.number}" />
<replacefilter token="@@DEFAULTLOCATIONS" value="" />
<replacefilter token="@@PDFVIEWER" value="viewerBrowser" />
- </replace>
+ </replace-->
<replace file="${buildChrome.dir}/about.html">
<replacefilter token="@@VERSION" value="${version}" />
<replacefilter token="@@APPNAME" value="${appname}" />
@@ -184,7 +174,7 @@ found in the LICENSE file.
<delete dir="${cordovaDev.dir}" />
<mkdir dir="${cordovaDev.dir}" />
<copy file="LICENSE" tofile="${cordovaDev.dir}/LICENSE.txt" />
- <copy file="config.xml" tofile="${cordovaDev.dir}/config.xml" />
+ <copy file="data/cordova/config.xml" tofile="${cordovaDev.dir}/config.xml" />
<replace file="${cordovaDev.dir}/config.xml">
<replacefilter token="@@VERSION" value="${version}" />
<replacefilter token="@@APPNAME" value="${appname}" />
@@ -197,6 +187,9 @@ found in the LICENSE file.
<copy todir="${cordovaDev.dir}/libs">
<fileset dir="data/libs" includes="**/*" />
</copy>
+ <copy todir="${cordovaDev.dir}/cordova">
+ <fileset dir="data/cordova" includes="**/*.js" />
+ </copy>
<copy todir="${cordovaDev.dir}/ext">
<fileset dir="data/ext">
<include name="perspectiveList/**/*" />
@@ -216,12 +209,7 @@ found in the LICENSE file.
<fileset dir="data/templates" includes="**/*" />
</copy>
<copy todir="${cordovaDev.dir}/js">
- <fileset dir="data/js" includes="**/*">
- <exclude name="ioapi.node.js" />
- <exclude name="ioapi.mozilla.js" />
- <exclude name="ioapi.chrome.js" />
- <exclude name="${defaultSettings.file}" />
- </fileset>
+ <fileset dir="data/js" includes="**/*"></fileset>
</copy>
<copy todir="${cordovaDev.dir}/assets">
<fileset dir="data/assets" includes="**/*" />
diff --git a/data/assets/tagspaces.css b/data/assets/tagspaces.css
index 55b307408..3c559bd54 100644
--- a/data/assets/tagspaces.css
+++ b/data/assets/tagspaces.css
@@ -483,15 +483,6 @@ li hr {
}
-/* JSON Editor */
-div.jsoneditor-menu {
- background-color: #C4E1A4;
-}
-
-div.jsoneditor-frame {
- border-color: green;
-}
-
table.dataTable tr.even {
background-color: white;
}
diff --git a/data/cordova/ioapi.cordova.js b/data/cordova/cordova.api.js
similarity index 100%
rename from data/cordova/ioapi.cordova.js
rename to data/cordova/cordova.api.js
diff --git a/data/ext/editorHTML/extension.js b/data/ext/editorHTML/extension.js
index 8eb898bd2..632ae5e61 100644
--- a/data/ext/editorHTML/extension.js
+++ b/data/ext/editorHTML/extension.js
@@ -14,22 +14,24 @@ define(function(require, exports, module) {
var TSCORE = require("tscore");
var htmlEditor = undefined;
- var extensionDirectory = TSCORE.Config.getExtensionPath()+"/"+exports.id;
+ var extensionsPath = TSCORE.Config.getExtensionPath();
+
+ var extensionDirectory = extensionsPath+"/"+exports.id;
exports.init = function(filePath, containerElementID) {
console.log("Initalization HTML Text Editor...");
require([
+ extensionsPath+'/editorText/codemirror/codemirror.js',
extensionDirectory+'/summernote/summernote.min.js',
- TSCORE.Config.getExtensionPath()+'/editorText/codemirror/codemirror.js',
//"css!"+extensionDirectory+'/summernote/summernote-bs3.css',
"css!"+extensionDirectory+'/summernote/summernote.css',
- 'css!'+TSCORE.Config.getExtensionPath()+'/editorText/codemirror/codemirror.css',
- 'css!'+TSCORE.Config.getExtensionPath()+'/editorText/codemirror/theme/monokai.css',
+ 'css!'+extensionsPath+'/editorText/codemirror/codemirror.css',
+ 'css!'+extensionsPath+'/editorText/codemirror/theme/monokai.css',
'css!'+extensionDirectory+'/extension.css',
], function() {
require([
- TSCORE.Config.getExtensionPath()+'/editorText/codemirror/mode/xml/xml.js',
+ extensionsPath+'/editorText/codemirror/mode/xml/xml.js',
]);
$("#"+containerElementID).append('<div id="htmlEditor"></div>');
TSCORE.IO.loadTextFile(filePath);
diff --git a/data/ext/editorHTML/summernote/summernote.js b/data/ext/editorHTML/summernote/summernote.js
deleted file mode 100644
index 78d179ba9..000000000
--- a/data/ext/editorHTML/summernote/summernote.js
+++ /dev/null
@@ -1,2368 +0,0 @@
-/**
- * summernote.js
- * (c) 2013~ Alan Hong
- * summernote may be freely distributed under the MIT license./
- */
-(function ($, CodeMirror) {
- 'use strict';
- /**
- * object which check platform/agent
- */
- var agent = {
- bMac: navigator.appVersion.indexOf('Mac') > -1,
- bMSIE: navigator.userAgent.indexOf('MSIE') > -1,
- bFF: navigator.userAgent.indexOf('Firefox') > -1,
- bCodeMirror: !!CodeMirror
- };
-
- /**
- * func utils (for high-order func's arg)
- */
- var func = (function () {
- var eq = function (elA) { return function (elB) { return elA === elB; }; };
- var eq2 = function (elA, elB) { return elA === elB; };
- var fail = function () { return false; };
- var not = function (f) { return function () { return !f.apply(f, arguments); }; };
- var self = function (a) { return a; };
- return { eq: eq, eq2: eq2, fail: fail, not: not, self: self };
- })();
-
- /**
- * list utils
- */
- var list = (function () {
- var head = function (array) { return array[0]; };
- var last = function (array) { return array[array.length - 1]; };
- var initial = function (array) { return array.slice(0, array.length - 1); };
- var tail = function (array) { return array.slice(1); };
-
- /**
- * get sum from a list
- * @param {array} array - array
- * @param {function} fn - iterator
- */
- var sum = function (array, fn) {
- fn = fn || func.self;
- return array.reduce(function (memo, v) {
- return memo + fn(v);
- }, 0);
- };
-
- /**
- * returns a copy of the collection with array type.
- * @param {collection} collection - collection eg) node.childNodes, ...
- */
- var from = function (collection) {
- var result = [], idx = -1, length = collection.length;
- while (++idx < length) {
- result[idx] = collection[idx];
- }
- return result;
- };
-
- /**
- * cluster item by second function
- * @param {array} array - array
- * @param {function} fn - predicate function for cluster rule
- */
- var clusterBy = function (array, fn) {
- if (array.length === 0) { return []; }
- var aTail = tail(array);
- return aTail.reduce(function (memo, v) {
- var aLast = last(memo);
- if (fn(last(aLast), v)) {
- aLast[aLast.length] = v;
- } else {
- memo[memo.length] = [v];
- }
- return memo;
- }, [[head(array)]]);
- };
-
- /**
- * returns a copy of the array with all falsy values removed
- * @param {array} array - array
- * @param {function} fn - predicate function for cluster rule
- */
- var compact = function (array) {
- var aResult = [];
- for (var idx = 0, sz = array.length; idx < sz; idx ++) {
- if (array[idx]) { aResult.push(array[idx]); }
- }
- return aResult;
- };
-
- return { head: head, last: last, initial: initial, tail: tail,
- sum: sum, from: from, compact: compact, clusterBy: clusterBy };
- })();
-
- /**
- * aysnc functions which returns deferred object
- */
- var async = (function () {
- /**
- * readFile
- * @param {file} file - file object
- */
- var readFile = function (file) {
- return $.Deferred(function (deferred) {
- var reader = new FileReader();
- reader.onload = function (e) { deferred.resolve(e.target.result); };
- reader.onerror = function () { deferred.reject(this); };
- reader.readAsDataURL(file);
- }).promise();
- };
-
- /**
- * loadImage from url string
- * @param {string} sUrl
- */
- var loadImage = function (sUrl) {
- return $.Deferred(function (deferred) {
-   var image = new Image();
-   image.onload = loaded;
-   image.onerror = errored; // URL returns 404, etc
-   image.onabort = errored; // IE may call this if user clicks "Stop"
-   image.src = sUrl;
-    
-   function loaded() {
-     unbindEvents();
- deferred.resolve(image);
-   }
-   function errored() {
-     unbindEvents();
- deferred.reject(image);
-   }
-   function unbindEvents() {
-     image.onload = null;
-     image.onerror = null;
-     image.onabort = null;
-   }
- }).promise();
- };
-
- return { readFile: readFile, loadImage: loadImage };
- })();
-
- /**
- * dom utils
- */
- var dom = (function () {
- /**
- * returns predicate which judge whether nodeName is same
- */
- var makePredByNodeName = function (sNodeName) {
- // nodeName of element is always uppercase.
- return function (node) {
- return node && node.nodeName === sNodeName;
- };
- };
-
- var isPara = function (node) {
- // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph
- return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName);
- };
-
- var emptyPara = '<p><br/></p>';
-
- var isList = function (node) {
- return node && /^UL|^OL/.test(node.nodeName);
- };
-
- var isEditable = function (node) {
- return node && $(node).hasClass('note-editable');
- };
-
- var isControlSizing = function (node) {
- return node && $(node).hasClass('note-control-sizing');
- };
-
- /**
- * find nearest ancestor predicate hit
- * @param {element} node
- * @param {function} pred - predicate function
- */
- var ancestor = function (node, pred) {
- while (node) {
- if (pred(node)) { return node; }
- node = node.parentNode;
- }
- return null;
- };
-
- /**
- * returns new array of ancestor nodes (until predicate hit).
- * @param {element} node
- * @param {function} [optional] pred - predicate function
- */
- var listAncestor = function (node, pred) {
- pred = pred || func.fail;
-
- var aAncestor = [];
- ancestor(node, function (el) {
- aAncestor.push(el);
- return pred(el);
- });
- return aAncestor;
- };
-
- /**
- * returns common ancestor node between two nodes.
- * @param {element} nodeA
- * @param {element} nodeB
- */
- var commonAncestor = function (nodeA, nodeB) {
- var aAncestor = listAncestor(nodeA);
- for (var n = nodeB; n; n = n.parentNode) {
- if ($.inArray(n, aAncestor) > -1) { return n; }
- }
- return null; // difference document area
- };
-
- /**
- * listing all Nodes between two nodes.
- * FIXME: nodeA and nodeB must be sorted, use comparePoints later.
- * @param {element} nodeA
- * @param {element} nodeB
- */
- var listBetween = function (nodeA, nodeB) {
- var aNode = [];
-
- var bStart = false, bEnd = false;
- var fnWalk = function (node) {
- if (!node) { return; } // traverse fisnish
- if (node === nodeA) { bStart = true; } // start point
- if (bStart && !bEnd) { aNode.push(node); } // between
- if (node === nodeB) { bEnd = true; return; } // end point
-
- for (var idx = 0, sz = node.childNodes.length; idx < sz; idx++) {
- fnWalk(node.childNodes[idx]);
- }
- };
-
- fnWalk(commonAncestor(nodeA, nodeB)); // DFS with commonAcestor.
- return aNode;
- };
-
- /**
- * listing all prevSiblings (until predicate hit).
- * @param {element} node
- * @param {function} [optional] pred - predicate function
- */
- var listPrev = function (node, pred) {
- pred = pred || func.fail;
-
- var aNext = [];
- while (node) {
- aNext.push(node);
- if (pred(node)) { break; }
- node = node.previousSibling;
- }
- return aNext;
- };
-
- /**
- * listing nextSiblings (until predicate hit).
- * @param {element} node
- * @param {function} pred [optional] - predicate function
- */
- var listNext = function (node, pred) {
- pred = pred || func.fail;
-
- var aNext = [];
- while (node) {
- aNext.push(node);
- if (pred(node)) { break; }
- node = node.nextSibling;
- }
- return aNext;
- };
-
- /**
- * insert node after preceding
- * @param {element} node
- * @param {element} preceding - predicate function
- */
- var insertAfter = function (node, preceding) {
- var next = preceding.nextSibling, parent = preceding.parentNode;
- if (next) {
- parent.insertBefore(node, next);
- } else {
- parent.appendChild(node);
- }
- return node;
- };
-
- /**
- * append children
- * @param {element} node
- * @param {collection} aChild
- */
- var appends = function (node, aChild) {
- $.each(aChild, function (idx, child) {
- node.appendChild(child);
- });
- return node;
- };
-
- var isText = makePredByNodeName('#text');
-
- /**
- * returns #text's text size or element's childNodes size
- * @param {element} node
- */
- var length = function (node) {
- if (isText(node)) { return node.nodeValue.length; }
- return node.childNodes.length;
- };
-
- /**
- * returns offset from parent.
- * @param {element} node
- */
- var position = function (node) {
- var offset = 0;
- while (node = node.previousSibling) { offset += 1; }
- return offset;
- };
-
- /**
- * return offsetPath(array of offset) from ancestor
- * @param {element} ancestor - ancestor node
- * @param {element} node
- */
- var makeOffsetPath = function (ancestor, node) {
- var aAncestor = list.initial(listAncestor(node, func.eq(ancestor)));
- return $.map(aAncestor, position).reverse();
- };
-
- /**
- * return element from offsetPath(array of offset)
- * @param {element} ancestor - ancestor node
- * @param {array} aOffset - offsetPath
- */
- var fromOffsetPath = function (ancestor, aOffset) {
- var current = ancestor;
- for (var i = 0, sz = aOffset.length; i < sz; i++) {
- current = current.childNodes[aOffset[i]];
- }
- return current;
- };
-
- /**
- * split element or #text
- * @param {element} node
- * @param {number} offset
- */
- var splitData = function (node, offset) {
- if (offset === 0) { return node; }
- if (offset >= length(node)) { return node.nextSibling; }
-
- // splitText
- if (isText(node)) { return node.splitText(offset); }
-
- // splitElement
- var child = node.childNodes[offset];
- node = insertAfter(node.cloneNode(false), node);
- return appends(node, listNext(child));
- };
-
- /**
- * split dom tree by boundaryPoint(pivot and offset)
- * @param {element} root
- * @param {element} pivot - this will be boundaryPoint's node
- * @param {number} offset - this will be boundaryPoint's offset
- */
- var split = function (root, pivot, offset) {
- var aAncestor = listAncestor(pivot, func.eq(root));
- if (aAncestor.length === 1) { return splitData(pivot, offset); }
- return aAncestor.reduce(function (node, parent) {
- var clone = parent.cloneNode(false);
- insertAfter(clone, parent);
- if (node === pivot) {
- node = splitData(node, offset);
- }
- appends(clone, listNext(node));
- return clone;
- });
- };
-
- /**
- * remove node, (bRemoveChild: remove child or not)
- * @param {element} node
- * @param {boolean} bRemoveChild
- */
- var remove = function (node, bRemoveChild) {
- if (!node || !node.parentNode) { return; }
- if (node.removeNode) { return node.removeNode(bRemoveChild); }
-
- var elParent = node.parentNode;
- if (!bRemoveChild) {
- var aNode = [];
- var i, sz;
- for (i = 0, sz = node.childNodes.length; i < sz; i++) {
- aNode.push(node.childNodes[i]);
- }
-
- for (i = 0, sz = aNode.length; i < sz; i++) {
- elParent.insertBefore(aNode[i], node);
- }
- }
-
- elParent.removeChild(node);
- };
-
- var html = function ($node) {
- return dom.isTextarea($node[0]) ? $node.val() : $node.html();
- };
-
- return {
- emptyPara: emptyPara,
- isText: isText,
- isPara: isPara,
- isList: isList,
- isEditable: isEditable,
- isControlSizing: isControlSizing,
- isAnchor: makePredByNodeName('A'),
- isDiv: makePredByNodeName('DIV'),
- isSpan: makePredByNodeName('SPAN'),
- isB: makePredByNodeName('B'),
- isU: makePredByNodeName('U'),
- isS: makePredByNodeName('S'),
- isI: makePredByNodeName('I'),
- isImg: makePredByNodeName('IMG'),
- isTextarea: makePredByNodeName('TEXTAREA'),
- ancestor: ancestor,
- listAncestor: listAncestor,
- listNext: listNext,
- listPrev: listPrev,
- commonAncestor: commonAncestor,
- listBetween: listBetween,
- insertAfter: insertAfter,
- position: position,
- makeOffsetPath: makeOffsetPath,
- fromOffsetPath: fromOffsetPath,
- split: split,
- remove: remove,
- html: html
- };
- })();
-
- /**
- * range module
- */
- var range = (function () {
- var bW3CRangeSupport = !!document.createRange;
-
- // return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js
- var textRange2bp = function (textRange, bStart) {
- var elCont = textRange.parentElement(), nOffset;
-
- var tester = document.body.createTextRange(), elPrevCont;
- var aChild = list.from(elCont.childNodes);
- for (nOffset = 0; nOffset < aChild.length; nOffset++) {
- if (dom.isText(aChild[nOffset])) { continue; }
- tester.moveToElementText(aChild[nOffset]);
- if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; }
- elPrevCont = aChild[nOffset];
- }
-
- if (nOffset !== 0 && dom.isText(aChild[nOffset - 1])) {
- var textRangeStart = document.body.createTextRange(), elCurText = null;
- textRangeStart.moveToElementText(elPrevCont || elCont);
- textRangeStart.collapse(!elPrevCont);
- elCurText = elPrevCont ? elPrevCont.nextSibling : elCont.firstChild;
-
- var pointTester = textRange.duplicate();
- pointTester.setEndPoint('StartToStart', textRangeStart);
- var nTextCount = pointTester.text.replace(/[\r\n]/g, '').length;
-
- while (nTextCount > elCurText.nodeValue.length && elCurText.nextSibling) {
- nTextCount -= elCurText.nodeValue.length;
- elCurText = elCurText.nextSibling;
- }
-
- /* jshint ignore:start */
- var sDummy = elCurText.nodeValue; //enforce IE to re-reference elCurText, hack
- /* jshint ignore:end */
-
- if (bStart && elCurText.nextSibling && dom.isText(elCurText.nextSibling) &&
- nTextCount === elCurText.nodeValue.length) {
- nTextCount -= elCurText.nodeValue.length;
- elCurText = elCurText.nextSibling;
- }
-
- elCont = elCurText;
- nOffset = nTextCount;
- }
-
- return {cont: elCont, offset: nOffset};
- };
-
- // return TextRange from boundary point (inspired by google closure-library)
- var bp2textRange = function (bp) {
- var textRangeInfo = function (elCont, nOffset) {
- var elNode, bCollapseToStart;
-
- if (dom.isText(elCont)) {
- var aPrevText = dom.listPrev(elCont, func.not(dom.isText));
- var elPrevCont = list.last(aPrevText).previousSibling;
- elNode = elPrevCont || elCont.parentNode;
- nOffset += list.sum(list.tail(aPrevText), dom.length);
- bCollapseToStart = !elPrevCont;
- } else {
- elNode = elCont.childNodes[nOffset] || elCont;
- if (dom.isText(elNode)) {
- return textRangeInfo(elNode, nOffset);
- }
-
- nOffset = 0;
- bCollapseToStart = false;
- }
-
- return {cont: elNode, collapseToStart: bCollapseToStart, offset: nOffset};
- };
-
- var textRange = document.body.createTextRange();
- var info = textRangeInfo(bp.cont, bp.offset);
-
- textRange.moveToElementText(info.cont);
- textRange.collapse(info.collapseToStart);
- textRange.moveStart('character', info.offset);
- return textRange;
- };
-
- // {startContainer, startOffset, endContainer, endOffset}
- var WrappedRange = function (sc, so, ec, eo) {
- this.sc = sc;
- this.so = so;
- this.ec = ec;
- this.eo = eo;
-
- // nativeRange: get nativeRange from sc, so, ec, eo
- var nativeRange = function () {
- if (bW3CRangeSupport) {
- var w3cRange = document.createRange();
- w3cRange.setStart(sc, so);
- w3cRange.setEnd(ec, eo);
- return w3cRange;
- } else {
- var textRange = bp2textRange({cont: sc, offset: so});
- textRange.setEndPoint('EndToEnd', bp2textRange({cont: ec, offset: eo}));
- return textRange;
- }
- };
-
- // select: update visible range
- this.select = function () {
- var nativeRng = nativeRange();
- if (bW3CRangeSupport) {
- var selection = document.getSelection();
- if (selection.rangeCount > 0) { selection.removeAllRanges(); }
- selection.addRange(nativeRng);
- } else {
- nativeRng.select();
- }
- };
-
- // listPara: listing paragraphs on range
- this.listPara = function () {
- var aNode = dom.listBetween(sc, ec);
- var aPara = list.compact($.map(aNode, function (node) {
- return dom.ancestor(node, dom.isPara);
- }));
- return $.map(list.clusterBy(aPara, func.eq2), list.head);
- };
-
- // makeIsOn: return isOn(pred) function
- var makeIsOn = function (pred) {
- return function () {
- var elAncestor = dom.ancestor(sc, pred);
- return elAncestor && (elAncestor === dom.ancestor(ec, pred));
- };
- };
-
- // isOnEditable: judge whether range is on editable or not
- this.isOnEditable = makeIsOn(dom.isEditable);
- // isOnList: judge whether range is on list node or not
- this.isOnList = makeIsOn(dom.isList);
- // isOnAnchor: judge whether range is on anchor node or not
- this.isOnAnchor = makeIsOn(dom.isAnchor);
- // isCollapsed: judge whether range was collapsed
- this.isCollapsed = function () { return sc === ec && so === eo; };
-
- // insertNode
- this.insertNode = function (node) {
- var nativeRng = nativeRange();
- if (bW3CRangeSupport) {
- nativeRng.insertNode(node);
- } else {
- nativeRng.pasteHTML(node.outerHTML); // NOTE: missing node reference.
- }
- };
-
- this.toString = function () {
- var nativeRng = nativeRange();
- return bW3CRangeSupport ? nativeRng.toString() : nativeRng.text;
- };
-
- //bookmark: offsetPath bookmark
- this.bookmark = function (elEditable) {
- return {
- s: { path: dom.makeOffsetPath(elEditable, sc), offset: so },
- e: { path: dom.makeOffsetPath(elEditable, ec), offset: eo }
- };
- };
- };
-
- return { // Range Object
- // create Range Object From arguments or Browser Selection
- create : function (sc, so, ec, eo) {
- if (arguments.length === 0) { // from Browser Selection
- if (bW3CRangeSupport) { // webkit, firefox
- var selection = document.getSelection();
- if (selection.rangeCount === 0) { return null; }
-
- var nativeRng = selection.getRangeAt(0);
- sc = nativeRng.startContainer;
- so = nativeRng.startOffset;
- ec = nativeRng.endContainer;
- eo = nativeRng.endOffset;
- } else { // IE8: TextRange
- var textRange = document.selection.createRange();
- var textRangeEnd = textRange.duplicate();
- textRangeEnd.collapse(false);
- var textRangeStart = textRange;
- textRangeStart.collapse(true);
-
- var bpStart = textRange2bp(textRangeStart, true),
- bpEnd = textRange2bp(textRangeEnd, false);
-
- sc = bpStart.cont;
- so = bpStart.offset;
- ec = bpEnd.cont;
- eo = bpEnd.offset;
- }
- } else if (arguments.length === 2) { //collapsed
- ec = sc;
- eo = so;
- }
- return new WrappedRange(sc, so, ec, eo);
- },
- // createFromBookmark
- createFromBookmark : function (elEditable, bookmark) {
- var sc = dom.fromOffsetPath(elEditable, bookmark.s.path);
- var so = bookmark.s.offset;
- var ec = dom.fromOffsetPath(elEditable, bookmark.e.path);
- var eo = bookmark.e.offset;
- return new WrappedRange(sc, so, ec, eo);
- }
- };
- })();
-
- /**
- * Style
- */
- var Style = function () {
- // para level style
- this.stylePara = function (rng, oStyle) {
- var aPara = rng.listPara();
- $.each(aPara, function (idx, elPara) {
- $.each(oStyle, function (sKey, sValue) {
- elPara.style[sKey] = sValue;
- });
- });
- };
-
- // get current style, elTarget: target element on event.
- this.current = function (rng, elTarget) {
- var $cont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc);
- var oStyle = $cont.css(['font-size', 'text-align',
- 'list-style-type', 'line-height']) || {};
-
- oStyle['font-size'] = parseInt(oStyle['font-size']);
-
- // document.queryCommandState for toggle state
- oStyle['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal';
- oStyle['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal';
- oStyle['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal';
-
- // list-style-type to list-style(unordered, ordered)
- if (!rng.isOnList()) {
- oStyle['list-style'] = 'none';
- } else {
- var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square'];
- var bUnordered = $.inArray(oStyle['list-style-type'], aOrderedType) > -1;
- oStyle['list-style'] = bUnordered ? 'unordered' : 'ordered';
- }
-
- var elPara = dom.ancestor(rng.sc, dom.isPara);
- if (elPara && elPara.style['line-height']) {
- oStyle['line-height'] = elPara.style.lineHeight;
- } else {
- var lineHeight = parseInt(oStyle['line-height']) / parseInt(oStyle['font-size']);
- oStyle['line-height'] = lineHeight.toFixed(1);
- }
-
- oStyle.image = dom.isImg(elTarget) && elTarget;
- oStyle.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor);
- oStyle.aAncestor = dom.listAncestor(rng.sc, dom.isEditable);
-
- return oStyle;
- };
- };
-
- /**
- * History
- */
- var History = function () {
- var aUndo = [], aRedo = [];
-
- var makeSnap = function ($editable) {
- var elEditable = $editable[0], rng = range.create();
- return {
- contents: $editable.html(),
- bookmark: rng.bookmark(elEditable),
- scrollTop: $editable.scrollTop()
- };
- };
-
- var applySnap = function ($editable, oSnap) {
- $editable.html(oSnap.contents).scrollTop(oSnap.scrollTop);
- range.createFromBookmark($editable[0], oSnap.bookmark).select();
- };
-
- this.undo = function ($editable) {
- var oSnap = makeSnap($editable);
- if (aUndo.length === 0) { return; }
- applySnap($editable, aUndo.pop());
- aRedo.push(oSnap);
- };
-
- this.redo = function ($editable) {
- var oSnap = makeSnap($editable);
- if (aRedo.length === 0) { return; }
- applySnap($editable, aRedo.pop());
- aUndo.push(oSnap);
- };
-
- this.recordUndo = function ($editable) {
- aRedo = [];
- aUndo.push(makeSnap($editable));
- };
- };
-
- /**
- * Editor
- */
- var Editor = function () {
- // save current range
- this.saveRange = function ($editable) {
- $editable.data('range', range.create());
- };
-
- // restore lately range
- this.restoreRange = function ($editable) {
- var rng = $editable.data('range');
- if (rng) { rng.select(); }
- };
-
- //currentStyle
- var style = new Style();
- this.currentStyle = function (elTarget) {
- var rng = range.create();
- return rng.isOnEditable() && style.current(rng, elTarget);
- };
-
- this.tab = function ($editable) {
- recordUndo($editable);
- var rng = range.create();
- var sNbsp = new Array($editable.data('tabsize') + 1).join('&nbsp;');
- rng.insertNode($('<span id="noteTab">' + sNbsp + '</span>')[0]);
- var $tab = $('#noteTab').removeAttr('id');
- rng = range.create($tab[0], 1);
- rng.select();
- dom.remove($tab[0]);
- };
-
- // undo
- this.undo = function ($editable) {
- $editable.data('NoteHistory').undo($editable);
- };
-
- // redo
- this.redo = function ($editable) {
- $editable.data('NoteHistory').redo($editable);
- };
-
- // recordUndo
- var recordUndo = this.recordUndo = function ($editable) {
- $editable.data('NoteHistory').recordUndo($editable);
- };
-
- /* jshint ignore:start */
- // native commands(with execCommand), generate function for execCommand
- var aCmd = ['bold', 'italic', 'underline', 'strikethrough',
- 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
- 'insertOrderedList', 'insertUnorderedList',
- 'indent', 'outdent', 'formatBlock', 'removeFormat',
- 'backColor', 'foreColor', 'insertHorizontalRule'];
-
- for (var idx = 0, len = aCmd.length; idx < len; idx ++) {
- this[aCmd[idx]] = (function (sCmd) {
- return function ($editable, sValue) {
- recordUndo($editable);
- document.execCommand(sCmd, false, sValue);
- };
- })(aCmd[idx]);
- }
- /* jshint ignore:end */
-
- this.insertImage = function ($editable, sUrl) {
- async.loadImage(sUrl).done(function (image) {
- recordUndo($editable);
- var $image = $('<img>').attr('src', sUrl);
- $image.css('width', Math.min($editable.width(), image.width));
- range.create().insertNode($image[0]);
- }).fail(function () {
- var callbacks = $editable.data('callbacks');
- if (callbacks.onImageUploadError) {
- callbacks.onImageUploadError();
- }
- });
- };
-
- this.formatBlock = function ($editable, sValue) {
- recordUndo($editable);
- sValue = agent.bMSIE ? '<' + sValue + '>' : sValue;
- document.execCommand('FormatBlock', false, sValue);
- };
-
- this.fontSize = function ($editable, sValue) {
- recordUndo($editable);
- document.execCommand('fontSize', false, 3);
- if (agent.bFF) {
- // firefox: <font size="3"> to <span style='font-size={sValue}px;'>, buggy
- $editable.find('font[size=3]').removeAttr('size').css('font-size', sValue + 'px');
- } else {
- // chrome: <span style="font-size: medium"> to <span style='font-size={sValue}px;'>
- $editable.find('span').filter(function () {
- return this.style.fontSize === 'medium';
- }).css('font-size', sValue + 'px');
- }
- };
-
- this.lineHeight = function ($editable, sValue) {
- recordUndo($editable);
- style.stylePara(range.create(), {lineHeight: sValue});
- };
-
- this.unlink = function ($editable) {
- var rng = range.create();
- if (rng.isOnAnchor()) {
- recordUndo($editable);
- var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
- rng = range.create(elAnchor, 0, elAnchor, 1);
- rng.select();
- document.execCommand('unlink');
- }
- };
-
- this.setLinkDialog = function ($editable, fnShowDialog) {
- var rng = range.create();
- if (rng.isOnAnchor()) {
- var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
- rng = range.create(elAnchor, 0, elAnchor, 1);
- }
- fnShowDialog({
- range: rng,
- text: rng.toString(),
- url: rng.isOnAnchor() ? dom.ancestor(rng.sc, dom.isAnchor).href : ''
- }, function (sLinkUrl) {
- rng.select();
- recordUndo($editable);
-
- var sLinkUrlWithProtocol;
- if (sLinkUrl.indexOf('@') !== -1) { // email address
- sLinkUrlWithProtocol = sLinkUrl.indexOf(':') !== -1 ? sLinkUrl : 'mailto:' + sLinkUrl;
- } else { // normal address
- sLinkUrlWithProtocol = sLinkUrl.indexOf('://') !== -1 ? sLinkUrl : 'http://' + sLinkUrl;
- }
-
- //IE: createLink when range collapsed.
- if (agent.bMSIE && rng.isCollapsed()) {
- rng.insertNode($('<A id="linkAnchor">' + sLinkUrl + '</A>')[0]);
- var $anchor = $('#linkAnchor').removeAttr('id')
- .attr('href', sLinkUrlWithProtocol);
- rng = range.create($anchor[0], 0, $anchor[0], 1);
- rng.select();
- } else {
- document.execCommand('createlink', false, sLinkUrlWithProtocol);
- }
- });
- };
-
- this.color = function ($editable, sObjColor) {
- var oColor = JSON.parse(sObjColor);
- var foreColor = oColor.foreColor, backColor = oColor.backColor;
-
- recordUndo($editable);
- if (foreColor) { document.execCommand('foreColor', false, foreColor); }
- if (backColor) { document.execCommand('backColor', false, backColor); }
- };
-
- this.insertTable = function ($editable, sDim) {
- recordUndo($editable);
- var aDim = sDim.split('x');
- var nCol = aDim[0], nRow = aDim[1];
-
- var aTD = [], sTD;
- var sWhitespace = agent.bMSIE ? '&nbsp;' : '<br/>';
- for (var idxCol = 0; idxCol < nCol; idxCol++) {
- aTD.push('<td>' + sWhitespace + '</td>');
- }
- sTD = aTD.join('');
-
- var aTR = [], sTR;
- for (var idxRow = 0; idxRow < nRow; idxRow++) {
- aTR.push('<tr>' + sTD + '</tr>');
- }
- sTR = aTR.join('');
- var sTable = '<table class="table table-bordered">' + sTR + '</table>';
- range.create().insertNode($(sTable)[0]);
- };
-
- this.floatMe = function ($editable, sValue, elTarget) {
- recordUndo($editable);
- elTarget.style.cssFloat = sValue;
- };
-
- this.resize = function ($editable, sValue, elTarget) {
- recordUndo($editable);
- elTarget.style.width = $editable.width() * sValue + 'px';
- elTarget.style.height = '';
- };
-
- this.resizeTo = function (pos, $target) {
- var newRatio = pos.y / pos.x;
- var ratio = $target.data('ratio');
-
- $target.css({
- width: ratio > newRatio ? pos.x : pos.y / ratio,
- height: ratio > newRatio ? pos.x * ratio : pos.y
- });
- };
- };
-
- /**
- * Toolbar
- */
- var Toolbar = function () {
- this.update = function ($toolbar, oStyle) {
- //handle selectbox for fontsize, lineHeight
- var checkDropdownMenu = function ($btn, nValue) {
- $btn.find('.dropdown-menu li a').each(function () {
- var bChecked = parseFloat($(this).data('value')) === nValue;
- this.className = bChecked ? 'checked' : '';
- });
- };
-
- var $fontsize = $toolbar.find('.note-fontsize');
- $fontsize.find('.note-current-fontsize').html(oStyle['font-size']);
- checkDropdownMenu($fontsize, parseFloat(oStyle['font-size']));
-
- var $lineHeight = $toolbar.find('.note-height');
- checkDropdownMenu($lineHeight, parseFloat(oStyle['line-height']));
-
- //check button state
- var btnState = function (sSelector, pred) {
- var $btn = $toolbar.find(sSelector);
- $btn[pred() ? 'addClass' : 'removeClass']('active');
- };
-
- btnState('button[data-event="bold"]', function () {
- return oStyle['font-bold'] === 'bold';
- });
- btnState('button[data-event="italic"]', function () {
- return oStyle['font-italic'] === 'italic';
- });
- btnState('button[data-event="underline"]', function () {
- return oStyle['font-underline'] === 'underline';
- });
- btnState('button[data-event="justifyLeft"]', function () {
- return oStyle['text-align'] === 'left' || oStyle['text-align'] === 'start';
- });
- btnState('button[data-event="justifyCenter"]', function () {
- return oStyle['text-align'] === 'center';
- });
- btnState('button[data-event="justifyRight"]', function () {
- return oStyle['text-align'] === 'right';
- });
- btnState('button[data-event="justifyFull"]', function () {
- return oStyle['text-align'] === 'justify';
- });
- btnState('button[data-event="insertUnorderedList"]', function () {
- return oStyle['list-style'] === 'unordered';
- });
- btnState('button[data-event="insertOrderedList"]', function () {
- return oStyle['list-style'] === 'ordered';
- });
- };
-
- this.updateRecentColor = function (elBtn, sEvent, sValue) {
- var $color = $(elBtn).closest('.note-color');
- var $recentColor = $color.find('.note-recent-color');
- var oColor = JSON.parse($recentColor.attr('data-value'));
- oColor[sEvent] = sValue;
- $recentColor.attr('data-value', JSON.stringify(oColor));
- var sKey = sEvent === 'backColor' ? 'background-color' : 'color';
- $recentColor.find('i').css(sKey, sValue);
- };
-
- this.updateFullscreen = function ($toolbar, bFullscreen) {
- var $btn = $toolbar.find('button[data-event="fullscreen"]');
- $btn[bFullscreen ? 'addClass' : 'removeClass']('active');
- };
- this.updateCodeview = function ($toolbar, bCodeview) {
- var $btn = $toolbar.find('button[data-event="codeview"]');
- $btn[bCodeview ? 'addClass' : 'removeClass']('active');
- };
-
- this.enable = function ($toolbar) {
- $toolbar.find('button').not('button[data-event="codeview"]').removeClass('disabled');
- };
-
- this.disable = function ($toolbar) {
- $toolbar.find('button').not('button[data-event="codeview"]').addClass('disabled');
- };
- };
-
- /**
- * Popover (http://getbootstrap.com/javascript/#popovers)
- */
- var Popover = function () {
- var showPopover = function ($popover, elPlaceholder) {
- var $placeholder = $(elPlaceholder);
- var pos = $placeholder.position(), height = $placeholder.height();
- $popover.css({
- display: 'block',
- left: pos.left,
- top: pos.top + height
- });
- };
-
- this.update = function ($popover, oStyle) {
- var $linkPopover = $popover.find('.note-link-popover'),
- $imagePopover = $popover.find('.note-image-popover');
- if (oStyle.anchor) {
- var $anchor = $linkPopover.find('a');
- $anchor.attr('href', oStyle.anchor.href).html(oStyle.anchor.href);
- showPopover($linkPopover, oStyle.anchor);
- } else {
- $linkPopover.hide();
- }
-
- if (oStyle.image) {
- showPopover($imagePopover, oStyle.image);
- } else {
- $imagePopover.hide();
- }
- };
-
- this.hide = function ($popover) {
- $popover.children().hide();
- };
- };
-
- /**
- * Handle
- */
- var Handle = function () {
- this.update = function ($handle, oStyle) {
- var $selection = $handle.find('.note-control-selection');
- if (oStyle.image) {
- var $image = $(oStyle.image);
- var pos = $image.position();
- var szImage = {w: $image.width(), h: $image.height()};
- $selection.css({
- display: 'block',
- left: pos.left,
- top: pos.top,
- width: szImage.w,
- height: szImage.h
- }).data('target', oStyle.image); // save current image element.
- var sSizing = szImage.w + 'x' + szImage.h;
- $selection.find('.note-control-selection-info').text(sSizing);
- } else {
- $selection.hide();
- }
- };
-
- this.hide = function ($handle) {
- $handle.children().hide();
- };
- };
-
- /**
- * Dialog
- */
- var Dialog = function () {
- this.showImageDialog = function ($dialog, hDropImage, fnInsertImages, fnInsertImage) {
- var $imageDialog = $dialog.find('.note-image-dialog');
- var $dropzone = $dialog.find('.note-dropzone'),
- $imageInput = $dialog.find('.note-image-input'),
- $imageUrl = $dialog.find('.note-image-url'),
- $imageBtn = $dialog.find('.note-image-btn');
-
- $imageDialog.on('shown.bs.modal', function () {
- $dropzone.on('dragenter dragover dragleave', false);
- $dropzone.on('drop', function (e) {
- hDropImage(e);
- $imageDialog.modal('hide');
- });
- $imageInput.on('change', function () {
- fnInsertImages(this.files);
- $(this).val('');
- $imageDialog.modal('hide');
- });
- $imageUrl.val('').keyup(function () {
- if ($imageUrl.val()) {
- $imageBtn.removeClass('disabled').attr('disabled', false);
- } else {
- $imageBtn.addClass('disabled').attr('disabled', true);
- }
- }).trigger('focus');
- $imageBtn.click(function (event) {
- $imageDialog.modal('hide');
- fnInsertImage($imageUrl.val());
- event.preventDefault();
- });
- }).on('hidden.bs.modal', function () {
- $dropzone.off('dragenter dragover dragleave drop');
- $imageInput.off('change');
- $imageDialog.off('shown.bs.modal hidden.bs.modal');
- $imageUrl.off('keyup');
- $imageBtn.off('click');
- }).modal('show');
- };
-
- this.showLinkDialog = function ($dialog, linkInfo, callback) {
- var $linkDialog = $dialog.find('.note-link-dialog');
- var $linkText = $linkDialog.find('.note-link-text'),
- $linkUrl = $linkDialog.find('.note-link-url'),
- $linkBtn = $linkDialog.find('.note-link-btn');
-
- $linkDialog.on('shown.bs.modal', function () {
- $linkText.html(linkInfo.text);
- $linkUrl.val(linkInfo.url).keyup(function () {
- if ($linkUrl.val()) {
- $linkBtn.removeClass('disabled').attr('disabled', false);
- } else {
- $linkBtn.addClass('disabled').attr('disabled', true);
- }
-
- if (!linkInfo.text) { $linkText.html($linkUrl.val()); }
- }).trigger('focus');
- $linkBtn.click(function (event) {
- $linkDialog.modal('hide'); //hide and createLink (ie9+)
- callback($linkUrl.val());
- event.preventDefault();
- });
- }).on('hidden.bs.modal', function () {
- $linkUrl.off('keyup');
- $linkBtn.off('click');
- $linkDialog.off('shown.bs.modal hidden.bs.modal');
- }).modal('show');
- };
-
- this.showHelpDialog = function ($dialog) {
- $dialog.find('.note-help-dialog').modal('show');
- };
- };
-
- /**
- * EventHandler
- *
- * handle mouse & key event on note
- */
- var EventHandler = function () {
- var editor = new Editor();
- var toolbar = new Toolbar(), popover = new Popover();
- var handle = new Handle(), dialog = new Dialog();
-
- var key = { BACKSPACE: 8, TAB: 9, ENTER: 13, SPACE: 32,
- NUM0: 48, NUM1: 49, NUM6: 54, NUM7: 55, NUM8: 56,
- B: 66, E: 69, I: 73, J: 74, K: 75, L: 76, R: 82, S: 83, U: 85,
- Y: 89, Z: 90, SLASH: 191,
- LEFTBRACKET: 219, BACKSLACH: 220, RIGHTBRACKET: 221 };
-
- // makeLayoutInfo from editor's descendant node.
- var makeLayoutInfo = function (descendant) {
- var $editor = $(descendant).closest('.note-editor');
- return {
- editor: function () { return $editor; },
- toolbar: function () { return $editor.find('.note-toolbar'); },
- editable: function () { return $editor.find('.note-editable'); },
- codable: function () { return $editor.find('.note-codable'); },
- statusbar: function () { return $editor.find('.note-statusbar'); },
- popover: function () { return $editor.find('.note-popover'); },
- handle: function () { return $editor.find('.note-handle'); },
- dialog: function () { return $editor.find('.note-dialog'); }
- };
- };
-
- var hKeydown = function (event) {
- var bCmd = agent.bMac ? event.metaKey : event.ctrlKey,
- bShift = event.shiftKey, keyCode = event.keyCode;
-
- // optimize
- var bExecCmd = (bCmd || bShift || keyCode === key.TAB);
- var oLayoutInfo = (bExecCmd) ? makeLayoutInfo(event.target) : null;
-
- if (keyCode === key.TAB && oLayoutInfo.editable().data('tabsize')) {
- editor.tab(oLayoutInfo.editable());
- } else if (bCmd && ((bShift && keyCode === key.Z) || keyCode === key.Y)) {
- editor.redo(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.Z) {
- editor.undo(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.B) {
- editor.bold(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.I) {
- editor.italic(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.U) {
- editor.underline(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.S) {
- editor.strikethrough(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.BACKSLACH) {
- editor.removeFormat(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.K) {
- oLayoutInfo.editable();
- editor.setLinkDialog(oLayoutInfo.editable(), function (linkInfo, cb) {
- dialog.showLinkDialog(oLayoutInfo.dialog(), linkInfo, cb);
- });
- } else if (bCmd && keyCode === key.SLASH) {
- dialog.showHelpDialog(oLayoutInfo.dialog());
- } else if (bCmd && bShift && keyCode === key.L) {
- editor.justifyLeft(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.E) {
- editor.justifyCenter(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.R) {
- editor.justifyRight(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.J) {
- editor.justifyFull(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.NUM7) {
- editor.insertUnorderedList(oLayoutInfo.editable());
- } else if (bCmd && bShift && keyCode === key.NUM8) {
- editor.insertOrderedList(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.LEFTBRACKET) {
- editor.outdent(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.RIGHTBRACKET) {
- editor.indent(oLayoutInfo.editable());
- } else if (bCmd && keyCode === key.NUM0) { // formatBlock Paragraph
- editor.formatBlock(oLayoutInfo.editable(), 'P');
- } else if (bCmd && (key.NUM1 <= keyCode && keyCode <= key.NUM6)) {
- var sHeading = 'H' + String.fromCharCode(keyCode); // H1~H6
- editor.formatBlock(oLayoutInfo.editable(), sHeading);
- } else if (bCmd && keyCode === key.ENTER) {
- editor.insertHorizontalRule(oLayoutInfo.editable());
- } else {
- if (keyCode === key.BACKSPACE || keyCode === key.ENTER ||
- keyCode === key.SPACE) {
- editor.recordUndo(makeLayoutInfo(event.target).editable());
- }
- return; // not matched
- }
- event.preventDefault(); //prevent default event for FF
- };
-
- var insertImages = function ($editable, files) {
- var callbacks = $editable.data('callbacks');
- editor.restoreRange($editable);
- if (callbacks.onImageUpload) { // call custom handler
- callbacks.onImageUpload(files, editor, $editable);
- } else {
- $.each(files, function (idx, file) {
- async.readFile(file).done(function (sURL) {
- editor.insertImage($editable, sURL);
- }).fail(function () {
- if (callbacks.onImageUploadError) {
- callbacks.onImageUploadError();
- }
- });
- });
- }
- };
-
- var hDropImage = function (event) {
- var dataTransfer = event.originalEvent.dataTransfer;
- if (dataTransfer && dataTransfer.files) {
- var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
- insertImages(oLayoutInfo.editable(), dataTransfer.files);
- }
- event.stopPropagation();
- event.preventDefault();
- };
-
- var hMousedown = function (event) {
- //preventDefault Selection for FF, IE8+
- if (dom.isImg(event.target)) { event.preventDefault(); }
- };
-
- var hToolbarAndPopoverUpdate = function (event) {
- var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
- var oStyle = editor.currentStyle(event.target);
- if (!oStyle) { return; }
- toolbar.update(oLayoutInfo.toolbar(), oStyle);
- popover.update(oLayoutInfo.popover(), oStyle);
- handle.update(oLayoutInfo.handle(), oStyle);
- };
-
- var hScroll = function (event) {
- var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target);
- //hide popover and handle when scrolled
- popover.hide(oLayoutInfo.popover());
- handle.hide(oLayoutInfo.handle());
- };
-
- var hHandleMousedown = function (event) {
- if (dom.isControlSizing(event.target)) {
- var oLayoutInfo = makeLayoutInfo(event.target),
- $handle = oLayoutInfo.handle(), $popover = oLayoutInfo.popover(),
- $editable = oLayoutInfo.editable(), $editor = oLayoutInfo.editor();
-
- var elTarget = $handle.find('.note-control-selection').data('target'),
- $target = $(elTarget);
- var posStart = $target.offset(),
- scrollTop = $(document).scrollTop(), posDistance;
-
- $editor.on('mousemove', function (event) {
- posDistance = {x: event.clientX - posStart.left,
- y: event.clientY - (posStart.top - scrollTop)};
- editor.resizeTo(posDistance, $target);
- handle.update($handle, {image: elTarget});
- popover.update($popover, {image: elTarget});
- }).on('mouseup', function () {
- $editor.off('mousemove').off('mouseup');
- });
-
- if (!$target.data('ratio')) { // original ratio.
- $target.data('ratio', $target.height() / $target.width());
- }
-
- editor.recordUndo($editable);
- event.stopPropagation();
- event.preventDefault();
- }
- };
-
- var hToolbarAndPopoverMousedown = function (event) {
- // prevent default event when insertTable (FF, Webkit)
- var $btn = $(event.target).closest('[data-event]');
- if ($btn.length > 0) { event.preventDefault(); }
- };
-
- var hToolbarAndPopoverClick = function (event) {
- var $btn = $(event.target).closest('[data-event]');
-
- if ($btn.length > 0) {
- var sEvent = $btn.attr('data-event'),
- sValue = $btn.attr('data-value');
-
- var oLayoutInfo = makeLayoutInfo(event.target);
- var $editor = oLayoutInfo.editor(),
- $toolbar = oLayoutInfo.toolbar(),
- $dialog = oLayoutInfo.dialog(),
- $editable = oLayoutInfo.editable(),
- $codable = oLayoutInfo.codable();
-
- // before command
- var elTarget;
- if ($.inArray(sEvent, ['resize', 'floatMe']) !== -1) {
- var $handle = oLayoutInfo.handle();
- var $selection = $handle.find('.note-control-selection');
- elTarget = $selection.data('target');
- }
-
- if (editor[sEvent]) { // on command
- $editable.trigger('focus');
- editor[sEvent]($editable, sValue, elTarget);
- }
-
- // after command
- if ($.inArray(sEvent, ['backColor', 'foreColor']) !== -1) {
- toolbar.updateRecentColor($btn[0], sEvent, sValue);
- } else if (sEvent === 'showLinkDialog') { // popover to dialog
- $editable.focus();
- editor.setLinkDialog($editable, function (linkInfo, cb) {
- dialog.showLinkDialog($dialog, linkInfo, cb);
- });
- } else if (sEvent === 'showImageDialog') {
- $editable.focus();
- dialog.showImageDialog($dialog, hDropImage, function (files) {
- insertImages($editable, files);
- }, function (sUrl) {
- editor.restoreRange($editable);
- editor.insertImage($editable, sUrl);
- });
- } else if (sEvent === 'showHelpDialog') {
- dialog.showHelpDialog($dialog);
- } else if (sEvent === 'fullscreen') {
- $editor.toggleClass('fullscreen');
-
- var hResizeFullscreen = function () {
- var nHeight = $(window).height() - $toolbar.outerHeight();
- $editable.css('height', nHeight);
- };
-
- var bFullscreen = $editor.hasClass('fullscreen');
- if (bFullscreen) {
- $editable.data('orgHeight', $editable.css('height'));
- $(window).resize(hResizeFullscreen).trigger('resize');
- } else {
- var hasOptionHeight = !!$editable.data('optionHeight');
- $editable.css('height', hasOptionHeight ? $editable.data('orgHeight') : 'auto');
- $(window).off('resize');
- }
-
- toolbar.updateFullscreen($toolbar, bFullscreen);
- } else if (sEvent === 'codeview') {
- $editor.toggleClass('codeview');
-
- var bCodeview = $editor.hasClass('codeview');
- if (bCodeview) {
- $codable.val($editable.html());
- $codable.height($editable.height());
- toolbar.disable($toolbar);
- $codable.focus();
-
- // activate CodeMirror as codable
- if (agent.bCodeMirror) {
- var cmEditor = CodeMirror.fromTextArea($codable[0], $.extend({
- mode: 'text/html',
- lineNumbers: true
- }, $editor.data('options').codemirror));
- // CodeMirror hasn't Padding.
- cmEditor.setSize(null, $editable.outerHeight());
- // autoFormatRange If formatting included
- if (cmEditor.autoFormatRange) {
- cmEditor.autoFormatRange({line: 0, ch: 0}, {
- line: cmEditor.lineCount(),
- ch: cmEditor.getTextArea().value.length
- });
- }
- $codable.data('cmEditor', cmEditor);
- }
- } else {
- // deactivate CodeMirror as codable
- if (agent.bCodeMirror) {
- $codable.data('cmEditor').toTextArea();
- }
-
- $editable.html($codable.val() || dom.emptyPara);
- $editable.height($editable.data('optionHeight') ? $codable.height() : 'auto');
-
- toolbar.enable($toolbar);
- $editable.focus();
- }
-
- toolbar.updateCodeview(oLayoutInfo.toolbar(), bCodeview);
- }
-
- hToolbarAndPopoverUpdate(event);
- }
- };
-
- var EDITABLE_PADDING = 24;
- var hStatusbarMousedown = function (event) {
- var $document = $(document);
- var oLayoutInfo = makeLayoutInfo(event.target);
- var $editable = oLayoutInfo.editable();
-
- var nEditableTop = $editable.offset().top - $document.scrollTop();
- var hMousemove = function (event) {
- $editable.height(event.clientY - (nEditableTop + EDITABLE_PADDING));
- };
- var hMouseup = function () {
- $document.unbind('mousemove', hMousemove)
- .unbind('mouseup', hMouseup);
- };
- $document.mousemove(hMousemove).mouseup(hMouseup);
- event.stopPropagation();
- event.preventDefault();
- };
-
- var PX_PER_EM = 18;
- var hDimensionPickerMove = function (event) {
- var $picker = $(event.target.parentNode); // target is mousecatcher
- var $dimensionDisplay = $picker.next();
- var $catcher = $picker.find('.note-dimension-picker-mousecatcher');
- var $highlighted = $picker.find('.note-dimension-picker-highlighted');
- var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted');
- var posOffset;
- if (event.offsetX === undefined) {
- // HTML5 with jQuery - e.offsetX is undefined in Firefox
- var posCatcher = $(event.target).offset();
- posOffset = {x: event.pageX - posCatcher.left,
- y: event.pageY - posCatcher.top};
- } else {
- posOffset = {x: event.offsetX, y: event.offsetY};
- }
-
- var dim = {c: Math.ceil(posOffset.x / PX_PER_EM) || 1,
- r: Math.ceil(posOffset.y / PX_PER_EM) || 1};
-
- $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' });
- $catcher.attr('data-value', dim.c + 'x' + dim.r);
-
- if (3 < dim.c && dim.c < 10) { // 5~10
- $unhighlighted.css({ width: dim.c + 1 + 'em'});
- }
-
- if (3 < dim.r && dim.r < 10) { // 5~10
- $unhighlighted.css({ height: dim.r + 1 + 'em'});
- }
-
- $dimensionDisplay.html(dim.c + ' x ' + dim.r);
- };
-
- /**
- * Attach eventhandler
- * @param {object} oLayoutInfo - layout Informations
- * @param {object} options - user options include custom event handlers
- * @param {function} options.enter - enter key handler
- */
- this.attach = function (oLayoutInfo, options) {
- oLayoutInfo.editable.on('keydown', hKeydown);
- oLayoutInfo.editable.on('mousedown', hMousedown);
- oLayoutInfo.editable.on('keyup mouseup', hToolbarAndPopoverUpdate);
- oLayoutInfo.editable.on('scroll', hScroll);
- //TODO: handle Drag point
- oLayoutInfo.editable.on('dragenter dragover dragleave', false);
- oLayoutInfo.editable.on('drop', hDropImage);
-
- oLayoutInfo.handle.on('mousedown', hHandleMousedown);
-
- oLayoutInfo.toolbar.on('click', hToolbarAndPopoverClick);
- oLayoutInfo.popover.on('click', hToolbarAndPopoverClick);
- oLayoutInfo.toolbar.on('mousedown', hToolbarAndPopoverMousedown);
- oLayoutInfo.popover.on('mousedown', hToolbarAndPopoverMousedown);
-
- oLayoutInfo.statusbar.on('mousedown', hStatusbarMousedown);
-
- //toolbar table dimension
- var $toolbar = oLayoutInfo.toolbar;
- var $catcher = $toolbar.find('.note-dimension-picker-mousecatcher');
- $catcher.on('mousemove', hDimensionPickerMove);
-
- // save selection when focusout
- oLayoutInfo.editable.on('blur', function () {
- editor.saveRange(oLayoutInfo.editable);
- });
-
- // basic event callbacks (lowercase)
- // enter, focus, blur, keyup, keydown
- if (options.onenter) {
- oLayoutInfo.editable.keypress(function (event) {
- if (event.keyCode === key.ENTER) { options.onenter(event); }
- });
- }
- if (options.onfocus) { oLayoutInfo.editable.focus(options.onfocus); }
- if (options.onblur) { oLayoutInfo.editable.blur(options.onblur); }
- if (options.onkeyup) { oLayoutInfo.editable.keyup(options.onkeyup); }
- if (options.onkeydown) { oLayoutInfo.editable.keydown(options.onkeydown); }
-
- // callbacks for advanced features (camel)
- // All editor status will be saved on editable with jquery's data
- // for support multiple editor with singleton object.
- oLayoutInfo.editable.data('callbacks', {
- onChange: options.onChange,
- onAutoSave: options.onAutoSave,
- onPasteBefore: options.onPasteBefore,
- onPasteAfter: options.onPasteAfter,
- onImageUpload: options.onImageUpload,
- onImageUploadError: options.onImageUpload,
- onFileUpload: options.onFileUpload,
- onFileUploadError: options.onFileUpload
- });
- };
-
- this.dettach = function (oLayoutInfo) {
- oLayoutInfo.editable.off();
- oLayoutInfo.toolbar.off();
- oLayoutInfo.handle.off();
- oLayoutInfo.popover.off();
- };
- };
-
- /**
- * Locale
- */
- var Locale = {
- 'en-US': {
- font: {
- bold: 'Bold',
- italic: 'Italic',
- underline: 'Underline',
- strike: 'Strike',
- clear: 'Remove Font Style',
- height: 'Line Height',
- size: 'Font Size'
- },
- image: {
- image: 'Picture',
- insert: 'Insert Image',
- resize_full: 'Resize Full',
- resize_half: 'Resize Half',
- resize_quarter: 'Resize Quarter',
- float_left: 'Float Left',
- float_right: 'Float Right',
- float_none: 'Float None',
- drag_image_here: 'Drag an image here',
- select_from_files: 'Select from files',
- url: 'Image URL'
- },
- link: {
- link: 'Link',
- insert: 'Insert Link',
- unlink: 'Unlink',
- edit: 'Edit',
- text_to_display: 'Text to display',
- url: 'To what URL should this link go?'
- },
- table: {
- table: 'Table'
- },
- hr: {
- insert: 'Insert Horizontal Rule'
- },
- style: {
- style: 'Style',
- normal: 'Normal',
- blockquote: 'Quote',
- pre: 'Code',
- h1: 'Header 1',
- h2: 'Header 2',
- h3: 'Header 3',
- h4: 'Header 4',
- h5: 'Header 5',
- h6: 'Header 6'
- },
- lists: {
- unordered: 'Unordered list',
- ordered: 'Ordered list'
- },
- options: {
- help: 'Help',
- fullscreen: 'Full Screen',
- codeview: 'Code View'
- },
- paragraph: {
- paragraph: 'Paragraph',
- outdent: 'Outdent',
- indent: 'Indent',
- left: 'Align left',
- center: 'Align center',
- right: 'Align right',
- justify: 'Justify full'
- },
- color: {
- recent: 'Recent Color',
- more: 'More Color',
- background: 'BackColor',
- foreground: 'FontColor',
- transparent: 'Transparent',
- set_transparent: 'Set transparent',
- reset: 'Reset',
- reset_to_default: 'Reset to default'
- },
- shortcut: {
- shortcuts: 'Keyboard shortcuts',
- close: 'Close',
- text_formatting: 'Text formatting',
- action: 'Action',
- paragraph_formatting: 'Paragraph formatting',
- document_style: 'Document Style'
- },
- history: {
- undo: 'Undo',
- redo: 'Redo'
- }
- },
-
- 'nl-NL': {
- font: {
- bold: 'Vet',
- italic: 'Cursief',
- underline: 'Onderstrepen',
- strike: 'Doorhalen',
- clear: 'Stijl verwijderen',
- height: 'Regelhoogte',
- size: 'Tekstgrootte'
- },
- image: {
- image: 'Afbeelding',
- insert: 'Afbeelding invoegen',
- resize_full: 'Volledige breedte',
- resize_half: 'Halve breedte',
- resize_quarter: 'Kwart breedte',
- float_left: 'Links uitlijnen',
- float_right: 'Rechts uitlijnen',
- float_none: 'Geen uitlijning',
- drag_image_here: 'Sleep hier een afbeelding naar toe',
- select_from_files: 'Selecteer een bestand',
- url: 'URL van de afbeelding'
- },
- link: {
- link: 'Link',
- insert: 'Link invoegen',
- unlink: 'Link verwijderen',
- edit: 'Wijzigen',
- text_to_display: 'Tekst van link',
- url: 'Naar welke URL moet deze link verwijzen?'
- },
- table: {
- table: 'Tabel'
- },
- hr: {
- insert: 'Horizontale lijn invoegen'
- },
- style: {
- style: 'Stijl',
- normal: 'Normaal',
- blockquote: 'Quote',
- pre: 'Code',
- h1: 'Kop 1',
- h2: 'Kop 2',
- h3: 'Kop 3',
- h4: 'Kop 4',
- h5: 'Kop 5',
- h6: 'Kop 6'
- },
- lists: {
- unordered: 'Ongeordende lijst',
- ordered: 'Geordende lijst'
- },
- options: {
- help: 'Help',
- fullscreen: 'Volledig scherm',
- codeview: 'Bekijk Code'
- },
- paragraph: {
- paragraph: 'Paragraaf',
- outdent: 'Inspringen verkleinen',
- indent: 'Inspringen vergroten',
- left: 'Links uitlijnen',
- center: 'Centreren',
- right: 'Rechts uitlijnen',
- justify: 'Uitvullen'
- },
- color: {
- recent: 'Recente kleur',
- more: 'Meer kleuren',
- background: 'Achtergrond kleur',
- foreground: 'Tekst kleur',
- transparent: 'Transparant',
- set_transparent: 'Transparant',
- reset: 'Standaard',
- reset_to_default: 'Standaard kleur'
- },
- shortcut: {
- shortcuts: 'Toetsencombinaties',
- close: 'sluiten',
- text_formatting: 'Tekststijlen',
- action: 'Acties',
- paragraph_formatting: 'Paragraafstijlen',
- document_style: 'Documentstijlen'
- },
- history: {
- undo: 'Ongedaan maken',
- redo: 'Opnieuw doorvoeren'
- }
- }
- };
-
- /**
- * Renderer
- *
- * rendering toolbar and editable
- */
- var Renderer = function () {
- /* jshint ignore:start */
- var aToolbarItem = {
- picture: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.image + '" data-event="showImageDialog" tabindex="-1"><i class="fa fa-picture-o icon-picture"></i></button>';
- },
- link: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.link.link + '" data-event="showLinkDialog" data-shortcut="Ctrl+K" data-mac-shortcut="⌘+K" tabindex="-1"><i class="fa fa-link icon-link"></i></button>';
- },
- table: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" title="' + locale.table.table + '" data-toggle="dropdown" tabindex="-1"><i class="fa fa-table icon-table"></i> <span class="caret"></span></button>' +
- '<ul class="dropdown-menu">' +
- '<div class="note-dimension-picker">' +
- '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>' +
- '<div class="note-dimension-picker-highlighted"></div>' +
- '<div class="note-dimension-picker-unhighlighted"></div>' +
- '</div>' +
- '<div class="note-dimension-display"> 1 x 1 </div>' +
- '</ul>';
- },
- style: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" title="' + locale.style.style + '" data-toggle="dropdown" tabindex="-1"><i class="fa fa-magic icon-magic"></i> <span class="caret"></span></button>' +
- '<ul class="dropdown-menu">' +
- '<li><a data-event="formatBlock" data-value="p">' + locale.style.normal + '</a></li>' +
- '<li><a data-event="formatBlock" data-value="blockquote"><blockquote>' + locale.style.blockquote + '</blockquote></a></li>' +
- '<li><a data-event="formatBlock" data-value="pre">' + locale.style.pre + '</a></li>' +
- '<li><a data-event="formatBlock" data-value="h1"><h1>' + locale.style.h1 + '</h1></a></li>' +
- '<li><a data-event="formatBlock" data-value="h2"><h2>' + locale.style.h2 + '</h2></a></li>' +
- '<li><a data-event="formatBlock" data-value="h3"><h3>' + locale.style.h3 + '</h3></a></li>' +
- '<li><a data-event="formatBlock" data-value="h4"><h4>' + locale.style.h4 + '</h4></a></li>' +
- '<li><a data-event="formatBlock" data-value="h5"><h5>' + locale.style.h5 + '</h5></a></li>' +
- '<li><a data-event="formatBlock" data-value="h6"><h6>' + locale.style.h6 + '</h6></a></li>' +
- '</ul>';
- },
- fontsize: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" data-toggle="dropdown" title="' + locale.font.size + '" tabindex="-1"><span class="note-current-fontsize">11</span> <b class="caret"></b></button>' +
- '<ul class="dropdown-menu">' +
- '<li><a data-event="fontSize" data-value="8"><i class="fa fa-check icon-ok"></i> 8</a></li>' +
- '<li><a data-event="fontSize" data-value="9"><i class="fa fa-check icon-ok"></i> 9</a></li>' +
- '<li><a data-event="fontSize" data-value="10"><i class="fa fa-check icon-ok"></i> 10</a></li>' +
- '<li><a data-event="fontSize" data-value="11"><i class="fa fa-check icon-ok"></i> 11</a></li>' +
- '<li><a data-event="fontSize" data-value="12"><i class="fa fa-check icon-ok"></i> 12</a></li>' +
- '<li><a data-event="fontSize" data-value="14"><i class="fa fa-check icon-ok"></i> 14</a></li>' +
- '<li><a data-event="fontSize" data-value="18"><i class="fa fa-check icon-ok"></i> 18</a></li>' +
- '<li><a data-event="fontSize" data-value="24"><i class="fa fa-check icon-ok"></i> 24</a></li>' +
- '<li><a data-event="fontSize" data-value="36"><i class="fa fa-check icon-ok"></i> 36</a></li>' +
- '</ul>';
- },
- color: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small note-recent-color" title="' + locale.color.recent + '" data-event="color" data-value=\'{"backColor":"yellow"}\' tabindex="-1"><i class="fa fa-font icon-font" style="color:black;background-color:yellow;"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" title="' + locale.color.more + '" data-toggle="dropdown" tabindex="-1">' +
- '<span class="caret"></span>' +
- '</button>' +
- '<ul class="dropdown-menu">' +
- '<li>' +
- '<div class="btn-group">' +
- '<div class="note-palette-title">' + locale.color.background + '</div>' +
- '<div class="note-color-reset" data-event="backColor" data-value="inherit" title="' + locale.color.transparent + '">' + locale.color.set_transparent + '</div>' +
- '<div class="note-color-palette" data-target-event="backColor"></div>' +
- '</div>' +
- '<div class="btn-group">' +
- '<div class="note-palette-title">' + locale.color.foreground + '</div>' +
- '<div class="note-color-reset" data-event="foreColor" data-value="inherit" title="' + locale.color.reset + '">' + locale.color.reset_to_default + '</div>' +
- '<div class="note-color-palette" data-target-event="foreColor"></div>' +
- '</div>' +
- '</li>' +
- '</ul>';
- },
- bold: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.font.bold + '" data-shortcut="Ctrl+B" data-mac-shortcut="⌘+B" data-event="bold" tabindex="-1"><i class="fa fa-bold icon-bold"></i></button>';
- },
- italic: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.font.italic + '" data-shortcut="Ctrl+I" data-mac-shortcut="⌘+I" data-event="italic" tabindex="-1"><i class="fa fa-italic icon-italic"></i></button>';
- },
- underline: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.font.underline + '" data-shortcut="Ctrl+U" data-mac-shortcut="⌘+U" data-event="underline" tabindex="-1"><i class="fa fa-underline icon-underline"></i></button>';
- },
- clear: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.font.clear + '" data-shortcut="Ctrl+\\" data-mac-shortcut="⌘+\\" data-event="removeFormat" tabindex="-1"><i class="fa fa-eraser icon-eraser"></i></button>';
- },
- ul: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.lists.unordered + '" data-shortcut="Ctrl+Shift+8" data-mac-shortcut="⌘+⇧+7" data-event="insertUnorderedList" tabindex="-1"><i class="fa fa-list-ul icon-list-ul"></i></button>';
- },
- ol: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.lists.ordered + '" data-shortcut="Ctrl+Shift+7" data-mac-shortcut="⌘+⇧+8" data-event="insertOrderedList" tabindex="-1"><i class="fa fa-list-ol icon-list-ol"></i></button>';
- },
- paragraph: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" title="' + locale.paragraph.paragraph + '" data-toggle="dropdown" tabindex="-1"><i class="fa fa-align-left icon-align-left"></i> <span class="caret"></span></button>' +
- '<ul class="dropdown-menu">' +
- '<li>' +
- '<div class="note-align btn-group">' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.left + '" data-shortcut="Ctrl+Shift+L" data-mac-shortcut="⌘+⇧+L" data-event="justifyLeft" tabindex="-1"><i class="fa fa-align-left icon-align-left"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.center + '" data-shortcut="Ctrl+Shift+E" data-mac-shortcut="⌘+⇧+E" data-event="justifyCenter" tabindex="-1"><i class="fa fa-align-center icon-align-center"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.right + '" data-shortcut="Ctrl+Shift+R" data-mac-shortcut="⌘+⇧+R" data-event="justifyRight" tabindex="-1"><i class="fa fa-align-right icon-align-right"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.justify + '" data-shortcut="Ctrl+Shift+J" data-mac-shortcut="⌘+⇧+J" data-event="justifyFull" tabindex="-1"><i class="fa fa-align-justify icon-align-justify"></i></button>' +
- '</div>' +
- '</li>' +
- '<li>' +
- '<div class="note-list btn-group">' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.outdent + '" data-shortcut="Ctrl+[" data-mac-shortcut="⌘+[" data-event="outdent" tabindex="-1"><i class="fa fa-outdent icon-indent-left"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.paragraph.indent + '" data-shortcut="Ctrl+]" data-mac-shortcut="⌘+]" data-event="indent" tabindex="-1"><i class="fa fa-indent icon-indent-right"></i></button>' +
- '</li>' +
- '</ul>';
- },
- height: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small dropdown-toggle" data-toggle="dropdown" title="' + locale.font.height + '" tabindex="-1"><i class="fa fa-text-height icon-text-height"></i>&nbsp; <b class="caret"></b></button>' +
- '<ul class="dropdown-menu">' +
- '<li><a data-event="lineHeight" data-value="1.0"><i class="fa fa-check icon-ok"></i> 1.0</a></li>' +
- '<li><a data-event="lineHeight" data-value="1.2"><i class="fa fa-check icon-ok"></i> 1.2</a></li>' +
- '<li><a data-event="lineHeight" data-value="1.4"><i class="fa fa-check icon-ok"></i> 1.4</a></li>' +
- '<li><a data-event="lineHeight" data-value="1.5"><i class="fa fa-check icon-ok"></i> 1.5</a></li>' +
- '<li><a data-event="lineHeight" data-value="1.6"><i class="fa fa-check icon-ok"></i> 1.6</a></li>' +
- '<li><a data-event="lineHeight" data-value="1.8"><i class="fa fa-check icon-ok"></i> 1.8</a></li>' +
- '<li><a data-event="lineHeight" data-value="2.0"><i class="fa fa-check icon-ok"></i> 2.0</a></li>' +
- '<li><a data-event="lineHeight" data-value="3.0"><i class="fa fa-check icon-ok"></i> 3.0</a></li>' +
- '</ul>';
- },
- help: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.options.help + '" data-shortcut="Ctrl+/" data-mac-shortcut="⌘+/" data-event="showHelpDialog" tabindex="-1"><i class="fa fa-question icon-question"></i></button>';
- },
- fullscreen: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.options.fullscreen + '" data-event="fullscreen" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>';
- },
- codeview: function(locale) {
- return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.options.codeview + '" data-event="codeview" tabindex="-1"><i class="fa fa-code icon-code"></i></button>';
- }
- };
- var sPopover = function(locale) {
- return '<div class="note-popover">' +
- '<div class="note-link-popover popover bottom in" style="display: none;">' +
- '<div class="arrow"></div>' +
- '<div class="popover-content note-link-content">' +
- '<a href="http://www.google.com" target="_blank">www.google.com</a>&nbsp;&nbsp;' +
- '<div class="note-insert btn-group">' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.link.edit + '" data-event="showLinkDialog" tabindex="-1"><i class="fa fa-edit icon-edit"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.link.unlink + '" data-event="unlink" tabindex="-1"><i class="fa fa-unlink icon-unlink"></i></button>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '<div class="note-image-popover popover bottom in" style="display: none;">' +
- '<div class="arrow"></div>' +
- '<div class="popover-content note-image-content">' +
- '<div class="btn-group">' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.resize_full + '" data-event="resize" data-value="1" tabindex="-1"><span class="note-fontsize-10">100%</span> </button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.resize_half + '" data-event="resize" data-value="0.5" tabindex="-1"><span class="note-fontsize-10">50%</span> </button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.resize_quarter + '" data-event="resize" data-value="0.25" tabindex="-1"><span class="note-fontsize-10">25%</span> </button>' +
- '</div>' +
- '<div class="btn-group">' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.float_left + '" data-event="floatMe" data-value="left" tabindex="-1"><i class="fa fa-align-left icon-align-left"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.float_right + '" data-event="floatMe" data-value="right" tabindex="-1"><i class="fa fa-align-right icon-align-right"></i></button>' +
- '<button type="button" class="btn btn-default btn-sm btn-small" title="' + locale.image.float_none + '" data-event="floatMe" data-value="none" tabindex="-1"><i class="fa fa-align-justify icon-align-justify"></i></button>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '</div>';
- };
-
- var sHandle = '<div class="note-handle">' +
- '<div class="note-control-selection">' +
- '<div class="note-control-selection-bg"></div>' +
- '<div class="note-control-holder note-control-nw"></div>' +
- '<div class="note-control-holder note-control-ne"></div>' +
- '<div class="note-control-holder note-control-sw"></div>' +
- '<div class="note-control-sizing note-control-se"></div>' +
- '<div class="note-control-selection-info"></div>' +
- '</div>' +
- '</div>';
-
- var sShortcutText = function(locale) {
- return '<table class="note-shortcut">' +
- '<thead>' +
- '<tr><th></th><th>' + locale.shortcut.text_formatting + '</th></tr>' +
- '</thead>' +
- '<tbody>' +
- '<tr><td>⌘ + B</td><td>' + locale.font.bold + '</td></tr>' +
- '<tr><td>⌘ + I</td><td>' + locale.font.italic + '</td></tr>' +
- '<tr><td>⌘ + U</td><td>' + locale.font.underline + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + S</td><td>' + locale.font.strike + '</td></tr>' +
- '<tr><td>⌘ + \\</td><td>' + locale.font.clear + '</td></tr>' +
- '</tr>' +
- '</tbody>' +
- '</table>';
- };
-
- var sShortcutAction = function(locale) {
- return '<table class="note-shortcut">' +
- '<thead>' +
- '<tr><th></th><th>' + locale.shortcut.action + '</th></tr>' +
- '</thead>' +
- '<tbody>' +
- '<tr><td>⌘ + Z</td><td>' + locale.history.undo + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + Z</td><td>' + locale.history.redo + '</td></tr>' +
- '<tr><td>⌘ + ]</td><td>' + locale.paragraph.indent + '</td></tr>' +
- '<tr><td>⌘ + [</td><td>' + locale.paragraph.outdent + '</td></tr>' +
- '<tr><td>⌘ + K</td><td>' + locale.link.insert + '</td></tr>' +
- '<tr><td>⌘ + ENTER</td><td>' + locale.hr.insert + '</td></tr>' +
- '</tbody>' +
- '</table>';
- };
-
- var sShortcutPara = function(locale) {
- return '<table class="note-shortcut">' +
- '<thead>' +
- '<tr><th></th><th>' + locale.shortcut.paragraph_formatting + '</th></tr>' +
- '</thead>' +
- '<tbody>' +
- '<tr><td>⌘ + ⇧ + L</td><td>' + locale.paragraph.left + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + E</td><td>' + locale.paragraph.center + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + R</td><td>' + locale.paragraph.right + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + J</td><td>' + locale.paragraph.justify + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + NUM7</td><td>' + locale.lists.ordered + '</td></tr>' +
- '<tr><td>⌘ + ⇧ + NUM8</td><td>' + locale.lists.unordered + '</td></tr>' +
- '</tbody>' +
- '</table>';
- };
-
- var sShortcutStyle = function(locale) {
- return '<table class="note-shortcut">' +
- '<thead>' +
- '<tr><th></th><th>' + locale.shortcut.document_style + '</th></tr>' +
- '</thead>' +
- '<tbody>' +
- '<tr><td>⌘ + NUM0</td><td>' + locale.style.normal + '</td></tr>' +
- '<tr><td>⌘ + NUM1</td><td>' + locale.style.h1 + '</td></tr>' +
- '<tr><td>⌘ + NUM2</td><td>' + locale.style.h2 + '</td></tr>' +
- '<tr><td>⌘ + NUM3</td><td>' + locale.style.h3 + '</td></tr>' +
- '<tr><td>⌘ + NUM4</td><td>' + locale.style.h4 + '</td></tr>' +
- '<tr><td>⌘ + NUM5</td><td>' + locale.style.h5 + '</td></tr>' +
- '<tr><td>⌘ + NUM6</td><td>' + locale.style.h6 + '</td></tr>' +
- '</tbody>' +
- '</table>';
- };
-
- var sShortcutTable = function(locale) {
- return '<table class="note-shortcut-layout">' +
- '<tbody>' +
- '<tr><td>' + sShortcutAction(locale) + '</td><td>' + sShortcutText(locale) + '</td></tr>' +
- '<tr><td>' + sShortcutStyle(locale) + '</td><td>' + sShortcutPara(locale) + '</td></tr>' +
- '</tbody>' +
- '</table>';
- };
-
- var replaceMacKeys = function (sHtml) {
- return sHtml.replace(/⌘/g, 'Ctrl').replace(/⇧/g, 'Shift');
- };
-
- var sDialog = function(locale) {
- return '<div class="note-dialog">' +
- '<div class="note-image-dialog modal" aria-hidden="false">' +
- '<div class="modal-dialog">' +
- '<div class="modal-content">' +
- '<div class="modal-header">' +
- '<button type="button" class="close" aria-hidden="true" tabindex="-1">×</button>' +
- '<h4>' + locale.image.insert + '</h4>' +
- '</div>' +
- '<div class="modal-body">' +
- '<div class="row-fluid">' +
- '<div class="note-dropzone span12">' + locale.image.drag_image_here + '</div>' +
- '<h5>' + locale.image.select_from_files + '</h5>' +
- '<input class="note-image-input" type="file" name="files" accept="image/*" capture="camera" />' +
- '<h5>' + locale.image.url + '</h5>' +
- '<input class="note-image-url form-control span12" type="text" />' +
- '</div>' +
- '</div>' +
- '<div class="modal-footer">' +
- '<button href="#" class="btn btn-primary note-image-btn disabled" disabled="disabled">' + locale.image.insert + '</button>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '<div class="note-link-dialog modal" aria-hidden="false">' +
- '<div class="modal-dialog">' +
- '<div class="modal-content">' +
- '<div class="modal-header">' +
- '<button type="button" class="close" aria-hidden="true" tabindex="-1">×</button>' +
- '<h4>' + locale.link.insert + '</h4>' +
- '</div>' +
- '<div class="modal-body">' +
- '<div class="row-fluid">' +
-
- '<div class="form-group">' +
- '<label>' + locale.link.text_to_display + '</label>' +
- '<span class="note-link-text form-control input-xlarge uneditable-input" />' +
- '</div>' +
- '<div class="form-group">' +
- '<label>' + locale.link.url + '</label>' +
- '<input class="note-link-url form-control span12" type="text" />' +
- '</div>' +
- '</div>' +
- '</div>' +
- '<div class="modal-footer">' +
- '<button href="#" class="btn btn-primary note-link-btn disabled" disabled="disabled">' + locale.link.insert + '</button>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '<div class="note-help-dialog modal" aria-hidden="false">' +
- '<div class="modal-dialog">' +
- '<div class="modal-content">' +
- '<div class="modal-body">' +
- '<div class="modal-background">' +
- '<a class="modal-close pull-right" aria-hidden="true" tabindex="-1">' + locale.shortcut.close + '</a>' +
- '<div class="title">' + locale.shortcut.shortcuts + '</div>' +
- (agent.bMac ? sShortcutTable(locale) : replaceMacKeys(sShortcutTable(locale))) +
- '<p class="text-center"><a href="//hackerwins.github.io/summernote/" target="_blank">Summernote v0.4</a> · <a href="//github.com/HackerWins/summernote" target="_blank">Project</a> · <a href="//github.com/HackerWins/summernote/issues" target="_blank">Issues</a></p>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '</div>' +
- '</div>';
- };
-
- var sStatusbar = '<div class="note-resizebar"><div class="note-icon-bar"></div><div class="note-icon-bar"></div><div class="note-icon-bar"></div></div>';
- /* jshint ignore:end */
-
- // createTooltip
- var createTooltip = function ($container, sPlacement) {
- $container.find('button').each(function (i, elBtn) {
- var $btn = $(elBtn);
- var sShortcut = $btn.attr(agent.bMac ? 'data-mac-shortcut': 'data-shortcut');
- if (sShortcut) { $btn.attr('title', function (i, v) { return v + ' (' + sShortcut + ')'; }); }
- //bootstrap tooltip on btn-group bug: https://github.com/twitter/bootstrap/issues/5687
- }).tooltip({container: 'body', placement: sPlacement || 'top'});
- };
-
- // pallete colors
- var aaColor = [
- ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'],
- ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'],
- ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'],
- ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'],
- ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'],
- ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'],
- ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'],
- ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']
- ];
-
- // createPalette
- var createPalette = function ($container) {
- $container.find('.note-color-palette').each(function () {
- var $palette = $(this), sEvent = $palette.attr('data-target-event');
- var sPaletteContents = '';
- for (var row = 0, szRow = aaColor.length; row < szRow; row++) {
- var aColor = aaColor[row];
- var sLine = '<div>';
- for (var col = 0, szCol = aColor.length; col < szCol; col++) {
- var sColor = aColor[col];
- var sButton = ['<button type="button" class="note-color-btn" style="background-color:', sColor,
- ';" data-event="', sEvent,
- '" data-value="', sColor,
- '" title="', sColor,
- '" data-toggle="button" tabindex="-1"></button>'].join('');
- sLine += sButton;
- }
- sLine += '</div>';
- sPaletteContents += sLine;
- }
- $palette.html(sPaletteContents);
- });
- };
-
- // createLayout
- this.createLayout = function ($holder, options) {
- var nHeight = options.height,
- nTabsize = options.tabsize,
- aToolbarSetting = options.toolbar;
-
- //already created
- if ($holder.next().hasClass('note-editor')) { return; }
-
- //01. create Editor
- var $editor = $('<div class="note-editor"></div>');
- $editor.data('options', options);
-
- //02. statusbar
- if (nHeight > 0) {
- $('<div class="note-statusbar">' + sStatusbar + '</div>').prependTo($editor);
- }
-
- //03. create Editable
- var $editable = $('<div class="note-editable" contentEditable="true"></div>').prependTo($editor);
- if (nHeight) {
- $editable.height(nHeight);
- $editable.data('optionHeight', nHeight);
- }
- if (nTabsize) {
- $editable.data('tabsize', nTabsize);
- }
-
- $editable.html(dom.html($holder) || dom.emptyPara);
- $editable.data('NoteHistory', new History());
-
- //031. create codable
- $('<textarea class="note-codable"></textarea>').prependTo($editor);
-
- //032. set styleWithCSS for backColor / foreColor clearing with 'inherit'.
- setTimeout(function () { // protect FF Error: NS_ERROR_FAILURE: Failure
- document.execCommand('styleWithCSS', 0, true);
- });
-
- //04. create Toolbar
- var sToolbar = '';
- for (var idx = 0, sz = aToolbarSetting.length; idx < sz; idx ++) {
- var group = aToolbarSetting[idx];
- sToolbar += '<div class="note-' + group[0] + ' btn-group">';
- for (var i = 0, szGroup = group[1].length; i < szGroup; i++) {
- sToolbar += aToolbarItem[group[1][i]](Locale[options.locale]);
- }
- sToolbar += '</div>';
- }
-
- sToolbar = '<div class="note-toolbar btn-toolbar">' + sToolbar + '</div>';
-
- var $toolbar = $(sToolbar).prependTo($editor);
- createPalette($toolbar);
- createTooltip($toolbar, 'bottom');
-
- //05. create Popover
- var $popover = $(sPopover(Locale[options.locale])).prependTo($editor);
- createTooltip($popover);
-
- //06. handle(control selection, ...)
- $(sHandle).prependTo($editor);
-
- //07. create Dialog
- var $dialog = $(sDialog(Locale[options.locale])).prependTo($editor);
- $dialog.find('button.close, a.modal-close').click(function () {
- $(this).closest('.modal').modal('hide');
- });
-
- //08. Editor/Holder switch
- $editor.insertAfter($holder);
- $holder.hide();
- };
-
- // layoutInfoFromHolder
- var layoutInfoFromHolder = this.layoutInfoFromHolder = function ($holder) {
- var $editor = $holder.next();
- if (!$editor.hasClass('note-editor')) { return; }
-
- return {
- editor: $editor,
- toolbar: $editor.find('.note-toolbar'),
- editable: $editor.find('.note-editable'),
- codable: $editor.find('.note-codable'),
- statusbar: $editor.find('.note-statusbar'),
- popover: $editor.find('.note-popover'),
- handle: $editor.find('.note-handle'),
- dialog: $editor.find('.note-dialog')
- };
- };
-
- // removeLayout
- this.removeLayout = function ($holder) {
- var info = layoutInfoFromHolder($holder);
- if (!info) { return; }
- $holder.html(info.editable.html());
-
- info.editor.remove();
- $holder.show();
- };
- };
-
- var renderer = new Renderer();
- var eventHandler = new EventHandler();
-
- /**
- * extend jquery fn
- */
- $.fn.extend({
- // create Editor Layout and attach Key and Mouse Event
- summernote: function (options) {
- options = $.extend({
- toolbar: [
- ['style', ['style']],
- ['font', ['bold', 'italic', 'underline', 'clear']],
- ['fontsize', ['fontsize']],
- ['color', ['color']],
- ['para', ['ul', 'ol', 'paragraph']],
- ['height', ['height']],
- ['table', ['table']],
- ['insert', ['link', 'picture']],
- ['view', ['fullscreen', 'codeview']],
- ['help', ['help']]
- ],
- locale: 'en-US'
- }, options);
-
- this.each(function (idx, elHolder) {
- var $holder = $(elHolder);
-
- // createLayout with options
- renderer.createLayout($holder, options);
-
- var info = renderer.layoutInfoFromHolder($holder);
- eventHandler.attach(info, options);
-
- // Textarea auto filling the code before form submit.
- if (dom.isTextarea($holder[0])) {
- $holder.closest('form').submit(function () {
- $holder.html($holder.code());
- });
- }
- });
-
- if (this.first() && options.focus) { // focus on first editable element
- var info = renderer.layoutInfoFromHolder(this.first());
- info.editable.focus();
- }
- if (this.length > 0 && options.oninit) { // callback on init
- options.oninit();
- }
- },
- // get the HTML contents of note or set the HTML contents of note.
- code: function (sHTML) {
- //get the HTML contents
- if (sHTML === undefined) {
- var $holder = this.first();
- if ($holder.length === 0) { return; }
- var info = renderer.layoutInfoFromHolder($holder);
- if (!!(info && info.editable)) {
- var bCodeview = info.editor.hasClass('codeview');
- if (agent.bCodeMirror) {
- info.codable.data('cmEditor').save();
- }
- return bCodeview ? info.codable.val() : info.editable.html();
- }
- return $holder.html();
- }
-
- // set the HTML contents
- this.each(function (i, elHolder) {
- var info = renderer.layoutInfoFromHolder($(elHolder));
- if (info && info.editable) { info.editable.html(sHTML); }
- });
- },
- // destroy Editor Layout and dettach Key and Mouse Event
- destroy: function () {
- this.each(function (idx, elHolder) {
- var $holder = $(elHolder);
-
- var info = renderer.layoutInfoFromHolder($holder);
- if (!info || !info.editable) { return; }
- eventHandler.dettach(info);
- renderer.removeLayout($holder);
- });
- },
- // inner object for test
- summernoteInner: function () {
- return { dom: dom, list: list, func: func, range: range };
- }
- });
-})(window.jQuery, window.CodeMirror); // jQuery, CodeMirror
-
-// Array.prototype.reduce fallback
-// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
-if ('function' !== typeof Array.prototype.reduce) {
- Array.prototype.reduce = function (callback, optInitialValue) {
- 'use strict';
- var idx, value, length = this.length >>> 0, isValueSet = false;
- if (1 < arguments.length) {
- value = optInitialValue;
- isValueSet = true;
- }
- for (idx = 0; length > idx; ++idx) {
- if (this.hasOwnProperty(idx)) {
- if (isValueSet) {
- value = callback(value, this[idx], idx, this);
- } else {
- value = this[idx];
- isValueSet = true;
- }
- }
- }
- if (!isValueSet) {
- throw new TypeError('Reduce of empty array with no initial value');
- }
- return value;
- };
-}
diff --git a/data/ext/viewerImage/extension.js b/data/ext/viewerImage/extension.js
index 632d18686..6249bc976 100644
--- a/data/ext/viewerImage/extension.js
+++ b/data/ext/viewerImage/extension.js
@@ -28,7 +28,7 @@ define(function(require, exports, module) {
require([
extensionDirectory+'/viewerUI.js',
"text!"+extensionDirectory+'/mainUI.html',
- extensionDirectory+'/jquery.panzoom/jquery.panzoom.js',
+ extensionDirectory+'/jquery.panzoom/jquery.panzoom.min.js',
extensionDirectory+'/jquery.mousewheel/jquery.mousewheel.js',
extensionDirectory+'/pixastic/pixastic.custom.js',
], function(extUI, uiTPL) {
diff --git a/data/ext/viewerImage/jquery.panzoom/jquery.panzoom.js b/data/ext/viewerImage/jquery.panzoom/jquery.panzoom.js
deleted file mode 100644
index 19fb773b1..000000000
--- a/data/ext/viewerImage/jquery.panzoom/jquery.panzoom.js
+++ /dev/null
@@ -1,1093 +0,0 @@
-/**
- * @license jquery.panzoom.js v1.8.2
- * Updated: Wed Nov 20 2013
- * Add pan and zoom functionality to any element
- * Copyright (c) 2013 timmy willison
- * Released under the MIT license
- * https://github.com/timmywil/jquery.panzoom/blob/master/MIT-License.txt
- */
-
-(function( global, factory ) {
- // AMD
- if ( typeof define === 'function' && define.amd ) {
- define( [ 'jquery' ], factory );
- // CommonJS/Browserify
- } else if ( typeof exports === 'object' ) {
- factory( require('jquery') );
- // Global
- } else {
- factory( global.jQuery );
- }
-}( this, function( $ ) {
- 'use strict';
-
- // Lift touch properties using fixHooks
- var touchHook = {
- props: [ 'touches', 'pageX', 'pageY' ],
- /**
- * Support: Android
- * Android sets pageX/Y to 0 for any touch event
- * Attach first touch's pageX/pageY if not set correctly
- */
- filter: function( event, originalEvent ) {
- var touch;
- if ( !originalEvent.pageX && originalEvent.touches && (touch = originalEvent.touches[0]) ) {
- event.pageX = touch.pageX;
- event.pageY = touch.pageY;
- }
- return event;
- }
- };
- $.each([ 'touchstart', 'touchmove', 'touchend' ], function( i, name ) {
- $.event.fixHooks[ name ] = touchHook;
- });
-
- var datakey = '__pz__';
- var slice = Array.prototype.slice;
- var rupper = /([A-Z])/g;
- var rsvg = /^http:[\w\.\/]+svg$/;
- var rinline = /^inline/;
-
- var floating = '(\\-?[\\d\\.e]+)';
- var commaSpace = '\\,?\\s*';
- var rmatrix = new RegExp(
- '^matrix\\(' +
- floating + commaSpace +
- floating + commaSpace +
- floating + commaSpace +
- floating + commaSpace +
- floating + commaSpace +
- floating + '\\)$'
- );
-
- /**
- * Creates the options object for reset functions
- * @param {Boolean|Object} opts See reset methods
- * @returns {Object} Returns the newly-created options object
- */
- function createResetOptions( opts ) {
- var options = { range: true, animate: true };
- if ( typeof opts === 'boolean' ) {
- options.animate = opts;
- } else {
- $.extend( options, opts );
- }
- return options;
- }
-
- /**
- * Represent a transformation matrix with a 3x3 matrix for calculations
- * Matrix functions adapted from Louis Remi's jQuery.transform (https://github.com/louisremi/jquery.transform.js)
- * @param {Array|Number} a An array of six values representing a 2d transformation matrix
- */
- function Matrix( a, b, c, d, e, f, g, h, i ) {
- if ( $.type(a) === 'array' ) {
- this.elements = [
- +a[0], +a[2], +a[4],
- +a[1], +a[3], +a[5],
- 0, 0, 1
- ];
- } else {
- this.elements = [
- a, b, c,
- d, e, f,
- g || 0, h || 0, i || 1
- ];
- }
- }
-
- Matrix.prototype = {
- /**
- * Multiply a 3x3 matrix by a similar matrix or a vector
- * @param {Matrix|Vector} matrix
- * @return {Matrix|Vector} Returns a vector if multiplying by a vector
- */
- x: function( matrix ) {
- var isVector = matrix instanceof Vector;
-
- var a = this.elements,
- b = matrix.elements;
-
- if ( isVector && b.length === 3 ) {
- // b is actually a vector
- return new Vector(
- a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
- a[3] * b[0] + a[4] * b[1] + a[5] * b[2],
- a[6] * b[0] + a[7] * b[1] + a[8] * b[2]
- );
- } else if ( b.length === a.length ) {
- // b is a 3x3 matrix
- return new Matrix(
- a[0] * b[0] + a[1] * b[3] + a[2] * b[6],
- a[0] * b[1] + a[1] * b[4] + a[2] * b[7],
- a[0] * b[2] + a[1] * b[5] + a[2] * b[8],
-
- a[3] * b[0] + a[4] * b[3] + a[5] * b[6],
- a[3] * b[1] + a[4] * b[4] + a[5] * b[7],
- a[3] * b[2] + a[4] * b[5] + a[5] * b[8],
-
- a[6] * b[0] + a[7] * b[3] + a[8] * b[6],
- a[6] * b[1] + a[7] * b[4] + a[8] * b[7],
- a[6] * b[2] + a[7] * b[5] + a[8] * b[8]
- );
- }
- return false; // fail
- },
- /**
- * Generates an inverse of the current matrix
- * @returns {Matrix}
- */
- inverse: function() {
- var d = 1 / this.determinant(),
- a = this.elements;
- return new Matrix(
- d * ( a[8] * a[4] - a[7] * a[5]),
- d * (-(a[8] * a[1] - a[7] * a[2])),
- d * ( a[5] * a[1] - a[4] * a[2]),
-
- d * (-(a[8] * a[3] - a[6] * a[5])),
- d * ( a[8] * a[0] - a[6] * a[2]),
- d * (-(a[5] * a[0] - a[3] * a[2])),
-
- d * ( a[7] * a[3] - a[6] * a[4]),
- d * (-(a[7] * a[0] - a[6] * a[1])),
- d * ( a[4] * a[0] - a[3] * a[1])
- );
- },
- /**
- * Calculates the determinant of the current matrix
- * @returns {Number}
- */
- determinant: function() {
- var a = this.elements;
- return a[0] * (a[8] * a[4] - a[7] * a[5]) - a[3] * (a[8] * a[1] - a[7] * a[2]) + a[6] * (a[5] * a[1] - a[4] * a[2]);
- }
- };
-
- /**
- * Create a vector containing three values
- */
- function Vector( x, y, z ) {
- this.elements = [ x, y, z ];
- }
-
- /**
- * Get the element at zero-indexed index i
- * @param {Number} i
- */
- Vector.prototype.e = Matrix.prototype.e = function( i ) {
- return this.elements[ i ];
- };
-
- /**
- * Create a Panzoom object for a given element
- * @constructor
- * @param {Element} elem - Element to use pan and zoom
- * @param {Object} [options] - An object literal containing options to override default options
- * (See Panzoom.defaults for ones not listed below)
- * @param {jQuery} [options.$zoomIn] - zoom in buttons/links collection (you can also bind these yourself
- * e.g. $button.on('click', function( e ) { e.preventDefault(); $elem.panzooom('zoomIn'); }); )
- * @param {jQuery} [options.$zoomOut] - zoom out buttons/links collection on which to bind zoomOut
- * @param {jQuery} [options.$zoomRange] - zoom in/out with this range control
- * @param {jQuery} [options.$reset] - Reset buttons/links collection on which to bind the reset method
- * @param {Function} [options.on[Start|Change|Zoom|Pan|End|Reset] - Optional callbacks for panzoom events
- */
- function Panzoom( elem, options ) {
-
- // Sanity checks
- if ( elem.nodeType !== 1 ) {
- $.error('Panzoom called on non-Element node');
- }
- if ( !$.contains(document, elem) ) {
- $.error('Panzoom element must be attached to the document');
- }
-
- // Don't remake
- var d = $.data( elem, datakey );
- if ( d ) {
- return d;
- }
-
- // Allow instantiation without `new` keyword
- if ( !(this instanceof Panzoom) ) {
- return new Panzoom( elem, options );
- }
-
- // Extend default with given object literal
- // Each instance gets its own options
- this.options = options = $.extend( {}, Panzoom.defaults, options );
- this.elem = elem;
- var $elem = this.$elem = $(elem);
- this.$doc = $(elem.ownerDocument || document);
- this.$parent = $elem.parent();
-
- // This is SVG if the namespace is SVG
- // However, while <svg> elements are SVG, we want to treat those like other elements
- this.isSVG = rsvg.test( elem.namespaceURI ) && elem.nodeName.toLowerCase() !== 'svg';
-
- this.panning = false;
-
- // Save the original transform value
- // Save the prefixed transform style key
- // Set the starting transform
- this._buildTransform();
-
- // Build the appropriately-prefixed transform style property name
- // De-camelcase
- // Transitioning the attribute for SVG doesn't apply
- if ( !this.isSVG ) {
- this._transform = $.cssProps.transform.replace( rupper, '-$1' ).toLowerCase();
- }
-
- // Build the transition value
- this._buildTransition();
-
- // Build containment dimensions
- this.resetDimensions();
-
- // Add zoom and reset buttons to `this`
- var $empty = $();
- var self = this;
- $.each([ '$zoomIn', '$zoomOut', '$zoomRange', '$reset' ], function( i, name ) {
- self[ name ] = options[ name ] || $empty;
- });
-
- this.enable();
-
- // Save the instance
- $.data( elem, datakey, this );
- }
-
- // Attach regex for possible use (immutable)
- Panzoom.rmatrix = rmatrix;
-
- Panzoom.defaults = {
- // Should always be non-empty
- // Used to bind jQuery events without collisions
- // A guid is not added here as different instantiations/versions of panzoom
- // on the same element is not supported, so don't do it.
- eventNamespace: '.panzoom',
-
- // Whether or not to transition the scale
- transition: true,
-
- // Default cursor style for the element
- cursor: 'move',
-
- // There may be some use cases for zooming without panning or vice versa
- disablePan: false,
- disableZoom: false,
-
- // The increment at which to zoom
- // adds/subtracts to the scale each time zoomIn/Out is called
- increment: 0.3,
-
- minScale: 0.4,
- maxScale: 5,
-
- // The default step for the range input
- // Precendence: default < HTML attribute < option setting
- rangeStep: 0.05,
-
- // Animation duration (ms)
- duration: 200,
- // CSS easing used for scale transition
- easing: 'ease-in-out',
-
- // Indicate that the element should be contained within it's parent when panning
- // Note: this does not affect zooming outside of the parent
- // Set this value to 'invert' to only allow panning outside of the parent element (basically the opposite of the normal use of contain)
- // 'invert' is useful for a large panzoom element where you don't want to show anything behind it
- contain: false
- };
-
- Panzoom.prototype = {
- constructor: Panzoom,
-
- /**
- * @returns {Panzoom} Returns the instance
- */
- instance: function() {
- return this;
- },
-
- /**
- * Enable or re-enable the panzoom instance
- */
- enable: function() {
- // Unbind first
- this._initStyle();
- this._bind();
- this.disabled = false;
- },
-
- /**
- * Disable panzoom
- */
- disable: function() {
- this.disabled = true;
- this._resetStyle();
- this._unbind();
- },
-
- /**
- * @returns {Boolean} Returns whether the current panzoom instance is disabled
- */
- isDisabled: function() {
- return this.disabled;
- },
-
- /**
- * Destroy the panzoom instance
- */
- destroy: function() {
- this.disable();
- $.removeData( this.elem, datakey );
- },
-
- /**
- * Builds the restricing dimensions from the containment element
- * Also used with focal points
- * Call this method whenever the dimensions of the element or parent are changed
- */
- resetDimensions: function() {
- // Reset container properties
- var $parent = this.$parent;
- this.container = {
- width: $parent.width(),
- height: $parent.height()
- };
- var elem = this.elem;
- var $elem = this.$elem;
- var dims = this.dimensions = this.isSVG ? {
- left: elem.getAttribute('x') || 0,
- top: elem.getAttribute('y') || 0,
- width: elem.getAttribute('width') || $elem.outerWidth(),
- height: elem.getAttribute('height') || $elem.outerHeight()
- } : {
- left: $.css( elem, 'left', true ) || 0,
- top: $.css( elem, 'top', true ) || 0,
- width: $elem.outerWidth(),
- height: $elem.outerHeight()
- };
- dims.widthBorder = ($.css( elem, 'borderLeftWidth', true ) + $.css( elem, 'borderRightWidth', true )) || 0;
- dims.heightBorder = ($.css( elem, 'borderTopWidth', true ) + $.css( elem, 'borderBottomWidth', true )) || 0;
- },
-
- /**
- * Return the element to it's original transform matrix
- * @param {Boolean} [options] If a boolean is passed, animate the reset (default: true). If an options object is passed, simply pass that along to setMatrix.
- * @param {Boolean} [options.silent] Silence the reset event
- */
- reset: function( options ) {
- options = createResetOptions( options );
- // Reset the transform to its original value
- var matrix = this.setMatrix( this._origTransform, options );
- if ( !options.silent ) {
- this._trigger( 'reset', matrix );
- }
- },
-
- /**
- * Only resets zoom level
- * @param {Boolean|Object} [options] Whether to animate the reset (default: true) or an object of options to pass to zoom()
- */
- resetZoom: function( options ) {
- options = createResetOptions( options );
- var origMatrix = this.getMatrix( this._origTransform );
- options.dValue = origMatrix[ 3 ];
- this.zoom( origMatrix[0], options );
- },
-
- /**
- * Only reset panning
- * @param {Boolean|Object} [options] Whether to animate the reset (default: true) or an object of options to pass to pan()
- */
- resetPan: function( options ) {
- var origMatrix = this.getMatrix( this._origTransform );
- this.pan( origMatrix[4], origMatrix[5], createResetOptions(options) );
- },
-
- /**
- * Retrieving the transform is different for SVG (unless a style transform is already present)
- * @param {String} [transform] Pass in an transform value (like 'scale(1.1)') to have it formatted into matrix format for use by Panzoom
- * @returns {String} Returns the current transform value of the element
- */
- getTransform: function( transform ) {
- var elem = this.elem;
- var method = this.isSVG ? 'attr' : 'style';
- if ( transform ) {
- // Set the passed in value
- $[ method ]( elem, 'transform', transform );
- } else {
- // Use style rather than computed
- // If currently transitioning, computed transform might be unchanged
- // Retrieve with attr for SVG
- transform = $[ method ]( elem, 'transform' );
- }
-
- // Convert any transforms set by the user to matrix format
- // by setting to computed
- if ( transform !== 'none' && !rmatrix.test(transform) && !this.isSVG ) {
- // Get computed
- transform = $.css( elem, 'transform' );
- // Set for next time
- $.style( elem, 'transform', transform );
- }
-
- return transform || 'none';
- },
-
- /**
- * Retrieve the current transform matrix for $elem (or turn a transform into it's array values)
- * @param {String} [transform] matrix-formatted transform value
- * @returns {Array} Returns the current transform matrix split up into it's parts, or a default matrix
- */
- getMatrix: function( transform ) {
- var matrix = rmatrix.exec( transform || this.getTransform() );
- if ( matrix ) {
- matrix.shift();
- }
- return matrix || [ 1, 0, 0, 1, 0, 0 ];
- },
-
- /**
- * Given a matrix object, quickly set the current matrix of the element
- * @param {Array|String} matrix
- * @param {Boolean} [animate] Whether to animate the transform change
- * @param {Object} [options]
- * @param {Boolean|String} [options.animate] Whether to animate the transform change, or 'skip' indicating that it is unnecessary to set
- * @param {Boolean} [options.contain] Override the global contain option
- * @param {Boolean} [options.range] If true, $zoomRange's value will be updated.
- * @param {Boolean} [options.silent] If true, the change event will not be triggered
- * @returns {Array} Returns the newly-set matrix
- */
- setMatrix: function( matrix, options ) {
- if ( this.disabled ) { return; }
- if ( !options ) { options = {}; }
- // Convert to array
- if ( typeof matrix === 'string' ) {
- matrix = this.getMatrix( matrix );
- }
- var dims, container, marginW, marginH, diffW, diffH;
- var scale = +matrix[0];
- var $parent = this.$parent;
- var elem = this.elem;
- var contain = typeof options.contain !== 'undefined' ? options.contain : this.options.contain;
-
- // Apply containment
- if ( contain ) {
- dims = this._checkDims();
- container = this.container;
- marginW = ((dims.width * scale) - container.width) / 2;
- marginH = ((dims.height * scale) - container.height) / 2;
- if ( contain === 'invert' ) {
- diffW = dims.width > container.width ? dims.width - container.width : 0;
- diffH = dims.height > container.height ? dims.height - container.height : 0;
- marginW += (container.width - dims.width) / 2;
- marginH += (container.height - dims.height) / 2;
- matrix[4] = Math.max( Math.min( matrix[4], marginW - dims.left ), -marginW - dims.left - diffW );
- matrix[5] = Math.max( Math.min( matrix[5], marginH - dims.top ), -marginH - dims.top - diffH + dims.heightBorder );
- } else {
- diffH = container.height > dims.height ? container.height - dims.height : 0;
- // If the element is not naturally centered, assume full margin right
- if ( $parent.css('textAlign') !== 'center' || !rinline.test($.css(elem, 'display')) ) {
- diffW = container.width > dims.width ? container.width - dims.width : 0;
- marginW = marginH = 0;
- } else {
- diffW = 0;
- }
- matrix[4] = Math.min(
- Math.max( matrix[4], marginW - dims.left ),
- -marginW - dims.left + diffW
- );
- matrix[5] = Math.min(
- Math.max( matrix[5], marginH - dims.top ),
- -marginH - dims.top + diffH
- );
- }
- }
- if ( options.animate !== 'skip' ) {
- // Set transition
- this.transition( !options.animate );
- }
- // Update range
- if ( options.range ) {
- this.$zoomRange.val( scale );
- }
- $[ this.isSVG ? 'attr' : 'style' ]( elem, 'transform', 'matrix(' + matrix.join(',') + ')' );
- if ( !options.silent ) {
- this._trigger( 'change', matrix );
- }
-
- return matrix;
- },
-
- /**
- * @returns {Boolean} Returns whether the panzoom element is currently being dragged
- */
- isPanning: function() {
- return this.panning;
- },
-
- /**
- * Apply the current transition to the element, if allowed
- * @param {Boolean} [off] Indicates that the transition should be turned off
- */
- transition: function( off ) {
- var transition = off || !this.options.transition ? 'none' : this._transition;
- // Avoid reflows when zooming
- if ( $.style( this.elem, 'transition') !== transition ) {
- $.style( this.elem, 'transition', transition );
- }
- },
-
- /**
- * Pan the element to the specified translation X and Y
- * Note: this is not the same as setting jQuery#offset() or jQuery#position()
- * @param {Number} x
- * @param {Number} y
- * @param {Object} [options] These options are passed along to setMatrix
- * @param {Array} [options.matrix] The matrix being manipulated (if already known so it doesn't have to be retrieved again)
- * @param {Boolean} [options.silent] Silence the pan event. Note that this will also silence the setMatrix change event.
- * @param {Boolean} [options.relative] Make the x and y values relative to the existing matrix
- */
- pan: function( x, y, options ) {
- if ( this.options.disablePan ) { return; }
- if ( !options ) { options = {}; }
- var matrix = options.matrix;
- if ( !matrix ) {
- matrix = this.getMatrix();
- }
- // Cast existing matrix values to numbers
- if ( options.relative ) {
- matrix[4] = +matrix[4] + x;
- matrix[5] = +matrix[5] + y;
- } else {
- matrix[4] = x;
- matrix[5] = y;
- }
- this.setMatrix( matrix, options );
- if ( !options.silent ) {
- this._trigger( 'pan', x, y );
- }
- },
-
- /**
- * Zoom in/out the element using the scale properties of a transform matrix
- * @param {Number|Boolean} [scale] The scale to which to zoom or a boolean indicating to transition a zoom out
- * @param {Object} [opts] All global options can be overwritten by this options object. For example, override the default increment.
- * @param {Boolean} [opts.noSetRange] Specify that the method should not set the $zoomRange value (as is the case when $zoomRange is calling zoom on change)
- * @param {jQuery.Event|Object} [opts.focal] A focal point on the panzoom element on which to zoom.
- * If an object, set the clientX and clientY properties to the position relative to the parent
- * @param {Boolean} [opts.animate] Whether to animate the zoom (defaults to true if scale is not a number, false otherwise)
- * @param {Boolean} [opts.silent] Silence the zoom event
- * @param {Array} [opts.matrix] Optionally pass the current matrix so it doesn't need to be retrieved
- * @param {Number} [opts.dValue] Think of a transform matrix as four values a, b, c, d
- * where a/d are the horizontal/vertical scale values and b/c are the skew values
- * (5 and 6 of matrix array are the tx/ty transform values).
- * Normally, the scale is set to both the a and d values of the matrix.
- * This option allows you to specify a different d value for the zoom.
- * For instance, to flip vertically, you could set -1 as the dValue.
- */
- zoom: function( scale, opts ) {
- // Shuffle arguments
- if ( typeof scale === 'object' ) {
- opts = scale;
- scale = null;
- } else if ( !opts ) {
- opts = {};
- }
- var options = $.extend( {}, this.options, opts );
- // Check if disabled
- if ( options.disableZoom ) { return; }
- var animate = false;
- var matrix = options.matrix || this.getMatrix();
-
- // Calculate zoom based on increment
- if ( typeof scale !== 'number' ) {
- scale = +matrix[0] + (options.increment * (scale ? -1 : 1));
- animate = true;
- }
-
- // Constrain scale
- if ( scale > options.maxScale ) {
- scale = options.maxScale;
- } else if ( scale < options.minScale ) {
- scale = options.minScale;
- }
-
- // Calculate focal point based on scale
- var focal = options.focal;
- if ( focal && !options.disablePan ) {
- // animate isn't necessary for focal point use cases
- animate = false;
- // Adapted from code by Florian Günther
- // https://github.com/florianguenther/zui53
- // Adjusts the focal point for default transform-origin => 50% 50%
- var dims = this._checkDims();
- var clientX = focal.clientX - dims.width / 2;
- var clientY = focal.clientY - dims.height / 2;
- var clientV = new Vector( clientX, clientY, 1 );
- var surfaceM = new Matrix( matrix );
- var o = this.$parent.offset();
- var offsetM = new Matrix( 1, 0, o.left - this.$doc.scrollLeft(), 0, 1, o.top - this.$doc.scrollTop() );
- var surfaceV = surfaceM.inverse().x( offsetM.inverse().x(clientV) );
- var scaleBy = scale / matrix[0];
- surfaceM = surfaceM.x( new Matrix([ scaleBy, 0, 0, scaleBy, 0, 0 ]) );
- clientV = offsetM.x( surfaceM.x( surfaceV ) );
- matrix[4] = +matrix[4] + (clientX - clientV.e(0));
- matrix[5] = +matrix[5] + (clientY - clientV.e(1));
- }
-
- // Set the scale
- matrix[0] = scale;
- matrix[3] = typeof options.dValue === 'number' ? options.dValue : scale;
-
- // Calling zoom may still pan the element
- this.setMatrix( matrix, {
- animate: typeof options.animate === 'boolean' ? options.animate : animate,
- // Set the zoomRange value
- range: !options.noSetRange
- });
-
- // Trigger zoom event
- if ( !options.silent ) {
- this._trigger( 'zoom', scale, options );
- }
- },
-
- /**
- * Get/set option on an existing instance
- * @returns {Array|undefined} If getting, returns an array of all values
- * on each instance for a given key. If setting, continue chaining by returning undefined.
- */
- option: function( key, value ) {
- var options;
- if ( !key ) {
- // Avoids returning direct reference
- return $.extend( {}, this.options );
- }
-
- if ( typeof key === 'string' ) {
- if ( arguments.length === 1 ) {
- return this.options[ key ] !== undefined ?
- this.options[ key ] :
- null;
- }
- options = {};
- options[ key ] = value;
- } else {
- options = key;
- }
-
- this._setOptions( options );
- },
-
- /**
- * Internally sets options
- * @param {Object} options - An object literal of options to set
- */
- _setOptions: function( options ) {
- var self = this;
- $.each( options, function( key, value ) {
- switch( key ) {
- case 'disablePan':
- self._resetStyle();
- /* falls through */
- case 'disableZoom':
- case '$zoomIn':
- case '$zoomOut':
- case '$zoomRange':
- case '$reset':
- case 'onStart':
- case 'onChange':
- case 'onZoom':
- case 'onPan':
- case 'onEnd':
- case 'onReset':
- case 'eventNamespace':
- self._unbind();
- }
- self.options[ key ] = value;
- switch( key ) {
- case 'disablePan':
- self._initStyle();
- /* falls through */
- case 'disableZoom':
- case '$zoomIn':
- case '$zoomOut':
- case '$zoomRange':
- case '$reset':
- case 'onStart':
- case 'onChange':
- case 'onZoom':
- case 'onPan':
- case 'onEnd':
- case 'onReset':
- case 'eventNamespace':
- self._bind();
- break;
- case 'cursor':
- $.style( self.elem, 'cursor', value );
- break;
- case 'minScale':
- self.$zoomRange.attr( 'min', value );
- break;
- case 'maxScale':
- self.$zoomRange.attr( 'max', value );
- break;
- case 'rangeStep':
- self.$zoomRange.attr( 'step', value );
- break;
- case 'startTransform':
- self._buildTransform();
- break;
- case 'duration':
- case 'easing':
- self._buildTransition();
- /* falls through */
- case 'transition':
- self.transition();
- }
- });
- },
-
- /**
- * Initialize base styles for the element and its parent
- */
- _initStyle: function() {
- // Set elem styles
- if ( !this.options.disablePan ) {
- this.$elem.css( 'cursor', this.options.cursor );
- }
-
- // Set parent to relative if set to static
- var $parent = this.$parent;
- // No need to add styles to the body
- if ( $parent.length && !$.nodeName($parent[0], 'body') ) {
- var parentStyles = {
- overflow: 'hidden'
- };
- if ( $parent.css('position') === 'static' ) {
- parentStyles.position = 'relative';
- }
- $parent.css( parentStyles );
- }
- },
-
- /**
- * Undo any styles attached in this plugin
- */
- _resetStyle: function() {
- this.$elem.css({
- 'cursor': '',
- 'transition': ''
- });
- this.$parent.css({
- 'overflow': '',
- 'position': ''
- });
- },
-
- /**
- * Binds all necessary events
- */
- _bind: function() {
- var self = this;
- var options = this.options;
- var ns = options.eventNamespace;
- var str_start = 'touchstart' + ns + ' mousedown' + ns;
- var str_click = 'touchend' + ns + ' click' + ns;
- var events = {};
- var $reset = this.$reset;
- var $zoomRange = this.$zoomRange;
-
- // Bind panzoom events from options
- $.each([ 'Start', 'Change', 'Zoom', 'Pan', 'End', 'Reset' ], function() {
- var m = options[ 'on' + this ];
- if ( $.isFunction(m) ) {
- events[ 'panzoom' + this.toLowerCase() + ns ] = m;
- }
- });
-
- // Bind $elem drag and click/touchdown events
- // Bind touchstart if either panning or zooming is enabled
- if ( !options.disablePan || !options.disableZoom ) {
- events[ str_start ] = function( e ) {
- var touches;
- if ( e.type === 'mousedown' ?
- // Ignore right click when handling a click
- !options.disablePan && e.which === 1 :
- // Touch
- (touches = e.touches) && ((touches.length === 1 && !options.disablePan) || touches.length === 2) ) {
-
- e.preventDefault();
- e.stopPropagation();
- self._startMove( e, touches );
- }
- };
- }
- this.$elem.on( events );
-
- // Bind reset
- if ( $reset.length ) {
- $reset.on( str_click, function( e ) { e.preventDefault(); self.reset(); });
- }
-
- // Set default attributes for the range input
- if ( $zoomRange.length ) {
- $zoomRange.attr({
- // Only set the range step if explicit or
- // set the default if there is no attribute present
- step: options.rangeStep === Panzoom.defaults.rangeStep &&
- $zoomRange.attr('step') ||
- options.rangeStep,
- min: options.minScale,
- max: options.maxScale
- }).prop({
- value: this.getMatrix()[0]
- });
- }
-
- // No bindings if zooming is disabled
- if ( options.disableZoom ) {
- return;
- }
-
- var $zoomIn = this.$zoomIn;
- var $zoomOut = this.$zoomOut;
-
- // Bind zoom in/out
- // Don't bind one without the other
- if ( $zoomIn.length && $zoomOut.length ) {
- // preventDefault cancels future mouse events on touch events
- $zoomIn.on( str_click, function( e ) { e.preventDefault(); self.zoom(); });
- $zoomOut.on( str_click, function( e ) { e.preventDefault(); self.zoom( true ); });
- }
-
- if ( $zoomRange.length ) {
- events = {};
- // Cannot prevent default action here, just use mousedown event
- events[ 'mousedown' + ns ] = function() {
- self.transition( true );
- };
- events[ 'change' + ns ] = function() {
- self.zoom( +this.value, { noSetRange: true } );
- };
- $zoomRange.on( events );
- }
- },
-
- /**
- * Unbind all events
- */
- _unbind: function() {
- this.$elem
- .add( this.$zoomIn )
- .add( this.$zoomOut )
- .add( this.$reset )
- .off( this.options.eventNamespace );
- },
-
- /**
- * Builds the original transform value
- */
- _buildTransform: function() {
- // Save the original transform
- // Retrieving this also adds the correct prefixed style name
- // to jQuery's internal $.cssProps
- return this._origTransform = this.getTransform( this.options.startTransform );
- },
-
- /**
- * Set transition property for later use when zooming
- * If SVG, create necessary animations elements for translations and scaling
- */
- _buildTransition: function() {
- var options = this.options;
- if ( this._transform ) {
- this._transition = this._transform + ' ' + options.duration + 'ms ' + options.easing;
- }
- },
-
- /**
- * Checks dimensions to make sure they don't need to be re-calculated
- */
- _checkDims: function() {
- var dims = this.dimensions;
- // Rebuild if width or height is still 0
- if ( dims.width === dims.widthBorder || dims.height === dims.heightBorder ) {
- this.resetDimensions();
- }
- return this.dimensions;
- },
-
- /**
- * Calculates the distance between two touch points
- * Remember pythagorean?
- * @param {Array} touches
- * @returns {Number} Returns the distance
- */
- _getDistance: function( touches ) {
- var touch1 = touches[0];
- var touch2 = touches[1];
- return Math.sqrt( Math.pow(Math.abs( touch2.clientX - touch1.clientX ), 2) + Math.pow(Math.abs( touch2.clientY - touch1.clientY ), 2) );
- },
-
- /**
- * Constructs an approximated point in the middle of two touch points
- * @returns {Object} Returns an object containing pageX and pageY
- */
- _getMiddle: function( touches ) {
- var touch1 = touches[0];
- var touch2 = touches[1];
- return {
- clientX: ((touch2.clientX - touch1.clientX) / 2) + touch1.clientX,
- clientY: ((touch2.clientY - touch1.clientY) / 2) + touch1.clientY
- };
- },
-
- /**
- * Trigger a panzoom event on our element
- * The event is passed the Panzoom instance
- * @param {String|jQuery.Event} event
- * @param {Mixed} arg1[, arg2, arg3, ...] Arguments to append to the trigger
- */
- _trigger: function ( event ) {
- if ( typeof event === 'string' ) {
- event = 'panzoom' + event;
- }
- this.$elem.triggerHandler( event, [this].concat(slice.call( arguments, 1 )) );
- },
-
- /**
- * Starts the pan
- * This is bound to mouse/touchmove on the element
- * @param {jQuery.Event} event An event with pageX, pageY, and possibly the touches list
- * @param {TouchList} [touches] The touches list if present
- */
- _startMove: function( event, touches ) {
- var move,
- startDistance, startScale, startMiddle,
- startPageX, startPageY;
- var self = this;
- var options = this.options;
- var isTouch = event.type === 'touchstart';
- var ns = options.eventNamespace;
- var moveEvent = (isTouch ? 'touchmove' : 'mousemove') + ns;
- var endEvent = (isTouch ? 'touchend' : 'mouseup') + ns;
- var matrix = this.getMatrix();
- var original = matrix.slice( 0 );
- var origPageX = +original[4];
- var origPageY = +original[5];
- var panOptions = { matrix: matrix, animate: 'skip' };
-
- // Remove any transitions happening
- this.transition( true );
-
- // Indicate that we are currently panning
- this.panning = true;
-
- // Trigger start event
- this._trigger( 'start', event, touches );
-
- if ( touches && touches.length === 2 ) {
- startDistance = this._getDistance( touches );
- startScale = +matrix[0];
- startMiddle = this._getMiddle( touches );
- move = function( e ) {
- e.preventDefault();
-
- // Calculate move on middle point
- var middle = self._getMiddle( touches = e.touches );
- var diff = self._getDistance( touches ) - startDistance;
-
- // Set zoom
- self.zoom( diff * (options.increment / 100) + startScale, { focal: middle, matrix: matrix } );
-
- // Set pan
- self.pan(
- +matrix[4] + middle.clientX - startMiddle.clientX,
- +matrix[5] + middle.clientY - startMiddle.clientY,
- panOptions
- );
- startMiddle = middle;
- };
- } else {
- startPageX = event.pageX;
- startPageY = event.pageY;
-
- /**
- * Mousemove/touchmove function to pan the element
- * @param {Object} e Event object
- */
- move = function( e ) {
- e.preventDefault();
- self.pan(
- origPageX + e.pageX - startPageX,
- origPageY + e.pageY - startPageY,
- panOptions
- );
- };
- }
-
- // Bind the handlers
- $(document)
- .off( ns )
- .on( moveEvent, move )
- .on( endEvent, function( e ) {
- e.preventDefault();
- $(this).off( ns );
- self.panning = false;
- // Trigger our end event
- // Simply set the type to "panzoomend" to pass through all end properties
- // jQuery's `not` is used here to compare Array equality
- e.type = 'panzoomend';
- self._trigger( e, matrix, !!$(original).not(matrix).length );
- });
- }
- };
-
- /**
- * Extend jQuery
- * @param {Object|String} options - The name of a method to call on the prototype
- * or an object literal of options
- * @returns {jQuery|Mixed} jQuery instance for regular chaining or the return value(s) of a panzoom method call
- */
- $.fn.panzoom = function( options ) {
- var instance, args, m, ret;
-
- // Call methods widget-style
- if ( typeof options === 'string' ) {
- ret = [];
- args = slice.call( arguments, 1 );
- this.each(function() {
- instance = $.data( this, datakey );
-
- if ( !instance ) {
- ret.push( undefined );
-
- // Ignore methods beginning with `_`
- } else if ( options.charAt(0) !== '_' &&
- typeof (m = instance[ options ]) === 'function' &&
- // If nothing is returned, do not add to return values
- (m = m.apply( instance, args )) !== undefined ) {
-
- ret.push( m );
- }
- });
-
- // Return an array of values for the jQuery instances
- // Or the value itself if there is only one
- // Or keep chaining
- return ret.length ?
- (ret.length === 1 ? ret[0] : ret) :
- this;
- }
-
- return this.each(function() { new Panzoom( this, options ); });
- };
-
- return Panzoom;
-}));
diff --git a/data/js/core.ui.js b/data/js/core.ui.js
index 7f276841a..0d7f44a22 100644
--- a/data/js/core.ui.js
+++ b/data/js/core.ui.js
@@ -8,8 +8,6 @@ define(function(require, exports, module) {
var TSCORE = require("tscore");
- var jsonEditor = undefined;
-
var fileContent = undefined;
var fileType = undefined;
diff --git a/data/js/settings.default.js b/data/js/settings.default.js
index 85598398f..717a48df8 100644
--- a/data/js/settings.default.js
+++ b/data/js/settings.default.js
@@ -7,7 +7,7 @@ define(function(require, exports, module) {
exports.defaultSettings = {
"appName": "TagSpaces",
"appVersion": "1.7",
- "appBuild": "1819",
+ "appBuild": "1850",
"settingsVersion": 2,
"newTextFileContent": "Text file created with TagSpaces!",
"newHTMLFileContent": "<html><head><title>Created with TagSpaces!</title></head><body>Feel free to change this text...</body></html>",
diff --git a/data/libs/bootstrap/js/bootstrap.js b/data/libs/bootstrap/js/bootstrap.js
deleted file mode 100644
index 850e6e53b..000000000
--- a/data/libs/bootstrap/js/bootstrap.js
+++ /dev/null
@@ -1,2006 +0,0 @@
-/*!
- * Bootstrap v3.0.3 (http://getbootstrap.com)
- * Copyright 2013 Twitter, Inc.
- * Licensed under http://www.apache.org/licenses/LICENSE-2.0
- */
-
-if (typeof jQuery === "undefined") { throw new Error("Bootstrap requires jQuery") }
-
-/* ========================================================================
- * Bootstrap: transition.js v3.0.3
- * http://getbootstrap.com/javascript/#transitions
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
- // ============================================================
-
- function transitionEnd() {
- var el = document.createElement('bootstrap')
-
- var transEndEventNames = {
- 'WebkitTransition' : 'webkitTransitionEnd'
- , 'MozTransition' : 'transitionend'
- , 'OTransition' : 'oTransitionEnd otransitionend'
- , 'transition' : 'transitionend'
- }
-
- for (var name in transEndEventNames) {
- if (el.style[name] !== undefined) {
- return { end: transEndEventNames[name] }
- }
- }
- }
-
- // http://blog.alexmaccaw.com/css-transitions
- $.fn.emulateTransitionEnd = function (duration) {
- var called = false, $el = this
- $(this).one($.support.transition.end, function () { called = true })
- var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
- setTimeout(callback, duration)
- return this
- }
-
- $(function () {
- $.support.transition = transitionEnd()
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: alert.js v3.0.3
- * http://getbootstrap.com/javascript/#alerts
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // ALERT CLASS DEFINITION
- // ======================
-
- var dismiss = '[data-dismiss="alert"]'
- var Alert = function (el) {
- $(el).on('click', dismiss, this.close)
- }
-
- Alert.prototype.close = function (e) {
- var $this = $(this)
- var selector = $this.attr('data-target')
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
- }
-
- var $parent = $(selector)
-
- if (e) e.preventDefault()
-
- if (!$parent.length) {
- $parent = $this.hasClass('alert') ? $this : $this.parent()
- }
-
- $parent.trigger(e = $.Event('close.bs.alert'))
-
- if (e.isDefaultPrevented()) return
-
- $parent.removeClass('in')
-
- function removeElement() {
- $parent.trigger('closed.bs.alert').remove()
- }
-
- $.support.transition && $parent.hasClass('fade') ?
- $parent
- .one($.support.transition.end, removeElement)
- .emulateTransitionEnd(150) :
- removeElement()
- }
-
-
- // ALERT PLUGIN DEFINITION
- // =======================
-
- var old = $.fn.alert
-
- $.fn.alert = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.alert')
-
- if (!data) $this.data('bs.alert', (data = new Alert(this)))
- if (typeof option == 'string') data[option].call($this)
- })
- }
-
- $.fn.alert.Constructor = Alert
-
-
- // ALERT NO CONFLICT
- // =================
-
- $.fn.alert.noConflict = function () {
- $.fn.alert = old
- return this
- }
-
-
- // ALERT DATA-API
- // ==============
-
- $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: button.js v3.0.3
- * http://getbootstrap.com/javascript/#buttons
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // BUTTON PUBLIC CLASS DEFINITION
- // ==============================
-
- var Button = function (element, options) {
- this.$element = $(element)
- this.options = $.extend({}, Button.DEFAULTS, options)
- }
-
- Button.DEFAULTS = {
- loadingText: 'loading...'
- }
-
- Button.prototype.setState = function (state) {
- var d = 'disabled'
- var $el = this.$element
- var val = $el.is('input') ? 'val' : 'html'
- var data = $el.data()
-
- state = state + 'Text'
-
- if (!data.resetText) $el.data('resetText', $el[val]())
-
- $el[val](data[state] || this.options[state])
-
- // push to event loop to allow forms to submit
- setTimeout(function () {
- state == 'loadingText' ?
- $el.addClass(d).attr(d, d) :
- $el.removeClass(d).removeAttr(d);
- }, 0)
- }
-
- Button.prototype.toggle = function () {
- var $parent = this.$element.closest('[data-toggle="buttons"]')
- var changed = true
-
- if ($parent.length) {
- var $input = this.$element.find('input')
- if ($input.prop('type') === 'radio') {
- // see if clicking on current one
- if ($input.prop('checked') && this.$element.hasClass('active'))
- changed = false
- else
- $parent.find('.active').removeClass('active')
- }
- if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
- }
-
- if (changed) this.$element.toggleClass('active')
- }
-
-
- // BUTTON PLUGIN DEFINITION
- // ========================
-
- var old = $.fn.button
-
- $.fn.button = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.button')
- var options = typeof option == 'object' && option
-
- if (!data) $this.data('bs.button', (data = new Button(this, options)))
-
- if (option == 'toggle') data.toggle()
- else if (option) data.setState(option)
- })
- }
-
- $.fn.button.Constructor = Button
-
-
- // BUTTON NO CONFLICT
- // ==================
-
- $.fn.button.noConflict = function () {
- $.fn.button = old
- return this
- }
-
-
- // BUTTON DATA-API
- // ===============
-
- $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
- var $btn = $(e.target)
- if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
- $btn.button('toggle')
- e.preventDefault()
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: carousel.js v3.0.3
- * http://getbootstrap.com/javascript/#carousel
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // CAROUSEL CLASS DEFINITION
- // =========================
-
- var Carousel = function (element, options) {
- this.$element = $(element)
- this.$indicators = this.$element.find('.carousel-indicators')
- this.options = options
- this.paused =
- this.sliding =
- this.interval =
- this.$active =
- this.$items = null
-
- this.options.pause == 'hover' && this.$element
- .on('mouseenter', $.proxy(this.pause, this))
- .on('mouseleave', $.proxy(this.cycle, this))
- }
-
- Carousel.DEFAULTS = {
- interval: 5000
- , pause: 'hover'
- , wrap: true
- }
-
- Carousel.prototype.cycle = function (e) {
- e || (this.paused = false)
-
- this.interval && clearInterval(this.interval)
-
- this.options.interval
- && !this.paused
- && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
-
- return this
- }
-
- Carousel.prototype.getActiveIndex = function () {
- this.$active = this.$element.find('.item.active')
- this.$items = this.$active.parent().children()
-
- return this.$items.index(this.$active)
- }
-
- Carousel.prototype.to = function (pos) {
- var that = this
- var activeIndex = this.getActiveIndex()
-
- if (pos > (this.$items.length - 1) || pos < 0) return
-
- if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) })
- if (activeIndex == pos) return this.pause().cycle()
-
- return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
- }
-
- Carousel.prototype.pause = function (e) {
- e || (this.paused = true)
-
- if (this.$element.find('.next, .prev').length && $.support.transition.end) {
- this.$element.trigger($.support.transition.end)
- this.cycle(true)
- }
-
- this.interval = clearInterval(this.interval)
-
- return this
- }
-
- Carousel.prototype.next = function () {
- if (this.sliding) return
- return this.slide('next')
- }
-
- Carousel.prototype.prev = function () {
- if (this.sliding) return
- return this.slide('prev')
- }
-
- Carousel.prototype.slide = function (type, next) {
- var $active = this.$element.find('.item.active')
- var $next = next || $active[type]()
- var isCycling = this.interval
- var direction = type == 'next' ? 'left' : 'right'
- var fallback = type == 'next' ? 'first' : 'last'
- var that = this
-
- if (!$next.length) {
- if (!this.options.wrap) return
- $next = this.$element.find('.item')[fallback]()
- }
-
- this.sliding = true
-
- isCycling && this.pause()
-
- var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
-
- if ($next.hasClass('active')) return
-
- if (this.$indicators.length) {
- this.$indicators.find('.active').removeClass('active')
- this.$element.one('slid.bs.carousel', function () {
- var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
- $nextIndicator && $nextIndicator.addClass('active')
- })
- }
-
- if ($.support.transition && this.$element.hasClass('slide')) {
- this.$element.trigger(e)
- if (e.isDefaultPrevented()) return
- $next.addClass(type)
- $next[0].offsetWidth // force reflow
- $active.addClass(direction)
- $next.addClass(direction)
- $active
- .one($.support.transition.end, function () {
- $next.removeClass([type, direction].join(' ')).addClass('active')
- $active.removeClass(['active', direction].join(' '))
- that.sliding = false
- setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0)
- })
- .emulateTransitionEnd(600)
- } else {
- this.$element.trigger(e)
- if (e.isDefaultPrevented()) return
- $active.removeClass('active')
- $next.addClass('active')
- this.sliding = false
- this.$element.trigger('slid.bs.carousel')
- }
-
- isCycling && this.cycle()
-
- return this
- }
-
-
- // CAROUSEL PLUGIN DEFINITION
- // ==========================
-
- var old = $.fn.carousel
-
- $.fn.carousel = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.carousel')
- var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
- var action = typeof option == 'string' ? option : options.slide
-
- if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
- if (typeof option == 'number') data.to(option)
- else if (action) data[action]()
- else if (options.interval) data.pause().cycle()
- })
- }
-
- $.fn.carousel.Constructor = Carousel
-
-
- // CAROUSEL NO CONFLICT
- // ====================
-
- $.fn.carousel.noConflict = function () {
- $.fn.carousel = old
- return this
- }
-
-
- // CAROUSEL DATA-API
- // =================
-
- $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
- var $this = $(this), href
- var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
- var options = $.extend({}, $target.data(), $this.data())
- var slideIndex = $this.attr('data-slide-to')
- if (slideIndex) options.interval = false
-
- $target.carousel(options)
-
- if (slideIndex = $this.attr('data-slide-to')) {
- $target.data('bs.carousel').to(slideIndex)
- }
-
- e.preventDefault()
- })
-
- $(window).on('load', function () {
- $('[data-ride="carousel"]').each(function () {
- var $carousel = $(this)
- $carousel.carousel($carousel.data())
- })
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: collapse.js v3.0.3
- * http://getbootstrap.com/javascript/#collapse
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // COLLAPSE PUBLIC CLASS DEFINITION
- // ================================
-
- var Collapse = function (element, options) {
- this.$element = $(element)
- this.options = $.extend({}, Collapse.DEFAULTS, options)
- this.transitioning = null
-
- if (this.options.parent) this.$parent = $(this.options.parent)
- if (this.options.toggle) this.toggle()
- }
-
- Collapse.DEFAULTS = {
- toggle: true
- }
-
- Collapse.prototype.dimension = function () {
- var hasWidth = this.$element.hasClass('width')
- return hasWidth ? 'width' : 'height'
- }
-
- Collapse.prototype.show = function () {
- if (this.transitioning || this.$element.hasClass('in')) return
-
- var startEvent = $.Event('show.bs.collapse')
- this.$element.trigger(startEvent)
- if (startEvent.isDefaultPrevented()) return
-
- var actives = this.$parent && this.$parent.find('> .panel > .in')
-
- if (actives && actives.length) {
- var hasData = actives.data('bs.collapse')
- if (hasData && hasData.transitioning) return
- actives.collapse('hide')
- hasData || actives.data('bs.collapse', null)
- }
-
- var dimension = this.dimension()
-
- this.$element
- .removeClass('collapse')
- .addClass('collapsing')
- [dimension](0)
-
- this.transitioning = 1
-
- var complete = function () {
- this.$element
- .removeClass('collapsing')
- .addClass('in')
- [dimension]('auto')
- this.transitioning = 0
- this.$element.trigger('shown.bs.collapse')
- }
-
- if (!$.support.transition) return complete.call(this)
-
- var scrollSize = $.camelCase(['scroll', dimension].join('-'))
-
- this.$element
- .one($.support.transition.end, $.proxy(complete, this))
- .emulateTransitionEnd(350)
- [dimension](this.$element[0][scrollSize])
- }
-
- Collapse.prototype.hide = function () {
- if (this.transitioning || !this.$element.hasClass('in')) return
-
- var startEvent = $.Event('hide.bs.collapse')
- this.$element.trigger(startEvent)
- if (startEvent.isDefaultPrevented()) return
-
- var dimension = this.dimension()
-
- this.$element
- [dimension](this.$element[dimension]())
- [0].offsetHeight
-
- this.$element
- .addClass('collapsing')
- .removeClass('collapse')
- .removeClass('in')
-
- this.transitioning = 1
-
- var complete = function () {
- this.transitioning = 0
- this.$element
- .trigger('hidden.bs.collapse')
- .removeClass('collapsing')
- .addClass('collapse')
- }
-
- if (!$.support.transition) return complete.call(this)
-
- this.$element
- [dimension](0)
- .one($.support.transition.end, $.proxy(complete, this))
- .emulateTransitionEnd(350)
- }
-
- Collapse.prototype.toggle = function () {
- this[this.$element.hasClass('in') ? 'hide' : 'show']()
- }
-
-
- // COLLAPSE PLUGIN DEFINITION
- // ==========================
-
- var old = $.fn.collapse
-
- $.fn.collapse = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.collapse')
- var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
-
- if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.collapse.Constructor = Collapse
-
-
- // COLLAPSE NO CONFLICT
- // ====================
-
- $.fn.collapse.noConflict = function () {
- $.fn.collapse = old
- return this
- }
-
-
- // COLLAPSE DATA-API
- // =================
-
- $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
- var $this = $(this), href
- var target = $this.attr('data-target')
- || e.preventDefault()
- || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
- var $target = $(target)
- var data = $target.data('bs.collapse')
- var option = data ? 'toggle' : $this.data()
- var parent = $this.attr('data-parent')
- var $parent = parent && $(parent)
-
- if (!data || !data.transitioning) {
- if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
- $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
- }
-
- $target.collapse(option)
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: dropdown.js v3.0.3
- * http://getbootstrap.com/javascript/#dropdowns
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // DROPDOWN CLASS DEFINITION
- // =========================
-
- var backdrop = '.dropdown-backdrop'
- var toggle = '[data-toggle=dropdown]'
- var Dropdown = function (element) {
- $(element).on('click.bs.dropdown', this.toggle)
- }
-
- Dropdown.prototype.toggle = function (e) {
- var $this = $(this)
-
- if ($this.is('.disabled, :disabled')) return
-
- var $parent = getParent($this)
- var isActive = $parent.hasClass('open')
-
- clearMenus()
-
- if (!isActive) {
- if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
- // if mobile we use a backdrop because click events don't delegate
- $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
- }
-
- $parent.trigger(e = $.Event('show.bs.dropdown'))
-
- if (e.isDefaultPrevented()) return
-
- $parent
- .toggleClass('open')
- .trigger('shown.bs.dropdown')
-
- $this.focus()
- }
-
- return false
- }
-
- Dropdown.prototype.keydown = function (e) {
- if (!/(38|40|27)/.test(e.keyCode)) return
-
- var $this = $(this)
-
- e.preventDefault()
- e.stopPropagation()
-
- if ($this.is('.disabled, :disabled')) return
-
- var $parent = getParent($this)
- var isActive = $parent.hasClass('open')
-
- if (!isActive || (isActive && e.keyCode == 27)) {
- if (e.which == 27) $parent.find(toggle).focus()
- return $this.click()
- }
-
- var $items = $('[role=menu] li:not(.divider):visible a', $parent)
-
- if (!$items.length) return
-
- var index = $items.index($items.filter(':focus'))
-
- if (e.keyCode == 38 && index > 0) index-- // up
- if (e.keyCode == 40 && index < $items.length - 1) index++ // down
- if (!~index) index=0
-
- $items.eq(index).focus()
- }
-
- function clearMenus() {
- $(backdrop).remove()
- $(toggle).each(function (e) {
- var $parent = getParent($(this))
- if (!$parent.hasClass('open')) return
- $parent.trigger(e = $.Event('hide.bs.dropdown'))
- if (e.isDefaultPrevented()) return
- $parent.removeClass('open').trigger('hidden.bs.dropdown')
- })
- }
-
- function getParent($this) {
- var selector = $this.attr('data-target')
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
- }
-
- var $parent = selector && $(selector)
-
- return $parent && $parent.length ? $parent : $this.parent()
- }
-
-
- // DROPDOWN PLUGIN DEFINITION
- // ==========================
-
- var old = $.fn.dropdown
-
- $.fn.dropdown = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.dropdown')
-
- if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
- if (typeof option == 'string') data[option].call($this)
- })
- }
-
- $.fn.dropdown.Constructor = Dropdown
-
-
- // DROPDOWN NO CONFLICT
- // ====================
-
- $.fn.dropdown.noConflict = function () {
- $.fn.dropdown = old
- return this
- }
-
-
- // APPLY TO STANDARD DROPDOWN ELEMENTS
- // ===================================
-
- $(document)
- .on('click.bs.dropdown.data-api', clearMenus)
- .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
- .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
- .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: modal.js v3.0.3
- * http://getbootstrap.com/javascript/#modals
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // MODAL CLASS DEFINITION
- // ======================
-
- var Modal = function (element, options) {
- this.options = options
- this.$element = $(element)
- this.$backdrop =
- this.isShown = null
-
- if (this.options.remote) this.$element.load(this.options.remote)
- }
-
- Modal.DEFAULTS = {
- backdrop: true
- , keyboard: true
- , show: true
- }
-
- Modal.prototype.toggle = function (_relatedTarget) {
- return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
- }
-
- Modal.prototype.show = function (_relatedTarget) {
- var that = this
- var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
-
- this.$element.trigger(e)
-
- if (this.isShown || e.isDefaultPrevented()) return
-
- this.isShown = true
-
- this.escape()
-
- this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
-
- this.backdrop(function () {
- var transition = $.support.transition && that.$element.hasClass('fade')
-
- if (!that.$element.parent().length) {
- that.$element.appendTo(document.body) // don't move modals dom position
- }
-
- that.$element.show()
-
- if (transition) {
- that.$element[0].offsetWidth // force reflow
- }
-
- that.$element
- .addClass('in')
- .attr('aria-hidden', false)
-
- that.enforceFocus()
-
- var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
-
- transition ?
- that.$element.find('.modal-dialog') // wait for modal to slide in
- .one($.support.transition.end, function () {
- that.$element.focus().trigger(e)
- })
- .emulateTransitionEnd(300) :
- that.$element.focus().trigger(e)
- })
- }
-
- Modal.prototype.hide = function (e) {
- if (e) e.preventDefault()
-
- e = $.Event('hide.bs.modal')
-
- this.$element.trigger(e)
-
- if (!this.isShown || e.isDefaultPrevented()) return
-
- this.isShown = false
-
- this.escape()
-
- $(document).off('focusin.bs.modal')
-
- this.$element
- .removeClass('in')
- .attr('aria-hidden', true)
- .off('click.dismiss.modal')
-
- $.support.transition && this.$element.hasClass('fade') ?
- this.$element
- .one($.support.transition.end, $.proxy(this.hideModal, this))
- .emulateTransitionEnd(300) :
- this.hideModal()
- }
-
- Modal.prototype.enforceFocus = function () {
- $(document)
- .off('focusin.bs.modal') // guard against infinite focus loop
- .on('focusin.bs.modal', $.proxy(function (e) {
- if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
- this.$element.focus()
- }
- }, this))
- }
-
- Modal.prototype.escape = function () {
- if (this.isShown && this.options.keyboard) {
- this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
- e.which == 27 && this.hide()
- }, this))
- } else if (!this.isShown) {
- this.$element.off('keyup.dismiss.bs.modal')
- }
- }
-
- Modal.prototype.hideModal = function () {
- var that = this
- this.$element.hide()
- this.backdrop(function () {
- that.removeBackdrop()
- that.$element.trigger('hidden.bs.modal')
- })
- }
-
- Modal.prototype.removeBackdrop = function () {
- this.$backdrop && this.$backdrop.remove()
- this.$backdrop = null
- }
-
- Modal.prototype.backdrop = function (callback) {
- var that = this
- var animate = this.$element.hasClass('fade') ? 'fade' : ''
-
- if (this.isShown && this.options.backdrop) {
- var doAnimate = $.support.transition && animate
-
- this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
- .appendTo(document.body)
-
- this.$element.on('click.dismiss.modal', $.proxy(function (e) {
- if (e.target !== e.currentTarget) return
- this.options.backdrop == 'static'
- ? this.$element[0].focus.call(this.$element[0])
- : this.hide.call(this)
- }, this))
-
- if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
-
- this.$backdrop.addClass('in')
-
- if (!callback) return
-
- doAnimate ?
- this.$backdrop
- .one($.support.transition.end, callback)
- .emulateTransitionEnd(150) :
- callback()
-
- } else if (!this.isShown && this.$backdrop) {
- this.$backdrop.removeClass('in')
-
- $.support.transition && this.$element.hasClass('fade')?
- this.$backdrop
- .one($.support.transition.end, callback)
- .emulateTransitionEnd(150) :
- callback()
-
- } else if (callback) {
- callback()
- }
- }
-
-
- // MODAL PLUGIN DEFINITION
- // =======================
-
- var old = $.fn.modal
-
- $.fn.modal = function (option, _relatedTarget) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.modal')
- var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
-
- if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
- if (typeof option == 'string') data[option](_relatedTarget)
- else if (options.show) data.show(_relatedTarget)
- })
- }
-
- $.fn.modal.Constructor = Modal
-
-
- // MODAL NO CONFLICT
- // =================
-
- $.fn.modal.noConflict = function () {
- $.fn.modal = old
- return this
- }
-
-
- // MODAL DATA-API
- // ==============
-
- $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
- var $this = $(this)
- var href = $this.attr('href')
- var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
- var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
-
- e.preventDefault()
-
- $target
- .modal(option, this)
- .one('hide', function () {
- $this.is(':visible') && $this.focus()
- })
- })
-
- $(document)
- .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') })
- .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: tooltip.js v3.0.3
- * http://getbootstrap.com/javascript/#tooltip
- * Inspired by the original jQuery.tipsy by Jason Frame
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // TOOLTIP PUBLIC CLASS DEFINITION
- // ===============================
-
- var Tooltip = function (element, options) {
- this.type =
- this.options =
- this.enabled =
- this.timeout =
- this.hoverState =
- this.$element = null
-
- this.init('tooltip', element, options)
- }
-
- Tooltip.DEFAULTS = {
- animation: true
- , placement: 'top'
- , selector: false
- , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
- , trigger: 'hover focus'
- , title: ''
- , delay: 0
- , html: false
- , container: false
- }
-
- Tooltip.prototype.init = function (type, element, options) {
- this.enabled = true
- this.type = type
- this.$element = $(element)
- this.options = this.getOptions(options)
-
- var triggers = this.options.trigger.split(' ')
-
- for (var i = triggers.length; i--;) {
- var trigger = triggers[i]
-
- if (trigger == 'click') {
- this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
- } else if (trigger != 'manual') {
- var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
- var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
-
- this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
- this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
- }
- }
-
- this.options.selector ?
- (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
- this.fixTitle()
- }
-
- Tooltip.prototype.getDefaults = function () {
- return Tooltip.DEFAULTS
- }
-
- Tooltip.prototype.getOptions = function (options) {
- options = $.extend({}, this.getDefaults(), this.$element.data(), options)
-
- if (options.delay && typeof options.delay == 'number') {
- options.delay = {
- show: options.delay
- , hide: options.delay
- }
- }
-
- return options
- }
-
- Tooltip.prototype.getDelegateOptions = function () {
- var options = {}
- var defaults = this.getDefaults()
-
- this._options && $.each(this._options, function (key, value) {
- if (defaults[key] != value) options[key] = value
- })
-
- return options
- }
-
- Tooltip.prototype.enter = function (obj) {
- var self = obj instanceof this.constructor ?
- obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
-
- clearTimeout(self.timeout)
-
- self.hoverState = 'in'
-
- if (!self.options.delay || !self.options.delay.show) return self.show()
-
- self.timeout = setTimeout(function () {
- if (self.hoverState == 'in') self.show()
- }, self.options.delay.show)
- }
-
- Tooltip.prototype.leave = function (obj) {
- var self = obj instanceof this.constructor ?
- obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
-
- clearTimeout(self.timeout)
-
- self.hoverState = 'out'
-
- if (!self.options.delay || !self.options.delay.hide) return self.hide()
-
- self.timeout = setTimeout(function () {
- if (self.hoverState == 'out') self.hide()
- }, self.options.delay.hide)
- }
-
- Tooltip.prototype.show = function () {
- var e = $.Event('show.bs.'+ this.type)
-
- if (this.hasContent() && this.enabled) {
- this.$element.trigger(e)
-
- if (e.isDefaultPrevented()) return
-
- var $tip = this.tip()
-
- this.setContent()
-
- if (this.options.animation) $tip.addClass('fade')
-
- var placement = typeof this.options.placement == 'function' ?
- this.options.placement.call(this, $tip[0], this.$element[0]) :
- this.options.placement
-
- var autoToken = /\s?auto?\s?/i
- var autoPlace = autoToken.test(placement)
- if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
-
- $tip
- .detach()
- .css({ top: 0, left: 0, display: 'block' })
- .addClass(placement)
-
- this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
-
- var pos = this.getPosition()
- var actualWidth = $tip[0].offsetWidth
- var actualHeight = $tip[0].offsetHeight
-
- if (autoPlace) {
- var $parent = this.$element.parent()
-
- var orgPlacement = placement
- var docScroll = document.documentElement.scrollTop || document.body.scrollTop
- var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
- var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
- var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
-
- placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
- placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
- placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
- placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
- placement
-
- $tip
- .removeClass(orgPlacement)
- .addClass(placement)
- }
-
- var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
-
- this.applyPlacement(calculatedOffset, placement)
- this.$element.trigger('shown.bs.' + this.type)
- }
- }
-
- Tooltip.prototype.applyPlacement = function(offset, placement) {
- var replace
- var $tip = this.tip()
- var width = $tip[0].offsetWidth
- var height = $tip[0].offsetHeight
-
- // manually read margins because getBoundingClientRect includes difference
- var marginTop = parseInt($tip.css('margin-top'), 10)
- var marginLeft = parseInt($tip.css('margin-left'), 10)
-
- // we must check for NaN for ie 8/9
- if (isNaN(marginTop)) marginTop = 0
- if (isNaN(marginLeft)) marginLeft = 0
-
- offset.top = offset.top + marginTop
- offset.left = offset.left + marginLeft
-
- $tip
- .offset(offset)
- .addClass('in')
-
- // check to see if placing tip in new offset caused the tip to resize itself
- var actualWidth = $tip[0].offsetWidth
- var actualHeight = $tip[0].offsetHeight
-
- if (placement == 'top' && actualHeight != height) {
- replace = true
- offset.top = offset.top + height - actualHeight
- }
-
- if (/bottom|top/.test(placement)) {
- var delta = 0
-
- if (offset.left < 0) {
- delta = offset.left * -2
- offset.left = 0
-
- $tip.offset(offset)
-
- actualWidth = $tip[0].offsetWidth
- actualHeight = $tip[0].offsetHeight
- }
-
- this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
- } else {
- this.replaceArrow(actualHeight - height, actualHeight, 'top')
- }
-
- if (replace) $tip.offset(offset)
- }
-
- Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
- this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
- }
-
- Tooltip.prototype.setContent = function () {
- var $tip = this.tip()
- var title = this.getTitle()
-
- $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
- $tip.removeClass('fade in top bottom left right')
- }
-
- Tooltip.prototype.hide = function () {
- var that = this
- var $tip = this.tip()
- var e = $.Event('hide.bs.' + this.type)
-
- function complete() {
- if (that.hoverState != 'in') $tip.detach()
- }
-
- this.$element.trigger(e)
-
- if (e.isDefaultPrevented()) return
-
- $tip.removeClass('in')
-
- $.support.transition && this.$tip.hasClass('fade') ?
- $tip
- .one($.support.transition.end, complete)
- .emulateTransitionEnd(150) :
- complete()
-
- this.$element.trigger('hidden.bs.' + this.type)
-
- return this
- }
-
- Tooltip.prototype.fixTitle = function () {
- var $e = this.$element
- if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
- $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
- }
- }
-
- Tooltip.prototype.hasContent = function () {
- return this.getTitle()
- }
-
- Tooltip.prototype.getPosition = function () {
- var el = this.$element[0]
- return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
- width: el.offsetWidth
- , height: el.offsetHeight
- }, this.$element.offset())
- }
-
- Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
- return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
- placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
- placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
- /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
- }
-
- Tooltip.prototype.getTitle = function () {
- var title
- var $e = this.$element
- var o = this.options
-
- title = $e.attr('data-original-title')
- || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
-
- return title
- }
-
- Tooltip.prototype.tip = function () {
- return this.$tip = this.$tip || $(this.options.template)
- }
-
- Tooltip.prototype.arrow = function () {
- return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
- }
-
- Tooltip.prototype.validate = function () {
- if (!this.$element[0].parentNode) {
- this.hide()
- this.$element = null
- this.options = null
- }
- }
-
- Tooltip.prototype.enable = function () {
- this.enabled = true
- }
-
- Tooltip.prototype.disable = function () {
- this.enabled = false
- }
-
- Tooltip.prototype.toggleEnabled = function () {
- this.enabled = !this.enabled
- }
-
- Tooltip.prototype.toggle = function (e) {
- var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
- self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
- }
-
- Tooltip.prototype.destroy = function () {
- this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
- }
-
-
- // TOOLTIP PLUGIN DEFINITION
- // =========================
-
- var old = $.fn.tooltip
-
- $.fn.tooltip = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.tooltip')
- var options = typeof option == 'object' && option
-
- if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.tooltip.Constructor = Tooltip
-
-
- // TOOLTIP NO CONFLICT
- // ===================
-
- $.fn.tooltip.noConflict = function () {
- $.fn.tooltip = old
- return this
- }
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: popover.js v3.0.3
- * http://getbootstrap.com/javascript/#popovers
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // POPOVER PUBLIC CLASS DEFINITION
- // ===============================
-
- var Popover = function (element, options) {
- this.init('popover', element, options)
- }
-
- if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
-
- Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, {
- placement: 'right'
- , trigger: 'click'
- , content: ''
- , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
- })
-
-
- // NOTE: POPOVER EXTENDS tooltip.js
- // ================================
-
- Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
-
- Popover.prototype.constructor = Popover
-
- Popover.prototype.getDefaults = function () {
- return Popover.DEFAULTS
- }
-
- Popover.prototype.setContent = function () {
- var $tip = this.tip()
- var title = this.getTitle()
- var content = this.getContent()
-
- $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
- $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
-
- $tip.removeClass('fade top bottom left right in')
-
- // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
- // this manually by checking the contents.
- if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
- }
-
- Popover.prototype.hasContent = function () {
- return this.getTitle() || this.getContent()
- }
-
- Popover.prototype.getContent = function () {
- var $e = this.$element
- var o = this.options
-
- return $e.attr('data-content')
- || (typeof o.content == 'function' ?
- o.content.call($e[0]) :
- o.content)
- }
-
- Popover.prototype.arrow = function () {
- return this.$arrow = this.$arrow || this.tip().find('.arrow')
- }
-
- Popover.prototype.tip = function () {
- if (!this.$tip) this.$tip = $(this.options.template)
- return this.$tip
- }
-
-
- // POPOVER PLUGIN DEFINITION
- // =========================
-
- var old = $.fn.popover
-
- $.fn.popover = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.popover')
- var options = typeof option == 'object' && option
-
- if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.popover.Constructor = Popover
-
-
- // POPOVER NO CONFLICT
- // ===================
-
- $.fn.popover.noConflict = function () {
- $.fn.popover = old
- return this
- }
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: scrollspy.js v3.0.3
- * http://getbootstrap.com/javascript/#scrollspy
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // SCROLLSPY CLASS DEFINITION
- // ==========================
-
- function ScrollSpy(element, options) {
- var href
- var process = $.proxy(this.process, this)
-
- this.$element = $(element).is('body') ? $(window) : $(element)
- this.$body = $('body')
- this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
- this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
- this.selector = (this.options.target
- || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
- || '') + ' .nav li > a'
- this.offsets = $([])
- this.targets = $([])
- this.activeTarget = null
-
- this.refresh()
- this.process()
- }
-
- ScrollSpy.DEFAULTS = {
- offset: 10
- }
-
- ScrollSpy.prototype.refresh = function () {
- var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
-
- this.offsets = $([])
- this.targets = $([])
-
- var self = this
- var $targets = this.$body
- .find(this.selector)
- .map(function () {
- var $el = $(this)
- var href = $el.data('target') || $el.attr('href')
- var $href = /^#\w/.test(href) && $(href)
-
- return ($href
- && $href.length
- && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
- })
- .sort(function (a, b) { return a[0] - b[0] })
- .each(function () {
- self.offsets.push(this[0])
- self.targets.push(this[1])
- })
- }
-
- ScrollSpy.prototype.process = function () {
- var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
- var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
- var maxScroll = scrollHeight - this.$scrollElement.height()
- var offsets = this.offsets
- var targets = this.targets
- var activeTarget = this.activeTarget
- var i
-
- if (scrollTop >= maxScroll) {
- return activeTarget != (i = targets.last()[0]) && this.activate(i)
- }
-
- for (i = offsets.length; i--;) {
- activeTarget != targets[i]
- && scrollTop >= offsets[i]
- && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
- && this.activate( targets[i] )
- }
- }
-
- ScrollSpy.prototype.activate = function (target) {
- this.activeTarget = target
-
- $(this.selector)
- .parents('.active')
- .removeClass('active')
-
- var selector = this.selector
- + '[data-target="' + target + '"],'
- + this.selector + '[href="' + target + '"]'
-
- var active = $(selector)
- .parents('li')
- .addClass('active')
-
- if (active.parent('.dropdown-menu').length) {
- active = active
- .closest('li.dropdown')
- .addClass('active')
- }
-
- active.trigger('activate.bs.scrollspy')
- }
-
-
- // SCROLLSPY PLUGIN DEFINITION
- // ===========================
-
- var old = $.fn.scrollspy
-
- $.fn.scrollspy = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.scrollspy')
- var options = typeof option == 'object' && option
-
- if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.scrollspy.Constructor = ScrollSpy
-
-
- // SCROLLSPY NO CONFLICT
- // =====================
-
- $.fn.scrollspy.noConflict = function () {
- $.fn.scrollspy = old
- return this
- }
-
-
- // SCROLLSPY DATA-API
- // ==================
-
- $(window).on('load', function () {
- $('[data-spy="scroll"]').each(function () {
- var $spy = $(this)
- $spy.scrollspy($spy.data())
- })
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: tab.js v3.0.3
- * http://getbootstrap.com/javascript/#tabs
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // TAB CLASS DEFINITION
- // ====================
-
- var Tab = function (element) {
- this.element = $(element)
- }
-
- Tab.prototype.show = function () {
- var $this = this.element
- var $ul = $this.closest('ul:not(.dropdown-menu)')
- var selector = $this.data('target')
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
- }
-
- if ($this.parent('li').hasClass('active')) return
-
- var previous = $ul.find('.active:last a')[0]
- var e = $.Event('show.bs.tab', {
- relatedTarget: previous
- })
-
- $this.trigger(e)
-
- if (e.isDefaultPrevented()) return
-
- var $target = $(selector)
-
- this.activate($this.parent('li'), $ul)
- this.activate($target, $target.parent(), function () {
- $this.trigger({
- type: 'shown.bs.tab'
- , relatedTarget: previous
- })
- })
- }
-
- Tab.prototype.activate = function (element, container, callback) {
- var $active = container.find('> .active')
- var transition = callback
- && $.support.transition
- && $active.hasClass('fade')
-
- function next() {
- $active
- .removeClass('active')
- .find('> .dropdown-menu > .active')
- .removeClass('active')
-
- element.addClass('active')
-
- if (transition) {
- element[0].offsetWidth // reflow for transition
- element.addClass('in')
- } else {
- element.removeClass('fade')
- }
-
- if (element.parent('.dropdown-menu')) {
- element.closest('li.dropdown').addClass('active')
- }
-
- callback && callback()
- }
-
- transition ?
- $active
- .one($.support.transition.end, next)
- .emulateTransitionEnd(150) :
- next()
-
- $active.removeClass('in')
- }
-
-
- // TAB PLUGIN DEFINITION
- // =====================
-
- var old = $.fn.tab
-
- $.fn.tab = function ( option ) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.tab')
-
- if (!data) $this.data('bs.tab', (data = new Tab(this)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.tab.Constructor = Tab
-
-
- // TAB NO CONFLICT
- // ===============
-
- $.fn.tab.noConflict = function () {
- $.fn.tab = old
- return this
- }
-
-
- // TAB DATA-API
- // ============
-
- $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
- e.preventDefault()
- $(this).tab('show')
- })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: affix.js v3.0.3
- * http://getbootstrap.com/javascript/#affix
- * ========================================================================
- * Copyright 2013 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================================== */
-
-
-+function ($) { "use strict";
-
- // AFFIX CLASS DEFINITION
- // ======================
-
- var Affix = function (element, options) {
- this.options = $.extend({}, Affix.DEFAULTS, options)
- this.$window = $(window)
- .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
- .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
-
- this.$element = $(element)
- this.affixed =
- this.unpin = null
-
- this.checkPosition()
- }
-
- Affix.RESET = 'affix affix-top affix-bottom'
-
- Affix.DEFAULTS = {
- offset: 0
- }
-
- Affix.prototype.checkPositionWithEventLoop = function () {
- setTimeout($.proxy(this.checkPosition, this), 1)
- }
-
- Affix.prototype.checkPosition = function () {
- if (!this.$element.is(':visible')) return
-
- var scrollHeight = $(document).height()
- var scrollTop = this.$window.scrollTop()
- var position = this.$element.offset()
- var offset = this.options.offset
- var offsetTop = offset.top
- var offsetBottom = offset.bottom
-
- if (typeof offset != 'object') offsetBottom = offsetTop = offset
- if (typeof offsetTop == 'function') offsetTop = offset.top()
- if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
-
- var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
- offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
- offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
-
- if (this.affixed === affix) return
- if (this.unpin) this.$element.css('top', '')
-
- this.affixed = affix
- this.unpin = affix == 'bottom' ? position.top - scrollTop : null
-
- this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
-
- if (affix == 'bottom') {
- this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
- }
- }
-
-
- // AFFIX PLUGIN DEFINITION
- // =======================
-
- var old = $.fn.affix
-
- $.fn.affix = function (option) {
- return this.each(function () {
- var $this = $(this)
- var data = $this.data('bs.affix')
- var options = typeof option == 'object' && option
-
- if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.affix.Constructor = Affix
-
-
- // AFFIX NO CONFLICT
- // =================
-
- $.fn.affix.noConflict = function () {
- $.fn.affix = old
- return this
- }
-
-
- // AFFIX DATA-API
- // ==============
-
- $(window).on('load', function () {
- $('[data-spy="affix"]').each(function () {
- var $spy = $(this)
- var data = $spy.data()
-
- data.offset = data.offset || {}
-
- if (data.offsetBottom) data.offset.bottom = data.offsetBottom
- if (data.offsetTop) data.offset.top = data.offsetTop
-
- $spy.affix(data)
- })
- })
-
-}(jQuery);
diff --git a/data/libs/hammerjs/jquery.hammer.js b/data/libs/hammerjs/jquery.hammer.js
deleted file mode 100644
index 3a9faa1c4..000000000
--- a/data/libs/hammerjs/jquery.hammer.js
+++ /dev/null
@@ -1,1529 +0,0 @@
-/*! Hammer.JS - v1.0.5 - 2013-04-07
- * http://eightmedia.github.com/hammer.js
- *
- * Copyright (c) 2013 Jorik Tangelder <[email protected]>;
- * Licensed under the MIT license */
-
-(function(window, undefined) {
- 'use strict';
-
-/**
- * Hammer
- * use this to create instances
- * @param {HTMLElement} element
- * @param {Object} options
- * @returns {Hammer.Instance}
- * @constructor
- */
-var Hammer = function(element, options) {
- return new Hammer.Instance(element, options || {});
-};
-
-// default settings
-Hammer.defaults = {
- // add styles and attributes to the element to prevent the browser from doing
- // its native behavior. this doesnt prevent the scrolling, but cancels
- // the contextmenu, tap highlighting etc
- // set to false to disable this
- stop_browser_behavior: {
- // this also triggers onselectstart=false for IE
- userSelect: 'none',
- // this makes the element blocking in IE10 >, you could experiment with the value
- // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
- touchAction: 'none',
- touchCallout: 'none',
- contentZooming: 'none',
- userDrag: 'none',
- tapHighlightColor: 'rgba(0,0,0,0)'
- }
-
- // more settings are defined per gesture at gestures.js
-};
-
-// detect touchevents
-Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
-Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
-
-// dont use mouseevents on mobile devices
-Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
-Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
-
-// eventtypes per touchevent (start, move, end)
-// are filled by Hammer.event.determineEventTypes on setup
-Hammer.EVENT_TYPES = {};
-
-// direction defines
-Hammer.DIRECTION_DOWN = 'down';
-Hammer.DIRECTION_LEFT = 'left';
-Hammer.DIRECTION_UP = 'up';
-Hammer.DIRECTION_RIGHT = 'right';
-
-// pointer type
-Hammer.POINTER_MOUSE = 'mouse';
-Hammer.POINTER_TOUCH = 'touch';
-Hammer.POINTER_PEN = 'pen';
-
-// touch event defines
-Hammer.EVENT_START = 'start';
-Hammer.EVENT_MOVE = 'move';
-Hammer.EVENT_END = 'end';
-
-// hammer document where the base events are added at
-Hammer.DOCUMENT = document;
-
-// plugins namespace
-Hammer.plugins = {};
-
-// if the window events are set...
-Hammer.READY = false;
-
-/**
- * setup events to detect gestures on the document
- */
-function setup() {
- if(Hammer.READY) {
- return;
- }
-
- // find what eventtypes we add listeners to
- Hammer.event.determineEventTypes();
-
- // Register all gestures inside Hammer.gestures
- for(var name in Hammer.gestures) {
- if(Hammer.gestures.hasOwnProperty(name)) {
- Hammer.detection.register(Hammer.gestures[name]);
- }
- }
-
- // Add touch events on the document
- Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
- Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
-
- // Hammer is ready...!
- Hammer.READY = true;
-}
-
-/**
- * create new hammer instance
- * all methods should return the instance itself, so it is chainable.
- * @param {HTMLElement} element
- * @param {Object} [options={}]
- * @returns {Hammer.Instance}
- * @constructor
- */
-Hammer.Instance = function(element, options) {
- var self = this;
-
- // setup HammerJS window events and register all gestures
- // this also sets up the default options
- setup();
-
- this.element = element;
-
- // start/stop detection option
- this.enabled = true;
-
- // merge options
- this.options = Hammer.utils.extend(
- Hammer.utils.extend({}, Hammer.defaults),
- options || {});
-
- // add some css to the element to prevent the browser from doing its native behavoir
- if(this.options.stop_browser_behavior) {
- Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
- }
-
- // start detection on touchstart
- Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
- if(self.enabled) {
- Hammer.detection.startDetect(self, ev);
- }
- });
-
- // return instance
- return this;
-};
-
-
-Hammer.Instance.prototype = {
- /**
- * bind events to the instance
- * @param {String} gesture
- * @param {Function} handler
- * @returns {Hammer.Instance}
- */
- on: function onEvent(gesture, handler){
- var gestures = gesture.split(' ');
- for(var t=0; t<gestures.length; t++) {
- this.element.addEventListener(gestures[t], handler, false);
- }
- return this;
- },
-
-
- /**
- * unbind events to the instance
- * @param {String} gesture
- * @param {Function} handler
- * @returns {Hammer.Instance}
- */
- off: function offEvent(gesture, handler){
- var gestures = gesture.split(' ');
- for(var t=0; t<gestures.length; t++) {
- this.element.removeEventListener(gestures[t], handler, false);
- }
- return this;
- },
-
-
- /**
- * trigger gesture event
- * @param {String} gesture
- * @param {Object} eventData
- * @returns {Hammer.Instance}
- */
- trigger: function triggerEvent(gesture, eventData){
- // create DOM event
- var event = Hammer.DOCUMENT.createEvent('Event');
- event.initEvent(gesture, true, true);
- event.gesture = eventData;
-
- // trigger on the target if it is in the instance element,
- // this is for event delegation tricks
- var element = this.element;
- if(Hammer.utils.hasParent(eventData.target, element)) {
- element = eventData.target;
- }
-
- element.dispatchEvent(event);
- return this;
- },
-
-
- /**
- * enable of disable hammer.js detection
- * @param {Boolean} state
- * @returns {Hammer.Instance}
- */
- enable: function enable(state) {
- this.enabled = state;
- return this;
- }
-};
-
-/**
- * this holds the last move event,
- * used to fix empty touchend issue
- * see the onTouch event for an explanation
- * @type {Object}
- */
-var last_move_event = null;
-
-
-/**
- * when the mouse is hold down, this is true
- * @type {Boolean}
- */
-var enable_detect = false;
-
-
-/**
- * when touch events have been fired, this is true
- * @type {Boolean}
- */
-var touch_triggered = false;
-
-
-Hammer.event = {
- /**
- * simple addEventListener
- * @param {HTMLElement} element
- * @param {String} type
- * @param {Function} handler
- */
- bindDom: function(element, type, handler) {
- var types = type.split(' ');
- for(var t=0; t<types.length; t++) {
- element.addEventListener(types[t], handler, false);
- }
- },
-
-
- /**
- * touch events with mouse fallback
- * @param {HTMLElement} element
- * @param {String} eventType like Hammer.EVENT_MOVE
- * @param {Function} handler
- */
- onTouch: function onTouch(element, eventType, handler) {
- var self = this;
-
- this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
- var sourceEventType = ev.type.toLowerCase();
-
- // onmouseup, but when touchend has been fired we do nothing.
- // this is for touchdevices which also fire a mouseup on touchend
- if(sourceEventType.match(/mouse/) && touch_triggered) {
- return;
- }
-
- // mousebutton must be down or a touch event
- else if( sourceEventType.match(/touch/) || // touch events are always on screen
- sourceEventType.match(/pointerdown/) || // pointerevents touch
- (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
- ){
- enable_detect = true;
- }
-
- // we are in a touch event, set the touch triggered bool to true,
- // this for the conflicts that may occur on ios and android
- if(sourceEventType.match(/touch|pointer/)) {
- touch_triggered = true;
- }
-
- // count the total touches on the screen
- var count_touches = 0;
-
- // when touch has been triggered in this detection session
- // and we are now handling a mouse event, we stop that to prevent conflicts
- if(enable_detect) {
- // update pointerevent
- if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
- count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
- }
- // touch
- else if(sourceEventType.match(/touch/)) {
- count_touches = ev.touches.length;
- }
- // mouse
- else if(!touch_triggered) {
- count_touches = sourceEventType.match(/up/) ? 0 : 1;
- }
-
- // if we are in a end event, but when we remove one touch and
- // we still have enough, set eventType to move
- if(count_touches > 0 && eventType == Hammer.EVENT_END) {
- eventType = Hammer.EVENT_MOVE;
- }
- // no touches, force the end event
- else if(!count_touches) {
- eventType = Hammer.EVENT_END;
- }
-
- // because touchend has no touches, and we often want to use these in our gestures,
- // we send the last move event as our eventData in touchend
- if(!count_touches && last_move_event !== null) {
- ev = last_move_event;
- }
- // store the last move event
- else {
- last_move_event = ev;
- }
-
- // trigger the handler
- handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
-
- // remove pointerevent from list
- if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
- count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
- }
- }
-
- //debug(sourceEventType +" "+ eventType);
-
- // on the end we reset everything
- if(!count_touches) {
- last_move_event = null;
- enable_detect = false;
- touch_triggered = false;
- Hammer.PointerEvent.reset();
- }
- });
- },
-
-
- /**
- * we have different events for each device/browser
- * determine what we need and set them in the Hammer.EVENT_TYPES constant
- */
- determineEventTypes: function determineEventTypes() {
- // determine the eventtype we want to set
- var types;
-
- // pointerEvents magic
- if(Hammer.HAS_POINTEREVENTS) {
- types = Hammer.PointerEvent.getEvents();
- }
- // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
- else if(Hammer.NO_MOUSEEVENTS) {
- types = [
- 'touchstart',
- 'touchmove',
- 'touchend touchcancel'];
- }
- // for non pointer events browsers and mixed browsers,
- // like chrome on windows8 touch laptop
- else {
- types = [
- 'touchstart mousedown',
- 'touchmove mousemove',
- 'touchend touchcancel mouseup'];
- }
-
- Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
- Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
- Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
- },
-
-
- /**
- * create touchlist depending on the event
- * @param {Object} ev
- * @param {String} eventType used by the fakemultitouch plugin
- */
- getTouchList: function getTouchList(ev/*, eventType*/) {
- // get the fake pointerEvent touchlist
- if(Hammer.HAS_POINTEREVENTS) {
- return Hammer.PointerEvent.getTouchList();
- }
- // get the touchlist
- else if(ev.touches) {
- return ev.touches;
- }
- // make fake touchlist from mouse position
- else {
- return [{
- identifier: 1,
- pageX: ev.pageX,
- pageY: ev.pageY,
- target: ev.target
- }];
- }
- },
-
-
- /**
- * collect event data for Hammer js
- * @param {HTMLElement} element
- * @param {String} eventType like Hammer.EVENT_MOVE
- * @param {Object} eventData
- */
- collectEventData: function collectEventData(element, eventType, ev) {
- var touches = this.getTouchList(ev, eventType);
-
- // find out pointerType
- var pointerType = Hammer.POINTER_TOUCH;
- if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
- pointerType = Hammer.POINTER_MOUSE;
- }
-
- return {
- center : Hammer.utils.getCenter(touches),
- timeStamp : new Date().getTime(),
- target : ev.target,
- touches : touches,
- eventType : eventType,
- pointerType : pointerType,
- srcEvent : ev,
-
- /**
- * prevent the browser default actions
- * mostly used to disable scrolling of the browser
- */
- preventDefault: function() {
- if(this.srcEvent.preventManipulation) {
- this.srcEvent.preventManipulation();
- }
-
- if(this.srcEvent.preventDefault) {
- this.srcEvent.preventDefault();
- }
- },
-
- /**
- * stop bubbling the event up to its parents
- */
- stopPropagation: function() {
- this.srcEvent.stopPropagation();
- },
-
- /**
- * immediately stop gesture detection
- * might be useful after a swipe was detected
- * @return {*}
- */
- stopDetect: function() {
- return Hammer.detection.stopDetect();
- }
- };
- }
-};
-
-Hammer.PointerEvent = {
- /**
- * holds all pointers
- * @type {Object}
- */
- pointers: {},
-
- /**
- * get a list of pointers
- * @returns {Array} touchlist
- */
- getTouchList: function() {
- var self = this;
- var touchlist = [];
-
- // we can use forEach since pointerEvents only is in IE10
- Object.keys(self.pointers).sort().forEach(function(id) {
- touchlist.push(self.pointers[id]);
- });
- return touchlist;
- },
-
- /**
- * update the position of a pointer
- * @param {String} type Hammer.EVENT_END
- * @param {Object} pointerEvent
- */
- updatePointer: function(type, pointerEvent) {
- if(type == Hammer.EVENT_END) {
- this.pointers = {};
- }
- else {
- pointerEvent.identifier = pointerEvent.pointerId;
- this.pointers[pointerEvent.pointerId] = pointerEvent;
- }
-
- return Object.keys(this.pointers).length;
- },
-
- /**
- * check if ev matches pointertype
- * @param {String} pointerType Hammer.POINTER_MOUSE
- * @param {PointerEvent} ev
- */
- matchType: function(pointerType, ev) {
- if(!ev.pointerType) {
- return false;
- }
-
- var types = {};
- types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
- types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
- types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
- return types[pointerType];
- },
-
-
- /**
- * get events
- */
- getEvents: function() {
- return [
- 'pointerdown MSPointerDown',
- 'pointermove MSPointerMove',
- 'pointerup pointercancel MSPointerUp MSPointerCancel'
- ];
- },
-
- /**
- * reset the list
- */
- reset: function() {
- this.pointers = {};
- }
-};
-
-
-Hammer.utils = {
- /**
- * extend method,
- * also used for cloning when dest is an empty object
- * @param {Object} dest
- * @param {Object} src
- * @parm {Boolean} merge do a merge
- * @returns {Object} dest
- */
- extend: function extend(dest, src, merge) {
- for (var key in src) {
- if(dest[key] !== undefined && merge) {
- continue;
- }
- dest[key] = src[key];
- }
- return dest;
- },
-
-
- /**
- * find if a node is in the given parent
- * used for event delegation tricks
- * @param {HTMLElement} node
- * @param {HTMLElement} parent
- * @returns {boolean} has_parent
- */
- hasParent: function(node, parent) {
- while(node){
- if(node == parent) {
- return true;
- }
- node = node.parentNode;
- }
- return false;
- },
-
-
- /**
- * get the center of all the touches
- * @param {Array} touches
- * @returns {Object} center
- */
- getCenter: function getCenter(touches) {
- var valuesX = [], valuesY = [];
-
- for(var t= 0,len=touches.length; t<len; t++) {
- valuesX.push(touches[t].pageX);
- valuesY.push(touches[t].pageY);
- }
-
- return {
- pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
- pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
- };
- },
-
-
- /**
- * calculate the velocity between two points
- * @param {Number} delta_time
- * @param {Number} delta_x
- * @param {Number} delta_y
- * @returns {Object} velocity
- */
- getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
- return {
- x: Math.abs(delta_x / delta_time) || 0,
- y: Math.abs(delta_y / delta_time) || 0
- };
- },
-
-
- /**
- * calculate the angle between two coordinates
- * @param {Touch} touch1
- * @param {Touch} touch2
- * @returns {Number} angle
- */
- getAngle: function getAngle(touch1, touch2) {
- var y = touch2.pageY - touch1.pageY,
- x = touch2.pageX - touch1.pageX;
- return Math.atan2(y, x) * 180 / Math.PI;
- },
-
-
- /**
- * angle to direction define
- * @param {Touch} touch1
- * @param {Touch} touch2
- * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
- */
- getDirection: function getDirection(touch1, touch2) {
- var x = Math.abs(touch1.pageX - touch2.pageX),
- y = Math.abs(touch1.pageY - touch2.pageY);
-
- if(x >= y) {
- return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
- }
- else {
- return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
- }
- },
-
-
- /**
- * calculate the distance between two touches
- * @param {Touch} touch1
- * @param {Touch} touch2
- * @returns {Number} distance
- */
- getDistance: function getDistance(touch1, touch2) {
- var x = touch2.pageX - touch1.pageX,
- y = touch2.pageY - touch1.pageY;
- return Math.sqrt((x*x) + (y*y));
- },
-
-
- /**
- * calculate the scale factor between two touchLists (fingers)
- * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
- * @param {Array} start
- * @param {Array} end
- * @returns {Number} scale
- */
- getScale: function getScale(start, end) {
- // need two fingers...
- if(start.length >= 2 && end.length >= 2) {
- return this.getDistance(end[0], end[1]) /
- this.getDistance(start[0], start[1]);
- }
- return 1;
- },
-
-
- /**
- * calculate the rotation degrees between two touchLists (fingers)
- * @param {Array} start
- * @param {Array} end
- * @returns {Number} rotation
- */
- getRotation: function getRotation(start, end) {
- // need two fingers
- if(start.length >= 2 && end.length >= 2) {
- return this.getAngle(end[1], end[0]) -
- this.getAngle(start[1], start[0]);
- }
- return 0;
- },
-
-
- /**
- * boolean if the direction is vertical
- * @param {String} direction
- * @returns {Boolean} is_vertical
- */
- isVertical: function isVertical(direction) {
- return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
- },
-
-
- /**
- * stop browser default behavior with css props
- * @param {HtmlElement} element
- * @param {Object} css_props
- */
- stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
- var prop,
- vendors = ['webkit','khtml','moz','ms','o',''];
-
- if(!css_props || !element.style) {
- return;
- }
-
- // with css properties for modern browsers
- for(var i = 0; i < vendors.length; i++) {
- for(var p in css_props) {
- if(css_props.hasOwnProperty(p)) {
- prop = p;
-
- // vender prefix at the property
- if(vendors[i]) {
- prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
- }
-
- // set the style
- element.style[prop] = css_props[p];
- }
- }
- }
-
- // also the disable onselectstart
- if(css_props.userSelect == 'none') {
- element.onselectstart = function() {
- return false;
- };
- }
- }
-};
-
-Hammer.detection = {
- // contains all registred Hammer.gestures in the correct order
- gestures: [],
-
- // data of the current Hammer.gesture detection session
- current: null,
-
- // the previous Hammer.gesture session data
- // is a full clone of the previous gesture.current object
- previous: null,
-
- // when this becomes true, no gestures are fired
- stopped: false,
-
-
- /**
- * start Hammer.gesture detection
- * @param {Hammer.Instance} inst
- * @param {Object} eventData
- */
- startDetect: function startDetect(inst, eventData) {
- // already busy with a Hammer.gesture detection on an element
- if(this.current) {
- return;
- }
-
- this.stopped = false;
-
- this.current = {
- inst : inst, // reference to HammerInstance we're working for
- startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
- lastEvent : false, // last eventData
- name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
- };
-
- this.detect(eventData);
- },
-
-
- /**
- * Hammer.gesture detection
- * @param {Object} eventData
- * @param {Object} eventData
- */
- detect: function detect(eventData) {
- if(!this.current || this.stopped) {
- return;
- }
-
- // extend event data with calculations about scale, distance etc
- eventData = this.extendEventData(eventData);
-
- // instance options
- var inst_options = this.current.inst.options;
-
- // call Hammer.gesture handlers
- for(var g=0,len=this.gestures.length; g<len; g++) {
- var gesture = this.gestures[g];
-
- // only when the instance options have enabled this gesture
- if(!this.stopped && inst_options[gesture.name] !== false) {
- // if a handler returns false, we stop with the detection
- if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
- this.stopDetect();
- break;
- }
- }
- }
-
- // store as previous event event
- if(this.current) {
- this.current.lastEvent = eventData;
- }
-
- // endevent, but not the last touch, so dont stop
- if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
- this.stopDetect();
- }
-
- return eventData;
- },
-
-
- /**
- * clear the Hammer.gesture vars
- * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
- * to stop other Hammer.gestures from being fired
- */
- stopDetect: function stopDetect() {
- // clone current data to the store as the previous gesture
- // used for the double tap gesture, since this is an other gesture detect session
- this.previous = Hammer.utils.extend({}, this.current);
-
- // reset the current
- this.current = null;
-
- // stopped!
- this.stopped = true;
- },
-
-
- /**
- * extend eventData for Hammer.gestures
- * @param {Object} ev
- * @returns {Object} ev
- */
- extendEventData: function extendEventData(ev) {
- var startEv = this.current.startEvent;
-
- // if the touches change, set the new touches over the startEvent touches
- // this because touchevents don't have all the touches on touchstart, or the
- // user must place his fingers at the EXACT same time on the screen, which is not realistic
- // but, sometimes it happens that both fingers are touching at the EXACT same time
- if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
- // extend 1 level deep to get the touchlist with the touch objects
- startEv.touches = [];
- for(var i=0,len=ev.touches.length; i<len; i++) {
- startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
- }
- }
-
- var delta_time = ev.timeStamp - startEv.timeStamp,
- delta_x = ev.center.pageX - startEv.center.pageX,
- delta_y = ev.center.pageY - startEv.center.pageY,
- velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
-
- Hammer.utils.extend(ev, {
- deltaTime : delta_time,
-
- deltaX : delta_x,
- deltaY : delta_y,
-
- velocityX : velocity.x,
- velocityY : velocity.y,
-
- distance : Hammer.utils.getDistance(startEv.center, ev.center),
- angle : Hammer.utils.getAngle(startEv.center, ev.center),
- direction : Hammer.utils.getDirection(startEv.center, ev.center),
-
- scale : Hammer.utils.getScale(startEv.touches, ev.touches),
- rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
-
- startEvent : startEv
- });
-
- return ev;
- },
-
-
- /**
- * register new gesture
- * @param {Object} gesture object, see gestures.js for documentation
- * @returns {Array} gestures
- */
- register: function register(gesture) {
- // add an enable gesture options if there is no given
- var options = gesture.defaults || {};
- if(options[gesture.name] === undefined) {
- options[gesture.name] = true;
- }
-
- // extend Hammer default options with the Hammer.gesture options
- Hammer.utils.extend(Hammer.defaults, options, true);
-
- // set its index
- gesture.index = gesture.index || 1000;
-
- // add Hammer.gesture to the list
- this.gestures.push(gesture);
-
- // sort the list by index
- this.gestures.sort(function(a, b) {
- if (a.index < b.index) {
- return -1;
- }
- if (a.index > b.index) {
- return 1;
- }
- return 0;
- });
-
- return this.gestures;
- }
-};
-
-
-Hammer.gestures = Hammer.gestures || {};
-
-/**
- * Custom gestures
- * ==============================
- *
- * Gesture object
- * --------------------
- * The object structure of a gesture:
- *
- * { name: 'mygesture',
- * index: 1337,
- * defaults: {
- * mygesture_option: true
- * }
- * handler: function(type, ev, inst) {
- * // trigger gesture event
- * inst.trigger(this.name, ev);
- * }
- * }
-
- * @param {String} name
- * this should be the name of the gesture, lowercase
- * it is also being used to disable/enable the gesture per instance config.
- *
- * @param {Number} [index=1000]
- * the index of the gesture, where it is going to be in the stack of gestures detection
- * like when you build an gesture that depends on the drag gesture, it is a good
- * idea to place it after the index of the drag gesture.
- *
- * @param {Object} [defaults={}]
- * the default settings of the gesture. these are added to the instance settings,
- * and can be overruled per instance. you can also add the name of the gesture,
- * but this is also added by default (and set to true).
- *
- * @param {Function} handler
- * this handles the gesture detection of your custom gesture and receives the
- * following arguments:
- *
- * @param {Object} eventData
- * event data containing the following properties:
- * timeStamp {Number} time the event occurred
- * target {HTMLElement} target element
- * touches {Array} touches (fingers, pointers, mouse) on the screen
- * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
- * center {Object} center position of the touches. contains pageX and pageY
- * deltaTime {Number} the total time of the touches in the screen
- * deltaX {Number} the delta on x axis we haved moved
- * deltaY {Number} the delta on y axis we haved moved
- * velocityX {Number} the velocity on the x
- * velocityY {Number} the velocity on y
- * angle {Number} the angle we are moving
- * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
- * distance {Number} the distance we haved moved
- * scale {Number} scaling of the touches, needs 2 touches
- * rotation {Number} rotation of the touches, needs 2 touches *
- * eventType {String} matches Hammer.EVENT_START|MOVE|END
- * srcEvent {Object} the source event, like TouchStart or MouseDown *
- * startEvent {Object} contains the same properties as above,
- * but from the first touch. this is used to calculate
- * distances, deltaTime, scaling etc
- *
- * @param {Hammer.Instance} inst
- * the instance we are doing the detection for. you can get the options from
- * the inst.options object and trigger the gesture event by calling inst.trigger
- *
- *
- * Handle gestures
- * --------------------
- * inside the handler you can get/set Hammer.detection.current. This is the current
- * detection session. It has the following properties
- * @param {String} name
- * contains the name of the gesture we have detected. it has not a real function,
- * only to check in other gestures if something is detected.
- * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
- * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
- *
- * @readonly
- * @param {Hammer.Instance} inst
- * the instance we do the detection for
- *
- * @readonly
- * @param {Object} startEvent
- * contains the properties of the first gesture detection in this session.
- * Used for calculations about timing, distance, etc.
- *
- * @readonly
- * @param {Object} lastEvent
- * contains all the properties of the last gesture detect in this session.
- *
- * after the gesture detection session has been completed (user has released the screen)
- * the Hammer.detection.current object is copied into Hammer.detection.previous,
- * this is usefull for gestures like doubletap, where you need to know if the
- * previous gesture was a tap
- *
- * options that have been set by the instance can be received by calling inst.options
- *
- * You can trigger a gesture event by calling inst.trigger("mygesture", event).
- * The first param is the name of your gesture, the second the event argument
- *
- *
- * Register gestures
- * --------------------
- * When an gesture is added to the Hammer.gestures object, it is auto registered
- * at the setup of the first Hammer instance. You can also call Hammer.detection.register
- * manually and pass your gesture object as a param
- *
- */
-
-/**
- * Hold
- * Touch stays at the same place for x time
- * @events hold
- */
-Hammer.gestures.Hold = {
- name: 'hold',
- index: 10,
- defaults: {
- hold_timeout : 500,
- hold_threshold : 1
- },
- timer: null,
- handler: function holdGesture(ev, inst) {
- switch(ev.eventType) {
- case Hammer.EVENT_START:
- // clear any running timers
- clearTimeout(this.timer);
-
- // set the gesture so we can check in the timeout if it still is
- Hammer.detection.current.name = this.name;
-
- // set timer and if after the timeout it still is hold,
- // we trigger the hold event
- this.timer = setTimeout(function() {
- if(Hammer.detection.current.name == 'hold') {
- inst.trigger('hold', ev);
- }
- }, inst.options.hold_timeout);
- break;
-
- // when you move or end we clear the timer
- case Hammer.EVENT_MOVE:
- if(ev.distance > inst.options.hold_threshold) {
- clearTimeout(this.timer);
- }
- break;
-
- case Hammer.EVENT_END:
- clearTimeout(this.timer);
- break;
- }
- }
-};
-
-
-/**
- * Tap/DoubleTap
- * Quick touch at a place or double at the same place
- * @events tap, doubletap
- */
-Hammer.gestures.Tap = {
- name: 'tap',
- index: 100,
- defaults: {
- tap_max_touchtime : 250,
- tap_max_distance : 10,
- tap_always : true,
- doubletap_distance : 20,
- doubletap_interval : 300
- },
- handler: function tapGesture(ev, inst) {
- if(ev.eventType == Hammer.EVENT_END) {
- // previous gesture, for the double tap since these are two different gesture detections
- var prev = Hammer.detection.previous,
- did_doubletap = false;
-
- // when the touchtime is higher then the max touch time
- // or when the moving distance is too much
- if(ev.deltaTime > inst.options.tap_max_touchtime ||
- ev.distance > inst.options.tap_max_distance) {
- return;
- }
-
- // check if double tap
- if(prev && prev.name == 'tap' &&
- (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
- ev.distance < inst.options.doubletap_distance) {
- inst.trigger('doubletap', ev);
- did_doubletap = true;
- }
-
- // do a single tap
- if(!did_doubletap || inst.options.tap_always) {
- Hammer.detection.current.name = 'tap';
- inst.trigger(Hammer.detection.current.name, ev);
- }
- }
- }
-};
-
-
-/**
- * Swipe
- * triggers swipe events when the end velocity is above the threshold
- * @events swipe, swipeleft, swiperight, swipeup, swipedown
- */
-Hammer.gestures.Swipe = {
- name: 'swipe',
- index: 40,
- defaults: {
- // set 0 for unlimited, but this can conflict with transform
- swipe_max_touches : 1,
- swipe_velocity : 0.7
- },
- handler: function swipeGesture(ev, inst) {
- if(ev.eventType == Hammer.EVENT_END) {
- // max touches
- if(inst.options.swipe_max_touches > 0 &&
- ev.touches.length > inst.options.swipe_max_touches) {
- return;
- }
-
- // when the distance we moved is too small we skip this gesture
- // or we can be already in dragging
- if(ev.velocityX > inst.options.swipe_velocity ||
- ev.velocityY > inst.options.swipe_velocity) {
- // trigger swipe events
- inst.trigger(this.name, ev);
- inst.trigger(this.name + ev.direction, ev);
- }
- }
- }
-};
-
-
-/**
- * Drag
- * Move with x fingers (default 1) around on the page. Blocking the scrolling when
- * moving left and right is a good practice. When all the drag events are blocking
- * you disable scrolling on that area.
- * @events drag, drapleft, dragright, dragup, dragdown
- */
-Hammer.gestures.Drag = {
- name: 'drag',
- index: 50,
- defaults: {
- drag_min_distance : 10,
- // set 0 for unlimited, but this can conflict with transform
- drag_max_touches : 1,
- // prevent default browser behavior when dragging occurs
- // be careful with it, it makes the element a blocking element
- // when you are using the drag gesture, it is a good practice to set this true
- drag_block_horizontal : false,
- drag_block_vertical : false,
- // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
- // It disallows vertical directions if the initial direction was horizontal, and vice versa.
- drag_lock_to_axis : false,
- // drag lock only kicks in when distance > drag_lock_min_distance
- // This way, locking occurs only when the distance has become large enough to reliably determine the direction
- drag_lock_min_distance : 25
- },
- triggered: false,
- handler: function dragGesture(ev, inst) {
- // current gesture isnt drag, but dragged is true
- // this means an other gesture is busy. now call dragend
- if(Hammer.detection.current.name != this.name && this.triggered) {
- inst.trigger(this.name +'end', ev);
- this.triggered = false;
- return;
- }
-
- // max touches
- if(inst.options.drag_max_touches > 0 &&
- ev.touches.length > inst.options.drag_max_touches) {
- return;
- }
-
- switch(ev.eventType) {
- case Hammer.EVENT_START:
- this.triggered = false;
- break;
-
- case Hammer.EVENT_MOVE:
- // when the distance we moved is too small we skip this gesture
- // or we can be already in dragging
- if(ev.distance < inst.options.drag_min_distance &&
- Hammer.detection.current.name != this.name) {
- return;
- }
-
- // we are dragging!
- Hammer.detection.current.name = this.name;
-
- // lock drag to axis?
- if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
- ev.drag_locked_to_axis = true;
- }
- var last_direction = Hammer.detection.current.lastEvent.direction;
- if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
- // keep direction on the axis that the drag gesture started on
- if(Hammer.utils.isVertical(last_direction)) {
- ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
- }
- else {
- ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
- }
- }
-
- // first time, trigger dragstart event
- if(!this.triggered) {
- inst.trigger(this.name +'start', ev);
- this.triggered = true;
- }
-
- // trigger normal event
- inst.trigger(this.name, ev);
-
- // direction event, like dragdown
- inst.trigger(this.name + ev.direction, ev);
-
- // block the browser events
- if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
- (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
- ev.preventDefault();
- }
- break;
-
- case Hammer.EVENT_END:
- // trigger dragend
- if(this.triggered) {
- inst.trigger(this.name +'end', ev);
- }
-
- this.triggered = false;
- break;
- }
- }
-};
-
-
-/**
- * Transform
- * User want to scale or rotate with 2 fingers
- * @events transform, pinch, pinchin, pinchout, rotate
- */
-Hammer.gestures.Transform = {
- name: 'transform',
- index: 45,
- defaults: {
- // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
- transform_min_scale : 0.01,
- // rotation in degrees
- transform_min_rotation : 1,
- // prevent default browser behavior when two touches are on the screen
- // but it makes the element a blocking element
- // when you are using the transform gesture, it is a good practice to set this true
- transform_always_block : false
- },
- triggered: false,
- handler: function transformGesture(ev, inst) {
- // current gesture isnt drag, but dragged is true
- // this means an other gesture is busy. now call dragend
- if(Hammer.detection.current.name != this.name && this.triggered) {
- inst.trigger(this.name +'end', ev);
- this.triggered = false;
- return;
- }
-
- // atleast multitouch
- if(ev.touches.length < 2) {
- return;
- }
-
- // prevent default when two fingers are on the screen
- if(inst.options.transform_always_block) {
- ev.preventDefault();
- }
-
- switch(ev.eventType) {
- case Hammer.EVENT_START:
- this.triggered = false;
- break;
-
- case Hammer.EVENT_MOVE:
- var scale_threshold = Math.abs(1-ev.scale);
- var rotation_threshold = Math.abs(ev.rotation);
-
- // when the distance we moved is too small we skip this gesture
- // or we can be already in dragging
- if(scale_threshold < inst.options.transform_min_scale &&
- rotation_threshold < inst.options.transform_min_rotation) {
- return;
- }
-
- // we are transforming!
- Hammer.detection.current.name = this.name;
-
- // first time, trigger dragstart event
- if(!this.triggered) {
- inst.trigger(this.name +'start', ev);
- this.triggered = true;
- }
-
- inst.trigger(this.name, ev); // basic transform event
-
- // trigger rotate event
- if(rotation_threshold > inst.options.transform_min_rotation) {
- inst.trigger('rotate', ev);
- }
-
- // trigger pinch event
- if(scale_threshold > inst.options.transform_min_scale) {
- inst.trigger('pinch', ev);
- inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
- }
- break;
-
- case Hammer.EVENT_END:
- // trigger dragend
- if(this.triggered) {
- inst.trigger(this.name +'end', ev);
- }
-
- this.triggered = false;
- break;
- }
- }
-};
-
-
-/**
- * Touch
- * Called as first, tells the user has touched the screen
- * @events touch
- */
-Hammer.gestures.Touch = {
- name: 'touch',
- index: -Infinity,
- defaults: {
- // call preventDefault at touchstart, and makes the element blocking by
- // disabling the scrolling of the page, but it improves gestures like
- // transforming and dragging.
- // be careful with using this, it can be very annoying for users to be stuck
- // on the page
- prevent_default: false,
-
- // disable mouse events, so only touch (or pen!) input triggers events
- prevent_mouseevents: false
- },
- handler: function touchGesture(ev, inst) {
- if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
- ev.stopDetect();
- return;
- }
-
- if(inst.options.prevent_default) {
- ev.preventDefault();
- }
-
- if(ev.eventType == Hammer.EVENT_START) {
- inst.trigger(this.name, ev);
- }
- }
-};
-
-
-/**
- * Release
- * Called as last, tells the user has released the screen
- * @events release
- */
-Hammer.gestures.Release = {
- name: 'release',
- index: Infinity,
- handler: function releaseGesture(ev, inst) {
- if(ev.eventType == Hammer.EVENT_END) {
- inst.trigger(this.name, ev);
- }
- }
-};
-
-// node export
-if(typeof module === 'object' && typeof module.exports === 'object'){
- module.exports = Hammer;
-}
-// just window export
-else {
- window.Hammer = Hammer;
-
- // requireJS module definition
- if(typeof window.define === 'function' && window.define.amd) {
- window.define('hammer', [], function() {
- return Hammer;
- });
- }
-}
-})(this);
-
-(function($, undefined) {
- 'use strict';
-
- // no jQuery or Zepto!
- if($ === undefined) {
- return;
- }
-
- /**
- * bind dom events
- * this overwrites addEventListener
- * @param {HTMLElement} element
- * @param {String} eventTypes
- * @param {Function} handler
- */
- Hammer.event.bindDom = function(element, eventTypes, handler) {
- $(element).on(eventTypes, function(ev) {
- var data = ev.originalEvent || ev;
-
- // IE pageX fix
- if(data.pageX === undefined) {
- data.pageX = ev.pageX;
- data.pageY = ev.pageY;
- }
-
- // IE target fix
- if(!data.target) {
- data.target = ev.target;
- }
-
- // IE button fix
- if(data.which === undefined) {
- data.which = data.button;
- }
-
- // IE preventDefault
- if(!data.preventDefault) {
- data.preventDefault = ev.preventDefault;
- }
-
- // IE stopPropagation
- if(!data.stopPropagation) {
- data.stopPropagation = ev.stopPropagation;
- }
-
- handler.call(this, data);
- });
- };
-
- /**
- * the methods are called by the instance, but with the jquery plugin
- * we use the jquery event methods instead.
- * @this {Hammer.Instance}
- * @return {jQuery}
- */
- Hammer.Instance.prototype.on = function(types, handler) {
- return $(this.element).on(types, handler);
- };
- Hammer.Instance.prototype.off = function(types, handler) {
- return $(this.element).off(types, handler);
- };
-
-
- /**
- * trigger events
- * this is called by the gestures to trigger an event like 'tap'
- * @this {Hammer.Instance}
- * @param {String} gesture
- * @param {Object} eventData
- * @return {jQuery}
- */
- Hammer.Instance.prototype.trigger = function(gesture, eventData){
- var el = $(this.element);
- if(el.has(eventData.target).length) {
- el = $(eventData.target);
- }
-
- return el.trigger({
- type: gesture,
- gesture: eventData
- });
- };
-
-
- /**
- * jQuery plugin
- * create instance of Hammer and watch for gestures,
- * and when called again you can change the options
- * @param {Object} [options={}]
- * @return {jQuery}
- */
- $.fn.hammer = function(options) {
- return this.each(function() {
- var el = $(this);
- var inst = el.data('hammer');
- // start new hammer instance
- if(!inst) {
- el.data('hammer', new Hammer(this, options || {}));
- }
- // change the options
- else if(inst && options) {
- Hammer.utils.extend(inst.options, options);
- }
- });
- };
-
-})(window.jQuery || window.Zepto);
diff --git a/data/libs/i18next/i18next-1.7.1.js b/data/libs/i18next/i18next-1.7.1.js
deleted file mode 100644
index 2f531ae03..000000000
--- a/data/libs/i18next/i18next-1.7.1.js
+++ /dev/null
@@ -1,2662 +0,0 @@
-// i18next, v1.7.1
-// Copyright (c)2013 Jan Mühlemann (jamuhl).
-// Distributed under MIT license
-// http://i18next.com
-(function() {
-
- // add indexOf to non ECMA-262 standard compliant browsers
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
- "use strict";
- if (this == null) {
- throw new TypeError();
- }
- var t = Object(this);
- var len = t.length >>> 0;
- if (len === 0) {
- return -1;
- }
- var n = 0;
- if (arguments.length > 0) {
- n = Number(arguments[1]);
- if (n != n) { // shortcut for verifying if it's NaN
- n = 0;
- } else if (n != 0 && n != Infinity && n != -Infinity) {
- n = (n > 0 || -1) * Math.floor(Math.abs(n));
- }
- }
- if (n >= len) {
- return -1;
- }
- var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
- for (; k < len; k++) {
- if (k in t && t[k] === searchElement) {
- return k;
- }
- }
- return -1;
- }
- }
-
- // add lastIndexOf to non ECMA-262 standard compliant browsers
- if (!Array.prototype.lastIndexOf) {
- Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
- "use strict";
- if (this == null) {
- throw new TypeError();
- }
- var t = Object(this);
- var len = t.length >>> 0;
- if (len === 0) {
- return -1;
- }
- var n = len;
- if (arguments.length > 1) {
- n = Number(arguments[1]);
- if (n != n) {
- n = 0;
- } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
- n = (n > 0 || -1) * Math.floor(Math.abs(n));
- }
- }
- var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
- for (; k >= 0; k--) {
- if (k in t && t[k] === searchElement) {
- return k;
- }
- }
- return -1;
- };
- }
-
- var root = this
- , $ = root.jQuery || root.Zepto
- , i18n = {}
- , resStore = {}
- , currentLng
- , replacementCounter = 0
- , languages = []
- , initialized = false;
-
-
- // Export the i18next object for **CommonJS**.
- // If we're not in CommonJS, add `i18n` to the
- // global object or to jquery.
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = i18n;
- } else {
- if ($) {
- $.i18n = $.i18n || i18n;
- }
-
- root.i18n = root.i18n || i18n;
- }
- // defaults
- var o = {
- lng: undefined,
- load: 'all',
- preload: [],
- lowerCaseLng: false,
- returnObjectTrees: false,
- fallbackLng: 'dev',
- fallbackNS: [],
- detectLngQS: 'setLng',
- ns: 'translation',
- fallbackOnNull: true,
- fallbackToDefaultNS: false,
- nsseparator: ':',
- keyseparator: '.',
- selectorAttr: 'data-i18n',
- debug: false,
-
- resGetPath: 'locales/__lng__/__ns__.json',
- resPostPath: 'locales/add/__lng__/__ns__',
-
- getAsync: true,
- postAsync: true,
-
- resStore: undefined,
- useLocalStorage: false,
- localStorageExpirationTime: 7*24*60*60*1000,
-
- dynamicLoad: false,
- sendMissing: false,
- sendMissingTo: 'fallback', // current | all
- sendType: 'POST',
-
- interpolationPrefix: '__',
- interpolationSuffix: '__',
- reusePrefix: '$t(',
- reuseSuffix: ')',
- pluralSuffix: '_plural',
- pluralNotFound: ['plural_not_found', Math.random()].join(''),
- contextNotFound: ['context_not_found', Math.random()].join(''),
- escapeInterpolation: false,
-
- setJqueryExt: true,
- defaultValueFromContent: true,
- useDataAttrOptions: false,
- cookieExpirationTime: undefined,
- useCookie: true,
- cookieName: 'i18next',
- cookieDomain: undefined,
-
- postProcess: undefined,
- parseMissingKey: undefined,
-
- shortcutFunction: 'sprintf' // or: defaultValue
- };
- function _extend(target, source) {
- if (!source || typeof source === 'function') {
- return target;
- }
-
- for (var attr in source) { target[attr] = source[attr]; }
- return target;
- }
-
- function _each(object, callback, args) {
- var name, i = 0,
- length = object.length,
- isObj = length === undefined || typeof object === "function";
-
- if (args) {
- if (isObj) {
- for (name in object) {
- if (callback.apply(object[name], args) === false) {
- break;
- }
- }
- } else {
- for ( ; i < length; ) {
- if (callback.apply(object[i++], args) === false) {
- break;
- }
- }
- }
-
- // A special, fast, case for the most common use of each
- } else {
- if (isObj) {
- for (name in object) {
- if (callback.call(object[name], name, object[name]) === false) {
- break;
- }
- }
- } else {
- for ( ; i < length; ) {
- if (callback.call(object[i], i, object[i++]) === false) {
- break;
- }
- }
- }
- }
-
- return object;
- }
-
- var _entityMap = {
- "&": "&amp;",
- "<": "&lt;",
- ">": "&gt;",
- '"': '&quot;',
- "'": '&#39;',
- "/": '&#x2F;'
- };
-
- function _escape(data) {
- if (typeof data === 'string') {
- return data.replace(/[&<>"'\/]/g, function (s) {
- return _entityMap[s];
- });
- }else{
- return data;
- }
- }
-
- function _ajax(options) {
-
- // v0.5.0 of https://github.com/goloroden/http.js
- var getXhr = function (callback) {
- // Use the native XHR object if the browser supports it.
- if (window.XMLHttpRequest) {
- return callback(null, new XMLHttpRequest());
- } else if (window.ActiveXObject) {
- // In Internet Explorer check for ActiveX versions of the XHR object.
- try {
- return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
- } catch (e) {
- return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
- }
- }
-
- // If no XHR support was found, throw an error.
- return callback(new Error());
- };
-
- var encodeUsingUrlEncoding = function (data) {
- if(typeof data === 'string') {
- return data;
- }
-
- var result = [];
- for(var dataItem in data) {
- if(data.hasOwnProperty(dataItem)) {
- result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
- }
- }
-
- return result.join('&');
- };
-
- var utf8 = function (text) {
- text = text.replace(/\r\n/g, '\n');
- var result = '';
-
- for(var i = 0; i < text.length; i++) {
- var c = text.charCodeAt(i);
-
- if(c < 128) {
- result += String.fromCharCode(c);
- } else if((c > 127) && (c < 2048)) {
- result += String.fromCharCode((c >> 6) | 192);
- result += String.fromCharCode((c & 63) | 128);
- } else {
- result += String.fromCharCode((c >> 12) | 224);
- result += String.fromCharCode(((c >> 6) & 63) | 128);
- result += String.fromCharCode((c & 63) | 128);
- }
- }
-
- return result;
- };
-
- var base64 = function (text) {
- var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
-
- text = utf8(text);
- var result = '',
- chr1, chr2, chr3,
- enc1, enc2, enc3, enc4,
- i = 0;
-
- do {
- chr1 = text.charCodeAt(i++);
- chr2 = text.charCodeAt(i++);
- chr3 = text.charCodeAt(i++);
-
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
-
- if(isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if(isNaN(chr3)) {
- enc4 = 64;
- }
-
- result +=
- keyStr.charAt(enc1) +
- keyStr.charAt(enc2) +
- keyStr.charAt(enc3) +
- keyStr.charAt(enc4);
- chr1 = chr2 = chr3 = '';
- enc1 = enc2 = enc3 = enc4 = '';
- } while(i < text.length);
-
- return result;
- };
-
- var mergeHeaders = function () {
- // Use the first header object as base.
- var result = arguments[0];
-
- // Iterate through the remaining header objects and add them.
- for(var i = 1; i < arguments.length; i++) {
- var currentHeaders = arguments[i];
- for(var header in currentHeaders) {
- if(currentHeaders.hasOwnProperty(header)) {
- result[header] = currentHeaders[header];
- }
- }
- }
-
- // Return the merged headers.
- return result;
- };
-
- var ajax = function (method, url, options, callback) {
- // Adjust parameters.
- if(typeof options === 'function') {
- callback = options;
- options = {};
- }
-
- // Set default parameter values.
- options.cache = options.cache || false;
- options.data = options.data || {};
- options.headers = options.headers || {};
- options.jsonp = options.jsonp || false;
- options.async = options.async === undefined ? true : options.async;
-
- // Merge the various header objects.
- var headers = mergeHeaders({
- 'accept': '*/*',
- 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
- }, ajax.headers, options.headers);
-
- // Encode the data according to the content-type.
- var payload;
- if (headers['content-type'] === 'application/json') {
- payload = JSON.stringify(options.data);
- } else {
- payload = encodeUsingUrlEncoding(options.data);
- }
-
- // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
- // if neccessary.
- if(method === 'GET') {
- // Setup the query string.
- var queryString = [];
- if(payload) {
- queryString.push(payload);
- payload = null;
- }
-
- // Handle caching.
- if(!options.cache) {
- queryString.push('_=' + (new Date()).getTime());
- }
-
- // If neccessary prepare the query string for a JSONP call.
- if(options.jsonp) {
- queryString.push('callback=' + options.jsonp);
- queryString.push('jsonp=' + options.jsonp);
- }
-
- // Merge the query string and attach it to the url.
- queryString = queryString.join('&');
- if (queryString.length > 1) {
- if (url.indexOf('?') > -1) {
- url += '&' + queryString;
- } else {
- url += '?' + queryString;
- }
- }
-
- // Make a JSONP call if neccessary.
- if(options.jsonp) {
- var head = document.getElementsByTagName('head')[0];
- var script = document.createElement('script');
- script.type = 'text/javascript';
- script.src = url;
- head.appendChild(script);
- return;
- }
- }
-
- // Since we got here, it is no JSONP request, so make a normal XHR request.
- getXhr(function (err, xhr) {
- if(err) return callback(err);
-
- // Open the request.
- xhr.open(method, url, options.async);
-
- // Set the request headers.
- for(var header in headers) {
- if(headers.hasOwnProperty(header)) {
- xhr.setRequestHeader(header, headers[header]);
- }
- }
-
- // Handle the request events.
- xhr.onreadystatechange = function () {
- if(xhr.readyState === 4) {
- var data = xhr.responseText || '';
-
- // If no callback is given, return.
- if(!callback) {
- return;
- }
-
- // Return an object that provides access to the data as text and JSON.
- callback(xhr.status, {
- text: function () {
- return data;
- },
-
- json: function () {
- return JSON.parse(data);
- }
- });
- }
- };
-
- // Actually send the XHR request.
- xhr.send(payload);
- });
- };
-
- // Define the external interface.
- var http = {
- authBasic: function (username, password) {
- ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
- },
-
- connect: function (url, options, callback) {
- return ajax('CONNECT', url, options, callback);
- },
-
- del: function (url, options, callback) {
- return ajax('DELETE', url, options, callback);
- },
-
- get: function (url, options, callback) {
- return ajax('GET', url, options, callback);
- },
-
- head: function (url, options, callback) {
- return ajax('HEAD', url, options, callback);
- },
-
- headers: function (headers) {
- ajax.headers = headers || {};
- },
-
- isAllowed: function (url, verb, callback) {
- this.options(url, function (status, data) {
- callback(data.text().indexOf(verb) !== -1);
- });
- },
-
- options: function (url, options, callback) {
- return ajax('OPTIONS', url, options, callback);
- },
-
- patch: function (url, options, callback) {
- return ajax('PATCH', url, options, callback);
- },
-
- post: function (url, options, callback) {
- return ajax('POST', url, options, callback);
- },
-
- put: function (url, options, callback) {
- return ajax('PUT', url, options, callback);
- },
-
- trace: function (url, options, callback) {
- return ajax('TRACE', url, options, callback);
- }
- };
-
-
- var methode = options.type ? options.type.toLowerCase() : 'get';
-
- http[methode](options.url, options, function (status, data) {
- if (status === 200) {
- options.success(data.json(), status, null);
- } else {
- options.error(data.text(), status, null);
- }
- });
- }
-
- var _cookie = {
- create: function(name,value,minutes,domain) {
- var expires;
- if (minutes) {
- var date = new Date();
- date.setTime(date.getTime()+(minutes*60*1000));
- expires = "; expires="+date.toGMTString();
- }
- else expires = "";
- domain = (domain)? "domain="+domain+";" : "";
- document.cookie = name+"="+value+expires+";"+domain+"path=/";
- },
-
- read: function(name) {
- var nameEQ = name + "=";
- var ca = document.cookie.split(';');
- for(var i=0;i < ca.length;i++) {
- var c = ca[i];
- while (c.charAt(0)==' ') c = c.substring(1,c.length);
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
- }
- return null;
- },
-
- remove: function(name) {
- this.create(name,"",-1);
- }
- };
-
- var cookie_noop = {
- create: function(name,value,minutes,domain) {},
- read: function(name) { return null; },
- remove: function(name) {}
- };
-
-
-
- // move dependent functions to a container so that
- // they can be overriden easier in no jquery environment (node.js)
- var f = {
- extend: $ ? $.extend : _extend,
- each: $ ? $.each : _each,
- ajax: $ ? $.ajax : _ajax,
- cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
- detectLanguage: detectLanguage,
- escape: _escape,
- log: function(str) {
- if (o.debug && typeof console !== "undefined") console.log(str);
- },
- toLanguages: function(lng) {
- var languages = [];
- if (typeof lng === 'string' && lng.indexOf('-') > -1) {
- var parts = lng.split('-');
-
- lng = o.lowerCaseLng ?
- parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
- parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
-
- if (o.load !== 'unspecific') languages.push(lng);
- if (o.load !== 'current') languages.push(parts[0]);
- } else {
- languages.push(lng);
- }
-
- if (languages.indexOf(o.fallbackLng) === -1 && o.fallbackLng) languages.push(o.fallbackLng);
-
- return languages;
- },
- regexEscape: function(str) {
- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
- }
- };
- function init(options, cb) {
-
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- options = options || {};
-
- // override defaults with passed in options
- f.extend(o, options);
- delete o.fixLng; /* passed in each time */
-
- // create namespace object if namespace is passed in as string
- if (typeof o.ns == 'string') {
- o.ns = { namespaces: [o.ns], defaultNs: o.ns};
- }
-
- // fallback namespaces
- if (typeof o.fallbackNS == 'string') {
- o.fallbackNS = [o.fallbackNS];
- }
-
- // escape prefix/suffix
- o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
- o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
-
- if (!o.lng) o.lng = f.detectLanguage();
- if (o.lng) {
- // set cookie with lng set (as detectLanguage will set cookie on need)
- if (o.useCookie) f.cookie.create(o.cookieName, o.lng, o.cookieExpirationTime, o.cookieDomain);
- } else {
- o.lng = o.fallbackLng;
- if (o.useCookie) f.cookie.remove(o.cookieName);
- }
-
- languages = f.toLanguages(o.lng);
- currentLng = languages[0];
- f.log('currentLng set to: ' + currentLng);
-
- var lngTranslate = translate;
- if (options.fixLng) {
- lngTranslate = function(key, options) {
- options = options || {};
- options.lng = options.lng || lngTranslate.lng;
- return translate(key, options);
- };
- lngTranslate.lng = currentLng;
- }
-
- pluralExtensions.setCurrentLng(currentLng);
-
- // add JQuery extensions
- if ($ && o.setJqueryExt) addJqueryFunct();
-
- // jQuery deferred
- var deferred;
- if ($ && $.Deferred) {
- deferred = $.Deferred();
- }
-
- // return immidiatly if res are passed in
- if (o.resStore) {
- resStore = o.resStore;
- initialized = true;
- if (cb) cb(lngTranslate);
- if (deferred) deferred.resolve(lngTranslate);
- if (deferred) return deferred.promise();
- return;
- }
-
- // languages to load
- var lngsToLoad = f.toLanguages(o.lng);
- if (typeof o.preload === 'string') o.preload = [o.preload];
- for (var i = 0, l = o.preload.length; i < l; i++) {
- var pres = f.toLanguages(o.preload[i]);
- for (var y = 0, len = pres.length; y < len; y++) {
- if (lngsToLoad.indexOf(pres[y]) < 0) {
- lngsToLoad.push(pres[y]);
- }
- }
- }
-
- // else load them
- i18n.sync.load(lngsToLoad, o, function(err, store) {
- resStore = store;
- initialized = true;
-
- if (cb) cb(lngTranslate);
- if (deferred) deferred.resolve(lngTranslate);
- });
-
- if (deferred) return deferred.promise();
- }
- function preload(lngs, cb) {
- if (typeof lngs === 'string') lngs = [lngs];
- for (var i = 0, l = lngs.length; i < l; i++) {
- if (o.preload.indexOf(lngs[i]) < 0) {
- o.preload.push(lngs[i]);
- }
- }
- return init(cb);
- }
-
- function addResourceBundle(lng, ns, resources) {
- if (typeof ns !== 'string') {
- resources = ns;
- ns = o.ns.defaultNs;
- } else if (o.ns.namespaces.indexOf(ns) < 0) {
- o.ns.namespaces.push(ns);
- }
-
- resStore[lng] = resStore[lng] || {};
- resStore[lng][ns] = resStore[lng][ns] || {};
-
- f.extend(resStore[lng][ns], resources);
- }
-
- function setDefaultNamespace(ns) {
- o.ns.defaultNs = ns;
- }
-
- function loadNamespace(namespace, cb) {
- loadNamespaces([namespace], cb);
- }
-
- function loadNamespaces(namespaces, cb) {
- var opts = {
- dynamicLoad: o.dynamicLoad,
- resGetPath: o.resGetPath,
- getAsync: o.getAsync,
- customLoad: o.customLoad,
- ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
- };
-
- // languages to load
- var lngsToLoad = f.toLanguages(o.lng);
- if (typeof o.preload === 'string') o.preload = [o.preload];
- for (var i = 0, l = o.preload.length; i < l; i++) {
- var pres = f.toLanguages(o.preload[i]);
- for (var y = 0, len = pres.length; y < len; y++) {
- if (lngsToLoad.indexOf(pres[y]) < 0) {
- lngsToLoad.push(pres[y]);
- }
- }
- }
-
- // check if we have to load
- var lngNeedLoad = [];
- for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
- var needLoad = false;
- var resSet = resStore[lngsToLoad[a]];
- if (resSet) {
- for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
- if (!resSet[namespaces[b]]) needLoad = true;
- }
- } else {
- needLoad = true;
- }
-
- if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
- }
-
- if (lngNeedLoad.length) {
- i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
- var todo = namespaces.length * lngNeedLoad.length;
-
- // load each file individual
- f.each(namespaces, function(nsIndex, nsValue) {
-
- // append namespace to namespace array
- if (o.ns.namespaces.indexOf(nsValue) < 0) {
- o.ns.namespaces.push(nsValue);
- }
-
- f.each(lngNeedLoad, function(lngIndex, lngValue) {
- resStore[lngValue] = resStore[lngValue] || {};
- resStore[lngValue][nsValue] = store[lngValue][nsValue];
-
- todo--; // wait for all done befor callback
- if (todo === 0 && cb) {
- if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
- cb();
- }
- });
- });
- });
- } else {
- if (cb) cb();
- }
- }
-
- function setLng(lng, options, cb) {
- if (typeof options === 'function') {
- cb = options;
- options = {};
- }
- options.lng = lng;
- return init(options, cb);
- }
-
- function lng() {
- return currentLng;
- }
- function addJqueryFunct() {
- // $.t shortcut
- $.t = $.t || translate;
-
- function parse(ele, key, options) {
- if (key.length === 0) return;
-
- var attr = 'text';
-
- if (key.indexOf('[') === 0) {
- var parts = key.split(']');
- key = parts[1];
- attr = parts[0].substr(1, parts[0].length-1);
- }
-
- if (key.indexOf(';') === key.length-1) {
- key = key.substr(0, key.length-2);
- }
-
- var optionsToUse;
- if (attr === 'html') {
- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
- ele.html($.t(key, optionsToUse));
- }
- else if (attr === 'text') {
- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
- ele.text($.t(key, optionsToUse));
- } else {
- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
- ele.attr(attr, $.t(key, optionsToUse));
- }
- }
-
- function localize(ele, options) {
- var key = ele.attr(o.selectorAttr);
- if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
- if (!key) return;
-
- var target = ele
- , targetSelector = ele.data("i18n-target");
- if (targetSelector) {
- target = ele.find(targetSelector) || ele;
- }
-
- if (!options && o.useDataAttrOptions === true) {
- options = ele.data("i18n-options");
- }
- options = options || {};
-
- if (key.indexOf(';') >= 0) {
- var keys = key.split(';');
-
- $.each(keys, function(m, k) {
- if (k !== '') parse(target, k, options);
- });
-
- } else {
- parse(target, key, options);
- }
-
- if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
- }
-
- // fn
- $.fn.i18n = function (options) {
- return this.each(function() {
- // localize element itself
- localize($(this), options);
-
- // localize childs
- var elements = $(this).find('[' + o.selectorAttr + ']');
- elements.each(function() {
- localize($(this), options);
- });
- });
- };
- }
- function applyReplacement(str, replacementHash, nestedKey, options) {
- if (!str) return str;
-
- options = options || replacementHash; // first call uses replacement hash combined with options
- if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
-
- var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
- , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
- , unEscapingSuffix = 'HTML'+suffix;
-
- f.each(replacementHash, function(key, value) {
- var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
- if (typeof value === 'object' && value !== null) {
- str = applyReplacement(str, value, nextKey, options);
- } else {
- if (options.escapeInterpolation || o.escapeInterpolation) {
- str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), value);
- str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.escape(value));
- } else {
- str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), value);
- }
- // str = options.escapeInterpolation;
- }
- });
- return str;
- }
-
- // append it to functions
- f.applyReplacement = applyReplacement;
-
- function applyReuse(translated, options) {
- var comma = ',';
- var options_open = '{';
- var options_close = '}';
-
- var opts = f.extend({}, options);
- delete opts.postProcess;
-
- while (translated.indexOf(o.reusePrefix) != -1) {
- replacementCounter++;
- if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
- var index_of_opening = translated.lastIndexOf(o.reusePrefix);
- var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
- var token = translated.substring(index_of_opening, index_of_end_of_closing);
- var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
-
-
- if (token_without_symbols.indexOf(comma) != -1) {
- var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
- if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
- var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
- var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
- try {
- opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
- token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
- } catch (e) {
- }
- }
- }
-
- var translated_token = _translate(token_without_symbols, opts);
- translated = translated.replace(token, translated_token);
- }
- return translated;
- }
-
- function hasContext(options) {
- return (options.context && typeof options.context == 'string');
- }
-
- function needsPlural(options) {
- return (options.count !== undefined && typeof options.count != 'string' && options.count !== 1);
- }
-
- function exists(key, options) {
- options = options || {};
-
- var notFound = _getDefaultValue(key, options)
- , found = _find(key, options);
-
- return found !== undefined || found === notFound;
- }
-
- function translate(key, options) {
- if (!initialized) {
- f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
- return options.defaultValue || '';
- };
- replacementCounter = 0;
- return _translate.apply(null, arguments);
- }
-
- function _getDefaultValue(key, options) {
- return (options.defaultValue !== undefined) ? options.defaultValue : key;
- }
-
- function _injectSprintfProcessor() {
-
- var values = [];
-
- // mh: build array from second argument onwards
- for (var i = 1; i < arguments.length; i++) {
- values.push(arguments[i]);
- }
-
- return {
- postProcess: 'sprintf',
- sprintf: values
- };
- }
-
- function _translate(potentialKeys, options) {
- if (typeof options == 'string') {
- if (o.shortcutFunction === 'sprintf') {
- // mh: gettext like sprintf syntax found, automatically create sprintf processor
- options = _injectSprintfProcessor.apply(null, arguments);
- } else if (o.shortcutFunction === 'defaultValue') {
- options = {
- defaultValue: options
- }
- }
- } else {
- options = options || {};
- }
-
- if (typeof potentialKeys == 'string') {
- potentialKeys = [potentialKeys];
- }
-
- var key = null;
-
- for (var i = 0; i < potentialKeys.length; i++) {
- key = potentialKeys[i];
- if (exists(key)) {
- break;
- }
- }
-
- var notFound = _getDefaultValue(key, options)
- , found = _find(key, options)
- , lngs = options.lng ? f.toLanguages(options.lng) : languages
- , ns = options.ns || o.ns.defaultNs
- , parts;
-
- // split ns and key
- if (key.indexOf(o.nsseparator) > -1) {
- parts = key.split(o.nsseparator);
- ns = parts[0];
- key = parts[1];
- }
-
- if (found === undefined && o.sendMissing) {
- if (options.lng) {
- sync.postMissing(lngs[0], ns, key, notFound, lngs);
- } else {
- sync.postMissing(o.lng, ns, key, notFound, lngs);
- }
- }
-
- var postProcessor = options.postProcess || o.postProcess;
- if (found !== undefined && postProcessor) {
- if (postProcessors[postProcessor]) {
- found = postProcessors[postProcessor](found, key, options);
- }
- }
-
- // process notFound if function exists
- var splitNotFound = notFound;
- if (notFound.indexOf(o.nsseparator) > -1) {
- parts = notFound.split(o.nsseparator);
- splitNotFound = parts[1];
- }
- if (splitNotFound === key && o.parseMissingKey) {
- notFound = o.parseMissingKey(notFound);
- }
-
- if (found === undefined) {
- notFound = applyReplacement(notFound, options);
- notFound = applyReuse(notFound, options);
-
- if (postProcessor && postProcessors[postProcessor]) {
- var val = _getDefaultValue(key, options);
- found = postProcessors[postProcessor](val, key, options);
- }
- }
-
- return (found !== undefined) ? found : notFound;
- }
-
- function _find(key, options){
- options = options || {};
-
- var optionWithoutCount, translated
- , notFound = _getDefaultValue(key, options)
- , lngs = languages;
-
- if (!resStore) { return notFound; } // no resStore to translate from
-
- if (options.lng) {
- lngs = f.toLanguages(options.lng);
-
- if (!resStore[lngs[0]]) {
- var oldAsync = o.getAsync;
- o.getAsync = false;
-
- i18n.sync.load(lngs, o, function(err, store) {
- f.extend(resStore, store);
- o.getAsync = oldAsync;
- });
- }
- }
-
- var ns = options.ns || o.ns.defaultNs;
- if (key.indexOf(o.nsseparator) > -1) {
- var parts = key.split(o.nsseparator);
- ns = parts[0];
- key = parts[1];
- }
-
- if (hasContext(options)) {
- optionWithoutCount = f.extend({}, options);
- delete optionWithoutCount.context;
- optionWithoutCount.defaultValue = o.contextNotFound;
-
- var contextKey = ns + o.nsseparator + key + '_' + options.context;
-
- translated = translate(contextKey, optionWithoutCount);
- if (translated != o.contextNotFound) {
- return applyReplacement(translated, { context: options.context }); // apply replacement for context only
- } // else continue translation with original/nonContext key
- }
-
- if (needsPlural(options)) {
- optionWithoutCount = f.extend({}, options);
- delete optionWithoutCount.count;
- optionWithoutCount.defaultValue = o.pluralNotFound;
-
- var pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
- var pluralExtension = pluralExtensions.get(lngs[0], options.count);
- if (pluralExtension >= 0) {
- pluralKey = pluralKey + '_' + pluralExtension;
- } else if (pluralExtension === 1) {
- pluralKey = ns + o.nsseparator + key; // singular
- }
-
- translated = translate(pluralKey, optionWithoutCount);
- if (translated != o.pluralNotFound) {
- return applyReplacement(translated, {
- count: options.count,
- interpolationPrefix: options.interpolationPrefix,
- interpolationSuffix: options.interpolationSuffix
- }); // apply replacement for count only
- } // else continue translation with original/singular key
- }
-
- var found;
- var keys = key.split(o.keyseparator);
- for (var i = 0, len = lngs.length; i < len; i++ ) {
- if (found !== undefined) break;
-
- var l = lngs[i];
-
- var x = 0;
- var value = resStore[l] && resStore[l][ns];
- while (keys[x]) {
- value = value && value[keys[x]];
- x++;
- }
- if (value !== undefined) {
- if (typeof value === 'string') {
- value = applyReplacement(value, options);
- value = applyReuse(value, options);
- } else if (Object.prototype.toString.apply(value) === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
- value = value.join('\n');
- value = applyReplacement(value, options);
- value = applyReuse(value, options);
- } else if (value === null && o.fallbackOnNull === true) {
- value = undefined;
- } else if (value !== null) {
- if (!o.returnObjectTrees && !options.returnObjectTrees) {
- value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
- 'returned a object instead of string.';
- f.log(value);
- } else if (typeof value !== 'number') {
- var copy = {}; // apply child translation on a copy
- f.each(value, function(m) {
- copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
- });
- value = copy;
- }
- }
- found = value;
- }
- }
-
- if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
- // set flag for fallback lookup - avoid recursion
- options.isFallbackLookup = true;
-
- if (o.fallbackNS.length) {
-
- for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
- found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
-
- if (found) {
- /* compare value without namespace */
- var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
- , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
-
- if (foundValue !== notFoundValue) break;
- }
- }
- } else {
- found = _find(key, options); // fallback to default NS
- }
- }
-
- return found;
- }
- function detectLanguage() {
- var detectedLng;
-
- // get from qs
- var qsParm = [];
- if (typeof window !== 'undefined') {
- (function() {
- var query = window.location.search.substring(1);
- var parms = query.split('&');
- for (var i=0; i<parms.length; i++) {
- var pos = parms[i].indexOf('=');
- if (pos > 0) {
- var key = parms[i].substring(0,pos);
- var val = parms[i].substring(pos+1);
- qsParm[key] = val;
- }
- }
- })();
- if (qsParm[o.detectLngQS]) {
- detectedLng = qsParm[o.detectLngQS];
- }
- }
-
- // get from cookie
- if (!detectedLng && typeof document !== 'undefined' && o.useCookie ) {
- var c = f.cookie.read(o.cookieName);
- if (c) detectedLng = c;
- }
-
- // get from navigator
- if (!detectedLng && typeof navigator !== 'undefined') {
- detectedLng = (navigator.language) ? navigator.language : navigator.userLanguage;
- }
-
- return detectedLng;
- }
- var sync = {
-
- load: function(lngs, options, cb) {
- if (options.useLocalStorage) {
- sync._loadLocal(lngs, options, function(err, store) {
- var missingLngs = [];
- for (var i = 0, len = lngs.length; i < len; i++) {
- if (!store[lngs[i]]) missingLngs.push(lngs[i]);
- }
-
- if (missingLngs.length > 0) {
- sync._fetch(missingLngs, options, function(err, fetched) {
- f.extend(store, fetched);
- sync._storeLocal(fetched);
-
- cb(null, store);
- });
- } else {
- cb(null, store);
- }
- });
- } else {
- sync._fetch(lngs, options, function(err, store){
- cb(null, store);
- });
- }
- },
-
- _loadLocal: function(lngs, options, cb) {
- var store = {}
- , nowMS = new Date().getTime();
-
- if(window.localStorage) {
-
- var todo = lngs.length;
-
- f.each(lngs, function(key, lng) {
- var local = window.localStorage.getItem('res_' + lng);
-
- if (local) {
- local = JSON.parse(local);
-
- if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
- store[lng] = local;
- }
- }
-
- todo--; // wait for all done befor callback
- if (todo === 0) cb(null, store);
- });
- }
- },
-
- _storeLocal: function(store) {
- if(window.localStorage) {
- for (var m in store) {
- store[m].i18nStamp = new Date().getTime();
- window.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
- }
- }
- return;
- },
-
- _fetch: function(lngs, options, cb) {
- var ns = options.ns
- , store = {};
-
- if (!options.dynamicLoad) {
- var todo = ns.namespaces.length * lngs.length
- , errors;
-
- // load each file individual
- f.each(ns.namespaces, function(nsIndex, nsValue) {
- f.each(lngs, function(lngIndex, lngValue) {
-
- // Call this once our translation has returned.
- var loadComplete = function(err, data) {
- if (err) {
- errors = errors || [];
- errors.push(err);
- }
- store[lngValue] = store[lngValue] || {};
- store[lngValue][nsValue] = data;
-
- todo--; // wait for all done befor callback
- if (todo === 0) cb(errors, store);
- };
-
- if(typeof options.customLoad == 'function'){
- // Use the specified custom callback.
- options.customLoad(lngValue, nsValue, options, loadComplete);
- } else {
- //~ // Use our inbuilt sync.
- sync._fetchOne(lngValue, nsValue, options, loadComplete);
- }
- });
- });
- } else {
- // Call this once our translation has returned.
- var loadComplete = function(err, data) {
- cb(null, data);
- };
-
- if(typeof options.customLoad == 'function'){
- // Use the specified custom callback.
- options.customLoad(lngs, ns.namespaces, options, loadComplete);
- } else {
- var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
- // load all needed stuff once
- f.ajax({
- url: url,
- success: function(data, status, xhr) {
- f.log('loaded: ' + url);
- loadComplete(null, data);
- },
- error : function(xhr, status, error) {
- f.log('failed loading: ' + url);
- loadComplete('failed loading resource.json error: ' + error);
- },
- dataType: "json",
- async : options.getAsync
- });
- }
- }
- },
-
- _fetchOne: function(lng, ns, options, done) {
- var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
- f.ajax({
- url: url,
- success: function(data, status, xhr) {
- f.log('loaded: ' + url);
- done(null, data);
- },
- error : function(xhr, status, error) {
- f.log('failed loading: ' + url);
- done(error, {});
- },
- dataType: "json",
- async : options.getAsync
- });
- },
-
- postMissing: function(lng, ns, key, defaultValue, lngs) {
- var payload = {};
- payload[key] = defaultValue;
-
- var urls = [];
-
- if (o.sendMissingTo === 'fallback' && o.fallbackLng !== false) {
- urls.push({lng: o.fallbackLng, url: applyReplacement(o.resPostPath, { lng: o.fallbackLng, ns: ns })});
- } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng === false) ) {
- urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
- } else if (o.sendMissingTo === 'all') {
- for (var i = 0, l = lngs.length; i < l; i++) {
- urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
- }
- }
-
- for (var y = 0, len = urls.length; y < len; y++) {
- var item = urls[y];
- f.ajax({
- url: item.url,
- type: o.sendType,
- data: payload,
- success: function(data, status, xhr) {
- f.log('posted missing key \'' + key + '\' to: ' + item.url);
-
- // add key to resStore
- var keys = key.split('.');
- var x = 0;
- var value = resStore[item.lng][ns];
- while (keys[x]) {
- if (x === keys.length - 1) {
- value = value[keys[x]] = defaultValue;
- } else {
- value = value[keys[x]] = value[keys[x]] || {};
- }
- x++;
- }
- },
- error : function(xhr, status, error) {
- f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
- },
- dataType: "json",
- async : o.postAsync
- });
- }
- }
- };
- // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
- var pluralExtensions = {
-
- rules: {
- "ach": {
- "name": "Acholi",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "af": {
- "name": "Afrikaans",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ak": {
- "name": "Akan",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "am": {
- "name": "Amharic",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "an": {
- "name": "Aragonese",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ar": {
- "name": "Arabic",
- "numbers": [
- 0,
- 1,
- 2,
- 3,
- 11,
- 100
- ],
- "plurals": function(n) { return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5); }
- },
- "arn": {
- "name": "Mapudungun",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "ast": {
- "name": "Asturian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ay": {
- "name": "Aymar\u00e1",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "az": {
- "name": "Azerbaijani",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "be": {
- "name": "Belarusian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "bg": {
- "name": "Bulgarian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "bn": {
- "name": "Bengali",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "bo": {
- "name": "Tibetan",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "br": {
- "name": "Breton",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "bs": {
- "name": "Bosnian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "ca": {
- "name": "Catalan",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "cgg": {
- "name": "Chiga",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "cs": {
- "name": "Czech",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2); }
- },
- "csb": {
- "name": "Kashubian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "cy": {
- "name": "Welsh",
- "numbers": [
- 1,
- 2,
- 3,
- 8
- ],
- "plurals": function(n) { return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3); }
- },
- "da": {
- "name": "Danish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "de": {
- "name": "German",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "dz": {
- "name": "Dzongkha",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "el": {
- "name": "Greek",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "en": {
- "name": "English",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "eo": {
- "name": "Esperanto",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "es": {
- "name": "Spanish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "es_ar": {
- "name": "Argentinean Spanish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "et": {
- "name": "Estonian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "eu": {
- "name": "Basque",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "fa": {
- "name": "Persian",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "fi": {
- "name": "Finnish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "fil": {
- "name": "Filipino",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "fo": {
- "name": "Faroese",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "fr": {
- "name": "French",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "fur": {
- "name": "Friulian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "fy": {
- "name": "Frisian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ga": {
- "name": "Irish",
- "numbers": [
- 1,
- 2,
- 3,
- 7,
- 11
- ],
- "plurals": function(n) { return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;}
- },
- "gd": {
- "name": "Scottish Gaelic",
- "numbers": [
- 1,
- 2,
- 3,
- 20
- ],
- "plurals": function(n) { return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3); }
- },
- "gl": {
- "name": "Galician",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "gu": {
- "name": "Gujarati",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "gun": {
- "name": "Gun",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "ha": {
- "name": "Hausa",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "he": {
- "name": "Hebrew",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "hi": {
- "name": "Hindi",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "hr": {
- "name": "Croatian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "hu": {
- "name": "Hungarian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "hy": {
- "name": "Armenian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ia": {
- "name": "Interlingua",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "id": {
- "name": "Indonesian",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "is": {
- "name": "Icelandic",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n%10!=1 || n%100==11); }
- },
- "it": {
- "name": "Italian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ja": {
- "name": "Japanese",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "jbo": {
- "name": "Lojban",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "jv": {
- "name": "Javanese",
- "numbers": [
- 0,
- 1
- ],
- "plurals": function(n) { return Number(n !== 0); }
- },
- "ka": {
- "name": "Georgian",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "kk": {
- "name": "Kazakh",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "km": {
- "name": "Khmer",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "kn": {
- "name": "Kannada",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ko": {
- "name": "Korean",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "ku": {
- "name": "Kurdish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "kw": {
- "name": "Cornish",
- "numbers": [
- 1,
- 2,
- 3,
- 4
- ],
- "plurals": function(n) { return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3); }
- },
- "ky": {
- "name": "Kyrgyz",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "lb": {
- "name": "Letzeburgesch",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ln": {
- "name": "Lingala",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "lo": {
- "name": "Lao",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "lt": {
- "name": "Lithuanian",
- "numbers": [
- 1,
- 2,
- 10
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "lv": {
- "name": "Latvian",
- "numbers": [
- 0,
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2); }
- },
- "mai": {
- "name": "Maithili",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "mfe": {
- "name": "Mauritian Creole",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "mg": {
- "name": "Malagasy",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "mi": {
- "name": "Maori",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "mk": {
- "name": "Macedonian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n==1 || n%10==1 ? 0 : 1); }
- },
- "ml": {
- "name": "Malayalam",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "mn": {
- "name": "Mongolian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "mnk": {
- "name": "Mandinka",
- "numbers": [
- 0,
- 1,
- 2
- ],
- "plurals": function(n) { return Number(0 ? 0 : n==1 ? 1 : 2); }
- },
- "mr": {
- "name": "Marathi",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ms": {
- "name": "Malay",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "mt": {
- "name": "Maltese",
- "numbers": [
- 1,
- 2,
- 11,
- 20
- ],
- "plurals": function(n) { return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3); }
- },
- "nah": {
- "name": "Nahuatl",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "nap": {
- "name": "Neapolitan",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "nb": {
- "name": "Norwegian Bokmal",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ne": {
- "name": "Nepali",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "nl": {
- "name": "Dutch",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "nn": {
- "name": "Norwegian Nynorsk",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "no": {
- "name": "Norwegian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "nso": {
- "name": "Northern Sotho",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "oc": {
- "name": "Occitan",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "or": {
- "name": "Oriya",
- "numbers": [
- 2,
- 1
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "pa": {
- "name": "Punjabi",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "pap": {
- "name": "Papiamento",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "pl": {
- "name": "Polish",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "pms": {
- "name": "Piemontese",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ps": {
- "name": "Pashto",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "pt": {
- "name": "Portuguese",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "pt_br": {
- "name": "Brazilian Portuguese",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "rm": {
- "name": "Romansh",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ro": {
- "name": "Romanian",
- "numbers": [
- 1,
- 2,
- 20
- ],
- "plurals": function(n) { return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2); }
- },
- "ru": {
- "name": "Russian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "sah": {
- "name": "Yakut",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "sco": {
- "name": "Scots",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "se": {
- "name": "Northern Sami",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "si": {
- "name": "Sinhala",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "sk": {
- "name": "Slovak",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2); }
- },
- "sl": {
- "name": "Slovenian",
- "numbers": [
- 5,
- 1,
- 2,
- 3
- ],
- "plurals": function(n) { return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
- },
- "so": {
- "name": "Somali",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "son": {
- "name": "Songhay",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "sq": {
- "name": "Albanian",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "sr": {
- "name": "Serbian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "su": {
- "name": "Sundanese",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "sv": {
- "name": "Swedish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "sw": {
- "name": "Swahili",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "ta": {
- "name": "Tamil",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "te": {
- "name": "Telugu",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "tg": {
- "name": "Tajik",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "th": {
- "name": "Thai",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "ti": {
- "name": "Tigrinya",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "tk": {
- "name": "Turkmen",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "tr": {
- "name": "Turkish",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "tt": {
- "name": "Tatar",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "ug": {
- "name": "Uyghur",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "uk": {
- "name": "Ukrainian",
- "numbers": [
- 1,
- 2,
- 5
- ],
- "plurals": function(n) { return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); }
- },
- "ur": {
- "name": "Urdu",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "uz": {
- "name": "Uzbek",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "vi": {
- "name": "Vietnamese",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "wa": {
- "name": "Walloon",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n > 1); }
- },
- "wo": {
- "name": "Wolof",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- },
- "yo": {
- "name": "Yoruba",
- "numbers": [
- 1,
- 2
- ],
- "plurals": function(n) { return Number(n != 1); }
- },
- "zh": {
- "name": "Chinese",
- "numbers": [
- 1
- ],
- "plurals": function(n) { return 0; }
- }
- },
-
- // for demonstration only sl and ar is added but you can add your own pluralExtensions
- addRule: function(lng, obj) {
- pluralExtensions.rules[lng] = obj;
- },
-
- setCurrentLng: function(lng) {
- if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
- var parts = lng.split('-');
-
- pluralExtensions.currentRule = {
- lng: lng,
- rule: pluralExtensions.rules[parts[0]]
- };
- }
- },
-
- get: function(lng, count) {
- var parts = lng.split('-');
-
- function getResult(l, c) {
- var ext;
- if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
- ext = pluralExtensions.currentRule.rule;
- } else {
- ext = pluralExtensions.rules[l];
- }
- if (ext) {
- var i = ext.plurals(c);
- var number = ext.numbers[i];
- if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
- if (number === 2) {
- number = -1; // regular plural
- } else if (number === 1) {
- number = 1; // singular
- }
- }//console.log(count + '-' + number);
- return number;
- } else {
- return c === 1 ? '1' : '-1';
- }
- }
-
- return getResult(parts[0], count);
- }
-
- };
- var postProcessors = {};
- var addPostProcessor = function(name, fc) {
- postProcessors[name] = fc;
- };
- // sprintf support
- var sprintf = (function() {
- function get_type(variable) {
- return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
- }
- function str_repeat(input, multiplier) {
- for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
- return output.join('');
- }
-
- var str_format = function() {
- if (!str_format.cache.hasOwnProperty(arguments[0])) {
- str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
- }
- return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
- };
-
- str_format.format = function(parse_tree, argv) {
- var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
- for (i = 0; i < tree_length; i++) {
- node_type = get_type(parse_tree[i]);
- if (node_type === 'string') {
- output.push(parse_tree[i]);
- }
- else if (node_type === 'array') {
- match = parse_tree[i]; // convenience purposes only
- if (match[2]) { // keyword argument
- arg = argv[cursor];
- for (k = 0; k < match[2].length; k++) {
- if (!arg.hasOwnProperty(match[2][k])) {
- throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
- }
- arg = arg[match[2][k]];
- }
- }
- else if (match[1]) { // positional argument (explicit)
- arg = argv[match[1]];
- }
- else { // positional argument (implicit)
- arg = argv[cursor++];
- }
-
- if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
- throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
- }
- switch (match[8]) {
- case 'b': arg = arg.toString(2); break;
- case 'c': arg = String.fromCharCode(arg); break;
- case 'd': arg = parseInt(arg, 10); break;
- case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
- case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
- case 'o': arg = arg.toString(8); break;
- case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
- case 'u': arg = Math.abs(arg); break;
- case 'x': arg = arg.toString(16); break;
- case 'X': arg = arg.toString(16).toUpperCase(); break;
- }
- arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
- pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
- pad_length = match[6] - String(arg).length;
- pad = match[6] ? str_repeat(pad_character, pad_length) : '';
- output.push(match[5] ? arg + pad : pad + arg);
- }
- }
- return output.join('');
- };
-
- str_format.cache = {};
-
- str_format.parse = function(fmt) {
- var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
- while (_fmt) {
- if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
- parse_tree.push(match[0]);
- }
- else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
- parse_tree.push('%');
- }
- else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
- if (match[2]) {
- arg_names |= 1;
- var field_list = [], replacement_field = match[2], field_match = [];
- if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
- field_list.push(field_match[1]);
- while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
- if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
- field_list.push(field_match[1]);
- }
- else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
- field_list.push(field_match[1]);
- }
- else {
- throw('[sprintf] huh?');
- }
- }
- }
- else {
- throw('[sprintf] huh?');
- }
- match[2] = field_list;
- }
- else {
- arg_names |= 2;
- }
- if (arg_names === 3) {
- throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
- }
- parse_tree.push(match);
- }
- else {
- throw('[sprintf] huh?');
- }
- _fmt = _fmt.substring(match[0].length);
- }
- return parse_tree;
- };
-
- return str_format;
- })();
-
- var vsprintf = function(fmt, argv) {
- argv.unshift(fmt);
- return sprintf.apply(null, argv);
- };
-
- addPostProcessor("sprintf", function(val, key, opts) {
- if (!opts.sprintf) return val;
-
- if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
- return vsprintf(val, opts.sprintf);
- } else if (typeof opts.sprintf === 'object') {
- return sprintf(val, opts.sprintf);
- }
-
- return val;
- });
- // public api interface
- i18n.init = init;
- i18n.setLng = setLng;
- i18n.preload = preload;
- i18n.addResourceBundle = addResourceBundle;
- i18n.loadNamespace = loadNamespace;
- i18n.loadNamespaces = loadNamespaces;
- i18n.setDefaultNamespace = setDefaultNamespace;
- i18n.t = translate;
- i18n.translate = translate;
- i18n.exists = exists;
- i18n.detectLanguage = f.detectLanguage;
- i18n.pluralExtensions = pluralExtensions;
- i18n.sync = sync;
- i18n.functions = f;
- i18n.lng = lng;
- i18n.addPostProcessor = addPostProcessor;
- i18n.options = o;
-
-})();
\ No newline at end of file
diff --git a/data/libs/jsoneditor/LICENSE[Apache 2.0] b/data/libs/jsoneditor/LICENSE[Apache 2.0]
deleted file mode 100644
index ea2712c09..000000000
--- a/data/libs/jsoneditor/LICENSE[Apache 2.0]
+++ /dev/null
@@ -1,176 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
diff --git a/data/libs/jsoneditor/img/jsoneditor-icons.png b/data/libs/jsoneditor/img/jsoneditor-icons.png
deleted file mode 100644
index 1a41fa2be..000000000
Binary files a/data/libs/jsoneditor/img/jsoneditor-icons.png and /dev/null differ
diff --git a/data/libs/jsoneditor/img/jsoneditor-icons.svg b/data/libs/jsoneditor/img/jsoneditor-icons.svg
deleted file mode 100644
index ae3c760eb..000000000
--- a/data/libs/jsoneditor/img/jsoneditor-icons.svg
+++ /dev/null
@@ -1,606 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="408"
- height="48"
- id="svg2"
- version="1.1"
- inkscape:version="0.48.3.1 r9886"
- sodipodi:docname="jsoneditor-icons.svg"
- inkscape:export-filename="/home/jos/jsoneditoronline/img/svg/duplicate.png"
- inkscape:export-xdpi="90"
- inkscape:export-ydpi="90">
- <defs
- id="defs4" />
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="2.0064148"
- inkscape:cx="113.57122"
- inkscape:cy="23.319345"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- showgrid="false"
- inkscape:snap-grids="true"
- inkscape:window-width="1600"
- inkscape:window-height="849"
- inkscape:window-x="0"
- inkscape:window-y="0"
- inkscape:window-maximized="1"
- showguides="true"
- inkscape:guide-bbox="true" />
- <metadata
- id="metadata7">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title />
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(0,-1004.3622)">
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754"
- width="16"
- height="16"
- x="4"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 11.03125,1035.7997 0,3.375 -3.4375001,0 0,2.25 3.4062501,0 0,3.3437 2.21875,0 0,-3.3125 3.40625,0 0,-2.3125 -3.34375,0 0,-3.375 z"
- id="path4368"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#109618;fill-opacity:1;stroke:none"
- id="rect3754-7"
- width="16"
- height="16"
- x="4"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 11.03125,1011.7997 0,3.375 -3.4375,0 0,2.25 3.40625,0 0,3.3438 2.21875,0 0,-3.3125 3.40625,0 0,-2.3125 -3.34375,0 0,-3.375 z"
- id="path4368-1"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#ff0000;fill-opacity:1;stroke:none"
- id="rect3754-9"
- width="16"
- height="16"
- x="28"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 38.506909,1012.3462 -2.386486,2.3865 -2.430679,-2.4307 -1.59099,1.591 2.408582,2.4086 -2.364388,2.3644 1.568893,1.5689 2.342291,-2.3423 2.408583,2.4086 1.635184,-1.6352 -2.364388,-2.3644 2.386485,-2.3865 z"
- id="path4368-9"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-6"
- width="16"
- height="16"
- x="28"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 38.506909,1036.3462 -2.386486,2.3865 -2.430679,-2.4307 -1.59099,1.591 2.408582,2.4086 -2.364388,2.3644 1.568893,1.5689 2.342291,-2.3423 2.408583,2.4086 1.635184,-1.6352 -2.364388,-2.3644 2.386485,-2.3865 z"
- id="path4368-7"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- id="rect3754-3"
- width="16"
- height="16"
- x="52"
- y="1008.3622" />
- <rect
- style="fill:#ffffff;fill-opacity:1;stroke:#97b0f8;stroke-width:0.91546917;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3776-1"
- width="8.0845308"
- height="8.0845308"
- x="54.457733"
- y="1010.8199" />
- <rect
- style="fill:#ffffff;fill-opacity:1;stroke:#97b0f8;stroke-width:0.90154964;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3776-1-6"
- width="8.0984497"
- height="8.0984507"
- x="57.459774"
- y="1013.8041" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-2"
- width="16"
- height="16"
- x="52"
- y="1032.3622" />
- <rect
- style="fill:#ffffff;fill-opacity:1;stroke:#d3d3d3;stroke-width:0.91546917;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3776-1-0"
- width="8.0845308"
- height="8.0845308"
- x="54.457733"
- y="1034.8198" />
- <rect
- style="fill:#ffffff;fill-opacity:1;stroke:#d3d3d3;stroke-width:0.90154964;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3776-1-6-4"
- width="8.0984497"
- height="8.0984507"
- x="57.459774"
- y="1037.804" />
- <rect
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- id="rect3754-4"
- width="16"
- height="16"
- x="76"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:0.2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 85.104474,1010.3779 -0.01563,1.4063 c 3.026682,-0.2402 0.330075,3.6508 2.484376,4.5781 -2.186943,1.0938 0.491913,4.9069 -2.453126,4.5781 l -0.01563,1.4219 c 5.708274,0.559 1.032633,-5.1005 4.703126,-5.2656 l 0,-1.4063 c -3.613031,-0.027 1.118935,-5.707 -4.703126,-5.3125 z"
- id="path4351"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccccccc" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:0.2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 82.781251,1010.3606 0.01563,1.4063 c -3.026681,-0.2402 -0.330074,3.6507 -2.484375,4.5781 2.186942,1.0938 -0.491913,4.9069 2.453125,4.5781 l 0.01562,1.4219 c -5.708273,0.559 -1.032632,-5.1004 -4.703125,-5.2656 l 0,-1.4063 c 3.613031,-0.027 -1.118935,-5.7071 4.703125,-5.3125 z"
- id="path4351-9"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccccccc" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-8"
- width="16"
- height="16"
- x="76"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:0.2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 85.10448,1034.3777 -0.01563,1.4063 c 3.026682,-0.2402 0.330074,3.6508 2.484376,4.5781 -2.186943,1.0938 0.491913,4.9069 -2.453126,4.5781 l -0.01563,1.4219 c 5.708274,0.559 1.032633,-5.1005 4.703126,-5.2656 l 0,-1.4063 c -3.613031,-0.027 1.118935,-5.707 -4.703126,-5.3125 z"
- id="path4351-1"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccccccc" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:0.2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 82.781257,1034.3604 0.01563,1.4063 c -3.026681,-0.2402 -0.330075,3.6507 -2.484375,4.5781 2.186942,1.0938 -0.491913,4.9069 2.453125,4.5781 l 0.01562,1.4219 c -5.708273,0.559 -1.032632,-5.1004 -4.703125,-5.2656 l 0,-1.4063 c 3.613031,-0.027 -1.118935,-5.7071 4.703125,-5.3125 z"
- id="path4351-9-5"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccccccc" />
- <rect
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- id="rect3754-25"
- width="16"
- height="16"
- x="100"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 104.21875,1010.0341 0,12.7188 3.03125,0 0,-1.5313 -1.34375,0 0,-9.625 1.375,0 0,-1.5625 z"
- id="path2987"
- inkscape:connector-curvature="0" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 111.71875,1010.0341 0,12.7188 -3.03125,0 0,-1.5313 1.34375,0 0,-9.625 -1.375,0 0,-1.5625 z"
- id="path2987-1"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-65"
- width="16"
- height="16"
- x="100"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 104.21875,1034.0341 0,12.7188 3.03125,0 0,-1.5313 -1.34375,0 0,-9.625 1.375,0 0,-1.5625 z"
- id="path2987-8"
- inkscape:connector-curvature="0" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 111.71875,1034.0341 0,12.7188 -3.03125,0 0,-1.5313 1.34375,0 0,-9.625 -1.375,0 0,-1.5625 z"
- id="path2987-1-9"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- id="rect3754-73"
- width="16"
- height="16"
- x="124"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 126.2824,1021.9651 1.78957,0 1.14143,-2.8641 5.65364,0 1.14856,2.8641 1.76565,0 -4.78687,-11.1611 -1.91903,0 z"
- id="path3780"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccccc" />
- <path
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- d="m 129.72704,1017.841 4.60852,0.01 -2.30426,-5.5498 z"
- id="path3782"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-92"
- width="16"
- height="16"
- x="124"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 126.2824,1045.9651 1.78957,0 1.14143,-2.8641 5.65364,0 1.14856,2.8641 1.76565,0 -4.78687,-11.1611 -1.91902,0 z"
- id="path3780-9"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccccc" />
- <path
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- d="m 129.72704,1041.841 4.60852,0.01 -2.30426,-5.5498 z"
- id="path3782-2"
- inkscape:connector-curvature="0" />
- <rect
- style="fill:#97b0f8;fill-opacity:1;stroke:none"
- id="rect3754-35"
- width="16"
- height="16"
- x="148"
- y="1008.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 156.47655,1010.2539 0,2.1797 0.46093,2.3984 1.82813,0 0.39844,-2.3984 0,-2.1797 z"
- id="path5008-2"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 152.51561,1010.2528 0,2.1797 0.46094,2.3984 1.82812,0 0.39844,-2.3984 0,-2.1797 z"
- id="path5008-2-8"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3754-47"
- width="16"
- height="16"
- x="148"
- y="1032.3622" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 156.47656,1034.2539 0,2.1797 0.46093,2.3984 1.82813,0 0.39844,-2.3984 0,-2.1797 z"
- id="path5008-2-1"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#ffffff;fill-opacity:1;stroke:none"
- d="m 152.51562,1034.2528 0,2.1797 0.46094,2.3984 1.82812,0 0.39844,-2.3984 0,-2.1797 z"
- id="path5008-2-8-8"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="opacity:0.9;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 177.0157,1012.3622 -0.0157,8 7,-3.9844 z"
- id="path3055"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.9;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 184,1037.3782 -8,-0.016 3.9844,7 z"
- id="path3055-0"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.9;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 206.9844,1012.3622 0.0156,8 -7,-3.9844 z"
- id="path3055-3"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.9;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 208,1043.3462 -8,0.016 3.9844,-7 z"
- id="path3055-0-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073"
- width="3"
- height="3"
- x="223.99998"
- y="1008.3622" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073-9"
- width="3"
- height="3"
- x="228.99998"
- y="1008.3622" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073-6"
- width="3"
- height="3"
- x="223.99998"
- y="1014.3622" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073-9-3"
- width="3"
- height="3"
- x="228.99998"
- y="1014.3622" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073-6-5"
- width="3"
- height="3"
- x="223.99998"
- y="1020.3622" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect5073-9-3-8"
- width="3"
- height="3"
- x="228.99998"
- y="1020.3622" />
- <path
- sodipodi:type="arc"
- style="fill:none;stroke:#4d4d4d;stroke-width:2.47487354;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path3131"
- sodipodi:cx="254.02811"
- sodipodi:cy="10.169789"
- sodipodi:rx="6.1871839"
- sodipodi:ry="6.1871839"
- d="m 260.21529,10.169789 c 0,3.417088 -2.7701,6.187184 -6.18718,6.187184 -3.41709,0 -6.18719,-2.770096 -6.18719,-6.187184 0,-3.417087 2.7701,-6.1871835 6.18719,-6.1871835 3.41708,0 6.18718,2.7700965 6.18718,6.1871835 z"
- transform="matrix(0.8081221,0,0,0.8081221,48.714273,1006.1438)" />
- <rect
- style="fill:#4d4d4d;fill-opacity:1;stroke:none"
- id="rect3901"
- width="7.0766954"
- height="4.3238611"
- x="-538.12122"
- y="909.72101"
- transform="matrix(0.72654224,-0.6871218,0.6979248,0.71617106,0,0)"
- ry="0" />
- <path
- sodipodi:type="arc"
- style="fill:none;stroke:#d3d3d3;stroke-width:2.47487354;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path3131-4"
- sodipodi:cx="254.02811"
- sodipodi:cy="10.169789"
- sodipodi:rx="6.1871839"
- sodipodi:ry="6.1871839"
- d="m 260.21529,10.169789 c 0,3.417088 -2.7701,6.187184 -6.18718,6.187184 -3.41709,0 -6.18719,-2.770096 -6.18719,-6.187184 0,-3.417087 2.7701,-6.1871835 6.18719,-6.1871835 3.41708,0 6.18718,2.7700965 6.18718,6.1871835 z"
- transform="matrix(0.8081221,0,0,0.8081221,48.489728,1030.1386)" />
- <rect
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- id="rect3901-7"
- width="7.0766954"
- height="4.3238611"
- x="-555.03052"
- y="927.00201"
- transform="matrix(0.72654224,-0.6871218,0.6979248,0.71617106,0,0)"
- ry="0" />
- <path
- style="fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 283,1012.3802 -14,-0.018 6.9727,8 z"
- id="path3055-0-6"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- d="m 283,1036.3802 -14,-0.018 6.9727,8 z"
- id="path3055-0-6-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 307,1020.3441 -14,0.018 6.9727,-8 z"
- id="path3055-0-6-3"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="fill:#d3d3d3;fill-opacity:1;stroke:none"
- d="m 307,1044.3441 -14,0.018 6.9727,-8 z"
- id="path3055-0-6-7-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- sodipodi:type="arc"
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2.66157866;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path4138"
- sodipodi:cx="345"
- sodipodi:cy="14.625"
- sodipodi:rx="5.875"
- sodipodi:ry="5.625"
- d="m 340.84575,10.647524 c 2.29433,-2.1966988 6.01417,-2.1966988 8.3085,0 2.29433,2.196699 2.29433,5.758252 0,7.954952 C 348.05248,19.657368 346.55815,20.25 345,20.25"
- transform="matrix(1.0994438,0,0,1.1555556,-31.147369,999.5247)"
- sodipodi:start="3.9269908"
- sodipodi:end="7.8539816"
- sodipodi:open="true" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 346.50256,1014.7688 -5.50291,-5.8066 -2.32475,7.7118 z"
- id="path3055-0-70-1-7-5"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- sodipodi:type="arc"
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2.66157866;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path4138-1"
- sodipodi:cx="345"
- sodipodi:cy="14.625"
- sodipodi:rx="5.875"
- sodipodi:ry="5.625"
- d="m 340.84575,10.647524 c 2.29433,-2.1966988 6.01417,-2.1966988 8.3085,0 2.29433,2.196699 2.29433,5.758252 0,7.954952 C 348.05248,19.657368 346.55815,20.25 345,20.25"
- transform="matrix(-1.0994438,0,0,1.1555556,751.26734,999.4622)"
- sodipodi:start="3.9269908"
- sodipodi:end="7.8539816"
- sodipodi:open="true" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 373.61741,1014.7063 5.50291,-5.8066 2.32475,7.7118 z"
- id="path3055-0-70-1-7-5-8"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- sodipodi:type="arc"
- style="opacity:0.4;fill:none;stroke:#4d4d4d;stroke-width:2.66157866;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path4138-7"
- sodipodi:cx="345"
- sodipodi:cy="14.625"
- sodipodi:rx="5.875"
- sodipodi:ry="5.625"
- d="m 340.84575,10.647524 c 2.29433,-2.1966988 6.01417,-2.1966988 8.3085,0 2.29433,2.196699 2.29433,5.758252 0,7.954952 C 348.05248,19.657368 346.55815,20.25 345,20.25"
- transform="matrix(1.0994438,0,0,1.1555556,-31.152274,1023.4622)"
- sodipodi:start="3.9269908"
- sodipodi:end="7.8539816"
- sodipodi:open="true" />
- <path
- style="opacity:0.4;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 346.49766,1038.7063 -5.50291,-5.8066 -2.32475,7.7118 z"
- id="path3055-0-70-1-7-5-85"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- sodipodi:type="arc"
- style="opacity:0.4;fill:none;stroke:#4d4d4d;stroke-width:2.66157866;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="path4138-1-0"
- sodipodi:cx="345"
- sodipodi:cy="14.625"
- sodipodi:rx="5.875"
- sodipodi:ry="5.625"
- d="m 340.84575,10.647524 c 2.29433,-2.1966988 6.01417,-2.1966988 8.3085,0 2.29433,2.196699 2.29433,5.758252 0,7.954952 C 348.05248,19.657368 346.55815,20.25 345,20.25"
- transform="matrix(-1.0994438,0,0,1.1555556,751.26244,1023.3997)"
- sodipodi:start="3.9269908"
- sodipodi:end="7.8539816"
- sodipodi:open="true" />
- <path
- style="opacity:0.4;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 373.61251,1038.6438 5.50291,-5.8066 2.32475,7.7118 z"
- id="path3055-0-70-1-7-5-8-4"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:1.99999988;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389,1014.3622 14.0009,0"
- id="path4946"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:1.99999988;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389,1022.3622 14.0009,0"
- id="path4946-9"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:1.99999988;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389,1018.3622 14.0009,0"
- id="path4946-9-8"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:1.99999988;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389,1010.3622 14.0009,0"
- id="path4946-0"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389.02095,1034.3622 9.99983,0"
- id="path4946-8-8"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 395,1038.3622 7.99983,0"
- id="path4946-9-8-2-3"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:1.99999952;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 394.98592,1042.3622 6.9998,0"
- id="path4946-9-8-2-3-7"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 389,1046.3622 8,0"
- id="path4946-9-8-2-3-7-4"
- inkscape:connector-curvature="0" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 327.9693,1010.3732 -8,-0.011 3.9844,5 z"
- id="path3055-0-77"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 327.9993,1022.3512 -8,0.011 3.9844,-5 z"
- id="path3055-0-7-5"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 328,1035.3508 -8,0.011 3.9844,-5 z"
- id="path3055-0-77-3"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- d="m 328.03,1045.3732 -8,-0.011 3.9844,5 z"
- id="path3055-0-7-5-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cccc" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 317,1016.3622 14,-0.031"
- id="path5244-5-0-5"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cc" />
- <path
- style="opacity:0.8;fill:none;stroke:#4d4d4d;stroke-width:2;stroke-linecap:square;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- d="m 317,1040.3775 14,-0.031"
- id="path5244-5-0-5-8"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="cc" />
- <rect
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- id="rect3832"
- width="3"
- height="2"
- x="322.5"
- y="1043.3622" />
- <rect
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- id="rect3832-8"
- width="3"
- height="2"
- x="322.5"
- y="1035.3622" />
- <rect
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- id="rect3832-8-2"
- width="3"
- height="2"
- x="322.5"
- y="1008.3622" />
- <rect
- style="opacity:0.8;fill:#4d4d4d;fill-opacity:1;stroke:none"
- id="rect3832-8-26"
- width="3"
- height="2"
- x="322.5"
- y="1022.3622" />
- </g>
-</svg>
diff --git a/data/libs/jsoneditor/jsoneditor.css b/data/libs/jsoneditor/jsoneditor.css
deleted file mode 100644
index 015c498f0..000000000
--- a/data/libs/jsoneditor/jsoneditor.css
+++ /dev/null
@@ -1,432 +0,0 @@
-
-.jsoneditor-field, .jsoneditor-value, .jsoneditor-field-readonly, .jsoneditor-readonly {
- border: 1px solid transparent;
- min-height: 16px;
- min-width: 24px;
- padding: 2px;
- margin: 1px;
- outline: none;
- word-wrap: break-word;
- float: left;
-}
-
-/* adjust margin of p elements inside editable divs, needed for Opera, IE */
-.jsoneditor-field p, .jsoneditor-value p {
- margin: 0;
-}
-
-.jsoneditor-value {
- word-break: break-word;
-}
-
-.jsoneditor-empty {
- background-color: #E5E5E5;
- border-radius: 2px;
-}
-
-.jsoneditor-separator {
- padding: 3px 0;
- vertical-align: top;
-}
-
-.jsoneditor-value:focus, .jsoneditor-field:focus,
- .jsoneditor-value:hover, .jsoneditor-field:hover,
- .jsoneditor-search-highlight {
- background-color: #FFFFAB;
- border: 1px solid yellow;
- border-radius: 2px;
-}
-
-.jsoneditor-search-highlight-active,
- .jsoneditor-search-highlight-active:focus,
- .jsoneditor-search-highlight-active:hover {
- background-color: #ffee00;
- border: 1px solid #ffc700;
- border-radius: 2px;
-}
-
-.jsoneditor-field-readonly:hover {
- border: 1px solid white;
-}
-
-.jsoneditor-readonly {
- color: gray;
-}
-
-button.jsoneditor-remove, button.jsoneditor-append, button.jsoneditor-duplicate,
-button.jsoneditor-collapsed, button.jsoneditor-expanded,
-button.jsoneditor-invisible, button.jsoneditor-dragarea,
-button.jsoneditor-type-auto, button.jsoneditor-type-string,
-button.jsoneditor-type-array, button.jsoneditor-type-object {
- width: 24px;
- height: 24px;
- padding: 0;
- margin: 0;
- border: none;
- cursor: pointer;
- background: url('img/jsoneditor-icons.png');
-}
-
-button:disabled {
- color: #808080;
-}
-
-button.jsoneditor-collapsed {
- background-position: -168px 0;
-}
-
-button.jsoneditor-expanded {
- background-position: -168px -24px;
-}
-
-button.jsoneditor-invisible {
- visibility: hidden;
- background: none;
-}
-
-button.jsoneditor-collapsed, button.jsoneditor-expanded,
-button.jsoneditor-invisible {
- float: left;
-}
-
-button.jsoneditor-remove {
- background-position: -24px -24px;
-}
-button.jsoneditor-remove:hover {
- background-position: -24px 0;
-}
-
-button.jsoneditor-append {
- background-position: 0 -24px;
-}
-button.jsoneditor-append:hover {
- background-position: 0 0;
-}
-
-button.jsoneditor-duplicate {
- background-position: -48px -24px;
-}
-button.jsoneditor-duplicate:hover {
- background-position: -48px 0;
-}
-
-button.jsoneditor-type-string {
- background-position: -144px -24px;
-}
-button.jsoneditor-type-string:hover {
- background-position: -144px 0;
-}
-
-button.jsoneditor-type-auto {
- background-position: -120px -24px;
-}
-button.jsoneditor-type-auto:hover {
- background-position: -120px 0;
-}
-
-button.jsoneditor-type-object {
- background-position: -72px -24px;
-}
-button.jsoneditor-type-object:hover {
- background-position: -72px 0;
-}
-
-button.jsoneditor-type-array {
- background-position: -96px -24px;
-}
-button.jsoneditor-type-array:hover {
- background-position: -96px 0;
-}
-
-div.jsoneditor-select {
- border: 1px solid gray;
- background-color: white;
- box-shadow: 4px 4px 10px rgba(128, 128, 128, 0.5);
-}
-
-div.jsoneditor-option {
- color: #4D4D4D;
- background-color: white;
-
- border: none;
- margin: 0;
- display: block;
- text-align: left;
- cursor: pointer;
-}
-div.jsoneditor-option:hover {
- background-color: #FFFFAB;
- color: #1A1A1A;
-}
-div.jsoneditor-option-selected {
- background-color: #D5DDF6;
-}
-div.jsoneditor-option-text {
- height: 24px;
- line-height: 24px;
- padding: 0 12px 0 0;
- display: inline-block;
-}
-
-div.jsoneditor-option-string, div.jsoneditor-option-auto,
-div.jsoneditor-option-object, div.jsoneditor-option-array {
- float: left;
- width: 24px;
- height: 24px;
- display: inline-block;
- background: url('img/jsoneditor-icons.png');
-}
-div.jsoneditor-option-string {
- background-position: -144px 0;
-}
-div.jsoneditor-option-auto {
- background-position: -120px 0;
-}
-div.jsoneditor-option-object {
- background-position: -72px 0;
-}
-div.jsoneditor-option-array {
- background-position: -96px 0;
-}
-
-
-div.jsoneditor-frame {
- color: #1A1A1A;
- border: 1px solid #97B0F8;
- box-sizing: border-box;
- width: 100%;
- height: 100%;
- overflow: auto;
- position: relative;
- padding: 0;
-}
-
-table.jsoneditor-table {
- border-collapse: collapse;
- border-spacing: 0;
- width: 100%;
- margin: 0;
-}
-
-div.jsoneditor-content-outer, div.jsonformatter-content {
- width: 100%;
- height: 100%;
- margin: -35px 0 0 0;
- padding: 35px 0 0 0;
-
- -moz-box-sizing: border-box;
- -webkit-box-sizing: border-box;
- box-sizing: border-box;
-
- overflow: hidden;
-}
-
-div.jsoneditor-content {
- width: 100%;
- height: 100%;
- position: relative;
- overflow: auto;
-}
-
-textarea.jsonformatter-textarea {
- width: 100%;
- height: 100%;
- margin: 0;
-
- -moz-box-sizing: border-box;
- -webkit-box-sizing: border-box;
- box-sizing: border-box;
-
- border: none;
- background-color: white;
- resize: none;
-}
-
-tr.jsoneditor-tr-highlight {
- background-color: #FFFFAB;
-}
-
-button.jsoneditor-dragarea {
- width: 16px;
- height: 24px;
- /*
- margin: 3px 0;
- background: url('img/dots_gray.gif') top center;
- background-repeat: repeat-y;
- */
- background: url('img/jsoneditor-icons.png') -220px 0;
-
- display: block;
- cursor: move;
-}
-
-div.jsoneditor-menu {
- width: 100%;
- height: 35px;
- padding: 2px;
- margin: 0;
- overflow: hidden;
- -moz-box-sizing: border-box;
- -webkit-box-sizing: border-box;
- box-sizing: border-box;
-
- color: #1A1A1A;
- background-color: #D5DDF6;
- border-bottom: 1px solid #97B0F8;
-}
-
-table.jsoneditor-search {
- position: absolute;
- right: 2px;
- top: 2px;
-}
-
-table.jsoneditor-search-input {
- border-collapse: collapse;
-}
-
-div.jsoneditor-search {
- border: 1px solid #97B0F8;
- background-color: white;
- padding: 0 2px;
- margin: 0;
-}
-
-input.jsoneditor-search {
- width: 120px;
- border: none;
- outline: none;
- margin: 1px;
-}
-
-div.jsoneditor-search-results {
- color: #4d4d4d;
- padding-right: 5px;
-}
-
-button.jsoneditor-search-refresh, button.jsoneditor-search-next,
- button.jsoneditor-search-previous {
- width: 16px;
- height: 24px;
- padding: 0;
- margin: 0;
- border: none;
- background: url('img/jsoneditor-icons.png');
- vertical-align: top;
-}
-
-button.jsoneditor-search-refresh {
- width: 18px;
- background-position: -243px -25px;
-}
-
-button.jsoneditor-search-next {
- cursor: pointer;
- background-position: -268px -25px;
-}
-button.jsoneditor-search-next:hover {
- background-position: -268px -1px;
-}
-
-button.jsoneditor-search-previous {
- cursor: pointer;
- background-position: -292px -25px;
- margin-right: 2px;
-}
-button.jsoneditor-search-previous:hover {
- background-position: -292px -1px;
-}
-
-
-button.jsoneditor-menu {
- width: 26px;
- height: 26px;
- margin: 2px;
- padding: 2px;
- border-radius: 2px;
- border: 1px solid #aec0f8;
- background: #e3eaf6 url('../jsoneditor/img/jsoneditor-icons.png');
-}
-
-button.jsoneditor-menu:hover {
- background-color: #f0f2f5;
-}
-button.jsoneditor-menu:active {
- background-color: #ffffff;
-}
-button.jsoneditor-menu:disabled {
- background-color: #e3eaf6;
-}
-
-button.jsoneditor-collapse-all {
- background-position: -312px 0;
-}
-button.jsoneditor-expand-all {
- background-position: -312px -24px;
-}
-button.jsoneditor-undo {
- background-position: -336px 0;
-}
-button.jsoneditor-redo {
- background-position: -360px 0;
-}
-button.jsoneditor-undo:disabled {
- background-position: -336px -24px;
-}
-button.jsoneditor-redo:disabled {
- background-position: -360px -24px;
-}
-/* TODO: css for button:disabled is not supported by IE8 */
-button.jsoneditor-compact {
- background-position: -384px 0;
-}
-button.jsoneditor-format {
- background-position: -384px -24px;
-}
-
-
-tr, th, td {
- padding: 0;
- margin: 0;
-}
-
-td.jsoneditor-td {
- vertical-align: top;
-}
-
-td.jsoneditor-td {
- padding: 0 3px;
-}
-
-td.jsoneditor-td-edit {
- background-color: #F5F5F5;
- padding: 0;
-}
-
-td.jsoneditor-td-tree {
- vertical-align: top;
-}
-
-td.jsoneditor-droparea {
- height: 24px;
-
- border-top: 1px dashed gray;
- border-bottom: 1px dashed gray;
- background-color: #FFFF80;
-}
-
-.jsoneditor-field, .jsoneditor-value, .jsoneditor-td, .jsoneditor-th,
-.jsoneditor-type,
-.jsonformatter-textarea {
- font-family: droid sans mono, monospace, courier new, courier, sans-serif;
- font-size: 10pt;
- color: #1A1A1A;
-}
-
-.jsoneditor-hidden-focus {
- position: absolute;
- left: -1000px;
- top: -1000px;
- border: none;
- outline: none;
-}
diff --git a/data/libs/jsoneditor/jsoneditor.js b/data/libs/jsoneditor/jsoneditor.js
deleted file mode 100644
index 08b3a4f4b..000000000
--- a/data/libs/jsoneditor/jsoneditor.js
+++ /dev/null
@@ -1,3825 +0,0 @@
-/**
- * @file jsoneditor.js
- *
- * @brief
- * JSONEditor is a web-based tool to view, edit, and format JSON.
- * It shows data a clear, editable treeview.
- *
- * Supported browsers: Chrome, Firefox, Safari, Opera, Internet Explorer 8+
- *
- * @license
- * This json editor is open sourced with the intention to use the editor as
- * a component in your own application. Not to just copy and monetize the editor
- * as it is.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy
- * of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- *
- * Copyright (c) 2011-2012 Jos de Jong, http://jsoneditoronline.org
- *
- * @author Jos de Jong, <[email protected]>
- * @date 2012-12-08
- */
-
-
-// Internet Explorer 8 and older does not support Array.indexOf,
-// so we define it here in that case
-// http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
-if(!Array.prototype.indexOf) {
- Array.prototype.indexOf = function(obj){
- for(var i = 0; i < this.length; i++){
- if(this[i] == obj){
- return i;
- }
- }
- return -1;
- }
-}
-
-// Internet Explorer 8 and older does not support Array.forEach,
-// so we define it here in that case
-// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
-if (!Array.prototype.forEach) {
- Array.prototype.forEach = function(fn, scope) {
- for(var i = 0, len = this.length; i < len; ++i) {
- fn.call(scope || this, this[i], i, this);
- }
- }
-}
-
-// define variable JSON, needed for correct error handling on IE7 and older
-var JSON;
-
-/**
- * JSONEditor
- * @param {Element} container Container element
- * @param {Object} [options] Object with options. available options:
- * {String} mode Editor mode. Available values:
- * 'editor' (default), 'viewer'.
- * {Boolean} search Enable search box.
- * True by default
- * {Boolean} history Enable history (undo/redo).
- * True by default
- * {function} change Callback method, triggered
- * on change of contents
- * {String} name Field name for the root node.
- * @param {Object | undefined} json JSON object
- */
-JSONEditor = function (container, options, json) {
- // check availability of JSON parser (not available in IE7 and older)
- if (!JSON) {
- throw new Error ('Your browser does not support JSON. \n\n' +
- 'Please install the newest version of your browser.\n' +
- '(all modern browsers support JSON).');
- }
-
- if (!container) {
- throw new Error('No container element provided.');
- }
- this.container = container;
- this.dom = {};
-
- this._setOptions(options);
-
- if (this.options.history && this.editable) {
- this.history = new JSONEditor.History(this);
- }
-
- this._createFrame();
- this._createTable();
-
- this.set(json || {});
-};
-
-/**
- * Initialize and set default options
- * @param {Object} [options] Object with options. available options:
- * {String} mode Editor mode. Available values:
- * 'editor' (default), 'viewer'.
- * {Boolean} search Enable search box.
- * True by default.
- * {Boolean} history Enable history (undo/redo).
- * True by default.
- * {function} change Callback method, triggered
- * on change of contents.
- * {String} name Field name for the root node.
- * @private
- */
-JSONEditor.prototype._setOptions = function (options) {
- this.options = {
- search: true,
- history: true,
- mode: 'editor',
- name: undefined // field name of root node
- };
-
- // copy all options
- if (options) {
- for (var prop in options) {
- if (options.hasOwnProperty(prop)) {
- this.options[prop] = options[prop];
- }
- }
-
- // check for deprecated options
- if (options.enableSearch) {
- // deprecated since version 1.6.0, 2012-11-03
- this.options.search = options.enableSearch;
- console.log('WARNING: Option "enableSearch" is deprecated. Use "search" instead.');
- }
- if (options.enableHistory) {
- // deprecated since version 1.6.0, 2012-11-03
- this.options.search = options.enableHistory;
- console.log('WARNING: Option "enableHistory" is deprecated. Use "history" instead.');
- }
- }
-
- // interpret the options
- this.editable = (this.options.mode != 'viewer');
-};
-
-// node currently being edited
-JSONEditor.focusNode = undefined;
-
-/**
- * Set JSON object in editor
- * @param {Object | undefined} json JSON data
- * @param {String} [name] Optional field name for the root node.
- * Can also be set using setName(name).
- */
-JSONEditor.prototype.set = function (json, name) {
- // adjust field name for root node
- if (name) {
- this.options.name = name;
- }
-
- // verify if json is valid JSON, ignore when a function
- if (json instanceof Function || (json === undefined)) {
- this.clear();
- }
- else {
- this.content.removeChild(this.table); // Take the table offline
-
- // replace the root node
- var params = {
- 'field': this.options.name,
- 'value': json
- };
- var node = new JSONEditor.Node(this, params);
- this._setRoot(node);
-
- // expand
- var recurse = false;
- this.node.expand(recurse);
-
- this.content.appendChild(this.table); // Put the table online again
- }
-
- // TODO: maintain history, store last state and previous document
- if (this.history) {
- this.history.clear();
- }
-};
-
-/**
- * Get JSON object from editor
- * @return {Object | undefined} json
- */
-JSONEditor.prototype.get = function () {
- // remove focus from currently edited node
- if (JSONEditor.focusNode) {
- JSONEditor.focusNode.blur();
- }
-
- if (this.node) {
- return this.node.getValue();
- }
- else {
- return undefined;
- }
-};
-
-/**
- * Set a field name for the root node.
- * @param {String | undefined} name
- */
-JSONEditor.prototype.setName = function (name) {
- this.options.name = name;
- if (this.node) {
- this.node.updateField(this.options.name);
- }
-};
-
-/**
- * Get the field name for the root node.
- * @return {String | undefined} name
- */
-JSONEditor.prototype.getName = function () {
- return this.options.name;
-};
-
-/**
- * Remove the root node from the editor
- */
-JSONEditor.prototype.clear = function () {
- if (this.node) {
- this.node.collapse();
- this.tbody.removeChild(this.node.getDom());
- delete this.node;
- }
-};
-
-/**
- * Set the root node for the json editor
- * @param {JSONEditor.Node} node
- * @private
- */
-JSONEditor.prototype._setRoot = function (node) {
- this.clear();
-
- this.node = node;
-
- // append to the dom
- this.tbody.appendChild(node.getDom());
-};
-
-/**
- * Search text in all nodes
- * The nodes will be expanded when the text is found one of its childs,
- * else it will be collapsed. Searches are case insensitive.
- * @param {String} text
- * @return {Object[]} results Array with nodes containing the search results
- * The result objects contains fields:
- * - {JSONEditor.Node} node,
- * - {String} elem the dom element name where
- * the result is found ('field' or
- * 'value')
- */
-JSONEditor.prototype.search = function (text) {
- var results;
- if (this.node) {
- this.content.removeChild(this.table); // Take the table offline
- results = this.node.search(text);
- this.content.appendChild(this.table); // Put the table online again
- }
- else {
- results = [];
- }
-
- return results;
-};
-
-/**
- * Expand all nodes
- */
-JSONEditor.prototype.expandAll = function () {
- if (this.node) {
- this.content.removeChild(this.table); // Take the table offline
- this.node.expand();
- this.content.appendChild(this.table); // Put the table online again
- }
-};
-
-/**
- * Collapse all nodes
- */
-JSONEditor.prototype.collapseAll = function () {
- if (this.node) {
- this.content.removeChild(this.table); // Take the table offline
- this.node.collapse();
- this.content.appendChild(this.table); // Put the table online again
- }
-};
-
-/**
- * The method onChange is called whenever a field or value is changed, created,
- * deleted, duplicated, etc.
- * @param {String} action Change action. Available values: "editField",
- * "editValue", "changeType", "appendNode",
- * "removeNode", "duplicateNode", "moveNode", "expand",
- * "collapse".
- * @param {Object} params Object containing parameters describing the change.
- * The parameters in params depend on the action (for
- * example for "editValue" the Node, old value, and new
- * value are provided). params contains all information
- * needed to undo or redo the action.
- */
-JSONEditor.prototype.onAction = function (action, params) {
- // add an action to the history
- if (this.history) {
- this.history.add(action, params);
- }
-
- // trigger the onChange callback
- if (this.options.change) {
- try {
- this.options.change();
- }
- catch (err) {
- console.log('Error in change callback: ', err);
- }
- }
-};
-
-/**
- * Set the focus to the JSONEditor. A hidden input field will be created
- * which captures key events
- */
-// TODO: use the focus method?
-JSONEditor.prototype.focus = function () {
- /*
- if (!this.dom.focus) {
- this.dom.focus = document.createElement('input');
- this.dom.focus.className = 'jsoneditor-hidden-focus';
-
- var editor = this;
- this.dom.focus.onblur = function () {
- // remove itself
- if (editor.dom.focus) {
- var focus = editor.dom.focus;
- delete editor.dom.focus;
- editor.frame.removeChild(focus);
- }
- };
-
- // attach the hidden input box to the DOM
- if (this.frame.firstChild) {
- this.frame.insertBefore(this.dom.focus, this.frame.firstChild);
- }
- else {
- this.frame.appendChild(this.dom.focus);
- }
- }
- this.dom.focus.focus();
- */
-};
-
-/**
- * Adjust the scroll position such that given top position is shown at 1/4
- * of the window height.
- * @param {Number} top
- */
-JSONEditor.prototype.scrollTo = function (top) {
- var content = this.content;
- if (content) {
- // cancel any running animation
- var editor = this;
- if (editor.animateTimeout) {
- clearTimeout(editor.animateTimeout);
- delete editor.animateTimeout;
- }
-
- // calculate final scroll position
- var height = content.clientHeight;
- var bottom = content.scrollHeight - height;
- var finalScrollTop = Math.min(Math.max(top - height / 4, 0), bottom);
-
- // animate towards the new scroll position
- var animate = function () {
- var scrollTop = content.scrollTop;
- var diff = (finalScrollTop - scrollTop);
- if (Math.abs(diff) > 3) {
- content.scrollTop += diff / 3;
- editor.animateTimeout = setTimeout(animate, 50);
- }
- };
- animate();
- }
-};
-
-
-/**
- * @constructor JSONEditor.History
- * Store action history, enables undo and redo
- * @param {JSONEditor} editor
- */
-JSONEditor.History = function (editor) {
- this.editor = editor;
- this.clear();
-
- // map with all supported actions
- this.actions = {
- 'editField': {
- 'undo': function (obj) {
- obj.params.node.updateField(obj.params.oldValue);
- },
- 'redo': function (obj) {
- obj.params.node.updateField(obj.params.newValue);
- }
- },
- 'editValue': {
- 'undo': function (obj) {
- obj.params.node.updateValue(obj.params.oldValue);
- },
- 'redo': function (obj) {
- obj.params.node.updateValue(obj.params.newValue);
- }
- },
- 'appendNode': {
- 'undo': function (obj) {
- obj.params.parent.removeChild(obj.params.node);
- },
- 'redo': function (obj) {
- obj.params.parent.appendChild(obj.params.node);
- }
- },
- 'removeNode': {
- 'undo': function (obj) {
- var parent = obj.params.parent;
- var beforeNode = parent.childs[obj.params.index] || parent.append;
- parent.insertBefore(obj.params.node, beforeNode);
- },
- 'redo': function (obj) {
- obj.params.parent.removeChild(obj.params.node);
- }
- },
- 'duplicateNode': {
- 'undo': function (obj) {
- obj.params.parent.removeChild(obj.params.clone);
- },
- 'redo': function (obj) {
- // TODO: insert after instead of insert before
- obj.params.parent.insertBefore(obj.params.clone, obj.params.node);
- }
- },
- 'changeType': {
- 'undo': function (obj) {
- obj.params.node.changeType(obj.params.oldType);
- },
- 'redo': function (obj) {
- obj.params.node.changeType(obj.params.newType);
- }
- },
- 'moveNode': {
- 'undo': function (obj) {
- obj.params.startParent.moveTo(obj.params.node, obj.params.startIndex);
- },
- 'redo': function (obj) {
- obj.params.endParent.moveTo(obj.params.node, obj.params.endIndex);
- }
- }
-
- // TODO: restore the original caret position and selection with each undo
- // TODO: implement history for actions "expand", "collapse", "scroll", "setDocument"
- };
-};
-
-/**
- * The method onChange is executed when the History is changed, and can
- * be overloaded.
- */
-JSONEditor.History.prototype.onChange = function () {};
-
-/**
- * Add a new action to the history
- * @param {String} action The executed action. Available actions: "editField",
- * "editValue", "changeType", "appendNode",
- * "removeNode", "duplicateNode", "moveNode"
- * @param {Object} params Object containing parameters describing the change.
- * The parameters in params depend on the action (for
- * example for "editValue" the Node, old value, and new
- * value are provided). params contains all information
- * needed to undo or redo the action.
- */
-JSONEditor.History.prototype.add = function (action, params) {
- this.index++;
- this.history[this.index] = {
- 'action': action,
- 'params': params,
- 'timestamp': new Date()
- };
-
- // remove redo actions which are invalid now
- if (this.index < this.history.length - 1) {
- this.history.splice(this.index + 1, this.history.length - this.index - 1);
- }
-
- // fire onchange event
- this.onChange();
-};
-
-/**
- * Clear history
- */
-JSONEditor.History.prototype.clear = function () {
- this.history = [];
- this.index = -1;
-
- // fire onchange event
- this.onChange();
-};
-
-/**
- * Check if there is an action available for undo
- * @return {Boolean} canUndo
- */
-JSONEditor.History.prototype.canUndo = function () {
- return (this.index >= 0);
-};
-
-/**
- * Check if there is an action available for redo
- * @return {Boolean} canRedo
- */
-JSONEditor.History.prototype.canRedo = function () {
- return (this.index < this.history.length - 1);
-};
-
-/**
- * Undo the last action
- */
-JSONEditor.History.prototype.undo = function () {
- if (this.canUndo()) {
- var obj = this.history[this.index];
- if (obj) {
- var action = this.actions[obj.action];
- if (action && action.undo) {
- action.undo(obj);
- }
- else {
- console.log('Error: unknown action "' + obj.action + '"');
- }
- }
- this.index--;
-
- // fire onchange event
- this.onChange();
- }
-};
-
-/**
- * Redo the last action
- */
-JSONEditor.History.prototype.redo = function () {
- if (this.canRedo()) {
- this.index++;
-
- var obj = this.history[this.index];
- if (obj) {
- if (obj) {
- var action = this.actions[obj.action];
- if (action && action.redo) {
- action.redo(obj);
- }
- else {
- console.log('Error: unknown action "' + obj.action + '"');
- }
- }
- }
-
- // fire onchange event
- this.onChange();
- }
-};
-
-
-/**
- * @constructor JSONEditor.Node
- * Create a new Node
- * @param {JSONEditor} editor
- * @param {Object} params Can contain parameters: field, fieldEditable, value.
- */
-JSONEditor.Node = function (editor, params) {
- this.editor = editor;
- this.dom = {};
- this.expanded = false;
-
- if(params && (params instanceof Object)) {
- this.setField(params.field, params.fieldEditable);
- this.setValue(params.value);
- }
- else {
- this.setField();
- this.setValue();
- }
-};
-
-/**
- * Set parent node
- * @param {JSONEditor.Node} parent
- */
-JSONEditor.Node.prototype.setParent = function(parent) {
- this.parent = parent;
-};
-
-/**
- * Get parent node. Returns undefined when no parent node is set.
- * @return {JSONEditor.Node} parent
- */
-JSONEditor.Node.prototype.getParent = function () {
- return this.parent;
-};
-
-/**
- * Set field
- * @param {String} field
- * @param {boolean} fieldEditable
- */
-JSONEditor.Node.prototype.setField = function(field, fieldEditable) {
- this.field = field;
- this.fieldEditable = (fieldEditable == true);
-};
-
-/**
- * Get field
- * @return {String}
- */
-JSONEditor.Node.prototype.getField = function() {
- if (this.field === undefined) {
- this._getDomField();
- }
-
- return this.field;
-};
-
-/**
- * Set value. Value is a JSON structure or an element String, Boolean, etc.
- * @param {*} value
- */
-JSONEditor.Node.prototype.setValue = function(value) {
- var childValue, child;
-
- // first clear all current childs (if any)
- var childs = this.childs;
- if (childs) {
- while (childs.length) {
- this.removeChild(childs[0]);
- }
- }
-
- // TODO: remove the DOM of this Node
-
- this.type = this._getType(value);
- if (this.type == 'array') {
- // array
- this.childs = [];
- for (var i = 0, iMax = value.length; i < iMax; i++) {
- childValue = value[i];
- if (childValue !== undefined && !(childValue instanceof Function)) {
- // ignore undefined and functions
- child = new JSONEditor.Node(this.editor, {
- 'value': childValue
- });
- this.appendChild(child);
- }
- }
- this.value = '';
- }
- else if (this.type == 'object') {
- // object
- this.childs = [];
- for (var childField in value) {
- if (value.hasOwnProperty(childField)) {
- childValue = value[childField];
- if (childValue !== undefined && !(childValue instanceof Function)) {
- // ignore undefined and functions
- child = new JSONEditor.Node(this.editor, {
- 'field': childField,
- 'value': childValue
- });
- this.appendChild(child);
- }
- }
- }
- this.value = '';
- }
- else {
- // value
- this.childs = undefined;
- this.value = value;
- /* TODO
- if (typeof(value) == 'string') {
- var escValue = JSON.stringify(value);
- this.value = escValue.substring(1, escValue.length - 1);
- console.log('check', value, this.value);
- }
- else {
- this.value = value;
- }
- */
- }
-};
-
-/**
- * Get value. Value is a JSON structure
- * @return {*} value
- */
-JSONEditor.Node.prototype.getValue = function() {
- //var childs, i, iMax;
-
- if (this.type == 'array') {
- var arr = [];
- this.childs.forEach (function (child) {
- arr.push(child.getValue());
- });
- return arr;
- }
- else if (this.type == 'object') {
- var obj = {};
- this.childs.forEach (function (child) {
- obj[child.getField()] = child.getValue();
- });
- return obj;
- }
- else {
- if (this.value === undefined) {
- this._getDomValue();
- }
-
- return this.value;
- }
-};
-
-/**
- * Get the nesting level of this node
- * @return {Number} level
- */
-JSONEditor.Node.prototype.getLevel = function() {
- return (this.parent ? this.parent.getLevel() + 1 : 0);
-};
-
-/**
- * Create a clone of a node
- * The complete state of a clone is copied, including whether it is expanded or
- * not. The DOM elements are not cloned.
- * @return {JSONEditor.Node} clone
- */
-JSONEditor.Node.prototype.clone = function() {
- var clone = new JSONEditor.Node(this.editor);
- clone.type = this.type;
- clone.field = this.field;
- clone.fieldInnerText = this.fieldInnerText;
- clone.fieldEditable = this.fieldEditable;
- clone.value = this.value;
- clone.valueInnerText = this.valueInnerText;
- clone.expanded = this.expanded;
-
- if (this.childs) {
- // an object or array
- var cloneChilds = [];
- this.childs.forEach(function (child) {
- var childClone = child.clone();
- childClone.setParent(clone);
- cloneChilds.push(childClone);
- });
- clone.childs = cloneChilds;
- }
- else {
- // a value
- clone.childs = undefined;
- }
-
- return clone;
-};
-
-/**
- * Expand this node and optionally its childs.
- * @param {boolean} recurse Optional recursion, true by default. When
- * true, all childs will be expanded recursively
- */
-JSONEditor.Node.prototype.expand = function(recurse) {
- if (!this.childs) {
- return;
- }
-
- // set this node expanded
- this.expanded = true;
- if (this.dom.expand) {
- this.dom.expand.className = 'jsoneditor-expanded';
- }
-
- this.showChilds();
-
- if (recurse != false) {
- this.childs.forEach(function (child) {
- child.expand(recurse);
- });
- }
-};
-
-/**
- * Collapse this node and optionally its childs.
- * @param {Number} recurse Optional recursion, true by default. When
- * true, all childs will be collapsed recursively
- */
-JSONEditor.Node.prototype.collapse = function(recurse) {
- if (!this.childs) {
- return;
- }
-
- this.hideChilds();
-
- // collapse childs in case of recurse
- if (recurse != false) {
- this.childs.forEach(function (child) {
- child.collapse(recurse);
- });
-
- }
-
- // make this node collapsed
- if (this.dom.expand) {
- this.dom.expand.className = 'jsoneditor-collapsed';
- }
- this.expanded = false;
-};
-
-/**
- * Recursively show all childs when they are expanded
- */
-JSONEditor.Node.prototype.showChilds = function() {
- var childs = this.childs;
- if (!childs) {
- return;
- }
- if (!this.expanded) {
- return;
- }
-
- var tr = this.dom.tr;
- var table = tr ? tr.parentNode : undefined;
- if (table) {
- // show row with append button
- var append = this.getAppend();
- var nextTr = tr.nextSibling;
- if (nextTr) {
- table.insertBefore(append, nextTr);
- }
- else {
- table.appendChild(append);
- }
-
- // show childs
- this.childs.forEach(function (child) {
- table.insertBefore(child.getDom(), append);
- child.showChilds();
- });
- }
-};
-
-/**
- * Hide the node with all its childs
- */
-JSONEditor.Node.prototype.hide = function() {
- var tr = this.dom.tr;
- var table = tr ? tr.parentNode : undefined;
- if (table) {
- table.removeChild(tr);
- }
- this.hideChilds();
-};
-
-
-/**
- * Recursively hide all childs
- */
-JSONEditor.Node.prototype.hideChilds = function() {
- var childs = this.childs;
- if (!childs) {
- return;
- }
- if (!this.expanded) {
- return;
- }
-
- // hide append row
- var append = this.getAppend();
- if (append.parentNode) {
- append.parentNode.removeChild(append);
- }
-
- // hide childs
- this.childs.forEach(function (child) {
- child.hide();
- });
-};
-
-
-/**
- * Add a new child to the node.
- * Only applicable when Node value is of type array or object
- * @param {JSONEditor.Node} node
- */
-JSONEditor.Node.prototype.appendChild = function(node) {
- if (this.type == 'array' || this.type == 'object') {
- // adjust the link to the parent
- node.setParent(this);
- node.fieldEditable = (this.type == 'object');
- if (this.type == 'array') {
- node.index = this.childs.length;
- }
- this.childs.push(node);
-
- if (this.expanded) {
- // insert into the DOM, before the appendRow
- var newtr = node.getDom();
- var appendTr = this.getAppend();
- var table = appendTr ? appendTr.parentNode : undefined;
- if (appendTr && table) {
- table.insertBefore(newtr, appendTr);
- }
-
- node.showChilds();
- }
-
- this.updateDom({'updateIndexes': true});
- node.updateDom({'recurse': true});
- }
-};
-
-
-/**
- * Move a node from its current parent to this node
- * Only applicable when Node value is of type array or object
- * @param {JSONEditor.Node} node
- * @param {JSONEditor.Node} beforeNode
- */
-JSONEditor.Node.prototype.moveBefore = function(node, beforeNode) {
- if (this.type == 'array' || this.type == 'object') {
- // create a temporary row, to prevent the scroll position from jumping
- // when removing the node
- var tbody = (this.dom.tr) ? this.dom.tr.parentNode : undefined;
- if (tbody) {
- var trTemp = document.createElement('tr');
- trTemp.style.height = tbody.clientHeight + 'px';
- tbody.appendChild(trTemp);
- }
-
- var parent = node.getParent();
- if (parent) {
- parent.removeChild(node);
- }
- if (beforeNode instanceof JSONEditor.AppendNode) {
- this.appendChild(node);
- }
- else {
- this.insertBefore(node, beforeNode);
- }
-
- if (tbody) {
- tbody.removeChild(trTemp);
- }
- }
-};
-
-/**
- * Move a node from its current parent to this node
- * Only applicable when Node value is of type array or object.
- * If index is out of range, the node will be appended to the end
- * @param {JSONEditor.Node} node
- * @param {Number} index
- */
-JSONEditor.Node.prototype.moveTo = function (node, index) {
- if (node.parent == this) {
- // same parent
- var currentIndex = this.childs.indexOf(node);
- if (currentIndex < index) {
- // compensate the index for removal of the node itself
- index++;
- }
- }
-
- var beforeNode = this.childs[index] || this.append;
- this.moveBefore(node, beforeNode);
-};
-
-/**
- * Insert a new child before a given node
- * Only applicable when Node value is of type array or object
- * @param {JSONEditor.Node} node
- * @param {JSONEditor.Node} beforeNode
- */
-JSONEditor.Node.prototype.insertBefore = function(node, beforeNode) {
- if (this.type == 'array' || this.type == 'object') {
- if (beforeNode == this.append) {
- // append to the child nodes
-
- // adjust the link to the parent
- node.setParent(this);
- node.fieldEditable = (this.type == 'object');
- this.childs.push(node);
- }
- else {
- // insert before a child node
- var index = this.childs.indexOf(beforeNode);
- if (index == -1) {
- throw new Error('Node not found');
- }
-
- // adjust the link to the parent
- node.setParent(this);
- node.fieldEditable = (this.type == 'object');
- this.childs.splice(index, 0, node);
- }
-
- if (this.expanded) {
- // insert into the DOM
- var newTr = node.getDom();
- var nextTr = beforeNode.getDom();
- var table = nextTr ? nextTr.parentNode : undefined;
- if (nextTr && table) {
- table.insertBefore(newTr, nextTr);
- }
-
- node.showChilds();
- }
-
- this.updateDom({'updateIndexes': true});
- node.updateDom({'recurse': true});
- }
-};
-
-/**
- * Search in this node
- * The node will be expanded when the text is found one of its childs, else
- * it will be collapsed. Searches are case insensitive.
- * @param {String} text
- * @return {JSONEditor.Node[]} results Array with nodes containing the search text
- */
-JSONEditor.Node.prototype.search = function(text) {
- var results = [];
- var index;
- var search = text ? text.toLowerCase() : undefined;
-
- // delete old search data
- delete this.searchField;
- delete this.searchValue;
-
- // search in field
- if (this.field != undefined) {
- var field = String(this.field).toLowerCase();
- index = field.indexOf(search);
- if (index != -1) {
- this.searchField = true;
- results.push({
- 'node': this,
- 'elem': 'field'
- });
- }
-
- // update dom
- this._updateDomField();
- }
-
- // search in value
- if (this.type == 'array' || this.type == 'object') {
- // array, object
-
- // search the nodes childs
- if (this.childs) {
- var childResults = [];
- this.childs.forEach(function (child) {
- childResults = childResults.concat(child.search(text));
- });
- results = results.concat(childResults);
- }
-
- // update dom
- if (search != undefined) {
- var recurse = false;
- if (childResults.length == 0) {
- this.collapse(recurse);
- }
- else {
- this.expand(recurse);
- }
- }
- }
- else {
- // string, auto
- if (this.value != undefined ) {
- var value = String(this.value).toLowerCase();
- index = value.indexOf(search);
- if (index != -1) {
- this.searchValue = true;
- results.push({
- 'node': this,
- 'elem': 'value'
- });
- }
- }
-
- // update dom
- this._updateDomValue();
- }
-
- return results;
-};
-
-/**
- * Move the scroll position such that this node is in the visible area.
- * The node will not get the focus
- */
-JSONEditor.Node.prototype.scrollTo = function() {
- if (!this.dom.tr || !this.dom.tr.parentNode) {
- // if the node is not visible, expand its parents
- var parent = this.parent;
- var recurse = false;
- while (parent) {
- parent.expand(recurse);
- parent = parent.parent;
- }
- }
-
- if (this.dom.tr && this.dom.tr.parentNode) {
- this.editor.scrollTo(this.dom.tr.offsetTop);
- }
-};
-
-/**
- * Set focus to the value of this node
- * @param {String} [field] The field name of the element to get the focus
- * available values: 'field', 'value'
- */
-JSONEditor.Node.prototype.focus = function(field) {
- if (this.dom.tr && this.dom.tr.parentNode) {
- if (field != 'value' && this.fieldEditable) {
- var domField = this.dom.field;
- if (domField) {
- domField.focus();
- }
- }
- else {
- var domValue = this.dom.value;
- if (domValue) {
- domValue.focus();
- }
- }
- }
-};
-
-/**
- * Update the values from the DOM field and value of this node
- */
-JSONEditor.Node.prototype.blur = function() {
- // retrieve the actual field and value from the DOM.
- this._getDomValue(false);
- this._getDomField(false);
-};
-
-/**
- * Duplicate given child node
- * new structure will be added right before the cloned node
- * @param {JSONEditor.Node} node the childNode to be duplicated
- * @return {JSONEditor.Node} clone the clone of the node
- * @private
- */
-JSONEditor.Node.prototype._duplicate = function(node) {
- var clone = node.clone();
-
- /* TODO: adjust the field name (to prevent equal field names)
- if (this.type == 'object') {
- }
- */
-
- // TODO: insert after instead of insert before
- this.insertBefore(clone, node);
-
- return clone;
-};
-
-/**
- * Check if given node is a child. The method will check recursively to find
- * this node.
- * @param {JSONEditor.Node} node
- * @return {boolean} containsNode
- */
-JSONEditor.Node.prototype.containsNode = function(node) {
- if (this == node) {
- return true;
- }
-
- var childs = this.childs;
- if (childs) {
- // TOOD: use the js5 Array.some() here?
- for (var i = 0, iMax = childs.length; i < iMax; i++) {
- if (childs[i].containsNode(node)) {
- return true;
- }
- }
- }
-
- return false;
-};
-
-/**
- * Move given node into this node
- * @param {JSONEditor.Node} node the childNode to be moved
- * @param {JSONEditor.Node} beforeNode node will be inserted before given
- * node. If no beforeNode is given,
- * the node is appended at the end
- * @private
- */
-JSONEditor.Node.prototype._move = function(node, beforeNode) {
- if (node == beforeNode) {
- // nothing to do...
- return;
- }
-
- // check if this node is not a child of the node to be moved here
- if (node.containsNode(this)) {
- throw new Error('Cannot move a field into a child of itself');
- }
-
- // remove the original node
- if (node.parent) {
- node.parent.removeChild(node);
- }
-
- // create a clone of the node
- var clone = node.clone();
- node.clearDom();
-
- // insert or append the node
- if (beforeNode) {
- this.insertBefore(clone, beforeNode);
- }
- else {
- this.appendChild(clone);
- }
-
- /* TODO: adjust the field name (to prevent equal field names)
- if (this.type == 'object') {
- }
- */
-};
-
-/**
- * Remove a child from the node.
- * Only applicable when Node value is of type array or object
- * @param {JSONEditor.Node} node The child node to be removed;
- * @return {JSONEditor.Node | undefined} node The removed node on success,
- * else undefined
- */
-JSONEditor.Node.prototype.removeChild = function(node) {
- if (this.childs) {
- var index = this.childs.indexOf(node);
-
- if (index != -1) {
- node.hide();
-
- // delete old search results
- delete node.searchField;
- delete node.searchValue;
-
- var removedNode = this.childs.splice(index, 1)[0];
-
- this.updateDom({'updateIndexes': true});
-
- return removedNode;
- }
- }
-
- return undefined;
-};
-
-/**
- * Remove a child node node from this node
- * This method is equal to Node.removeChild, except that _remove firex an
- * onChange event.
- * @param {JSONEditor.Node} node
- * @private
- */
-JSONEditor.Node.prototype._remove = function (node) {
- this.removeChild(node);
-};
-
-/**
- * Change the type of the value of this Node
- * @param {String} newType
- */
-JSONEditor.Node.prototype.changeType = function (newType) {
- var oldType = this.type;
-
- if ((newType == 'string' || newType == 'auto') &&
- (oldType == 'string' || oldType == 'auto')) {
- // this is an easy change
- this.type = newType;
- }
- else {
- // change from array to object, or from string/auto to object/array
-
- var table = this.dom.tr ? this.dom.tr.parentNode : undefined;
- var lastTr;
- if (this.expanded) {
- lastTr = this.getAppend();
- }
- else {
- lastTr = this.getDom();
- }
- var nextTr = (lastTr && lastTr.parentNode) ? lastTr.nextSibling : undefined;
-
- // hide current field and all its childs
- this.hide();
- this.clearDom();
-
- // adjust the field and the value
- this.type = newType;
-
- // adjust childs
- if (newType == 'object') {
- if (!this.childs) {
- this.childs = [];
- }
-
- this.childs.forEach(function (child, index) {
- child.clearDom();
- delete child.index;
- child.fieldEditable = true;
- if (child.field == undefined) {
- child.field = index;
- }
- });
-
- if (oldType == 'string' || oldType == 'auto') {
- this.expanded = true;
- }
- }
- else if (newType == 'array') {
- if (!this.childs) {
- this.childs = [];
- }
-
- this.childs.forEach(function (child, index) {
- child.clearDom();
- child.fieldEditable = false;
- child.index = index;
- });
-
- if (oldType == 'string' || oldType == 'auto') {
- this.expanded = true;
- }
- }
- else {
- this.expanded = false;
- }
-
- // create new DOM
- if (table) {
- if (nextTr) {
- table.insertBefore(this.getDom(), nextTr);
- }
- else {
- table.appendChild(this.getDom());
- }
- }
- this.showChilds();
- }
-
- if (newType == 'auto' || newType == 'string') {
- // cast value to the correct type
- if (newType == 'string') {
- this.value = String(this.value);
- }
- else {
- this.value = this._stringCast(String(this.value));
- }
-
- this.focus();
- }
-
- this.updateDom({'updateIndexes': true});
-};
-
-/**
- * Retrieve value from DOM
- * @param {boolean} silent. If true (default), no errors will be thrown in
- * case of invalid data
- * @private
- */
-JSONEditor.Node.prototype._getDomValue = function(silent) {
- if (this.dom.value && this.type != 'array' && this.type != 'object') {
- this.valueInnerText = JSONEditor.getInnerText(this.dom.value);
- }
-
- if (this.valueInnerText != undefined) {
- try {
- // retrieve the value
- var value;
- if (this.type == 'string') {
- value = this._unescapeHTML(this.valueInnerText);
- }
- else {
- var str = this._unescapeHTML(this.valueInnerText);
- value = this._stringCast(str);
- }
- if (value !== this.value) {
- var oldValue = this.value;
- this.value = value;
- this.editor.onAction('editValue', {
- 'node': this,
- 'oldValue': oldValue,
- 'newValue': value
- });
- }
- }
- catch (err) {
- this.value = undefined;
- // TODO: sent an action with the new, invalid value?
- if (silent != true) {
- throw err;
- }
- }
- }
-};
-
-/**
- * Update dom value:
- * - the text color of the value, depending on the type of the value
- * - the height of the field, depending on the width
- * - background color in case it is empty
- * @private
- */
-JSONEditor.Node.prototype._updateDomValue = function () {
- var domValue = this.dom.value;
- if (domValue) {
- // set text color depending on value type
- var v = this.value;
- var t = (this.type == 'auto') ? typeof(v) : this.type;
- var color = '';
- if (t == 'string') {
- color = 'green';
- }
- else if (t == 'number') {
- color = 'red';
- }
- else if (t == 'boolean') {
- color = 'blue';
- }
- else if (this.type == 'object' || this.type == 'array') {
- // note: typeof(null)=="object", therefore check this.type instead of t
- color = '';
- }
- else if (v === null) {
- color = 'purple';
- }
- else if (v === undefined) {
- // invalid value
- color = 'green';
- }
- domValue.style.color = color;
-
- // make backgound color lightgray when empty
- var isEmpty = (String(this.value) == '' && this.type != 'array' && this.type != 'object');
- if (isEmpty) {
- JSONEditor.addClassName(domValue, 'jsoneditor-empty');
- }
- else {
- JSONEditor.removeClassName(domValue, 'jsoneditor-empty');
- }
-
- // highlight when there is a search result
- if (this.searchValueActive) {
- JSONEditor.addClassName(domValue, 'jsoneditor-search-highlight-active');
- }
- else {
- JSONEditor.removeClassName(domValue, 'jsoneditor-search-highlight-active');
- }
- if (this.searchValue) {
- JSONEditor.addClassName(domValue, 'jsoneditor-search-highlight');
- }
- else {
- JSONEditor.removeClassName(domValue, 'jsoneditor-search-highlight');
- }
-
- // strip formatting from the contents of the editable div
- JSONEditor.stripFormatting(domValue);
- }
-};
-
-/**
- * Update dom field:
- * - the text color of the field, depending on the text
- * - the height of the field, depending on the width
- * - background color in case it is empty
- * @private
- */
-JSONEditor.Node.prototype._updateDomField = function () {
- var domField = this.dom.field;
- if (domField) {
- // make backgound color lightgray when empty
- var isEmpty = (String(this.field) == '');
- if (isEmpty) {
- JSONEditor.addClassName(domField, 'jsoneditor-empty');
- }
- else {
- JSONEditor.removeClassName(domField, 'jsoneditor-empty');
- }
-
- // highlight when there is a search result
- if (this.searchFieldActive) {
- JSONEditor.addClassName(domField, 'jsoneditor-search-highlight-active');
- }
- else {
- JSONEditor.removeClassName(domField, 'jsoneditor-search-highlight-active');
- }
- if (this.searchField) {
- JSONEditor.addClassName(domField, 'jsoneditor-search-highlight');
- }
- else {
- JSONEditor.removeClassName(domField, 'jsoneditor-search-highlight');
- }
-
- // strip formatting from the contents of the editable div
- JSONEditor.stripFormatting(domField);
- }
-};
-
-/**
- * Retrieve field from DOM
- * @param {boolean} silent. If true (default), no errors will be thrown in
- * case of invalid data
- * @private
- */
-JSONEditor.Node.prototype._getDomField = function(silent) {
- if (this.dom.field && this.fieldEditable) {
- this.fieldInnerText = JSONEditor.getInnerText(this.dom.field);
- }
-
- if (this.fieldInnerText != undefined) {
- try {
- var field = this._unescapeHTML(this.fieldInnerText);
-
- if (field !== this.field) {
- var oldField = this.field;
- this.field = field;
- this.editor.onAction('editField', {
- 'node': this,
- 'oldValue': oldField,
- 'newValue': field
- });
- }
- }
- catch (err) {
- this.field = undefined;
- // TODO: sent an action here, with the new, invalid value?
- if (silent != true) {
- throw err;
- }
- }
- }
-};
-
-/**
- * Clear the dom of the node
- */
-JSONEditor.Node.prototype.clearDom = function() {
- // TODO: hide the node first?
- //this.hide();
- // TOOD: recursively clear dom?
-
- this.dom = {};
-};
-
-/**
- * Get the HTML DOM TR element of the node.
- * The dom will be generated when not yet created
- * @return {Element} tr HTML DOM TR Element
- */
-JSONEditor.Node.prototype.getDom = function() {
- var dom = this.dom;
- if (dom.tr) {
- return dom.tr;
- }
-
- // create row
- dom.tr = document.createElement('tr');
- dom.tr.className = 'jsoneditor-tr';
- dom.tr.node = this;
-
- if (this.editor.editable) {
- // create draggable area
- var tdDrag = document.createElement('td');
- tdDrag.className = 'jsoneditor-td';
- dom.drag = this._createDomDragArea();
- if (dom.drag) {
- tdDrag.appendChild(dom.drag);
- }
- dom.tr.appendChild(tdDrag);
- }
-
- // create tree and field
- var tdField = document.createElement('td');
- tdField.className = 'jsoneditor-td';
- dom.tr.appendChild(tdField);
- dom.expand = this._createDomExpandButton();
- dom.field = this._createDomField();
- dom.value = this._createDomValue();
- dom.tree = this._createDomTree(dom.expand, dom.field, dom.value);
- tdField.appendChild(dom.tree);
-
- if (this.editor.editable) {
- // create type select box
- var tdType = document.createElement('td');
- tdType.className = 'jsoneditor-td jsoneditor-td-edit';
- dom.tr.appendChild(tdType);
- dom.type = this._createDomTypeButton();
- tdType.appendChild(dom.type);
-
- // create duplicate button
- var tdDuplicate = document.createElement('td');
- tdDuplicate.className = 'jsoneditor-td jsoneditor-td-edit';
- dom.tr.appendChild(tdDuplicate);
- dom.duplicate = this._createDomDuplicateButton();
- if (dom.duplicate) {
- tdDuplicate.appendChild(dom.duplicate);
- }
-
- // create remove button
- var tdRemove = document.createElement('td');
- tdRemove.className = 'jsoneditor-td jsoneditor-td-edit';
- dom.tr.appendChild(tdRemove);
- dom.remove = this._createDomRemoveButton();
- if (dom.remove) {
- tdRemove.appendChild(dom.remove);
- }
- }
-
- this.updateDom(); // TODO: recurse here?
-
- return dom.tr;
-};
-
-/**
- * DragStart event, fired on mousedown on the dragarea at the left side of a Node
- * @param {Event} event
- * @private
- */
-JSONEditor.Node.prototype._onDragStart = function (event) {
- event = event || window.event;
-
- var node = this;
- if (!this.mousemove) {
- this.mousemove = JSONEditor.Events.addEventListener(document, 'mousemove',
- function (event) {
- node._onDrag(event);
- });
- }
-
- if (!this.mouseup) {
- this.mouseup = JSONEditor.Events.addEventListener(document, 'mouseup',
- function (event ) {
- node._onDragEnd(event);
- });
- }
-
- /* TODO: correct highlighting when the TypeDropDown is visible (And has highlighting locked)
- if (JSONEditor.freezeHighlight) {
- console.log('heee');
- JSONEditor.freezeHighlight = false;
- this.setHighlight(true);
- }
- */
- JSONEditor.freezeHighlight = true;
- this.drag = {
- 'oldCursor': document.body.style.cursor,
- 'startParent': this.parent,
- 'startIndex': this.parent.childs.indexOf(this)
- };
- document.body.style.cursor = 'move';
-
- JSONEditor.Events.preventDefault(event);
-};
-
-/**
- * Drag event, fired when moving the mouse while dragging a Node
- * @param {Event} event
- * @private
- */
-JSONEditor.Node.prototype._onDrag = function (event) {
- event = event || window.event;
- var trThis = this.dom.tr;
-
- // TODO: add an ESC option, which resets to the original position
-
- var topThis = JSONEditor.getAbsoluteTop(trThis);
- var heightThis = trThis.offsetHeight;
- var mouseY = event.pageY || (event.clientY + document.body.scrollTop);
- if (mouseY < topThis) {
- // move up
- var trPrev = trThis.previousSibling;
- var topPrev = JSONEditor.getAbsoluteTop(trPrev);
- var nodePrev = JSONEditor.getNodeFromTarget(trPrev);
- while (trPrev && mouseY < topPrev) {
- nodePrev = JSONEditor.getNodeFromTarget(trPrev);
- trPrev = trPrev.previousSibling;
- topPrev = JSONEditor.getAbsoluteTop(trPrev);
- }
-
- if (nodePrev) {
- trPrev = nodePrev.dom.tr;
- topPrev = JSONEditor.getAbsoluteTop(trPrev);
- if (mouseY > topPrev + heightThis) {
- nodePrev = undefined;
- }
- }
-
- if (nodePrev && nodePrev.parent) {
- nodePrev.parent.moveBefore(this, nodePrev);
- }
- }
- else {
- // move down
- var trLast = (this.expanded && this.append) ? this.append.getDom() : this.dom.tr;
- var trFirst = trLast ? trLast.nextSibling : undefined;
- if (trFirst) {
- var topFirst = JSONEditor.getAbsoluteTop(trFirst);
-
- var nodeNext = undefined;
- var trNext = trFirst.nextSibling;
- var topNext = JSONEditor.getAbsoluteTop(trNext);
- var heightNext = trNext ? (topNext - topFirst) : 0;
- while (trNext && mouseY > topThis + heightNext) {
- nodeNext = JSONEditor.getNodeFromTarget(trNext);
- trNext = trNext.nextSibling;
- topNext = JSONEditor.getAbsoluteTop(trNext);
- heightNext = trNext ? (topNext - topFirst) : 0;
- }
-
- if (nodeNext && nodeNext.parent) {
- nodeNext.parent.moveBefore(this, nodeNext);
- }
- }
- }
- JSONEditor.Events.preventDefault(event);
-};
-
-/**
- * Drag event, fired on mouseup after having dragged a node
- * @param {Event} event
- * @private
- */
-JSONEditor.Node.prototype._onDragEnd = function (event) {
- event = event || window.event;
-
- var params = {
- 'node': this,
- 'startParent': this.drag.startParent,
- 'startIndex': this.drag.startIndex,
- 'endParent': this.parent,
- 'endIndex': this.parent.childs.indexOf(this)
- };
- if ((params.startParent != params.endParent) ||
- (params.startIndex != params.endIndex)) {
- // only register this action if the node is actually moved to another place
- this.editor.onAction('moveNode', params);
- }
-
- document.body.style.cursor = this.drag.oldCursor;
- delete JSONEditor.freezeHighlight;
- delete this.drag;
- this.setHighlight(false);
-
- if (this.mousemove) {
- JSONEditor.Events.removeEventListener(document, 'mousemove', this.mousemove);
- delete this.mousemove;
- }
- if (this.mouseup) {
- JSONEditor.Events.removeEventListener(document, 'mouseup', this.mouseup);
- delete this.mouseup;
- }
-
- JSONEditor.Events.preventDefault(event);
-};
-
-/**
- * Create a drag area, displayed at the left side of the node
- * @return {Element | undefined} domDrag
- * @private
- */
-JSONEditor.Node.prototype._createDomDragArea = function () {
- if (!this.parent) {
- return undefined;
- }
-
- var domDrag = document.createElement('button');
- domDrag.className = 'jsoneditor-dragarea';
- domDrag.title = 'Move field (drag and drop)';
-
- return domDrag;
-};
-
-/**
- * Create an editable field
- * @return {Element} domField
- * @private
- */
-JSONEditor.Node.prototype._createDomField = function () {
- return document.createElement('div');
-};
-
-/**
- * Set highlighting for this node and all its childs.
- * Only applied to the currently visible (expanded childs)
- * @param {boolean} highlight
- */
-JSONEditor.Node.prototype.setHighlight = function (highlight) {
- if (JSONEditor.freezeHighlight) {
- return;
- }
-
- if (this.dom.tr) {
- this.dom.tr.className = 'jsoneditor-tr' + (highlight ? ' jsoneditor-tr-highlight' : '');
-
- if (this.append) {
- this.append.setHighlight(highlight);
- }
-
- if (this.childs) {
- this.childs.forEach(function (child) {
- child.setHighlight(highlight);
- });
- }
- }
-};
-
-/**
- * Update the value of the node. Only primitive types are allowed, no Object
- * or Array is allowed.
- * @param {String | Number | Boolean | null} value
- */
-JSONEditor.Node.prototype.updateValue = function (value) {
- this.value = value;
- this.updateDom();
-};
-
-/**
- * Update the field of the node.
- * @param {String} field
- */
-JSONEditor.Node.prototype.updateField = function (field) {
- this.field = field;
- this.updateDom();
-};
-
-/**
- * Update the HTML DOM, optionally recursing through the childs
- * @param {Object} [options] Available parameters:
- * {boolean} [recurse] If true, the
- * DOM of the childs will be updated recursively.
- * False by default.
- * {boolean} [updateIndexes] If true, the childs
- * indexes of the node will be updated too. False by
- * default.
- */
-JSONEditor.Node.prototype.updateDom = function (options) {
- // update level indentation
- var domTree = this.dom.tree;
- if (domTree) {
- domTree.style.marginLeft = this.getLevel() * 24 + 'px';
- }
-
- // update field
- var domField = this.dom.field;
- if (domField) {
- if (this.fieldEditable == true) {
- // parent is an object
- domField.contentEditable = this.editor.editable;
- domField.spellcheck = false;
- domField.className = 'jsoneditor-field';
- }
- else {
- // parent is an array this is the root node
- domField.className = 'jsoneditor-readonly';
- }
-
- var field;
- if (this.index != undefined) {
- field = this.index;
- }
- else if (this.field != undefined) {
- field = this.field;
- }
- else if (this.type == 'array' || this.type == 'object') {
- field = this.type;
- }
- else {
- field = 'field';
- }
- domField.innerHTML = this._escapeHTML(field);
- }
-
- // update value
- var domValue = this.dom.value;
- if (domValue) {
- var count = this.childs ? this.childs.length : 0;
- if (this.type == 'array') {
- domValue.innerHTML = '[' + count + ']';
- domValue.title = this.type + ' containing ' + count + ' items';
- }
- else if (this.type == 'object') {
- domValue.innerHTML = '{' + count + '}';
- domValue.title = this.type + ' containing ' + count + ' items';
- }
- else {
- domValue.innerHTML = this._escapeHTML(this.value);
- delete domValue.title;
- }
- }
-
- // update field and value
- this._updateDomField();
- this._updateDomValue();
-
- // update childs indexes
- if (options && options.updateIndexes == true) {
- // updateIndexes is true or undefined
- this._updateDomIndexes();
- }
-
- if (options && options.recurse == true) {
- // recurse is true or undefined. update childs recursively
- if (this.childs) {
- this.childs.forEach(function (child) {
- child.updateDom(options);
- });
- }
-
- // update row with append button
- if (this.append) {
- this.append.updateDom();
- }
- }
-};
-
-/**
- * Update the DOM of the childs of a node: update indexes and undefined field
- * names.
- * Only applicable when structure is an array or object
- * @private
- */
-JSONEditor.Node.prototype._updateDomIndexes = function () {
- var domValue = this.dom.value;
- var childs = this.childs;
- if (domValue && childs) {
- if (this.type == 'array') {
- childs.forEach(function (child, index) {
- child.index = index;
- var childField = child.dom.field;
- if (childField) {
- childField.innerHTML = index;
- }
- });
- }
- else if (this.type == 'object') {
- childs.forEach(function (child) {
- if (child.index != undefined) {
- delete child.index;
-
- if (child.field == undefined) {
- child.field = 'field';
- }
- }
- });
- }
- }
-};
-
-/**
- * Create an editable value
- * @private
- */
-JSONEditor.Node.prototype._createDomValue = function () {
- var domValue;
-
- if (this.type == 'array') {
- domValue = document.createElement('div');
- domValue.className = 'jsoneditor-readonly';
- domValue.innerHTML = '[...]';
- }
- else if (this.type == 'object') {
- domValue = document.createElement('div');
- domValue.className = 'jsoneditor-readonly';
- domValue.innerHTML = '{...}';
- }
- else if (this.type == 'string') {
- domValue = document.createElement('div');
- domValue.contentEditable = this.editor.editable;
- domValue.spellcheck = false;
- domValue.className = 'jsoneditor-value';
- domValue.innerHTML = this._escapeHTML(this.value);
- }
- else {
- domValue = document.createElement('div');
- domValue.contentEditable = this.editor.editable;
- domValue.spellcheck = false;
- domValue.className = 'jsoneditor-value';
- domValue.innerHTML = this._escapeHTML(this.value);
- }
-
- // TODO: in FF spel/check of editable divs is done via the body. quite ugly
- // document.body.spellcheck = false;
-
- return domValue;
-};
-
-/**
- * Create an expand/collapse button
- * @return {Element} expand
- * @private
- */
-JSONEditor.Node.prototype._createDomExpandButton = function () {
- // create expand button
- var expand = document.createElement('button');
- var expandable = (this.type == 'array' || this.type == 'object');
- if (expandable) {
- expand.className = this.expanded ? 'jsoneditor-expanded' : 'jsoneditor-collapsed';
- expand.title =
- 'Click to expand/collapse this field. \n' +
- 'Ctrl+Click to expand/collapse including all childs.';
- }
- else {
- expand.className = 'jsoneditor-invisible';
- expand.title = '';
- }
-
- return expand;
-};
-
-
-/**
- * Create a DOM tree element, containing the expand/collapse button
- * @param {Element} domExpand
- * @param {Element} domField
- * @param {Element} domValue
- * @return {Element} domTree
- * @private
- */
-JSONEditor.Node.prototype._createDomTree = function (domExpand, domField, domValue) {
- var dom = this.dom;
- var domTree = document.createElement('table');
- var tbody = document.createElement('tbody');
- domTree.style.borderCollapse = 'collapse'; // TODO: put in css
- domTree.appendChild(tbody);
- var tr = document.createElement('tr');
- tbody.appendChild(tr);
-
- // create expand button
- var tdExpand = document.createElement('td');
- tdExpand.className = 'jsoneditor-td-tree';
- tr.appendChild(tdExpand);
- tdExpand.appendChild(domExpand);
- dom.tdExpand = tdExpand;
-
- // add the field
- var tdField = document.createElement('td');
- tdField.className = 'jsoneditor-td-tree';
- tr.appendChild(tdField);
- tdField.appendChild(domField);
- dom.tdField = tdField;
-
- // add a separator
- var tdSeparator = document.createElement('td');
- tdSeparator.className = 'jsoneditor-td-tree';
- tr.appendChild(tdSeparator);
- if (this.type != 'object' && this.type != 'array') {
- tdSeparator.appendChild(document.createTextNode(':'));
- tdSeparator.className = 'jsoneditor-separator';
- }
- dom.tdSeparator = tdSeparator;
-
- // add the value
- var tdValue = document.createElement('td');
- tdValue.className = 'jsoneditor-td-tree';
- tr.appendChild(tdValue);
- tdValue.appendChild(domValue);
- dom.tdValue = tdValue;
-
- return domTree;
-};
-
-/**
- * Handle an event. The event is catched centrally by the editor
- * @param {Event} event
- */
-JSONEditor.Node.prototype.onEvent = function (event) {
- var type = event.type;
- var target = event.target || event.srcElement;
- var dom = this.dom;
- var node = this;
- var expandable = (this.type == 'array' || this.type == 'object');
-
- // value events
- var domValue = dom.value;
- if (target == domValue) {
- switch (type) {
- case 'focus':
- JSONEditor.focusNode = this;
- break;
-
- case 'blur':
- case 'change':
- this._getDomValue(true);
- this._updateDomValue();
- if (this.value) {
- domValue.innerHTML = this._escapeHTML(this.value);
- }
- break;
-
- case 'keyup':
- this._getDomValue(true);
- this._updateDomValue();
- break;
-
- case 'cut':
- case 'paste':
- setTimeout(function () {
- node._getDomValue(true);
- node._updateDomValue();
- }, 1);
- break;
- }
- }
-
- // field events
- var domField = dom.field;
- if (target == domField) {
- switch (type) {
- case 'focus':
- JSONEditor.focusNode = this;
- break;
-
- case 'change':
- case 'blur':
- this._getDomField(true);
- this._updateDomField();
- if (this.field) {
- domField.innerHTML = this._escapeHTML(this.field);
- }
- break;
-
- case 'keyup':
- this._getDomField(true);
- this._updateDomField();
- break;
-
- case 'cut':
- case 'paste':
- setTimeout(function () {
- node._getDomField(true);
- node._updateDomField();
- }, 1);
- break;
- }
- }
-
- // drag events
- var domDrag = dom.drag;
- if (target == domDrag) {
- switch (type) {
- case 'mousedown':
- this._onDragStart(event);
- break;
- case 'mouseover':
- this.setHighlight(true);
- break;
- case 'mouseout':
- this.setHighlight(false);
- break;
- }
- }
-
- // expand events
- var domExpand = dom.expand;
- if (target == domExpand) {
- if (type == 'click') {
- if (expandable) {
- this._onExpand(event);
- }
- }
- }
-
- // duplicate button
- var domDuplicate = dom.duplicate;
- if (target == domDuplicate) {
- switch (type) {
- case 'click':
- var clone = this.parent._duplicate(this);
-
- this.editor.onAction('duplicateNode', {
- 'node': this,
- 'clone': clone,
- 'parent': this.parent
- });
- break;
- case 'mouseover':
- this.setHighlight(true);
- break;
- case 'mouseout':
- this.setHighlight(false);
- break;
- }
- }
-
- // remove button
- var domRemove = dom.remove;
- if (target == domRemove) {
- switch (type) {
- case 'click':
- this._onRemove();
- break;
- case 'mouseover':
- this.setHighlight(true);
- break;
- case 'mouseout':
- this.setHighlight(false);
- break;
- }
- }
-
- // type button
- var domType = dom.type;
- if (target == domType) {
- switch (type) {
- case 'click':
- this._onChangeType(event);
- break;
- case 'mouseover':
- this.setHighlight(true);
- break;
- case 'mouseout':
- this.setHighlight(false);
- break;
- }
- }
-
- // focus
- // when clicked in whitespace left or right from the field or value, set focus
- var domTree = dom.tree;
- if (target == domTree.parentNode) {
- switch (type) {
- case 'click':
- var left = (event.offsetX != undefined) ?
- (event.offsetX < (this.getLevel() + 1) * 24) :
- (event.clientX < JSONEditor.getAbsoluteLeft(dom.tdSeparator));// for FF
- if (left || expandable) {
- // node is expandable when it is an object or array
- if (domField) {
- JSONEditor.setEndOfContentEditable(domField);
- domField.focus();
- }
- }
- else {
- if (domValue) {
- JSONEditor.setEndOfContentEditable(domValue);
- domValue.focus();
- }
- }
- break;
- }
- }
-
- if ((target == dom.tdExpand && !expandable) || target == dom.tdField || target == dom.tdSeparator) {
- switch (type) {
- case 'click':
- if (domField) {
- JSONEditor.setEndOfContentEditable(domField);
- domField.focus();
- }
- break;
- }
- }
-};
-
-/**
- * Handle the expand event, when clicked on the expand button
- * @param {Event} event
- * @private
- */
-JSONEditor.Node.prototype._onExpand = function (event) {
- event = event || window.event;
- var recurse = event.ctrlKey; // with ctrl-key, expand/collapse all
-
- if (recurse) {
- // Take the table offline
- var table = this.dom.tr.parentNode; // TODO: not nice to access the main table like this
- var frame = table.parentNode;
- var scrollTop = frame.scrollTop;
- frame.removeChild(table);
- }
-
- if (this.expanded) {
- this.collapse(recurse);
- }
- else {
- this.expand(recurse);
- }
-
- if (recurse) {
- // Put the table online again
- frame.appendChild(table);
- frame.scrollTop = scrollTop;
- }
-};
-
-JSONEditor.Node.types = [
- {
- 'value': 'array',
- 'className': 'jsoneditor-option-array',
- 'title': 'Field type "array". ' +
- 'An array contains an ordered collection of values.'
- },
- {
- 'value': 'auto',
- 'className': 'jsoneditor-option-auto',
- 'title': 'Field type "auto". ' +
- 'The field type is automatically determined from the value ' +
- 'and can be a string, number, boolean, or null.'
- },
- {
- 'value': 'object',
- 'className': 'jsoneditor-option-object',
- 'title': 'Field type "object". ' +
- 'An object contains an unordered set of key/value pairs.'
- },
- {
- 'value': 'string',
- 'className': 'jsoneditor-option-string',
- 'title': 'Field type "string". ' +
- 'Field type is not determined from the value, ' +
- 'but always returned as string.'
- }
-];
-
-/**
- * Create a DOM select box containing the node type
- * @return {Element} domType
- * @private
- */
-JSONEditor.Node.prototype._createDomTypeButton = function () {
- var node = this;
- var domType = document.createElement('button');
- domType.className = 'jsoneditor-type-' + node.type;
- domType.title = 'Change field type';
-
- return domType;
-};
-
-/**
- * Remove this node
- * @private
- */
-JSONEditor.Node.prototype._onRemove = function() {
- this.setHighlight(false);
- var index = this.parent.childs.indexOf(this);
-
- this.parent._remove(this);
-
- this.editor.onAction('removeNode', {
- 'node': this,
- 'parent': this.parent,
- 'index': index
- });
-};
-
-/**
- * Handle a click on the Type-button
- * @param {Event} event
- * @private
- */
-JSONEditor.Node.prototype._onChangeType = function (event) {
- JSONEditor.Events.stopPropagation(event);
-
- var domType = this.dom.type;
-
- var node = this;
- var x = JSONEditor.getAbsoluteLeft(domType);
- var y = JSONEditor.getAbsoluteTop(domType) + domType.clientHeight;
- var callback = function (newType) {
- var oldType = node.type;
- node.changeType(newType);
- node.editor.onAction('changeType', {
- 'node': node,
- 'oldType': oldType,
- 'newType': newType
- });
- domType.className = 'jsoneditor-type-' + node.type;
- };
- JSONEditor.showDropDownList({
- 'x': x,
- 'y': y,
- 'node': node,
- 'value': node.type,
- 'values': JSONEditor.Node.types,
- 'className': 'jsoneditor-select',
- 'optionSelectedClassName': 'jsoneditor-option-selected',
- 'optionClassName': 'jsoneditor-option',
- 'callback': callback
- });
-};
-
-/**
- * Show a dropdown list
- * @param {Object} params Available parameters:
- * {Number} x The absolute horizontal position
- * {Number} y The absolute vertical position
- * {JSONEditor.Node} node node used for highlighting
- * {String} value current selected value
- * {Object[]} values the available values. Each object
- * contains a value, title, and
- * className
- * {String} optionSelectedClassName
- * {String} optionClassName
- * {function} callback Callback method, called when
- * the selected value changed.
- */
-JSONEditor.showDropDownList = function (params) {
- var select = document.createElement('div');
- select.className = params.className || '';
- select.style.position = 'absolute';
- select.style.left = (params.x || 0) + 'px';
- select.style.top = (params.y || 0) + 'px';
-
- params.values.forEach(function (v) {
- var text = v.value || String(v);
- var className = 'jsoneditor-option';
- var selected = (text == params.value);
- if (selected) {
- className += ' ' + params.optionSelectedClassName;
- }
- var option = document.createElement('div');
- option.className = className;
- if (v.title) {
- option.title = v.title;
- }
-
- var divIcon = document.createElement('div');
- divIcon.className = (v.className || '');
- option.appendChild(divIcon);
-
- var divText = document.createElement('div');
- divText.className = 'jsoneditor-option-text';
- divText.innerHTML = '<div>' + text + '</div>';
- option.appendChild(divText);
-
- option.onmousedown = (function (value) {
- return function () {
- params.callback(value);
- };
- })(v.value);
- select.appendChild(option);
- });
-
- document.body.appendChild(select);
- params.node.setHighlight(true);
- JSONEditor.freezeHighlight = true;
-
- // TODO: change to onclick? -> but be sure to remove existing dropdown first
- var onmousedown = JSONEditor.Events.addEventListener(document, 'mousedown', function () {
- JSONEditor.freezeHighlight = false;
- params.node.setHighlight(false);
- if (select && select.parentNode) {
- select.parentNode.removeChild(select);
- }
- JSONEditor.Events.removeEventListener(document, 'mousedown', onmousedown);
- });
- var onmousewheel = JSONEditor.Events.addEventListener(document, 'mousewheel', function () {
- JSONEditor.freezeHighlight = false;
- params.node.setHighlight(false);
- if (select && select.parentNode) {
- select.parentNode.removeChild(select);
- }
- JSONEditor.Events.removeEventListener(document, 'mousewheel', onmousewheel);
- });
-};
-
-/**
- * Create a table row with an append button.
- * @return {Element | undefined} buttonAppend or undefined when inapplicable
- */
-JSONEditor.Node.prototype.getAppend = function () {
- if (!this.append) {
- this.append = new JSONEditor.AppendNode(this.editor);
- this.append.setParent(this);
- }
- return this.append.getDom();
-};
-
-/**
- * Create a remove button. Returns undefined when the structure cannot
- * be removed
- * @return {Element | undefined} removeButton, or undefined when inapplicable
- * @private
- */
-JSONEditor.Node.prototype._createDomRemoveButton = function () {
- if (this.parent && (this.parent.type == 'array' || this.parent.type == 'object')) {
- var buttonRemove = document.createElement('button');
- buttonRemove.className = 'jsoneditor-remove';
- buttonRemove.title = 'Remove field (including all its childs)';
-
- return buttonRemove;
- }
- else {
- return undefined;
- }
-};
-
-/**
- * Create a duplicate button.
- * If the Node is the root node, no duplicate button is available and undefined
- * will be returned
- * @return {Element | undefined} buttonDuplicate
- * @private
- */
-JSONEditor.Node.prototype._createDomDuplicateButton = function () {
- if (this.parent && (this.parent.type == 'array' || this.parent.type == 'object')) {
- var buttonDupliate = document.createElement('button');
- buttonDupliate.className = 'jsoneditor-duplicate';
- buttonDupliate.title = 'Duplicate field (including all childs)';
-
- return buttonDupliate;
- }
- else {
- return undefined;
- }
-};
-
-/**
- * get the type of a value
- * @param {*} value
- * @return {String} type Can be 'object', 'array', 'string', 'auto'
- * @private
- */
-JSONEditor.Node.prototype._getType = function(value) {
- if (value instanceof Array) {
- return 'array';
- }
- if (value instanceof Object) {
- return 'object';
- }
- if (typeof(value) == 'string' && typeof(this._stringCast(value)) != 'string') {
- return 'string';
- }
-
- return 'auto';
-};
-
-/**
- * cast contents of a string to the correct type. This can be a string,
- * a number, a boolean, etc
- * @param {String} str
- * @return {*} castedStr
- * @private
- */
-JSONEditor.Node.prototype._stringCast = function(str) {
- var lower = str.toLowerCase(),
- num = Number(str), // will nicely fail with '123ab'
- numFloat = parseFloat(str); // will nicely fail with ' '
-
- if (str == '') {
- return '';
- }
- else if (lower == 'null') {
- return null;
- }
- else if (lower == 'true') {
- return true;
- }
- else if (lower == 'false') {
- return false;
- }
- else if (!isNaN(num) && !isNaN(numFloat)) {
- return num;
- }
- else {
- return str;
- }
-};
-
-/**
- * escape a text, such that it can be displayed safely in an HTML element
- * @param {String} text
- * @return {String} escapedText
- * @private
- */
-JSONEditor.Node.prototype._escapeHTML = function (text) {
- var htmlEscaped = String(text)
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/ /g, ' &nbsp;') // replace double space with an nbsp and space
- .replace(/^ /, '&nbsp;') // space at start
- .replace(/ $/, '&nbsp;'); // space at end
-
- var json = JSON.stringify(htmlEscaped);
- return json.substring(1, json.length - 1);
-};
-
-/**
- * unescape a string.
- * @param {String} escapedText
- * @return {String} text
- * @private
- */
-JSONEditor.Node.prototype._unescapeHTML = function (escapedText) {
- var json = '"' + this._escapeJSON(escapedText) + '"';
- var htmlEscaped = JSONEditor.parse(json);
- return htmlEscaped
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&nbsp;/g, ' ');
-};
-
-/**
- * escape a text to make it a valid JSON string. The method will:
- * - replace unescaped double quotes with '\"'
- * - replace unescaped backslash with '\\'
- * - replace returns with '\n'
- * @param {String} text
- * @return {String} escapedText
- * @private
- */
-JSONEditor.Node.prototype._escapeJSON = function (text) {
- // TODO: replace with some smart regex (only when a new solution is faster!)
- var escaped = '';
- var i = 0, iMax = text.length;
- while (i < iMax) {
- var c = text.charAt(i);
- if (c == '\n') {
- escaped += '\\n';
- }
- else if (c == '\\') {
- escaped += c;
- i++;
-
- c = text.charAt(i);
- if ('"\\/bfnrtu'.indexOf(c) == -1) {
- escaped += '\\'; // no valid escape character
- }
- escaped += c;
- }
- else if (c == '"') {
- escaped += '\\"';
- }
- else {
- escaped += c;
- }
- i++;
- }
-
- return escaped;
-};
-
-/**
- * @constructor JSONEditor.AppendNode
- * @extends JSONEditor.Node
- * @param {JSONEditor} editor
- * Create a new AppendNode. This is a special node which is created at the
- * end of the list with childs for an object or array
- */
-JSONEditor.AppendNode = function (editor) {
- this.editor = editor;
- this.dom = {};
-};
-
-JSONEditor.AppendNode.prototype = new JSONEditor.Node();
-
-/**
- * Return a table row with an append button.
- * @return {Element} dom TR element
- */
-JSONEditor.AppendNode.prototype.getDom = function () {
- if (this.dom.tr) {
- return this.dom.tr;
- }
-
- /**
- * Create a TD element, and give it the provided class name (if any)
- * @param {String} [className]
- * @return {Element} td
- */
- function newTd(className) {
- var td = document.createElement('td');
- td.className = className || '';
- return td;
- }
-
- // a row for the append button
- var trAppend = document.createElement('tr');
- trAppend.node = this;
-
- // TODO: do not create an appendNode at all when in viewer mode
- if (!this.editor.editable) {
- return trAppend;
- }
-
- // a cell for the drag area column
- trAppend.appendChild(newTd('jsoneditor-td'));
-
- // a cell for the append button
- var tdAppend = document.createElement('td');
- trAppend.appendChild(tdAppend);
- tdAppend.className = 'jsoneditor-td';
-
- // create the append button
- var buttonAppend = document.createElement('button');
- buttonAppend.className = 'jsoneditor-append';
- buttonAppend.title = 'Append a field';
- this.dom.append = buttonAppend;
- tdAppend.appendChild(buttonAppend);
-
- trAppend.appendChild(newTd('jsoneditor-td jsoneditor-td-edit'));
- trAppend.appendChild(newTd('jsoneditor-td jsoneditor-td-edit'));
- trAppend.appendChild(newTd('jsoneditor-td jsoneditor-td-edit'));
-
- this.dom.tr = trAppend;
- this.dom.td = tdAppend;
-
- this.updateDom();
-
- return trAppend;
-};
-
-/**
- * Update the HTML dom of the Node
- */
-JSONEditor.AppendNode.prototype.updateDom = function () {
- var tdAppend = this.dom.td;
- if (tdAppend) {
- tdAppend.style.paddingLeft = (this.getLevel() * 24 + 26) + 'px';
- // TODO: not so nice hard coded offset
- }
-};
-
-/**
- * Handle an event. The event is catched centrally by the editor
- * @param {Event} event
- */
-JSONEditor.AppendNode.prototype.onEvent = function (event) {
- var type = event.type;
- var target = event.target || event.srcElement;
- var dom = this.dom;
-
- var domAppend = dom.append;
- if (target == domAppend) {
- switch (type) {
- case 'click':
- this._onAppend();
- break;
-
- case 'mouseover':
- this.parent.setHighlight(true);
- break;
-
- case 'mouseout':
- this.parent.setHighlight(false);
- }
- }
-};
-
-/**
- * Handle append event
- * @private
- */
-JSONEditor.AppendNode.prototype._onAppend = function () {
- var newNode = new JSONEditor.Node(this.editor, {
- 'field': 'field',
- 'value': 'value'
- });
- this.parent.appendChild(newNode);
- this.parent.setHighlight(false);
- newNode.focus();
-
- this.editor.onAction('appendNode', {
- 'node': newNode,
- 'parent': this.parent
- });
-};
-
-/**
- * Create main frame
- * @private
- */
-JSONEditor.prototype._createFrame = function () {
- // create the frame
- this.container.innerHTML = '';
- this.frame = document.createElement('div');
- this.frame.className = 'jsoneditor-frame';
- this.container.appendChild(this.frame);
-
- // create one global event listener to handle all events from all nodes
- var editor = this;
- // TODO: move this onEvent to JSONEditor.prototype.onEvent
- var onEvent = function (event) {
- event = event || window.event;
- var target = event.target || event.srcElement;
-
- /* TODO: Enable quickkeys Ctrl+F and F3.
- // Requires knowing whether the JSONEditor has focus or not
- // (use a global event listener for that?)
- // Check for search quickkeys, Ctrl+F and F3
- if (editor.options.search) {
- if (event.type == 'keydown') {
- var keynum = event.which || event.keyCode;
- if (keynum == 70 && event.ctrlKey) { // Ctrl+F
- if (editor.searchBox) {
- editor.searchBox.dom.search.focus();
- editor.searchBox.dom.search.select();
- JSONEditor.Events.preventDefault(event);
- JSONEditor.Events.stopPropagation(event);
- }
- }
- else if (keynum == 114) { // F3
- if (!event.shiftKey) {
- // select next search result
- editor.searchBox.next();
- }
- else {
- // select previous search result
- editor.searchBox.previous();
- }
- editor.searchBox.focusActiveResult();
-
- // set selection to the current
- JSONEditor.Events.preventDefault(event);
- JSONEditor.Events.stopPropagation(event);
- }
- }
- }
- */
-
- var node = JSONEditor.getNodeFromTarget(target);
- if (node) {
- node.onEvent(event);
- }
- };
- this.frame.onclick = function (event) {
- onEvent(event);
-
- // prevent default submit action when JSONEditor is located inside a form
- JSONEditor.Events.preventDefault(event);
- };
- this.frame.onchange = onEvent;
- this.frame.onkeydown = onEvent;
- this.frame.onkeyup = onEvent;
- this.frame.oncut = onEvent;
- this.frame.onpaste = onEvent;
- this.frame.onmousedown = onEvent;
- this.frame.onmouseup = onEvent;
- this.frame.onmouseover = onEvent;
- this.frame.onmouseout = onEvent;
- // Note: focus and blur events do not propagate, therefore they defined
- // using an eventListener with useCapture=true
- // see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
- JSONEditor.Events.addEventListener(this.frame, 'focus', onEvent, true);
- JSONEditor.Events.addEventListener(this.frame, 'blur', onEvent, true);
- this.frame.onfocusin = onEvent; // for IE
- this.frame.onfocusout = onEvent; // for IE
-
- // create menu
- this.menu = document.createElement('div');
- this.menu.className = 'jsoneditor-menu';
- this.frame.appendChild(this.menu);
-
- // create expand all button
- var expandAll = document.createElement('button');
- expandAll.className = 'jsoneditor-menu jsoneditor-expand-all';
- expandAll.title = 'Expand all fields';
- expandAll.onclick = function () {
- editor.expandAll();
- };
- this.menu.appendChild(expandAll);
-
- // create expand all button
- var collapseAll = document.createElement('button');
- collapseAll.title = 'Collapse all fields';
- collapseAll.className = 'jsoneditor-menu jsoneditor-collapse-all';
- collapseAll.onclick = function () {
- editor.collapseAll();
- };
- this.menu.appendChild(collapseAll);
-
- // create expand/collapse buttons
- if (this.history) {
- // create separator
- var separator = document.createElement('span');
- separator.innerHTML = '&nbsp;';
- this.menu.appendChild(separator);
-
- // create undo button
- var undo = document.createElement('button');
- undo.className = 'jsoneditor-menu jsoneditor-undo';
- undo.title = 'Undo last action';
- undo.onclick = function () {
- // undo last action
- editor.history.undo();
-
- // trigger change callback
- if (editor.options.change) {
- editor.options.change();
- }
- };
- this.menu.appendChild(undo);
- this.dom.undo = undo;
-
- // create redo button
- var redo = document.createElement('button');
- redo.className = 'jsoneditor-menu jsoneditor-redo';
- redo.title = 'Redo';
- redo.onclick = function () {
- // redo last action
- editor.history.redo();
-
- // trigger change callback
- if (editor.options.change) {
- editor.options.change();
- }
- };
- this.menu.appendChild(redo);
- this.dom.redo = redo;
-
- // register handler for onchange of history
- this.history.onChange = function () {
- undo.disabled = !editor.history.canUndo();
- redo.disabled = !editor.history.canRedo();
- };
- this.history.onChange();
- }
-
- // create search box
- if (this.options.search) {
- this.searchBox = new JSONEditor.SearchBox(this, this.menu);
- }
-};
-
-
-/**
- * Create main table
- * @private
- */
-JSONEditor.prototype._createTable = function () {
- var contentOuter = document.createElement('div');
- contentOuter.className = 'jsoneditor-content-outer';
- this.contentOuter = contentOuter;
-
- this.content = document.createElement('div');
- this.content.className = 'jsoneditor-content';
- contentOuter.appendChild(this.content);
-
- this.table = document.createElement('table');
- this.table.className = 'jsoneditor-table';
- this.content.appendChild(this.table);
-
- // IE8 does not handle overflow='auto' correctly.
- // Therefore, set overflow to 'scroll'
- var ieVersion = JSONEditor.getInternetExplorerVersion();
- if (ieVersion == 8) {
- this.content.style.overflow = 'scroll';
- }
-
- // create colgroup where the first two columns don't have a fixed
- // width, and the edit columns do have a fixed width
- var col;
- this.colgroupContent = document.createElement('colgroup');
- col = document.createElement('col');
- col.width = "24px";
- this.colgroupContent.appendChild(col);
- col = document.createElement('col');
- this.colgroupContent.appendChild(col);
- col = document.createElement('col');
- col.width = "24px";
- this.colgroupContent.appendChild(col);
- col = document.createElement('col');
- col.width = "24px";
- this.colgroupContent.appendChild(col);
- col = document.createElement('col');
- col.width = "24px";
- this.colgroupContent.appendChild(col);
- this.table.appendChild(this.colgroupContent);
-
- this.tbody = document.createElement('tbody');
- this.table.appendChild(this.tbody);
-
- this.frame.appendChild(contentOuter);
-};
-
-/**
- * Find the node from an event target
- * @param {Element} target
- * @return {JSONEditor.Node | undefined} node or undefined when not found
- */
-JSONEditor.getNodeFromTarget = function (target) {
- while (target) {
- if (target.node) {
- return target.node;
- }
- target = target.parentNode;
- }
-
- return undefined;
-};
-
-/**
- * Create a JSONFormatter and attach it to given container
- * @constructor JSONFormatter
- * @param {Element} container
- * @param {Object} [options] Object with options. available options:
- * {Number} indentation Number of indentation
- * spaces. 4 by default.
- * {function} change Callback method
- * triggered on change
- * @param {JSON | String} [json] initial contents of the formatter
- */
-JSONFormatter = function (container, options, json) {
- // check availability of JSON parser (not available in IE7 and older)
- if (!JSON) {
- throw new Error('Your browser does not support JSON. \n\n' +
- 'Please install the newest version of your browser.\n' +
- '(all modern browsers support JSON).');
- }
-
- this.container = container;
- this.indentation = 4; // number of spaces
-
- this.width = container.clientWidth;
- this.height = container.clientHeight;
-
- this.frame = document.createElement('div');
- this.frame.className = "jsoneditor-frame";
- this.frame.onclick = function (event) {
- // prevent default submit action when JSONFormatter is located inside a form
- JSONEditor.Events.preventDefault(event);
- };
-
- // create menu
- this.menu = document.createElement('div');
- this.menu.className = 'jsoneditor-menu';
- this.frame.appendChild(this.menu);
-
- // create format button
- var buttonFormat = document.createElement('button');
- //buttonFormat.innerHTML = 'Format';
- buttonFormat.className = 'jsoneditor-menu jsoneditor-format';
- buttonFormat.title = 'Format JSON data, with proper indentation and line feeds';
- //buttonFormat.className = 'jsoneditor-button';
- this.menu.appendChild(buttonFormat);
-
- // create compact button
- var buttonCompact = document.createElement('button');
- //buttonCompact.innerHTML = 'Compact';
- buttonCompact.className = 'jsoneditor-menu jsoneditor-compact';
- buttonCompact.title = 'Compact JSON data, remove all whitespaces';
- //buttonCompact.className = 'jsoneditor-button';
- this.menu.appendChild(buttonCompact);
-
- this.content = document.createElement('div');
- this.content.className = 'jsonformatter-content';
- this.frame.appendChild(this.content);
-
- this.textarea = document.createElement('textarea');
- this.textarea.className = "jsonformatter-textarea";
- this.textarea.spellcheck = false;
- this.content.appendChild(this.textarea);
-
- var textarea = this.textarea;
-
- // read the options
- if (options) {
- if (options.change) {
- // register on change event
- if (this.textarea.oninput === null) {
- this.textarea.oninput = function () {
- options.change();
- }
- }
- else {
- // oninput is undefined. For IE8-
- this.textarea.onchange = function () {
- options.change();
- }
- }
- }
- if (options.indentation) {
- this.indentation = Number(options.indentation);
- }
- }
-
- var me = this;
- buttonFormat.onclick = function () {
- try {
- var json = JSONEditor.parse(textarea.value);
- textarea.value = JSON.stringify(json, null, me.indentation);
- }
- catch (err) {
- me.onError(err);
- }
- };
- buttonCompact.onclick = function () {
- try {
- var json = JSONEditor.parse(textarea.value);
- textarea.value = JSON.stringify(json);
- }
- catch (err) {
- me.onError(err);
- }
- };
-
- this.container.appendChild(this.frame);
-
- // load initial json object or string
- if (typeof(json) == 'string') {
- this.setText(json);
- }
- else {
- this.set(json);
- }
-};
-
-/**
- * This method is executed on error.
- * It can be overwritten for each instance of the JSONFormatter
- * @param {String} err
- */
-JSONFormatter.prototype.onError = function(err) {
- // action should be implemented for the instance
-};
-
-/**
- * Set json data in the formatter
- * @param {Object} json
- */
-JSONFormatter.prototype.set = function(json) {
- this.textarea.value = JSON.stringify(json, null, this.indentation);
-};
-
-/**
- * Get json data from the formatter
- * @return {Object} json
- */
-JSONFormatter.prototype.get = function() {
- return JSONEditor.parse(this.textarea.value);
-};
-
-/**
- * Get the text contents of the JSONFormatter
- * @return {String} text
- */
-JSONFormatter.prototype.getText = function() {
- return this.textarea.value;
-};
-
-/**
- * Set the text contents of the JSONFormatter
- * @param {String} text
- */
-JSONFormatter.prototype.setText = function(text) {
- this.textarea.value = text;
-};
-
-/**
- * @constructor JSONEditor.SearchBox
- * Create a search box in given HTML container
- * @param {JSONEditor} editor The JSON Editor to attach to
- * @param {Element} container HTML container element of where to create the
- * search box
- */
-JSONEditor.SearchBox = function(editor, container) {
- var searchBox = this;
-
- this.editor = editor;
- this.timeout = undefined;
- this.delay = 200; // ms
- this.lastText = undefined;
-
- this.dom = {};
- this.dom.container = container;
-
- var table = document.createElement('table');
- this.dom.table = table;
- table.className = 'jsoneditor-search';
- container.appendChild(table);
- var tbody = document.createElement('tbody');
- this.dom.tbody = tbody;
- table.appendChild(tbody);
- var tr = document.createElement('tr');
- tbody.appendChild(tr);
-
- var td = document.createElement('td');
- td.className = 'jsoneditor-search';
- tr.appendChild(td);
- var results = document.createElement('div');
- this.dom.results = results;
- results.className = 'jsoneditor-search-results';
- td.appendChild(results);
-
- td = document.createElement('td');
- td.className = 'jsoneditor-search';
- tr.appendChild(td);
- var divInput = document.createElement('div');
- this.dom.input = divInput;
- divInput.className = 'jsoneditor-search';
- divInput.title = 'Search fields and values';
- td.appendChild(divInput);
-
- // table to contain the text input and search button
- var tableInput = document.createElement('table');
- tableInput.className = 'jsoneditor-search-input';
- divInput.appendChild(tableInput);
- var tbodySearch = document.createElement('tbody');
- tableInput.appendChild(tbodySearch);
- tr = document.createElement('tr');
- tbodySearch.appendChild(tr);
-
- var refreshSearch = document.createElement('button');
- refreshSearch.className = 'jsoneditor-search-refresh';
- td = document.createElement('td');
- td.appendChild(refreshSearch);
- tr.appendChild(td);
-
- var search = document.createElement('input');
- this.dom.search = search;
- search.className = 'jsoneditor-search';
- search.oninput = function (event) {
- searchBox.onDelayedSearch(event);
- };
- search.onchange = function (event) { // For IE 8
- searchBox.onSearch(event);
- };
- search.onkeydown = function (event) {
- searchBox.onKeyDown(event);
- };
- search.onkeyup = function (event) {
- searchBox.onKeyUp(event);
- };
- refreshSearch.onclick = function (event) {
- search.select();
- };
-
- // TODO: ESC in FF restores the last input, is a FF bug, https://bugzilla.mozilla.org/show_bug.cgi?id=598819
- td = document.createElement('td');
- td.appendChild(search);
- tr.appendChild(td);
-
- var searchNext = document.createElement('button');
- searchNext.title = 'Next result (Enter)';
- searchNext.className = 'jsoneditor-search-next';
- searchNext.onclick = function () {
- searchBox.next();
- };
- td = document.createElement('td');
- td.appendChild(searchNext);
- tr.appendChild(td);
-
- var searchPrevious = document.createElement('button');
- searchPrevious.title = 'Previous result (Shift+Enter)';
- searchPrevious.className = 'jsoneditor-search-previous';
- searchPrevious.onclick = function () {
- searchBox.previous();
- };
- td = document.createElement('td');
- td.appendChild(searchPrevious);
- tr.appendChild(td);
-
-};
-
-/**
- * Go to the next search result
- */
-JSONEditor.SearchBox.prototype.next = function() {
- if (this.results != undefined) {
- var index = (this.resultIndex != undefined) ? this.resultIndex + 1 : 0;
- if (index > this.results.length - 1) {
- index = 0;
- }
- this.setActiveResult(index);
- }
-};
-
-/**
- * Go to the prevous search result
- */
-JSONEditor.SearchBox.prototype.previous = function() {
- if (this.results != undefined) {
- var max = this.results.length - 1;
- var index = (this.resultIndex != undefined) ? this.resultIndex - 1 : max;
- if (index < 0) {
- index = max;
- }
- this.setActiveResult(index);
- }
-};
-
-/**
- * Set new value for the current active result
- * @param {Number} index
- */
-JSONEditor.SearchBox.prototype.setActiveResult = function(index) {
- // de-activate current active result
- if (this.activeResult) {
- var prevNode = this.activeResult.node;
- var prevElem = this.activeResult.elem;
- if (prevElem == 'field') {
- delete prevNode.searchFieldActive;
- }
- else {
- delete prevNode.searchValueActive;
- }
- prevNode.updateDom();
- }
-
- if (!this.results || !this.results[index]) {
- // out of range, set to undefined
- this.resultIndex = undefined;
- this.activeResult = undefined;
- return;
- }
-
- this.resultIndex = index;
-
- // set new node active
- var node = this.results[this.resultIndex].node;
- var elem = this.results[this.resultIndex].elem;
- if (elem == 'field') {
- node.searchFieldActive = true;
- }
- else {
- node.searchValueActive = true;
- }
- this.activeResult = this.results[this.resultIndex];
- node.updateDom();
-
- node.scrollTo();
-};
-
-/**
- * Set the focus to the currently active result. If there is no currently
- * active result, the next search result will get focus
- */
-JSONEditor.SearchBox.prototype.focusActiveResult = function() {
- if (!this.activeResult) {
- this.next();
- }
-
- if (this.activeResult) {
- this.activeResult.node.focus(this.activeResult.elem);
- }
-};
-
-/**
- * Cancel any running onDelayedSearch.
- */
-JSONEditor.SearchBox.prototype.clearDelay = function() {
- if (this.timeout != undefined) {
- clearTimeout(this.timeout);
- delete this.timeout;
- }
-};
-
-/**
- * Start a timer to execute a search after a short delay.
- * Used for reducing the number of searches while typing.
- * @param {Event} event
- */
-JSONEditor.SearchBox.prototype.onDelayedSearch = function (event) {
- // execute the search after a short delay (reduces the number of
- // search actions while typing in the search text box)
- this.clearDelay();
- var searchBox = this;
- this.timeout = setTimeout(function (event) {
- searchBox.onSearch(event);
- },
- this.delay);
-};
-
-/**
- * Handle onSearch event
- * @param {Event} event
- * @param {boolean} [forceSearch] If true, search will be executed again even
- * when the search text is not changed.
- * Default is false.
- */
-JSONEditor.SearchBox.prototype.onSearch = function (event, forceSearch) {
- this.clearDelay();
-
- var value = this.dom.search.value;
- var text = (value.length > 0) ? value : undefined;
- if (text != this.lastText || forceSearch) {
- // only search again when changed
- this.lastText = text;
- this.results = this.editor.search(text);
- this.setActiveResult(undefined);
-
- // display search results
- if (text != undefined) {
- var resultCount = this.results.length;
- switch (resultCount) {
- case 0: this.dom.results.innerHTML = 'no&nbsp;results'; break;
- case 1: this.dom.results.innerHTML = '1&nbsp;result'; break;
- default: this.dom.results.innerHTML = resultCount + '&nbsp;results'; break;
- }
- }
- else {
- this.dom.results.innerHTML = '';
- }
- }
-};
-
-/**
- * Handle onKeyDown event in the input box
- * @param {Event} event
- */
-JSONEditor.SearchBox.prototype.onKeyDown = function (event) {
- event = event || window.event;
- var keynum = event.which || event.keyCode;
- if (keynum == 27) { // ESC
- this.dom.search.value = ''; // clear search
- this.onSearch(event);
- JSONEditor.Events.preventDefault(event);
- JSONEditor.Events.stopPropagation(event);
- }
- else if (keynum == 13) { // Enter
- if (event.ctrlKey) {
- // force to search again
- this.onSearch(event, true);
- }
- else if (event.shiftKey) {
- // move to the previous search result
- this.previous();
- }
- else {
- // move to the next search result
- this.next();
- }
- JSONEditor.Events.preventDefault(event);
- JSONEditor.Events.stopPropagation(event);
- }
-};
-
-/**
- * Handle onKeyUp event in the input box
- * @param {Event} event
- */
-JSONEditor.SearchBox.prototype.onKeyUp = function (event) {
- event = event || window.event;
- var keynum = event.which || event.keyCode;
- if (keynum != 27 && keynum != 13) { // !ESC and !Enter
- this.onDelayedSearch(event); // For IE 8
- }
-};
-
-// create namespace for event methods
-JSONEditor.Events = {};
-
-/**
- * Add and event listener. Works for all browsers
- * @param {Element} element An html element
- * @param {string} action The action, for example "click",
- * without the prefix "on"
- * @param {function} listener The callback function to be executed
- * @param {boolean} useCapture
- * @return {function} the created event listener
- */
-JSONEditor.Events.addEventListener = function (element, action, listener, useCapture) {
- if (element.addEventListener) {
- if (useCapture === undefined)
- useCapture = false;
-
- if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
- action = "DOMMouseScroll"; // For Firefox
- }
-
- element.addEventListener(action, listener, useCapture);
- return listener;
- } else {
- // IE browsers
- var f = function () {
- return listener.call(element, window.event);
- };
- element.attachEvent("on" + action, f);
- return f;
- }
-};
-
-/**
- * Remove an event listener from an element
- * @param {Element} element An html dom element
- * @param {string} action The name of the event, for example "mousedown"
- * @param {function} listener The listener function
- * @param {boolean} useCapture
- */
-JSONEditor.Events.removeEventListener = function(element, action, listener, useCapture) {
- if (element.removeEventListener) {
- // non-IE browsers
- if (useCapture === undefined)
- useCapture = false;
-
- if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
- action = "DOMMouseScroll"; // For Firefox
- }
-
- element.removeEventListener(action, listener, useCapture);
- } else {
- // IE browsers
- element.detachEvent("on" + action, listener);
- }
-};
-
-
-/**
- * Stop event propagation
- * @param {Event} event
- */
-JSONEditor.Events.stopPropagation = function (event) {
- if (!event)
- event = window.event;
-
- if (event.stopPropagation) {
- event.stopPropagation(); // non-IE browsers
- }
- else {
- event.cancelBubble = true; // IE browsers
- }
-};
-
-
-/**
- * Cancels the event if it is cancelable, without stopping further propagation of the event.
- * @param {Event} event
- */
-JSONEditor.Events.preventDefault = function (event) {
- if (!event)
- event = window.event;
-
- if (event.preventDefault) {
- event.preventDefault(); // non-IE browsers
- }
- else {
- event.returnValue = false; // IE browsers
- }
-};
-
-
-
-/**
- * Retrieve the absolute left value of a DOM element
- * @param {Element} elem A dom element, for example a div
- * @return {Number} left The absolute left position of this element
- * in the browser page.
- */
-JSONEditor.getAbsoluteLeft = function (elem) {
- var left = 0;
- var body = document.body;
- while (elem != null && elem != body) {
- left += elem.offsetLeft;
- left -= elem.scrollLeft;
- elem = elem.offsetParent;
- }
- return left;
-};
-
-/**
- * Retrieve the absolute top value of a DOM element
- * @param {Element} elem A dom element, for example a div
- * @return {Number} top The absolute top position of this element
- * in the browser page.
- */
-JSONEditor.getAbsoluteTop = function (elem) {
- var top = 0;
- var body = document.body;
- while (elem != null && elem != body) {
- top += elem.offsetTop;
- top -= elem.scrollTop;
- elem = elem.offsetParent;
- }
- return top;
-};
-
-/**
- * add a className to the given elements style
- * @param {Element} elem
- * @param {String} className
- */
-JSONEditor.addClassName = function(elem, className) {
- var classes = elem.className.split(' ');
- if (classes.indexOf(className) == -1) {
- classes.push(className); // add the class to the array
- elem.className = classes.join(' ');
- }
-};
-
-/**
- * add a className to the given elements style
- * @param {Element} elem
- * @param {String} className
- */
-JSONEditor.removeClassName = function(elem, className) {
- var classes = elem.className.split(' ');
- var index = classes.indexOf(className);
- if (index != -1) {
- classes.splice(index, 1); // remove the class from the array
- elem.className = classes.join(' ');
- }
-};
-
-/**
- * Strip the formatting from the contents of a div
- * the formatting from the div itself is not stripped, only from its childs.
- * @param {Element} divElement
- */
-JSONEditor.stripFormatting = function (divElement) {
- var childs = divElement.childNodes;
- for (var i = 0, iMax = childs.length; i < iMax; i++) {
- var child = childs[i];
-
- // remove the style
- if (child.style) {
- // TODO: test if child.attributes does contain style
- child.removeAttribute('style');
- }
-
- // remove all attributes
- var attributes = child.attributes;
- if (attributes) {
- for (var j = attributes.length - 1; j >= 0; j--) {
- var attribute = attributes[j];
- if (attribute.specified == true) {
- child.removeAttribute(attribute.name);
- }
- }
- }
-
- // recursively strip childs
- JSONEditor.stripFormatting(child);
- }
-};
-
-/**
- * Set focus to the end of an editable div
- * code from Nico Burns
- * http://stackoverflow.com/users/140293/nico-burns
- * http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity
- * @param {Element} contentEditableElement
- */
-JSONEditor.setEndOfContentEditable = function (contentEditableElement) {
- var range, selection;
- if(document.createRange) {//Firefox, Chrome, Opera, Safari, IE 9+
- range = document.createRange();//Create a range (a range is a like the selection but invisible)
- range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
- range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
- selection = window.getSelection();//get the selection object (allows you to change selection)
- selection.removeAllRanges();//remove any selections already made
- selection.addRange(range);//make the range you have just created the visible selection
- }
- else if(document.selection) {//IE 8 and lower
- range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
- range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
- range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
- range.select();//Select the range (make it the visible selection
- }
-};
-
-/**
- * Get the inner text of an HTML element (for example a div element)
- * @param {Element} element
- * @param {Object} [buffer]
- * @return {String} innerText
- */
-JSONEditor.getInnerText = function (element, buffer) {
- var first = (buffer == undefined);
- if (first) {
- buffer = {
- 'text': '',
- 'flush': function () {
- var text = this.text;
- this.text = '';
- return text;
- },
- 'set': function (text) {
- this.text = text;
- }
- };
- }
-
- // text node
- if (element.nodeValue) {
- return buffer.flush() + element.nodeValue;
- }
-
- // divs or other HTML elements
- if (element.hasChildNodes()) {
- var childNodes = element.childNodes;
- var innerText = '';
-
- for (var i = 0, iMax = childNodes.length; i < iMax; i++) {
- var child = childNodes[i];
-
- if (child.nodeName == 'DIV' || child.nodeName == 'P') {
- var prevChild = childNodes[i - 1];
- var prevName = prevChild ? prevChild.nodeName : undefined;
- if (prevName && prevName != 'DIV' && prevName != 'P' && prevName != 'BR') {
- innerText += '\n';
- buffer.flush();
- }
- innerText += JSONEditor.getInnerText(child, buffer);
- buffer.set('\n');
- }
- else if (child.nodeName == 'BR') {
- innerText += buffer.flush();
- buffer.set('\n');
- }
- else {
- innerText += JSONEditor.getInnerText(child, buffer);
- }
- }
-
- return innerText;
- }
- else {
- if (element.nodeName == 'P' && JSONEditor.getInternetExplorerVersion() != -1) {
- // On Internet Explorer, a <p> with hasChildNodes()==false is
- // rendered with a new line. Note that a <p> with
- // hasChildNodes()==true is rendered without a new line
- // Other browsers always ensure there is a <br> inside the <p>,
- // and if not, the <p> does not render a new line
- return buffer.flush();
- }
- }
-
- // br or unknown
- return '';
-};
-
-/**
- * Returns the version of Internet Explorer or a -1
- * (indicating the use of another browser).
- * Source: http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
- * @return {Number} Internet Explorer version, or -1 in case of an other browser
- */
-JSONEditor._ieVersion = undefined;
-JSONEditor.getInternetExplorerVersion = function() {
- if (JSONEditor._ieVersion == undefined) {
- var rv = -1; // Return value assumes failure.
- if (navigator.appName == 'Microsoft Internet Explorer')
- {
- var ua = navigator.userAgent;
- var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
- if (re.exec(ua) != null) {
- rv = parseFloat( RegExp.$1 );
- }
- }
-
- JSONEditor._ieVersion = rv;
- }
-
- return JSONEditor._ieVersion;
-};
-
-JSONEditor.ieVersion = JSONEditor.getInternetExplorerVersion();
-
-/**
- * Parse JSON using the parser built-in in the browser.
- * On exception, the jsonString is validated and a detailed error is thrown.
- * @param {String} jsonString
- */
-JSONEditor.parse = function (jsonString) {
- try {
- return JSON.parse(jsonString);
- }
- catch (err) {
- // get a detailed error message using validate
- var message = JSONEditor.validate(jsonString) || err;
- throw new Error(message);
- }
-};
-
-/**
- * Validate a string containing a JSON object
- * This method uses JSONLint to validate the String. If JSONLint is not
- * available, the built-in JSON parser of the browser is used.
- * @param {String} jsonString String with an (invalid) JSON object
- * @return {String | undefined} Returns undefined when the string is valid JSON,
- * returns a string with an error message when
- * the data is invalid
- */
-JSONEditor.validate = function (jsonString) {
- var message = undefined;
-
- try {
- if (window.jsonlint) {
- window.jsonlint.parse(jsonString);
- }
- else {
- JSON.parse(jsonString);
- }
- }
- catch (err) {
- message = '<pre class="error">' + err.toString() + '</pre>';
- if (window.jsonlint) {
- message +=
- '<a class="error" href="http://zaach.github.com/jsonlint/" target="_blank">' +
- 'validated by jsonlint' +
- '</a>';
- }
- }
-
- return message;
-};
-
diff --git a/data/libs/select2/select2.js b/data/libs/select2/select2.js
deleted file mode 100644
index 3b5e8e280..000000000
--- a/data/libs/select2/select2.js
+++ /dev/null
@@ -1,3255 +0,0 @@
-/*
-Copyright 2012 Igor Vaynberg
-
-Version: 3.4.5 Timestamp: Mon Nov 4 08:22:42 PST 2013
-
-This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
-General Public License version 2 (the "GPL License"). You may choose either license to govern your
-use of this software only upon the condition that you accept all of the terms of either the Apache
-License or the GPL License.
-
-You may obtain a copy of the Apache License and the GPL License at:
-
- http://www.apache.org/licenses/LICENSE-2.0
- http://www.gnu.org/licenses/gpl-2.0.html
-
-Unless required by applicable law or agreed to in writing, software distributed under the
-Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
-the specific language governing permissions and limitations under the Apache License and the GPL License.
-*/
-(function ($) {
- if(typeof $.fn.each2 == "undefined") {
- $.extend($.fn, {
- /*
- * 4-10 times faster .each replacement
- * use it carefully, as it overrides jQuery context of element on each iteration
- */
- each2 : function (c) {
- var j = $([0]), i = -1, l = this.length;
- while (
- ++i < l
- && (j.context = j[0] = this[i])
- && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
- );
- return this;
- }
- });
- }
-})(jQuery);
-
-(function ($, undefined) {
- "use strict";
- /*global document, window, jQuery, console */
-
- if (window.Select2 !== undefined) {
- return;
- }
-
- var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
- lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
-
- KEY = {
- TAB: 9,
- ENTER: 13,
- ESC: 27,
- SPACE: 32,
- LEFT: 37,
- UP: 38,
- RIGHT: 39,
- DOWN: 40,
- SHIFT: 16,
- CTRL: 17,
- ALT: 18,
- PAGE_UP: 33,
- PAGE_DOWN: 34,
- HOME: 36,
- END: 35,
- BACKSPACE: 8,
- DELETE: 46,
- isArrow: function (k) {
- k = k.which ? k.which : k;
- switch (k) {
- case KEY.LEFT:
- case KEY.RIGHT:
- case KEY.UP:
- case KEY.DOWN:
- return true;
- }
- return false;
- },
- isControl: function (e) {
- var k = e.which;
- switch (k) {
- case KEY.SHIFT:
- case KEY.CTRL:
- case KEY.ALT:
- return true;
- }
-
- if (e.metaKey) return true;
-
- return false;
- },
- isFunctionKey: function (k) {
- k = k.which ? k.which : k;
- return k >= 112 && k <= 123;
- }
- },
- MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",
-
- DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"};
-
- $document = $(document);
-
- nextUid=(function() { var counter=1; return function() { return counter++; }; }());
-
-
- function stripDiacritics(str) {
- var ret, i, l, c;
-
- if (!str || str.length < 1) return str;
-
- ret = "";
- for (i = 0, l = str.length; i < l; i++) {
- c = str.charAt(i);
- ret += DIACRITICS[c] || c;
- }
- return ret;
- }
-
- function indexOf(value, array) {
- var i = 0, l = array.length;
- for (; i < l; i = i + 1) {
- if (equal(value, array[i])) return i;
- }
- return -1;
- }
-
- function measureScrollbar () {
- var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
- $template.appendTo('body');
-
- var dim = {
- width: $template.width() - $template[0].clientWidth,
- height: $template.height() - $template[0].clientHeight
- };
- $template.remove();
-
- return dim;
- }
-
- /**
- * Compares equality of a and b
- * @param a
- * @param b
- */
- function equal(a, b) {
- if (a === b) return true;
- if (a === undefined || b === undefined) return false;
- if (a === null || b === null) return false;
- // Check whether 'a' or 'b' is a string (primitive or object).
- // The concatenation of an empty string (+'') converts its argument to a string's primitive.
- if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
- if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
- return false;
- }
-
- /**
- * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
- * strings
- * @param string
- * @param separator
- */
- function splitVal(string, separator) {
- var val, i, l;
- if (string === null || string.length < 1) return [];
- val = string.split(separator);
- for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
- return val;
- }
-
- function getSideBorderPadding(element) {
- return element.outerWidth(false) - element.width();
- }
-
- function installKeyUpChangeEvent(element) {
- var key="keyup-change-value";
- element.on("keydown", function () {
- if ($.data(element, key) === undefined) {
- $.data(element, key, element.val());
- }
- });
- element.on("keyup", function () {
- var val= $.data(element, key);
- if (val !== undefined && element.val() !== val) {
- $.removeData(element, key);
- element.trigger("keyup-change");
- }
- });
- }
-
- $document.on("mousemove", function (e) {
- lastMousePosition.x = e.pageX;
- lastMousePosition.y = e.pageY;
- });
-
- /**
- * filters mouse events so an event is fired only if the mouse moved.
- *
- * filters out mouse events that occur when mouse is stationary but
- * the elements under the pointer are scrolled.
- */
- function installFilteredMouseMove(element) {
- element.on("mousemove", function (e) {
- var lastpos = lastMousePosition;
- if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
- $(e.target).trigger("mousemove-filtered", e);
- }
- });
- }
-
- /**
- * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
- * within the last quietMillis milliseconds.
- *
- * @param quietMillis number of milliseconds to wait before invoking fn
- * @param fn function to be debounced
- * @param ctx object to be used as this reference within fn
- * @return debounced version of fn
- */
- function debounce(quietMillis, fn, ctx) {
- ctx = ctx || undefined;
- var timeout;
- return function () {
- var args = arguments;
- window.clearTimeout(timeout);
- timeout = window.setTimeout(function() {
- fn.apply(ctx, args);
- }, quietMillis);
- };
- }
-
- /**
- * A simple implementation of a thunk
- * @param formula function used to lazily initialize the thunk
- * @return {Function}
- */
- function thunk(formula) {
- var evaluated = false,
- value;
- return function() {
- if (evaluated === false) { value = formula(); evaluated = true; }
- return value;
- };
- };
-
- function installDebouncedScroll(threshold, element) {
- var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
- element.on("scroll", function (e) {
- if (indexOf(e.target, element.get()) >= 0) notify(e);
- });
- }
-
- function focus($el) {
- if ($el[0] === document.activeElement) return;
-
- /* set the focus in a 0 timeout - that way the focus is set after the processing
- of the current event has finished - which seems like the only reliable way
- to set focus */
- window.setTimeout(function() {
- var el=$el[0], pos=$el.val().length, range;
-
- $el.focus();
-
- /* make sure el received focus so we do not error out when trying to manipulate the caret.
- sometimes modals or others listeners may steal it after its set */
- if ($el.is(":visible") && el === document.activeElement) {
-
- /* after the focus is set move the caret to the end, necessary when we val()
- just before setting focus */
- if(el.setSelectionRange)
- {
- el.setSelectionRange(pos, pos);
- }
- else if (el.createTextRange) {
- range = el.createTextRange();
- range.collapse(false);
- range.select();
- }
- }
- }, 0);
- }
-
- function getCursorInfo(el) {
- el = $(el)[0];
- var offset = 0;
- var length = 0;
- if ('selectionStart' in el) {
- offset = el.selectionStart;
- length = el.selectionEnd - offset;
- } else if ('selection' in document) {
- el.focus();
- var sel = document.selection.createRange();
- length = document.selection.createRange().text.length;
- sel.moveStart('character', -el.value.length);
- offset = sel.text.length - length;
- }
- return { offset: offset, length: length };
- }
-
- function killEvent(event) {
- event.preventDefault();
- event.stopPropagation();
- }
- function killEventImmediately(event) {
- event.preventDefault();
- event.stopImmediatePropagation();
- }
-
- function measureTextWidth(e) {
- if (!sizer){
- var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
- sizer = $(document.createElement("div")).css({
- position: "absolute",
- left: "-10000px",
- top: "-10000px",
- display: "none",
- fontSize: style.fontSize,
- fontFamily: style.fontFamily,
- fontStyle: style.fontStyle,
- fontWeight: style.fontWeight,
- letterSpacing: style.letterSpacing,
- textTransform: style.textTransform,
- whiteSpace: "nowrap"
- });
- sizer.attr("class","select2-sizer");
- $("body").append(sizer);
- }
- sizer.text(e.val());
- return sizer.width();
- }
-
- function syncCssClasses(dest, src, adapter) {
- var classes, replacements = [], adapted;
-
- classes = dest.attr("class");
- if (classes) {
- classes = '' + classes; // for IE which returns object
- $(classes.split(" ")).each2(function() {
- if (this.indexOf("select2-") === 0) {
- replacements.push(this);
- }
- });
- }
- classes = src.attr("class");
- if (classes) {
- classes = '' + classes; // for IE which returns object
- $(classes.split(" ")).each2(function() {
- if (this.indexOf("select2-") !== 0) {
- adapted = adapter(this);
- if (adapted) {
- replacements.push(adapted);
- }
- }
- });
- }
- dest.attr("class", replacements.join(" "));
- }
-
-
- function markMatch(text, term, markup, escapeMarkup) {
- var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
- tl=term.length;
-
- if (match<0) {
- markup.push(escapeMarkup(text));
- return;
- }
-
- markup.push(escapeMarkup(text.substring(0, match)));
- markup.push("<span class='select2-match'>");
- markup.push(escapeMarkup(text.substring(match, match + tl)));
- markup.push("</span>");
- markup.push(escapeMarkup(text.substring(match + tl, text.length)));
- }
-
- function defaultEscapeMarkup(markup) {
- var replace_map = {
- '\\': '&#92;',
- '&': '&amp;',
- '<': '&lt;',
- '>': '&gt;',
- '"': '&quot;',
- "'": '&#39;',
- "/": '&#47;'
- };
-
- return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
- return replace_map[match];
- });
- }
-
- /**
- * Produces an ajax-based query function
- *
- * @param options object containing configuration paramters
- * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
- * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
- * @param options.url url for the data
- * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
- * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
- * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
- * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
- * The expected format is an object containing the following keys:
- * results array of objects that will be used as choices
- * more (optional) boolean indicating whether there are more results available
- * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
- */
- function ajax(options) {
- var timeout, // current scheduled but not yet executed request
- handler = null,
- quietMillis = options.quietMillis || 100,
- ajaxUrl = options.url,
- self = this;
-
- return function (query) {
- window.clearTimeout(timeout);
- timeout = window.setTimeout(function () {
- var data = options.data, // ajax data function
- url = ajaxUrl, // ajax url string or function
- transport = options.transport || $.fn.select2.ajaxDefaults.transport,
- // deprecated - to be removed in 4.0 - use params instead
- deprecated = {
- type: options.type || 'GET', // set type of request (GET or POST)
- cache: options.cache || false,
- jsonpCallback: options.jsonpCallback||undefined,
- dataType: options.dataType||"json"
- },
- params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
-
- data = data ? data.call(self, query.term, query.page, query.context) : null;
- url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
-
- if (handler) { handler.abort(); }
-
- if (options.params) {
- if ($.isFunction(options.params)) {
- $.extend(params, options.params.call(self));
- } else {
- $.extend(params, options.params);
- }
- }
-
- $.extend(params, {
- url: url,
- dataType: options.dataType,
- data: data,
- success: function (data) {
- // TODO - replace query.page with query so users have access to term, page, etc.
- var results = options.results(data, query.page);
- query.callback(results);
- }
- });
- handler = transport.call(self, params);
- }, quietMillis);
- };
- }
-
- /**
- * Produces a query function that works with a local array
- *
- * @param options object containing configuration parameters. The options parameter can either be an array or an
- * object.
- *
- * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
- *
- * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
- * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
- * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
- * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
- * the text.
- */
- function local(options) {
- var data = options, // data elements
- dataText,
- tmp,
- text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
-
- if ($.isArray(data)) {
- tmp = data;
- data = { results: tmp };
- }
-
- if ($.isFunction(data) === false) {
- tmp = data;
- data = function() { return tmp; };
- }
-
- var dataItem = data();
- if (dataItem.text) {
- text = dataItem.text;
- // if text is not a function we assume it to be a key name
- if (!$.isFunction(text)) {
- dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
- text = function (item) { return item[dataText]; };
- }
- }
-
- return function (query) {
- var t = query.term, filtered = { results: [] }, process;
- if (t === "") {
- query.callback(data());
- return;
- }
-
- process = function(datum, collection) {
- var group, attr;
- datum = datum[0];
- if (datum.children) {
- group = {};
- for (attr in datum) {
- if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
- }
- group.children=[];
- $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
- if (group.children.length || query.matcher(t, text(group), datum)) {
- collection.push(group);
- }
- } else {
- if (query.matcher(t, text(datum), datum)) {
- collection.push(datum);
- }
- }
- };
-
- $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
- query.callback(filtered);
- };
- }
-
- // TODO javadoc
- function tags(data) {
- var isFunc = $.isFunction(data);
- return function (query) {
- var t = query.term, filtered = {results: []};
- $(isFunc ? data() : data).each(function () {
- var isObject = this.text !== undefined,
- text = isObject ? this.text : this;
- if (t === "" || query.matcher(t, text)) {
- filtered.results.push(isObject ? this : {id: this, text: this});
- }
- });
- query.callback(filtered);
- };
- }
-
- /**
- * Checks if the formatter function should be used.
- *
- * Throws an error if it is not a function. Returns true if it should be used,
- * false if no formatting should be performed.
- *
- * @param formatter
- */
- function checkFormatter(formatter, formatterName) {
- if ($.isFunction(formatter)) return true;
- if (!formatter) return false;
- throw new Error(formatterName +" must be a function or a falsy value");
- }
-
- function evaluate(val) {
- return $.isFunction(val) ? val() : val;
- }
-
- function countResults(results) {
- var count = 0;
- $.each(results, function(i, item) {
- if (item.children) {
- count += countResults(item.children);
- } else {
- count++;
- }
- });
- return count;
- }
-
- /**
- * Default tokenizer. This function uses breaks the input on substring match of any string from the
- * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
- * two options have to be defined in order for the tokenizer to work.
- *
- * @param input text user has typed so far or pasted into the search field
- * @param selection currently selected choices
- * @param selectCallback function(choice) callback tho add the choice to selection
- * @param opts select2's opts
- * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
- */
- function defaultTokenizer(input, selection, selectCallback, opts) {
- var original = input, // store the original so we can compare and know if we need to tell the search to update its text
- dupe = false, // check for whether a token we extracted represents a duplicate selected choice
- token, // token
- index, // position at which the separator was found
- i, l, // looping variables
- separator; // the matched separator
-
- if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
-
- while (true) {
- index = -1;
-
- for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
- separator = opts.tokenSeparators[i];
- index = input.indexOf(separator);
- if (index >= 0) break;
- }
-
- if (index < 0) break; // did not find any token separator in the input string, bail
-
- token = input.substring(0, index);
- input = input.substring(index + separator.length);
-
- if (token.length > 0) {
- token = opts.createSearchChoice.call(this, token, selection);
- if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
- dupe = false;
- for (i = 0, l = selection.length; i < l; i++) {
- if (equal(opts.id(token), opts.id(selection[i]))) {
- dupe = true; break;
- }
- }
-
- if (!dupe) selectCallback(token);
- }
- }
- }
-
- if (original!==input) return input;
- }
-
- /**
- * Creates a new class
- *
- * @param superClass
- * @param methods
- */
- function clazz(SuperClass, methods) {
- var constructor = function () {};
- constructor.prototype = new SuperClass;
- constructor.prototype.constructor = constructor;
- constructor.prototype.parent = SuperClass.prototype;
- constructor.prototype = $.extend(constructor.prototype, methods);
- return constructor;
- }
-
- AbstractSelect2 = clazz(Object, {
-
- // abstract
- bind: function (func) {
- var self = this;
- return function () {
- func.apply(self, arguments);
- };
- },
-
- // abstract
- init: function (opts) {
- var results, search, resultsSelector = ".select2-results";
-
- // prepare options
- this.opts = opts = this.prepareOpts(opts);
-
- this.id=opts.id;
-
- // destroy if called on an existing component
- if (opts.element.data("select2") !== undefined &&
- opts.element.data("select2") !== null) {
- opts.element.data("select2").destroy();
- }
-
- this.container = this.createContainer();
-
- this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
- this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
- this.container.attr("id", this.containerId);
-
- // cache the body so future lookups are cheap
- this.body = thunk(function() { return opts.element.closest("body"); });
-
- syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
-
- this.container.attr("style", opts.element.attr("style"));
- this.container.css(evaluate(opts.containerCss));
- this.container.addClass(evaluate(opts.containerCssClass));
-
- this.elementTabIndex = this.opts.element.attr("tabindex");
-
- // swap container for the element
- this.opts.element
- .data("select2", this)
- .attr("tabindex", "-1")
- .before(this.container)
- .on("click.select2", killEvent); // do not leak click events
-
- this.container.data("select2", this);
-
- this.dropdown = this.container.find(".select2-drop");
-
- syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
-
- this.dropdown.addClass(evaluate(opts.dropdownCssClass));
- this.dropdown.data("select2", this);
- this.dropdown.on("click", killEvent);
-
- this.results = results = this.container.find(resultsSelector);
- this.search = search = this.container.find("input.select2-input");
-
- this.queryCount = 0;
- this.resultsPage = 0;
- this.context = null;
-
- // initialize the container
- this.initContainer();
-
- this.container.on("click", killEvent);
-
- installFilteredMouseMove(this.results);
- this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
-
- installDebouncedScroll(80, this.results);
- this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
-
- // do not propagate change event from the search field out of the component
- $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
- $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
-
- // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
- if ($.fn.mousewheel) {
- results.mousewheel(function (e, delta, deltaX, deltaY) {
- var top = results.scrollTop();
- if (deltaY > 0 && top - deltaY <= 0) {
- results.scrollTop(0);
- killEvent(e);
- } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
- results.scrollTop(results.get(0).scrollHeight - results.height());
- killEvent(e);
- }
- });
- }
-
- installKeyUpChangeEvent(search);
- search.on("keyup-change input paste", this.bind(this.updateResults));
- search.on("focus", function () { search.addClass("select2-focused"); });
- search.on("blur", function () { search.removeClass("select2-focused");});
-
- this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
- if ($(e.target).closest(".select2-result-selectable").length > 0) {
- this.highlightUnderEvent(e);
- this.selectHighlighted(e);
- }
- }));
-
- // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
- // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
- // dom it will trigger the popup close, which is not what we want
- this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
-
- if ($.isFunction(this.opts.initSelection)) {
- // initialize selection based on the current value of the source element
- this.initSelection();
-
- // if the user has provided a function that can set selection based on the value of the source element
- // we monitor the change event on the element and trigger it, allowing for two way synchronization
- this.monitorSource();
- }
-
- if (opts.maximumInputLength !== null) {
- this.search.attr("maxlength", opts.maximumInputLength);
- }
-
- var disabled = opts.element.prop("disabled");
- if (disabled === undefined) disabled = false;
- this.enable(!disabled);
-
- var readonly = opts.element.prop("readonly");
- if (readonly === undefined) readonly = false;
- this.readonly(readonly);
-
- // Calculate size of scrollbar
- scrollBarDimensions = scrollBarDimensions || measureScrollbar();
-
- this.autofocus = opts.element.prop("autofocus");
- opts.element.prop("autofocus", false);
- if (this.autofocus) this.focus();
-
- this.nextSearchTerm = undefined;
- },
-
- // abstract
- destroy: function () {
- var element=this.opts.element, select2 = element.data("select2");
-
- this.close();
-
- if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
-
- if (select2 !== undefined) {
- select2.container.remove();
- select2.dropdown.remove();
- element
- .removeClass("select2-offscreen")
- .removeData("select2")
- .off(".select2")
- .prop("autofocus", this.autofocus || false);
- if (this.elementTabIndex) {
- element.attr({tabindex: this.elementTabIndex});
- } else {
- element.removeAttr("tabindex");
- }
- element.show();
- }
- },
-
- // abstract
- optionToData: function(element) {
- if (element.is("option")) {
- return {
- id:element.prop("value"),
- text:element.text(),
- element: element.get(),
- css: element.attr("class"),
- disabled: element.prop("disabled"),
- locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
- };
- } else if (element.is("optgroup")) {
- return {
- text:element.attr("label"),
- children:[],
- element: element.get(),
- css: element.attr("class")
- };
- }
- },
-
- // abstract
- prepareOpts: function (opts) {
- var element, select, idKey, ajaxUrl, self = this;
-
- element = opts.element;
-
- if (element.get(0).tagName.toLowerCase() === "select") {
- this.select = select = opts.element;
- }
-
- if (select) {
- // these options are not allowed when attached to a select because they are picked up off the element itself
- $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
- if (this in opts) {
- throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
- }
- });
- }
-
- opts = $.extend({}, {
- populateResults: function(container, results, query) {
- var populate, id=this.opts.id;
-
- populate=function(results, container, depth) {
-
- var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
-
- results = opts.sortResults(results, container, query);
-
- for (i = 0, l = results.length; i < l; i = i + 1) {
-
- result=results[i];
-
- disabled = (result.disabled === true);
- selectable = (!disabled) && (id(result) !== undefined);
-
- compound=result.children && result.children.length > 0;
-
- node=$("<li></li>");
- node.addClass("select2-results-dept-"+depth);
- node.addClass("select2-result");
- node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
- if (disabled) { node.addClass("select2-disabled"); }
- if (compound) { node.addClass("select2-result-with-children"); }
- node.addClass(self.opts.formatResultCssClass(result));
-
- label=$(document.createElement("div"));
- label.addClass("select2-result-label");
-
- formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
- if (formatted!==undefined) {
- label.html(formatted);
- }
-
- node.append(label);
-
- if (compound) {
-
- innerContainer=$("<ul></ul>");
- innerContainer.addClass("select2-result-sub");
- populate(result.children, innerContainer, depth+1);
- node.append(innerContainer);
- }
-
- node.data("select2-data", result);
- container.append(node);
- }
- };
-
- populate(results, container, 0);
- }
- }, $.fn.select2.defaults, opts);
-
- if (typeof(opts.id) !== "function") {
- idKey = opts.id;
- opts.id = function (e) { return e[idKey]; };
- }
-
- if ($.isArray(opts.element.data("select2Tags"))) {
- if ("tags" in opts) {
- throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
- }
- opts.tags=opts.element.data("select2Tags");
- }
-
- if (select) {
- opts.query = this.bind(function (query) {
- var data = { results: [], more: false },
- term = query.term,
- children, placeholderOption, process;
-
- process=function(element, collection) {
- var group;
- if (element.is("option")) {
- if (query.matcher(term, element.text(), element)) {
- collection.push(self.optionToData(element));
- }
- } else if (element.is("optgroup")) {
- group=self.optionToData(element);
- element.children().each2(function(i, elm) { process(elm, group.children); });
- if (group.children.length>0) {
- collection.push(group);
- }
- }
- };
-
- children=element.children();
-
- // ignore the placeholder option if there is one
- if (this.getPlaceholder() !== undefined && children.length > 0) {
- placeholderOption = this.getPlaceholderOption();
- if (placeholderOption) {
- children=children.not(placeholderOption);
- }
- }
-
- children.each2(function(i, elm) { process(elm, data.results); });
-
- query.callback(data);
- });
- // this is needed because inside val() we construct choices from options and there id is hardcoded
- opts.id=function(e) { return e.id; };
- opts.formatResultCssClass = function(data) { return data.css; };
- } else {
- if (!("query" in opts)) {
-
- if ("ajax" in opts) {
- ajaxUrl = opts.element.data("ajax-url");
- if (ajaxUrl && ajaxUrl.length > 0) {
- opts.ajax.url = ajaxUrl;
- }
- opts.query = ajax.call(opts.element, opts.ajax);
- } else if ("data" in opts) {
- opts.query = local(opts.data);
- } else if ("tags" in opts) {
- opts.query = tags(opts.tags);
- if (opts.createSearchChoice === undefined) {
- opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
- }
- if (opts.initSelection === undefined) {
- opts.initSelection = function (element, callback) {
- var data = [];
- $(splitVal(element.val(), opts.separator)).each(function () {
- var obj = { id: this, text: this },
- tags = opts.tags;
- if ($.isFunction(tags)) tags=tags();
- $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
- data.push(obj);
- });
-
- callback(data);
- };
- }
- }
- }
- }
- if (typeof(opts.query) !== "function") {
- throw "query function not defined for Select2 " + opts.element.attr("id");
- }
-
- return opts;
- },
-
- /**
- * Monitor the original element for changes and update select2 accordingly
- */
- // abstract
- monitorSource: function () {
- var el = this.opts.element, sync, observer;
-
- el.on("change.select2", this.bind(function (e) {
- if (this.opts.element.data("select2-change-triggered") !== true) {
- this.initSelection();
- }
- }));
-
- sync = this.bind(function () {
-
- // sync enabled state
- var disabled = el.prop("disabled");
- if (disabled === undefined) disabled = false;
- this.enable(!disabled);
-
- var readonly = el.prop("readonly");
- if (readonly === undefined) readonly = false;
- this.readonly(readonly);
-
- syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
- this.container.addClass(evaluate(this.opts.containerCssClass));
-
- syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
- this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
-
- });
-
- // IE8-10
- el.on("propertychange.select2", sync);
-
- // hold onto a reference of the callback to work around a chromium bug
- if (this.mutationCallback === undefined) {
- this.mutationCallback = function (mutations) {
- mutations.forEach(sync);
- }
- }
-
- // safari, chrome, firefox, IE11
- observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
- if (observer !== undefined) {
- if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
- this.propertyObserver = new observer(this.mutationCallback);
- this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
- }
- },
-
- // abstract
- triggerSelect: function(data) {
- var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
- this.opts.element.trigger(evt);
- return !evt.isDefaultPrevented();
- },
-
- /**
- * Triggers the change event on the source element
- */
- // abstract
- triggerChange: function (details) {
-
- details = details || {};
- details= $.extend({}, details, { type: "change", val: this.val() });
- // prevents recursive triggering
- this.opts.element.data("select2-change-triggered", true);
- this.opts.element.trigger(details);
- this.opts.element.data("select2-change-triggered", false);
-
- // some validation frameworks ignore the change event and listen instead to keyup, click for selects
- // so here we trigger the click event manually
- this.opts.element.click();
-
- // ValidationEngine ignorea the change event and listens instead to blur
- // so here we trigger the blur event manually if so desired
- if (this.opts.blurOnChange)
- this.opts.element.blur();
- },
-
- //abstract
- isInterfaceEnabled: function()
- {
- return this.enabledInterface === true;
- },
-
- // abstract
- enableInterface: function() {
- var enabled = this._enabled && !this._readonly,
- disabled = !enabled;
-
- if (enabled === this.enabledInterface) return false;
-
- this.container.toggleClass("select2-container-disabled", disabled);
- this.close();
- this.enabledInterface = enabled;
-
- return true;
- },
-
- // abstract
- enable: function(enabled) {
- if (enabled === undefined) enabled = true;
- if (this._enabled === enabled) return;
- this._enabled = enabled;
-
- this.opts.element.prop("disabled", !enabled);
- this.enableInterface();
- },
-
- // abstract
- disable: function() {
- this.enable(false);
- },
-
- // abstract
- readonly: function(enabled) {
- if (enabled === undefined) enabled = false;
- if (this._readonly === enabled) return false;
- this._readonly = enabled;
-
- this.opts.element.prop("readonly", enabled);
- this.enableInterface();
- return true;
- },
-
- // abstract
- opened: function () {
- return this.container.hasClass("select2-dropdown-open");
- },
-
- // abstract
- positionDropdown: function() {
- var $dropdown = this.dropdown,
- offset = this.container.offset(),
- height = this.container.outerHeight(false),
- width = this.container.outerWidth(false),
- dropHeight = $dropdown.outerHeight(false),
- $window = $(window),
- windowWidth = $window.width(),
- windowHeight = $window.height(),
- viewPortRight = $window.scrollLeft() + windowWidth,
- viewportBottom = $window.scrollTop() + windowHeight,
- dropTop = offset.top + height,
- dropLeft = offset.left,
- enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
- enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
- dropWidth = $dropdown.outerWidth(false),
- enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
- aboveNow = $dropdown.hasClass("select2-drop-above"),
- bodyOffset,
- above,
- changeDirection,
- css,
- resultsListNode;
-
- // always prefer the current above/below alignment, unless there is not enough room
- if (aboveNow) {
- above = true;
- if (!enoughRoomAbove && enoughRoomBelow) {
- changeDirection = true;
- above = false;
- }
- } else {
- above = false;
- if (!enoughRoomBelow && enoughRoomAbove) {
- changeDirection = true;
- above = true;
- }
- }
-
- //if we are changing direction we need to get positions when dropdown is hidden;
- if (changeDirection) {
- $dropdown.hide();
- offset = this.container.offset();
- height = this.container.outerHeight(false);
- width = this.container.outerWidth(false);
- dropHeight = $dropdown.outerHeight(false);
- viewPortRight = $window.scrollLeft() + windowWidth;
- viewportBottom = $window.scrollTop() + windowHeight;
- dropTop = offset.top + height;
- dropLeft = offset.left;
- dropWidth = $dropdown.outerWidth(false);
- enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
- $dropdown.show();
- }
-
- if (this.opts.dropdownAutoWidth) {
- resultsListNode = $('.select2-results', $dropdown)[0];
- $dropdown.addClass('select2-drop-auto-width');
- $dropdown.css('width', '');
- // Add scrollbar width to dropdown if vertical scrollbar is present
- dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
- dropWidth > width ? width = dropWidth : dropWidth = width;
- enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
- }
- else {
- this.container.removeClass('select2-drop-auto-width');
- }
-
- //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
- //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
-
- // fix positioning when body has an offset and is not position: static
- if (this.body().css('position') !== 'static') {
- bodyOffset = this.body().offset();
- dropTop -= bodyOffset.top;
- dropLeft -= bodyOffset.left;
- }
-
- if (!enoughRoomOnRight) {
- dropLeft = offset.left + width - dropWidth;
- }
-
- css = {
- left: dropLeft,
- width: width
- };
-
- if (above) {
- css.bottom = windowHeight - offset.top;
- css.top = 'auto';
- this.container.addClass("select2-drop-above");
- $dropdown.addClass("select2-drop-above");
- }
- else {
- css.top = dropTop;
- css.bottom = 'auto';
- this.container.removeClass("select2-drop-above");
- $dropdown.removeClass("select2-drop-above");
- }
- css = $.extend(css, evaluate(this.opts.dropdownCss));
-
- $dropdown.css(css);
- },
-
- // abstract
- shouldOpen: function() {
- var event;
-
- if (this.opened()) return false;
-
- if (this._enabled === false || this._readonly === true) return false;
-
- event = $.Event("select2-opening");
- this.opts.element.trigger(event);
- return !event.isDefaultPrevented();
- },
-
- // abstract
- clearDropdownAlignmentPreference: function() {
- // clear the classes used to figure out the preference of where the dropdown should be opened
- this.container.removeClass("select2-drop-above");
- this.dropdown.removeClass("select2-drop-above");
- },
-
- /**
- * Opens the dropdown
- *
- * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
- * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
- */
- // abstract
- open: function () {
-
- if (!this.shouldOpen()) return false;
-
- this.opening();
-
- return true;
- },
-
- /**
- * Performs the opening of the dropdown
- */
- // abstract
- opening: function() {
- var cid = this.containerId,
- scroll = "scroll." + cid,
- resize = "resize."+cid,
- orient = "orientationchange."+cid,
- mask;
-
- this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
-
- this.clearDropdownAlignmentPreference();
-
- if(this.dropdown[0] !== this.body().children().last()[0]) {
- this.dropdown.detach().appendTo(this.body());
- }
-
- // create the dropdown mask if doesnt already exist
- mask = $("#select2-drop-mask");
- if (mask.length == 0) {
- mask = $(document.createElement("div"));
- mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
- mask.hide();
- mask.appendTo(this.body());
- mask.on("mousedown touchstart click", function (e) {
- var dropdown = $("#select2-drop"), self;
- if (dropdown.length > 0) {
- self=dropdown.data("select2");
- if (self.opts.selectOnBlur) {
- self.selectHighlighted({noFocus: true});
- }
- self.close({focus:true});
- e.preventDefault();
- e.stopPropagation();
- }
- });
- }
-
- // ensure the mask is always right before the dropdown
- if (this.dropdown.prev()[0] !== mask[0]) {
- this.dropdown.before(mask);
- }
-
- // move the global id to the correct dropdown
- $("#select2-drop").removeAttr("id");
- this.dropdown.attr("id", "select2-drop");
-
- // show the elements
- mask.show();
-
- this.positionDropdown();
- this.dropdown.show();
- this.positionDropdown();
-
- this.dropdown.addClass("select2-drop-active");
-
- // attach listeners to events that can change the position of the container and thus require
- // the position of the dropdown to be updated as well so it does not come unglued from the container
- var that = this;
- this.container.parents().add(window).each(function () {
- $(this).on(resize+" "+scroll+" "+orient, function (e) {
- that.positionDropdown();
- });
- });
-
-
- },
-
- // abstract
- close: function () {
- if (!this.opened()) return;
-
- var cid = this.containerId,
- scroll = "scroll." + cid,
- resize = "resize."+cid,
- orient = "orientationchange."+cid;
-
- // unbind event listeners
- this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
-
- this.clearDropdownAlignmentPreference();
-
- $("#select2-drop-mask").hide();
- this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
- this.dropdown.hide();
- this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
- this.results.empty();
-
-
- this.clearSearch();
- this.search.removeClass("select2-active");
- this.opts.element.trigger($.Event("select2-close"));
- },
-
- /**
- * Opens control, sets input value, and updates results.
- */
- // abstract
- externalSearch: function (term) {
- this.open();
- this.search.val(term);
- this.updateResults(false);
- },
-
- // abstract
- clearSearch: function () {
-
- },
-
- //abstract
- getMaximumSelectionSize: function() {
- return evaluate(this.opts.maximumSelectionSize);
- },
-
- // abstract
- ensureHighlightVisible: function () {
- var results = this.results, children, index, child, hb, rb, y, more;
-
- index = this.highlight();
-
- if (index < 0) return;
-
- if (index == 0) {
-
- // if the first element is highlighted scroll all the way to the top,
- // that way any unselectable headers above it will also be scrolled
- // into view
-
- results.scrollTop(0);
- return;
- }
-
- children = this.findHighlightableChoices().find('.select2-result-label');
-
- child = $(children[index]);
-
- hb = child.offset().top + child.outerHeight(true);
-
- // if this is the last child lets also make sure select2-more-results is visible
- if (index === children.length - 1) {
- more = results.find("li.select2-more-results");
- if (more.length > 0) {
- hb = more.offset().top + more.outerHeight(true);
- }
- }
-
- rb = results.offset().top + results.outerHeight(true);
- if (hb > rb) {
- results.scrollTop(results.scrollTop() + (hb - rb));
- }
- y = child.offset().top - results.offset().top;
-
- // make sure the top of the element is visible
- if (y < 0 && child.css('display') != 'none' ) {
- results.scrollTop(results.scrollTop() + y); // y is negative
- }
- },
-
- // abstract
- findHighlightableChoices: function() {
- return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)");
- },
-
- // abstract
- moveHighlight: function (delta) {
- var choices = this.findHighlightableChoices(),
- index = this.highlight();
-
- while (index > -1 && index < choices.length) {
- index += delta;
- var choice = $(choices[index]);
- if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
- this.highlight(index);
- break;
- }
- }
- },
-
- // abstract
- highlight: function (index) {
- var choices = this.findHighlightableChoices(),
- choice,
- data;
-
- if (arguments.length === 0) {
- return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
- }
-
- if (index >= choices.length) index = choices.length - 1;
- if (index < 0) index = 0;
-
- this.removeHighlight();
-
- choice = $(choices[index]);
- choice.addClass("select2-highlighted");
-
- this.ensureHighlightVisible();
-
- data = choice.data("select2-data");
- if (data) {
- this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
- }
- },
-
- removeHighlight: function() {
- this.results.find(".select2-highlighted").removeClass("select2-highlighted");
- },
-
- // abstract
- countSelectableResults: function() {
- return this.findHighlightableChoices().length;
- },
-
- // abstract
- highlightUnderEvent: function (event) {
- var el = $(event.target).closest(".select2-result-selectable");
- if (el.length > 0 && !el.is(".select2-highlighted")) {
- var choices = this.findHighlightableChoices();
- this.highlight(choices.index(el));
- } else if (el.length == 0) {
- // if we are over an unselectable item remove all highlights
- this.removeHighlight();
- }
- },
-
- // abstract
- loadMoreIfNeeded: function () {
- var results = this.results,
- more = results.find("li.select2-more-results"),
- below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
- page = this.resultsPage + 1,
- self=this,
- term=this.search.val(),
- context=this.context;
-
- if (more.length === 0) return;
- below = more.offset().top - results.offset().top - results.height();
-
- if (below <= this.opts.loadMorePadding) {
- more.addClass("select2-active");
- this.opts.query({
- element: this.opts.element,
- term: term,
- page: page,
- context: context,
- matcher: this.opts.matcher,
- callback: this.bind(function (data) {
-
- // ignore a response if the select2 has been closed before it was received
- if (!self.opened()) return;
-
-
- self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
- self.postprocessResults(data, false, false);
-
- if (data.more===true) {
- more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
- window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
- } else {
- more.remove();
- }
- self.positionDropdown();
- self.resultsPage = page;
- self.context = data.context;
- this.opts.element.trigger({ type: "select2-loaded", items: data });
- })});
- }
- },
-
- /**
- * Default tokenizer function which does nothing
- */
- tokenize: function() {
-
- },
-
- /**
- * @param initial whether or not this is the call to this method right after the dropdown has been opened
- */
- // abstract
- updateResults: function (initial) {
- var search = this.search,
- results = this.results,
- opts = this.opts,
- data,
- self = this,
- input,
- term = search.val(),
- lastTerm = $.data(this.container, "select2-last-term"),
- // sequence number used to drop out-of-order responses
- queryNumber;
-
- // prevent duplicate queries against the same term
- if (initial !== true && lastTerm && equal(term, lastTerm)) return;
-
- $.data(this.container, "select2-last-term", term);
-
- // if the search is currently hidden we do not alter the results
- if (initial !== true && (this.showSearchInput === false || !this.opened())) {
- return;
- }
-
- function postRender() {
- search.removeClass("select2-active");
- self.positionDropdown();
- }
-
- function render(html) {
- results.html(html);
- postRender();
- }
-
- queryNumber = ++this.queryCount;
-
- var maxSelSize = this.getMaximumSelectionSize();
- if (maxSelSize >=1) {
- data = this.data();
- if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
- render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
- return;
- }
- }
-
- if (search.val().length < opts.minimumInputLength) {
- if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
- render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
- } else {
- render("");
- }
- if (initial && this.showSearch) this.showSearch(true);
- return;
- }
-
- if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
- if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
- render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
- } else {
- render("");
- }
- return;
- }
-
- if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
- render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
- }
-
- search.addClass("select2-active");
-
- this.removeHighlight();
-
- // give the tokenizer a chance to pre-process the input
- input = this.tokenize();
- if (input != undefined && input != null) {
- search.val(input);
- }
-
- this.resultsPage = 1;
-
- opts.query({
- element: opts.element,
- term: search.val(),
- page: this.resultsPage,
- context: null,
- matcher: opts.matcher,
- callback: this.bind(function (data) {
- var def; // default choice
-
- // ignore old responses
- if (queryNumber != this.queryCount) {
- return;
- }
-
- // ignore a response if the select2 has been closed before it was received
- if (!this.opened()) {
- this.search.removeClass("select2-active");
- return;
- }
-
- // save context, if any
- this.context = (data.context===undefined) ? null : data.context;
- // create a default choice and prepend it to the list
- if (this.opts.createSearchChoice && search.val() !== "") {
- def = this.opts.createSearchChoice.call(self, search.val(), data.results);
- if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
- if ($(data.results).filter(
- function () {
- return equal(self.id(this), self.id(def));
- }).length === 0) {
- data.results.unshift(def);
- }
- }
- }
-
- if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
- render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
- return;
- }
-
- results.empty();
- self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
-
- if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
- results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
- window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
- }
-
- this.postprocessResults(data, initial);
-
- postRender();
-
- this.opts.element.trigger({ type: "select2-loaded", items: data });
- })});
- },
-
- // abstract
- cancel: function () {
- this.close();
- },
-
- // abstract
- blur: function () {
- // if selectOnBlur == true, select the currently highlighted option
- if (this.opts.selectOnBlur)
- this.selectHighlighted({noFocus: true});
-
- this.close();
- this.container.removeClass("select2-container-active");
- // synonymous to .is(':focus'), which is available in jquery >= 1.6
- if (this.search[0] === document.activeElement) { this.search.blur(); }
- this.clearSearch();
- this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
- },
-
- // abstract
- focusSearch: function () {
- focus(this.search);
- },
-
- // abstract
- selectHighlighted: function (options) {
- var index=this.highlight(),
- highlighted=this.results.find(".select2-highlighted"),
- data = highlighted.closest('.select2-result').data("select2-data");
-
- if (data) {
- this.highlight(index);
- this.onSelect(data, options);
- } else if (options && options.noFocus) {
- this.close();
- }
- },
-
- // abstract
- getPlaceholder: function () {
- var placeholderOption;
- return this.opts.element.attr("placeholder") ||
- this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
- this.opts.element.data("placeholder") ||
- this.opts.placeholder ||
- ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
- },
-
- // abstract
- getPlaceholderOption: function() {
- if (this.select) {
- var firstOption = this.select.children('option').first();
- if (this.opts.placeholderOption !== undefined ) {
- //Determine the placeholder option based on the specified placeholderOption setting
- return (this.opts.placeholderOption === "first" && firstOption) ||
- (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
- } else if (firstOption.text() === "" && firstOption.val() === "") {
- //No explicit placeholder option specified, use the first if it's blank
- return firstOption;
- }
- }
- },
-
- /**
- * Get the desired width for the container element. This is
- * derived first from option `width` passed to select2, then
- * the inline 'style' on the original element, and finally
- * falls back to the jQuery calculated element width.
- */
- // abstract
- initContainerWidth: function () {
- function resolveContainerWidth() {
- var style, attrs, matches, i, l, attr;
-
- if (this.opts.width === "off") {
- return null;
- } else if (this.opts.width === "element"){
- return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
- } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
- // check if there is inline style on the element that contains width
- style = this.opts.element.attr('style');
- if (style !== undefined) {
- attrs = style.split(';');
- for (i = 0, l = attrs.length; i < l; i = i + 1) {
- attr = attrs[i].replace(/\s/g, '');
- matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
- if (matches !== null && matches.length >= 1)
- return matches[1];
- }
- }
-
- if (this.opts.width === "resolve") {
- // next check if css('width') can resolve a width that is percent based, this is sometimes possible
- // when attached to input type=hidden or elements hidden via css
- style = this.opts.element.css('width');
- if (style.indexOf("%") > 0) return style;
-
- // finally, fallback on the calculated width of the element
- return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
- }
-
- return null;
- } else if ($.isFunction(this.opts.width)) {
- return this.opts.width();
- } else {
- return this.opts.width;
- }
- };
-
- var width = resolveContainerWidth.call(this);
- if (width !== null) {
- this.container.css("width", width);
- }
- }
- });
-
- SingleSelect2 = clazz(AbstractSelect2, {
-
- // single
-
- createContainer: function () {
- var container = $(document.createElement("div")).attr({
- "class": "select2-container"
- }).html([
- "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
- " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>",
- " <span class='select2-arrow'><b></b></span>",
- "</a>",
- "<input class='select2-focusser select2-offscreen' type='text'/>",
- "<div class='select2-drop select2-display-none'>",
- " <div class='select2-search'>",
- " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>",
- " </div>",
- " <ul class='select2-results'>",
- " </ul>",
- "</div>"].join(""));
- return container;
- },
-
- // single
- enableInterface: function() {
- if (this.parent.enableInterface.apply(this, arguments)) {
- this.focusser.prop("disabled", !this.isInterfaceEnabled());
- }
- },
-
- // single
- opening: function () {
- var el, range, len;
-
- if (this.opts.minimumResultsForSearch >= 0) {
- this.showSearch(true);
- }
-
- this.parent.opening.apply(this, arguments);
-
- if (this.showSearchInput !== false) {
- // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
- // all other browsers handle this just fine
-
- this.search.val(this.focusser.val());
- }
- this.search.focus();
- // move the cursor to the end after focussing, otherwise it will be at the beginning and
- // new text will appear *before* focusser.val()
- el = this.search.get(0);
- if (el.createTextRange) {
- range = el.createTextRange();
- range.collapse(false);
- range.select();
- } else if (el.setSelectionRange) {
- len = this.search.val().length;
- el.setSelectionRange(len, len);
- }
-
- // initializes search's value with nextSearchTerm (if defined by user)
- // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
- if(this.search.val() === "") {
- if(this.nextSearchTerm != undefined){
- this.search.val(this.nextSearchTerm);
- this.search.select();
- }
- }
-
- this.focusser.prop("disabled", true).val("");
- this.updateResults(true);
- this.opts.element.trigger($.Event("select2-open"));
- },
-
- // single
- close: function (params) {
- if (!this.opened()) return;
- this.parent.close.apply(this, arguments);
-
- params = params || {focus: true};
- this.focusser.removeAttr("disabled");
-
- if (params.focus) {
- this.focusser.focus();
- }
- },
-
- // single
- focus: function () {
- if (this.opened()) {
- this.close();
- } else {
- this.focusser.removeAttr("disabled");
- this.focusser.focus();
- }
- },
-
- // single
- isFocused: function () {
- return this.container.hasClass("select2-container-active");
- },
-
- // single
- cancel: function () {
- this.parent.cancel.apply(this, arguments);
- this.focusser.removeAttr("disabled");
- this.focusser.focus();
- },
-
- // single
- destroy: function() {
- $("label[for='" + this.focusser.attr('id') + "']")
- .attr('for', this.opts.element.attr("id"));
- this.parent.destroy.apply(this, arguments);
- },
-
- // single
- initContainer: function () {
-
- var selection,
- container = this.container,
- dropdown = this.dropdown;
-
- if (this.opts.minimumResultsForSearch < 0) {
- this.showSearch(false);
- } else {
- this.showSearch(true);
- }
-
- this.selection = selection = container.find(".select2-choice");
-
- this.focusser = container.find(".select2-focusser");
-
- // rewrite labels from original element to focusser
- this.focusser.attr("id", "s2id_autogen"+nextUid());
-
- $("label[for='" + this.opts.element.attr("id") + "']")
- .attr('for', this.focusser.attr('id'));
-
- this.focusser.attr("tabindex", this.elementTabIndex);
-
- this.search.on("keydown", this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
-
- if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
- // prevent the page from scrolling
- killEvent(e);
- return;
- }
-
- switch (e.which) {
- case KEY.UP:
- case KEY.DOWN:
- this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
- killEvent(e);
- return;
- case KEY.ENTER:
- this.selectHighlighted();
- killEvent(e);
- return;
- case KEY.TAB:
- this.selectHighlighted({noFocus: true});
- return;
- case KEY.ESC:
- this.cancel(e);
- killEvent(e);
- return;
- }
- }));
-
- this.search.on("blur", this.bind(function(e) {
- // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
- // without this the search field loses focus which is annoying
- if (document.activeElement === this.body().get(0)) {
- window.setTimeout(this.bind(function() {
- this.search.focus();
- }), 0);
- }
- }));
-
- this.focusser.on("keydown", this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
-
- if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
- return;
- }
-
- if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
- killEvent(e);
- return;
- }
-
- if (e.which == KEY.DOWN || e.which == KEY.UP
- || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
-
- if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
-
- this.open();
- killEvent(e);
- return;
- }
-
- if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
- if (this.opts.allowClear) {
- this.clear();
- }
- killEvent(e);
- return;
- }
- }));
-
-
- installKeyUpChangeEvent(this.focusser);
- this.focusser.on("keyup-change input", this.bind(function(e) {
- if (this.opts.minimumResultsForSearch >= 0) {
- e.stopPropagation();
- if (this.opened()) return;
- this.open();
- }
- }));
-
- selection.on("mousedown", "abbr", this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
- this.clear();
- killEventImmediately(e);
- this.close();
- this.selection.focus();
- }));
-
- selection.on("mousedown", this.bind(function (e) {
-
- if (!this.container.hasClass("select2-container-active")) {
- this.opts.element.trigger($.Event("select2-focus"));
- }
-
- if (this.opened()) {
- this.close();
- } else if (this.isInterfaceEnabled()) {
- this.open();
- }
-
- killEvent(e);
- }));
-
- dropdown.on("mousedown", this.bind(function() { this.search.focus(); }));
-
- selection.on("focus", this.bind(function(e) {
- killEvent(e);
- }));
-
- this.focusser.on("focus", this.bind(function(){
- if (!this.container.hasClass("select2-container-active")) {
- this.opts.element.trigger($.Event("select2-focus"));
- }
- this.container.addClass("select2-container-active");
- })).on("blur", this.bind(function() {
- if (!this.opened()) {
- this.container.removeClass("select2-container-active");
- this.opts.element.trigger($.Event("select2-blur"));
- }
- }));
- this.search.on("focus", this.bind(function(){
- if (!this.container.hasClass("select2-container-active")) {
- this.opts.element.trigger($.Event("select2-focus"));
- }
- this.container.addClass("select2-container-active");
- }));
-
- this.initContainerWidth();
- this.opts.element.addClass("select2-offscreen");
- this.setPlaceholder();
-
- },
-
- // single
- clear: function(triggerChange) {
- var data=this.selection.data("select2-data");
- if (data) { // guard against queued quick consecutive clicks
- var evt = $.Event("select2-clearing");
- this.opts.element.trigger(evt);
- if (evt.isDefaultPrevented()) {
- return;
- }
- var placeholderOption = this.getPlaceholderOption();
- this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
- this.selection.find(".select2-chosen").empty();
- this.selection.removeData("select2-data");
- this.setPlaceholder();
-
- if (triggerChange !== false){
- this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
- this.triggerChange({removed:data});
- }
- }
- },
-
- /**
- * Sets selection based on source element's value
- */
- // single
- initSelection: function () {
- var selected;
- if (this.isPlaceholderOptionSelected()) {
- this.updateSelection(null);
- this.close();
- this.setPlaceholder();
- } else {
- var self = this;
- this.opts.initSelection.call(null, this.opts.element, function(selected){
- if (selected !== undefined && selected !== null) {
- self.updateSelection(selected);
- self.close();
- self.setPlaceholder();
- }
- });
- }
- },
-
- isPlaceholderOptionSelected: function() {
- var placeholderOption;
- if (!this.getPlaceholder()) return false; // no placeholder specified so no option should be considered
- return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
- || (this.opts.element.val() === "")
- || (this.opts.element.val() === undefined)
- || (this.opts.element.val() === null);
- },
-
- // single
- prepareOpts: function () {
- var opts = this.parent.prepareOpts.apply(this, arguments),
- self=this;
-
- if (opts.element.get(0).tagName.toLowerCase() === "select") {
- // install the selection initializer
- opts.initSelection = function (element, callback) {
- var selected = element.find("option").filter(function() { return this.selected });
- // a single select box always has a value, no need to null check 'selected'
- callback(self.optionToData(selected));
- };
- } else if ("data" in opts) {
- // install default initSelection when applied to hidden input and data is local
- opts.initSelection = opts.initSelection || function (element, callback) {
- var id = element.val();
- //search in data by id, storing the actual matching item
- var match = null;
- opts.query({
- matcher: function(term, text, el){
- var is_match = equal(id, opts.id(el));
- if (is_match) {
- match = el;
- }
- return is_match;
- },
- callback: !$.isFunction(callback) ? $.noop : function() {
- callback(match);
- }
- });
- };
- }
-
- return opts;
- },
-
- // single
- getPlaceholder: function() {
- // if a placeholder is specified on a single select without a valid placeholder option ignore it
- if (this.select) {
- if (this.getPlaceholderOption() === undefined) {
- return undefined;
- }
- }
-
- return this.parent.getPlaceholder.apply(this, arguments);
- },
-
- // single
- setPlaceholder: function () {
- var placeholder = this.getPlaceholder();
-
- if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
-
- // check for a placeholder option if attached to a select
- if (this.select && this.getPlaceholderOption() === undefined) return;
-
- this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
-
- this.selection.addClass("select2-default");
-
- this.container.removeClass("select2-allowclear");
- }
- },
-
- // single
- postprocessResults: function (data, initial, noHighlightUpdate) {
- var selected = 0, self = this, showSearchInput = true;
-
- // find the selected element in the result list
-
- this.findHighlightableChoices().each2(function (i, elm) {
- if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
- selected = i;
- return false;
- }
- });
-
- // and highlight it
- if (noHighlightUpdate !== false) {
- if (initial === true && selected >= 0) {
- this.highlight(selected);
- } else {
- this.highlight(0);
- }
- }
-
- // hide the search box if this is the first we got the results and there are enough of them for search
-
- if (initial === true) {
- var min = this.opts.minimumResultsForSearch;
- if (min >= 0) {
- this.showSearch(countResults(data.results) >= min);
- }
- }
- },
-
- // single
- showSearch: function(showSearchInput) {
- if (this.showSearchInput === showSearchInput) return;
-
- this.showSearchInput = showSearchInput;
-
- this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
- this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
- //add "select2-with-searchbox" to the container if search box is shown
- $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
- },
-
- // single
- onSelect: function (data, options) {
-
- if (!this.triggerSelect(data)) { return; }
-
- var old = this.opts.element.val(),
- oldData = this.data();
-
- this.opts.element.val(this.id(data));
- this.updateSelection(data);
-
- this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
-
- this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
- this.close();
-
- if (!options || !options.noFocus)
- this.focusser.focus();
-
- if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
- },
-
- // single
- updateSelection: function (data) {
-
- var container=this.selection.find(".select2-chosen"), formatted, cssClass;
-
- this.selection.data("select2-data", data);
-
- container.empty();
- if (data !== null) {
- formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
- }
- if (formatted !== undefined) {
- container.append(formatted);
- }
- cssClass=this.opts.formatSelectionCssClass(data, container);
- if (cssClass !== undefined) {
- container.addClass(cssClass);
- }
-
- this.selection.removeClass("select2-default");
-
- if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
- this.container.addClass("select2-allowclear");
- }
- },
-
- // single
- val: function () {
- var val,
- triggerChange = false,
- data = null,
- self = this,
- oldData = this.data();
-
- if (arguments.length === 0) {
- return this.opts.element.val();
- }
-
- val = arguments[0];
-
- if (arguments.length > 1) {
- triggerChange = arguments[1];
- }
-
- if (this.select) {
- this.select
- .val(val)
- .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
- data = self.optionToData(elm);
- return false;
- });
- this.updateSelection(data);
- this.setPlaceholder();
- if (triggerChange) {
- this.triggerChange({added: data, removed:oldData});
- }
- } else {
- // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
- if (!val && val !== 0) {
- this.clear(triggerChange);
- return;
- }
- if (this.opts.initSelection === undefined) {
- throw new Error("cannot call val() if initSelection() is not defined");
- }
- this.opts.element.val(val);
- this.opts.initSelection(this.opts.element, function(data){
- self.opts.element.val(!data ? "" : self.id(data));
- self.updateSelection(data);
- self.setPlaceholder();
- if (triggerChange) {
- self.triggerChange({added: data, removed:oldData});
- }
- });
- }
- },
-
- // single
- clearSearch: function () {
- this.search.val("");
- this.focusser.val("");
- },
-
- // single
- data: function(value) {
- var data,
- triggerChange = false;
-
- if (arguments.length === 0) {
- data = this.selection.data("select2-data");
- if (data == undefined) data = null;
- return data;
- } else {
- if (arguments.length > 1) {
- triggerChange = arguments[1];
- }
- if (!value) {
- this.clear(triggerChange);
- } else {
- data = this.data();
- this.opts.element.val(!value ? "" : this.id(value));
- this.updateSelection(value);
- if (triggerChange) {
- this.triggerChange({added: value, removed:data});
- }
- }
- }
- }
- });
-
- MultiSelect2 = clazz(AbstractSelect2, {
-
- // multi
- createContainer: function () {
- var container = $(document.createElement("div")).attr({
- "class": "select2-container select2-container-multi"
- }).html([
- "<ul class='select2-choices'>",
- " <li class='select2-search-field'>",
- " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
- " </li>",
- "</ul>",
- "<div class='select2-drop select2-drop-multi select2-display-none'>",
- " <ul class='select2-results'>",
- " </ul>",
- "</div>"].join(""));
- return container;
- },
-
- // multi
- prepareOpts: function () {
- var opts = this.parent.prepareOpts.apply(this, arguments),
- self=this;
-
- // TODO validate placeholder is a string if specified
-
- if (opts.element.get(0).tagName.toLowerCase() === "select") {
- // install sthe selection initializer
- opts.initSelection = function (element, callback) {
-
- var data = [];
-
- element.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
- data.push(self.optionToData(elm));
- });
- callback(data);
- };
- } else if ("data" in opts) {
- // install default initSelection when applied to hidden input and data is local
- opts.initSelection = opts.initSelection || function (element, callback) {
- var ids = splitVal(element.val(), opts.separator);
- //search in data by array of ids, storing matching items in a list
- var matches = [];
- opts.query({
- matcher: function(term, text, el){
- var is_match = $.grep(ids, function(id) {
- return equal(id, opts.id(el));
- }).length;
- if (is_match) {
- matches.push(el);
- }
- return is_match;
- },
- callback: !$.isFunction(callback) ? $.noop : function() {
- // reorder matches based on the order they appear in the ids array because right now
- // they are in the order in which they appear in data array
- var ordered = [];
- for (var i = 0; i < ids.length; i++) {
- var id = ids[i];
- for (var j = 0; j < matches.length; j++) {
- var match = matches[j];
- if (equal(id, opts.id(match))) {
- ordered.push(match);
- matches.splice(j, 1);
- break;
- }
- }
- }
- callback(ordered);
- }
- });
- };
- }
-
- return opts;
- },
-
- // multi
- selectChoice: function (choice) {
-
- var selected = this.container.find(".select2-search-choice-focus");
- if (selected.length && choice && choice[0] == selected[0]) {
-
- } else {
- if (selected.length) {
- this.opts.element.trigger("choice-deselected", selected);
- }
- selected.removeClass("select2-search-choice-focus");
- if (choice && choice.length) {
- this.close();
- choice.addClass("select2-search-choice-focus");
- this.opts.element.trigger("choice-selected", choice);
- }
- }
- },
-
- // multi
- destroy: function() {
- $("label[for='" + this.search.attr('id') + "']")
- .attr('for', this.opts.element.attr("id"));
- this.parent.destroy.apply(this, arguments);
- },
-
- // multi
- initContainer: function () {
-
- var selector = ".select2-choices", selection;
-
- this.searchContainer = this.container.find(".select2-search-field");
- this.selection = selection = this.container.find(selector);
-
- var _this = this;
- this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
- //killEvent(e);
- _this.search[0].focus();
- _this.selectChoice($(this));
- });
-
- // rewrite labels from original element to focusser
- this.search.attr("id", "s2id_autogen"+nextUid());
- $("label[for='" + this.opts.element.attr("id") + "']")
- .attr('for', this.search.attr('id'));
-
- this.search.on("input paste", this.bind(function() {
- if (!this.isInterfaceEnabled()) return;
- if (!this.opened()) {
- this.open();
- }
- }));
-
- this.search.attr("tabindex", this.elementTabIndex);
-
- this.keydowns = 0;
- this.search.on("keydown", this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
-
- ++this.keydowns;
- var selected = selection.find(".select2-search-choice-focus");
- var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
- var next = selected.next(".select2-search-choice:not(.select2-locked)");
- var pos = getCursorInfo(this.search);
-
- if (selected.length &&
- (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
- var selectedChoice = selected;
- if (e.which == KEY.LEFT && prev.length) {
- selectedChoice = prev;
- }
- else if (e.which == KEY.RIGHT) {
- selectedChoice = next.length ? next : null;
- }
- else if (e.which === KEY.BACKSPACE) {
- this.unselect(selected.first());
- this.search.width(10);
- selectedChoice = prev.length ? prev : next;
- } else if (e.which == KEY.DELETE) {
- this.unselect(selected.first());
- this.search.width(10);
- selectedChoice = next.length ? next : null;
- } else if (e.which == KEY.ENTER) {
- selectedChoice = null;
- }
-
- this.selectChoice(selectedChoice);
- killEvent(e);
- if (!selectedChoice || !selectedChoice.length) {
- this.open();
- }
- return;
- } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
- || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
-
- this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
- killEvent(e);
- return;
- } else {
- this.selectChoice(null);
- }
-
- if (this.opened()) {
- switch (e.which) {
- case KEY.UP:
- case KEY.DOWN:
- this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
- killEvent(e);
- return;
- case KEY.ENTER:
- this.selectHighlighted();
- killEvent(e);
- return;
- case KEY.TAB:
- this.selectHighlighted({noFocus:true});
- this.close();
- return;
- case KEY.ESC:
- this.cancel(e);
- killEvent(e);
- return;
- }
- }
-
- if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
- || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
- return;
- }
-
- if (e.which === KEY.ENTER) {
- if (this.opts.openOnEnter === false) {
- return;
- } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
- return;
- }
- }
-
- this.open();
-
- if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
- // prevent the page from scrolling
- killEvent(e);
- }
-
- if (e.which === KEY.ENTER) {
- // prevent form from being submitted
- killEvent(e);
- }
-
- }));
-
- this.search.on("keyup", this.bind(function (e) {
- this.keydowns = 0;
- this.resizeSearch();
- })
- );
-
- this.search.on("blur", this.bind(function(e) {
- this.container.removeClass("select2-container-active");
- this.search.removeClass("select2-focused");
- this.selectChoice(null);
- if (!this.opened()) this.clearSearch();
- e.stopImmediatePropagation();
- this.opts.element.trigger($.Event("select2-blur"));
- }));
-
- this.container.on("click", selector, this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
- if ($(e.target).closest(".select2-search-choice").length > 0) {
- // clicked inside a select2 search choice, do not open
- return;
- }
- this.selectChoice(null);
- this.clearPlaceholder();
- if (!this.container.hasClass("select2-container-active")) {
- this.opts.element.trigger($.Event("select2-focus"));
- }
- this.open();
- this.focusSearch();
- e.preventDefault();
- }));
-
- this.container.on("focus", selector, this.bind(function () {
- if (!this.isInterfaceEnabled()) return;
- if (!this.container.hasClass("select2-container-active")) {
- this.opts.element.trigger($.Event("select2-focus"));
- }
- this.container.addClass("select2-container-active");
- this.dropdown.addClass("select2-drop-active");
- this.clearPlaceholder();
- }));
-
- this.initContainerWidth();
- this.opts.element.addClass("select2-offscreen");
-
- // set the placeholder if necessary
- this.clearSearch();
- },
-
- // multi
- enableInterface: function() {
- if (this.parent.enableInterface.apply(this, arguments)) {
- this.search.prop("disabled", !this.isInterfaceEnabled());
- }
- },
-
- // multi
- initSelection: function () {
- var data;
- if (this.opts.element.val() === "" && this.opts.element.text() === "") {
- this.updateSelection([]);
- this.close();
- // set the placeholder if necessary
- this.clearSearch();
- }
- if (this.select || this.opts.element.val() !== "") {
- var self = this;
- this.opts.initSelection.call(null, this.opts.element, function(data){
- if (data !== undefined && data !== null) {
- self.updateSelection(data);
- self.close();
- // set the placeholder if necessary
- self.clearSearch();
- }
- });
- }
- },
-
- // multi
- clearSearch: function () {
- var placeholder = this.getPlaceholder(),
- maxWidth = this.getMaxSearchWidth();
-
- if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
- this.search.val(placeholder).addClass("select2-default");
- // stretch the search box to full width of the container so as much of the placeholder is visible as possible
- // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
- this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
- } else {
- this.search.val("").width(10);
- }
- },
-
- // multi
- clearPlaceholder: function () {
- if (this.search.hasClass("select2-default")) {
- this.search.val("").removeClass("select2-default");
- }
- },
-
- // multi
- opening: function () {
- this.clearPlaceholder(); // should be done before super so placeholder is not used to search
- this.resizeSearch();
-
- this.parent.opening.apply(this, arguments);
-
- this.focusSearch();
-
- this.updateResults(true);
- this.search.focus();
- this.opts.element.trigger($.Event("select2-open"));
- },
-
- // multi
- close: function () {
- if (!this.opened()) return;
- this.parent.close.apply(this, arguments);
- },
-
- // multi
- focus: function () {
- this.close();
- this.search.focus();
- },
-
- // multi
- isFocused: function () {
- return this.search.hasClass("select2-focused");
- },
-
- // multi
- updateSelection: function (data) {
- var ids = [], filtered = [], self = this;
-
- // filter out duplicates
- $(data).each(function () {
- if (indexOf(self.id(this), ids) < 0) {
- ids.push(self.id(this));
- filtered.push(this);
- }
- });
- data = filtered;
-
- this.selection.find(".select2-search-choice").remove();
- $(data).each(function () {
- self.addSelectedChoice(this);
- });
- self.postprocessResults();
- },
-
- // multi
- tokenize: function() {
- var input = this.search.val();
- input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
- if (input != null && input != undefined) {
- this.search.val(input);
- if (input.length > 0) {
- this.open();
- }
- }
-
- },
-
- // multi
- onSelect: function (data, options) {
-
- if (!this.triggerSelect(data)) { return; }
-
- this.addSelectedChoice(data);
-
- this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
-
- if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
-
- if (this.opts.closeOnSelect) {
- this.close();
- this.search.width(10);
- } else {
- if (this.countSelectableResults()>0) {
- this.search.width(10);
- this.resizeSearch();
- if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
- // if we reached max selection size repaint the results so choices
- // are replaced with the max selection reached message
- this.updateResults(true);
- }
- this.positionDropdown();
- } else {
- // if nothing left to select close
- this.close();
- this.search.width(10);
- }
- }
-
- // since its not possible to select an element that has already been
- // added we do not need to check if this is a new element before firing change
- this.triggerChange({ added: data });
-
- if (!options || !options.noFocus)
- this.focusSearch();
- },
-
- // multi
- cancel: function () {
- this.close();
- this.focusSearch();
- },
-
- addSelectedChoice: function (data) {
- var enableChoice = !data.locked,
- enabledItem = $(
- "<li class='select2-search-choice'>" +
- " <div></div>" +
- " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
- "</li>"),
- disabledItem = $(
- "<li class='select2-search-choice select2-locked'>" +
- "<div></div>" +
- "</li>");
- var choice = enableChoice ? enabledItem : disabledItem,
- id = this.id(data),
- val = this.getVal(),
- formatted,
- cssClass;
-
- formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
- if (formatted != undefined) {
- choice.find("div").replaceWith("<div>"+formatted+"</div>");
- }
- cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
- if (cssClass != undefined) {
- choice.addClass(cssClass);
- }
-
- if(enableChoice){
- choice.find(".select2-search-choice-close")
- .on("mousedown", killEvent)
- .on("click dblclick", this.bind(function (e) {
- if (!this.isInterfaceEnabled()) return;
-
- $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
- this.unselect($(e.target));
- this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
- this.close();
- this.focusSearch();
- })).dequeue();
- killEvent(e);
- })).on("focus", this.bind(function () {
- if (!this.isInterfaceEnabled()) return;
- this.container.addClass("select2-container-active");
- this.dropdown.addClass("select2-drop-active");
- }));
- }
-
- choice.data("select2-data", data);
- choice.insertBefore(this.searchContainer);
-
- val.push(id);
- this.setVal(val);
- },
-
- // multi
- unselect: function (selected) {
- var val = this.getVal(),
- data,
- index;
- selected = selected.closest(".select2-search-choice");
-
- if (selected.length === 0) {
- throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
- }
-
- data = selected.data("select2-data");
-
- if (!data) {
- // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
- // and invoked on an element already removed
- return;
- }
-
- while((index = indexOf(this.id(data), val)) >= 0) {
- val.splice(index, 1);
- this.setVal(val);
- if (this.select) this.postprocessResults();
- }
-
- var evt = $.Event("select2-removing");
- evt.val = this.id(data);
- evt.choice = data;
- this.opts.element.trigger(evt);
-
- if (evt.isDefaultPrevented()) {
- return;
- }
-
- selected.remove();
-
- this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
- this.triggerChange({ removed: data });
- },
-
- // multi
- postprocessResults: function (data, initial, noHighlightUpdate) {
- var val = this.getVal(),
- choices = this.results.find(".select2-result"),
- compound = this.results.find(".select2-result-with-children"),
- self = this;
-
- choices.each2(function (i, choice) {
- var id = self.id(choice.data("select2-data"));
- if (indexOf(id, val) >= 0) {
- choice.addClass("select2-selected");
- // mark all children of the selected parent as selected
- choice.find(".select2-result-selectable").addClass("select2-selected");
- }
- });
-
- compound.each2(function(i, choice) {
- // hide an optgroup if it doesnt have any selectable children
- if (!choice.is('.select2-result-selectable')
- && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
- choice.addClass("select2-selected");
- }
- });
-
- if (this.highlight() == -1 && noHighlightUpdate !== false){
- self.highlight(0);
- }
-
- //If all results are chosen render formatNoMAtches
- if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
- if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
- if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
- this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
- }
- }
- }
-
- },
-
- // multi
- getMaxSearchWidth: function() {
- return this.selection.width() - getSideBorderPadding(this.search);
- },
-
- // multi
- resizeSearch: function () {
- var minimumWidth, left, maxWidth, containerLeft, searchWidth,
- sideBorderPadding = getSideBorderPadding(this.search);
-
- minimumWidth = measureTextWidth(this.search) + 10;
-
- left = this.search.offset().left;
-
- maxWidth = this.selection.width();
- containerLeft = this.selection.offset().left;
-
- searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
-
- if (searchWidth < minimumWidth) {
- searchWidth = maxWidth - sideBorderPadding;
- }
-
- if (searchWidth < 40) {
- searchWidth = maxWidth - sideBorderPadding;
- }
-
- if (searchWidth <= 0) {
- searchWidth = minimumWidth;
- }
-
- this.search.width(Math.floor(searchWidth));
- },
-
- // multi
- getVal: function () {
- var val;
- if (this.select) {
- val = this.select.val();
- return val === null ? [] : val;
- } else {
- val = this.opts.element.val();
- return splitVal(val, this.opts.separator);
- }
- },
-
- // multi
- setVal: function (val) {
- var unique;
- if (this.select) {
- this.select.val(val);
- } else {
- unique = [];
- // filter out duplicates
- $(val).each(function () {
- if (indexOf(this, unique) < 0) unique.push(this);
- });
- this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
- }
- },
-
- // multi
- buildChangeDetails: function (old, current) {
- var current = current.slice(0),
- old = old.slice(0);
-
- // remove intersection from each array
- for (var i = 0; i < current.length; i++) {
- for (var j = 0; j < old.length; j++) {
- if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
- current.splice(i, 1);
- if(i>0){
- i--;
- }
- old.splice(j, 1);
- j--;
- }
- }
- }
-
- return {added: current, removed: old};
- },
-
-
- // multi
- val: function (val, triggerChange) {
- var oldData, self=this;
-
- if (arguments.length === 0) {
- return this.getVal();
- }
-
- oldData=this.data();
- if (!oldData.length) oldData=[];
-
- // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
- if (!val && val !== 0) {
- this.opts.element.val("");
- this.updateSelection([]);
- this.clearSearch();
- if (triggerChange) {
- this.triggerChange({added: this.data(), removed: oldData});
- }
- return;
- }
-
- // val is a list of ids
- this.setVal(val);
-
- if (this.select) {
- this.opts.initSelection(this.select, this.bind(this.updateSelection));
- if (triggerChange) {
- this.triggerChange(this.buildChangeDetails(oldData, this.data()));
- }
- } else {
- if (this.opts.initSelection === undefined) {
- throw new Error("val() cannot be called if initSelection() is not defined");
- }
-
- this.opts.initSelection(this.opts.element, function(data){
- var ids=$.map(data, self.id);
- self.setVal(ids);
- self.updateSelection(data);
- self.clearSearch();
- if (triggerChange) {
- self.triggerChange(self.buildChangeDetails(oldData, self.data()));
- }
- });
- }
- this.clearSearch();
- },
-
- // multi
- onSortStart: function() {
- if (this.select) {
- throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
- }
-
- // collapse search field into 0 width so its container can be collapsed as well
- this.search.width(0);
- // hide the container
- this.searchContainer.hide();
- },
-
- // multi
- onSortEnd:function() {
-
- var val=[], self=this;
-
- // show search and move it to the end of the list
- this.searchContainer.show();
- // make sure the search container is the last item in the list
- this.searchContainer.appendTo(this.searchContainer.parent());
- // since we collapsed the width in dragStarted, we resize it here
- this.resizeSearch();
-
- // update selection
- this.selection.find(".select2-search-choice").each(function() {
- val.push(self.opts.id($(this).data("select2-data")));
- });
- this.setVal(val);
- this.triggerChange();
- },
-
- // multi
- data: function(values, triggerChange) {
- var self=this, ids, old;
- if (arguments.length === 0) {
- return this.selection
- .find(".select2-search-choice")
- .map(function() { return $(this).data("select2-data"); })
- .get();
- } else {
- old = this.data();
- if (!values) { values = []; }
- ids = $.map(values, function(e) { return self.opts.id(e); });
- this.setVal(ids);
- this.updateSelection(values);
- this.clearSearch();
- if (triggerChange) {
- this.triggerChange(this.buildChangeDetails(old, this.data()));
- }
- }
- }
- });
-
- $.fn.select2 = function () {
-
- var args = Array.prototype.slice.call(arguments, 0),
- opts,
- select2,
- method, value, multiple,
- allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
- valueMethods = ["opened", "isFocused", "container", "dropdown"],
- propertyMethods = ["val", "data"],
- methodsMap = { search: "externalSearch" };
-
- this.each(function () {
- if (args.length === 0 || typeof(args[0]) === "object") {
- opts = args.length === 0 ? {} : $.extend({}, args[0]);
- opts.element = $(this);
-
- if (opts.element.get(0).tagName.toLowerCase() === "select") {
- multiple = opts.element.prop("multiple");
- } else {
- multiple = opts.multiple || false;
- if ("tags" in opts) {opts.multiple = multiple = true;}
- }
-
- select2 = multiple ? new MultiSelect2() : new SingleSelect2();
- select2.init(opts);
- } else if (typeof(args[0]) === "string") {
-
- if (indexOf(args[0], allowedMethods) < 0) {
- throw "Unknown method: " + args[0];
- }
-
- value = undefined;
- select2 = $(this).data("select2");
- if (select2 === undefined) return;
-
- method=args[0];
-
- if (method === "container") {
- value = select2.container;
- } else if (method === "dropdown") {
- value = select2.dropdown;
- } else {
- if (methodsMap[method]) method = methodsMap[method];
-
- value = select2[method].apply(select2, args.slice(1));
- }
- if (indexOf(args[0], valueMethods) >= 0
- || (indexOf(args[0], propertyMethods) && args.length == 1)) {
- return false; // abort the iteration, ready to return first matched value
- }
- } else {
- throw "Invalid arguments to select2 plugin: " + args;
- }
- });
- return (value === undefined) ? this : value;
- };
-
- // plugin defaults, accessible to users
- $.fn.select2.defaults = {
- width: "copy",
- loadMorePadding: 0,
- closeOnSelect: true,
- openOnEnter: true,
- containerCss: {},
- dropdownCss: {},
- containerCssClass: "",
- dropdownCssClass: "",
- formatResult: function(result, container, query, escapeMarkup) {
- var markup=[];
- markMatch(result.text, query.term, markup, escapeMarkup);
- return markup.join("");
- },
- formatSelection: function (data, container, escapeMarkup) {
- return data ? escapeMarkup(data.text) : undefined;
- },
- sortResults: function (results, container, query) {
- return results;
- },
- formatResultCssClass: function(data) {return undefined;},
- formatSelectionCssClass: function(data, container) {return undefined;},
- formatNoMatches: function () { return "No matches found"; },
- formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
- formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
- formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
- formatLoadMore: function (pageNumber) { return "Loading more results..."; },
- formatSearching: function () { return "Searching..."; },
- minimumResultsForSearch: 0,
- minimumInputLength: 0,
- maximumInputLength: null,
- maximumSelectionSize: 0,
- id: function (e) { return e.id; },
- matcher: function(term, text) {
- return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
- },
- separator: ",",
- tokenSeparators: [],
- tokenizer: defaultTokenizer,
- escapeMarkup: defaultEscapeMarkup,
- blurOnChange: false,
- selectOnBlur: false,
- adaptContainerCssClass: function(c) { return c; },
- adaptDropdownCssClass: function(c) { return null; },
- nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }
- };
-
- $.fn.select2.ajaxDefaults = {
- transport: $.ajax,
- params: {
- type: "GET",
- cache: false,
- dataType: "json"
- }
- };
-
- // exports
- window.Select2 = {
- query: {
- ajax: ajax,
- local: local,
- tags: tags
- }, util: {
- debounce: debounce,
- markMatch: markMatch,
- escapeMarkup: defaultEscapeMarkup,
- stripDiacritics: stripDiacritics
- }, "class": {
- "abstract": AbstractSelect2,
- "single": SingleSelect2,
- "multi": MultiSelect2
- }
- };
-
-}(jQuery));
diff --git a/data/loader.js b/data/loader.js
index 52d063773..a7af0b871 100644
--- a/data/loader.js
+++ b/data/loader.js
@@ -72,7 +72,7 @@ requirejs.config({
jqueryuiautocomplete: 'libs/jqueryui/jquery.ui.autocomplete',
jqueryuidatepicker: 'libs/jqueryui/jquery.ui.datepicker',
- bootstrap: 'libs/bootstrap/js/bootstrap',
+ bootstrap: 'libs/bootstrap/js/bootstrap.min',
bootstrap3xeditable: 'libs/bootstrap3xeditable/js/bootstrap-editable',
jquerysimplecolorpicker:'libs/jquery-simplecolorpicker/jquery.simplecolorpicker',
jquerylayout: 'libs/jquerylayout/jquery.layout-latest',
@@ -81,8 +81,8 @@ requirejs.config({
dropbox: 'libs/dropbox/dropbox.0.10.2',
i18next: 'libs/i18next/i18next.amd.withJQuery-1.7.1',
jqueryhotkeys: 'libs/jqueryhotkeys/jquery.hotkeys',
- select2: 'libs/select2/select2',
- hammerjs: 'libs/hammerjs/jquery.hammer',
+ select2: 'libs/select2/select2.min',
+ hammerjs: 'libs/hammerjs/jquery.hammer.min',
handlebarsjs: 'libs/handlebars.js/handlebars-v1.1.2',
tscore: 'js/core.api',
diff --git a/data/manifest.json b/data/manifest.json
index 53f6c011e..e621c8d51 100644
--- a/data/manifest.json
+++ b/data/manifest.json
@@ -1,6 +1,6 @@
{
"name": "TagSpaces",
- "version": "1.7.1845",
+ "version": "1.7.1850",
"manifest_version": 2,
"description": "An offline file browser/manager for your local files, with support of tagging and editing.",
"icons": {
diff --git a/data/mozilla/update.rdf b/data/mozilla/update.rdf
index 3841bb061..a5dec570b 100644
--- a/data/mozilla/update.rdf
+++ b/data/mozilla/update.rdf
@@ -7,13 +7,13 @@
<r:Seq>
<r:li>
<r:Description>
- <version>1.7.1845</version>
+ <version>1.7.1849</version>
<targetApplication>
<r:Description>
<id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</id>
<minVersion>20.0</minVersion>
<maxVersion>*</maxVersion>
- <updateLink>http://tagspaces.com/releases/1.7/tagspaces.1.7.1845.xpi</updateLink>
+ <updateLink>http://tagspaces.com/releases/1.7/tagspaces.1.7.1849.xpi</updateLink>
<updateInfoURL>http://tagspaces.com/releases/1.7/updateInfo.xml</updateInfoURL>
</r:Description>
</targetApplication>
diff --git a/package.json b/package.json
index 20bf351d5..e06e7946f 100644
--- a/package.json
+++ b/package.json
@@ -2,8 +2,8 @@
"name": "tagspaces",
"license": "AGPL 3.0",
"author": "Ugg Rock",
- "version": "1.7.1845",
- "build": "1845",
+ "version": "1.7.1850",
+ "build": "1850",
"fullName": "TagSpaces",
"id": "jid1-FBaMKxTifTSahQ",
"lib": "data/mozilla",