spec/dummy_app/tmp/cache/assets/development/sprockets/cffd775d018f68ce5dba1ee0d951a994 in basepack-1.0.0.pre.0 vs spec/dummy_app/tmp/cache/assets/development/sprockets/cffd775d018f68ce5dba1ee0d951a994 in basepack-1.0.0
- old
+ new
@@ -1,8 +1,8 @@
{I"
class:ETI"BundledAsset; FI"logical_path; TI"application.js; TI"
pathname; TI"0$root/app/assets/javascripts/application.js; FI"content_type; TI"application/javascript; TI"
-mtime; Tl+¢QŒSI"length; Ti¼©I"digest; TI"%ca7ab405bb70cbd08e680821a63dad75; FI"source; TI"¼©/*!
+mtime; Tl+ÝlºSI"length; TiéuI"digest; TI"%e88009135b14b60d77ec625b9c16f2be; FI"source; TI"éu/*!
* jQuery JavaScript Library v1.11.0
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
@@ -26501,37 +26501,5411 @@
-/*! jQuery Fancytree Plugin - v2.0.0-5 - 2014-01-04 16:01
- * https://github.com/mar10/fancytree
- * Copyright (c) 2014 Martin Wendt; Licensed MIT */
+/*!
+ * jquery.fancytree.js
+ * Dynamic tree view control, with support for lazy loading of branches.
+ * https://github.com/mar10/fancytree/
+ *
+ * Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de)
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+/** Core Fancytree module.
+ */
-!function(a,b,c,d){"use strict";function e(b){b=b||"",a.error("Not implemented: "+b)}function f(b,c){b||(c=c?": "+c:"",a.error("Assertion failed"+c))}function g(a,c){var d,e,f=b.console?b.console[a]:null;if(f)if(f.apply)f.apply(b.console,c);else{for(e="",d=0;d<c.length;d++)e+=c[d];f(e)}}function h(b){var c,d,e,f=a.map(a.trim(b).split("."),function(a){return parseInt(a,10)}),g=a.map(Array.prototype.slice.call(arguments,1),function(a){return parseInt(a,10)});for(c=0;c<g.length;c++)if(d=f[c]||0,e=g[c]||0,d!==e)return d>e;return!0}function i(a,b,c,d,e){var f=function(){var c=b[a],f=d[a],g=b.ext[e],h=function(){return c.apply(b,arguments)};return function(){var a=b._local,c=b._super;try{return b._local=g,b._super=h,f.apply(b,arguments)}finally{b._local=a,b._super=c}}}();return f}function j(b,c,d,e){for(var f in d)"function"==typeof d[f]?"function"==typeof b[f]?b[f]=i(f,b,c,d,e):"_"===f.charAt(0)?b.ext[e][f]=i(f,b,c,d,e):a.error("Could not override tree."+f+". Use prefix '_' to create tree."+e+"._"+f):"options"!==f&&(b.ext[e][f]=d[f])}function k(b,c){return b===d?a.Deferred(function(){this.resolve()}).promise():a.Deferred(function(){this.resolveWith(b,c)}).promise()}function l(b,c){return b===d?a.Deferred(function(){this.reject()}).promise():a.Deferred(function(){this.rejectWith(b,c)}).promise()}function m(a,b){return function(){a.resolveWith(b)}}function n(a){return a=a.toLowerCase(),function(b){return b.title.toLowerCase().indexOf(a)>=0}}function o(b,c){var d,e,g,h;for(this.parent=b,this.tree=b.tree,this.ul=null,this.li=null,this.isStatusNode=!1,this.data={},d=0,e=u.length;e>d;d++)g=u[d],this[g]=c[g];c.data&&a.extend(this.data,c.data);for(g in c)v[g]||a.isFunction(c[g])||w[g]||(this.data[g]=c[g]);null==this.key&&(this.key="_"+r._nextNodeKey++),c.active&&(f(null===this.tree.activeNode,"only one active node allowed"),this.tree.activeNode=this),this.children=null,h=c.children,h&&h.length&&this._setChildren(h)}function p(b){this.widget=b,this.$div=b.element,this.options=b.options,this.ext={},this.data={},this._id=a.ui.fancytree._nextId++,this._ns=".fancytree-"+this._id,this.activeNode=null,this.focusNode=null,this._hasFocus=null,this.lastSelectedNode=null,this.systemFocusElement=null,this.statusClassPropName="span",this.ariaPropName="li",this.nodeContainerAttrName="li",this.$div.find(">ul.fancytree-container").remove();var c,d={tree:this};this.rootNode=new o(d,{title:"root",key:"root_"+this._id,children:null}),this.rootNode.parent=null,c=a("<ul>",{"class":"ui-fancytree fancytree-container"}).appendTo(this.$div),this.$container=c,this.rootNode.ul=c[0],null==this.options.debugLevel&&(this.options.debugLevel=r.debugLevel),this.$container.attr("tabindex",this.options.tabbable?"0":"-1"),this.options.aria&&this.$container.attr("role","tree").attr("aria-multiselectable",!0)}if(a.ui.fancytree&&a.ui.fancytree.version)return a.ui.fancytree.warn("Fancytree: ignored duplicate include"),void 0;var q,r=null,s="active expanded focus folder lazy selected unselectable".split(" "),t={},u="expanded extraClasses folder hideCheckbox key lazy selected title tooltip unselectable".split(" "),v={},w={active:!0,children:!0,data:!0,focus:!0};for(q=0;q<s.length;q++)t[s[q]]=!0;for(q=0;q<u.length;q++)v[u[q]]=!0;o.prototype={_findDirectChild:function(a){var b,c,d=this.children;if(d)if("string"==typeof a){for(b=0,c=d.length;c>b;b++)if(d[b].key===a)return d[b]}else{if("number"==typeof a)return this.children[a];if(a.parent===this)return a}return null},_setChildren:function(a){f(a&&(!this.children||0===this.children.length),"only init supported"),this.children=[];for(var b=0,c=a.length;c>b;b++)this.children.push(new o(this,a[b]))},addChildren:function(b,c){var d,e,g,h=null,i=[];for(a.isPlainObject(b)&&(b=[b]),this.children||(this.children=[]),d=0,e=b.length;e>d;d++)i.push(new o(this,b[d]));return h=i[0],null==c?this.children=this.children.concat(i):(c=this._findDirectChild(c),g=a.inArray(c,this.children),f(g>=0,"insertBefore must be an existing child"),this.children.splice.apply(this.children,[g,0].concat(i))),(!this.parent||this.parent.ul||this.tr)&&this.render(),3===this.tree.options.selectMode&&this.fixSelection3FromEndNodes(),h},addNode:function(a,b){switch((b===d||"over"===b)&&(b="child"),b){case"after":return this.getParent().addChildren(a,this.getNextSibling());case"before":return this.getParent().addChildren(a,this);case"child":case"over":return this.addChildren(a)}f(!1,"Invalid mode: "+b)},applyPatch:function(b){if(null===b)return this.remove(),k(this);var c,d,e,f={children:!0,expanded:!0,parent:!0};for(c in b)e=b[c],f[c]||a.isFunction(e)||(v[c]?this[c]=e:this.data[c]=e);return b.hasOwnProperty("children")&&(this.removeChildren(),b.children&&this._setChildren(b.children)),this.isVisible()&&(this.renderTitle(),this.renderStatus()),d=b.hasOwnProperty("expanded")?this.setExpanded(b.expanded):k(this)},collapseSiblings:function(){return this.tree._callHook("nodeCollapseSiblings",this)},copyTo:function(a,b,c){return a.addNode(this.toDict(!0,c),b)},countChildren:function(a){var b,c,d,e=this.children;if(!e)return 0;if(d=e.length,a!==!1)for(b=0,c=d;c>b;b++)d+=e[b].countChildren();return d},debug:function(){this.tree.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),g("debug",arguments))},discard:function(){return this.lazy&&a.isArray(this.children)?(this.removeChildren(),this.setExpanded(!1)):void 0},findAll:function(b){b=a.isFunction(b)?b:n(b);var c=[];return this.visit(function(a){b(a)&&c.push(a)}),c},findFirst:function(b){b=a.isFunction(b)?b:n(b);var c=null;return this.visit(function(a){return b(a)?(c=a,!1):void 0}),c},_changeSelectStatusAttrs:function(a){var b=!1;switch(a){case!1:b=this.selected||this.partsel,this.selected=!1,this.partsel=!1;break;case!0:b=!this.selected||!this.partsel,this.selected=!0,this.partsel=!0;break;case d:b=this.selected||!this.partsel,this.selected=!1,this.partsel=!0;break;default:f(!1,"invalid state: "+a)}return this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()",a,b),b&&this.renderStatus(),b},fixSelection3AfterClick:function(){var a=this.isSelected();this.visit(function(b){b._changeSelectStatusAttrs(a)}),this.fixSelection3FromEndNodes()},fixSelection3FromEndNodes:function(){function a(b){var c,e,f,g,h,i,j,k=b.children;if(k){for(i=!0,j=!1,c=0,e=k.length;e>c;c++)f=k[c],g=a(f),g!==!1&&(j=!0),g!==!0&&(i=!1);h=i?!0:j?d:!1}else h=!!b.selected;return b._changeSelectStatusAttrs(h),h}f(3===this.tree.options.selectMode,"expected selectMode 3"),a(this),this.visitParents(function(a){var b,c,e,f,g=a.children,h=!0,i=!1;for(b=0,c=g.length;c>b;b++)e=g[b],(e.selected||e.partsel)&&(i=!0),e.unselectable||e.selected||(h=!1);f=h?!0:i?d:!1,a._changeSelectStatusAttrs(f)})},fromDict:function(b){for(var c in b)v[c]?this[c]=b[c]:"data"===c?a.extend(this.data,b.data):a.isFunction(b[c])||w[c]||(this.data[c]=b[c]);b.children?(this.removeChildren(),this.addChildren(b.children)):this.renderTitle()},getChildren:function(){return this.hasChildren()===d?d:this.children},getFirstChild:function(){return this.children?this.children[0]:null},getIndex:function(){return a.inArray(this,this.parent.children)},getIndexHier:function(b){b=b||".";var c=[];return a.each(this.getParentList(!1,!0),function(a,b){c.push(b.getIndex()+1)}),c.join(b)},getKeyPath:function(a){var b=[],c=this.tree.options.keyPathSeparator;return this.visitParents(function(a){a.parent&&b.unshift(a.key)},!a),c+b.join(c)},getLastChild:function(){return this.children?this.children[this.children.length-1]:null},getLevel:function(){for(var a=0,b=this.parent;b;)a++,b=b.parent;return a},getNextSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=0,b=c.length-1;b>a;a++)if(c[a]===this)return c[a+1]}return null},getParent:function(){return this.parent},getParentList:function(a,b){for(var c=[],d=b?this:this.parent;d;)(a||d.parent)&&c.unshift(d),d=d.parent;return c},getPrevSibling:function(){if(this.parent){var a,b,c=this.parent.children;for(a=1,b=c.length;b>a;a++)if(c[a]===this)return c[a-1]}return null},hasChildren:function(){return this.lazy?null==this.children?d:0===this.children.length?!1:1===this.children.length&&this.children[0].isStatusNode?d:!0:!!this.children},hasFocus:function(){return this.tree.hasFocus()&&this.tree.focusNode===this},isActive:function(){return this.tree.activeNode===this},isChildOf:function(a){return this.parent&&this.parent===a},isDescendantOf:function(a){if(!a||a.tree!==this.tree)return!1;for(var b=this.parent;b;){if(b===a)return!0;b=b.parent}return!1},isExpanded:function(){return!!this.expanded},isFirstSibling:function(){var a=this.parent;return!a||a.children[0]===this},isFolder:function(){return!!this.folder},isLastSibling:function(){var a=this.parent;return!a||a.children[a.children.length-1]===this},isLazy:function(){return!!this.lazy},isLoading:function(){e()},isRoot:function(){return this.tree.rootNode===this},isSelected:function(){return!!this.selected},isVisible:function(){var a,b,c=this.getParentList(!1,!1);for(a=0,b=c.length;b>a;a++)if(!c[a].expanded)return!1;return!0},makeVisible:function(){var a,b,c=this.getParentList(!1,!1);for(a=0,b=c.length;b>a;a++)c[a].setExpanded(!0)},moveTo:function(b,c,e){(c===d||"over"===c)&&(c="child");var g,h=this.parent,i="child"===c?b:b.parent;if(this!==b){if(!this.parent)throw"Cannot move system root";if(i.isDescendantOf(this))throw"Cannot move a node to it's own descendant";if(1===this.parent.children.length?(this.parent.children=this.parent.lazy?[]:null,this.parent.expanded=!1):(g=a.inArray(this,this.parent.children),f(g>=0),this.parent.children.splice(g,1)),this.parent=i,i.hasChildren())switch(c){case"child":i.children.push(this);break;case"before":g=a.inArray(b,i.children),f(g>=0),i.children.splice(g,0,this);break;case"after":g=a.inArray(b,i.children),f(g>=0),i.children.splice(g+1,0,this);break;default:throw"Invalid mode "+c}else i.children=[this];e&&b.visit(e,!0),this.tree!==b.tree&&(this.warn("Cross-tree moveTo is experimantal!"),this.visit(function(a){a.tree=b.tree},!0)),i.expanded||h.ul.removeChild(this.li),h.isDescendantOf(i)||h.render(),i.isDescendantOf(h)||i===h||i.render()}},navigate:function(b,c){function d(a){return a?(a.makeVisible(),c===!1?a.setFocus():a.setActive()):void 0}var e,f,g=!0,h=a.ui.keyCode,i=null;switch(b){case h.BACKSPACE:this.parent&&this.parent.parent&&d(this.parent);break;case h.LEFT:this.expanded?(this.setExpanded(!1),d(this)):this.parent&&this.parent.parent&&d(this.parent);break;case h.RIGHT:this.expanded||!this.children&&!this.lazy?this.children&&this.children.length&&d(this.children[0]):(this.setExpanded(),d(this));break;case h.UP:for(i=this.getPrevSibling();i&&i.expanded&&i.children&&i.children.length;)i=i.children[i.children.length-1];!i&&this.parent&&this.parent.parent&&(i=this.parent),d(i);break;case h.DOWN:if(this.expanded&&this.children&&this.children.length)i=this.children[0];else for(f=this.getParentList(!1,!0),e=f.length-1;e>=0&&!(i=f[e].getNextSibling());e--);d(i);break;default:g=!1}},lazyLoad:function(b){(b||this.hasChildren()===d)&&this.discard(),f(!a.isArray(this.children));var c=this.tree._triggerNodeEvent("lazyload",this);return f("boolean"!=typeof c,"lazyload event must return source in data.result"),this.tree._callHook("nodeLoadChildren",this,c)},render:function(a,b){return this.tree._callHook("nodeRender",this,a,b)},renderTitle:function(){return this.tree._callHook("nodeRenderTitle",this)},renderStatus:function(){return this.tree._callHook("nodeRenderStatus",this)},remove:function(){return this.parent.removeChild(this)},removeChild:function(a){return this.tree._callHook("nodeRemoveChild",this,a)},removeChildren:function(){return this.tree._callHook("nodeRemoveChildren",this)},scheduleAction:function(a,b){this.tree.timer&&clearTimeout(this.tree.timer),this.tree.timer=null;var c=this;switch(a){case"cancel":break;case"expand":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger expand"),c.setExpanded(!0)},b);break;case"activate":this.tree.timer=setTimeout(function(){c.tree.debug("setTimeout: trigger activate"),c.setActive(!0)},b);break;default:throw"Invalid mode "+a}},scrollIntoView:function(b,c){b=b===!0?{duration:200,queue:!1}:b;var d,e=new a.Deferred,f=a(this.span).position().top,g=a(this.span).height(),h=this.tree.$container,i=h[0].scrollTop,j=Math.max(0,h.innerHeight()-h[0].clientHeight),k=h.height()-j,l=null;return 0>f?l=i+f:f+g>k&&(l=i+f-k+g,c&&(d=c?a(c.span).position().top:0,f-d>k&&(l=i+f))),null!==l?b?h.animate({scrollTop:l},b):(h[0].scrollTop=l,e.resolveWith(this)):e.resolveWith(this),e.promise()},setActive:function(a){return this.tree._callHook("nodeSetActive",this,a)},setExpanded:function(a){return this.tree._callHook("nodeSetExpanded",this,a)},setFocus:function(a){return this.tree._callHook("nodeSetFocus",this,a)},setSelected:function(a){return this.tree._callHook("nodeSetSelected",this,a)},setTitle:function(a){this.title=a,this.renderTitle()},sortChildren:function(a,b){var c,d,e=this.children;if(e){if(a=a||function(a,b){var c=a.title.toLowerCase(),d=b.title.toLowerCase();return c===d?0:c>d?1:-1},e.sort(a),b)for(c=0,d=e.length;d>c;c++)e[c].children&&e[c].sortChildren(a,"$norender$");"$norender$"!==b&&this.render()}},toDict:function(b,c){var d,e,f,g={},h=this;if(a.each(u,function(a,b){(h[b]||h[b]===!1)&&(g[b]=h[b])}),a.isEmptyObject(this.data)||(g.data=a.extend({},this.data),a.isEmptyObject(g.data)&&delete g.data),c&&c(g),b&&this.hasChildren())for(g.children=[],d=0,e=this.children.length;e>d;d++)f=this.children[d],f.isStatusNode||g.children.push(f.toDict(!0,c));return g},toggleExpanded:function(){return this.tree._callHook("nodeToggleExpanded",this)},toggleSelected:function(){return this.tree._callHook("nodeToggleSelected",this)},toString:function(){return"<FancytreeNode(#"+this.key+", '"+this.title+"')>"},visit:function(a,b){var c,d,e=!0,f=this.children;if(b===!0&&(e=a(this),e===!1||"skip"===e))return e;if(f)for(c=0,d=f.length;d>c&&(e=f[c].visit(a,!0),e!==!1);c++);return e},visitParents:function(a,b){if(b&&a(this)===!1)return!1;for(var c=this.parent;c;){if(a(c)===!1)return!1;c=c.parent}return!0},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),g("warn",arguments)}},p.prototype={_makeHookContext:function(b,c,e){var f,g;return b.node!==d?(c&&b.originalEvent!==c&&a.error("invalid args"),f=b):b.tree?(g=b.tree,f={node:b,tree:g,widget:g.widget,options:g.widget.options,originalEvent:c}):b.widget?f={node:null,tree:b,widget:b.widget,options:b.widget.options,originalEvent:c}:a.error("invalid args"),e&&a.extend(f,e),f},_callHook:function(b,c){var d=this._makeHookContext(c),e=this[b],f=Array.prototype.slice.call(arguments,2);return a.isFunction(e)||a.error("_callHook('"+b+"') is not a function"),f.unshift(d),e.apply(this,f)},activateKey:function(a){var b=this.getNodeByKey(a);return b?b.setActive():this.activeNode&&this.activeNode.setActive(!1),b},applyPatch:function(b){var c,d,e,g,h,i,j=b.length,k=[];for(d=0;j>d;d++)e=b[d],f(2===e.length,"patchList must be an array of length-2-arrays"),g=e[0],h=e[1],i=null===g?this.rootNode:this.getNodeByKey(g),i?(c=new a.Deferred,k.push(c),i.applyPatch(h).always(m(c,i))):this.warn("could not find node with key '"+g+"'");return a.when.apply(a,k).promise()},count:function(){return this.rootNode.countChildren()},debug:function(){this.options.debugLevel>=2&&(Array.prototype.unshift.call(arguments,this.toString()),g("debug",arguments))},generateFormElements:function(b,c){var d,e=b!==!1?"ft_"+this._id:b,f=c!==!1?"ft_"+this._id+"_active":c,g="fancytree_result_"+this._id,h=this.$container.find("div#"+g);h.length?h.empty():h=a("<div>",{id:g}).hide().appendTo(this.$container),e&&(d=this.getSelectedNodes(3===this.options.selectMode),a.each(d,function(b,c){h.append(a("<input>",{type:"checkbox",name:e,value:c.key,checked:!0}))})),f&&this.activeNode&&h.append(a("<input>",{type:"radio",name:f,value:this.activeNode.key,checked:!0}))},getActiveNode:function(){return this.activeNode},getFirstChild:function(){return this.rootNode.getFirstChild()},getFocusNode:function(){return this.focusNode},getNodeByKey:function(a,b){var d,e;return!b&&(d=c.getElementById(this.options.idPrefix+a))?d.ftnode?d.ftnode:null:(b=b||this.rootNode,e=null,b.visit(function(b){return b.key===a?(e=b,!1):void 0},!0),e)},getSelectedNodes:function(a){var b=[];return this.rootNode.visit(function(c){return c.selected&&(b.push(c),a===!0)?"skip":void 0}),b},hasFocus:function(){return!!this._hasFocus},info:function(){this.options.debugLevel>=1&&(Array.prototype.unshift.call(arguments,this.toString()),g("info",arguments))},loadKeyPath:function(b,c,e){function f(a,b,d){c.call(r,b,"loading"),b.lazyLoad().done(function(){r.loadKeyPath.call(r,l[a],c,b).always(m(d,r))}).fail(function(){r.warn("loadKeyPath: error loading: "+a+" (parent: "+p+")"),c.call(r,b,"error"),d.reject()})}var g,h,i,j,k,l,n,o,p=e||this.rootNode,q=this.options.keyPathSeparator,r=this;for(a.isArray(b)||(b=[b]),l={},i=0;i<b.length;i++)for(j=b[i],j.charAt(0)===q&&(j=j.substr(1)),o=j.split(q);o.length;){if(k=o.shift(),n=p._findDirectChild(k),!n){this.warn("loadKeyPath: key not found: "+k+" (parent: "+p+")"),c.call(this,k,"error");break}if(0===o.length){c.call(this,n,"ok");break}if(n.lazy&&n.hasChildren()===d){c.call(this,n,"loaded"),l[k]?l[k].push(o.join(q)):l[k]=[o.join(q)];break}c.call(this,n,"loaded"),p=n}g=[];for(k in l)n=p._findDirectChild(k),h=new a.Deferred,g.push(h),f(k,n,h);return a.when.apply(a,g).promise()},nodeClick:function(a){var b,c,d=a.originalEvent,e=a.targetType,f=a.node;if("expander"===e)this._callHook("nodeToggleExpanded",a);else if("checkbox"===e)this._callHook("nodeToggleSelected",a),this._callHook("nodeSetFocus",a,!0);else{if(c=!1,b=!0,f.folder)switch(a.options.clickFolderMode){case 2:c=!0,b=!1;break;case 3:b=!0,c=!0}b&&(this.nodeSetFocus(a),this._callHook("nodeSetActive",a,!0)),c&&this._callHook("nodeToggleExpanded",a)}"a"===d.target.localName&&"fancytree-title"===d.target.className&&d.preventDefault()},nodeCollapseSiblings:function(a){var b,c,d,e=a.node;if(e.parent)for(b=e.parent.children,c=0,d=b.length;d>c;c++)b[c]!==e&&b[c].expanded&&this._callHook("nodeSetExpanded",b[c],!1)},nodeDblclick:function(a){"title"===a.targetType&&4===a.options.clickFolderMode&&this._callHook("nodeToggleExpanded",a),"title"===a.targetType&&a.originalEvent.preventDefault()},nodeKeydown:function(b){var c,d=b.originalEvent,e=b.node,f=b.tree,g=b.options,h=!0,i=!(d.ctrlKey||!g.autoActivate),j=a.ui.keyCode;switch(e||(this.rootNode.getFirstChild().setFocus(),e=b.node=this.focusNode,e.debug("Keydown force focus on first node")),d.which){case j.NUMPAD_ADD:case 187:f.nodeSetExpanded(b,!0);break;case j.NUMPAD_SUBTRACT:case 189:f.nodeSetExpanded(b,!1);break;case j.SPACE:g.checkbox?f.nodeToggleSelected(b):f.nodeSetActive(b,!0);break;case j.ENTER:f.nodeSetActive(b,!0);break;case j.BACKSPACE:case j.LEFT:case j.RIGHT:case j.UP:case j.DOWN:c=e.navigate(d.which,i);break;default:h=!1}h&&d.preventDefault()},nodeLoadChildren:function(b,c){var d,e,g=b.tree,h=b.node;return a.isFunction(c)&&(c=c()),c.url&&(d=a.extend({},b.options.ajax,c),d.debugDelay?(e=d.debugDelay,a.isArray(e)&&(e=e[0]+Math.random()*(e[1]-e[0])),h.debug("nodeLoadChildren waiting debug delay "+Math.round(e)+"ms"),d.debugDelay=!1,c=a.Deferred(function(b){setTimeout(function(){a.ajax(d).done(function(){b.resolveWith(this,arguments)}).fail(function(){b.rejectWith(this,arguments)})},e)})):c=a.ajax(d),c=c.pipe(function(c){var d;return"string"==typeof c&&a.error("Ajax request returned a string (did you get the JSON dataType wrong?)."),b.options.postProcess?(d=g._triggerNodeEvent("postProcess",b,b.originalEvent,{response:c,dataType:this.dataType}),c=a.isArray(d)?d:c):c&&c.hasOwnProperty("d")&&b.options.enableAspx&&(c="string"==typeof c.d?a.parseJSON(c.d):c.d),c},function(a,b,c){return g._makeHookContext(h,null,{error:a,args:Array.prototype.slice.call(arguments),message:c,details:a.status+": "+c})})),a.isFunction(c.promise)&&(g.nodeSetStatus(b,"loading"),c.done(function(){g.nodeSetStatus(b,"ok")}).fail(function(a){var c;c=a.node&&a.error&&a.message?a:g._makeHookContext(h,null,{error:a,args:Array.prototype.slice.call(arguments),message:a?a.message||a.toString():""}),g._triggerNodeEvent("loaderror",c,null),g.nodeSetStatus(b,"error",c.message,c.details)})),a.when(c).done(function(b){var c;a.isPlainObject(b)&&(f(a.isArray(b.children),"source must contain (or be) an array of children"),f(h.isRoot(),"source may only be an object for root nodes"),c=b,b=b.children,delete c.children,a.extend(g.data,c)),f(a.isArray(b),"expected array of children"),h._setChildren(b),h.parent&&g._triggerNodeEvent("loadChildren",h)})},nodeLoadKeyPath:function(){},nodeMakeVisible:function(a){var b,c,d=a.node.getParentList(!1,!1);for(b=0,c=d.length;c>b;b++)d[b].setExpanded(!0)},nodeRemoveChild:function(b,c){var d,e=b.node,g=b.options,h=a.extend({},b,{node:c}),i=e.children;return r.debug("nodeRemoveChild()",e.toString(),c.toString()),1===i.length?(f(c===i[0]),this.nodeRemoveChildren(b)):(this.activeNode&&(c===this.activeNode||this.activeNode.isDescendantOf(c))&&this.activeNode.setActive(!1),this.focusNode&&(c===this.focusNode||this.focusNode.isDescendantOf(c))&&(this.focusNode=null),this.nodeRemoveMarkup(h),this.nodeRemoveChildren(h),d=a.inArray(c,i),f(d>=0),c.visit(function(a){a.parent=null},!0),g.removeNode&&g.removeNode.call(b.tree,{type:"removeNode"},h),i.splice(d,1),void 0)},nodeRemoveChildMarkup:function(b){var c=b.node;r.debug("nodeRemoveChildMarkup()",c.toString()),c.ul&&(a(c.ul).remove(),c.visit(function(a){a.li=a.ul=null}),c.ul=null)},nodeRemoveChildren:function(b){var c,e=b.node,f=e.children,g=b.options;r.debug("nodeRemoveChildren()",e.toString()),f&&(this.activeNode&&this.activeNode.isDescendantOf(e)&&this.activeNode.setActive(!1),this.focusNode&&this.focusNode.isDescendantOf(e)&&(this.focusNode=null),this.nodeRemoveChildMarkup(b),c=a.extend({},b),e.visit(function(a){a.parent=null,g.removeNode&&(c.node=a,g.removeNode.call(b.tree,{type:"removeNode"},c))}),e.children=d,this.nodeRenderStatus(b))},nodeRemoveMarkup:function(b){var c=b.node;r.debug("nodeRemoveMarkup()",c.toString()),c.li&&(a(c.li).remove(),c.li=null),this.nodeRemoveChildMarkup(b)},nodeRender:function(b,d,e,g,h){var i,j,k,l,m,n,o=b.node,p=b.tree,q=b.options,r=q.aria,s=!1,t=o.parent,u=!t,v=o.children;if(u||t.ul){if(f(u||t.ul,"parent UL must exist"),u||(o.li&&(d||o.li.parentNode!==o.parent.ul)&&(o.li.parentNode!==o.parent.ul&&this.warn("unlink "+o+" (must be child of "+o.parent+")"),this.nodeRemoveMarkup(b)),o.li||(s=!0,o.li=c.createElement("li"),o.li.ftnode=o,o.key&&q.generateIds&&(o.li.id=q.idPrefix+o.key),o.span=c.createElement("span"),o.span.className="fancytree-node",r&&a(o.span).attr("aria-labelledby","ftal_"+o.key),o.li.appendChild(o.span),this.nodeRenderTitle(b),q.createNode&&q.createNode.call(p,{type:"createNode"},b)),q.renderNode&&q.renderNode.call(p,{type:"renderNode"},b)),v){if(u||o.expanded||e===!0){for(o.ul||(o.ul=c.createElement("ul"),(g===!0&&!h||!o.expanded)&&(o.ul.style.display="none"),r&&a(o.ul).attr("role","group"),o.li?o.li.appendChild(o.ul):o.tree.$div.append(o.ul)),l=0,m=v.length;m>l;l++)n=a.extend({},b,{node:v[l]}),this.nodeRender(n,d,e,!1,!0);for(i=o.ul.firstChild,l=0,m=v.length-1;m>l;l++)j=v[l],k=i.ftnode,j!==k?(o.debug("_fixOrder: mismatch at index "+l+": "+j+" != "+k),o.ul.insertBefore(j.li,k.li)):i=i.nextSibling}}else o.ul&&(this.warn("remove child markup for "+o),this.nodeRemoveChildMarkup(b));u||(this.nodeRenderStatus(b),s&&t.ul.appendChild(o.li))}},nodeRenderTitle:function(a,b){var c,e,f,g,h,i=a.node,j=a.tree,k=a.options,l=k.aria,m=i.getLevel(),n=[],o=i.data.icon;b!==d&&(i.title=b),i.span&&(m<k.minExpandLevel?m>1&&(l?n.push("<span role='button' class='fancytree-expander'></span>"):n.push("<span class='fancytree-expander'></span>")):l?n.push("<span role='button' class='fancytree-expander'></span>"):n.push("<span class='fancytree-expander'></span>"),k.checkbox&&i.hideCheckbox!==!0&&!i.isStatusNode&&(l?n.push("<span role='checkbox' class='fancytree-checkbox'></span>"):n.push("<span class='fancytree-checkbox'></span>")),g=l?" role='img'":"",o&&"string"==typeof o?(e="/"===o.charAt(0)?o:k.imagePath+o,n.push("<img src='"+e+"' alt='' />")):i.data.iconclass?n.push("<span "+g+" class='fancytree-custom-icon "+i.data.iconclass+"'></span>"):(o===!0||o!==!1&&k.icons!==!1)&&n.push("<span "+g+" class='fancytree-icon'></span>"),f="",k.renderTitle&&(f=k.renderTitle.call(j,{type:"renderTitle"},a)||""),f||(h=i.tooltip?" title='"+i.tooltip.replace(/\"/g,""")+"'":"",c=l?" id='ftal_"+i.key+"'":"",g=l?" role='treeitem'":"",f="<span "+g+" class='fancytree-title'"+c+h+">"+i.title+"</span>"),n.push(f),i.span.innerHTML=n.join(""))},nodeRenderStatus:function(b){var c=b.node,d=b.tree,e=b.options,f=c.hasChildren(),g=c.isLastSibling(),h=e.aria,i=a(c.span).find(".fancytree-title"),j=e._classNames,k=[],l=c[d.statusClassPropName];l&&(k.push(j.node),d.activeNode===c&&k.push(j.active),d.focusNode===c?(k.push(j.focused),h&&i.attr("aria-activedescendant",!0)):h&&i.removeAttr("aria-activedescendant"),c.expanded?(k.push(j.expanded),h&&i.attr("aria-expanded",!0)):h&&i.removeAttr("aria-expanded"),c.folder&&k.push(j.folder),f!==!1&&k.push(j.hasChildren),g&&k.push(j.lastsib),c.lazy&&null==c.children&&k.push(j.lazy),c.partsel&&k.push(j.partsel),c.selected?(k.push(j.selected),h&&i.attr("aria-selected",!0)):h&&i.attr("aria-selected",!1),c.extraClasses&&k.push(c.extraClasses),f===!1?k.push(j.combinedExpanderPrefix+"n"+(g?"l":"")):k.push(j.combinedExpanderPrefix+(c.expanded?"e":"c")+(c.lazy&&null==c.children?"d":"")+(g?"l":"")),k.push(j.combinedIconPrefix+(c.expanded?"e":"c")+(c.folder?"f":"")),l.className=k.join(" "),c.li&&(c.li.className=g?j.lastsib:""))},nodeSetActive:function(b,c){var d,e=b.node,g=b.tree,h=b.options,i=e===g.activeNode;return c=c!==!1,e.debug("nodeSetActive",c),i===c?k(e):c&&this._triggerNodeEvent("beforeActivate",e,b.originalEvent)===!1?l(e,["rejected"]):(c?(g.activeNode&&(f(g.activeNode!==e,"node was active (inconsistency)"),d=a.extend({},b,{node:g.activeNode}),g.nodeSetActive(d,!1),f(null===g.activeNode,"deactivate was out of sync?")),h.activeVisible&&g.nodeMakeVisible(b),g.activeNode=e,g.nodeRenderStatus(b),g.nodeSetFocus(b),g._triggerNodeEvent("activate",e)):(f(g.activeNode===e,"node was not active (inconsistency)"),g.activeNode=null,this.nodeRenderStatus(b),b.tree._triggerNodeEvent("deactivate",e)),void 0)},nodeSetExpanded:function(b,c){var e,f,g,h,i,j,m=b.node,n=b.tree,o=b.options;if(c=c!==!1,m.debug("nodeSetExpanded("+c+")"),m.expanded&&c||!m.expanded&&!c)return m.debug("nodeSetExpanded("+c+"): nothing to do"),k(m);if(c&&!m.lazy&&!m.hasChildren())return l(m,["empty"]);if(!c&&m.getLevel()<o.minExpandLevel)return l(m,["locked"]);if(this._triggerNodeEvent("beforeExpand",m,b.originalEvent)===!1)return l(m,["rejected"]);if(f=new a.Deferred,c&&!m.expanded&&o.autoCollapse){i=m.getParentList(!1,!0),j=o.autoCollapse;try{for(o.autoCollapse=!1,g=0,h=i.length;h>g;g++)this._callHook("nodeCollapseSiblings",i[g])}finally{o.autoCollapse=j}}return f.done(function(){b.tree._triggerNodeEvent(c?"expand":"collapse",b),o.autoScroll&&m.getLastChild().scrollIntoView(!0,m)}),e=function(d){var e,f,g,h;if(m.expanded=c,n._callHook("nodeRender",b,!1,!1,!0),m.ul)if(g="none"!==m.ul.style.display,h=!!m.expanded,g===h)m.warn("nodeSetExpanded: UL.style.display already set");else{if(o.fx)return e=o.fx.duration||200,f=o.fx.easing,m.debug("nodeSetExpanded: animate start..."),a(m.ul).animate(o.fx,e,f,function(){m.debug("nodeSetExpanded: animate done"),d()}),void 0;m.ul.style.display=m.expanded||!parent?"":"none"}d()},c&&m.lazy&&m.hasChildren()===d?(m.debug("nodeSetExpanded: load start..."),m.lazyLoad().done(function(){m.debug("nodeSetExpanded: load done"),f.notifyWith&&f.notifyWith(m,["loaded"]),e(function(){f.resolveWith(m)})}).fail(function(a){e(function(){f.rejectWith(m,["load failed ("+a+")"])})})):e(function(){f.resolveWith(m)}),m.debug("nodeSetExpanded: returns"),f.promise()},nodeSetFocus:function(b,c){b.node.debug("nodeSetFocus("+c+")");var d,e=b.tree,f=b.node;if(c=c!==!1,e.focusNode){if(e.focusNode===f&&c)return f.debug("nodeSetFocus("+c+"): nothing to do"),void 0;d=a.extend({},b,{node:e.focusNode}),e.focusNode=null,this._triggerNodeEvent("blur",d),this._callHook("nodeRenderStatus",d)}c&&(this.hasFocus()||(f.debug("nodeSetFocus: forcing container focus"),this._callHook("treeSetFocus",b,!0,!0)),this.nodeMakeVisible(b),e.focusNode=f,this._triggerNodeEvent("focus",b),b.options.autoScroll&&f.scrollIntoView(),this._callHook("nodeRenderStatus",b))},nodeSetSelected:function(a,b){var c=a.node,d=a.tree,e=a.options;if(b=b!==!1,c.debug("nodeSetSelected("+b+")",a),!c.unselectable){if(c.selected&&b||!c.selected&&!b)return!!c.selected;if(this._triggerNodeEvent("beforeSelect",c,a.originalEvent)===!1)return!!c.selected;b&&1===e.selectMode?d.lastSelectedNode&&d.lastSelectedNode.setSelected(!1):3===e.selectMode&&(c.selected=b,c.fixSelection3AfterClick()),c.selected=b,this.nodeRenderStatus(a),d.lastSelectedNode=b?c:null,d._triggerNodeEvent("select",a)}},nodeSetStatus:function(b,c,d,e){var f,g,h=b.node,i=b.tree,j=b.options._classNames;switch(f=function(){var a=h.children?h.children[0]:null;if(a&&a.isStatusNode){try{h.ul&&(h.ul.removeChild(a.li),a.li=null)}catch(b){}1===h.children.length?h.children=[]:h.children.shift()}},g=function(b){var c=h.children?h.children[0]:null;return c&&c.isStatusNode?(a.extend(c,b),i._callHook("nodeRender",c)):(b.key="_statusNode",h._setChildren([b]),h.children[0].isStatusNode=!0,i.render()),h.children[0]},c){case"ok":f(),a(h.span).removeClass(j.loading),a(h.span).removeClass(j.error);break;case"loading":a(h.span).removeClass(j.error),a(h.span).addClass(j.loading),h.parent||g({title:i.options.strings.loading+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-wait"});break;case"error":a(h.span).removeClass(j.loading),a(h.span).addClass(j.error),g({title:i.options.strings.loadError+(d?" ("+d+") ":""),tooltip:e,extraClasses:"fancytree-statusnode-error"});break;default:a.error("invalid status "+c)}},nodeToggleExpanded:function(a){return this.nodeSetExpanded(a,!a.node.expanded)},nodeToggleSelected:function(a){return this.nodeSetSelected(a,!a.node.selected)},treeClear:function(a){var b=a.tree;b.activeNode=null,b.focusNode=null,b.$div.find(">ul.fancytree-container").empty(),b.rootNode.children=null},treeCreate:function(){},treeDestroy:function(){},treeInit:function(a){this.treeLoad(a)},treeLoad:function(b,c){var d,f,g,h=b.tree,i=b.widget.element,j=a.extend({},b,{node:this.rootNode});if(h.rootNode.children&&this.treeClear(b),c=c||this.options.source)"string"==typeof c&&e();else switch(d=i.data("type")||"html"){case"html":f=i.find(">ul:first"),f.addClass("ui-fancytree-source ui-helper-hidden"),c=a.ui.fancytree.parseHtml(f);break;case"json":c=a.parseJSON(i.text()),c.children&&(c.title&&(h.title=c.title),c=c.children);break;default:a.error("Invalid data-type: "+d)}return g=this.nodeLoadChildren(j,c).done(function(){h.render(),3===b.options.selectMode&&h.rootNode.fixSelection3FromEndNodes(),h._triggerTreeEvent("init",!0)}).fail(function(){h.render(),h._triggerTreeEvent("init",!1)})},treeSetFocus:function(a,b,c){b=b!==!1,this.debug("treeSetFocus("+b+"), _calledByNodeSetFocus: "+c),this.debug(" focusNode: "+this.focusNode),this.debug(" activeNode: "+this.activeNode),b!==this.hasFocus()&&(this._hasFocus=b,this.$container.toggleClass("fancytree-treefocus",b),this._triggerTreeEvent(b?"focusTree":"blurTree"))},reactivate:function(a){var b=this.activeNode;b&&(this.activeNode=null,b.setActive(),a&&b.setFocus())},reload:function(a){return this._callHook("treeClear",this),this._callHook("treeLoad",this,a)},render:function(a,b){return this.rootNode.render(a,b)},setFocus:function(a){return this._callHook("treeSetFocus",this,a)},toDict:function(a,b){var c=this.rootNode.toDict(!0,b);return a?c:c.children},toString:function(){return"<Fancytree(#"+this._id+")>"},_triggerNodeEvent:function(a,b,c,e){var f=this._makeHookContext(b,c,e),g=this.widget._trigger(a,c,f);
-return g!==!1&&f.result!==d?f.result:g},_triggerTreeEvent:function(a,b){var c=this._makeHookContext(this,b),e=this.widget._trigger(a,b,c);return e!==!1&&c.result!==d?c.result:e},visit:function(a){return this.rootNode.visit(a,!1)},warn:function(){Array.prototype.unshift.call(arguments,this.toString()),g("warn",arguments)}},a.widget("ui.fancytree",{options:{activeVisible:!0,ajax:{type:"GET",cache:!1,dataType:"json"},aria:!1,autoActivate:!0,autoCollapse:!1,autoScroll:!1,checkbox:!1,clickFolderMode:4,debugLevel:null,disabled:!1,enableAspx:!0,extensions:[],fx:{height:"toggle",duration:200},generateIds:!1,icons:!0,idPrefix:"ft_",keyboard:!0,keyPathSeparator:"/",minExpandLevel:1,selectMode:2,strings:{loading:"Loading…",loadError:"Load error!"},tabbable:!0,_classNames:{node:"fancytree-node",folder:"fancytree-folder",combinedExpanderPrefix:"fancytree-exp-",combinedIconPrefix:"fancytree-ico-",hasChildren:"fancytree-has-children",active:"fancytree-active",selected:"fancytree-selected",expanded:"fancytree-expanded",lazy:"fancytree-lazy",focused:"fancytree-focused",partsel:"fancytree-partsel",lastsib:"fancytree-lastsib",loading:"fancytree-loading",error:"fancytree-error"},lazyload:null,postProcess:null},_create:function(){this.tree=new p(this),this.$source=this.source||"json"===this.element.data("type")?this.element:this.element.find(">ul:first");var b,c,e,g=this.options.extensions,h=this.tree;for(e=0;e<g.length;e++)c=g[e],b=a.ui.fancytree._extensions[c],b||a.error("Could not apply extension '"+c+"' (it is not registered, did you forget to include it?)"),this.tree.options[c]=a.extend(!0,{},b.options,this.tree.options[c]),f(this.tree.ext[c]===d,"Extension name must not exist as Fancytree.ext attribute: '"+c+"'"),this.tree.ext[c]={},j(this.tree,h,b,c),h=b;this.tree._callHook("treeCreate",this.tree)},_init:function(){this.tree._callHook("treeInit",this.tree),this._bind()},_setOption:function(b,c){var d=!0,e=!1;switch(b){case"aria":case"checkbox":case"icons":case"minExpandLevel":case"tabbable":this.tree._callHook("treeCreate",this.tree),e=!0;break;case"source":d=!1,this.tree._callHook("treeLoad",this.tree,c)}this.tree.debug("set option "+b+"="+c+" <"+typeof c+">"),d&&a.Widget.prototype._setOption.apply(this,arguments),e&&this.tree.render(!0,!1)},destroy:function(){this._unbind(),this.tree._callHook("treeDestroy",this.tree),this.tree.$div.find(">ul.fancytree-container").remove(),this.$source&&this.$source.removeClass("ui-helper-hidden"),a.Widget.prototype.destroy.call(this)},_unbind:function(){var b=this.tree._ns;this.element.unbind(b),this.tree.$container.unbind(b),a(c).unbind(b)},_bind:function(){var a=this,b=this.options,c=this.tree,d=c._ns;this._unbind(),c.$container.on("focusin"+d+" focusout"+d,function(a){var b=r.getNode(a),d="focusin"===a.type;b?c._callHook("nodeSetFocus",b,d):c._callHook("treeSetFocus",c,d)}).on("selectstart"+d,"span.fancytree-title",function(a){a.preventDefault()}).on("keydown"+d,function(a){if(b.disabled||b.keyboard===!1)return!0;var d,e=c.focusNode,f=c._makeHookContext(e||c,a),g=c.phase;try{return c.phase="userEvent",d=e?c._triggerNodeEvent("keydown",e,a):c._triggerTreeEvent("keydown",a),"preventNav"===d?d=!0:d!==!1&&(d=c._callHook("nodeKeydown",f)),d}finally{c.phase=g}}).on("click"+d+" dblclick"+d,function(c){if(b.disabled)return!0;var d,e=r.getEventTarget(c),f=e.node,g=a.tree,h=g.phase;if(!f)return!0;d=g._makeHookContext(f,c);try{switch(g.phase="userEvent",c.type){case"click":return d.targetType=e.type,g._triggerNodeEvent("click",d,c)===!1?!1:g._callHook("nodeClick",d);case"dblclick":return d.targetType=e.type,g._triggerNodeEvent("dblclick",d,c)===!1?!1:g._callHook("nodeDblclick",d)}}finally{g.phase=h}})},getActiveNode:function(){return this.tree.activeNode},getNodeByKey:function(a){return this.tree.getNodeByKey(a)},getRootNode:function(){return this.tree.rootNode},getTree:function(){return this.tree}}),r=a.ui.fancytree,a.extend(a.ui.fancytree,{version:"2.0.0-5",buildType:"release",debugLevel:1,_nextId:1,_nextNodeKey:1,_extensions:{},_FancytreeClass:p,_FancytreeNodeClass:o,jquerySupports:{positionMyOfs:h(a.ui.version,1,9)},assert:function(a,b){return f(a,b)},debug:function(){a.ui.fancytree.debugLevel>=2&&g("log",arguments)},error:function(){g("error",arguments)},getEventTargetType:function(a){return this.getEventTarget(a).type},getEventTarget:function(a){var b=a&&a.target?a.target.className:"",c={node:this.getNode(a.target),type:d};return/\bfancytree-title\b/.test(b)?c.type="title":/\bfancytree-expander\b/.test(b)?c.type=c.node.hasChildren()===!1?"prefix":"expander":/\bfancytree-checkbox\b/.test(b)?c.type="checkbox":/\bfancytree-icon\b/.test(b)?c.type="icon":/\bfancytree-node\b/.test(b)&&(c.type="title"),c},getNode:function(a){if(a instanceof o)return a;for(a.selector!==d?a=a[0]:a.originalEvent!==d&&(a=a.target);a;){if(a.ftnode)return a.ftnode;a=a.parentNode}return null},info:function(){a.ui.fancytree.debugLevel>=1&&g("info",arguments)},parseHtml:function(b){var c,e,f,g,h,i,j,k=b.find(">li"),l=[];return k.each(function(){var k,m,n=a(this),o=n.find(">span:first",this),p=o.length?null:n.find(">a:first"),q={tooltip:null,data:{}};for(o.length?q.title=o.html():p&&p.length?(q.title=p.html(),q.data.href=p.attr("href"),q.data.target=p.attr("target"),q.tooltip=p.attr("title")):(q.title=n.html(),g=q.title.search(/<ul/i),g>=0&&(q.title=q.title.substring(0,g))),q.title=a.trim(q.title),e=0,f=s.length;f>e;e++)q[s[e]]=d;for(i=this.className.split(" "),c=[],e=0,f=i.length;f>e;e++)j=i[e],t[j]?q[j]=!0:c.push(j);q.extraClasses=c.join(" "),h=n.attr("title"),h&&(q.tooltip=h),h=n.attr("id"),h&&(q.key=h),k=n.data(),k&&!a.isEmptyObject(k)&&(m=k.json,delete k.json,a.extend(q.data,k),m&&a.extend(q.data,m)),b=n.find(">ul:first"),q.children=b.length?a.ui.fancytree.parseHtml(b):q.lazy?d:null,l.push(q)}),l},registerExtension:function(b,c){a.ui.fancytree._extensions[b]=c},warn:function(){g("warn",arguments)}})}(jQuery,window,document),function(a){"use strict";a.ui.fancytree.registerExtension("columnview",{version:"0.0.1",options:{},treeInit:function(b){var c,d,e=b.tree,f=e.widget.element;e.tr=a("tbody tr",f)[0],e.columnCount=a(">td",e.tr).length,this._super(b),d=a(e.rootNode.ul),c=a(">td",e.tr).eq(0),d.removeClass("fancytree-container"),d.removeAttr("tabindex"),e.$container=f,f.addClass("fancytree-container fancytree-ext-columnview"),f.attr("tabindex","0"),c.empty(),d.detach().appendTo(c),e.widget.options.autoCollapse=!0,e.widget.options.fx=!1,e.widget.options.clickFolderMode=1,f.bind("fancytreeactivate",function(b,c){var d,e,f=c.node,g=c.tree,h=f.getLevel();if(g._callHook("nodeCollapseSiblings",f),h<=g.columnCount)for(e=a(">td",g.tr),d=h;d<g.columnCount;d++)e.eq(d).empty();f.expanded||!f.children&&!f.lazy||f.setExpanded()}).bind("fancytreekeydown",function(b,c){var d=null;switch(b.which){case a.ui.keyCode.DOWN:return d=c.node.getNextSibling(),d&&d.setFocus(),!1;case a.ui.keyCode.LEFT:return d=c.node.getParent(),d&&d.setFocus(),!1;case a.ui.keyCode.UP:return d=c.node.getPrevSibling(),d&&d.setFocus(),!1}})},nodeRender:function(b,c,d,e,f){this._super(b,c,d,e,f);var g,h,i,j=b.tree,k=b.node,l=a(k.span);l.find("span.fancytree-expander").remove(),k.hasChildren()===!1||l.find("span.fancytree-cv-right").length||l.append(a("<span class='fancytree-icon fancytree-cv-right'>")),k.ul&&(k.ul.style.display="",g=k.getLevel(),g<j.columnCount&&(h=a(">td",j.tr).eq(g),i=a(k.ul).detach(),h.empty().append(i)))}})}(jQuery,window,document),function(a,b,c,d){"use strict";function e(a){return 0===a?"":a>0?"+"+a:""+a}function f(b){var c=b.options.dnd||null;c&&g(),c&&c.dragStart&&b.widget.element.draggable({addClasses:!1,appendTo:"body",containment:!1,delay:0,distance:4,revert:!1,scroll:!0,scrollSpeed:7,scrollSensitivity:10,connectToFancytree:!0,helper:function(b){var c=a.ui.fancytree.getNode(b.target);return c?c.tree.ext.dnd._onDragEvent("helper",c,null,b,null,null):"<div>ERROR?: helper requested but sourceNode not found</div>"},start:function(){}}),c&&c.dragDrop&&b.widget.element.droppable({addClasses:!1,tolerance:"intersect",greedy:!1})}function g(){i||(a.ui.plugin.add("draggable","connectToFancytree",{start:function(b,c){var d=a(this).data("ui-draggable")||a(this).data("draggable"),e=c.helper.data("ftSourceNode")||null;return e?(d.offset.click.top=-2,d.offset.click.left=16,e.tree.ext.dnd._onDragEvent("start",e,null,b,c,d)):void 0},drag:function(b,c){var d,e=a(this).data("ui-draggable")||a(this).data("draggable"),f=c.helper.data("ftSourceNode")||null,g=c.helper.data("ftTargetNode")||null,i=a.ui.fancytree.getNode(b.target);return b.target&&!i&&(d=a(b.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length>0)?(h("Drag event over helper: ignored."),void 0):(c.helper.data("ftTargetNode",i),g&&g!==i&&g.tree.ext.dnd._onDragEvent("leave",g,f,b,c,e),i&&i.tree.options.dnd.dragDrop&&(i===g?i.tree.ext.dnd._onDragEvent("over",i,f,b,c,e):i.tree.ext.dnd._onDragEvent("enter",i,f,b,c,e)),void 0)},stop:function(b,c){var d=a(this).data("ui-draggable")||a(this).data("draggable"),e=c.helper.data("ftSourceNode")||null,f=c.helper.data("ftTargetNode")||null,g=b.type,i="mouseup"===g&&1===b.which;i||h("Drag was cancelled"),f&&(i&&f.tree.ext.dnd._onDragEvent("drop",f,e,b,c,d),f.tree.ext.dnd._onDragEvent("leave",f,e,b,c,d)),e&&e.tree.ext.dnd._onDragEvent("stop",e,null,b,c,d)}}),i=!0)}var h=a.ui.fancytree.debug,i=!1;a.ui.fancytree.registerExtension("dnd",{version:"0.0.1",options:{dragStart:null,dragStop:null,autoExpandMS:1e3,preventVoidMoves:!0,preventRecursiveMoves:!0,dragEnter:null,dragOver:null,dragDrop:null,dragLeave:null},treeInit:function(a){var b=a.tree;this._super(a),f(b)},nodeKeydown:function(b){var c=b.originalEvent;c.which===a.ui.keyCode.ESCAPE&&this._local._cancelDrag(),this._super(b)},_setDndStatus:function(b,c,d,f,g){var h,i=0,j="center",k=this._local,l=b?a(b.span):null,m=a(c.span);if(k.$dropMarker||(k.$dropMarker=a("<div id='fancytree-drop-marker'></div>").hide().css({"z-index":1e3}).prependTo(a(this.$div).parent())),"after"===f||"before"===f||"over"===f){switch(f){case"before":k.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over"),k.$dropMarker.addClass("fancytree-drop-before"),j="top";break;case"after":k.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over"),k.$dropMarker.addClass("fancytree-drop-after"),j="bottom";break;default:k.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before"),k.$dropMarker.addClass("fancytree-drop-over"),m.addClass("fancytree-drop-target"),i=8}h=a.ui.fancytree.jquerySupports.positionMyOfs?{my:"left"+e(i)+" center",at:"left "+j,of:m}:{my:"left center",at:"left "+j,of:m,offset:""+i+" 0"},k.$dropMarker.show().position(h)}else m.removeClass("fancytree-drop-target"),k.$dropMarker.hide();"after"===f?m.addClass("fancytree-drop-after"):m.removeClass("fancytree-drop-after"),"before"===f?m.addClass("fancytree-drop-before"):m.removeClass("fancytree-drop-before"),g===!0?(l&&l.addClass("fancytree-drop-accept"),m.addClass("fancytree-drop-accept"),d.addClass("fancytree-drop-accept")):(l&&l.removeClass("fancytree-drop-accept"),m.removeClass("fancytree-drop-accept"),d.removeClass("fancytree-drop-accept")),g===!1?(l&&l.addClass("fancytree-drop-reject"),m.addClass("fancytree-drop-reject"),d.addClass("fancytree-drop-reject")):(l&&l.removeClass("fancytree-drop-reject"),m.removeClass("fancytree-drop-reject"),d.removeClass("fancytree-drop-reject"))},_onDragEvent:function(b,c,e,f,g,i){"over"!==b&&h("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o",b,c,e,this);var j,k,l,m,n,o,p,q=this.options,r=q.dnd,s=this._makeHookContext(c,f,{otherNode:e,ui:g,draggable:i}),t=null,u=a(c.span);switch(b){case"helper":j=a("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>").append(u.find("span.fancytree-title").clone()),a("ul.fancytree-container",c.tree.$div).append(j),j.data("ftSourceNode",c),t=j;break;case"start":c.isStatusNode?t=!1:r.dragStart&&(t=r.dragStart(c,s)),t===!1?(this.debug("tree.dragStart() cancelled"),g.helper.trigger("mouseup"),g.helper.hide()):u.addClass("fancytree-drag-source");break;case"enter":p=r.preventRecursiveMoves&&c.isDescendantOf(e)?!1:r.dragEnter?r.dragEnter(c,s):null,t=p?a.isArray(p)?{over:a.inArray("over",p)>=0,before:a.inArray("before",p)>=0,after:a.inArray("after",p)>=0}:{over:p===!0||"over"===p,before:p===!0||"before"===p,after:p===!0||"after"===p}:!1,g.helper.data("enterResponse",t),h("helper.enterResponse: %o",t);break;case"over":n=g.helper.data("enterResponse"),o=null,n===!1||("string"==typeof n?o=n:(k=u.offset(),l={x:f.pageX-k.left,y:f.pageY-k.top},m={x:l.x/u.width(),y:l.y/u.height()},n.after&&m.y>.75?o="after":!n.over&&n.after&&m.y>.5?o="after":n.before&&m.y<=.25?o="before":!n.over&&n.before&&m.y<=.5?o="before":n.over&&(o="over"),r.preventVoidMoves&&(c===e?(h(" drop over source node prevented"),o=null):"before"===o&&e&&c===e.getNextSibling()?(h(" drop after source node prevented"),o=null):"after"===o&&e&&c===e.getPrevSibling()?(h(" drop before source node prevented"),o=null):"over"===o&&e&&e.parent===c&&e.isLastSibling()&&(h(" drop last child over own parent prevented"),o=null)),g.helper.data("hitMode",o))),"over"===o&&r.autoExpandMS&&c.hasChildren()!==!1&&!c.expanded&&c.scheduleAction("expand",r.autoExpandMS),o&&r.dragOver&&(s.hitMode=o,t=r.dragOver(c,s)),this._local._setDndStatus(e,c,g.helper,o,t!==!1&&null!==o);break;case"drop":o=g.helper.data("hitMode"),o&&r.dragDrop&&(s.hitMode=o,r.dragDrop(c,s));break;case"leave":c.scheduleAction("cancel"),g.helper.data("enterResponse",null),g.helper.data("hitMode",null),this._local._setDndStatus(e,c,g.helper,"out",d),r.dragLeave&&r.dragLeave(c,s);break;case"stop":u.removeClass("fancytree-drag-source"),r.dragStop&&r.dragStop(c,s);break;default:throw"Unsupported drag event: "+b}return t},_cancelDrag:function(){var b=a.ui.ddmanager.current;b&&b.cancel()}})}(jQuery,window,document),function(a){"use strict";function b(a){return(a+"").replace(/([.?*+\^\$\[\]\\(){}|-])/g,"\\$1")}a.ui.fancytree._FancytreeClass.prototype.applyFilter=function(a){var c,d,e=0,f=this.options.filter.leavesOnly;return this.visit(function(a){delete a.match,delete a.subMatch}),"string"==typeof a&&(c=b(a),d=new RegExp(".*"+c+".*","i"),a=function(a){return!!d.exec(a.title)}),this.enableFilter=!0,this.$div.addClass("fancytree-ext-filter"),"hide"===this.options.filter.mode&&this.$div.addClass("fancytree-ext-filter-hide"),this.visit(function(b){f&&null!=b.children||!a(b)||(e++,b.match=!0,b.visitParents(function(a){a.subMatch=!0}))}),this.render(),e},a.ui.fancytree._FancytreeClass.prototype.clearFilter=function(){this.visit(function(b){delete b.match,delete b.subMatch,a(b.li).show()}),this.enableFilter=!1,this.render(),this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-hide")},a.ui.fancytree.registerExtension("filter",{version:"0.0.1",options:{mode:"dimm",leavesOnly:!1},treeInit:function(a){this._super(a)},treeDestroy:function(a){this._super(a)},nodeRenderStatus:function(b){var c,d=b.node,e=b.options,f=b.tree,g=a(d[f.statusClassPropName]);g.length&&(this._super(b),f.enableFilter&&(d.match?g.addClass("fancytree-match"):g.removeClass("fancytree-match"),d.subMatch?g.addClass("fancytree-submatch"):g.removeClass("fancytree-submatch"),"hide"===e.filter.mode&&(c=!(!d.match&&!d.subMatch),d.debug(d.title+": visible="+c),a(d.li).toggle(c))))}})}(jQuery,window,document),function(a,b,c){"use strict";a.ui.fancytree.registerExtension("menu",{version:"0.0.1",options:{enable:!0,selector:null,position:{},create:a.noop,beforeOpen:a.noop,open:a.noop,focus:a.noop,select:a.noop,close:a.noop},treeInit:function(b){var c=b.options,d=b.tree;this._super(b),d.ext.menu.data={tree:d,node:null,$menu:null,menuId:null},d.$container.delegate("span.fancytree-node","contextmenu",function(b){var c=a.ui.fancytree.getNode(b),e={node:c,tree:c.tree,originalEvent:b,options:d.options};return d.ext.menu._openMenu(e),!1}),a(c.menu.selector).menu({create:function(b){d.ext.menu.data.$menu=a(this).menu("widget");var e=a.extend({},d.ext.menu.data);c.menu.create.call(d,b,e)},focus:function(b,e){var f=a.extend({},d.ext.menu.data,{menuItem:e.item,menuId:e.item.find(">a").attr("href")});c.menu.focus.call(d,b,f)},select:function(e,f){var g=a.extend({},d.ext.menu.data,{menuItem:f.item,menuId:f.item.find(">a").attr("href")});c.menu.select.call(d,e,g)!==!1&&d.ext.menu._closeMenu(b)}}).hide()},treeDestroy:function(a){this._super(a)},_openMenu:function(b){var d,e=b.tree,f=b.options,g=a(f.menu.selector);e.ext.menu.data.node=b.node,d=a.extend({},e.ext.menu.data),f.menu.beforeOpen.call(e,b.originalEvent,d)!==!1&&(a(c).bind("keydown.fancytree",function(c){c.which===a.ui.keyCode.ESCAPE&&e.ext.menu._closeMenu(b)}).bind("mousedown.fancytree",function(c){0===a(c.target).closest(".ui-menu-item").length&&e.ext.menu._closeMenu(b)}),g.css("position","absolute").show().position({my:"left top",at:"right top",of:b.originalEvent,collision:"fit"}).focus(),f.menu.open.call(e,b.originalEvent,d))},_closeMenu:function(b){var d,e=b.tree,f=b.options,g=a.extend({},e.ext.menu.data);f.menu.close.call(e,b.originalEvent,g)!==!1&&(d=a(f.menu.selector),a(c).unbind("keydown.fancytree, mousedown.fancytree"),d.hide(),e.ext.menu.data.node=null)}})}(jQuery,window,document),function(a,b,c,d){"use strict";function e(b,c){c=c||"",b||a.error("Assertion failed "+c)}var f="active",g="expanded",h="focus",i="selected";a.ui.fancytree._FancytreeClass.prototype.clearCookies=function(b){var c=this.ext.persist,d=c.cookiePrefix;b=b||"active expanded focus selected",b.indexOf(f)>=0&&a.cookie(d+f,null),b.indexOf(g)>=0&&a.cookie(d+g,null),b.indexOf(h)>=0&&a.cookie(d+h,null),b.indexOf(i)>=0&&a.cookie(d+i,null)},a.ui.fancytree._FancytreeClass.prototype.getPersistData=function(){var b=this.ext.persist,c=this.options.persist,d=c.cookieDelimiter,e={};e[f]=a.cookie(b.cookiePrefix+f),e[g]=(a.cookie(b.cookiePrefix+g)||"").split(d),e[i]=(a.cookie(b.cookiePrefix+i)||"").split(d),e[h]=a.cookie(b.cookiePrefix+h)},a.ui.fancytree.registerExtension("persist",{version:"0.0.1",options:{cookieDelimiter:"~",cookiePrefix:d,cookie:{raw:!1,expires:"",path:"",domain:"",secure:!1},overrideSource:!1,types:"active expanded focus selected"},_setKey:function(b,c,d){c=""+c;var e=this._local,f=this.options.persist,g=e.cookiePrefix+b,h=a.cookie(g),i=h?h.split(f.cookieDelimiter):[],j=a.inArray(c,i);j>=0&&i.splice(j,1),d&&i.push(c),a.cookie(g,i.join(f.cookieDelimiter),f.cookie)},treeInit:function(b){var j=b.tree,k=b.options,l=this._local,m=this.options.persist;e(a.cookie,"Missing required plugin for 'persist' extension: jquery.cookie.js"),l.cookiePrefix=m.cookiePrefix||"fancytree-"+j._id+"-",l.storeActive=m.types.indexOf(f)>=0,l.storeExpanded=m.types.indexOf(g)>=0,l.storeSelected=m.types.indexOf(i)>=0,l.storeFocus=m.types.indexOf(h)>=0,j.$div.bind("fancytreeinit",function(){var b,e,n,o,p=a.cookie(l.cookiePrefix+h);if(j.debug("COOKIE "+c.cookie),l.storeExpanded&&(b=a.cookie(l.cookiePrefix+g)))for(e=b.split(m.cookieDelimiter),n=0;n<e.length;n++)o=j.getNodeByKey(e[n]),o?(o.expanded===d||m.overrideSource&&o.expanded===!1)&&(o.expanded=!0,o.render()):l._setKey(g,e[n],!1);if(l.storeSelected&&(b=a.cookie(l.cookiePrefix+i)))for(e=b.split(m.cookieDelimiter),n=0;n<e.length;n++)o=j.getNodeByKey(e[n]),o?(o.selected===d||m.overrideSource&&o.selected===!1)&&(o.selected=!0,o.renderStatus()):l._setKey(i,e[n],!1);l.storeActive&&(b=a.cookie(l.cookiePrefix+f),!b||!k.persist.overrideSource&&j.activeNode||(o=j.getNodeByKey(b),o&&o.setActive())),l.storeFocus&&p&&(o=j.getNodeByKey(p),o&&o.setFocus())}),this._super(b)},nodeSetActive:function(b,c){var d=this._local,e=this.options.persist;this._super(b,c),d.storeActive&&a.cookie(d.cookiePrefix+f,this.activeNode?this.activeNode.key:null,e.cookie)},nodeSetExpanded:function(a,b){var c=a.node,d=this._local;this._super(a,b),d.storeExpanded&&d._setKey(g,c.key,b)},nodeSetFocus:function(b){var c=this._local,d=this.options.persist;this._super(b),c.storeFocus&&a.cookie(this.cookiePrefix+h,this.focusNode?this.focusNode.key:null,d.cookie)},nodeSetSelected:function(a,b){var c=a.node,d=this._local;this._super(a,b),d.storeSelected&&d._setKey(i,c.key,b)}})}(jQuery,window,document),function(a,b,c){"use strict";function d(b,c){c=c||"",b||a.error("Assertion failed "+c)}function e(a,b){a.parentNode.insertBefore(b,a.nextSibling)}function f(a,b){a.visit(function(a){var c=a.tr;return c&&(c.style.display=b?"":"none"),a.expanded?void 0:"skip"})}function g(b){var c,e,f,g=b.parent,h=g?g.children:null;if(h&&h.length>1&&h[0]!==b)for(c=a.inArray(b,h),f=h[c-1],d(f.tr);f.children&&(e=f.children[f.children.length-1],e.tr);)f=e;else f=g;return f}a.ui.fancytree.registerExtension("table",{version:"0.0.1",options:{indentation:16,nodeColumnIdx:0,checkboxColumnIdx:null},treeInit:function(b){var d,e,f,g=b.tree,h=g.widget.element;for(h.addClass("fancytree-container fancytree-ext-table"),g.tbody=h.find("> tbody")[0],g.columnCount=a("thead >tr >th",h).length,a(g.tbody).empty(),g.rowFragment=c.createDocumentFragment(),e=a("<tr>"),f="",b.options.aria&&(e.attr("role","row"),f=" role='gridcell'"),d=0;d<g.columnCount;d++)b.options.table.nodeColumnIdx===d?e.append("<td"+f+"><span class='fancytree-node'></span></td>"):e.append("<td"+f+">");g.rowFragment.appendChild(e.get(0)),g.statusClassPropName="tr",g.ariaPropName="tr",this.nodeContainerAttrName="tr",this._super(b),a(g.rootNode.ul).remove(),g.rootNode.ul=null,g.$container=h,this.$container.attr("tabindex",this.options.tabbable?"0":"-1"),this.options.aria&&g.$container.attr("role","treegrid").attr("aria-readonly",!0)},nodeRemoveChildMarkup:function(b){var c=b.node;c.visit(function(b){b.tr&&(a(b.tr).remove(),b.tr=null)})},nodeRemoveMarkup:function(b){var c=b.node;c.tr&&(a(c.tr).remove(),c.tr=null),this.nodeRemoveChildMarkup(b)},nodeRender:function(b,c,f,h,i){var j,k,l,m,n,o,p,q,r=b.tree,s=b.node,t=b.options,u=!s.parent;if(i||(b.hasCollapsedParents=s.parent&&!s.parent.expanded),u||(s.tr?this.nodeRenderTitle(b):(n=r.rowFragment.firstChild.cloneNode(!0),o=g(s),d(o),h===!0&&i?n.style.display="none":f&&b.hasCollapsedParents&&(n.style.display="none"),o.tr?e(o.tr,n):(d(!o.parent,"prev. row must have a tr, or is system root"),r.tbody.appendChild(n)),s.tr=n,s.key&&t.generateIds&&(s.tr.id=t.idPrefix+s.key),s.tr.ftnode=s,t.aria&&a(s.tr).attr("aria-labelledby","ftal_"+s.key),s.span=a("span.fancytree-node",s.tr).get(0),this.nodeRenderTitle(b),t.createNode&&t.createNode.call(r,{type:"createNode"},b))),t.renderNode&&t.renderNode.call(r,{type:"renderNode"},b),j=s.children,j&&(u||f||s.expanded))for(l=0,m=j.length;m>l;l++)q=a.extend({},b,{node:j[l]}),q.hasCollapsedParents=q.hasCollapsedParents||!s.expanded,this.nodeRender(q,c,f,h,!0);j&&!i&&(p=s.tr||null,k=r.tbody.firstChild,s.visit(function(a){if(a.tr){if(s.expanded||u||"none"===a.tr.style.display||(a.tr.style.display="none"),a.tr.previousSibling!==p){s.debug("_fixOrder: mismatch at node: "+a);var b=p?p.nextSibling:k;r.tbody.insertBefore(a.tr,b)}p=a.tr}})),u||this.nodeRenderStatus(b)},nodeRenderTitle:function(b){var c,d=b.node,e=b.options;this._super(b),e.checkbox&&null!=e.table.checkboxColumnIdx&&(c=a("span.fancytree-checkbox",d.span).detach(),a(d.tr).find("td:first").html(c)),e.renderColumns&&e.renderColumns.call(b.tree,{type:"renderColumns"},b)},nodeRenderStatus:function(b){var c,d=b.node,e=b.options;this._super(b),a(d.tr).removeClass("fancytree-node"),c=(d.getLevel()-1)*e.table.indentation,c&&a(d.span).css({marginLeft:c+"px"})},nodeSetExpanded:function(a,b){return this._super(a,b).always(function(){b=b!==!1,f(a.node,b)})},nodeSetStatus:function(b,c,d,e){if("ok"===c){var f=b.node,g=f.children?f.children[0]:null;g&&g.isStatusNode&&a(g.tr).remove()}this._super(b,c,d,e)}})}(jQuery,window,document),function(a){"use strict";a.ui.fancytree.registerExtension("themeroller",{version:"0.0.1",options:{activeClass:"ui-state-active",foccusClass:"ui-state-focus",hoverClass:"ui-state-hover",selectedClass:"ui-state-highlight"},treeInit:function(b){this._super(b);var c=b.widget.element;"TABLE"===c[0].nodeName?(c.addClass("ui-widget ui-corner-all"),c.find(">thead tr").addClass("ui-widget-header"),c.find(">tbody").addClass("ui-widget-conent")):c.addClass("ui-widget ui-widget-content ui-corner-all"),c.delegate(".fancytree-node","mouseenter mouseleave",function(b){var c=a.ui.fancytree.getNode(b.target),d="mouseenter"===b.type;c.debug("hover: "+d),a(c.span).toggleClass("ui-state-hover ui-corner-all",d)})},treeDestroy:function(a){this._super(a),a.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all")},nodeRenderStatus:function(b){var c=b.node,d=a(c.span);this._super(b),d.toggleClass("ui-state-active",c.isActive()),d.toggleClass("ui-state-focus",c.hasFocus()),d.toggleClass("ui-state-highlight",c.isSelected())}})}(jQuery,window,document);
-//# sourceMappingURL=jquery.fancytree-all.min.js.map
-;
+// Start of local namespace
+;(function($, window, document, undefined) {
+"use strict";
+// prevent duplicate loading
+if ( $.ui.fancytree && $.ui.fancytree.version ) {
+ $.ui.fancytree.warn("Fancytree: ignored duplicate include");
+ return;
+}
+
+
+/* *****************************************************************************
+ * Private functions and variables
+ */
+
+function _raiseNotImplemented(msg){
+ msg = msg || "";
+ $.error("Not implemented: " + msg);
+}
+
+function _assert(cond, msg){
+ // TODO: see qunit.js extractStacktrace()
+ if(!cond){
+ msg = msg ? ": " + msg : "";
+ $.error("Assertion failed" + msg);
+ }
+}
+
+function consoleApply(method, args){
+ var i, s,
+ fn = window.console ? window.console[method] : null;
+
+ if(fn){
+ if(fn.apply){
+ fn.apply(window.console, args);
+ }else{
+ // IE?
+ s = "";
+ for( i=0; i<args.length; i++){
+ s += args[i];
+ }
+ fn(s);
+ }
+ }
+}
+
+/*Return true if x is a FancytreeNode.*/
+function _isNode(x){
+ return !!(x.tree && x.statusNodeType !== undefined);
+}
+
+/** Return true if dotted version string is equal or higher than requested version.
+ *
+ * See http://jsfiddle.net/mar10/FjSAN/
+ */
+function isVersionAtLeast(dottedVersion, major, minor, patch){
+ var i, v, t,
+ verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
+ testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
+
+ for( i = 0; i < testParts.length; i++ ){
+ v = verParts[i] || 0;
+ t = testParts[i] || 0;
+ if( v !== t ){
+ return ( v > t );
+ }
+ }
+ return true;
+}
+
+/** Return a wrapper that calls sub.methodName() and exposes
+ * this : tree
+ * this._local : tree.ext.EXTNAME
+ * this._super : base.methodName()
+ */
+function _makeVirtualFunction(methodName, tree, base, extension, extName){
+ // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
+ // if(rexTestSuper && !rexTestSuper.test(func)){
+ // // extension.methodName() doesn't call _super(), so no wrapper required
+ // return func;
+ // }
+ // Use an immediate function as closure
+ var proxy = (function(){
+ var prevFunc = tree[methodName], // org. tree method or prev. proxy
+ baseFunc = extension[methodName], //
+ _local = tree.ext[extName],
+ _super = function(){
+ return prevFunc.apply(tree, arguments);
+ };
+
+ // Return the wrapper function
+ return function(){
+ var prevLocal = tree._local,
+ prevSuper = tree._super;
+ try{
+ tree._local = _local;
+ tree._super = _super;
+ return baseFunc.apply(tree, arguments);
+ }finally{
+ tree._local = prevLocal;
+ tree._super = prevSuper;
+ }
+ };
+ })(); // end of Immediate Function
+ return proxy;
+}
+
+/**
+ * Subclass `base` by creating proxy functions
+ */
+function _subclassObject(tree, base, extension, extName){
+ // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
+ for(var attrName in extension){
+ if(typeof extension[attrName] === "function"){
+ if(typeof tree[attrName] === "function"){
+ // override existing method
+ tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
+ }else if(attrName.charAt(0) === "_"){
+ // Create private methods in tree.ext.EXTENSION namespace
+ tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
+ }else{
+ $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
+ }
+ }else{
+ // Create member variables in tree.ext.EXTENSION namespace
+ if(attrName !== "options"){
+ tree.ext[extName][attrName] = extension[attrName];
+ }
+ }
+ }
+}
+
+
+function _getResolvedPromise(context, argArray){
+ if(context === undefined){
+ return $.Deferred(function(){this.resolve();}).promise();
+ }else{
+ return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
+ }
+}
+
+
+function _getRejectedPromise(context, argArray){
+ if(context === undefined){
+ return $.Deferred(function(){this.reject();}).promise();
+ }else{
+ return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
+ }
+}
+
+
+function _makeResolveFunc(deferred, context){
+ return function(){
+ deferred.resolveWith(context);
+ };
+}
+
+
+function _getElementDataAsDict($el){
+ // Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
+ var d = $.extend({}, $el.data()),
+ json = d.json;
+ delete d.fancytree; // added to container by widget factory
+ if( json ) {
+ delete d.json;
+ // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
+ d = $.extend(d, json);
+ }
+ return d;
+}
+
+
+// TODO: use currying
+function _makeNodeTitleMatcher(s){
+ s = s.toLowerCase();
+ return function(node){
+ return node.title.toLowerCase().indexOf(s) >= 0;
+ };
+}
+
+var i,
+ FT = null, // initialized below
+ ENTITY_MAP = {"&": "&", "<": "<", ">": ">", "\"": """, "'": "'", "/": "/"},
+ //boolean attributes that can be set with equivalent class names in the LI tags
+ CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
+ CLASS_ATTR_MAP = {},
+ // Top-level Fancytree node attributes, that can be set by dict
+ NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "),
+ NODE_ATTR_MAP = {},
+ // Attribute names that should NOT be added to node.data
+ NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
+
+for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
+for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
+
+
+/* *****************************************************************************
+ * FancytreeNode
+ */
+
+
+/**
+ * Creates a new FancytreeNode
+ *
+ * @class FancytreeNode
+ * @classdesc A FancytreeNode represents the hierarchical data model and operations.
+ *
+ * @param {FancytreeNode} parent
+ * @param {NodeData} obj
+ *
+ * @property {Fancytree} tree The tree instance
+ * @property {FancytreeNode} parent The parent node
+ * @property {string} key Node id (must be unique inside the tree)
+ * @property {string} title Display name (may contain HTML)
+ * @property {object} data Contains all extra data that was passed on node creation
+ * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
+ * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
+ * to define a node that has no children.
+ * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
+ * @property {string} extraClasses Addtional CSS classes, added to the node's `<span>`
+ * @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
+ * Note: Also non-folders may have children.
+ * @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
+ * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
+ * @property {boolean} selected Use isSelected(), setSelected() to access this property.
+ * @property {string} tooltip Alternative description used as hover banner
+ */
+function FancytreeNode(parent, obj){
+ var i, l, name, cl;
+
+ this.parent = parent;
+ this.tree = parent.tree;
+ this.ul = null;
+ this.li = null; // <li id='key' ftnode=this> tag
+ this.statusNodeType = null; // if this is a temp. node to display the status of its parent
+ this._isLoading = false; // if this node itself is loading
+ this._error = null; // {message: '...'} if a load error occured
+ this.data = {};
+
+ // TODO: merge this code with node.toDict()
+ // copy attributes from obj object
+ for(i=0, l=NODE_ATTRS.length; i<l; i++){
+ name = NODE_ATTRS[i];
+ this[name] = obj[name];
+ }
+ // node.data += obj.data
+ if(obj.data){
+ $.extend(this.data, obj.data);
+ }
+ // copy all other attributes to this.data.NAME
+ for(name in obj){
+ if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
+ // node.data.NAME = obj.NAME
+ this.data[name] = obj[name];
+ }
+ }
+
+ // Fix missing key
+ if( this.key == null ){ // test for null OR undefined
+ if( this.tree.options.defaultKey ) {
+ this.key = this.tree.options.defaultKey(this);
+ _assert(this.key, "defaultKey() must return a unique key");
+ } else {
+ this.key = "_" + (FT._nextNodeKey++);
+ }
+ } else {
+ this.key = "" + this.key; // Convert to string (#217)
+ }
+
+ // Fix tree.activeNode
+ // TODO: not elegant: we use obj.active as marker to set tree.activeNode
+ // when loading from a dictionary.
+ if(obj.active){
+ _assert(this.tree.activeNode === null, "only one active node allowed");
+ this.tree.activeNode = this;
+ }
+ if( obj.selected ){ // #186
+ this.tree.lastSelectedNode = this;
+ }
+ // TODO: handle obj.focus = true
+ // Create child nodes
+ this.children = null;
+ cl = obj.children;
+ if(cl && cl.length){
+ this._setChildren(cl);
+ }
+ // Add to key/ref map (except for root node)
+// if( parent ) {
+ this.tree._callHook("treeRegisterNode", this.tree, true, this);
+// }
+}
+
+
+FancytreeNode.prototype = /** @lends FancytreeNode# */{
+ /* Return the direct child FancytreeNode with a given key, index. */
+ _findDirectChild: function(ptr){
+ var i, l,
+ cl = this.children;
+
+ if(cl){
+ if(typeof ptr === "string"){
+ for(i=0, l=cl.length; i<l; i++){
+ if(cl[i].key === ptr){
+ return cl[i];
+ }
+ }
+ }else if(typeof ptr === "number"){
+ return this.children[ptr];
+ }else if(ptr.parent === this){
+ return ptr;
+ }
+ }
+ return null;
+ },
+ // TODO: activate()
+ // TODO: activateSilently()
+ /* Internal helper called in recursive addChildren sequence.*/
+ _setChildren: function(children){
+ _assert(children && (!this.children || this.children.length === 0), "only init supported");
+ this.children = [];
+ for(var i=0, l=children.length; i<l; i++){
+ this.children.push(new FancytreeNode(this, children[i]));
+ }
+ },
+ /**
+ * Append (or insert) a list of child nodes.
+ *
+ * @param {NodeData[]} children array of child node definitions (also single child accepted)
+ * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
+ * If omitted, the new children are appended.
+ * @returns {FancytreeNode} first child added
+ *
+ * @see FancytreeNode#applyPatch
+ */
+ addChildren: function(children, insertBefore){
+ var i, l, pos,
+ firstNode = null,
+ nodeList = [];
+
+ if($.isPlainObject(children) ){
+ children = [children];
+ }
+ if(!this.children){
+ this.children = [];
+ }
+ for(i=0, l=children.length; i<l; i++){
+ nodeList.push(new FancytreeNode(this, children[i]));
+ }
+ firstNode = nodeList[0];
+ if(insertBefore == null){
+ this.children = this.children.concat(nodeList);
+ }else{
+ insertBefore = this._findDirectChild(insertBefore);
+ pos = $.inArray(insertBefore, this.children);
+ _assert(pos >= 0, "insertBefore must be an existing child");
+ // insert nodeList after children[pos]
+ this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
+ }
+ if( !this.parent || this.parent.ul || this.tr ){
+ // render if the parent was rendered (or this is a root node)
+ this.render();
+ }
+ if( this.tree.options.selectMode === 3 ){
+ this.fixSelection3FromEndNodes();
+ }
+ return firstNode;
+ },
+ /**
+ * Append or prepend a node, or append a child node.
+ *
+ * This a convenience function that calls addChildren()
+ *
+ * @param {NodeData} node node definition
+ * @param {string} [mode=child] 'before', 'after', or 'child' ('over' is a synonym for 'child')
+ * @returns {FancytreeNode} new node
+ */
+ addNode: function(node, mode){
+ if(mode === undefined || mode === "over"){
+ mode = "child";
+ }
+ switch(mode){
+ case "after":
+ return this.getParent().addChildren(node, this.getNextSibling());
+ case "before":
+ return this.getParent().addChildren(node, this);
+ case "child":
+ case "over":
+ return this.addChildren(node);
+ }
+ _assert(false, "Invalid mode: " + mode);
+ },
+ /**
+ * Append new node after this.
+ *
+ * This a convenience function that calls addNode(node, 'after')
+ *
+ * @param {NodeData} node node definition
+ * @returns {FancytreeNode} new node
+ */
+ appendSibling: function(node){
+ return this.addNode(node, "after");
+ },
+ /**
+ * Modify existing child nodes.
+ *
+ * @param {NodePatch} patch
+ * @returns {$.Promise}
+ * @see FancytreeNode#addChildren
+ */
+ applyPatch: function(patch) {
+ // patch [key, null] means 'remove'
+ if(patch === null){
+ this.remove();
+ return _getResolvedPromise(this);
+ }
+ // TODO: make sure that root node is not collapsed or modified
+ // copy (most) attributes to node.ATTR or node.data.ATTR
+ var name, promise, v,
+ IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
+
+ for(name in patch){
+ v = patch[name];
+ if( !IGNORE_MAP[name] && !$.isFunction(v)){
+ if(NODE_ATTR_MAP[name]){
+ this[name] = v;
+ }else{
+ this.data[name] = v;
+ }
+ }
+ }
+ // Remove and/or create children
+ if(patch.hasOwnProperty("children")){
+ this.removeChildren();
+ if(patch.children){ // only if not null and not empty list
+ // TODO: addChildren instead?
+ this._setChildren(patch.children);
+ }
+ // TODO: how can we APPEND or INSERT child nodes?
+ }
+ if(this.isVisible()){
+ this.renderTitle();
+ this.renderStatus();
+ }
+ // Expand collapse (final step, since this may be async)
+ if(patch.hasOwnProperty("expanded")){
+ promise = this.setExpanded(patch.expanded);
+ }else{
+ promise = _getResolvedPromise(this);
+ }
+ return promise;
+ },
+ /** Collapse all sibling nodes.
+ * @returns {$.Promise}
+ */
+ collapseSiblings: function() {
+ return this.tree._callHook("nodeCollapseSiblings", this);
+ },
+ /** Copy this node as sibling or child of `node`.
+ *
+ * @param {FancytreeNode} node source node
+ * @param {string} mode 'before' | 'after' | 'child'
+ * @param {Function} [map] callback function(NodeData) that could modify the new node
+ * @returns {FancytreeNode} new
+ */
+ copyTo: function(node, mode, map) {
+ return node.addNode(this.toDict(true, map), mode);
+ },
+ /** Count direct and indirect children.
+ *
+ * @param {boolean} [deep=true] pass 'false' to only count direct children
+ * @returns {int} number of child nodes
+ */
+ countChildren: function(deep) {
+ var cl = this.children, i, l, n;
+ if( !cl ){
+ return 0;
+ }
+ n = cl.length;
+ if(deep !== false){
+ for(i=0, l=n; i<l; i++){
+ n += cl[i].countChildren();
+ }
+ }
+ return n;
+ },
+ // TODO: deactivate()
+ /** Write to browser console if debugLevel >= 2 (prepending node info)
+ *
+ * @param {*} msg string or object or array of such
+ */
+ debug: function(msg){
+ if( this.tree.options.debugLevel >= 2 ) {
+ Array.prototype.unshift.call(arguments, this.toString());
+ consoleApply("debug", arguments);
+ }
+ },
+ /** Deprecated.
+ * @deprecated since 2014-02-16. Use resetLazy() instead.
+ */
+ discard: function(){
+ this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
+ return this.resetLazy();
+ },
+ // TODO: expand(flag)
+ /**Find all nodes that contain `match` in the title.
+ *
+ * @param {string | function(node)} match string to search for, of a function that
+ * returns `true` if a node is matched.
+ * @returns {FancytreeNode[]} array of nodes (may be empty)
+ * @see FancytreeNode#findAll
+ */
+ findAll: function(match) {
+ match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
+ var res = [];
+ this.visit(function(n){
+ if(match(n)){
+ res.push(n);
+ }
+ });
+ return res;
+ },
+ /**Find first node that contains `match` in the title (not including self).
+ *
+ * @param {string | function(node)} match string to search for, of a function that
+ * returns `true` if a node is matched.
+ * @returns {FancytreeNode} matching node or null
+ * @example
+ * <b>fat</b> text
+ */
+ findFirst: function(match) {
+ match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
+ var res = null;
+ this.visit(function(n){
+ if(match(n)){
+ res = n;
+ return false;
+ }
+ });
+ return res;
+ },
+ /* Apply selection state (internal use only) */
+ _changeSelectStatusAttrs: function (state) {
+ var changed = false;
+
+ switch(state){
+ case false:
+ changed = ( this.selected || this.partsel );
+ this.selected = false;
+ this.partsel = false;
+ break;
+ case true:
+ changed = ( !this.selected || !this.partsel );
+ this.selected = true;
+ this.partsel = true;
+ break;
+ case undefined:
+ changed = ( this.selected || !this.partsel );
+ this.selected = false;
+ this.partsel = true;
+ break;
+ default:
+ _assert(false, "invalid state: " + state);
+ }
+ // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
+ if( changed ){
+ this.renderStatus();
+ }
+ return changed;
+ },
+ /**
+ * Fix selection status, after this node was (de)selected in multi-hier mode.
+ * This includes (de)selecting all children.
+ */
+ fixSelection3AfterClick: function() {
+ var flag = this.isSelected();
+
+// this.debug("fixSelection3AfterClick()");
+
+ this.visit(function(node){
+ node._changeSelectStatusAttrs(flag);
+ });
+ this.fixSelection3FromEndNodes();
+ },
+ /**
+ * Fix selection status for multi-hier mode.
+ * Only end-nodes are considered to update the descendants branch and parents.
+ * Should be called after this node has loaded new children or after
+ * children have been modified using the API.
+ */
+ fixSelection3FromEndNodes: function() {
+// this.debug("fixSelection3FromEndNodes()");
+ _assert(this.tree.options.selectMode === 3, "expected selectMode 3");
+
+ // Visit all end nodes and adjust their parent's `selected` and `partsel`
+ // attributes. Return selection state true, false, or undefined.
+ function _walk(node){
+ var i, l, child, s, state, allSelected,someSelected,
+ children = node.children;
+
+ if( children ){
+ // check all children recursively
+ allSelected = true;
+ someSelected = false;
+
+ for( i=0, l=children.length; i<l; i++ ){
+ child = children[i];
+ // the selection state of a node is not relevant; we need the end-nodes
+ s = _walk(child);
+ if( s !== false ) {
+ someSelected = true;
+ }
+ if( s !== true ) {
+ allSelected = false;
+ }
+ }
+ state = allSelected ? true : (someSelected ? undefined : false);
+ }else{
+ // This is an end-node: simply report the status
+// state = ( node.unselectable ) ? undefined : !!node.selected;
+ state = !!node.selected;
+ }
+ node._changeSelectStatusAttrs(state);
+ return state;
+ }
+ _walk(this);
+
+ // Update parent's state
+ this.visitParents(function(node){
+ var i, l, child, state,
+ children = node.children,
+ allSelected = true,
+ someSelected = false;
+
+ for( i=0, l=children.length; i<l; i++ ){
+ child = children[i];
+ // When fixing the parents, we trust the sibling status (i.e.
+ // we don't recurse)
+ if( child.selected || child.partsel ) {
+ someSelected = true;
+ }
+ if( !child.unselectable && !child.selected ) {
+ allSelected = false;
+ }
+ }
+ state = allSelected ? true : (someSelected ? undefined : false);
+ node._changeSelectStatusAttrs(state);
+ });
+ },
+ // TODO: focus()
+ /**
+ * Update node data. If dict contains 'children', then also replace
+ * the hole sub tree.
+ * @param {NodeData} dict
+ *
+ * @see FancytreeNode#addChildren
+ * @see FancytreeNode#applyPatch
+ */
+ fromDict: function(dict) {
+ // copy all other attributes to this.data.xxx
+ for(var name in dict){
+ if(NODE_ATTR_MAP[name]){
+ // node.NAME = dict.NAME
+ this[name] = dict[name];
+ }else if(name === "data"){
+ // node.data += dict.data
+ $.extend(this.data, dict.data);
+ }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
+ // node.data.NAME = dict.NAME
+ this.data[name] = dict[name];
+ }
+ }
+ if(dict.children){
+ // recursively set children and render
+ this.removeChildren();
+ this.addChildren(dict.children);
+ }
+ this.renderTitle();
+/*
+ var children = dict.children;
+ if(children === undefined){
+ this.data = $.extend(this.data, dict);
+ this.render();
+ return;
+ }
+ dict = $.extend({}, dict);
+ dict.children = undefined;
+ this.data = $.extend(this.data, dict);
+ this.removeChildren();
+ this.addChild(children);
+*/
+ },
+ /** Return the list of child nodes (undefined for unexpanded lazy nodes).
+ * @returns {FancytreeNode[] | undefined}
+ */
+ getChildren: function() {
+ if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
+ return undefined; // Lazy node: unloaded, currently loading, or load error
+ }
+ return this.children;
+ },
+ /** Return the first child node or null.
+ * @returns {FancytreeNode | null}
+ */
+ getFirstChild: function() {
+ return this.children ? this.children[0] : null;
+ },
+ /** Return the 0-based child index.
+ * @returns {int}
+ */
+ getIndex: function() {
+// return this.parent.children.indexOf(this);
+ return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
+ },
+ /** Return the hierarchical child index (1-based, e.g. '3.2.4').
+ * @returns {string}
+ */
+ getIndexHier: function(separator) {
+ separator = separator || ".";
+ var res = [];
+ $.each(this.getParentList(false, true), function(i, o){
+ res.push(o.getIndex() + 1);
+ });
+ return res.join(separator);
+ },
+ /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
+ * @param {boolean} [excludeSelf=false]
+ * @returns {string}
+ */
+ getKeyPath: function(excludeSelf) {
+ var path = [],
+ sep = this.tree.options.keyPathSeparator;
+ this.visitParents(function(n){
+ if(n.parent){
+ path.unshift(n.key);
+ }
+ }, !excludeSelf);
+ return sep + path.join(sep);
+ },
+ /** Return the last child of this node or null.
+ * @returns {FancytreeNode | null}
+ */
+ getLastChild: function() {
+ return this.children ? this.children[this.children.length - 1] : null;
+ },
+ /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
+ * @returns {int}
+ */
+ getLevel: function() {
+ var level = 0,
+ dtn = this.parent;
+ while( dtn ) {
+ level++;
+ dtn = dtn.parent;
+ }
+ return level;
+ },
+ /** Return the successor node (under the same parent) or null.
+ * @returns {FancytreeNode | null}
+ */
+ getNextSibling: function() {
+ // TODO: use indexOf, if available: (not in IE6)
+ if( this.parent ){
+ var i, l,
+ ac = this.parent.children;
+
+ for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
+ if( ac[i] === this ){
+ return ac[i+1];
+ }
+ }
+ }
+ return null;
+ },
+ /** Return the parent node (null for the system root node).
+ * @returns {FancytreeNode | null}
+ */
+ getParent: function() {
+ // TODO: return null for top-level nodes?
+ return this.parent;
+ },
+ /** Return an array of all parent nodes (top-down).
+ * @param {boolean} [includeRoot=false] Include the invisible system root node.
+ * @param {boolean} [includeSelf=false] Include the node itself.
+ * @returns {FancytreeNode[]}
+ */
+ getParentList: function(includeRoot, includeSelf) {
+ var l = [],
+ dtn = includeSelf ? this : this.parent;
+ while( dtn ) {
+ if( includeRoot || dtn.parent ){
+ l.unshift(dtn);
+ }
+ dtn = dtn.parent;
+ }
+ return l;
+ },
+ /** Return the predecessor node (under the same parent) or null.
+ * @returns {FancytreeNode | null}
+ */
+ getPrevSibling: function() {
+ if( this.parent ){
+ var i, l,
+ ac = this.parent.children;
+
+ for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
+ if( ac[i] === this ){
+ return ac[i-1];
+ }
+ }
+ }
+ return null;
+ },
+ /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
+ * @returns {boolean | undefined}
+ */
+ hasChildren: function() {
+ if(this.lazy){
+ if(this.children == null ){
+ // null or undefined: Not yet loaded
+ return undefined;
+ }else if(this.children.length === 0){
+ // Loaded, but response was empty
+ return false;
+ }else if(this.children.length === 1 && this.children[0].isStatusNode() ){
+ // Currently loading or load error
+ return undefined;
+ }
+ return true;
+ }
+ return !!this.children;
+ },
+ /** Return true if node has keyboard focus.
+ * @returns {boolean}
+ */
+ hasFocus: function() {
+ return (this.tree.hasFocus() && this.tree.focusNode === this);
+ },
+ /** Return true if node is active (see also FancytreeNode#isSelected).
+ * @returns {boolean}
+ */
+ isActive: function() {
+ return (this.tree.activeNode === this);
+ },
+ /** Return true if node is a direct child of otherNode.
+ * @param {FancytreeNode} otherNode
+ * @returns {boolean}
+ */
+ isChildOf: function(otherNode) {
+ return (this.parent && this.parent === otherNode);
+ },
+ /** Return true, if node is a direct or indirect sub node of otherNode.
+ * @param {FancytreeNode} otherNode
+ * @returns {boolean}
+ */
+ isDescendantOf: function(otherNode) {
+ if(!otherNode || otherNode.tree !== this.tree){
+ return false;
+ }
+ var p = this.parent;
+ while( p ) {
+ if( p === otherNode ){
+ return true;
+ }
+ p = p.parent;
+ }
+ return false;
+ },
+ /** Return true if node is expanded.
+ * @returns {boolean}
+ */
+ isExpanded: function() {
+ return !!this.expanded;
+ },
+ /** Return true if node is the first node of its parent's children.
+ * @returns {boolean}
+ */
+ isFirstSibling: function() {
+ var p = this.parent;
+ return !p || p.children[0] === this;
+ },
+ /** Return true if node is a folder, i.e. has the node.folder attribute set.
+ * @returns {boolean}
+ */
+ isFolder: function() {
+ return !!this.folder;
+ },
+ /** Return true if node is the last node of its parent's children.
+ * @returns {boolean}
+ */
+ isLastSibling: function() {
+ var p = this.parent;
+ return !p || p.children[p.children.length-1] === this;
+ },
+ /** Return true if node is lazy (even if data was already loaded)
+ * @returns {boolean}
+ */
+ isLazy: function() {
+ return !!this.lazy;
+ },
+ /** Return true if node is lazy and loaded. For non-lazy nodes always return true.
+ * @returns {boolean}
+ */
+ isLoaded: function() {
+ return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
+ },
+ /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
+ * @returns {boolean}
+ */
+ isLoading: function() {
+ return !!this._isLoading;
+ },
+ /** Return true if this is the (invisible) system root node.
+ * @returns {boolean}
+ */
+ isRoot: function() {
+ return (this.tree.rootNode === this);
+ },
+ /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
+ * @returns {boolean}
+ */
+ isSelected: function() {
+ return !!this.selected;
+ },
+ /** Return true if this node is a temporarily generated system node like
+ * 'loading', or 'error' (node.statusNodeType contains the type).
+ * @returns {boolean}
+ */
+ isStatusNode: function() {
+ return !!this.statusNodeType;
+ },
+ /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
+ * @returns {boolean}
+ */
+ isUndefined: function() {
+ return this.hasChildren() === undefined; // also checks if the only child is a status node
+ },
+ /** Return true if all parent nodes are expanded. Note: this does not check
+ * whether the node is scrolled into the visible part of the screen.
+ * @returns {boolean}
+ */
+ isVisible: function() {
+ var i, l,
+ parents = this.getParentList(false, false);
+
+ for(i=0, l=parents.length; i<l; i++){
+ if( ! parents[i].expanded ){ return false; }
+ }
+ return true;
+ },
+ /** Deprecated.
+ * @deprecated since 2014-02-16: use load() instead.
+ */
+ lazyLoad: function(discard) {
+ this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
+ return this.load(discard);
+ },
+ /**
+ * Load all children of a lazy node.
+ * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
+ * @returns {$.Promise}
+ */
+ load: function(forceReload) {
+ var res, source,
+ that = this;
+
+ _assert( this.isLazy(), "load() requires a lazy node" );
+ _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
+
+ if( this.isLoaded() ){
+ this.resetLazy(); // also collapses
+ }
+ // This method is also called by setExpanded() and loadKeyPath(), so we
+ // have to avoid recursion.
+ source = this.tree._triggerNodeEvent("lazyLoad", this);
+ if( source === false ) { // #69
+ return _getResolvedPromise(this);
+ }
+ _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
+ res = this.tree._callHook("nodeLoadChildren", this, source);
+ if( this.expanded ) {
+ res.always(function(){
+ that.render();
+ });
+ }
+ return res;
+ },
+ /** Expand all parents and optionally scroll into visible area as neccessary.
+ * Promise is resolved, when lazy loading and animations are done.
+ * @param {object} [opts] passed to `setExpanded()`.
+ * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
+ * @returns {$.Promise}
+ */
+ makeVisible: function(opts) {
+ var i,
+ that = this,
+ deferreds = [],
+ dfd = new $.Deferred(),
+ parents = this.getParentList(false, false),
+ len = parents.length,
+ effects = !(opts && opts.noAnimation === true),
+ scroll = !(opts && opts.scrollIntoView === false);
+
+ // Expand bottom-up, so only the top node is animated
+ for(i = len - 1; i >= 0; i--){
+ // that.debug("pushexpand" + parents[i]);
+ deferreds.push(parents[i].setExpanded(true, opts));
+ }
+ $.when.apply($, deferreds).done(function(){
+ // All expands have finished
+ // that.debug("expand DONE", scroll);
+ if( scroll ){
+ that.scrollIntoView(effects).done(function(){
+ // that.debug("scroll DONE");
+ dfd.resolve();
+ });
+ } else {
+ dfd.resolve();
+ }
+ });
+ return dfd.promise();
+ },
+ /** Move this node to targetNode.
+ * @param {FancytreeNode} targetNode
+ * @param {string} mode <pre>
+ * 'child': append this node as last child of targetNode.
+ * This is the default. To be compatble with the D'n'd
+ * hitMode, we also accept 'over'.
+ * 'before': add this node as sibling before targetNode.
+ * 'after': add this node as sibling after targetNode.</pre>
+ * @param {function} [map] optional callback(FancytreeNode) to allow modifcations
+ */
+ moveTo: function(targetNode, mode, map) {
+ if(mode === undefined || mode === "over"){
+ mode = "child";
+ }
+ var pos,
+ prevParent = this.parent,
+ targetParent = (mode === "child") ? targetNode : targetNode.parent;
+
+ if(this === targetNode){
+ return;
+ }else if( !this.parent ){
+ throw "Cannot move system root";
+ }else if( targetParent.isDescendantOf(this) ){
+ throw "Cannot move a node to its own descendant";
+ }
+ // Unlink this node from current parent
+ if( this.parent.children.length === 1 ) {
+ this.parent.children = this.parent.lazy ? [] : null;
+ this.parent.expanded = false;
+ } else {
+ pos = $.inArray(this, this.parent.children);
+ _assert(pos >= 0);
+ this.parent.children.splice(pos, 1);
+ }
+ // Remove from source DOM parent
+// if(this.parent.ul){
+// this.parent.ul.removeChild(this.li);
+// }
+
+ // Insert this node to target parent's child list
+ this.parent = targetParent;
+ if( targetParent.hasChildren() ) {
+ switch(mode) {
+ case "child":
+ // Append to existing target children
+ targetParent.children.push(this);
+ break;
+ case "before":
+ // Insert this node before target node
+ pos = $.inArray(targetNode, targetParent.children);
+ _assert(pos >= 0);
+ targetParent.children.splice(pos, 0, this);
+ break;
+ case "after":
+ // Insert this node after target node
+ pos = $.inArray(targetNode, targetParent.children);
+ _assert(pos >= 0);
+ targetParent.children.splice(pos+1, 0, this);
+ break;
+ default:
+ throw "Invalid mode " + mode;
+ }
+ } else {
+ targetParent.children = [ this ];
+ }
+ // Parent has no <ul> tag yet:
+// if( !targetParent.ul ) {
+// // This is the parent's first child: create UL tag
+// // (Hidden, because it will be
+// targetParent.ul = document.createElement("ul");
+// targetParent.ul.style.display = "none";
+// targetParent.li.appendChild(targetParent.ul);
+// }
+// // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
+// if(this.li){
+// targetParent.ul.appendChild(this.li);
+// }^
+
+ // Let caller modify the nodes
+ if( map ){
+ targetNode.visit(map, true);
+ }
+ // Handle cross-tree moves
+ if( this.tree !== targetNode.tree ) {
+ // Fix node.tree for all source nodes
+// _assert(false, "Cross-tree move is not yet implemented.");
+ this.warn("Cross-tree moveTo is experimantal!");
+ this.visit(function(n){
+ // TODO: fix selection state and activation, ...
+ n.tree = targetNode.tree;
+ }, true);
+ }
+
+ // A collaposed node won't re-render children, so we have to remove it manually
+ // if( !targetParent.expanded ){
+ // prevParent.ul.removeChild(this.li);
+ // }
+
+ // Update HTML markup
+ if( !prevParent.isDescendantOf(targetParent)) {
+ prevParent.render();
+ }
+ if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
+ targetParent.render();
+ }
+ // TODO: fix selection state
+ // TODO: fix active state
+
+/*
+ var tree = this.tree;
+ var opts = tree.options;
+ var pers = tree.persistence;
+
+
+ // Always expand, if it's below minExpandLevel
+// tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
+ if ( opts.minExpandLevel >= ftnode.getLevel() ) {
+// tree.logDebug ("Force expand for %o", ftnode);
+ this.bExpanded = true;
+ }
+
+ // In multi-hier mode, update the parents selection state
+ // DT issue #82: only if not initializing, because the children may not exist yet
+// if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
+// ftnode._fixSelectionState();
+
+ // In multi-hier mode, update the parents selection state
+ if( ftnode.bSelected && opts.selectMode==3 ) {
+ var p = this;
+ while( p ) {
+ if( !p.hasSubSel )
+ p._setSubSel(true);
+ p = p.parent;
+ }
+ }
+ // render this node and the new child
+ if ( tree.bEnableUpdate )
+ this.render();
+
+ return ftnode;
+
+*/
+ },
+ /** Set focus relative to this node and optionally activate.
+ *
+ * @param {number} where The keyCode that would normally trigger this move,
+ * e.g. `$.ui.keyCode.LEFT` would collapse the node if it
+ * is expanded or move to the parent oterwise.
+ * @param {boolean} [activate=true]
+ * @returns {$.Promise}
+ */
+ navigate: function(where, activate) {
+ var i, parents,
+ handled = true,
+ KC = $.ui.keyCode,
+ sib = null;
+
+ // Navigate to node
+ function _goto(n){
+ if( n ){
+ n.makeVisible();
+ // Node may still be hidden by a filter
+ if( ! $(n.span).is(":visible") ) {
+ n.debug("Navigate: skipping hidden node");
+ n.navigate(where, activate);
+ return;
+ }
+ return activate === false ? n.setFocus() : n.setActive();
+ }
+ }
+
+ switch( where ) {
+ case KC.BACKSPACE:
+ if( this.parent && this.parent.parent ) {
+ _goto(this.parent);
+ }
+ break;
+ case KC.LEFT:
+ if( this.expanded ) {
+ this.setExpanded(false);
+ _goto(this);
+ } else if( this.parent && this.parent.parent ) {
+ _goto(this.parent);
+ }
+ break;
+ case KC.RIGHT:
+ if( !this.expanded && (this.children || this.lazy) ) {
+ this.setExpanded();
+ _goto(this);
+ } else if( this.children && this.children.length ) {
+ _goto(this.children[0]);
+ }
+ break;
+ case KC.UP:
+ sib = this.getPrevSibling();
+ while( sib && sib.expanded && sib.children && sib.children.length ){
+ sib = sib.children[sib.children.length - 1];
+ }
+ if( !sib && this.parent && this.parent.parent ){
+ sib = this.parent;
+ }
+ _goto(sib);
+ break;
+ case KC.DOWN:
+ if( this.expanded && this.children && this.children.length ) {
+ sib = this.children[0];
+ } else {
+ parents = this.getParentList(false, true);
+ for(i=parents.length-1; i>=0; i--) {
+ sib = parents[i].getNextSibling();
+ if( sib ){ break; }
+ }
+ }
+ _goto(sib);
+ break;
+ default:
+ handled = false;
+ }
+ },
+ /**
+ * Remove this node (not allowed for system root).
+ */
+ remove: function() {
+ return this.parent.removeChild(this);
+ },
+ /**
+ * Remove childNode from list of direct children.
+ * @param {FancytreeNode} childNode
+ */
+ removeChild: function(childNode) {
+ return this.tree._callHook("nodeRemoveChild", this, childNode);
+ },
+ /**
+ * Remove all child nodes and descendents. This converts the node into a leaf.<br>
+ * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
+ * in order to trigger lazyLoad on next expand.
+ */
+ removeChildren: function() {
+ return this.tree._callHook("nodeRemoveChildren", this);
+ },
+ /**
+ * This method renders and updates all HTML markup that is required
+ * to display this node in its current state.<br>
+ * Note:
+ * <ul>
+ * <li>It should only be neccessary to call this method after the node object
+ * was modified by direct access to its properties, because the common
+ * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
+ * already handle this.
+ * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
+ * are implied. If changes are more local, calling only renderTitle() or
+ * renderStatus() may be sufficient and faster.
+ * <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
+ * </ul>
+ *
+ * @param {boolean} [force=false] re-render, even if html markup was already created
+ * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
+ */
+ render: function(force, deep) {
+ return this.tree._callHook("nodeRender", this, force, deep);
+ },
+ /** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
+ * @see Fancytree_Hooks#nodeRenderTitle
+ */
+ renderTitle: function() {
+ return this.tree._callHook("nodeRenderTitle", this);
+ },
+ /** Update element's CSS classes according to node state.
+ * @see Fancytree_Hooks#nodeRenderStatus
+ */
+ renderStatus: function() {
+ return this.tree._callHook("nodeRenderStatus", this);
+ },
+ /**
+ * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
+ * event is triggered on next expand.
+ */
+ resetLazy: function() {
+ this.removeChildren();
+ this.expanded = false;
+ this.lazy = true;
+ this.children = undefined;
+ this.renderStatus();
+ },
+ /** Schedule activity for delayed execution (cancel any pending request).
+ * scheduleAction('cancel') will only cancel a pending request (if any).
+ * @param {string} mode
+ * @param {number} ms
+ */
+ scheduleAction: function(mode, ms) {
+ if( this.tree.timer ) {
+ clearTimeout(this.tree.timer);
+// this.tree.debug("clearTimeout(%o)", this.tree.timer);
+ }
+ this.tree.timer = null;
+ var self = this; // required for closures
+ switch (mode) {
+ case "cancel":
+ // Simply made sure that timer was cleared
+ break;
+ case "expand":
+ this.tree.timer = setTimeout(function(){
+ self.tree.debug("setTimeout: trigger expand");
+ self.setExpanded(true);
+ }, ms);
+ break;
+ case "activate":
+ this.tree.timer = setTimeout(function(){
+ self.tree.debug("setTimeout: trigger activate");
+ self.setActive(true);
+ }, ms);
+ break;
+ default:
+ throw "Invalid mode " + mode;
+ }
+// this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
+ },
+ /**
+ *
+ * @param {boolean | PlainObject} [effects=false] animation options.
+ * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
+ * any case, even if `this` is outside the scroll pane.
+ * @returns {$.Promise}
+ */
+ scrollIntoView: function(effects, options) {
+ if( options !== undefined && _isNode(options) ) {
+ this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead.");
+ options = {topNode: options};
+ }
+ // this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent);
+ // this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container;
+
+ var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop,
+ opts = $.extend({
+ effects: (effects === true) ? {duration: 200, queue: false} : effects,
+ scrollOfs: this.tree.options.scrollOfs,
+ scrollParent: this.tree.options.scrollParent || this.tree.$container,
+ topNode: null
+ }, options),
+ dfd = new $.Deferred(),
+ that = this,
+ nodeHeight = $(this.span).height(),
+ $container = $(opts.scrollParent),
+ topOfs = opts.scrollOfs.top || 0,
+ bottomOfs = opts.scrollOfs.bottom || 0,
+ containerHeight = $container.height(),// - topOfs - bottomOfs,
+ scrollTop = $container.scrollTop(),
+ $animateTarget = $container,
+ isParentWindow = $container[0] === window,
+ topNode = opts.topNode || null,
+ newScrollTop = null;
+
+ // this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs);
+ _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
+
+ if( isParentWindow ) {
+ nodeY = $(this.span).offset().top;
+ topNodeY = topNode ? $(topNode.span).offset().top : 0;
+ $animateTarget = $("html,body");
+
+ } else {
+ _assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body.");
+
+ containerOffsetTop = $container.offset().top,
+ nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
+ topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0;
+ horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight));
+ containerHeight -= horzScrollbarHeight;
+ }
+
+ // this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight);
+ if( nodeY < (scrollTop + topOfs) ){
+ // Node is above visible container area
+ newScrollTop = nodeY - topOfs;
+ // this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop);
+
+ }else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){
+ newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
+ // this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop);
+ // If a topNode was passed, make sure that it is never scrolled
+ // outside the upper border
+ if(topNode){
+ _assert($(topNode.span).is(":visible"));
+ if( topNodeY < newScrollTop ){
+ newScrollTop = topNodeY - topOfs;
+ // this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop);
+ }
+ }
+ }
+
+ if(newScrollTop !== null){
+ // this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop);
+ if(opts.effects){
+ opts.effects.complete = function(){
+ dfd.resolveWith(that);
+ };
+ $animateTarget.stop(true).animate({
+ scrollTop: newScrollTop
+ }, opts.effects);
+ }else{
+ $animateTarget[0].scrollTop = newScrollTop;
+ dfd.resolveWith(this);
+ }
+ }else{
+ dfd.resolveWith(this);
+ }
+ return dfd.promise();
+ },
+
+ /**Activate this node.
+ * @param {boolean} [flag=true] pass false to deactivate
+ * @param {object} [opts] additional options. Defaults to {noEvents: false}
+ */
+ setActive: function(flag, opts){
+ return this.tree._callHook("nodeSetActive", this, flag, opts);
+ },
+ /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
+ * @param {boolean} [flag=true] pass false to collapse
+ * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
+ * @returns {$.Promise}
+ */
+ setExpanded: function(flag, opts){
+ return this.tree._callHook("nodeSetExpanded", this, flag, opts);
+ },
+ /**Set keyboard focus to this node.
+ * @param {boolean} [flag=true] pass false to blur
+ * @see Fancytree#setFocus
+ */
+ setFocus: function(flag){
+ return this.tree._callHook("nodeSetFocus", this, flag);
+ },
+ // TODO: setLazyNodeStatus
+ /**Select this node, i.e. check the checkbox.
+ * @param {boolean} [flag=true] pass false to deselect
+ */
+ setSelected: function(flag){
+ return this.tree._callHook("nodeSetSelected", this, flag);
+ },
+ /**Rename this node.
+ * @param {string} title
+ */
+ setTitle: function(title){
+ this.title = title;
+ this.renderTitle();
+ },
+ /**Sort child list by title.
+ * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
+ * @param {boolean} [deep=false] pass true to sort all descendant nodes
+ */
+ sortChildren: function(cmp, deep) {
+ var i,l,
+ cl = this.children;
+
+ if( !cl ){
+ return;
+ }
+ cmp = cmp || function(a, b) {
+ var x = a.title.toLowerCase(),
+ y = b.title.toLowerCase();
+ return x === y ? 0 : x > y ? 1 : -1;
+ };
+ cl.sort(cmp);
+ if( deep ){
+ for(i=0, l=cl.length; i<l; i++){
+ if( cl[i].children ){
+ cl[i].sortChildren(cmp, "$norender$");
+ }
+ }
+ }
+ if( deep !== "$norender$" ){
+ this.render();
+ }
+ },
+ /** Convert node (or whole branch) into a plain object.
+ *
+ * The result is compatible with node.addChildren().
+ *
+ * @param {boolean} recursive
+ * @param {function} callback callback(dict) is called for every node, in order to allow modifications
+ * @returns {NodeData}
+ */
+ toDict: function(recursive, callback) {
+ var i, l, node,
+ dict = {},
+ self = this;
+
+ $.each(NODE_ATTRS, function(i, a){
+ if(self[a] || self[a] === false){
+ dict[a] = self[a];
+ }
+ });
+ if(!$.isEmptyObject(this.data)){
+ dict.data = $.extend({}, this.data);
+ if($.isEmptyObject(dict.data)){
+ delete dict.data;
+ }
+ }
+ if( callback ){
+ callback(dict);
+ }
+ if( recursive ) {
+ if(this.hasChildren()){
+ dict.children = [];
+ for(i=0, l=this.children.length; i<l; i++ ){
+ node = this.children[i];
+ if( !node.isStatusNode() ){
+ dict.children.push(node.toDict(true, callback));
+ }
+ }
+ }else{
+// dict.children = null;
+ }
+ }
+ return dict;
+ },
+ /** Flip expanded status. */
+ toggleExpanded: function(){
+ return this.tree._callHook("nodeToggleExpanded", this);
+ },
+ /** Flip selection status. */
+ toggleSelected: function(){
+ return this.tree._callHook("nodeToggleSelected", this);
+ },
+ toString: function() {
+ return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
+ },
+ /** Call fn(node) for all child nodes.<br>
+ * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
+ * Return false if iteration was stopped.
+ *
+ * @param {function} fn the callback function.
+ * Return false to stop iteration, return "skip" to skip this node and children only.
+ * @param {boolean} [includeSelf=false]
+ * @returns {boolean}
+ */
+ visit: function(fn, includeSelf) {
+ var i, l,
+ res = true,
+ children = this.children;
+
+ if( includeSelf === true ) {
+ res = fn(this);
+ if( res === false || res === "skip" ){
+ return res;
+ }
+ }
+ if(children){
+ for(i=0, l=children.length; i<l; i++){
+ res = children[i].visit(fn, true);
+ if( res === false ){
+ break;
+ }
+ }
+ }
+ return res;
+ },
+ /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
+ * Stop iteration, if fn() returns false.<br>
+ * Return false if iteration was stopped.
+ *
+ * @param {function} fn the callback function.
+ * Return false to stop iteration, return "skip" to skip this node and children only.
+ * @param {boolean} [includeSelf=false]
+ * @returns {boolean}
+ */
+ visitParents: function(fn, includeSelf) {
+ // Visit parent nodes (bottom up)
+ if(includeSelf && fn(this) === false){
+ return false;
+ }
+ var p = this.parent;
+ while( p ) {
+ if(fn(p) === false){
+ return false;
+ }
+ p = p.parent;
+ }
+ return true;
+ },
+ /** Write warning to browser console (prepending node info)
+ *
+ * @param {*} msg string or object or array of such
+ */
+ warn: function(msg){
+ Array.prototype.unshift.call(arguments, this.toString());
+ consoleApply("warn", arguments);
+ }
+};
+
+
+/* *****************************************************************************
+ * Fancytree
+ */
+/**
+ * Construct a new tree object.
+ *
+ * @class Fancytree
+ * @classdesc The controller behind a fancytree.
+ * This class also contains 'hook methods': see {@link Fancytree_Hooks}.
+ *
+ * @param {Widget} widget
+ *
+ * @property {FancytreeOptions} options
+ * @property {FancytreeNode} rootNode
+ * @property {FancytreeNode} activeNode
+ * @property {FancytreeNode} focusNode
+ * @property {jQueryObject} $div
+ * @property {object} widget
+ * @property {object} ext
+ * @property {object} data
+ * @property {object} options
+ * @property {string} _id
+ * @property {string} statusClassPropName
+ * @property {string} ariaPropName
+ * @property {string} nodeContainerAttrName
+ * @property {string} $container
+ * @property {FancytreeNode} lastSelectedNode
+ */
+function Fancytree(widget) {
+ this.widget = widget;
+ this.$div = widget.element;
+ this.options = widget.options;
+ if( this.options && $.isFunction(this.options.lazyload) ) {
+ if( ! $.isFunction(this.options.lazyLoad ) ) {
+ this.options.lazyLoad = function() {
+ FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
+ widget.options.lazyload.apply(this, arguments);
+ };
+ }
+ }
+ this.ext = {}; // Active extension instances
+ // allow to init tree.data.foo from <div data-foo=''>
+ this.data = _getElementDataAsDict(this.$div);
+ this._id = $.ui.fancytree._nextId++;
+ this._ns = ".fancytree-" + this._id; // append for namespaced events
+ this.activeNode = null;
+ this.focusNode = null;
+ this._hasFocus = null;
+ this.lastSelectedNode = null;
+ this.systemFocusElement = null;
+
+ this.statusClassPropName = "span";
+ this.ariaPropName = "li";
+ this.nodeContainerAttrName = "li";
+
+ // Remove previous markup if any
+ this.$div.find(">ul.fancytree-container").remove();
+
+ // Create a node without parent.
+ var fakeParent = { tree: this },
+ $ul;
+ this.rootNode = new FancytreeNode(fakeParent, {
+ title: "root",
+ key: "root_" + this._id,
+ children: null,
+ expanded: true
+ });
+ this.rootNode.parent = null;
+
+ // Create root markup
+ $ul = $("<ul>", {
+ "class": "ui-fancytree fancytree-container"
+ }).appendTo(this.$div);
+ this.$container = $ul;
+ this.rootNode.ul = $ul[0];
+
+ if(this.options.debugLevel == null){
+ this.options.debugLevel = FT.debugLevel;
+ }
+ // Add container to the TAB chain
+ // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
+ this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
+ if(this.options.aria){
+ this.$container
+ .attr("role", "tree")
+ .attr("aria-multiselectable", true);
+ }
+}
+
+
+Fancytree.prototype = /** @lends Fancytree# */{
+ /* Return a context object that can be re-used for _callHook().
+ * @param {Fancytree | FancytreeNode | EventData} obj
+ * @param {Event} originalEvent
+ * @param {Object} extra
+ * @returns {EventData}
+ */
+ _makeHookContext: function(obj, originalEvent, extra) {
+ var ctx, tree;
+ if(obj.node !== undefined){
+ // obj is already a context object
+ if(originalEvent && obj.originalEvent !== originalEvent){
+ $.error("invalid args");
+ }
+ ctx = obj;
+ }else if(obj.tree){
+ // obj is a FancytreeNode
+ tree = obj.tree;
+ ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
+ }else if(obj.widget){
+ // obj is a Fancytree
+ ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
+ }else{
+ $.error("invalid args");
+ }
+ if(extra){
+ $.extend(ctx, extra);
+ }
+ return ctx;
+ },
+ /* Trigger a hook function: funcName(ctx, [...]).
+ *
+ * @param {string} funcName
+ * @param {Fancytree|FancytreeNode|EventData} contextObject
+ * @param {any} [_extraArgs] optional additional arguments
+ * @returns {any}
+ */
+ _callHook: function(funcName, contextObject, _extraArgs) {
+ var ctx = this._makeHookContext(contextObject),
+ fn = this[funcName],
+ args = Array.prototype.slice.call(arguments, 2);
+ if(!$.isFunction(fn)){
+ $.error("_callHook('" + funcName + "') is not a function");
+ }
+ args.unshift(ctx);
+// this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
+ return fn.apply(this, args);
+ },
+ /* Check if current extensions dependencies are met and throw an error if not.
+ *
+ * This method may be called inside the `treeInit` hook for custom extensions.
+ *
+ * @param {string} extension name of the required extension
+ * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
+ * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
+ * @param {string} [message] optional error message (defaults to a descriptve error message)
+ */
+ _requireExtension: function(name, required, before, message) {
+ before = !!before;
+ var thisName = this._local.name,
+ extList = this.options.extensions,
+ isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
+ isMissing = required && this.ext[name] == null,
+ badOrder = !isMissing && before != null && (before !== isBefore);
+
+ _assert(thisName && thisName !== name);
+
+ if( isMissing || badOrder ){
+ if( !message ){
+ if( isMissing || required ){
+ message = "'" + thisName + "' extension requires '" + name + "'";
+ if( badOrder ){
+ message += " to be registered " + (before ? "before" : "after") + " itself";
+ }
+ }else{
+ message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
+ }
+ }
+ $.error(message);
+ return false;
+ }
+ return true;
+ },
+ /** Activate node with a given key and fire focus and activate events.
+ *
+ * A prevously activated node will be deactivated.
+ * If activeVisible option is set, all parents will be expanded as necessary.
+ * Pass key = false, to deactivate the current node only.
+ * @param {string} key
+ * @returns {FancytreeNode} activated node (null, if not found)
+ */
+ activateKey: function(key) {
+ var node = this.getNodeByKey(key);
+ if(node){
+ node.setActive();
+ }else if(this.activeNode){
+ this.activeNode.setActive(false);
+ }
+ return node;
+ },
+ /** (experimental)
+ *
+ * @param {Array} patchList array of [key, NodePatch] arrays
+ * @returns {$.Promise} resolved, when all patches have been applied
+ * @see TreePatch
+ */
+ applyPatch: function(patchList) {
+ var dfd, i, p2, key, patch, node,
+ patchCount = patchList.length,
+ deferredList = [];
+
+ for(i=0; i<patchCount; i++){
+ p2 = patchList[i];
+ _assert(p2.length === 2, "patchList must be an array of length-2-arrays");
+ key = p2[0];
+ patch = p2[1];
+ node = (key === null) ? this.rootNode : this.getNodeByKey(key);
+ if(node){
+ dfd = new $.Deferred();
+ deferredList.push(dfd);
+ node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
+ }else{
+ this.warn("could not find node with key '" + key + "'");
+ }
+ }
+ // Return a promise that is resovled, when ALL patches were applied
+ return $.when.apply($, deferredList).promise();
+ },
+ /* TODO: implement in dnd extension
+ cancelDrag: function() {
+ var dd = $.ui.ddmanager.current;
+ if(dd){
+ dd.cancel();
+ }
+ },
+ */
+ /** Return the number of nodes.
+ * @returns {integer}
+ */
+ count: function() {
+ return this.rootNode.countChildren();
+ },
+ /** Write to browser console if debugLevel >= 2 (prepending tree name)
+ *
+ * @param {*} msg string or object or array of such
+ */
+ debug: function(msg){
+ if( this.options.debugLevel >= 2 ) {
+ Array.prototype.unshift.call(arguments, this.toString());
+ consoleApply("debug", arguments);
+ }
+ },
+ // TODO: disable()
+ // TODO: enable()
+ // TODO: enableUpdate()
+ // TODO: fromDict
+ /**
+ * Generate INPUT elements that can be submitted with html forms.
+ *
+ * In selectMode 3 only the topmost selected nodes are considered.
+ *
+ * @param {boolean | string} [selected=true]
+ * @param {boolean | string} [active=true]
+ */
+ generateFormElements: function(selected, active) {
+ // TODO: test case
+ var nodeList,
+ selectedName = (selected !== false) ? "ft_" + this._id : selected,
+ activeName = (active !== false) ? "ft_" + this._id + "_active" : active,
+ id = "fancytree_result_" + this._id,
+ $result = this.$container.find("div#" + id);
+
+ if($result.length){
+ $result.empty();
+ }else{
+ $result = $("<div>", {
+ id: id
+ }).hide().appendTo(this.$container);
+ }
+ if(selectedName){
+ nodeList = this.getSelectedNodes( this.options.selectMode === 3 );
+ $.each(nodeList, function(idx, node){
+ $result.append($("<input>", {
+ type: "checkbox",
+ name: selectedName,
+ value: node.key,
+ checked: true
+ }));
+ });
+ }
+ if(activeName && this.activeNode){
+ $result.append($("<input>", {
+ type: "radio",
+ name: activeName,
+ value: this.activeNode.key,
+ checked: true
+ }));
+ }
+ },
+ /**
+ * Return the currently active node or null.
+ * @returns {FancytreeNode}
+ */
+ getActiveNode: function() {
+ return this.activeNode;
+ },
+ /** Return the first top level node if any (not the invisible root node).
+ * @returns {FancytreeNode | null}
+ */
+ getFirstChild: function() {
+ return this.rootNode.getFirstChild();
+ },
+ /**
+ * Return node that has keyboard focus.
+ * @param {boolean} [ifTreeHasFocus=false] (not yet implemented)
+ * @returns {FancytreeNode}
+ */
+ getFocusNode: function(ifTreeHasFocus) {
+ // TODO: implement ifTreeHasFocus
+ return this.focusNode;
+ },
+ /**
+ * Return node with a given key or null if not found.
+ * @param {string} key
+ * @param {FancytreeNode} [searchRoot] only search below this node
+ * @returns {FancytreeNode | null}
+ */
+ getNodeByKey: function(key, searchRoot) {
+ // Search the DOM by element ID (assuming this is faster than traversing all nodes).
+ // $("#...") has problems, if the key contains '.', so we use getElementById()
+ var el, match;
+ if(!searchRoot){
+ el = document.getElementById(this.options.idPrefix + key);
+ if( el ){
+ return el.ftnode ? el.ftnode : null;
+ }
+ }
+ // Not found in the DOM, but still may be in an unrendered part of tree
+ // TODO: optimize with specialized loop
+ // TODO: consider keyMap?
+ searchRoot = searchRoot || this.rootNode;
+ match = null;
+ searchRoot.visit(function(node){
+// window.console.log("getNodeByKey(" + key + "): ", node.key);
+ if(node.key === key) {
+ match = node;
+ return false;
+ }
+ }, true);
+ return match;
+ },
+ // TODO: getRoot()
+ /**
+ * Return an array of selected nodes.
+ * @param {boolean} [stopOnParents=false] only return the topmost selected
+ * node (useful with selectMode 3)
+ * @returns {FancytreeNode[]}
+ */
+ getSelectedNodes: function(stopOnParents) {
+ var nodeList = [];
+ this.rootNode.visit(function(node){
+ if( node.selected ) {
+ nodeList.push(node);
+ if( stopOnParents === true ){
+ return "skip"; // stop processing this branch
+ }
+ }
+ });
+ return nodeList;
+ },
+ /** Return true if the tree control has keyboard focus
+ * @returns {boolean}
+ */
+ hasFocus: function(){
+ return !!this._hasFocus;
+ },
+ /** Write to browser console if debugLevel >= 1 (prepending tree name)
+ * @param {*} msg string or object or array of such
+ */
+ info: function(msg){
+ if( this.options.debugLevel >= 1 ) {
+ Array.prototype.unshift.call(arguments, this.toString());
+ consoleApply("info", arguments);
+ }
+ },
+/*
+ TODO: isInitializing: function() {
+ return ( this.phase=="init" || this.phase=="postInit" );
+ },
+ TODO: isReloading: function() {
+ return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
+ },
+ TODO: isUserEvent: function() {
+ return ( this.phase=="userEvent" );
+ },
+*/
+
+ /**
+ * Make sure that a node with a given ID is loaded, by traversing - and
+ * loading - its parents. This method is ment for lazy hierarchies.
+ * A callback is executed for every node as we go.
+ * @example
+ * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
+ * if(status === "loaded") {
+ * console.log("loaded intermiediate node " + node);
+ * }else if(status === "ok") {
+ * node.activate();
+ * }
+ * });
+ *
+ * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
+ * @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
+ * @returns {$.Promise}
+ */
+ loadKeyPath: function(keyPathList, callback, _rootNode) {
+ var deferredList, dfd, i, path, key, loadMap, node, segList,
+ root = _rootNode || this.rootNode,
+ sep = this.options.keyPathSeparator,
+ self = this;
+
+ if(!$.isArray(keyPathList)){
+ keyPathList = [keyPathList];
+ }
+ // Pass 1: handle all path segments for nodes that are already loaded
+ // Collect distinct top-most lazy nodes in a map
+ loadMap = {};
+
+ for(i=0; i<keyPathList.length; i++){
+ path = keyPathList[i];
+ // strip leading slash
+ if(path.charAt(0) === sep){
+ path = path.substr(1);
+ }
+ // traverse and strip keys, until we hit a lazy, unloaded node
+ segList = path.split(sep);
+ while(segList.length){
+ key = segList.shift();
+// node = _findDirectChild(root, key);
+ node = root._findDirectChild(key);
+ if(!node){
+ this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
+ callback.call(this, key, "error");
+ break;
+ }else if(segList.length === 0){
+ callback.call(this, node, "ok");
+ break;
+ }else if(!node.lazy || (node.hasChildren() !== undefined )){
+ callback.call(this, node, "loaded");
+ root = node;
+ }else{
+ callback.call(this, node, "loaded");
+// segList.unshift(key);
+ if(loadMap[key]){
+ loadMap[key].push(segList.join(sep));
+ }else{
+ loadMap[key] = [segList.join(sep)];
+ }
+ break;
+ }
+ }
+ }
+// alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
+ // Now load all lazy nodes and continue itearation for remaining paths
+ deferredList = [];
+ // Avoid jshint warning 'Don't make functions within a loop.':
+ function __lazyload(key, node, dfd){
+ callback.call(self, node, "loading");
+ node.load().done(function(){
+ self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
+ }).fail(function(errMsg){
+ self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
+ callback.call(self, node, "error");
+ dfd.reject();
+ });
+ }
+ for(key in loadMap){
+ node = root._findDirectChild(key);
+// alert("loadKeyPath: lazy node(" + key + ") = " + node);
+ dfd = new $.Deferred();
+ deferredList.push(dfd);
+ __lazyload(key, node, dfd);
+ }
+ // Return a promise that is resovled, when ALL paths were loaded
+ return $.when.apply($, deferredList).promise();
+ },
+ /** Re-fire beforeActivate and activate events. */
+ reactivate: function(setFocus) {
+ var node = this.activeNode;
+ if( node ) {
+ this.activeNode = null; // Force re-activating
+ node.setActive();
+ if( setFocus ){
+ node.setFocus();
+ }
+ }
+ },
+ /** Reload tree from source and return a promise.
+ * @param [source] optional new source (defaults to initial source data)
+ * @returns {$.Promise}
+ */
+ reload: function(source) {
+ this._callHook("treeClear", this);
+ return this._callHook("treeLoad", this, source);
+ },
+ /**Render tree (i.e. create DOM elements for all top-level nodes).
+ * @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed
+ * @param {boolean} [deep=false]
+ */
+ render: function(force, deep) {
+ return this.rootNode.render(force, deep);
+ },
+ // TODO: selectKey: function(key, select)
+ // TODO: serializeArray: function(stopOnParents)
+ /**
+ * @param {boolean} [flag=true]
+ */
+ setFocus: function(flag) {
+ return this._callHook("treeSetFocus", this, flag);
+ },
+ /**
+ * Return all nodes as nested list of {@link NodeData}.
+ *
+ * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
+ * @param {function} [callback(node)] Called for every node
+ * @returns {Array | object}
+ * @see FancytreeNode#toDict
+ */
+ toDict: function(includeRoot, callback){
+ var res = this.rootNode.toDict(true, callback);
+ return includeRoot ? res : res.children;
+ },
+ /* Implicitly called for string conversions.
+ * @returns {string}
+ */
+ toString: function(){
+ return "<Fancytree(#" + this._id + ")>";
+ },
+ /* _trigger a widget event with additional node ctx.
+ * @see EventData
+ */
+ _triggerNodeEvent: function(type, node, originalEvent, extra) {
+// this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
+ var ctx = this._makeHookContext(node, originalEvent, extra),
+ res = this.widget._trigger(type, originalEvent, ctx);
+ if(res !== false && ctx.result !== undefined){
+ return ctx.result;
+ }
+ return res;
+ },
+ /* _trigger a widget event with additional tree data. */
+ _triggerTreeEvent: function(type, originalEvent) {
+// this.debug("_trigger(" + type + ")", ctx);
+ var ctx = this._makeHookContext(this, originalEvent),
+ res = this.widget._trigger(type, originalEvent, ctx);
+
+ if(res !== false && ctx.result !== undefined){
+ return ctx.result;
+ }
+ return res;
+ },
+ /** Call fn(node) for all nodes.
+ *
+ * @param {function} fn the callback function.
+ * Return false to stop iteration, return "skip" to skip this node and children only.
+ * @returns {boolean} false, if the iterator was stopped.
+ */
+ visit: function(fn) {
+ return this.rootNode.visit(fn, false);
+ },
+ /** Write warning to browser console (prepending tree info)
+ *
+ * @param {*} msg string or object or array of such
+ */
+ warn: function(msg){
+ Array.prototype.unshift.call(arguments, this.toString());
+ consoleApply("warn", arguments);
+ }
+};
+
+/**
+ * These additional methods of the {@link Fancytree} class are 'hook functions'
+ * that can be used and overloaded by extensions.
+ * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
+ * @mixin Fancytree_Hooks
+ */
+$.extend(Fancytree.prototype,
+ /** @lends Fancytree_Hooks# */
+ {
+ /** Default handling for mouse click events.
+ *
+ * @param {EventData} ctx
+ */
+ nodeClick: function(ctx) {
+// this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
+ var activate, expand,
+ event = ctx.originalEvent,
+ targetType = ctx.targetType,
+ node = ctx.node;
+
+ // TODO: use switch
+ // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
+ if( targetType === "expander" ) {
+ // Clicking the expander icon always expands/collapses
+ this._callHook("nodeToggleExpanded", ctx);
+// this._callHook("nodeSetFocus", ctx, true); // DT issue 95
+ } else if( targetType === "checkbox" ) {
+ // Clicking the checkbox always (de)selects
+ this._callHook("nodeToggleSelected", ctx);
+ this._callHook("nodeSetFocus", ctx, true); // DT issue 95
+ } else {
+ // Honor `clickFolderMode` for
+ expand = false;
+ activate = true;
+ if( node.folder ) {
+ switch( ctx.options.clickFolderMode ) {
+ case 2: // expand only
+ expand = true;
+ activate = false;
+ break;
+ case 3: // expand and activate
+ activate = true;
+ expand = true; //!node.isExpanded();
+ break;
+ // else 1 or 4: just activate
+ }
+ }
+ if( activate ) {
+ this.nodeSetFocus(ctx);
+ this._callHook("nodeSetActive", ctx, true);
+ }
+ if( expand ) {
+ if(!activate){
+// this._callHook("nodeSetFocus", ctx);
+ }
+// this._callHook("nodeSetExpanded", ctx, true);
+ this._callHook("nodeToggleExpanded", ctx);
+ }
+ }
+ // Make sure that clicks stop, otherwise <a href='#'> jumps to the top
+ if(event.target.localName === "a" && event.target.className === "fancytree-title"){
+ event.preventDefault();
+ }
+ // TODO: return promise?
+ },
+ /** Collapse all other children of same parent.
+ *
+ * @param {EventData} ctx
+ * @param {object} callOpts
+ */
+ nodeCollapseSiblings: function(ctx, callOpts) {
+ // TODO: return promise?
+ var ac, i, l,
+ node = ctx.node;
+
+ if( node.parent ){
+ ac = node.parent.children;
+ for (i=0, l=ac.length; i<l; i++) {
+ if ( ac[i] !== node && ac[i].expanded ){
+ this._callHook("nodeSetExpanded", ac[i], false, callOpts);
+ }
+ }
+ }
+ },
+ /** Default handling for mouse douleclick events.
+ * @param {EventData} ctx
+ */
+ nodeDblclick: function(ctx) {
+ // TODO: return promise?
+ if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
+// this.nodeSetFocus(ctx);
+// this._callHook("nodeSetActive", ctx, true);
+ this._callHook("nodeToggleExpanded", ctx);
+ }
+ // TODO: prevent text selection on dblclicks
+ if( ctx.targetType === "title" ) {
+ ctx.originalEvent.preventDefault();
+ }
+ },
+ /** Default handling for mouse keydown events.
+ *
+ * NOTE: this may be called with node == null if tree (but no node) has focus.
+ * @param {EventData} ctx
+ */
+ nodeKeydown: function(ctx) {
+ // TODO: return promise?
+ var res,
+ event = ctx.originalEvent,
+ node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+ handled = true,
+ activate = !(event.ctrlKey || !opts.autoActivate ),
+ KC = $.ui.keyCode;
+
+// node.debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
+
+ // Set focus to first node, if no other node has the focus yet
+ if( !node ){
+ this.rootNode.getFirstChild().setFocus();
+ node = ctx.node = this.focusNode;
+ node.debug("Keydown force focus on first node");
+ }
+
+ switch( event.which ) {
+ // charCodes:
+ case KC.NUMPAD_ADD: //107: // '+'
+ case 187: // '+' @ Chrome, Safari
+ tree.nodeSetExpanded(ctx, true);
+ break;
+ case KC.NUMPAD_SUBTRACT: // '-'
+ case 189: // '-' @ Chrome, Safari
+ tree.nodeSetExpanded(ctx, false);
+ break;
+ case KC.SPACE:
+ if(opts.checkbox){
+ tree.nodeToggleSelected(ctx);
+ }else{
+ tree.nodeSetActive(ctx, true);
+ }
+ break;
+ case KC.ENTER:
+ tree.nodeSetActive(ctx, true);
+ break;
+ case KC.BACKSPACE:
+ case KC.LEFT:
+ case KC.RIGHT:
+ case KC.UP:
+ case KC.DOWN:
+ res = node.navigate(event.which, activate);
+ break;
+ default:
+ handled = false;
+ }
+ if(handled){
+ event.preventDefault();
+ }
+ },
+
+
+ // /** Default handling for mouse keypress events. */
+ // nodeKeypress: function(ctx) {
+ // var event = ctx.originalEvent;
+ // },
+
+ // /** Trigger lazyLoad event (async). */
+ // nodeLazyLoad: function(ctx) {
+ // var node = ctx.node;
+ // if(this._triggerNodeEvent())
+ // },
+ /** Load child nodes (async).
+ *
+ * @param {EventData} ctx
+ * @param {object[]|object|string|$.Promise|function} source
+ * @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
+ * data was rendered.
+ */
+ nodeLoadChildren: function(ctx, source) {
+ var ajax, delay,
+ tree = ctx.tree,
+ node = ctx.node;
+
+ if($.isFunction(source)){
+ source = source();
+ }
+ // TOTHINK: move to 'ajax' extension?
+ if(source.url){
+ // `source` is an Ajax options object
+ ajax = $.extend({}, ctx.options.ajax, source);
+ if(ajax.debugDelay){
+ // simulate a slow server
+ delay = ajax.debugDelay;
+ if($.isArray(delay)){ // random delay range [min..max]
+ delay = delay[0] + Math.random() * (delay[1] - delay[0]);
+ }
+
+ node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
+ ajax.debugDelay = false;
+ source = $.Deferred(function (dfd) {
+ setTimeout(function () {
+ $.ajax(ajax)
+ .done(function () { dfd.resolveWith(this, arguments); })
+ .fail(function () { dfd.rejectWith(this, arguments); });
+ }, delay);
+ });
+ }else{
+ source = $.ajax(ajax);
+ }
+
+ // TODO: change 'pipe' to 'then' for jQuery 1.8
+ // $.pipe returns a new Promise with filtered results
+ source = source.pipe(function (data, textStatus, jqXHR) {
+ var res;
+ if(typeof data === "string"){
+ $.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
+ }
+ // postProcess is similar to the standard dataFilter hook,
+ // but it is also called for JSONP
+ if( ctx.options.postProcess ){
+ res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, dataType: this.dataType});
+ data = $.isArray(res) ? res : data;
+ } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
+ // Process ASPX WebMethod JSON object inside "d" property
+ data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
+ }
+ return data;
+ }, function (jqXHR, textStatus, errorThrown) {
+ return tree._makeHookContext(node, null, {
+ error: jqXHR,
+ args: Array.prototype.slice.call(arguments),
+ message: errorThrown,
+ details: jqXHR.status + ": " + errorThrown
+ });
+ });
+ }
+
+ if($.isFunction(source.promise)){
+ // `source` is a deferred, i.e. ajax request
+ _assert(!node.isLoading());
+ // node._isLoading = true;
+ tree.nodeSetStatus(ctx, "loading");
+
+ source.done(function () {
+ tree.nodeSetStatus(ctx, "ok");
+ }).fail(function(error){
+ var ctxErr;
+ if (error.node && error.error && error.message) {
+ // error is already a context object
+ ctxErr = error;
+ } else {
+ ctxErr = tree._makeHookContext(node, null, {
+ error: error, // it can be jqXHR or any custom error
+ args: Array.prototype.slice.call(arguments),
+ message: error ? (error.message || error.toString()) : ""
+ });
+ }
+ tree._triggerNodeEvent("loaderror", ctxErr, null);
+ tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
+ });
+ }
+ // $.when(source) resolves also for non-deferreds
+ return $.when(source).done(function(children){
+ var metaData;
+
+ if( $.isPlainObject(children) ){
+ // We got {foo: 'abc', children: [...]}
+ // Copy extra properties to tree.data.foo
+ _assert($.isArray(children.children), "source must contain (or be) an array of children");
+ _assert(node.isRoot(), "source may only be an object for root nodes");
+ metaData = children;
+ children = children.children;
+ delete metaData.children;
+ $.extend(tree.data, metaData);
+ }
+ _assert($.isArray(children), "expected array of children");
+ node._setChildren(children);
+ // trigger fancytreeloadchildren
+ // if( node.parent ) {
+ tree._triggerNodeEvent("loadChildren", node);
+ // }
+ // }).always(function(){
+ // node._isLoading = false;
+ });
+ },
+ /** [Not Implemented] */
+ nodeLoadKeyPath: function(ctx, keyPathList) {
+ // TODO: implement and improve
+ // http://code.google.com/p/dynatree/issues/detail?id=222
+ },
+ /**
+ * Remove a single direct child of ctx.node.
+ * @param {EventData} ctx
+ * @param {FancytreeNode} childNode dircect child of ctx.node
+ */
+ nodeRemoveChild: function(ctx, childNode) {
+ var idx,
+ node = ctx.node,
+ opts = ctx.options,
+ subCtx = $.extend({}, ctx, {node: childNode}),
+ children = node.children;
+
+ // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
+
+ if( children.length === 1 ) {
+ _assert(childNode === children[0]);
+ return this.nodeRemoveChildren(ctx);
+ }
+ if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
+ this.activeNode.setActive(false); // TODO: don't fire events
+ }
+ if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
+ this.focusNode = null;
+ }
+ // TODO: persist must take care to clear select and expand cookies
+ this.nodeRemoveMarkup(subCtx);
+ this.nodeRemoveChildren(subCtx);
+ idx = $.inArray(childNode, children);
+ _assert(idx >= 0);
+ // Unlink to support GC
+ childNode.visit(function(n){
+ n.parent = null;
+ }, true);
+ this._callHook("treeRegisterNode", this, false, childNode);
+ if ( opts.removeNode ){
+ opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
+ }
+ // remove from child list
+ children.splice(idx, 1);
+ },
+ /**Remove HTML markup for all descendents of ctx.node.
+ * @param {EventData} ctx
+ */
+ nodeRemoveChildMarkup: function(ctx) {
+ var node = ctx.node;
+
+ // FT.debug("nodeRemoveChildMarkup()", node.toString());
+ // TODO: Unlink attr.ftnode to support GC
+ if(node.ul){
+ if( node.isRoot() ) {
+ $(node.ul).empty();
+ } else {
+ $(node.ul).remove();
+ node.ul = null;
+ }
+ node.visit(function(n){
+ n.li = n.ul = null;
+ });
+ }
+ },
+ /**Remove all descendants of ctx.node.
+ * @param {EventData} ctx
+ */
+ nodeRemoveChildren: function(ctx) {
+ var subCtx,
+ tree = ctx.tree,
+ node = ctx.node,
+ children = node.children,
+ opts = ctx.options;
+
+ // FT.debug("nodeRemoveChildren()", node.toString());
+ if(!children){
+ return;
+ }
+ if( this.activeNode && this.activeNode.isDescendantOf(node)){
+ this.activeNode.setActive(false); // TODO: don't fire events
+ }
+ if( this.focusNode && this.focusNode.isDescendantOf(node)){
+ this.focusNode = null;
+ }
+ // TODO: persist must take care to clear select and expand cookies
+ this.nodeRemoveChildMarkup(ctx);
+ // Unlink children to support GC
+ // TODO: also delete this.children (not possible using visit())
+ subCtx = $.extend({}, ctx);
+ node.visit(function(n){
+ n.parent = null;
+ tree._callHook("treeRegisterNode", tree, false, n);
+ if ( opts.removeNode ){
+ subCtx.node = n;
+ opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
+ }
+ });
+ if( node.lazy ){
+ // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
+ node.children = [];
+ } else{
+ node.children = null;
+ }
+ this.nodeRenderStatus(ctx);
+ },
+ /**Remove HTML markup for ctx.node and all its descendents.
+ * @param {EventData} ctx
+ */
+ nodeRemoveMarkup: function(ctx) {
+ var node = ctx.node;
+ // FT.debug("nodeRemoveMarkup()", node.toString());
+ // TODO: Unlink attr.ftnode to support GC
+ if(node.li){
+ $(node.li).remove();
+ node.li = null;
+ }
+ this.nodeRemoveChildMarkup(ctx);
+ },
+ /**
+ * Create `<li><span>..</span> .. </li>` tags for this node.
+ *
+ * This method takes care that all HTML markup is created that is required
+ * to display this node in it's current state.
+ *
+ * Call this method to create new nodes, or after the strucuture
+ * was changed (e.g. after moving this node or adding/removing children)
+ * nodeRenderTitle() and nodeRenderStatus() are implied.
+ *
+ * Note: if a node was created/removed, nodeRender() must be called for the
+ * parent.
+ * <code>
+ * <li id='KEY' ftnode=NODE>
+ * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
+ * <span class="fancytree-expander"></span>
+ * <span class="fancytree-checkbox"></span> // only present in checkbox mode
+ * <span class="fancytree-icon"></span>
+ * <a href="#" class="fancytree-title"> Node 1 </a>
+ * </span>
+ * <ul> // only present if node has children
+ * <li id='KEY' ftnode=NODE> child1 ... </li>
+ * <li id='KEY' ftnode=NODE> child2 ... </li>
+ * </ul>
+ * </li>
+ * </code>
+ *
+ * @param {EventData} ctx
+ * @param {boolean} [force=false] re-render, even if html markup was already created
+ * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
+ * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
+ */
+ nodeRender: function(ctx, force, deep, collapsed, _recursive) {
+ /* This method must take care of all cases where the current data mode
+ * (i.e. node hierarchy) does not match the current markup.
+ *
+ * - node was not yet rendered:
+ * create markup
+ * - node was rendered: exit fast
+ * - children have been added
+ * - childern have been removed
+ */
+ var childLI, childNode1, childNode2, i, l, next, subCtx,
+ node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+ aria = opts.aria,
+ firstTime = false,
+ parent = node.parent,
+ isRootNode = !parent,
+ children = node.children;
+ // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
+
+ if( ! isRootNode && ! parent.ul ) {
+ // Calling node.collapse on a deep, unrendered node
+ return;
+ }
+ _assert(isRootNode || parent.ul, "parent UL must exist");
+
+// if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
+// if(node.li.parentNode !== node.parent.ul){
+// // alert("unlink " + node + " (must be child of " + node.parent + ")");
+// this.warn("unlink " + node + " (must be child of " + node.parent + ")");
+// }
+// // this.debug("nodeRemoveMarkup...");
+// this.nodeRemoveMarkup(ctx);
+// }
+ // Render the node
+ if( !isRootNode ){
+ // Discard markup on force-mode, or if it is not linked to parent <ul>
+ if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
+ if(node.li.parentNode !== node.parent.ul){
+// alert("unlink " + node + " (must be child of " + node.parent + ")");
+ this.warn("unlink " + node + " (must be child of " + node.parent + ")");
+ }
+// this.debug("nodeRemoveMarkup...");
+ this.nodeRemoveMarkup(ctx);
+ }
+ // Create <li><span /> </li>
+// node.debug("render...");
+ if( !node.li ) {
+// node.debug("render... really");
+ firstTime = true;
+ node.li = document.createElement("li");
+ node.li.ftnode = node;
+ if(aria){
+ // TODO: why doesn't this work:
+// node.li.role = "treeitem";
+// $(node.li).attr("role", "treeitem")
+// .attr("aria-labelledby", "ftal_" + node.key);
+ }
+ if( node.key && opts.generateIds ){
+ node.li.id = opts.idPrefix + node.key;
+ }
+ node.span = document.createElement("span");
+ node.span.className = "fancytree-node";
+ if(aria){
+ $(node.span).attr("aria-labelledby", "ftal_" + node.key);
+ }
+ node.li.appendChild(node.span);
+
+ // Create inner HTML for the <span> (expander, checkbox, icon, and title)
+ this.nodeRenderTitle(ctx);
+
+ // Allow tweaking and binding, after node was created for the first time
+ if ( opts.createNode ){
+ opts.createNode.call(tree, {type: "createNode"}, ctx);
+ }
+ }else{
+// this.nodeRenderTitle(ctx);
+ this.nodeRenderStatus(ctx);
+ }
+ // Allow tweaking after node state was rendered
+ if ( opts.renderNode ){
+ opts.renderNode.call(tree, {type: "renderNode"}, ctx);
+ }
+ }
+
+ // Visit child nodes
+ if( children ){
+ if( isRootNode || node.expanded || deep === true ) {
+ // Create a UL to hold the children
+ if( !node.ul ){
+ node.ul = document.createElement("ul");
+ if((collapsed === true && !_recursive) || !node.expanded){
+ // hide top UL, so we can use an animation to show it later
+ node.ul.style.display = "none";
+ }
+ if(aria){
+ $(node.ul).attr("role", "group");
+ }
+ if ( node.li ) { // issue #67
+ node.li.appendChild(node.ul);
+ } else {
+ node.tree.$div.append(node.ul);
+ }
+ }
+ // Add child markup
+ for(i=0, l=children.length; i<l; i++) {
+ subCtx = $.extend({}, ctx, {node: children[i]});
+ this.nodeRender(subCtx, force, deep, false, true);
+ }
+ // Remove <li> if nodes have moved to another parent
+ childLI = node.ul.firstChild;
+ while( childLI ){
+ childNode2 = childLI.ftnode;
+ if( childNode2 && childNode2.parent !== node ) {
+ node.debug("_fixParent: remove missing " + childNode2, childLI);
+ next = childLI.nextSibling;
+ childLI.parentNode.removeChild(childLI);
+ childLI = next;
+ }else{
+ childLI = childLI.nextSibling;
+ }
+ }
+ // Make sure, that <li> order matches node.children order.
+ childLI = node.ul.firstChild;
+ for(i=0, l=children.length-1; i<l; i++) {
+ childNode1 = children[i];
+ childNode2 = childLI.ftnode;
+ if( childNode1 !== childNode2 ) {
+ // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
+ node.ul.insertBefore(childNode1.li, childNode2.li);
+ } else {
+ childLI = childLI.nextSibling;
+ }
+ }
+ }
+ }else{
+ // No children: remove markup if any
+ if( node.ul ){
+// alert("remove child markup for " + node);
+ this.warn("remove child markup for " + node);
+ this.nodeRemoveChildMarkup(ctx);
+ }
+ }
+ if( !isRootNode ){
+ // Update element classes according to node state
+ // this.nodeRenderStatus(ctx);
+ // Finally add the whole structure to the DOM, so the browser can render
+ if(firstTime){
+ parent.ul.appendChild(node.li);
+ }
+ }
+ },
+ /** Create HTML for the node's outer <span> (expander, checkbox, icon, and title).
+ *
+ * nodeRenderStatus() is implied.
+ * @param {EventData} ctx
+ * @param {string} [title] optinal new title
+ */
+ nodeRenderTitle: function(ctx, title) {
+ // set node connector images, links and text
+ var id, imageSrc, nodeTitle, role, tabindex, tooltip,
+ node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+ aria = opts.aria,
+ level = node.getLevel(),
+ ares = [],
+ icon = node.data.icon;
+
+ if(title !== undefined){
+ node.title = title;
+ }
+ if(!node.span){
+ // Silently bail out if node was not rendered yet, assuming
+ // node.render() will be called as the node becomes visible
+ return;
+ }
+ // connector (expanded, expandable or simple)
+ // TODO: optiimize this if clause
+ if( level < opts.minExpandLevel ) {
+ if(level > 1){
+ if(aria){
+ ares.push("<span role='button' class='fancytree-expander'></span>");
+ }else{
+ ares.push("<span class='fancytree-expander'></span>");
+ }
+ }
+ // .. else (i.e. for root level) skip expander/connector alltogether
+ } else {
+ if(aria){
+ ares.push("<span role='button' class='fancytree-expander'></span>");
+ }else{
+ ares.push("<span class='fancytree-expander'></span>");
+ }
+ }
+ // Checkbox mode
+ if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
+ if(aria){
+ ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
+ }else{
+ ares.push("<span class='fancytree-checkbox'></span>");
+ }
+ }
+ // folder or doctype icon
+ role = aria ? " role='img'" : "";
+ if ( icon && typeof icon === "string" ) {
+ imageSrc = (icon.charAt(0) === "/") ? icon : ((opts.imagePath || "") + icon);
+ ares.push("<img src='" + imageSrc + "' class='fancytree-icon' alt='' />");
+ } else if ( node.data.iconclass ) {
+ // TODO: review and test and document
+ ares.push("<span " + role + " class='fancytree-custom-icon" + " " + node.data.iconclass + "'></span>");
+ } else if ( icon === true || (icon !== false && opts.icons !== false) ) {
+ // opts.icons defines the default behavior.
+ // node.icon == true/false can override this
+ ares.push("<span " + role + " class='fancytree-icon'></span>");
+ }
+ // node title
+ nodeTitle = "";
+ // TODO: currently undocumented; may be removed?
+ if ( opts.renderTitle ){
+ nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
+ }
+ if(!nodeTitle){
+ tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : "";
+ id = aria ? " id='ftal_" + node.key + "'" : "";
+ role = aria ? " role='treeitem'" : "";
+ tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
+
+ nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>";
+ }
+ ares.push(nodeTitle);
+ // Note: this will trigger focusout, if node had the focus
+ //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
+ node.span.innerHTML = ares.join("");
+ // Update CSS classes
+ this.nodeRenderStatus(ctx);
+ },
+ /** Update element classes according to node state.
+ * @param {EventData} ctx
+ */
+ nodeRenderStatus: function(ctx) {
+ // Set classes for current status
+ var node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+// nodeContainer = node[tree.nodeContainerAttrName],
+ hasChildren = node.hasChildren(),
+ isLastSib = node.isLastSibling(),
+ aria = opts.aria,
+// $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
+ $ariaElem = $(node.span).find(".fancytree-title"),
+ cn = opts._classNames,
+ cnList = [],
+ statusElem = node[tree.statusClassPropName];
+
+ if( !statusElem ){
+ // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
+ return;
+ }
+ // Build a list of class names that we will add to the node <span>
+ cnList.push(cn.node);
+ if( tree.activeNode === node ){
+ cnList.push(cn.active);
+// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
+// tree.$container.removeAttr("tabindex");
+ // }else{
+// $(">span.fancytree-title", statusElem).removeAttr("tabindex");
+// tree.$container.attr("tabindex", "0");
+ }
+ if( tree.focusNode === node ){
+ cnList.push(cn.focused);
+ if(aria){
+// $(">span.fancytree-title", statusElem).attr("tabindex", "0");
+// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
+ // TODO: is this the right element for this attribute?
+ $ariaElem
+ .attr("aria-activedescendant", true);
+// .attr("tabindex", "-1");
+ }
+ }else if(aria){
+// $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
+ $ariaElem
+ .removeAttr("aria-activedescendant");
+// .removeAttr("tabindex");
+ }
+ if( node.expanded ){
+ cnList.push(cn.expanded);
+ if(aria){
+ $ariaElem.attr("aria-expanded", true);
+ }
+ }else if(aria){
+ $ariaElem.removeAttr("aria-expanded");
+ }
+ if( node.folder ){
+ cnList.push(cn.folder);
+ }
+ if( hasChildren !== false ){
+ cnList.push(cn.hasChildren);
+ }
+ // TODO: required?
+ if( isLastSib ){
+ cnList.push(cn.lastsib);
+ }
+ if( node.lazy && node.children == null ){
+ cnList.push(cn.lazy);
+ }
+ if( node.partsel ){
+ cnList.push(cn.partsel);
+ }
+ if( node._isLoading ){
+ cnList.push(cn.loading);
+ }
+ if( node._error ){
+ cnList.push(cn.error);
+ }
+ if( node.selected ){
+ cnList.push(cn.selected);
+ if(aria){
+ $ariaElem.attr("aria-selected", true);
+ }
+ }else if(aria){
+ $ariaElem.attr("aria-selected", false);
+ }
+ if( node.extraClasses ){
+ cnList.push(node.extraClasses);
+ }
+ // IE6 doesn't correctly evaluate multiple class names,
+ // so we create combined class names that can be used in the CSS
+ if( hasChildren === false ){
+ cnList.push(cn.combinedExpanderPrefix + "n" +
+ (isLastSib ? "l" : "")
+ );
+ }else{
+ cnList.push(cn.combinedExpanderPrefix +
+ (node.expanded ? "e" : "c") +
+ (node.lazy && node.children == null ? "d" : "") +
+ (isLastSib ? "l" : "")
+ );
+ }
+ cnList.push(cn.combinedIconPrefix +
+ (node.expanded ? "e" : "c") +
+ (node.folder ? "f" : "")
+ );
+// node.span.className = cnList.join(" ");
+ statusElem.className = cnList.join(" ");
+
+ // TODO: we should not set this in the <span> tag also, if we set it here:
+ // Maybe most (all) of the classes should be set in LI instead of SPAN?
+ if(node.li){
+ node.li.className = isLastSib ? cn.lastsib : "";
+ }
+ },
+ /** Activate node.
+ * flag defaults to true.
+ * If flag is true, the node is activated (must be a synchronous operation)
+ * If flag is false, the node is deactivated (must be a synchronous operation)
+ * @param {EventData} ctx
+ * @param {boolean} [flag=true]
+ * @param {object} [opts] additional options. Defaults to {noEvents: false}
+ */
+ nodeSetActive: function(ctx, flag, callOpts) {
+ // Handle user click / [space] / [enter], according to clickFolderMode.
+ callOpts = callOpts || {};
+ var subCtx,
+ node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+ noEvents = (callOpts.noEvents === true),
+ isActive = (node === tree.activeNode);
+
+ // flag defaults to true
+ flag = (flag !== false);
+ // node.debug("nodeSetActive", flag);
+
+ if(isActive === flag){
+ // Nothing to do
+ return _getResolvedPromise(node);
+ }else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
+ // Callback returned false
+ return _getRejectedPromise(node, ["rejected"]);
+ }
+ if(flag){
+ if(tree.activeNode){
+ _assert(tree.activeNode !== node, "node was active (inconsistency)");
+ subCtx = $.extend({}, ctx, {node: tree.activeNode});
+ tree.nodeSetActive(subCtx, false);
+ _assert(tree.activeNode === null, "deactivate was out of sync?");
+ }
+ if(opts.activeVisible){
+ // tree.nodeMakeVisible(ctx);
+ node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll
+ }
+ tree.activeNode = node;
+ tree.nodeRenderStatus(ctx);
+ tree.nodeSetFocus(ctx);
+ if( !noEvents ) {
+ tree._triggerNodeEvent("activate", node, ctx.originalEvent);
+ }
+ }else{
+ _assert(tree.activeNode === node, "node was not active (inconsistency)");
+ tree.activeNode = null;
+ this.nodeRenderStatus(ctx);
+ if( !noEvents ) {
+ ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent);
+ }
+ }
+ },
+ /** Expand or collapse node, return Deferred.promise.
+ *
+ * @param {EventData} ctx
+ * @param {boolean} [flag=true]
+ * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
+ * @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
+ * data was retrieved, rendered, and the expand animation finshed.
+ */
+ nodeSetExpanded: function(ctx, flag, callOpts) {
+ callOpts = callOpts || {};
+ var _afterLoad, dfd, i, l, parents, prevAC,
+ node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options,
+ noAnimation = (callOpts.noAnimation === true),
+ noEvents = (callOpts.noEvents === true);
+
+ // flag defaults to true
+ flag = (flag !== false);
+
+ // node.debug("nodeSetExpanded(" + flag + ")");
+
+ if((node.expanded && flag) || (!node.expanded && !flag)){
+ // Nothing to do
+ // node.debug("nodeSetExpanded(" + flag + "): nothing to do");
+ return _getResolvedPromise(node);
+ }else if(flag && !node.lazy && !node.hasChildren() ){
+ // Prevent expanding of empty nodes
+ // return _getRejectedPromise(node, ["empty"]);
+ return _getResolvedPromise(node);
+ }else if( !flag && node.getLevel() < opts.minExpandLevel ) {
+ // Prevent collapsing locked levels
+ return _getRejectedPromise(node, ["locked"]);
+ }else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
+ // Callback returned false
+ return _getRejectedPromise(node, ["rejected"]);
+ }
+ // If this node inside a collpased node, no animation and scrolling is needed
+ if( !noAnimation && !node.isVisible() ) {
+ noAnimation = callOpts.noAnimation = true;
+ }
+
+ dfd = new $.Deferred();
+
+ // Auto-collapse mode: collapse all siblings
+ if( flag && !node.expanded && opts.autoCollapse ) {
+ parents = node.getParentList(false, true);
+ prevAC = opts.autoCollapse;
+ try{
+ opts.autoCollapse = false;
+ for(i=0, l=parents.length; i<l; i++){
+ // TODO: should return promise?
+ this._callHook("nodeCollapseSiblings", parents[i], callOpts);
+ }
+ }finally{
+ opts.autoCollapse = prevAC;
+ }
+ }
+ // Trigger expand/collapse after expanding
+ dfd.done(function(){
+ if( flag && opts.autoScroll && !noAnimation ) {
+ // Scroll down to last child, but keep current node visible
+ node.getLastChild().scrollIntoView(true, {topNode: node}).always(function(){
+ if( !noEvents ) {
+ ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
+ }
+ });
+ } else {
+ if( !noEvents ) {
+ ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
+ }
+ }
+ });
+ // vvv Code below is executed after loading finished:
+ _afterLoad = function(callback){
+ var duration, easing, isVisible, isExpanded;
+
+ node.expanded = flag;
+ // Create required markup, but make sure the top UL is hidden, so we
+ // can animate later
+ tree._callHook("nodeRender", ctx, false, false, true);
+
+ // If the currently active node is now hidden, deactivate it
+ // if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
+ // this.activeNode.deactivate();
+ // }
+
+ // Expanding a lazy node: set 'loading...' and call callback
+ // if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
+ // this._loadContent();
+ // return;
+ // }
+ // Hide children, if node is collapsed
+ if( node.ul ) {
+ isVisible = (node.ul.style.display !== "none");
+ isExpanded = !!node.expanded;
+ if ( isVisible === isExpanded ) {
+ node.warn("nodeSetExpanded: UL.style.display already set");
+
+ } else if ( !opts.fx || noAnimation ) {
+ node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
+
+ } else {
+ duration = opts.fx.duration || 200;
+ easing = opts.fx.easing;
+ // node.debug("nodeSetExpanded: animate start...");
+ $(node.ul).animate(opts.fx, duration, easing, function(){
+ // node.debug("nodeSetExpanded: animate done");
+ callback();
+ });
+ return;
+ }
+ }
+ callback();
+ };
+ // ^^^ Code above is executed after loading finshed.
+
+ // Load lazy nodes, if any. Then continue with _afterLoad()
+ if(flag && node.lazy && node.hasChildren() === undefined){
+ // node.debug("nodeSetExpanded: load start...");
+ node.load().done(function(){
+ // node.debug("nodeSetExpanded: load done");
+ if(dfd.notifyWith){ // requires jQuery 1.6+
+ dfd.notifyWith(node, ["loaded"]);
+ }
+ _afterLoad(function () { dfd.resolveWith(node); });
+ }).fail(function(errMsg){
+ _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
+ });
+/*
+ var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
+ _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
+ node.debug("nodeSetExpanded: load start...");
+ this._callHook("nodeLoadChildren", ctx, source).done(function(){
+ node.debug("nodeSetExpanded: load done");
+ if(dfd.notifyWith){ // requires jQuery 1.6+
+ dfd.notifyWith(node, ["loaded"]);
+ }
+ _afterLoad.call(tree);
+ }).fail(function(errMsg){
+ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
+ });
+*/
+ }else{
+ _afterLoad(function () { dfd.resolveWith(node); });
+ }
+ // node.debug("nodeSetExpanded: returns");
+ return dfd.promise();
+ },
+ /** Focus ot blur this node.
+ * @param {EventData} ctx
+ * @param {boolean} [flag=true]
+ */
+ nodeSetFocus: function(ctx, flag) {
+ // ctx.node.debug("nodeSetFocus(" + flag + ")");
+ var ctx2,
+ tree = ctx.tree,
+ node = ctx.node;
+
+ flag = (flag !== false);
+
+ // Blur previous node if any
+ if(tree.focusNode){
+ if(tree.focusNode === node && flag){
+ // node.debug("nodeSetFocus(" + flag + "): nothing to do");
+ return;
+ }
+ ctx2 = $.extend({}, ctx, {node: tree.focusNode});
+ tree.focusNode = null;
+ this._triggerNodeEvent("blur", ctx2);
+ this._callHook("nodeRenderStatus", ctx2);
+ }
+ // Set focus to container and node
+ if(flag){
+ if( !this.hasFocus() ){
+ node.debug("nodeSetFocus: forcing container focus");
+ // Note: we pass _calledByNodeSetFocus=true
+ this._callHook("treeSetFocus", ctx, true, true);
+ }
+ // this.nodeMakeVisible(ctx);
+ node.makeVisible({scrollIntoView: false});
+ tree.focusNode = node;
+// node.debug("FOCUS...");
+// $(node.span).find(".fancytree-title").focus();
+ this._triggerNodeEvent("focus", ctx);
+// if(ctx.options.autoActivate){
+// tree.nodeSetActive(ctx, true);
+// }
+ if(ctx.options.autoScroll){
+ node.scrollIntoView();
+ }
+ this._callHook("nodeRenderStatus", ctx);
+ }
+ },
+ /** (De)Select node, return new status (sync).
+ *
+ * @param {EventData} ctx
+ * @param {boolean} [flag=true]
+ */
+ nodeSetSelected: function(ctx, flag) {
+ var node = ctx.node,
+ tree = ctx.tree,
+ opts = ctx.options;
+ // flag defaults to true
+ flag = (flag !== false);
+
+ node.debug("nodeSetSelected(" + flag + ")", ctx);
+ if( node.unselectable){
+ return;
+ }
+ // TODO: !!node.expanded is nicer, but doesn't pass jshint
+ // https://github.com/jshint/jshint/issues/455
+// if( !!node.expanded === !!flag){
+ if((node.selected && flag) || (!node.selected && !flag)){
+ return !!node.selected;
+ }else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
+ return !!node.selected;
+ }
+ if(flag && opts.selectMode === 1){
+ // single selection mode
+ if(tree.lastSelectedNode){
+ tree.lastSelectedNode.setSelected(false);
+ }
+ }else if(opts.selectMode === 3){
+ // multi.hier selection mode
+ node.selected = flag;
+// this._fixSelectionState(node);
+ node.fixSelection3AfterClick();
+ }
+ node.selected = flag;
+ this.nodeRenderStatus(ctx);
+ tree.lastSelectedNode = flag ? node : null;
+ tree._triggerNodeEvent("select", ctx);
+ },
+ /** Show node status (ok, loading, error) using styles and a dummy child node.
+ *
+ * @param {EventData} ctx
+ * @param status
+ * @param message
+ * @param details
+ */
+ nodeSetStatus: function(ctx, status, message, details) {
+ var node = ctx.node,
+ tree = ctx.tree;
+ // cn = ctx.options._classNames;
+
+ function _clearStatusNode() {
+ // Remove dedicated dummy node, if any
+ var firstChild = ( node.children ? node.children[0] : null );
+ if ( firstChild && firstChild.isStatusNode() ) {
+ try{
+ // I've seen exceptions here with loadKeyPath...
+ if(node.ul){
+ node.ul.removeChild(firstChild.li);
+ firstChild.li = null; // avoid leaks (DT issue 215)
+ }
+ }catch(e){}
+ if( node.children.length === 1 ){
+ node.children = [];
+ }else{
+ node.children.shift();
+ }
+ }
+ }
+ function _setStatusNode(data, type) {
+ // Create/modify the dedicated dummy node for 'loading...' or
+ // 'error!' status. (only called for direct child of the invisible
+ // system root)
+ var firstChild = ( node.children ? node.children[0] : null );
+ if ( firstChild && firstChild.isStatusNode() ) {
+ $.extend(firstChild, data);
+ tree._callHook("nodeRender", firstChild);
+ } else {
+ data.key = "_statusNode";
+ node._setChildren([data]);
+ node.children[0].statusNodeType = type;
+ tree.render();
+ }
+ return node.children[0];
+ }
+
+ switch( status ){
+ case "ok":
+ _clearStatusNode();
+ // $(node.span).removeClass(cn.loading).removeClass(cn.error);
+ node._isLoading = false;
+ node._error = null;
+ node.renderStatus();
+ break;
+ case "loading":
+ // $(node.span).removeClass(cn.error).addClass(cn.loading);
+ if( !node.parent ) {
+ _setStatusNode({
+ title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
+ tooltip: details,
+ extraClasses: "fancytree-statusnode-wait"
+ }, status);
+ }
+ node._isLoading = true;
+ node._error = null;
+ node.renderStatus();
+ break;
+ case "error":
+ // $(node.span).removeClass(cn.loading).addClass(cn.error);
+ _setStatusNode({
+ title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
+ tooltip: details,
+ extraClasses: "fancytree-statusnode-error"
+ }, status);
+ node._isLoading = false;
+ node._error = { message: message, details: details };
+ node.renderStatus();
+ break;
+ default:
+ $.error("invalid node status " + status);
+ }
+ },
+ /**
+ *
+ * @param {EventData} ctx
+ */
+ nodeToggleExpanded: function(ctx) {
+ return this.nodeSetExpanded(ctx, !ctx.node.expanded);
+ },
+ /**
+ * @param {EventData} ctx
+ */
+ nodeToggleSelected: function(ctx) {
+ return this.nodeSetSelected(ctx, !ctx.node.selected);
+ },
+ /** Remove all nodes.
+ * @param {EventData} ctx
+ */
+ treeClear: function(ctx) {
+ var tree = ctx.tree;
+ tree.activeNode = null;
+ tree.focusNode = null;
+ tree.$div.find(">ul.fancytree-container").empty();
+ // TODO: call destructors and remove reference loops
+ tree.rootNode.children = null;
+ },
+ /** Widget was created (called only once, even it re-initialized).
+ * @param {EventData} ctx
+ */
+ treeCreate: function(ctx) {
+ },
+ /** Widget was destroyed.
+ * @param {EventData} ctx
+ */
+ treeDestroy: function(ctx) {
+ },
+ /** Widget was (re-)initialized.
+ * @param {EventData} ctx
+ */
+ treeInit: function(ctx) {
+ //this.debug("Fancytree.treeInit()");
+ this.treeLoad(ctx);
+ },
+ /** Parse Fancytree from source, as configured in the options.
+ * @param {EventData} ctx
+ * @param {object} [source] optional new source (use last data otherwise)
+ */
+ treeLoad: function(ctx, source) {
+ var type, $ul,
+ tree = ctx.tree,
+ $container = ctx.widget.element,
+ dfd,
+ // calling context for root node
+ rootCtx = $.extend({}, ctx, {node: this.rootNode});
+
+ if(tree.rootNode.children){
+ this.treeClear(ctx);
+ }
+ source = source || this.options.source;
+
+ if(!source){
+ type = $container.data("type") || "html";
+ switch(type){
+ case "html":
+ $ul = $container.find(">ul:first");
+ $ul.addClass("ui-fancytree-source ui-helper-hidden");
+ source = $.ui.fancytree.parseHtml($ul);
+ // allow to init tree.data.foo from <ul data-foo=''>
+ this.data = $.extend(this.data, _getElementDataAsDict($ul));
+ break;
+ case "json":
+ // $().addClass("ui-helper-hidden");
+ source = $.parseJSON($container.text());
+ if(source.children){
+ if(source.title){tree.title = source.title;}
+ source = source.children;
+ }
+ break;
+ default:
+ $.error("Invalid data-type: " + type);
+ }
+ }else if(typeof source === "string"){
+ // TODO: source is an element ID
+ _raiseNotImplemented();
+ }
+
+ // $container.addClass("ui-widget ui-widget-content ui-corner-all");
+ // Trigger fancytreeinit after nodes have been loaded
+ dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
+ tree.render();
+ if( ctx.options.selectMode === 3 ){
+ tree.rootNode.fixSelection3FromEndNodes();
+ }
+ tree._triggerTreeEvent("init", true);
+ }).fail(function(){
+ tree.render();
+ tree._triggerTreeEvent("init", false);
+ });
+ return dfd;
+ },
+ /** Node was inserted into or removed from the tree.
+ * @param {EventData} ctx
+ * @param {boolean} add
+ * @param {FancytreeNode} node
+ */
+ treeRegisterNode: function(ctx, add, node) {
+ },
+ /** Widget got focus.
+ * @param {EventData} ctx
+ * @param {boolean} [flag=true]
+ */
+ treeSetFocus: function(ctx, flag, _calledByNodeSetFocus) {
+ flag = (flag !== false);
+
+ // this.debug("treeSetFocus(" + flag + "), _calledByNodeSetFocus: " + _calledByNodeSetFocus);
+ // this.debug(" focusNode: " + this.focusNode);
+ // this.debug(" activeNode: " + this.activeNode);
+ if( flag !== this.hasFocus() ){
+ this._hasFocus = flag;
+ this.$container.toggleClass("fancytree-treefocus", flag);
+ this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
+ }
+ }
+});
+
+
+/* ******************************************************************************
+ * jQuery UI widget boilerplate
+ */
+
+/**
+ * The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
+ * This constructor is not called directly. Use `$(selector).fancytree({})`
+ * to initialize the plugin instead.<br>
+ * <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members:
+ * var tree = $("#tree").fancytree("getTree");
+ * var node = $("#tree").fancytree("getActiveNode", "1234");
+ * </pre>
+ *
+ * @mixin Fancytree_Widget
+ */
+
+$.widget("ui.fancytree",
+ /** @lends Fancytree_Widget# */
+ {
+ /**These options will be used as defaults
+ * @type {FancytreeOptions}
+ */
+ options:
+ {
+ activeVisible: true,
+ ajax: {
+ type: "GET",
+ cache: false, // false: Append random '_' argument to the request url to prevent caching.
+// timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
+ dataType: "json" // Expect json format and pass json object to callbacks.
+ }, //
+ aria: false, // TODO: default to true
+ autoActivate: true,
+ autoCollapse: false,
+// autoFocus: false,
+ autoScroll: false,
+ checkbox: false,
+ /**defines click behavior*/
+ clickFolderMode: 4,
+ debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
+ disabled: false, // TODO: required anymore?
+ enableAspx: true, // TODO: document
+ extensions: [],
+ fx: { height: "toggle", duration: 200 },
+ generateIds: false,
+ icons: true,
+ idPrefix: "ft_",
+ keyboard: true,
+ keyPathSeparator: "/",
+ minExpandLevel: 1,
+ scrollOfs: {top: 0, bottom: 0},
+ scrollParent: null,
+ selectMode: 2,
+ strings: {
+ loading: "Loading…",
+ loadError: "Load error!"
+ },
+ tabbable: true,
+ titlesTabbable: false,
+ _classNames: {
+ node: "fancytree-node",
+ folder: "fancytree-folder",
+ combinedExpanderPrefix: "fancytree-exp-",
+ combinedIconPrefix: "fancytree-ico-",
+ hasChildren: "fancytree-has-children",
+ active: "fancytree-active",
+ selected: "fancytree-selected",
+ expanded: "fancytree-expanded",
+ lazy: "fancytree-lazy",
+ focused: "fancytree-focused",
+ partsel: "fancytree-partsel",
+ lastsib: "fancytree-lastsib",
+ loading: "fancytree-loading",
+ error: "fancytree-error"
+ },
+ // events
+ lazyLoad: null,
+ postProcess: null
+ },
+ /* Set up the widget, Called on first $().fancytree() */
+ _create: function() {
+ this.tree = new Fancytree(this);
+
+ this.$source = this.source || this.element.data("type") === "json" ? this.element
+ : this.element.find(">ul:first");
+ // Subclass Fancytree instance with all enabled extensions
+ var extension, extName, i,
+ extensions = this.options.extensions,
+ base = this.tree;
+
+ for(i=0; i<extensions.length; i++){
+ extName = extensions[i];
+ extension = $.ui.fancytree._extensions[extName];
+ if(!extension){
+ $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
+ }
+ // Add extension options as tree.options.EXTENSION
+// _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
+ this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
+ // Add a namespace tree.ext.EXTENSION, to hold instance data
+ _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
+// this.tree[extName] = extension;
+ this.tree.ext[extName] = {};
+ // Subclass Fancytree methods using proxies.
+ _subclassObject(this.tree, base, extension, extName);
+ // current extension becomes base for the next extension
+ base = extension;
+ }
+ //
+ this.tree._callHook("treeCreate", this.tree);
+ // Note: 'fancytreecreate' event is fired by widget base class
+// this.tree._triggerTreeEvent("create");
+ },
+
+ /* Called on every $().fancytree() */
+ _init: function() {
+ this.tree._callHook("treeInit", this.tree);
+ // TODO: currently we call bind after treeInit, because treeInit
+ // might change tree.$container.
+ // It would be better, to move ebent binding into hooks altogether
+ this._bind();
+ },
+
+ /* Use the _setOption method to respond to changes to options */
+ _setOption: function(key, value) {
+ var callDefault = true,
+ rerender = false;
+ switch( key ) {
+ case "aria":
+ case "checkbox":
+ case "icons":
+ case "minExpandLevel":
+ case "tabbable":
+// case "nolink":
+ this.tree._callHook("treeCreate", this.tree);
+ rerender = true;
+ break;
+ case "source":
+ callDefault = false;
+ this.tree._callHook("treeLoad", this.tree, value);
+ break;
+ }
+ this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
+ if(callDefault){
+ // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
+ $.Widget.prototype._setOption.apply(this, arguments);
+ // TODO: In jQuery UI 1.9 and above, you use the _super method instead
+// this._super( "_setOption", key, value );
+ }
+ if(rerender){
+ this.tree.render(true, false); // force, not-deep
+ }
+ },
+
+ /** Use the destroy method to clean up any modifications your widget has made to the DOM */
+ destroy: function() {
+ this._unbind();
+ this.tree._callHook("treeDestroy", this.tree);
+ // this.element.removeClass("ui-widget ui-widget-content ui-corner-all");
+ this.tree.$div.find(">ul.fancytree-container").remove();
+ this.$source && this.$source.removeClass("ui-helper-hidden");
+ // In jQuery UI 1.8, you must invoke the destroy method from the base widget
+ $.Widget.prototype.destroy.call(this);
+ // TODO: delete tree and nodes to make garbage collect easier?
+ // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
+ },
+
+ // -------------------------------------------------------------------------
+
+ /* Remove all event handlers for our namespace */
+ _unbind: function() {
+ var ns = this.tree._ns;
+ this.element.unbind(ns);
+ this.tree.$container.unbind(ns);
+ $(document).unbind(ns);
+ },
+ /* Add mouse and kyboard handlers to the container */
+ _bind: function() {
+ var that = this,
+ opts = this.options,
+ tree = this.tree,
+ ns = tree._ns
+ // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
+ ;
+
+ // Remove all previuous handlers for this tree
+ this._unbind();
+
+ //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
+ // tree.debug("bind events; container: ", tree.$container);
+ tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
+ var node = FT.getNode(event),
+ flag = (event.type === "focusin");
+ // tree.debug("Tree container got event " + event.type, node, event);
+ // tree.treeOnFocusInOut.call(tree, event);
+ if(node){
+ // For example clicking into an <input> that is part of a node
+ tree._callHook("nodeSetFocus", node, flag);
+ }else{
+ tree._callHook("treeSetFocus", tree, flag);
+ }
+ }).on("selectstart" + ns, "span.fancytree-title", function(event){
+ // prevent mouse-drags to select text ranges
+ // tree.debug("<span title> got event " + event.type);
+ event.preventDefault();
+ }).on("keydown" + ns, function(event){
+ // TODO: also bind keyup and keypress
+ // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
+ // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
+ if(opts.disabled || opts.keyboard === false ){
+ return true;
+ }
+ var res,
+ node = tree.focusNode, // node may be null
+ ctx = tree._makeHookContext(node || tree, event),
+ prevPhase = tree.phase;
+
+ try {
+ tree.phase = "userEvent";
+ // If a 'fancytreekeydown' handler returns false, skip the default
+ // handling (implemented by tree.nodeKeydown()).
+ if(node){
+ res = tree._triggerNodeEvent("keydown", node, event);
+ }else{
+ res = tree._triggerTreeEvent("keydown", event);
+ }
+ if ( res === "preventNav" ){
+ res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
+ } else if ( res !== false ){
+ res = tree._callHook("nodeKeydown", ctx);
+ }
+ return res;
+ } finally {
+ tree.phase = prevPhase;
+ }
+ }).on("click" + ns + " dblclick" + ns, function(event){
+ if(opts.disabled){
+ return true;
+ }
+ var ctx,
+ et = FT.getEventTarget(event),
+ node = et.node,
+ tree = that.tree,
+ prevPhase = tree.phase;
+
+ if( !node ){
+ return true; // Allow bubbling of other events
+ }
+ ctx = tree._makeHookContext(node, event);
+// that.tree.debug("event(" + event.type + "): node: ", node);
+ try {
+ tree.phase = "userEvent";
+ switch(event.type) {
+ case "click":
+ ctx.targetType = et.type;
+ return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
+ case "dblclick":
+ ctx.targetType = et.type;
+ return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
+ }
+// } catch(e) {
+// // var _ = null; // DT issue 117 // TODO
+// $.error(e);
+ } finally {
+ tree.phase = prevPhase;
+ }
+ });
+ },
+ /** Return the active node or null.
+ * @returns {FancytreeNode}
+ */
+ getActiveNode: function() {
+ return this.tree.activeNode;
+ },
+ /** Return the matching node or null.
+ * @param {string} key
+ * @returns {FancytreeNode}
+ */
+ getNodeByKey: function(key) {
+ return this.tree.getNodeByKey(key);
+ },
+ /** Return the invisible system root node.
+ * @returns {FancytreeNode}
+ */
+ getRootNode: function() {
+ return this.tree.rootNode;
+ },
+ /** Return the current tree instance.
+ * @returns {Fancytree}
+ */
+ getTree: function() {
+ return this.tree;
+ }
+});
+
+// $.ui.fancytree was created by the widget factory. Create a local shortcut:
+FT = $.ui.fancytree;
+
+/**
+ * Static members in the `$.ui.fancytree` namespace.<br>
+ * <br>
+ * <pre class="sh_javascript sunlight-highlight-javascript">// Access static members:
+ * var node = $.ui.fancytree.getNode(element);
+ * alert($.ui.fancytree.version);
+ * </pre>
+ *
+ * @mixin Fancytree_Static
+ */
+$.extend($.ui.fancytree,
+ /** @lends Fancytree_Static# */
+ {
+ /** @type {string} */
+ version: "2.1.0", // Set to semver by 'grunt release'
+ /** @type {string} */
+ buildType: "production", // Set to 'production' by 'grunt build'
+ /** @type {int} */
+ debugLevel: 1, // Set to 1 by 'grunt build'
+ // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
+
+ _nextId: 1,
+ _nextNodeKey: 1,
+ _extensions: {},
+ // focusTree: null,
+
+ /** Expose class object as $.ui.fancytree._FancytreeClass */
+ _FancytreeClass: Fancytree,
+ /** Expose class object as $.ui.fancytree._FancytreeNodeClass */
+ _FancytreeNodeClass: FancytreeNode,
+ /* Feature checks to provide backwards compatibility */
+ jquerySupports: {
+ // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
+ positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
+ },
+ /** Throw an error if condition fails (debug method).
+ * @param {boolean} cond
+ * @param {string} msg
+ */
+ assert: function(cond, msg){
+ return _assert(cond, msg);
+ },
+ /** Return a function that executes *fn* at most every *timeout* ms.
+ * @param {integer} timeout
+ * @param {function} fn
+ * @param {boolean} [invokeAsap=false]
+ * @param {any} [ctx]
+ */
+ debounce : function(timeout, fn, invokeAsap, ctx) {
+ var timer;
+ if(arguments.length === 3 && typeof invokeAsap !== "boolean") {
+ ctx = invokeAsap;
+ invokeAsap = false;
+ }
+ return function() {
+ var args = arguments;
+ ctx = ctx || this;
+ invokeAsap && !timer && fn.apply(ctx, args);
+ clearTimeout(timer);
+ timer = setTimeout(function() {
+ invokeAsap || fn.apply(ctx, args);
+ timer = null;
+ }, timeout);
+ };
+ },
+ /** Write message to console if debugLevel >= 2
+ * @param {string} msg
+ */
+ debug: function(msg){
+ /*jshint expr:true */
+ ($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
+ },
+ /** Write error message to console.
+ * @param {string} msg
+ */
+ error: function(msg){
+ consoleApply("error", arguments);
+ },
+ /** Convert <, >, &, ", ', / to the equivalent entitites.
+ *
+ * @param {string} s
+ * @returns {string}
+ */
+ escapeHtml: function(s){
+ return ("" + s).replace(/[&<>"'\/]/g, function (s) {
+ return ENTITY_MAP[s];
+ });
+ },
+ /** Inverse of escapeHtml().
+ *
+ * @param {string} s
+ * @returns {string}
+ */
+ unescapeHtml: function(s){
+ var e = document.createElement("div");
+ e.innerHTML = s;
+ return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
+ },
+ /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
+ *
+ * @param {Event} event Mouse event, e.g. click, ...
+ * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
+ */
+ getEventTargetType: function(event){
+ return this.getEventTarget(event).type;
+ },
+ /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
+ *
+ * @param {Event} event Mouse event, e.g. click, ...
+ * @returns {object} Return a {node: FancytreeNode, type: TYPE} object
+ * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
+ */
+ getEventTarget: function(event){
+ var tcn = event && event.target ? event.target.className : "",
+ res = {node: this.getNode(event.target), type: undefined};
+ // We use a fast version of $(res.node).hasClass()
+ // See http://jsperf.com/test-for-classname/2
+ if( /\bfancytree-title\b/.test(tcn) ){
+ res.type = "title";
+ }else if( /\bfancytree-expander\b/.test(tcn) ){
+ res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
+ }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
+ res.type = "checkbox";
+ }else if( /\bfancytree-icon\b/.test(tcn) ){
+ res.type = "icon";
+ }else if( /\bfancytree-node\b/.test(tcn) ){
+ // Somewhere near the title
+ res.type = "title";
+ }else if( event && event.target && $(event.target).closest(".fancytree-title").length ) {
+ // #228: clicking an embedded element inside a title
+ res.type = "title";
+ }
+ return res;
+ },
+ /** Return a FancytreeNode instance from element.
+ *
+ * @param {Element | jQueryObject | Event} el
+ * @returns {FancytreeNode} matching node or null
+ */
+ getNode: function(el){
+ if(el instanceof FancytreeNode){
+ return el; // el already was a FancytreeNode
+ }else if(el.selector !== undefined){
+ el = el[0]; // el was a jQuery object: use the DOM element
+ }else if(el.originalEvent !== undefined){
+ el = el.target; // el was an Event
+ }
+ while( el ) {
+ if(el.ftnode) {
+ return el.ftnode;
+ }
+ el = el.parentNode;
+ }
+ return null;
+ },
+ /* Return a Fancytree instance from element.
+ * TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
+ * @param {Element | jQueryObject | Event} el
+ * @returns {Fancytree} matching tree or null
+ * /
+ getTree: function(el){
+ if(el instanceof Fancytree){
+ return el; // el already was a Fancytree
+ }else if(el.selector !== undefined){
+ el = el[0]; // el was a jQuery object: use the DOM element
+ }else if(el.originalEvent !== undefined){
+ el = el.target; // el was an Event
+ }
+ ...
+ return null;
+ },
+ */
+ /** Write message to console if debugLevel >= 1
+ * @param {string} msg
+ */
+ info: function(msg){
+ /*jshint expr:true */
+ ($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
+ },
+ /**
+ * Parse tree data from HTML <ul> markup
+ *
+ * @param {jQueryObject} $ul
+ * @returns {NodeData[]}
+ */
+ parseHtml: function($ul) {
+ // TODO: understand this:
+ /*jshint validthis:true */
+ var extraClasses, i, l, iPos, tmp, tmp2, classes, className,
+ $children = $ul.find(">li"),
+ children = [];
+
+ $children.each(function() {
+ var allData,
+ $li = $(this),
+ $liSpan = $li.find(">span:first", this),
+ $liA = $liSpan.length ? null : $li.find(">a:first"),
+ d = { tooltip: null, data: {} };
+
+ if( $liSpan.length ) {
+ d.title = $liSpan.html();
+
+ } else if( $liA && $liA.length ) {
+ // If a <li><a> tag is specified, use it literally and extract href/target.
+ d.title = $liA.html();
+ d.data.href = $liA.attr("href");
+ d.data.target = $liA.attr("target");
+ d.tooltip = $liA.attr("title");
+
+ } else {
+ // If only a <li> tag is specified, use the trimmed string up to
+ // the next child <ul> tag.
+ d.title = $li.html();
+ iPos = d.title.search(/<ul/i);
+ if( iPos >= 0 ){
+ d.title = d.title.substring(0, iPos);
+ }
+ }
+ d.title = $.trim(d.title);
+
+ // Make sure all fields exist
+ for(i=0, l=CLASS_ATTRS.length; i<l; i++){
+ d[CLASS_ATTRS[i]] = undefined;
+ }
+ // Initialize to `true`, if class is set and collect extraClasses
+ classes = this.className.split(" ");
+ extraClasses = [];
+ for(i=0, l=classes.length; i<l; i++){
+ className = classes[i];
+ if(CLASS_ATTR_MAP[className]){
+ d[className] = true;
+ }else{
+ extraClasses.push(className);
+ }
+ }
+ d.extraClasses = extraClasses.join(" ");
+
+ // Parse node options from ID, title and class attributes
+ tmp = $li.attr("title");
+ if( tmp ){
+ d.tooltip = tmp; // overrides <a title='...'>
+ }
+ tmp = $li.attr("id");
+ if( tmp ){
+ d.key = tmp;
+ }
+ // Add <li data-NAME='...'> as node.data.NAME
+ allData = _getElementDataAsDict($li);
+ if(allData && !$.isEmptyObject(allData)) {
+ // #56: Allow to set special node.attributes from data-...
+ for(i=0, l=NODE_ATTRS.length; i<l; i++){
+ tmp = NODE_ATTRS[i];
+ tmp2 = allData[tmp];
+ if( tmp2 != null ) {
+ delete allData[tmp];
+ d[tmp] = tmp2;
+ }
+ }
+ // All other data-... goes to node.data...
+ $.extend(d.data, allData);
+ }
+ // Recursive reading of child nodes, if LI tag contains an UL tag
+ $ul = $li.find(">ul:first");
+ if( $ul.length ) {
+ d.children = $.ui.fancytree.parseHtml($ul);
+ }else{
+ d.children = d.lazy ? undefined : null;
+ }
+ children.push(d);
+// FT.debug("parse ", d, children);
+ });
+ return children;
+ },
+ /** Add Fancytree extension definition to the list of globally available extensions.
+ *
+ * @param {object} definition
+ */
+ registerExtension: function(definition){
+ _assert(definition.name != null, "extensions must have a `name` property.");
+ _assert(definition.version != null, "extensions must have a `version` property.");
+ $.ui.fancytree._extensions[definition.name] = definition;
+ },
+ /** Write warning message to console.
+ * @param {string} msg
+ */
+ warn: function(msg){
+ consoleApply("warn", arguments);
+ }
+});
+
+}(jQuery, window, document));
+
+// Extending Fancytree
+// ===================
+//
+// See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
+//
+// Every extension should have a comment header containing some information
+// about the author, copyright and licensing. Also a pointer to the latest
+// source code.
+// Prefix with `/*!` so the comment is not removed by the minifier.
+
/*!
+ * jquery.fancytree.childcounter.js
+ *
+ * Add a child counter bubble to tree nodes.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+// To keep the global namespace clean, we wrap everything in a closure
+
+;(function($, undefined) {
+
+// Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
+"use strict";
+
+// The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
+// require jshint compliance.
+// But for this sample, we want to allow unused variables for demonstration purpose.
+
+/*jshint unused:false */
+
+
+// Adding methods
+// --------------
+
+// New member functions can be added to the `Fancytree` class.
+// This function will be available for every tree instance.
+//
+// var tree = $("#tree").fancytree("getTree");
+// tree.countSelected(false);
+
+$.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){
+ var tree = this,
+ treeOptions = tree.options;
+ return tree.getSelectedNodes(topOnly).length;
+};
+
+
+// The `FancytreeNode` class can also be easily extended. This would be called
+// like
+//
+// node.toUpper();
+
+$.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){
+ var node = this;
+ return node.setTitle(node.title.toUpperCase());
+};
+
+
+// Finally, we can extend the widget API and create functions that are called
+// like so:
+//
+// $("#tree").fancytree("widgetMethod1", "abc");
+
+$.ui.fancytree.prototype.widgetMethod1 = function(arg1){
+ var tree = this.tree;
+ return arg1;
+};
+
+
+// Register a Fancytree extension
+// ------------------------------
+// A full blown extension, extension is available for all trees and can be
+// enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
+//
+// <script src="../src/jquery.fancytree.js" type="text/javascript"></script>
+// <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script>
+// ...
+//
+// $("#tree").fancytree({
+// extensions: ["childcounter"],
+// childcounter: {
+// hideExpanded: true
+// },
+// ...
+// });
+//
+
+
+/* 'childcounter' extension */
+$.ui.fancytree.registerExtension({
+// Every extension must be registered by a unique name.
+ name: "childcounter",
+// Version information should be compliant with [semver](http://semver.org)
+ version: "1.0.0",
+
+// Extension specific options and their defaults.
+// This options will be available as `tree.options.childcounter.hideExpanded`
+
+ options: {
+ deep: true,
+ hideZeros: true,
+ hideExpanded: false
+ },
+
+// Attributes other than `options` (or functions) can be defined here, and
+// will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
+// They can also be accessed as `this._local.foo` from within the extension
+// methods.
+ foo: 42,
+
+// Local functions are prefixed with an underscore '_'.
+// Callable as `this._local._appendCounter()`.
+
+ _appendCounter: function(bar){
+ var tree = this;
+ },
+
+// **Override virtual methods for this extension.**
+//
+// Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
+// with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
+// for details) and an extended calling context:<br>
+// `this` : the Fancytree instance<br>
+// `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
+// `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
+//
+// See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
+
+ /* Init */
+// `treeInit` is triggered when a tree is initalized. We can set up classes or
+// bind event handlers here...
+ treeInit: function(ctx){
+ var tree = this, // same as ctx.tree,
+ opts = ctx.options,
+ extOpts = ctx.options.childcounter;
+// Optionally check for dependencies with other extensions
+ /* this._requireExtension("glyph", false, false); */
+// Call the base implementation
+ this._super(ctx);
+// Add a class to the tree container
+ this.$container.addClass("fancytree-ext-childcounter");
+ },
+
+// Destroy this tree instance (we only call the default implementation, so
+// this method could as well be omitted).
+
+ treeDestroy: function(ctx){
+ this._super(ctx);
+ },
+
+// Overload the `renderTitle` hook, to append a counter badge
+ nodeRenderTitle: function(ctx, title) {
+ var node = ctx.node,
+ extOpts = ctx.options.childcounter,
+ count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter;
+// Let the base implementation render the title
+ this._super(ctx, title);
+// Append a counter badge
+ if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){
+ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count));
+ }
+ },
+// Overload the `setExpanded` hook, so the counters are updated
+ nodeSetExpanded: function(ctx, flag, opts) {
+ var tree = ctx.tree,
+ node = ctx.node;
+// Let the base implementation expand/collapse the node, then redraw the title
+// after the animation has finished
+ return this._super(ctx, flag, opts).always(function(){
+ tree.nodeRenderTitle(ctx);
+ });
+ }
+
+// End of extension definition
+});
+// End of namespace closure
+}(jQuery));
+
+/*!
+ * jquery.fancytree.dnd.js
+ *
+ * Drag-and-drop support.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+/* *****************************************************************************
+ * Private functions and variables
+ */
+var logMsg = $.ui.fancytree.debug,
+ didRegisterDnd = false;
+
+/* Convert number to string and prepend +/-; return empty string for 0.*/
+function offsetString(n){
+ return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
+}
+
+/* *****************************************************************************
+ * Drag and drop support
+ */
+function _initDragAndDrop(tree) {
+ var dnd = tree.options.dnd || null;
+ // Register 'connectToFancytree' option with ui.draggable
+ if( dnd ) {
+ _registerDnd();
+ }
+ // Attach ui.draggable to this Fancytree instance
+ if(dnd && dnd.dragStart ) {
+ tree.widget.element.draggable($.extend({
+ addClasses: false,
+ appendTo: "body",
+ containment: false,
+ delay: 0,
+ distance: 4,
+ // TODO: merge Dynatree issue 419
+ revert: false,
+ scroll: true, // issue 244: enable scrolling (if ul.fancytree-container)
+ scrollSpeed: 7,
+ scrollSensitivity: 10,
+ // Delegate draggable.start, drag, and stop events to our handler
+ connectToFancytree: true,
+ // Let source tree create the helper element
+ helper: function(event) {
+ var sourceNode = $.ui.fancytree.getNode(event.target);
+ if(!sourceNode){ // Dynatree issue 211
+ // might happen, if dragging a table *header*
+ return "<div>ERROR?: helper requested but sourceNode not found</div>";
+ }
+ return sourceNode.tree.ext.dnd._onDragEvent("helper", sourceNode, null, event, null, null);
+ },
+ start: function(event, ui) {
+ var sourceNode = ui.helper.data("ftSourceNode");
+ return !!sourceNode; // Abort dragging if no node could be found
+ }
+ }, tree.options.dnd.draggable));
+ }
+ // Attach ui.droppable to this Fancytree instance
+ if(dnd && dnd.dragDrop) {
+ tree.widget.element.droppable($.extend({
+ addClasses: false,
+ tolerance: "intersect",
+ greedy: false
+/*
+ activate: function(event, ui) {
+ logMsg("droppable - activate", event, ui, this);
+ },
+ create: function(event, ui) {
+ logMsg("droppable - create", event, ui);
+ },
+ deactivate: function(event, ui) {
+ logMsg("droppable - deactivate", event, ui);
+ },
+ drop: function(event, ui) {
+ logMsg("droppable - drop", event, ui);
+ },
+ out: function(event, ui) {
+ logMsg("droppable - out", event, ui);
+ },
+ over: function(event, ui) {
+ logMsg("droppable - over", event, ui);
+ }
+*/
+ }, tree.options.dnd.droppable));
+ }
+}
+
+//--- Extend ui.draggable event handling --------------------------------------
+
+function _registerDnd() {
+ if(didRegisterDnd){
+ return;
+ }
+
+ // Register proxy-functions for draggable.start/drag/stop
+
+ $.ui.plugin.add("draggable", "connectToFancytree", {
+ start: function(event, ui) {
+ // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
+ var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
+ sourceNode = ui.helper.data("ftSourceNode") || null;
+
+ if(sourceNode) {
+ // Adjust helper offset, so cursor is slightly outside top/left corner
+ draggable.offset.click.top = -2;
+ draggable.offset.click.left = + 16;
+ // Trigger dragStart event
+ // TODO: when called as connectTo..., the return value is ignored(?)
+ return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable);
+ }
+ },
+ drag: function(event, ui) {
+ var isHelper,
+ // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
+ draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
+ sourceNode = ui.helper.data("ftSourceNode") || null,
+ prevTargetNode = ui.helper.data("ftTargetNode") || null,
+ targetNode = $.ui.fancytree.getNode(event.target);
+
+ if(event.target && !targetNode){
+ // We got a drag event, but the targetNode could not be found
+ // at the event location. This may happen,
+ // 1. if the mouse jumped over the drag helper,
+ // 2. or if a non-fancytree element is dragged
+ // We ignore it:
+ isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0;
+ if(isHelper){
+ logMsg("Drag event over helper: ignored.");
+ return;
+ }
+ }
+ ui.helper.data("ftTargetNode", targetNode);
+ // Leaving a tree node
+ if(prevTargetNode && prevTargetNode !== targetNode ) {
+ prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
+ }
+ if(targetNode){
+ if(!targetNode.tree.options.dnd.dragDrop) {
+ // not enabled as drop target
+ } else if(targetNode === prevTargetNode) {
+ // Moving over same node
+ targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
+ }else{
+ // Entering this node first time
+ targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
+ }
+ }
+ // else go ahead with standard event handling
+ },
+ stop: function(event, ui) {
+ // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
+ var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
+ sourceNode = ui.helper.data("ftSourceNode") || null,
+ targetNode = ui.helper.data("ftTargetNode") || null,
+// mouseDownEvent = draggable._mouseDownEvent,
+ eventType = event.type,
+ dropped = (eventType === "mouseup" && event.which === 1);
+
+ if(!dropped){
+ logMsg("Drag was cancelled");
+ }
+ if(targetNode) {
+ if(dropped){
+ targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
+ }
+ targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
+ }
+ if(sourceNode){
+ sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable);
+ }
+ }
+ });
+
+ didRegisterDnd = true;
+}
+
+
+/* *****************************************************************************
+ *
+ */
+
+$.ui.fancytree.registerExtension({
+ name: "dnd",
+ version: "0.1.0",
+ // Default options for this extension.
+ options: {
+ // Make tree nodes draggable:
+ dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
+ dragStop: null, // Callback(sourceNode, data)
+// helper: null,
+ // Make tree nodes accept draggables
+ autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
+ preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
+ preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
+ dragEnter: null, // Callback(targetNode, data)
+ dragOver: null, // Callback(targetNode, data)
+ dragDrop: null, // Callback(targetNode, data)
+ dragLeave: null, // Callback(targetNode, data)
+ //
+ draggable: null, // Additional options passed to jQuery draggable
+ droppable: null // Additional options passed to jQuery droppable
+ },
+
+ treeInit: function(ctx){
+ var tree = ctx.tree;
+ this._super(ctx);
+ _initDragAndDrop(tree);
+ },
+ /* Override key handler in order to cancel dnd on escape.*/
+ nodeKeydown: function(ctx) {
+ var event = ctx.originalEvent;
+ if( event.which === $.ui.keyCode.ESCAPE) {
+ this._local._cancelDrag();
+ }
+ return this._super(ctx);
+ },
+ /* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */
+ _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
+ var posOpts,
+ markerOffsetX = 0,
+ markerAt = "center",
+ instData = this._local,
+ $source = sourceNode ? $(sourceNode.span) : null,
+ $target = $(targetNode.span);
+
+ if( !instData.$dropMarker ) {
+ instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>")
+ .hide()
+ .css({"z-index": 1000})
+ .prependTo($(this.$div).parent());
+// .prependTo("body");
+ }
+// this.$dropMarker.attr("class", hitMode);
+ if(hitMode === "after" || hitMode === "before" || hitMode === "over"){
+// $source && $source.addClass("fancytree-drag-source");
+
+// $target.addClass("fancytree-drop-target");
+
+ switch(hitMode){
+ case "before":
+ instData
+ .$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over")
+ .addClass("fancytree-drop-before");
+ markerAt = "top";
+ break;
+ case "after":
+ instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over")
+ .addClass("fancytree-drop-after");
+ markerAt = "bottom";
+ break;
+ default:
+ instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before")
+ .addClass("fancytree-drop-over");
+ $target.addClass("fancytree-drop-target");
+ markerOffsetX = 8;
+ }
+
+ if( $.ui.fancytree.jquerySupports.positionMyOfs ){
+ posOpts = {
+ my: "left" + offsetString(markerOffsetX) + " center",
+ at: "left " + markerAt,
+ of: $target
+ };
+ } else {
+ posOpts = {
+ my: "left center",
+ at: "left " + markerAt,
+ of: $target,
+ offset: "" + markerOffsetX + " 0"
+ };
+ }
+ instData.$dropMarker
+ .show()
+ .position(posOpts);
+// helper.addClass("fancytree-drop-hover");
+ } else {
+// $source && $source.removeClass("fancytree-drag-source");
+ $target.removeClass("fancytree-drop-target");
+ instData.$dropMarker.hide();
+// helper.removeClass("fancytree-drop-hover");
+ }
+ if(hitMode === "after"){
+ $target.addClass("fancytree-drop-after");
+ } else {
+ $target.removeClass("fancytree-drop-after");
+ }
+ if(hitMode === "before"){
+ $target.addClass("fancytree-drop-before");
+ } else {
+ $target.removeClass("fancytree-drop-before");
+ }
+ if(accept === true){
+ if($source){
+ $source.addClass("fancytree-drop-accept");
+ }
+ $target.addClass("fancytree-drop-accept");
+ helper.addClass("fancytree-drop-accept");
+ }else{
+ if($source){
+ $source.removeClass("fancytree-drop-accept");
+ }
+ $target.removeClass("fancytree-drop-accept");
+ helper.removeClass("fancytree-drop-accept");
+ }
+ if(accept === false){
+ if($source){
+ $source.addClass("fancytree-drop-reject");
+ }
+ $target.addClass("fancytree-drop-reject");
+ helper.addClass("fancytree-drop-reject");
+ }else{
+ if($source){
+ $source.removeClass("fancytree-drop-reject");
+ }
+ $target.removeClass("fancytree-drop-reject");
+ helper.removeClass("fancytree-drop-reject");
+ }
+ },
+
+ /*
+ * Handles drag'n'drop functionality.
+ *
+ * A standard jQuery drag-and-drop process may generate these calls:
+ *
+ * draggable helper():
+ * _onDragEvent("helper", sourceNode, null, event, null, null);
+ * start:
+ * _onDragEvent("start", sourceNode, null, event, ui, draggable);
+ * drag:
+ * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
+ * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
+ * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
+ * stop:
+ * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
+ * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
+ * _onDragEvent("stop", sourceNode, null, event, ui, draggable);
+ */
+ _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
+ if(eventName !== "over"){
+ logMsg("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
+ }
+ var $helper, nodeOfs, relPos, relPos2,
+ enterResponse, hitMode, r,
+ opts = this.options,
+ dnd = opts.dnd,
+ ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}),
+ res = null,
+ $nodeTag = $(node.span);
+
+ switch (eventName) {
+ case "helper":
+ // Only event and node argument is available
+ $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
+ .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar
+ .append($nodeTag.find("span.fancytree-title").clone());
+ // DT issue 244: helper should be child of scrollParent
+ $("ul.fancytree-container", node.tree.$div).append($helper);
+ // Attach node reference to helper object
+ $helper.data("ftSourceNode", node);
+ // logMsg("helper=%o", $helper);
+ // logMsg("helper.sourceNode=%o", $helper.data("ftSourceNode"));
+ res = $helper;
+ break;
+
+ case "start":
+ if( node.isStatusNode() ) {
+ res = false;
+ } else if(dnd.dragStart) {
+ res = dnd.dragStart(node, ctx);
+ }
+ if(res === false) {
+ this.debug("tree.dragStart() cancelled");
+ //draggable._clear();
+ // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned)
+ // TODO: call this._cancelDrag()?
+ ui.helper.trigger("mouseup")
+ .hide();
+ } else {
+ $nodeTag.addClass("fancytree-drag-source");
+ }
+ break;
+
+ case "enter":
+ if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){
+ r = false;
+ }else{
+ r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
+ }
+ if(!r){
+ // convert null, undefined, false to false
+ res = false;
+ }else if ( $.isArray(r) ) {
+ // TODO: also accept passing an object of this format directly
+ res = {
+ over: ($.inArray("over", r) >= 0),
+ before: ($.inArray("before", r) >= 0),
+ after: ($.inArray("after", r) >= 0)
+ };
+ }else{
+ res = {
+ over: ((r === true) || (r === "over")),
+ before: ((r === true) || (r === "before")),
+ after: ((r === true) || (r === "after"))
+ };
+ }
+ ui.helper.data("enterResponse", res);
+ logMsg("helper.enterResponse: %o", res);
+ break;
+
+ case "over":
+ enterResponse = ui.helper.data("enterResponse");
+ hitMode = null;
+ if(enterResponse === false){
+ // Don't call dragOver if onEnter returned false.
+// break;
+ } else if(typeof enterResponse === "string") {
+ // Use hitMode from onEnter if provided.
+ hitMode = enterResponse;
+ } else {
+ // Calculate hitMode from relative cursor position.
+ nodeOfs = $nodeTag.offset();
+ relPos = { x: event.pageX - nodeOfs.left,
+ y: event.pageY - nodeOfs.top };
+ relPos2 = { x: relPos.x / $nodeTag.width(),
+ y: relPos.y / $nodeTag.height() };
+
+ if( enterResponse.after && relPos2.y > 0.75 ){
+ hitMode = "after";
+ } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
+ hitMode = "after";
+ } else if(enterResponse.before && relPos2.y <= 0.25) {
+ hitMode = "before";
+ } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
+ hitMode = "before";
+ } else if(enterResponse.over) {
+ hitMode = "over";
+ }
+ // Prevent no-ops like 'before source node'
+ // TODO: these are no-ops when moving nodes, but not in copy mode
+ if( dnd.preventVoidMoves ){
+ if(node === otherNode){
+ logMsg(" drop over source node prevented");
+ hitMode = null;
+ }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
+ logMsg(" drop after source node prevented");
+ hitMode = null;
+ }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
+ logMsg(" drop before source node prevented");
+ hitMode = null;
+ }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){
+ logMsg(" drop last child over own parent prevented");
+ hitMode = null;
+ }
+ }
+// logMsg("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
+ ui.helper.data("hitMode", hitMode);
+ }
+ // Auto-expand node (only when 'over' the node, not 'before', or 'after')
+ if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) {
+ node.scheduleAction("expand", dnd.autoExpandMS);
+ }
+ if(hitMode && dnd.dragOver){
+ // TODO: http://code.google.com/p/dynatree/source/detail?r=625
+ ctx.hitMode = hitMode;
+ res = dnd.dragOver(node, ctx);
+ }
+ // DT issue 332
+// this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false);
+ this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null);
+ break;
+
+ case "drop":
+ hitMode = ui.helper.data("hitMode");
+ if(hitMode && dnd.dragDrop){
+ ctx.hitMode = hitMode;
+ dnd.dragDrop(node, ctx);
+ }
+ break;
+
+ case "leave":
+ // Cancel pending expand request
+ node.scheduleAction("cancel");
+ ui.helper.data("enterResponse", null);
+ ui.helper.data("hitMode", null);
+ this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined);
+ if(dnd.dragLeave){
+ dnd.dragLeave(node, ctx);
+ }
+ break;
+
+ case "stop":
+ $nodeTag.removeClass("fancytree-drag-source");
+ if(dnd.dragStop){
+ dnd.dragStop(node, ctx);
+ }
+ break;
+
+ default:
+ $.error("Unsupported drag event: " + eventName);
+ }
+ return res;
+ },
+
+ _cancelDrag: function() {
+ var dd = $.ui.ddmanager.current;
+ if(dd){
+ dd.cancel();
+ }
+ }
+});
+}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.edit.js
+ *
+ * Make node titles editable.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+
+/*******************************************************************************
+ * Private functions and variables
+ */
+
+var isMac = /Mac/.test(navigator.platform),
+ escapeHtml = $.ui.fancytree.escapeHtml,
+ unescapeHtml = $.ui.fancytree.unescapeHtml;
+ // modifiers = {shift: "shiftKey", ctrl: "ctrlKey", alt: "altKey", meta: "metaKey"},
+ // specialKeys = {
+ // 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
+ // 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
+ // 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
+ // 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
+ // 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
+ // 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
+ // 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 186: ";", 191: "/",
+ // 220: "\\", 222: "'", 224: "meta"
+ // },
+ // shiftNums = {
+ // "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
+ // "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
+ // ".": ">", "/": "?", "\\": "|"
+ // };
+
+
+// $.ui.fancytree.isKeydownEvent = function(e, code){
+// var i, part, partmap, partlist = code.split("+"), len = parts.length;
+// var c = String.fromCharCode(e.which).toLowerCase();
+// for( i = 0; i < len; i++ ) {
+// }
+// alert (parts.unshift());
+// alert (parts.unshift());
+// alert (parts.unshift());
+// };
+
+
+/**
+ * [ext-edit] Start inline editing of current node title.
+ *
+ * @alias FancytreeNode#editStart
+ * @requires Fancytree
+ */
+$.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){
+ var $input,
+ node = this,
+ tree = this.tree,
+ local = tree.ext.edit,
+ prevTitle = node.title,
+ instOpts = tree.options.edit,
+ $title = $(".fancytree-title", node.span),
+ eventData = {node: node, tree: tree, options: tree.options};
+
+ if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false){
+ return false;
+ }
+ // beforeEdit may want to modify the title before editing
+ prevTitle = node.title;
+
+ node.debug("editStart");
+ // Disable standard Fancytree mouse- and key handling
+ tree.widget._unbind();
+ // #116: ext-dnd prevents the blur event, so we have to catch outer clicks
+ $(document).on("mousedown.fancytree-edit", function(event){
+ if( ! $(event.target).hasClass("fancytree-edit-input") ){
+ node.editEnd(true, event);
+ }
+ });
+
+ // Replace node with <input>
+ $input = $("<input />", {
+ "class": "fancytree-edit-input",
+ value: unescapeHtml(prevTitle)
+ });
+ if ( instOpts.adjustWidthOfs != null ) {
+ $input.width($title.width() + instOpts.adjustWidthOfs);
+ }
+ if ( instOpts.inputCss != null ) {
+ $input.css(instOpts.inputCss);
+ }
+ eventData.input = $input;
+
+ $title.html($input);
+
+ $.ui.fancytree.assert(!local.currentNode, "recursive edit");
+ local.currentNode = this;
+ // Focus <input> and bind keyboard handler
+ $input
+ .focus()
+ .change(function(event){
+ $input.addClass("fancytree-edit-dirty");
+ }).keydown(function(event){
+ switch( event.which ) {
+ case $.ui.keyCode.ESCAPE:
+ node.editEnd(false, event);
+ break;
+ case $.ui.keyCode.ENTER:
+ node.editEnd(true, event);
+ return false; // so we don't start editmode on Mac
+ }
+ }).blur(function(event){
+ return node.editEnd(true, event);
+ });
+
+ instOpts.edit.call(node, {type: "edit"}, eventData);
+};
+
+
+/**
+ * [ext-edit] Stop inline editing.
+ * @param {Boolean} [applyChanges=false]
+ * @alias FancytreeNode#editEnd
+ * @requires jquery.fancytree.edit.js
+ */
+$.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){
+ var node = this,
+ tree = this.tree,
+ local = tree.ext.edit,
+ instOpts = tree.options.edit,
+ $title = $(".fancytree-title", node.span),
+ $input = $title.find("input.fancytree-edit-input"),
+ newVal = $input.val(),
+ dirty = $input.hasClass("fancytree-edit-dirty"),
+ doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title),
+ eventData = {
+ node: node, tree: tree, options: tree.options, originalEvent: _event,
+ dirty: dirty,
+ save: doSave,
+ input: $input,
+ value: newVal
+ };
+
+ if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){
+ return false;
+ }
+ if( doSave && instOpts.save.call(node, {type: "save"}, eventData) === false){
+ return false;
+ }
+ $input
+ .removeClass("fancytree-edit-dirty")
+ .unbind();
+ // Unbind outer-click handler
+ $(document).off(".fancytree-edit");
+
+ if( doSave ) {
+ node.setTitle( escapeHtml(newVal) );
+ }else{
+ node.renderTitle();
+ }
+ // Re-enable mouse and keyboard handling
+ tree.widget._bind();
+ local.currentNode = null;
+ node.setFocus();
+ // Set keyboard focus, even if setFocus() claims 'nothing to do'
+ $(tree.$container).focus();
+ eventData.input = null;
+ instOpts.close.call(node, {type: "close"}, eventData);
+ return true;
+};
+
+
+$.ui.fancytree._FancytreeNodeClass.prototype.startEdit = function(){
+ this.warn("FancytreeNode.startEdit() is deprecated since 2014-01-04. Use .editStart() instead.");
+ return this.editStart.apply(this, arguments);
+};
+
+
+$.ui.fancytree._FancytreeNodeClass.prototype.endEdit = function(){
+ this.warn("FancytreeNode.endEdit() is deprecated since 2014-01-04. Use .editEnd() instead.");
+ return this.editEnd.apply(this, arguments);
+};
+
+
+///**
+// * Create a new child or sibling node.
+// *
+// * @param {String} [mode] 'before', 'after', or 'child'
+// * @lends FancytreeNode.prototype
+// * @requires jquery.fancytree.edit.js
+// */
+//$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode){
+// var newNode,
+// node = this,
+// tree = this.tree,
+// local = tree.ext.edit,
+// instOpts = tree.options.edit,
+// $title = $(".fancytree-title", node.span),
+// $input = $title.find("input.fancytree-edit-input"),
+// newVal = $input.val(),
+// dirty = $input.hasClass("fancytree-edit-dirty"),
+// doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title),
+// eventData = {
+// node: node, tree: tree, options: tree.options, originalEvent: _event,
+// dirty: dirty,
+// save: doSave,
+// input: $input,
+// value: newVal
+// };
+//
+// node.debug("editCreate");
+//
+// if( instOpts.beforeEdit.call(node, {type: "beforeCreateNode"}, eventData) === false){
+// return false;
+// }
+// newNode = this.addNode({title: "Neuer Knoten"}, mode);
+//
+// newNode.editStart();
+//};
+
+
+/**
+ * [ext-edit] Check if any node in this tree in edit mode.
+ *
+ * @returns {FancytreeNode | null}
+ * @alias Fancytree#isEditing
+ * @requires jquery.fancytree.edit.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.isEditing = function(){
+ return this.ext.edit.currentNode;
+};
+
+
+/**
+ * [ext-edit] Check if this node is in edit mode.
+ * @returns {Boolean} true if node is currently beeing edited
+ * @alias FancytreeNode#isEditing
+ * @requires jquery.fancytree.edit.js
+ */
+$.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){
+ return this.tree.ext.edit.currentNode === this;
+};
+
+
+/*******************************************************************************
+ * Extension code
+ */
+$.ui.fancytree.registerExtension({
+ name: "edit",
+ version: "0.1.0",
+ // Default options for this extension.
+ options: {
+ adjustWidthOfs: 4, // null: don't adjust input size to content
+ inputCss: {minWidth: "3em"},
+ triggerCancel: ["esc", "tab", "click"],
+ // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
+ triggerStart: ["f2", "shift+click", "mac+enter"],
+ beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
+ beforeEdit: $.noop, // Return false to prevent edit mode
+ close: $.noop, // Editor was removed
+ edit: $.noop, // Editor was opened (available as data.input)
+// keypress: $.noop, // Not yet implemented
+ save: $.noop // Save data.input.val() or return false to keep editor open
+ },
+ // Local attributes
+ currentNode: null,
+
+ treeInit: function(ctx){
+ this._super(ctx);
+ this.$container.addClass("fancytree-ext-edit");
+ },
+ nodeClick: function(ctx) {
+ if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){
+ if( ctx.originalEvent.shiftKey ){
+ ctx.node.editStart();
+ return false;
+ }
+ }
+ return this._super(ctx);
+ },
+ nodeDblclick: function(ctx) {
+ if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){
+ ctx.node.editStart();
+ return false;
+ }
+ return this._super(ctx);
+ },
+ nodeKeydown: function(ctx) {
+ switch( ctx.originalEvent.which ) {
+ case 113: // [F2]
+ if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){
+ ctx.node.editStart();
+ return false;
+ }
+ break;
+ case $.ui.keyCode.ENTER:
+ if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){
+ ctx.node.editStart();
+ return false;
+ }
+ break;
+ }
+ return this._super(ctx);
+ }
+});
+}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.filter.js
+ *
+ * Remove or highlight tree nodes, based on a filter.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+
+/*******************************************************************************
+ * Private functions and variables
+ */
+
+function _escapeRegex(str){
+ /*jshint regexdash:true */
+ return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1");
+}
+
+$.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, leavesOnly){
+ var match, re,
+ count = 0,
+ hideMode = this.options.filter.mode === "hide";
+ // leavesOnly = !branchMode && this.options.filter.leavesOnly;
+ leavesOnly = !!leavesOnly && !branchMode;
+
+ // Default to 'match title substring (not case sensitive)'
+ if(typeof filter === "string"){
+ match = _escapeRegex(filter); // make sure a '.' is treated literally
+ re = new RegExp(".*" + match + ".*", "i");
+ filter = function(node){
+ return !!re.exec(node.title);
+ };
+ }
+
+ this.enableFilter = true;
+ this.$div.addClass("fancytree-ext-filter");
+ if( hideMode ){
+ this.$div.addClass("fancytree-ext-filter-hide");
+ } else {
+ this.$div.addClass("fancytree-ext-filter-dimm");
+ }
+ // Reset current filter
+ this.visit(function(node){
+ delete node.match;
+ delete node.subMatch;
+ });
+ // Adjust node.hide, .match, .subMatch flags
+ this.visit(function(node){
+ if ((!leavesOnly || node.children == null) && filter(node)) {
+ count++;
+ node.match = true;
+ node.visitParents(function(p){
+ p.subMatch = true;
+ });
+ if( branchMode ) {
+ node.visit(function(p){
+ p.match = true;
+ });
+ return "skip";
+ }
+ }
+ });
+ // Redraw
+ this.render();
+ return count;
+};
+
+/**
+ * [ext-filter] Dimm or hide nodes.
+ *
+ * @param {function | string} filter
+ * @param {boolean} [leavesOnly=false]
+ * @returns {integer} count
+ * @alias Fancytree#filterNodes
+ * @requires jquery.fancytree.filter.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, leavesOnly){
+ return this._applyFilterImpl(filter, false, leavesOnly);
+};
+
+$.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){
+ this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead.");
+ return this.filterNodes.apply(this, arguments);
+};
+
+/**
+ * [ext-filter] Dimm or hide whole branches.
+ *
+ * @param {function | string} filter
+ * @returns {integer} count
+ * @alias Fancytree#filterBranches
+ * @requires jquery.fancytree.filter.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter){
+ return this._applyFilterImpl(filter, true, null);
+};
+
+
+/**
+ * [ext-filter] Reset the filter.
+ *
+ * @alias Fancytree#clearFilter
+ * @requires jquery.fancytree.filter.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){
+ this.visit(function(node){
+ delete node.match;
+ delete node.subMatch;
+ });
+ this.enableFilter = false;
+ this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide");
+ this.render();
+};
+
+
+/*******************************************************************************
+ * Extension code
+ */
+$.ui.fancytree.registerExtension({
+ name: "filter",
+ version: "0.2.0",
+ // Default options for this extension.
+ options: {
+ mode: "dimm"
+// leavesOnly: false
+ },
+ treeInit: function(ctx){
+ this._super(ctx);
+ },
+ nodeRenderStatus: function(ctx) {
+ // Set classes for current status
+ var res,
+ node = ctx.node,
+ tree = ctx.tree,
+ $span = $(node[tree.statusClassPropName]);
+
+ res = this._super(ctx);
+ // nothing to do, if node was not yet rendered
+ if( !$span.length || !tree.enableFilter ) {
+ return res;
+ }
+ $span
+ .toggleClass("fancytree-match", !!node.match)
+ .toggleClass("fancytree-submatch", !!node.subMatch)
+ .toggleClass("fancytree-hide", !(node.match || node.subMatch));
+
+ return res;
+ }
+});
+}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.glyph.js
+ *
+ * Use glyph fonts as instead of icon sprites.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+/* *****************************************************************************
+ * Private functions and variables
+ */
+
+function _getIcon(opts, type){
+ return opts.map[type];
+}
+
+$.ui.fancytree.registerExtension({
+ name: "glyph",
+ version: "0.1.0",
+ // Default options for this extension.
+ options: {
+ prefix: "icon-",
+ extra: null,
+ map: {
+ doc: "icon-file-alt",
+ docOpen: "icon-file-alt",
+ checkbox: "icon-check-empty",
+ checkboxSelected: "icon-check",
+ checkboxUnknown: "icon-check icon-muted",
+ error: "icon-exclamation-sign",
+ expanderClosed: "icon-caret-right",
+ expanderLazy: "icon-angle-right",
+ expanderOpen: "icon-caret-down",
+ folder: "icon-folder-close-alt",
+ folderOpen: "icon-folder-open-alt",
+ loading: "icon-refresh icon-spin",
+ noExpander: ""
+ },
+ icon: null // TODO: allow callback here
+ },
+
+ treeInit: function(ctx){
+ var tree = ctx.tree;
+ this._super(ctx);
+ tree.$container.addClass("fancytree-ext-glyph");
+ },
+ nodeRenderStatus: function(ctx) {
+ var icon, span,
+ node = ctx.node,
+ opts = ctx.options.glyph,
+ // callback = opts.icon,
+ map = opts.map
+ // prefix = opts.prefix
+ // $span = $(node.span)
+ ;
+
+ this._super(ctx);
+
+ if( node.isRoot() ){
+ return;
+ }
+
+ span = $("span.fancytree-expander", node.span).get(0);
+ if( span ){
+ if( node.isLoading() ){
+ icon = "loading";
+ }else if( node.expanded ){
+ icon = "expanderOpen";
+ }else if( node.isUndefined() ){
+ icon = "expanderLazy";
+ }else if( node.hasChildren() ){
+ icon = "expanderClosed";
+ }else{
+ icon = "noExpander";
+ }
+ span.className = "fancytree-expander " + map[icon];
+ }
+
+ span = $("span.fancytree-checkbox", node.tr || node.span).get(0);
+ if( span ){
+ icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox");
+ span.className = "fancytree-checkbox " + map[icon];
+ }
+
+ span = $("span.fancytree-icon", node.span).get(0);
+ if( span ){
+ if( node.folder ){
+ icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder");
+ }else{
+ icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc");
+ }
+ span.className = "fancytree-icon " + icon;
+ }
+ },
+ nodeSetStatus: function(ctx, status, message, details) {
+ var span,
+ opts = ctx.options.glyph,
+ node = ctx.node;
+
+ this._super(ctx, status, message, details);
+
+ if(node.parent){
+ span = $("span.fancytree-expander", node.span).get(0);
+ }else{
+ span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName])
+ .find("span.fancytree-expander").get(0);
+ }
+ if( status === "loading"){
+ // $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading"));
+ span.className = "fancytree-expander " + _getIcon(opts, "loading");
+ }else if( status === "error"){
+ span.className = "fancytree-expander " + _getIcon(opts, "error");
+ }
+ }
+});
+}(jQuery, window, document));
+
+/*!
* jquery.fancytree.gridnav.js
*
* Support keyboard navigation for trees with embedded input controls.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
- * Copyright (c) 2013, Martin Wendt (http://wwWendt.de)
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
- * @version DEVELOPMENT
- * @date DEVELOPMENT
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
*/
-
;(function($, window, document, undefined) {
"use strict";
@@ -26551,80 +31925,115 @@
"select-one": [KC.LEFT, KC.RIGHT],
"select-multiple": [KC.LEFT, KC.RIGHT]
};
+/* Calculate TD column index (considering colspans).*/
+function getColIdx($tr, $td) {
+ var colspan,
+ td = $td.get(0),
+ idx = 0;
+
+ $tr.children().each(function () {
+ if( this === td ) {
+ return false;
+ }
+ colspan = $(this).prop("colspan");
+ idx += colspan ? colspan : 1;
+ });
+ return idx;
+}
+
+
+/* Find TD at given column index (considering colspans).*/
+function findTdAtColIdx($tr, colIdx) {
+ var colspan,
+ res = null,
+ idx = 0;
+
+ $tr.children().each(function () {
+ if( idx >= colIdx ) {
+ res = $(this);
+ return false;
+ }
+ colspan = $(this).prop("colspan");
+ idx += colspan ? colspan : 1;
+ });
+ return res;
+}
+
+
+/* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
function findNeighbourTd($target, keyCode){
- var $td = $target.closest("td");
+ var $tr, colIdx,
+ $td = $target.closest("td"),
+ $tdNext = null;
+
switch( keyCode ){
case KC.LEFT:
- return $td.prev();
+ $tdNext = $td.prev();
+ break;
case KC.RIGHT:
- return $td.next();
+ $tdNext = $td.next();
+ break;
case KC.UP:
- return $td.parent().prevAll(":visible").first().find("td").eq($td.index());
case KC.DOWN:
- return $td.parent().nextAll(":visible").first().find("td").eq($td.index());
+ $tr = $td.parent();
+ colIdx = getColIdx($tr, $td);
+ while( true ) {
+ $tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next();
+ if( !$tr.length ) {
+ break;
+ }
+ // Skip hidden rows
+ if( $tr.is(":hidden") ) {
+ continue;
+ }
+ // Find adjacent cell in the same column
+ $tdNext = findTdAtColIdx($tr, colIdx);
+ // Skip cells that don't conatain a focusable element
+ if( $tdNext && $tdNext.find(":input").length ) {
+ break;
+ }
+ }
+ break;
}
- return null;
+ return $tdNext;
}
+
/*******************************************************************************
* Extension code
*/
-$.ui.fancytree.registerExtension("gridnav", {
+$.ui.fancytree.registerExtension({
+ name: "gridnav",
version: "0.0.1",
// Default options for this extension.
options: {
autofocusInput: false, // Focus first embedded input if node gets activated
- handleCursorKeys: true, // Allow UP/DOWN in inputs to move to prev/next node
- titlesTabbable: true // Add node title to TAB chain
+ handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
},
treeInit: function(ctx){
-
+ // gridnav requires the table extension to be loaded before itself
+ this._requireExtension("table", true, true);
this._super(ctx);
this.$container.addClass("fancytree-ext-gridnav");
// Activate node if embedded input gets focus (due to a click)
-// this.$container.on("focusin", "input", function(event){
this.$container.on("focusin", function(event){
var ctx2,
node = $.ui.fancytree.getNode(event.target);
- // node.debug("INPUT focusin", event.target, event);
if( node && !node.isActive() ){
// Call node.setActive(), but also pass the event
ctx2 = ctx.tree._makeHookContext(node, event);
ctx.tree._callHook("nodeSetActive", ctx2, true);
}
});
},
- nodeRender: function(ctx) {
- this._super(ctx);
- // Add every node title to the tab sequence
- if( ctx.options.gridnav.titlesTabbable === true ){
- $(ctx.node.span).find("span.fancytree-title").attr("tabindex", "0");
- }
- },
- // nodeRenderStatus: function(ctx) {
- // var opts = ctx.options.gridnav,
- // node = ctx.node;
-
- // this._super(ctx);
-
- // // Note: Setting 'tabbable' only to the active node wouldn't help,
- // // because the first row contains a tabbable input element anyway.
- // if( opts.titlesTabbable === "active" ){
- // if( node.isActive() ){
- // $(node.span) .find("span.fancytree-title") .attr("tabindex", "0");
- // }else{
- // $(node.span) .find("span.fancytree-title") .removeAttr("tabindex");
- // }
- // }
- // },
nodeSetActive: function(ctx, flag) {
var $outer,
opts = ctx.options.gridnav,
node = ctx.node,
event = ctx.originalEvent || {},
@@ -26633,11 +32042,11 @@
flag = (flag !== false);
this._super(ctx, flag);
if( flag ){
- if( opts.titlesTabbable ){
+ if( ctx.options.titlesTabbable ){
if( !triggeredByInput ) {
$(node.span).find("span.fancytree-title").focus();
node.setFocus();
}
// If one node is tabbable, the container no longer needs to be
@@ -26657,11 +32066,11 @@
event = ctx.originalEvent,
$target = $(event.target);
// jQuery
inputType = $target.is(":input:enabled") ? $target.prop("type") : null;
- ctx.node.debug("input", event, inputType);
+// ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
if( inputType && opts.handleCursorKeys ){
handleKeys = NAV_KEYS[inputType];
if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
$td = findNeighbourTd($target, event.which);
@@ -26672,14 +32081,797 @@
return false;
}
}
return true;
}
+ ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
+ return this._super(ctx);
+ }
+});
+}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.persist.js
+ *
+ * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * @depends: jquery.cookie.js
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+
+/*******************************************************************************
+ * Private functions and variables
+ */
+function _assert(cond, msg){
+ msg = msg || "";
+ if(!cond){
+ $.error("Assertion failed " + msg);
+ }
+}
+
+var ACTIVE = "active",
+ EXPANDED = "expanded",
+ FOCUS = "focus",
+ SELECTED = "selected";
+
+
+/* Recursively load lazy nodes
+ * @param {string} mode 'load', 'expand', false
+ */
+function _loadLazyNodes(tree, local, keyList, mode, dfd) {
+ var i, key, l, node,
+ foundOne = false,
+ deferredList = [],
+ missingKeyList = [];
+
+ keyList = keyList || [];
+ dfd = dfd || $.Deferred();
+
+ for( i=0, l=keyList.length; i<l; i++ ) {
+ key = keyList[i];
+ node = tree.getNodeByKey(key);
+ if( node ) {
+ if( mode && node.isUndefined() ) {
+ foundOne = true;
+ tree.debug("_loadLazyNodes: " + node + " is lazy: loading...");
+ if( mode === "expand" ) {
+ deferredList.push(node.setExpanded());
+ } else {
+ deferredList.push(node.load());
+ }
+ } else {
+ tree.debug("_loadLazyNodes: " + node + " already loaded.");
+ node.setExpanded();
+ }
+ } else {
+ missingKeyList.push(key);
+ tree.debug("_loadLazyNodes: " + node + " was not yet found.");
+ }
+ }
+
+ $.when.apply($, deferredList).always(function(){
+ // All lazy-expands have finished
+ if( foundOne && missingKeyList.length > 0 ) {
+ // If we read new nodes from server, try to resolve yet-missing keys
+ _loadLazyNodes(tree, local, missingKeyList, mode, dfd);
+ } else {
+ if( missingKeyList.length ) {
+ tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList);
+ for( i=0, l=missingKeyList.length; i<l; i++ ) {
+ key = keyList[i];
+ local._appendKey(EXPANDED, keyList[i], false);
+ }
+ }
+ dfd.resolve();
+ }
+ });
+ return dfd;
+}
+
+
+/**
+ * [ext-persist] Remove persistence cookies of the given type(s).
+ * Called like
+ * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected");
+ *
+ * @alias Fancytree#clearCookies
+ * @requires jquery.fancytree.persist.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){
+ var local = this.ext.persist,
+ prefix = local.cookiePrefix;
+
+ types = types || "active expanded focus selected";
+ if(types.indexOf(ACTIVE) >= 0){
+ local._data(prefix + ACTIVE, null);
+ }
+ if(types.indexOf(EXPANDED) >= 0){
+ local._data(prefix + EXPANDED, null);
+ }
+ if(types.indexOf(FOCUS) >= 0){
+ local._data(prefix + FOCUS, null);
+ }
+ if(types.indexOf(SELECTED) >= 0){
+ local._data(prefix + SELECTED, null);
+ }
+};
+
+
+/**
+ * [ext-persist] Return persistence information from cookies
+ *
+ * Called like
+ * $("#tree").fancytree("getTree").getPersistData();
+ *
+ * @alias Fancytree#getPersistData
+ * @requires jquery.fancytree.persist.js
+ */
+$.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){
+ var local = this.ext.persist,
+ prefix = local.cookiePrefix,
+ delim = local.cookieDelimiter,
+ res = {};
+
+ res[ACTIVE] = local._data(prefix + ACTIVE);
+ res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
+ res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
+ res[FOCUS] = local._data(prefix + FOCUS);
+ return res;
+};
+
+
+/* *****************************************************************************
+ * Extension code
+ */
+$.ui.fancytree.registerExtension({
+ name: "persist",
+ version: "0.3.0",
+ // Default options for this extension.
+ options: {
+ cookieDelimiter: "~",
+ cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
+ cookie: {
+ raw: false,
+ expires: "",
+ path: "",
+ domain: "",
+ secure: false
+ },
+ expandLazy: false, // true: recursively expand and load lazy nodes
+ overrideSource: false, // true: cookie takes precedence over `source` data attributes.
+ store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
+ types: "active expanded focus selected"
+ },
+
+ /* Generic read/write string data to cookie, sessionStorage or localStorage. */
+ _data: function(key, value){
+ var ls = this._local.localStorage; // null, sessionStorage, or localStorage
+
+ if( value === undefined ) {
+ return ls ? ls.getItem(key) : $.cookie(key);
+ } else if ( value === null ) {
+ if( ls ) {
+ ls.removeItem(key);
+ } else {
+ $.removeCookie(key);
+ }
+ } else {
+ if( ls ) {
+ ls.setItem(key, value);
+ } else {
+ $.cookie(key, value, this.options.persist.cookie);
+ }
+ }
+ },
+
+ /* Append `key` to a cookie. */
+ _appendKey: function(type, key, flag){
+ key = "" + key; // #90
+ var local = this._local,
+ instOpts = this.options.persist,
+ delim = instOpts.cookieDelimiter,
+ cookieName = local.cookiePrefix + type,
+ data = local._data(cookieName),
+ keyList = data ? data.split(delim) : [],
+ idx = $.inArray(key, keyList);
+ // Remove, even if we add a key, so the key is always the last entry
+ if(idx >= 0){
+ keyList.splice(idx, 1);
+ }
+ // Append key to cookie
+ if(flag){
+ keyList.push(key);
+ }
+ local._data(cookieName, keyList.join(delim));
+ },
+
+ treeInit: function(ctx){
+ var tree = ctx.tree,
+ opts = ctx.options,
+ local = this._local,
+ instOpts = this.options.persist;
+
+ // For 'auto' or 'cookie' mode, the cookie plugin must be available
+ _assert(instOpts.store === "localStore" || $.cookie, "Missing required plugin for 'persist' extension: jquery.cookie.js");
+
+ local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-");
+ local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
+ local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
+ local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
+ local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
+ if( instOpts.store === "cookie" || !window.localStorage ) {
+ local.localStorage = null;
+ } else {
+ local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage;
+ }
+
+ // Bind init-handler to apply cookie state
+ tree.$div.bind("fancytreeinit", function(event){
+ var cookie, dfd, i, keyList, node,
+ prevFocus = $.cookie(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it;
+
+ tree.debug("COOKIE " + document.cookie);
+
+ cookie = local._data(local.cookiePrefix + EXPANDED);
+ keyList = cookie && cookie.split(instOpts.cookieDelimiter);
+
+ if( local.storeExpanded ) {
+ // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
+ // Also remove expand-cookies for unmatched nodes
+ dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null);
+ } else {
+ // nothing to do
+ dfd = new $.Deferred().resolve();
+ }
+
+ dfd.done(function(){
+ if(local.storeSelected){
+ cookie = local._data(local.cookiePrefix + SELECTED);
+ if(cookie){
+ keyList = cookie.split(instOpts.cookieDelimiter);
+ for(i=0; i<keyList.length; i++){
+ node = tree.getNodeByKey(keyList[i]);
+ if(node){
+ if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){
+ // node.setSelected();
+ node.selected = true;
+ node.renderStatus();
+ }
+ }else{
+ // node is no longer member of the tree: remove from cookie also
+ local._appendKey(SELECTED, keyList[i], false);
+ }
+ }
+ }
+ }
+ if(local.storeActive){
+ cookie = local._data(local.cookiePrefix + ACTIVE);
+ if(cookie && (opts.persist.overrideSource || !tree.activeNode)){
+ node = tree.getNodeByKey(cookie);
+ if(node){
+ node.setActive();
+ }
+ }
+ }
+ if(local.storeFocus && prevFocus){
+ node = tree.getNodeByKey(prevFocus);
+ if(node){
+ node.setFocus();
+ }
+ }
+ });
+ });
+ // Init the tree
+ return this._super(ctx);
+ },
+ nodeSetActive: function(ctx, flag, opts) {
+ var res,
+ local = this._local;
+
+ flag = (flag !== false);
+ res = this._super(ctx, flag, opts);
+
+ if(local.storeActive){
+ local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null);
+ }
+ return res;
+ },
+ nodeSetExpanded: function(ctx, flag, opts) {
+ var res,
+ node = ctx.node,
+ local = this._local;
+
+ flag = (flag !== false);
+ res = this._super(ctx, flag, opts);
+
+ if(local.storeExpanded){
+ local._appendKey(EXPANDED, node.key, flag);
+ }
+ return res;
+ },
+ nodeSetFocus: function(ctx, flag) {
+ var res,
+ local = this._local;
+
+ flag = (flag !== false);
+ res = this._super(ctx, flag);
+
+ if(flag && local.storeFocus){
+ local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null);
+ }
+ return res;
+ },
+ nodeSetSelected: function(ctx, flag) {
+ var res,
+ node = ctx.node,
+ local = this._local;
+
+ flag = (flag !== false);
+ res = this._super(ctx, flag);
+
+ if(local.storeSelected){
+ local._appendKey(SELECTED, node.key, flag);
+ }
+ return res;
+ }
+});
+}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.table.js
+ *
+ * Render tree as table (aka 'treegrid', 'tabletree').
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+/* *****************************************************************************
+ * Private functions and variables
+ */
+function _assert(cond, msg){
+ msg = msg || "";
+ if(!cond){
+ $.error("Assertion failed " + msg);
+ }
+}
+
+function insertSiblingAfter(referenceNode, newNode) {
+ referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
+}
+
+/* Show/hide all rows that are structural descendants of `parent`. */
+function setChildRowVisibility(parent, flag) {
+ parent.visit(function(node){
+ var tr = node.tr;
+ // currentFlag = node.hide ? false : flag; // fix for ext-filter
+ if(tr){
+ tr.style.display = (node.hide || !flag) ? "none" : "";
+ }
+ if(!node.expanded){
+ return "skip";
+ }
+ });
+}
+
+/* Find node that is rendered in previous row. */
+function findPrevRowNode(node){
+ var i, last, prev,
+ parent = node.parent,
+ siblings = parent ? parent.children : null;
+
+ if(siblings && siblings.length > 1 && siblings[0] !== node){
+ // use the lowest descendant of the preceeding sibling
+ i = $.inArray(node, siblings);
+ prev = siblings[i - 1];
+ _assert(prev.tr);
+ // descend to lowest child (with a <tr> tag)
+ while(prev.children){
+ last = prev.children[prev.children.length - 1];
+ if(!last.tr){
+ break;
+ }
+ prev = last;
+ }
+ }else{
+ // if there is no preceding sibling, use the direct parent
+ prev = parent;
+ }
+ return prev;
+}
+
+
+$.ui.fancytree.registerExtension({
+ name: "table",
+ version: "0.2.0",
+ // Default options for this extension.
+ options: {
+ checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
+ customStatus: false, // true: generate renderColumns events for status nodes
+ indentation: 16, // indent every node level by 16px
+ nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0)
+ },
+ // Overide virtual methods for this extension.
+ // `this` : is this extension object
+ // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
+ treeInit: function(ctx){
+ var i, $row, tdRole,
+ tree = ctx.tree,
+ $table = tree.widget.element;
+
+ $table.addClass("fancytree-container fancytree-ext-table");
+ tree.tbody = $table.find("> tbody")[0];
+ tree.columnCount = $("thead >tr >th", $table).length;
+ $(tree.tbody).empty();
+
+ tree.rowFragment = document.createDocumentFragment();
+ $row = $("<tr />");
+ tdRole = "";
+ if(ctx.options.aria){
+ $row.attr("role", "row");
+ tdRole = " role='gridcell'";
+ }
+ for(i=0; i<tree.columnCount; i++) {
+ if(ctx.options.table.nodeColumnIdx === i){
+ $row.append("<td" + tdRole + "><span class='fancytree-node' /></td>");
+ }else{
+ $row.append("<td" + tdRole + " />");
+ }
+ }
+ tree.rowFragment.appendChild($row.get(0));
+
+ // Make sure that status classes are set on the node's <tr> elements
+ tree.statusClassPropName = "tr";
+ tree.ariaPropName = "tr";
+ this.nodeContainerAttrName = "tr";
+
this._super(ctx);
+
+ // standard Fancytree created a root UL
+ $(tree.rootNode.ul).remove();
+ tree.rootNode.ul = null;
+ tree.$container = $table;
+ // Add container to the TAB chain
+ this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
+ if(this.options.aria){
+ tree.$container
+ .attr("role", "treegrid")
+ .attr("aria-readonly", true);
+ }
+ },
+ /* Called by nodeRender to sync node order with tag order.*/
+// nodeFixOrder: function(ctx) {
+// },
+ nodeRemoveChildMarkup: function(ctx) {
+ var node = ctx.node;
+// DT.debug("nodeRemoveChildMarkup()", node.toString());
+ node.visit(function(n){
+ if(n.tr){
+ $(n.tr).remove();
+ n.tr = null;
+ }
+ });
+ },
+ nodeRemoveMarkup: function(ctx) {
+ var node = ctx.node;
+// DT.debug("nodeRemoveMarkup()", node.toString());
+ if(node.tr){
+ $(node.tr).remove();
+ node.tr = null;
+ }
+ this.nodeRemoveChildMarkup(ctx);
+ },
+ /* Override standard render. */
+ nodeRender: function(ctx, force, deep, collapsed, _recursive) {
+ var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx,
+ tree = ctx.tree,
+ node = ctx.node,
+ opts = ctx.options,
+ isRootNode = !node.parent;
+
+ if( !_recursive ){
+ ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
+ }
+ // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
+ if( !isRootNode ){
+ if(!node.tr){
+ if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) {
+ // #166: we assume that the parent will be (recursively) rendered
+ // later anyway.
+ node.debug("nodeRender ignored due to unrendered parent");
+ return;
+ }
+ // Create new <tr> after previous row
+ newRow = tree.rowFragment.firstChild.cloneNode(true);
+ prevNode = findPrevRowNode(node);
+ // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
+ _assert(prevNode);
+ if(collapsed === true && _recursive){
+ // hide all child rows, so we can use an animation to show it later
+ newRow.style.display = "none";
+ }else if(deep && ctx.hasCollapsedParents){
+ // also hide this row if deep === true but any parent is collapsed
+ newRow.style.display = "none";
+// newRow.style.color = "red";
+ }
+ if(!prevNode.tr){
+ _assert(!prevNode.parent, "prev. row must have a tr, or is system root");
+ tree.tbody.appendChild(newRow);
+ }else{
+ insertSiblingAfter(prevNode.tr, newRow);
+ }
+ node.tr = newRow;
+ if( node.key && opts.generateIds ){
+ node.tr.id = opts.idPrefix + node.key;
+ }
+ node.tr.ftnode = node;
+ if(opts.aria){
+ // TODO: why doesn't this work:
+// node.li.role = "treeitem";
+ $(node.tr).attr("aria-labelledby", "ftal_" + node.key);
+ }
+ node.span = $("span.fancytree-node", node.tr).get(0);
+ // Set icon, link, and title (normally this is only required on initial render)
+ this.nodeRenderTitle(ctx);
+ // Allow tweaking, binding, after node was created for the first time
+// tree._triggerNodeEvent("createNode", ctx);
+ if ( opts.createNode ){
+ opts.createNode.call(tree, {type: "createNode"}, ctx);
+ }
+ } else {
+ if( force ) {
+ // Set icon, link, and title (normally this is only required on initial render)
+ this.nodeRenderTitle(ctx); // triggers renderColumns()
+ } else {
+ // Update element classes according to node state
+ this.nodeRenderStatus(ctx);
+ }
+ }
+ }
+ // Allow tweaking after node state was rendered
+// tree._triggerNodeEvent("renderNode", ctx);
+ if ( opts.renderNode ){
+ opts.renderNode.call(tree, {type: "renderNode"}, ctx);
+ }
+ // Visit child nodes
+ // Add child markup
+ children = node.children;
+ if(children && (isRootNode || deep || node.expanded)){
+ for(i=0, l=children.length; i<l; i++) {
+ subCtx = $.extend({}, ctx, {node: children[i]});
+ subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded;
+ this.nodeRender(subCtx, force, deep, collapsed, true);
+ }
+ }
+ // Make sure, that <tr> order matches node.children order.
+ if(children && !_recursive){ // we only have to do it once, for the root branch
+ prevTr = node.tr || null;
+ firstTr = tree.tbody.firstChild;
+ // Iterate over all descendants
+ node.visit(function(n){
+ if(n.tr){
+ if(!n.parent.expanded && n.tr.style.display !== "none"){
+ // fix after a node was dropped over a collapsed
+ n.tr.style.display = "none";
+ setChildRowVisibility(n, false);
+ }
+ if(n.tr.previousSibling !== prevTr){
+ node.debug("_fixOrder: mismatch at node: " + n);
+ var nextTr = prevTr ? prevTr.nextSibling : firstTr;
+ tree.tbody.insertBefore(n.tr, nextTr);
+ }
+ prevTr = n.tr;
+ }
+ });
+ }
+ // Update element classes according to node state
+ // if(!isRootNode){
+ // this.nodeRenderStatus(ctx);
+ // }
+ },
+ nodeRenderTitle: function(ctx, title) {
+ var $cb,
+ node = ctx.node,
+ opts = ctx.options;
+
+ this._super(ctx);
+ // Move checkbox to custom column
+ if(opts.checkbox && opts.table.checkboxColumnIdx != null ){
+ $cb = $("span.fancytree-checkbox", node.span).detach();
+ $(node.tr).find("td:first").html($cb);
+ }
+ // Let user code write column content
+ // ctx.tree._triggerNodeEvent("renderColumns", node);
+ // Update element classes according to node state
+ if( ! node.isRoot() ){
+ this.nodeRenderStatus(ctx);
+ }
+ if( !opts.table.customStatus && node.isStatusNode() ) {
+ // default rendering for status node: leave other cells empty
+ } else if ( opts.renderColumns ) {
+ opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx);
+ }
+ },
+ nodeRenderStatus: function(ctx) {
+ var indent,
+ node = ctx.node,
+ opts = ctx.options;
+
+ this._super(ctx);
+
+ $(node.tr).removeClass("fancytree-node");
+ // indent
+ indent = (node.getLevel() - 1) * opts.table.indentation;
+ $(node.span).css({marginLeft: indent + "px"});
+ },
+ /* Expand node, return Deferred.promise. */
+ nodeSetExpanded: function(ctx, flag, opts) {
+ var dfd = new $.Deferred(),
+ subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true});
+
+ opts = opts || {};
+
+ function _afterExpand(ok) {
+ flag = (flag !== false);
+ setChildRowVisibility(ctx.node, flag);
+ if( ok ) {
+ if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) {
+ // Scroll down to last child, but keep current node visible
+ ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){
+ if( !opts.noEvents ) {
+ ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
+ }
+ dfd.resolveWith(ctx.node);
+ });
+ } else {
+ if( !opts.noEvents ) {
+ ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
+ }
+ dfd.resolveWith(ctx.node);
+ }
+ } else {
+ if( !opts.noEvents ) {
+ ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
+ }
+ dfd.rejectWith(ctx.node);
+ }
+ }
+ // Call base-expand with disabled events and animation
+ this._super(ctx, flag, subOpts).done(function () {
+ _afterExpand(true);
+ }).fail(function () {
+ _afterExpand(false);
+ });
+ return dfd.promise();
+ },
+ nodeSetStatus: function(ctx, status, message, details) {
+ if(status === "ok"){
+ var node = ctx.node,
+ firstChild = ( node.children ? node.children[0] : null );
+ if ( firstChild && firstChild.isStatusNode() ) {
+ $(firstChild.tr).remove();
+ }
+ }
+ this._super(ctx, status, message, details);
+ },
+ treeClear: function(ctx) {
+ this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
+ return this._super(ctx);
}
+ /*,
+ treeSetFocus: function(ctx, flag) {
+// alert("treeSetFocus" + ctx.tree.$container);
+ ctx.tree.$container.focus();
+ $.ui.fancytree.focusTree = ctx.tree;
+ }*/
});
}(jQuery, window, document));
+
+/*!
+ * jquery.fancytree.themeroller.js
+ *
+ * Enable jQuery UI ThemeRoller styles.
+ * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
+ *
+ * @see http://jqueryui.com/themeroller/
+ *
+ * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
+ *
+ * Released under the MIT license
+ * https://github.com/mar10/fancytree/wiki/LicenseInfo
+ *
+ * @version 2.1.0
+ * @date 2014-05-29T16:44
+ */
+
+;(function($, window, document, undefined) {
+
+"use strict";
+
+/*******************************************************************************
+ * Extension code
+ */
+$.ui.fancytree.registerExtension({
+ name: "themeroller",
+ version: "0.0.1",
+ // Default options for this extension.
+ options: {
+ activeClass: "ui-state-active",
+ foccusClass: "ui-state-focus",
+ hoverClass: "ui-state-hover",
+ selectedClass: "ui-state-highlight"
+ },
+
+ treeInit: function(ctx){
+ this._super(ctx);
+ var $el = ctx.widget.element;
+
+ if($el[0].nodeName === "TABLE"){
+ $el.addClass("ui-widget ui-corner-all");
+ $el.find(">thead tr").addClass("ui-widget-header");
+ $el.find(">tbody").addClass("ui-widget-conent");
+ }else{
+ $el.addClass("ui-widget ui-widget-content ui-corner-all");
+ }
+
+ $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){
+ var node = $.ui.fancytree.getNode(event.target),
+ flag = (event.type === "mouseenter");
+ node.debug("hover: " + flag);
+ $(node.span).toggleClass("ui-state-hover ui-corner-all", flag);
+ });
+ },
+ treeDestroy: function(ctx){
+ this._super(ctx);
+ ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all");
+ },
+ nodeRenderStatus: function(ctx){
+ var node = ctx.node,
+ $el = $(node.span);
+ this._super(ctx);
+/*
+ .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
+ .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
+ .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
+
+ .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
+ .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
+ .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
+ .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
+*/
+ $el.toggleClass("ui-state-active", node.isActive());
+ $el.toggleClass("ui-state-focus", node.hasFocus());
+ $el.toggleClass("ui-state-highlight", node.isSelected());
+// node.debug("ext-themeroller.nodeRenderStatus: ", node.span.className);
+ }
+});
+}(jQuery, window, document));
+
+
(function($) {
window.NestedFormEvents = function() {
this.addFields = $.proxy(this.addFields, this);
this.removeFields = $.proxy(this.removeFields, this);
};
@@ -37989,10049 +44181,18 @@
// Integrate with Underscore.js if defined
// or create our own underscore object.
root._ = root._ || {};
root._.string = root._.str = _s;
}(this, String);
-/**
- * @license wysihtml5 v0.3.0
- * https://github.com/xing/wysihtml5
- *
- * Author: Christopher Blum (https://github.com/tiff)
- *
- * Copyright (C) 2012 XING AG
- * Licensed under the MIT license (MIT)
- *
- */
+/*! bootstrap3-wysihtml5-bower 2014-05-19 */
-var wysihtml5 = {
- version: "0.3.0",
-
- // namespaces
- commands: {},
- dom: {},
- quirks: {},
- toolbar: {},
- lang: {},
- selection: {},
- views: {},
-
- INVISIBLE_SPACE: "\uFEFF",
-
- EMPTY_FUNCTION: function() {},
-
- ELEMENT_NODE: 1,
- TEXT_NODE: 3,
-
- BACKSPACE_KEY: 8,
- ENTER_KEY: 13,
- ESCAPE_KEY: 27,
- SPACE_KEY: 32,
- DELETE_KEY: 46
-};/**
- * @license Rangy, a cross-browser JavaScript range and selection library
- * http://code.google.com/p/rangy/
- *
- * Copyright 2011, Tim Down
- * Licensed under the MIT license.
- * Version: 1.2.2
- * Build date: 13 November 2011
- */
-window['rangy'] = (function() {
-
-
- var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
-
- var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
- "commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"];
-
- var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
- "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
- "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
-
- var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
-
- // Subset of TextRange's full set of methods that we're interested in
- var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark",
- "moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"];
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Trio of functions taken from Peter Michaux's article:
- // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
- function isHostMethod(o, p) {
- var t = typeof o[p];
- return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
- }
-
- function isHostObject(o, p) {
- return !!(typeof o[p] == OBJECT && o[p]);
- }
-
- function isHostProperty(o, p) {
- return typeof o[p] != UNDEFINED;
- }
-
- // Creates a convenience function to save verbose repeated calls to tests functions
- function createMultiplePropertyTest(testFunc) {
- return function(o, props) {
- var i = props.length;
- while (i--) {
- if (!testFunc(o, props[i])) {
- return false;
- }
- }
- return true;
- };
- }
-
- // Next trio of functions are a convenience to save verbose repeated calls to previous two functions
- var areHostMethods = createMultiplePropertyTest(isHostMethod);
- var areHostObjects = createMultiplePropertyTest(isHostObject);
- var areHostProperties = createMultiplePropertyTest(isHostProperty);
-
- function isTextRange(range) {
- return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
- }
-
- var api = {
- version: "1.2.2",
- initialized: false,
- supported: true,
-
- util: {
- isHostMethod: isHostMethod,
- isHostObject: isHostObject,
- isHostProperty: isHostProperty,
- areHostMethods: areHostMethods,
- areHostObjects: areHostObjects,
- areHostProperties: areHostProperties,
- isTextRange: isTextRange
- },
-
- features: {},
-
- modules: {},
- config: {
- alertOnWarn: false,
- preferTextRange: false
- }
- };
-
- function fail(reason) {
- window.alert("Rangy not supported in your browser. Reason: " + reason);
- api.initialized = true;
- api.supported = false;
- }
-
- api.fail = fail;
-
- function warn(msg) {
- var warningMessage = "Rangy warning: " + msg;
- if (api.config.alertOnWarn) {
- window.alert(warningMessage);
- } else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) {
- window.console.log(warningMessage);
- }
- }
-
- api.warn = warn;
-
- if ({}.hasOwnProperty) {
- api.util.extend = function(o, props) {
- for (var i in props) {
- if (props.hasOwnProperty(i)) {
- o[i] = props[i];
- }
- }
- };
- } else {
- fail("hasOwnProperty not supported");
- }
-
- var initListeners = [];
- var moduleInitializers = [];
-
- // Initialization
- function init() {
- if (api.initialized) {
- return;
- }
- var testRange;
- var implementsDomRange = false, implementsTextRange = false;
-
- // First, perform basic feature tests
-
- if (isHostMethod(document, "createRange")) {
- testRange = document.createRange();
- if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
- implementsDomRange = true;
- }
- testRange.detach();
- }
-
- var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0];
-
- if (body && isHostMethod(body, "createTextRange")) {
- testRange = body.createTextRange();
- if (isTextRange(testRange)) {
- implementsTextRange = true;
- }
- }
-
- if (!implementsDomRange && !implementsTextRange) {
- fail("Neither Range nor TextRange are implemented");
- }
-
- api.initialized = true;
- api.features = {
- implementsDomRange: implementsDomRange,
- implementsTextRange: implementsTextRange
- };
-
- // Initialize modules and call init listeners
- var allListeners = moduleInitializers.concat(initListeners);
- for (var i = 0, len = allListeners.length; i < len; ++i) {
- try {
- allListeners[i](api);
- } catch (ex) {
- if (isHostObject(window, "console") && isHostMethod(window.console, "log")) {
- window.console.log("Init listener threw an exception. Continuing.", ex);
- }
-
- }
- }
- }
-
- // Allow external scripts to initialize this library in case it's loaded after the document has loaded
- api.init = init;
-
- // Execute listener immediately if already initialized
- api.addInitListener = function(listener) {
- if (api.initialized) {
- listener(api);
- } else {
- initListeners.push(listener);
- }
- };
-
- var createMissingNativeApiListeners = [];
-
- api.addCreateMissingNativeApiListener = function(listener) {
- createMissingNativeApiListeners.push(listener);
- };
-
- function createMissingNativeApi(win) {
- win = win || window;
- init();
-
- // Notify listeners
- for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) {
- createMissingNativeApiListeners[i](win);
- }
- }
-
- api.createMissingNativeApi = createMissingNativeApi;
-
- /**
- * @constructor
- */
- function Module(name) {
- this.name = name;
- this.initialized = false;
- this.supported = false;
- }
-
- Module.prototype.fail = function(reason) {
- this.initialized = true;
- this.supported = false;
-
- throw new Error("Module '" + this.name + "' failed to load: " + reason);
- };
-
- Module.prototype.warn = function(msg) {
- api.warn("Module " + this.name + ": " + msg);
- };
-
- Module.prototype.createError = function(msg) {
- return new Error("Error in Rangy " + this.name + " module: " + msg);
- };
-
- api.createModule = function(name, initFunc) {
- var module = new Module(name);
- api.modules[name] = module;
-
- moduleInitializers.push(function(api) {
- initFunc(api, module);
- module.initialized = true;
- module.supported = true;
- });
- };
-
- api.requireModules = function(modules) {
- for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) {
- moduleName = modules[i];
- module = api.modules[moduleName];
- if (!module || !(module instanceof Module)) {
- throw new Error("Module '" + moduleName + "' not found");
- }
- if (!module.supported) {
- throw new Error("Module '" + moduleName + "' not supported");
- }
- }
- };
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Wait for document to load before running tests
-
- var docReady = false;
-
- var loadHandler = function(e) {
-
- if (!docReady) {
- docReady = true;
- if (!api.initialized) {
- init();
- }
- }
- };
-
- // Test whether we have window and document objects that we will need
- if (typeof window == UNDEFINED) {
- fail("No window found");
- return;
- }
- if (typeof document == UNDEFINED) {
- fail("No document found");
- return;
- }
-
- if (isHostMethod(document, "addEventListener")) {
- document.addEventListener("DOMContentLoaded", loadHandler, false);
- }
-
- // Add a fallback in case the DOMContentLoaded event isn't supported
- if (isHostMethod(window, "addEventListener")) {
- window.addEventListener("load", loadHandler, false);
- } else if (isHostMethod(window, "attachEvent")) {
- window.attachEvent("onload", loadHandler);
- } else {
- fail("Window does not have required addEventListener or attachEvent method");
- }
-
- return api;
-})();
-rangy.createModule("DomUtil", function(api, module) {
-
- var UNDEF = "undefined";
- var util = api.util;
-
- // Perform feature tests
- if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
- module.fail("document missing a Node creation method");
- }
-
- if (!util.isHostMethod(document, "getElementsByTagName")) {
- module.fail("document missing getElementsByTagName method");
- }
-
- var el = document.createElement("div");
- if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
- !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
- module.fail("Incomplete Element implementation");
- }
-
- // innerHTML is required for Range's createContextualFragment method
- if (!util.isHostProperty(el, "innerHTML")) {
- module.fail("Element is missing innerHTML property");
- }
-
- var textNode = document.createTextNode("test");
- if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
- !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
- !util.areHostProperties(textNode, ["data"]))) {
- module.fail("Incomplete Text Node implementation");
- }
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
- // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
- // contains just the document as a single element and the value searched for is the document.
- var arrayContains = /*Array.prototype.indexOf ?
- function(arr, val) {
- return arr.indexOf(val) > -1;
- }:*/
-
- function(arr, val) {
- var i = arr.length;
- while (i--) {
- if (arr[i] === val) {
- return true;
- }
- }
- return false;
- };
-
- // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
- function isHtmlNamespace(node) {
- var ns;
- return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
- }
-
- function parentElement(node) {
- var parent = node.parentNode;
- return (parent.nodeType == 1) ? parent : null;
- }
-
- function getNodeIndex(node) {
- var i = 0;
- while( (node = node.previousSibling) ) {
- i++;
- }
- return i;
- }
-
- function getNodeLength(node) {
- var childNodes;
- return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0);
- }
-
- function getCommonAncestor(node1, node2) {
- var ancestors = [], n;
- for (n = node1; n; n = n.parentNode) {
- ancestors.push(n);
- }
-
- for (n = node2; n; n = n.parentNode) {
- if (arrayContains(ancestors, n)) {
- return n;
- }
- }
-
- return null;
- }
-
- function isAncestorOf(ancestor, descendant, selfIsAncestor) {
- var n = selfIsAncestor ? descendant : descendant.parentNode;
- while (n) {
- if (n === ancestor) {
- return true;
- } else {
- n = n.parentNode;
- }
- }
- return false;
- }
-
- function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
- var p, n = selfIsAncestor ? node : node.parentNode;
- while (n) {
- p = n.parentNode;
- if (p === ancestor) {
- return n;
- }
- n = p;
- }
- return null;
- }
-
- function isCharacterDataNode(node) {
- var t = node.nodeType;
- return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
- }
-
- function insertAfter(node, precedingNode) {
- var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
- if (nextNode) {
- parent.insertBefore(node, nextNode);
- } else {
- parent.appendChild(node);
- }
- return node;
- }
-
- // Note that we cannot use splitText() because it is bugridden in IE 9.
- function splitDataNode(node, index) {
- var newNode = node.cloneNode(false);
- newNode.deleteData(0, index);
- node.deleteData(index, node.length - index);
- insertAfter(newNode, node);
- return newNode;
- }
-
- function getDocument(node) {
- if (node.nodeType == 9) {
- return node;
- } else if (typeof node.ownerDocument != UNDEF) {
- return node.ownerDocument;
- } else if (typeof node.document != UNDEF) {
- return node.document;
- } else if (node.parentNode) {
- return getDocument(node.parentNode);
- } else {
- throw new Error("getDocument: no document found for node");
- }
- }
-
- function getWindow(node) {
- var doc = getDocument(node);
- if (typeof doc.defaultView != UNDEF) {
- return doc.defaultView;
- } else if (typeof doc.parentWindow != UNDEF) {
- return doc.parentWindow;
- } else {
- throw new Error("Cannot get a window object for node");
- }
- }
-
- function getIframeDocument(iframeEl) {
- if (typeof iframeEl.contentDocument != UNDEF) {
- return iframeEl.contentDocument;
- } else if (typeof iframeEl.contentWindow != UNDEF) {
- return iframeEl.contentWindow.document;
- } else {
- throw new Error("getIframeWindow: No Document object found for iframe element");
- }
- }
-
- function getIframeWindow(iframeEl) {
- if (typeof iframeEl.contentWindow != UNDEF) {
- return iframeEl.contentWindow;
- } else if (typeof iframeEl.contentDocument != UNDEF) {
- return iframeEl.contentDocument.defaultView;
- } else {
- throw new Error("getIframeWindow: No Window object found for iframe element");
- }
- }
-
- function getBody(doc) {
- return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
- }
-
- function getRootContainer(node) {
- var parent;
- while ( (parent = node.parentNode) ) {
- node = parent;
- }
- return node;
- }
-
- function comparePoints(nodeA, offsetA, nodeB, offsetB) {
- // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
- var nodeC, root, childA, childB, n;
- if (nodeA == nodeB) {
-
- // Case 1: nodes are the same
- return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
- } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
-
- // Case 2: node C (container B or an ancestor) is a child node of A
- return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
- } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
-
- // Case 3: node C (container A or an ancestor) is a child node of B
- return getNodeIndex(nodeC) < offsetB ? -1 : 1;
- } else {
-
- // Case 4: containers are siblings or descendants of siblings
- root = getCommonAncestor(nodeA, nodeB);
- childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
- childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
-
- if (childA === childB) {
- // This shouldn't be possible
-
- throw new Error("comparePoints got to case 4 and childA and childB are the same!");
- } else {
- n = root.firstChild;
- while (n) {
- if (n === childA) {
- return -1;
- } else if (n === childB) {
- return 1;
- }
- n = n.nextSibling;
- }
- throw new Error("Should not be here!");
- }
- }
- }
-
- function fragmentFromNodeChildren(node) {
- var fragment = getDocument(node).createDocumentFragment(), child;
- while ( (child = node.firstChild) ) {
- fragment.appendChild(child);
- }
- return fragment;
- }
-
- function inspectNode(node) {
- if (!node) {
- return "[No node]";
- }
- if (isCharacterDataNode(node)) {
- return '"' + node.data + '"';
- } else if (node.nodeType == 1) {
- var idAttr = node.id ? ' id="' + node.id + '"' : "";
- return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]";
- } else {
- return node.nodeName;
- }
- }
-
- /**
- * @constructor
- */
- function NodeIterator(root) {
- this.root = root;
- this._next = root;
- }
-
- NodeIterator.prototype = {
- _current: null,
-
- hasNext: function() {
- return !!this._next;
- },
-
- next: function() {
- var n = this._current = this._next;
- var child, next;
- if (this._current) {
- child = n.firstChild;
- if (child) {
- this._next = child;
- } else {
- next = null;
- while ((n !== this.root) && !(next = n.nextSibling)) {
- n = n.parentNode;
- }
- this._next = next;
- }
- }
- return this._current;
- },
-
- detach: function() {
- this._current = this._next = this.root = null;
- }
- };
-
- function createIterator(root) {
- return new NodeIterator(root);
- }
-
- /**
- * @constructor
- */
- function DomPosition(node, offset) {
- this.node = node;
- this.offset = offset;
- }
-
- DomPosition.prototype = {
- equals: function(pos) {
- return this.node === pos.node & this.offset == pos.offset;
- },
-
- inspect: function() {
- return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
- }
- };
-
- /**
- * @constructor
- */
- function DOMException(codeName) {
- this.code = this[codeName];
- this.codeName = codeName;
- this.message = "DOMException: " + this.codeName;
- }
-
- DOMException.prototype = {
- INDEX_SIZE_ERR: 1,
- HIERARCHY_REQUEST_ERR: 3,
- WRONG_DOCUMENT_ERR: 4,
- NO_MODIFICATION_ALLOWED_ERR: 7,
- NOT_FOUND_ERR: 8,
- NOT_SUPPORTED_ERR: 9,
- INVALID_STATE_ERR: 11
- };
-
- DOMException.prototype.toString = function() {
- return this.message;
- };
-
- api.dom = {
- arrayContains: arrayContains,
- isHtmlNamespace: isHtmlNamespace,
- parentElement: parentElement,
- getNodeIndex: getNodeIndex,
- getNodeLength: getNodeLength,
- getCommonAncestor: getCommonAncestor,
- isAncestorOf: isAncestorOf,
- getClosestAncestorIn: getClosestAncestorIn,
- isCharacterDataNode: isCharacterDataNode,
- insertAfter: insertAfter,
- splitDataNode: splitDataNode,
- getDocument: getDocument,
- getWindow: getWindow,
- getIframeWindow: getIframeWindow,
- getIframeDocument: getIframeDocument,
- getBody: getBody,
- getRootContainer: getRootContainer,
- comparePoints: comparePoints,
- inspectNode: inspectNode,
- fragmentFromNodeChildren: fragmentFromNodeChildren,
- createIterator: createIterator,
- DomPosition: DomPosition
- };
-
- api.DOMException = DOMException;
-});rangy.createModule("DomRange", function(api, module) {
- api.requireModules( ["DomUtil"] );
-
-
- var dom = api.dom;
- var DomPosition = dom.DomPosition;
- var DOMException = api.DOMException;
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Utility functions
-
- function isNonTextPartiallySelected(node, range) {
- return (node.nodeType != 3) &&
- (dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true));
- }
-
- function getRangeDocument(range) {
- return dom.getDocument(range.startContainer);
- }
-
- function dispatchEvent(range, type, args) {
- var listeners = range._listeners[type];
- if (listeners) {
- for (var i = 0, len = listeners.length; i < len; ++i) {
- listeners[i].call(range, {target: range, args: args});
- }
- }
- }
-
- function getBoundaryBeforeNode(node) {
- return new DomPosition(node.parentNode, dom.getNodeIndex(node));
- }
-
- function getBoundaryAfterNode(node) {
- return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1);
- }
-
- function insertNodeAtPosition(node, n, o) {
- var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
- if (dom.isCharacterDataNode(n)) {
- if (o == n.length) {
- dom.insertAfter(node, n);
- } else {
- n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o));
- }
- } else if (o >= n.childNodes.length) {
- n.appendChild(node);
- } else {
- n.insertBefore(node, n.childNodes[o]);
- }
- return firstNodeInserted;
- }
-
- function cloneSubtree(iterator) {
- var partiallySelected;
- for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
- partiallySelected = iterator.isPartiallySelectedSubtree();
-
- node = node.cloneNode(!partiallySelected);
- if (partiallySelected) {
- subIterator = iterator.getSubtreeIterator();
- node.appendChild(cloneSubtree(subIterator));
- subIterator.detach(true);
- }
-
- if (node.nodeType == 10) { // DocumentType
- throw new DOMException("HIERARCHY_REQUEST_ERR");
- }
- frag.appendChild(node);
- }
- return frag;
- }
-
- function iterateSubtree(rangeIterator, func, iteratorState) {
- var it, n;
- iteratorState = iteratorState || { stop: false };
- for (var node, subRangeIterator; node = rangeIterator.next(); ) {
- //log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node));
- if (rangeIterator.isPartiallySelectedSubtree()) {
- // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the
- // node selected by the Range.
- if (func(node) === false) {
- iteratorState.stop = true;
- return;
- } else {
- subRangeIterator = rangeIterator.getSubtreeIterator();
- iterateSubtree(subRangeIterator, func, iteratorState);
- subRangeIterator.detach(true);
- if (iteratorState.stop) {
- return;
- }
- }
- } else {
- // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
- // descendant
- it = dom.createIterator(node);
- while ( (n = it.next()) ) {
- if (func(n) === false) {
- iteratorState.stop = true;
- return;
- }
- }
- }
- }
- }
-
- function deleteSubtree(iterator) {
- var subIterator;
- while (iterator.next()) {
- if (iterator.isPartiallySelectedSubtree()) {
- subIterator = iterator.getSubtreeIterator();
- deleteSubtree(subIterator);
- subIterator.detach(true);
- } else {
- iterator.remove();
- }
- }
- }
-
- function extractSubtree(iterator) {
-
- for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
-
-
- if (iterator.isPartiallySelectedSubtree()) {
- node = node.cloneNode(false);
- subIterator = iterator.getSubtreeIterator();
- node.appendChild(extractSubtree(subIterator));
- subIterator.detach(true);
- } else {
- iterator.remove();
- }
- if (node.nodeType == 10) { // DocumentType
- throw new DOMException("HIERARCHY_REQUEST_ERR");
- }
- frag.appendChild(node);
- }
- return frag;
- }
-
- function getNodesInRange(range, nodeTypes, filter) {
- //log.info("getNodesInRange, " + nodeTypes.join(","));
- var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
- var filterExists = !!filter;
- if (filterNodeTypes) {
- regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
- }
-
- var nodes = [];
- iterateSubtree(new RangeIterator(range, false), function(node) {
- if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) {
- nodes.push(node);
- }
- });
- return nodes;
- }
-
- function inspect(range) {
- var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
- return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
- dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
- }
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)
-
- /**
- * @constructor
- */
- function RangeIterator(range, clonePartiallySelectedTextNodes) {
- this.range = range;
- this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;
-
-
-
- if (!range.collapsed) {
- this.sc = range.startContainer;
- this.so = range.startOffset;
- this.ec = range.endContainer;
- this.eo = range.endOffset;
- var root = range.commonAncestorContainer;
-
- if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) {
- this.isSingleCharacterDataNode = true;
- this._first = this._last = this._next = this.sc;
- } else {
- this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ?
- this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true);
- this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ?
- this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true);
- }
-
- }
- }
-
- RangeIterator.prototype = {
- _current: null,
- _next: null,
- _first: null,
- _last: null,
- isSingleCharacterDataNode: false,
-
- reset: function() {
- this._current = null;
- this._next = this._first;
- },
-
- hasNext: function() {
- return !!this._next;
- },
-
- next: function() {
- // Move to next node
- var current = this._current = this._next;
- if (current) {
- this._next = (current !== this._last) ? current.nextSibling : null;
-
- // Check for partially selected text nodes
- if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
- if (current === this.ec) {
-
- (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
- }
- if (this._current === this.sc) {
-
- (current = current.cloneNode(true)).deleteData(0, this.so);
- }
- }
- }
-
- return current;
- },
-
- remove: function() {
- var current = this._current, start, end;
-
- if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
- start = (current === this.sc) ? this.so : 0;
- end = (current === this.ec) ? this.eo : current.length;
- if (start != end) {
- current.deleteData(start, end - start);
- }
- } else {
- if (current.parentNode) {
- current.parentNode.removeChild(current);
- } else {
-
- }
- }
- },
-
- // Checks if the current node is partially selected
- isPartiallySelectedSubtree: function() {
- var current = this._current;
- return isNonTextPartiallySelected(current, this.range);
- },
-
- getSubtreeIterator: function() {
- var subRange;
- if (this.isSingleCharacterDataNode) {
- subRange = this.range.cloneRange();
- subRange.collapse();
- } else {
- subRange = new Range(getRangeDocument(this.range));
- var current = this._current;
- var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current);
-
- if (dom.isAncestorOf(current, this.sc, true)) {
- startContainer = this.sc;
- startOffset = this.so;
- }
- if (dom.isAncestorOf(current, this.ec, true)) {
- endContainer = this.ec;
- endOffset = this.eo;
- }
-
- updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
- }
- return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
- },
-
- detach: function(detachRange) {
- if (detachRange) {
- this.range.detach();
- }
- this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
- }
- };
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Exceptions
-
- /**
- * @constructor
- */
- function RangeException(codeName) {
- this.code = this[codeName];
- this.codeName = codeName;
- this.message = "RangeException: " + this.codeName;
- }
-
- RangeException.prototype = {
- BAD_BOUNDARYPOINTS_ERR: 1,
- INVALID_NODE_TYPE_ERR: 2
- };
-
- RangeException.prototype.toString = function() {
- return this.message;
- };
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- /**
- * Currently iterates through all nodes in the range on creation until I think of a decent way to do it
- * TODO: Look into making this a proper iterator, not requiring preloading everything first
- * @constructor
- */
- function RangeNodeIterator(range, nodeTypes, filter) {
- this.nodes = getNodesInRange(range, nodeTypes, filter);
- this._next = this.nodes[0];
- this._position = 0;
- }
-
- RangeNodeIterator.prototype = {
- _current: null,
-
- hasNext: function() {
- return !!this._next;
- },
-
- next: function() {
- this._current = this._next;
- this._next = this.nodes[ ++this._position ];
- return this._current;
- },
-
- detach: function() {
- this._current = this._next = this.nodes = null;
- }
- };
-
- var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
- var rootContainerNodeTypes = [2, 9, 11];
- var readonlyNodeTypes = [5, 6, 10, 12];
- var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
- var surroundNodeTypes = [1, 3, 4, 5, 7, 8];
-
- function createAncestorFinder(nodeTypes) {
- return function(node, selfIsAncestor) {
- var t, n = selfIsAncestor ? node : node.parentNode;
- while (n) {
- t = n.nodeType;
- if (dom.arrayContains(nodeTypes, t)) {
- return n;
- }
- n = n.parentNode;
- }
- return null;
- };
- }
-
- var getRootContainer = dom.getRootContainer;
- var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
- var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
- var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
-
- function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
- if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
- throw new RangeException("INVALID_NODE_TYPE_ERR");
- }
- }
-
- function assertNotDetached(range) {
- if (!range.startContainer) {
- throw new DOMException("INVALID_STATE_ERR");
- }
- }
-
- function assertValidNodeType(node, invalidTypes) {
- if (!dom.arrayContains(invalidTypes, node.nodeType)) {
- throw new RangeException("INVALID_NODE_TYPE_ERR");
- }
- }
-
- function assertValidOffset(node, offset) {
- if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
- throw new DOMException("INDEX_SIZE_ERR");
- }
- }
-
- function assertSameDocumentOrFragment(node1, node2) {
- if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
- throw new DOMException("WRONG_DOCUMENT_ERR");
- }
- }
-
- function assertNodeNotReadOnly(node) {
- if (getReadonlyAncestor(node, true)) {
- throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
- }
- }
-
- function assertNode(node, codeName) {
- if (!node) {
- throw new DOMException(codeName);
- }
- }
-
- function isOrphan(node) {
- return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true);
- }
-
- function isValidOffset(node, offset) {
- return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length);
- }
-
- function assertRangeValid(range) {
- assertNotDetached(range);
- if (isOrphan(range.startContainer) || isOrphan(range.endContainer) ||
- !isValidOffset(range.startContainer, range.startOffset) ||
- !isValidOffset(range.endContainer, range.endOffset)) {
- throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")");
- }
- }
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Test the browser's innerHTML support to decide how to implement createContextualFragment
- var styleEl = document.createElement("style");
- var htmlParsingConforms = false;
- try {
- styleEl.innerHTML = "<b>x</b>";
- htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
- } catch (e) {
- // IE 6 and 7 throw
- }
-
- api.features.htmlParsingConforms = htmlParsingConforms;
-
- var createContextualFragment = htmlParsingConforms ?
-
- // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
- // discussion and base code for this implementation at issue 67.
- // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
- // Thanks to Aleks Williams.
- function(fragmentStr) {
- // "Let node the context object's start's node."
- var node = this.startContainer;
- var doc = dom.getDocument(node);
-
- // "If the context object's start's node is null, raise an INVALID_STATE_ERR
- // exception and abort these steps."
- if (!node) {
- throw new DOMException("INVALID_STATE_ERR");
- }
-
- // "Let element be as follows, depending on node's interface:"
- // Document, Document Fragment: null
- var el = null;
-
- // "Element: node"
- if (node.nodeType == 1) {
- el = node;
-
- // "Text, Comment: node's parentElement"
- } else if (dom.isCharacterDataNode(node)) {
- el = dom.parentElement(node);
- }
-
- // "If either element is null or element's ownerDocument is an HTML document
- // and element's local name is "html" and element's namespace is the HTML
- // namespace"
- if (el === null || (
- el.nodeName == "HTML"
- && dom.isHtmlNamespace(dom.getDocument(el).documentElement)
- && dom.isHtmlNamespace(el)
- )) {
-
- // "let element be a new Element with "body" as its local name and the HTML
- // namespace as its namespace.""
- el = doc.createElement("body");
- } else {
- el = el.cloneNode(false);
- }
-
- // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
- // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
- // "In either case, the algorithm must be invoked with fragment as the input
- // and element as the context element."
- el.innerHTML = fragmentStr;
-
- // "If this raises an exception, then abort these steps. Otherwise, let new
- // children be the nodes returned."
-
- // "Let fragment be a new DocumentFragment."
- // "Append all new children to fragment."
- // "Return fragment."
- return dom.fragmentFromNodeChildren(el);
- } :
-
- // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
- // previous versions of Rangy used (with the exception of using a body element rather than a div)
- function(fragmentStr) {
- assertNotDetached(this);
- var doc = getRangeDocument(this);
- var el = doc.createElement("body");
- el.innerHTML = fragmentStr;
-
- return dom.fragmentFromNodeChildren(el);
- };
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
- "commonAncestorContainer"];
-
- var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
- var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;
-
- function RangePrototype() {}
-
- RangePrototype.prototype = {
- attachListener: function(type, listener) {
- this._listeners[type].push(listener);
- },
-
- compareBoundaryPoints: function(how, range) {
- assertRangeValid(this);
- assertSameDocumentOrFragment(this.startContainer, range.startContainer);
-
- var nodeA, offsetA, nodeB, offsetB;
- var prefixA = (how == e2s || how == s2s) ? "start" : "end";
- var prefixB = (how == s2e || how == s2s) ? "start" : "end";
- nodeA = this[prefixA + "Container"];
- offsetA = this[prefixA + "Offset"];
- nodeB = range[prefixB + "Container"];
- offsetB = range[prefixB + "Offset"];
- return dom.comparePoints(nodeA, offsetA, nodeB, offsetB);
- },
-
- insertNode: function(node) {
- assertRangeValid(this);
- assertValidNodeType(node, insertableNodeTypes);
- assertNodeNotReadOnly(this.startContainer);
-
- if (dom.isAncestorOf(node, this.startContainer, true)) {
- throw new DOMException("HIERARCHY_REQUEST_ERR");
- }
-
- // No check for whether the container of the start of the Range is of a type that does not allow
- // children of the type of node: the browser's DOM implementation should do this for us when we attempt
- // to add the node
-
- var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
- this.setStartBefore(firstNodeInserted);
- },
-
- cloneContents: function() {
- assertRangeValid(this);
-
- var clone, frag;
- if (this.collapsed) {
- return getRangeDocument(this).createDocumentFragment();
- } else {
- if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) {
- clone = this.startContainer.cloneNode(true);
- clone.data = clone.data.slice(this.startOffset, this.endOffset);
- frag = getRangeDocument(this).createDocumentFragment();
- frag.appendChild(clone);
- return frag;
- } else {
- var iterator = new RangeIterator(this, true);
- clone = cloneSubtree(iterator);
- iterator.detach();
- }
- return clone;
- }
- },
-
- canSurroundContents: function() {
- assertRangeValid(this);
- assertNodeNotReadOnly(this.startContainer);
- assertNodeNotReadOnly(this.endContainer);
-
- // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
- // no non-text nodes.
- var iterator = new RangeIterator(this, true);
- var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
- (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
- iterator.detach();
- return !boundariesInvalid;
- },
-
- surroundContents: function(node) {
- assertValidNodeType(node, surroundNodeTypes);
-
- if (!this.canSurroundContents()) {
- throw new RangeException("BAD_BOUNDARYPOINTS_ERR");
- }
-
- // Extract the contents
- var content = this.extractContents();
-
- // Clear the children of the node
- if (node.hasChildNodes()) {
- while (node.lastChild) {
- node.removeChild(node.lastChild);
- }
- }
-
- // Insert the new node and add the extracted contents
- insertNodeAtPosition(node, this.startContainer, this.startOffset);
- node.appendChild(content);
-
- this.selectNode(node);
- },
-
- cloneRange: function() {
- assertRangeValid(this);
- var range = new Range(getRangeDocument(this));
- var i = rangeProperties.length, prop;
- while (i--) {
- prop = rangeProperties[i];
- range[prop] = this[prop];
- }
- return range;
- },
-
- toString: function() {
- assertRangeValid(this);
- var sc = this.startContainer;
- if (sc === this.endContainer && dom.isCharacterDataNode(sc)) {
- return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
- } else {
- var textBits = [], iterator = new RangeIterator(this, true);
-
- iterateSubtree(iterator, function(node) {
- // Accept only text or CDATA nodes, not comments
-
- if (node.nodeType == 3 || node.nodeType == 4) {
- textBits.push(node.data);
- }
- });
- iterator.detach();
- return textBits.join("");
- }
- },
-
- // The methods below are all non-standard. The following batch were introduced by Mozilla but have since
- // been removed from Mozilla.
-
- compareNode: function(node) {
- assertRangeValid(this);
-
- var parent = node.parentNode;
- var nodeIndex = dom.getNodeIndex(node);
-
- if (!parent) {
- throw new DOMException("NOT_FOUND_ERR");
- }
-
- var startComparison = this.comparePoint(parent, nodeIndex),
- endComparison = this.comparePoint(parent, nodeIndex + 1);
-
- if (startComparison < 0) { // Node starts before
- return (endComparison > 0) ? n_b_a : n_b;
- } else {
- return (endComparison > 0) ? n_a : n_i;
- }
- },
-
- comparePoint: function(node, offset) {
- assertRangeValid(this);
- assertNode(node, "HIERARCHY_REQUEST_ERR");
- assertSameDocumentOrFragment(node, this.startContainer);
-
- if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
- return -1;
- } else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
- return 1;
- }
- return 0;
- },
-
- createContextualFragment: createContextualFragment,
-
- toHtml: function() {
- assertRangeValid(this);
- var container = getRangeDocument(this).createElement("div");
- container.appendChild(this.cloneContents());
- return container.innerHTML;
- },
-
- // touchingIsIntersecting determines whether this method considers a node that borders a range intersects
- // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
- intersectsNode: function(node, touchingIsIntersecting) {
- assertRangeValid(this);
- assertNode(node, "NOT_FOUND_ERR");
- if (dom.getDocument(node) !== getRangeDocument(this)) {
- return false;
- }
-
- var parent = node.parentNode, offset = dom.getNodeIndex(node);
- assertNode(parent, "NOT_FOUND_ERR");
-
- var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset),
- endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset);
-
- return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
- },
-
-
- isPointInRange: function(node, offset) {
- assertRangeValid(this);
- assertNode(node, "HIERARCHY_REQUEST_ERR");
- assertSameDocumentOrFragment(node, this.startContainer);
-
- return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
- (dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
- },
-
- // The methods below are non-standard and invented by me.
-
- // Sharing a boundary start-to-end or end-to-start does not count as intersection.
- intersectsRange: function(range, touchingIsIntersecting) {
- assertRangeValid(this);
-
- if (getRangeDocument(range) != getRangeDocument(this)) {
- throw new DOMException("WRONG_DOCUMENT_ERR");
- }
-
- var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset),
- endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset);
-
- return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
- },
-
- intersection: function(range) {
- if (this.intersectsRange(range)) {
- var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
- endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);
-
- var intersectionRange = this.cloneRange();
-
- if (startComparison == -1) {
- intersectionRange.setStart(range.startContainer, range.startOffset);
- }
- if (endComparison == 1) {
- intersectionRange.setEnd(range.endContainer, range.endOffset);
- }
- return intersectionRange;
- }
- return null;
- },
-
- union: function(range) {
- if (this.intersectsRange(range, true)) {
- var unionRange = this.cloneRange();
- if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
- unionRange.setStart(range.startContainer, range.startOffset);
- }
- if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
- unionRange.setEnd(range.endContainer, range.endOffset);
- }
- return unionRange;
- } else {
- throw new RangeException("Ranges do not intersect");
- }
- },
-
- containsNode: function(node, allowPartial) {
- if (allowPartial) {
- return this.intersectsNode(node, false);
- } else {
- return this.compareNode(node) == n_i;
- }
- },
-
- containsNodeContents: function(node) {
- return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0;
- },
-
- containsRange: function(range) {
- return this.intersection(range).equals(range);
- },
-
- containsNodeText: function(node) {
- var nodeRange = this.cloneRange();
- nodeRange.selectNode(node);
- var textNodes = nodeRange.getNodes([3]);
- if (textNodes.length > 0) {
- nodeRange.setStart(textNodes[0], 0);
- var lastTextNode = textNodes.pop();
- nodeRange.setEnd(lastTextNode, lastTextNode.length);
- var contains = this.containsRange(nodeRange);
- nodeRange.detach();
- return contains;
- } else {
- return this.containsNodeContents(node);
- }
- },
-
- createNodeIterator: function(nodeTypes, filter) {
- assertRangeValid(this);
- return new RangeNodeIterator(this, nodeTypes, filter);
- },
-
- getNodes: function(nodeTypes, filter) {
- assertRangeValid(this);
- return getNodesInRange(this, nodeTypes, filter);
- },
-
- getDocument: function() {
- return getRangeDocument(this);
- },
-
- collapseBefore: function(node) {
- assertNotDetached(this);
-
- this.setEndBefore(node);
- this.collapse(false);
- },
-
- collapseAfter: function(node) {
- assertNotDetached(this);
-
- this.setStartAfter(node);
- this.collapse(true);
- },
-
- getName: function() {
- return "DomRange";
- },
-
- equals: function(range) {
- return Range.rangesEqual(this, range);
- },
-
- inspect: function() {
- return inspect(this);
- }
- };
-
- function copyComparisonConstantsToObject(obj) {
- obj.START_TO_START = s2s;
- obj.START_TO_END = s2e;
- obj.END_TO_END = e2e;
- obj.END_TO_START = e2s;
-
- obj.NODE_BEFORE = n_b;
- obj.NODE_AFTER = n_a;
- obj.NODE_BEFORE_AND_AFTER = n_b_a;
- obj.NODE_INSIDE = n_i;
- }
-
- function copyComparisonConstants(constructor) {
- copyComparisonConstantsToObject(constructor);
- copyComparisonConstantsToObject(constructor.prototype);
- }
-
- function createRangeContentRemover(remover, boundaryUpdater) {
- return function() {
- assertRangeValid(this);
-
- var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;
-
- var iterator = new RangeIterator(this, true);
-
- // Work out where to position the range after content removal
- var node, boundary;
- if (sc !== root) {
- node = dom.getClosestAncestorIn(sc, root, true);
- boundary = getBoundaryAfterNode(node);
- sc = boundary.node;
- so = boundary.offset;
- }
-
- // Check none of the range is read-only
- iterateSubtree(iterator, assertNodeNotReadOnly);
-
- iterator.reset();
-
- // Remove the content
- var returnValue = remover(iterator);
- iterator.detach();
-
- // Move to the new position
- boundaryUpdater(this, sc, so, sc, so);
-
- return returnValue;
- };
- }
-
- function createPrototypeRange(constructor, boundaryUpdater, detacher) {
- function createBeforeAfterNodeSetter(isBefore, isStart) {
- return function(node) {
- assertNotDetached(this);
- assertValidNodeType(node, beforeAfterNodeTypes);
- assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);
-
- var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
- (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
- };
- }
-
- function setRangeStart(range, node, offset) {
- var ec = range.endContainer, eo = range.endOffset;
- if (node !== range.startContainer || offset !== range.startOffset) {
- // Check the root containers of the range and the new boundary, and also check whether the new boundary
- // is after the current end. In either case, collapse the range to the new position
- if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) {
- ec = node;
- eo = offset;
- }
- boundaryUpdater(range, node, offset, ec, eo);
- }
- }
-
- function setRangeEnd(range, node, offset) {
- var sc = range.startContainer, so = range.startOffset;
- if (node !== range.endContainer || offset !== range.endOffset) {
- // Check the root containers of the range and the new boundary, and also check whether the new boundary
- // is after the current end. In either case, collapse the range to the new position
- if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) {
- sc = node;
- so = offset;
- }
- boundaryUpdater(range, sc, so, node, offset);
- }
- }
-
- function setRangeStartAndEnd(range, node, offset) {
- if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) {
- boundaryUpdater(range, node, offset, node, offset);
- }
- }
-
- constructor.prototype = new RangePrototype();
-
- api.util.extend(constructor.prototype, {
- setStart: function(node, offset) {
- assertNotDetached(this);
- assertNoDocTypeNotationEntityAncestor(node, true);
- assertValidOffset(node, offset);
-
- setRangeStart(this, node, offset);
- },
-
- setEnd: function(node, offset) {
- assertNotDetached(this);
- assertNoDocTypeNotationEntityAncestor(node, true);
- assertValidOffset(node, offset);
-
- setRangeEnd(this, node, offset);
- },
-
- setStartBefore: createBeforeAfterNodeSetter(true, true),
- setStartAfter: createBeforeAfterNodeSetter(false, true),
- setEndBefore: createBeforeAfterNodeSetter(true, false),
- setEndAfter: createBeforeAfterNodeSetter(false, false),
-
- collapse: function(isStart) {
- assertRangeValid(this);
- if (isStart) {
- boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
- } else {
- boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
- }
- },
-
- selectNodeContents: function(node) {
- // This doesn't seem well specified: the spec talks only about selecting the node's contents, which
- // could be taken to mean only its children. However, browsers implement this the same as selectNode for
- // text nodes, so I shall do likewise
- assertNotDetached(this);
- assertNoDocTypeNotationEntityAncestor(node, true);
-
- boundaryUpdater(this, node, 0, node, dom.getNodeLength(node));
- },
-
- selectNode: function(node) {
- assertNotDetached(this);
- assertNoDocTypeNotationEntityAncestor(node, false);
- assertValidNodeType(node, beforeAfterNodeTypes);
-
- var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
- boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
- },
-
- extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),
-
- deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),
-
- canSurroundContents: function() {
- assertRangeValid(this);
- assertNodeNotReadOnly(this.startContainer);
- assertNodeNotReadOnly(this.endContainer);
-
- // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
- // no non-text nodes.
- var iterator = new RangeIterator(this, true);
- var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
- (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
- iterator.detach();
- return !boundariesInvalid;
- },
-
- detach: function() {
- detacher(this);
- },
-
- splitBoundaries: function() {
- assertRangeValid(this);
-
-
- var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
- var startEndSame = (sc === ec);
-
- if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
- dom.splitDataNode(ec, eo);
-
- }
-
- if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) {
-
- sc = dom.splitDataNode(sc, so);
- if (startEndSame) {
- eo -= so;
- ec = sc;
- } else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) {
- eo++;
- }
- so = 0;
-
- }
- boundaryUpdater(this, sc, so, ec, eo);
- },
-
- normalizeBoundaries: function() {
- assertRangeValid(this);
-
- var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
-
- var mergeForward = function(node) {
- var sibling = node.nextSibling;
- if (sibling && sibling.nodeType == node.nodeType) {
- ec = node;
- eo = node.length;
- node.appendData(sibling.data);
- sibling.parentNode.removeChild(sibling);
- }
- };
-
- var mergeBackward = function(node) {
- var sibling = node.previousSibling;
- if (sibling && sibling.nodeType == node.nodeType) {
- sc = node;
- var nodeLength = node.length;
- so = sibling.length;
- node.insertData(0, sibling.data);
- sibling.parentNode.removeChild(sibling);
- if (sc == ec) {
- eo += so;
- ec = sc;
- } else if (ec == node.parentNode) {
- var nodeIndex = dom.getNodeIndex(node);
- if (eo == nodeIndex) {
- ec = node;
- eo = nodeLength;
- } else if (eo > nodeIndex) {
- eo--;
- }
- }
- }
- };
-
- var normalizeStart = true;
-
- if (dom.isCharacterDataNode(ec)) {
- if (ec.length == eo) {
- mergeForward(ec);
- }
- } else {
- if (eo > 0) {
- var endNode = ec.childNodes[eo - 1];
- if (endNode && dom.isCharacterDataNode(endNode)) {
- mergeForward(endNode);
- }
- }
- normalizeStart = !this.collapsed;
- }
-
- if (normalizeStart) {
- if (dom.isCharacterDataNode(sc)) {
- if (so == 0) {
- mergeBackward(sc);
- }
- } else {
- if (so < sc.childNodes.length) {
- var startNode = sc.childNodes[so];
- if (startNode && dom.isCharacterDataNode(startNode)) {
- mergeBackward(startNode);
- }
- }
- }
- } else {
- sc = ec;
- so = eo;
- }
-
- boundaryUpdater(this, sc, so, ec, eo);
- },
-
- collapseToPoint: function(node, offset) {
- assertNotDetached(this);
-
- assertNoDocTypeNotationEntityAncestor(node, true);
- assertValidOffset(node, offset);
-
- setRangeStartAndEnd(this, node, offset);
- }
- });
-
- copyComparisonConstants(constructor);
- }
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- // Updates commonAncestorContainer and collapsed after boundary change
- function updateCollapsedAndCommonAncestor(range) {
- range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
- range.commonAncestorContainer = range.collapsed ?
- range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
- }
-
- function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
- var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset);
- var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset);
-
- range.startContainer = startContainer;
- range.startOffset = startOffset;
- range.endContainer = endContainer;
- range.endOffset = endOffset;
-
- updateCollapsedAndCommonAncestor(range);
- dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved});
- }
-
- function detach(range) {
- assertNotDetached(range);
- range.startContainer = range.startOffset = range.endContainer = range.endOffset = null;
- range.collapsed = range.commonAncestorContainer = null;
- dispatchEvent(range, "detach", null);
- range._listeners = null;
- }
-
- /**
- * @constructor
- */
- function Range(doc) {
- this.startContainer = doc;
- this.startOffset = 0;
- this.endContainer = doc;
- this.endOffset = 0;
- this._listeners = {
- boundarychange: [],
- detach: []
- };
- updateCollapsedAndCommonAncestor(this);
- }
-
- createPrototypeRange(Range, updateBoundaries, detach);
-
- api.rangePrototype = RangePrototype.prototype;
-
- Range.rangeProperties = rangeProperties;
- Range.RangeIterator = RangeIterator;
- Range.copyComparisonConstants = copyComparisonConstants;
- Range.createPrototypeRange = createPrototypeRange;
- Range.inspect = inspect;
- Range.getRangeDocument = getRangeDocument;
- Range.rangesEqual = function(r1, r2) {
- return r1.startContainer === r2.startContainer &&
- r1.startOffset === r2.startOffset &&
- r1.endContainer === r2.endContainer &&
- r1.endOffset === r2.endOffset;
- };
-
- api.DomRange = Range;
- api.RangeException = RangeException;
-});rangy.createModule("WrappedRange", function(api, module) {
- api.requireModules( ["DomUtil", "DomRange"] );
-
- /**
- * @constructor
- */
- var WrappedRange;
- var dom = api.dom;
- var DomPosition = dom.DomPosition;
- var DomRange = api.DomRange;
-
-
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- /*
- This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
- method. For example, in the following (where pipes denote the selection boundaries):
-
- <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>
-
- var range = document.selection.createRange();
- alert(range.parentElement().id); // Should alert "ul" but alerts "b"
-
- This method returns the common ancestor node of the following:
- - the parentElement() of the textRange
- - the parentElement() of the textRange after calling collapse(true)
- - the parentElement() of the textRange after calling collapse(false)
- */
- function getTextRangeContainerElement(textRange) {
- var parentEl = textRange.parentElement();
-
- var range = textRange.duplicate();
- range.collapse(true);
- var startEl = range.parentElement();
- range = textRange.duplicate();
- range.collapse(false);
- var endEl = range.parentElement();
- var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);
-
- return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
- }
-
- function textRangeIsCollapsed(textRange) {
- return textRange.compareEndPoints("StartToEnd", textRange) == 0;
- }
-
- // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as
- // an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has
- // grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling
- // for inputs and images, plus optimizations.
- function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) {
- var workingRange = textRange.duplicate();
-
- workingRange.collapse(isStart);
- var containerElement = workingRange.parentElement();
-
- // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
- // check for that
- // TODO: Find out when. Workaround for wholeRangeContainerElement may break this
- if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) {
- containerElement = wholeRangeContainerElement;
-
- }
-
-
-
- // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
- // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
- if (!containerElement.canHaveHTML) {
- return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
- }
-
- var workingNode = dom.getDocument(containerElement).createElement("span");
- var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
- var previousNode, nextNode, boundaryPosition, boundaryNode;
-
- // Move the working range through the container's children, starting at the end and working backwards, until the
- // working range reaches or goes past the boundary we're interested in
- do {
- containerElement.insertBefore(workingNode, workingNode.previousSibling);
- workingRange.moveToElementText(workingNode);
- } while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 &&
- workingNode.previousSibling);
-
- // We've now reached or gone past the boundary of the text range we're interested in
- // so have identified the node we want
- boundaryNode = workingNode.nextSibling;
-
- if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) {
- // This is a character data node (text, comment, cdata). The working range is collapsed at the start of the
- // node containing the text range's boundary, so we move the end of the working range to the boundary point
- // and measure the length of its text to get the boundary's offset within the node.
- workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);
-
-
- var offset;
-
- if (/[\r\n]/.test(boundaryNode.data)) {
- /*
- For the particular case of a boundary within a text node containing line breaks (within a <pre> element,
- for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts:
-
- - Each line break is represented as \r in the text node's data/nodeValue properties
- - Each line break is represented as \r\n in the TextRange's 'text' property
- - The 'text' property of the TextRange does not contain trailing line breaks
-
- To get round the problem presented by the final fact above, we can use the fact that TextRange's
- moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily
- the same as the number of characters it was instructed to move. The simplest approach is to use this to
- store the characters moved when moving both the start and end of the range to the start of the document
- body and subtracting the start offset from the end offset (the "move-negative-gazillion" method).
- However, this is extremely slow when the document is large and the range is near the end of it. Clearly
- doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same
- problem.
-
- Another approach that works is to use moveStart() to move the start boundary of the range up to the end
- boundary one character at a time and incrementing a counter with the value returned by the moveStart()
- call. However, the check for whether the start boundary has reached the end boundary is expensive, so
- this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of
- the range within the document).
-
- The method below is a hybrid of the two methods above. It uses the fact that a string containing the
- TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the
- text of the TextRange, so the start of the range is moved that length initially and then a character at
- a time to make up for any trailing line breaks not contained in the 'text' property. This has good
- performance in most situations compared to the previous two methods.
- */
- var tempRange = workingRange.duplicate();
- var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;
-
- offset = tempRange.moveStart("character", rangeLength);
- while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
- offset++;
- tempRange.moveStart("character", 1);
- }
- } else {
- offset = workingRange.text.length;
- }
- boundaryPosition = new DomPosition(boundaryNode, offset);
- } else {
-
-
- // If the boundary immediately follows a character data node and this is the end boundary, we should favour
- // a position within that, and likewise for a start boundary preceding a character data node
- previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
- nextNode = (isCollapsed || isStart) && workingNode.nextSibling;
-
-
-
- if (nextNode && dom.isCharacterDataNode(nextNode)) {
- boundaryPosition = new DomPosition(nextNode, 0);
- } else if (previousNode && dom.isCharacterDataNode(previousNode)) {
- boundaryPosition = new DomPosition(previousNode, previousNode.length);
- } else {
- boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
- }
- }
-
- // Clean up
- workingNode.parentNode.removeChild(workingNode);
-
- return boundaryPosition;
- }
-
- // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node.
- // This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
- // (http://code.google.com/p/ierange/)
- function createBoundaryTextRange(boundaryPosition, isStart) {
- var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
- var doc = dom.getDocument(boundaryPosition.node);
- var workingNode, childNodes, workingRange = doc.body.createTextRange();
- var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node);
-
- if (nodeIsDataNode) {
- boundaryNode = boundaryPosition.node;
- boundaryParent = boundaryNode.parentNode;
- } else {
- childNodes = boundaryPosition.node.childNodes;
- boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
- boundaryParent = boundaryPosition.node;
- }
-
- // Position the range immediately before the node containing the boundary
- workingNode = doc.createElement("span");
-
- // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the
- // element rather than immediately before or after it, which is what we want
- workingNode.innerHTML = "&#feff;";
-
- // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
- // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
- if (boundaryNode) {
- boundaryParent.insertBefore(workingNode, boundaryNode);
- } else {
- boundaryParent.appendChild(workingNode);
- }
-
- workingRange.moveToElementText(workingNode);
- workingRange.collapse(!isStart);
-
- // Clean up
- boundaryParent.removeChild(workingNode);
-
- // Move the working range to the text offset, if required
- if (nodeIsDataNode) {
- workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
- }
-
- return workingRange;
- }
-
- /*----------------------------------------------------------------------------------------------------------------*/
-
- if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) {
- // This is a wrapper around the browser's native DOM Range. It has two aims:
- // - Provide workarounds for specific browser bugs
- // - provide convenient extensions, which are inherited from Rangy's DomRange
-
- (function() {
- var rangeProto;
- var rangeProperties = DomRange.rangeProperties;
- var canSetRangeStartAfterEnd;
-
- function updateRangeProperties(range) {
- var i = rangeProperties.length, prop;
- while (i--) {
- prop = rangeProperties[i];
- range[prop] = range.nativeRange[prop];
- }
- }
-
- function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) {
- var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
- var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);
-
- // Always set both boundaries for the benefit of IE9 (see issue 35)
- if (startMoved || endMoved) {
- range.setEnd(endContainer, endOffset);
- range.setStart(startContainer, startOffset);
- }
- }
-
- function detach(range) {
- range.nativeRange.detach();
- range.detached = true;
- var i = rangeProperties.length, prop;
- while (i--) {
- prop = rangeProperties[i];
- range[prop] = null;
- }
- }
-
- var createBeforeAfterNodeSetter;
-
- WrappedRange = function(range) {
- if (!range) {
- throw new Error("Range must be specified");
- }
- this.nativeRange = range;
- updateRangeProperties(this);
- };
-
- DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach);
-
- rangeProto = WrappedRange.prototype;
-
- rangeProto.selectNode = function(node) {
- this.nativeRange.selectNode(node);
- updateRangeProperties(this);
- };
-
- rangeProto.deleteContents = function() {
- this.nativeRange.deleteContents();
- updateRangeProperties(this);
- };
-
- rangeProto.extractContents = function() {
- var frag = this.nativeRange.extractContents();
- updateRangeProperties(this);
- return frag;
- };
-
- rangeProto.cloneContents = function() {
- return this.nativeRange.cloneContents();
- };
-
- // TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still
- // present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for
- // insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of
- // insertNode, which works but is almost certainly slower than the native implementation.
-/*
- rangeProto.insertNode = function(node) {
- this.nativeRange.insertNode(node);
- updateRangeProperties(this);
- };
-*/
-
- rangeProto.surroundContents = function(node) {
- this.nativeRange.surroundContents(node);
- updateRangeProperties(this);
- };
-
- rangeProto.collapse = function(isStart) {
- this.nativeRange.collapse(isStart);
- updateRangeProperties(this);
- };
-
- rangeProto.cloneRange = function() {
- return new WrappedRange(this.nativeRange.cloneRange());
- };
-
- rangeProto.refresh = function() {
- updateRangeProperties(this);
- };
-
- rangeProto.toString = function() {
- return this.nativeRange.toString();
- };
-
- // Create test range and node for feature detection
-
- var testTextNode = document.createTextNode("test");
- dom.getBody(document).appendChild(testTextNode);
- var range = document.createRange();
-
- /*--------------------------------------------------------------------------------------------------------*/
-
- // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
- // correct for it
-
- range.setStart(testTextNode, 0);
- range.setEnd(testTextNode, 0);
-
- try {
- range.setStart(testTextNode, 1);
- canSetRangeStartAfterEnd = true;
-
- rangeProto.setStart = function(node, offset) {
- this.nativeRange.setStart(node, offset);
- updateRangeProperties(this);
- };
-
- rangeProto.setEnd = function(node, offset) {
- this.nativeRange.setEnd(node, offset);
- updateRangeProperties(this);
- };
-
- createBeforeAfterNodeSetter = function(name) {
- return function(node) {
- this.nativeRange[name](node);
- updateRangeProperties(this);
- };
- };
-
- } catch(ex) {
-
-
- canSetRangeStartAfterEnd = false;
-
- rangeProto.setStart = function(node, offset) {
- try {
- this.nativeRange.setStart(node, offset);
- } catch (ex) {
- this.nativeRange.setEnd(node, offset);
- this.nativeRange.setStart(node, offset);
- }
- updateRangeProperties(this);
- };
-
- rangeProto.setEnd = function(node, offset) {
- try {
- this.nativeRange.setEnd(node, offset);
- } catch (ex) {
- this.nativeRange.setStart(node, offset);
- this.nativeRange.setEnd(node, offset);
- }
- updateRangeProperties(this);
- };
-
- createBeforeAfterNodeSetter = function(name, oppositeName) {
- return function(node) {
- try {
- this.nativeRange[name](node);
- } catch (ex) {
- this.nativeRange[oppositeName](node);
- this.nativeRange[name](node);
- }
- updateRangeProperties(this);
- };
- };
- }
-
- rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
- rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
- rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
- rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");
-
- /*--------------------------------------------------------------------------------------------------------*/
-
- // Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to
- // the 0th character of the text node
- range.selectNodeContents(testTextNode);
- if (range.startContainer == testTextNode && range.endContainer == testTextNode &&
- range.startOffset == 0 && range.endOffset == testTextNode.length) {
- rangeProto.selectNodeContents = function(node) {
- this.nativeRange.selectNodeContents(node);
- updateRangeProperties(this);
- };
- } else {
- rangeProto.selectNodeContents = function(node) {
- this.setStart(node, 0);
- this.setEnd(node, DomRange.getEndOffset(node));
- };
- }
-
- /*--------------------------------------------------------------------------------------------------------*/
-
- // Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants
- // START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738
-
- range.selectNodeContents(testTextNode);
- range.setEnd(testTextNode, 3);
-
- var range2 = document.createRange();
- range2.selectNodeContents(testTextNode);
- range2.setEnd(testTextNode, 4);
- range2.setStart(testTextNode, 2);
-
- if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &
- range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
- // This is the wrong way round, so correct for it
-
-
- rangeProto.compareBoundaryPoints = function(type, range) {
- range = range.nativeRange || range;
- if (type == range.START_TO_END) {
- type = range.END_TO_START;
- } else if (type == range.END_TO_START) {
- type = range.START_TO_END;
- }
- return this.nativeRange.compareBoundaryPoints(type, range);
- };
- } else {
- rangeProto.compareBoundaryPoints = function(type, range) {
- return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
- };
- }
-
- /*--------------------------------------------------------------------------------------------------------*/
-
- // Test for existence of createContextualFragment and delegate to it if it exists
- if (api.util.isHostMethod(range, "createContextualFragment")) {
- rangeProto.createContextualFragment = function(fragmentStr) {
- return this.nativeRange.createContextualFragment(fragmentStr);
- };
- }
-
- /*--------------------------------------------------------------------------------------------------------*/
-
- // Clean up
- dom.getBody(document).removeChild(testTextNode);
- range.detach();
- range2.detach();
- })();
-
- api.createNativeRange = function(doc) {
- doc = doc || document;
- return doc.createRange();
- };
- } else if (api.features.implementsTextRange) {
- // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
- // prototype
-
- WrappedRange = function(textRange) {
- this.textRange = textRange;
- this.refresh();
- };
-
- WrappedRange.prototype = new DomRange(document);
-
- WrappedRange.prototype.refresh = function() {
- var start, end;
-
- // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
- var rangeContainerElement = getTextRangeContainerElement(this.textRange);
-
- if (textRangeIsCollapsed(this.textRange)) {
- end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true);
- } else {
-
- start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
- end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false);
- }
-
- this.setStart(start.node, start.offset);
- this.setEnd(end.node, end.offset);
- };
-
- DomRange.copyComparisonConstants(WrappedRange);
-
- // Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work
- var globalObj = (function() { return this; })();
- if (typeof globalObj.Range == "undefined") {
- globalObj.Range = WrappedRange;
- }
-
- api.createNativeRange = function(doc) {
- doc = doc || document;
- return doc.body.createTextRange();
- };
- }
-
- if (api.features.implementsTextRange) {
- WrappedRange.rangeToTextRange = function(range) {
- if (range.collapsed) {
- var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
-
-
-
- return tr;
-
- //return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
- } else {
- var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
- var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
- var textRange = dom.getDocument(range.startContainer).body.createTextRange();
- textRange.setEndPoint("StartToStart", startRange);
- textRange.setEndPoint("EndToEnd", endRange);
- return textRange;
- }
- };
- }
-
- WrappedRange.prototype.getName = function() {
- return "WrappedRange";
- };
-
- api.WrappedRange = WrappedRange;
-
- api.createRange = function(doc) {
- doc = doc || document;
- return new WrappedRange(api.createNativeRange(doc));
- };
-
- api.createRangyRange = function(doc) {
- doc = doc || document;
- return new DomRange(doc);
- };
-
- api.createIframeRange = function(iframeEl) {
- return api.createRange(dom.getIframeDocument(iframeEl));
- };
-
- api.createIframeRangyRange = function(iframeEl) {
- return api.createRangyRange(dom.getIframeDocument(iframeEl));
- };
-
- api.addCreateMissingNativeApiListener(function(win) {
- var doc = win.document;
- if (typeof doc.createRange == "undefined") {
- doc.createRange = function() {
- return api.createRange(this);
- };
- }
- doc = win = null;
- });
-});rangy.createModule("WrappedSelection", function(api, module) {
- // This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range
- // spec (http://html5.org/specs/dom-range.html)
-
- api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] );
-
- api.config.checkSelectionRanges = true;
-
- var BOOLEAN = "boolean",
- windowPropertyName = "_rangySelection",
- dom = api.dom,
- util = api.util,
- DomRange = api.DomRange,
- WrappedRange = api.WrappedRange,
- DOMException = api.DOMException,
- DomPosition = dom.DomPosition,
- getSelection,
- selectionIsCollapsed,
- CONTROL = "Control";
-
-
-
- function getWinSelection(winParam) {
- return (winParam || window).getSelection();
- }
-
- function getDocSelection(winParam) {
- return (winParam || window).document.selection;
- }
-
- // Test for the Range/TextRange and Selection features required
- // Test for ability to retrieve selection
- var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"),
- implementsDocSelection = api.util.isHostObject(document, "selection");
-
- var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);
-
- if (useDocumentSelection) {
- getSelection = getDocSelection;
- api.isSelectionValid = function(winParam) {
- var doc = (winParam || window).document, nativeSel = doc.selection;
-
- // Check whether the selection TextRange is actually contained within the correct document
- return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc);
- };
- } else if (implementsWinGetSelection) {
- getSelection = getWinSelection;
- api.isSelectionValid = function() {
- return true;
- };
- } else {
- module.fail("Neither document.selection or window.getSelection() detected.");
- }
-
- api.getNativeSelection = getSelection;
-
- var testSelection = getSelection();
- var testRange = api.createNativeRange(document);
- var body = dom.getBody(document);
-
- // Obtaining a range from a selection
- var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] &&
- util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"]));
- api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;
-
- // Test for existence of native selection extend() method
- var selectionHasExtend = util.isHostMethod(testSelection, "extend");
- api.features.selectionHasExtend = selectionHasExtend;
-
- // Test if rangeCount exists
- var selectionHasRangeCount = (typeof testSelection.rangeCount == "number");
- api.features.selectionHasRangeCount = selectionHasRangeCount;
-
- var selectionSupportsMultipleRanges = false;
- var collapsedNonEditableSelectionsSupported = true;
-
- if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
- typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) {
-
- (function() {
- var iframe = document.createElement("iframe");
- body.appendChild(iframe);
-
- var iframeDoc = dom.getIframeDocument(iframe);
- iframeDoc.open();
- iframeDoc.write("<html><head></head><body>12</body></html>");
- iframeDoc.close();
-
- var sel = dom.getIframeWindow(iframe).getSelection();
- var docEl = iframeDoc.documentElement;
- var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;
-
- // Test whether the native selection will allow a collapsed selection within a non-editable element
- var r1 = iframeDoc.createRange();
- r1.setStart(textNode, 1);
- r1.collapse(true);
- sel.addRange(r1);
- collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
- sel.removeAllRanges();
-
- // Test whether the native selection is capable of supporting multiple ranges
- var r2 = r1.cloneRange();
- r1.setStart(textNode, 0);
- r2.setEnd(textNode, 2);
- sel.addRange(r1);
- sel.addRange(r2);
-
- selectionSupportsMultipleRanges = (sel.rangeCount == 2);
-
- // Clean up
- r1.detach();
- r2.detach();
-
- body.removeChild(iframe);
- })();
- }
-
- api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
- api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;
-
- // ControlRanges
- var implementsControlRange = false, testControlRange;
-
- if (body && util.isHostMethod(body, "createControlRange")) {
- testControlRange = body.createControlRange();
- if (util.areHostProperties(testControlRange, ["item", "add"])) {
- implementsControlRange = true;
- }
- }
- api.features.implementsControlRange = implementsControlRange;
-
- // Selection collapsedness
- if (selectionHasAnchorAndFocus) {
- selectionIsCollapsed = function(sel) {
- return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
- };
- } else {
- selectionIsCollapsed = function(sel) {
- return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
- };
- }
-
- function updateAnchorAndFocusFromRange(sel, range, backwards) {
- var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end";
- sel.anchorNode = range[anchorPrefix + "Container"];
- sel.anchorOffset = range[anchorPrefix + "Offset"];
- sel.focusNode = range[focusPrefix + "Container"];
- sel.focusOffset = range[focusPrefix + "Offset"];
- }
-
- function updateAnchorAndFocusFromNativeSelection(sel) {
- var nativeSel = sel.nativeSelection;
- sel.anchorNode = nativeSel.anchorNode;
- sel.anchorOffset = nativeSel.anchorOffset;
- sel.focusNode = nativeSel.focusNode;
- sel.focusOffset = nativeSel.focusOffset;
- }
-
- function updateEmptySelection(sel) {
- sel.anchorNode = sel.focusNode = null;
- sel.anchorOffset = sel.focusOffset = 0;
- sel.rangeCount = 0;
- sel.isCollapsed = true;
- sel._ranges.length = 0;
- }
-
- function getNativeRange(range) {
- var nativeRange;
- if (range instanceof DomRange) {
- nativeRange = range._selectionNativeRange;
- if (!nativeRange) {
- nativeRange = api.createNativeRange(dom.getDocument(range.startContainer));
- nativeRange.setEnd(range.endContainer, range.endOffset);
- nativeRange.setStart(range.startContainer, range.startOffset);
- range._selectionNativeRange = nativeRange;
- range.attachListener("detach", function() {
-
- this._selectionNativeRange = null;
- });
- }
- } else if (range instanceof WrappedRange) {
- nativeRange = range.nativeRange;
- } else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
- nativeRange = range;
- }
- return nativeRange;
- }
-
- function rangeContainsSingleElement(rangeNodes) {
- if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
- return false;
- }
- for (var i = 1, len = rangeNodes.length; i < len; ++i) {
- if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
- return false;
- }
- }
- return true;
- }
-
- function getSingleElementFromRange(range) {
- var nodes = range.getNodes();
- if (!rangeContainsSingleElement(nodes)) {
- throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
- }
- return nodes[0];
- }
-
- function isTextRange(range) {
- return !!range && typeof range.text != "undefined";
- }
-
- function updateFromTextRange(sel, range) {
- // Create a Range from the selected TextRange
- var wrappedRange = new WrappedRange(range);
- sel._ranges = [wrappedRange];
-
- updateAnchorAndFocusFromRange(sel, wrappedRange, false);
- sel.rangeCount = 1;
- sel.isCollapsed = wrappedRange.collapsed;
- }
-
- function updateControlSelection(sel) {
- // Update the wrapped selection based on what's now in the native selection
- sel._ranges.length = 0;
- if (sel.docSelection.type == "None") {
- updateEmptySelection(sel);
- } else {
- var controlRange = sel.docSelection.createRange();
- if (isTextRange(controlRange)) {
- // This case (where the selection type is "Control" and calling createRange() on the selection returns
- // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
- // ControlRange have been removed from the ControlRange and removed from the document.
- updateFromTextRange(sel, controlRange);
- } else {
- sel.rangeCount = controlRange.length;
- var range, doc = dom.getDocument(controlRange.item(0));
- for (var i = 0; i < sel.rangeCount; ++i) {
- range = api.createRange(doc);
- range.selectNode(controlRange.item(i));
- sel._ranges.push(range);
- }
- sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
- updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
- }
- }
- }
-
- function addRangeToControlSelection(sel, range) {
- var controlRange = sel.docSelection.createRange();
- var rangeElement = getSingleElementFromRange(range);
-
- // Create a new ControlRange containing all the elements in the selected ControlRange plus the element
- // contained by the supplied range
- var doc = dom.getDocument(controlRange.item(0));
- var newControlRange = dom.getBody(doc).createControlRange();
- for (var i = 0, len = controlRange.length; i < len; ++i) {
- newControlRange.add(controlRange.item(i));
- }
- try {
- newControlRange.add(rangeElement);
- } catch (ex) {
- throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
- }
- newControlRange.select();
-
- // Update the wrapped selection based on what's now in the native selection
- updateControlSelection(sel);
- }
-
- var getSelectionRangeAt;
-
- if (util.isHostMethod(testSelection, "getRangeAt")) {
- getSelectionRangeAt = function(sel, index) {
- try {
- return sel.getRangeAt(index);
- } catch(ex) {
- return null;
- }
- };
- } else if (selectionHasAnchorAndFocus) {
- getSelectionRangeAt = function(sel) {
- var doc = dom.getDocument(sel.anchorNode);
- var range = api.createRange(doc);
- range.setStart(sel.anchorNode, sel.anchorOffset);
- range.setEnd(sel.focusNode, sel.focusOffset);
-
- // Handle the case when the selection was selected backwards (from the end to the start in the
- // document)
- if (range.collapsed !== this.isCollapsed) {
- range.setStart(sel.focusNode, sel.focusOffset);
- range.setEnd(sel.anchorNode, sel.anchorOffset);
- }
-
- return range;
- };
- }
-
- /**
- * @constructor
- */
- function WrappedSelection(selection, docSelection, win) {
- this.nativeSelection = selection;
- this.docSelection = docSelection;
- this._ranges = [];
- this.win = win;
- this.refresh();
- }
-
- api.getSelection = function(win) {
- win = win || window;
- var sel = win[windowPropertyName];
- var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
- if (sel) {
- sel.nativeSelection = nativeSel;
- sel.docSelection = docSel;
- sel.refresh(win);
- } else {
- sel = new WrappedSelection(nativeSel, docSel, win);
- win[windowPropertyName] = sel;
- }
- return sel;
- };
-
- api.getIframeSelection = function(iframeEl) {
- return api.getSelection(dom.getIframeWindow(iframeEl));
- };
-
- var selProto = WrappedSelection.prototype;
-
- function createControlSelection(sel, ranges) {
- // Ensure that the selection becomes of type "Control"
- var doc = dom.getDocument(ranges[0].startContainer);
- var controlRange = dom.getBody(doc).createControlRange();
- for (var i = 0, el; i < rangeCount; ++i) {
- el = getSingleElementFromRange(ranges[i]);
- try {
- controlRange.add(el);
- } catch (ex) {
- throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)");
- }
- }
- controlRange.select();
-
- // Update the wrapped selection based on what's now in the native selection
- updateControlSelection(sel);
- }
-
- // Selecting a range
- if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
- selProto.removeAllRanges = function() {
- this.nativeSelection.removeAllRanges();
- updateEmptySelection(this);
- };
-
- var addRangeBackwards = function(sel, range) {
- var doc = DomRange.getRangeDocument(range);
- var endRange = api.createRange(doc);
- endRange.collapseToPoint(range.endContainer, range.endOffset);
- sel.nativeSelection.addRange(getNativeRange(endRange));
- sel.nativeSelection.extend(range.startContainer, range.startOffset);
- sel.refresh();
- };
-
- if (selectionHasRangeCount) {
- selProto.addRange = function(range, backwards) {
- if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
- addRangeToControlSelection(this, range);
- } else {
- if (backwards && selectionHasExtend) {
- addRangeBackwards(this, range);
- } else {
- var previousRangeCount;
- if (selectionSupportsMultipleRanges) {
- previousRangeCount = this.rangeCount;
- } else {
- this.removeAllRanges();
- previousRangeCount = 0;
- }
- this.nativeSelection.addRange(getNativeRange(range));
-
- // Check whether adding the range was successful
- this.rangeCount = this.nativeSelection.rangeCount;
-
- if (this.rangeCount == previousRangeCount + 1) {
- // The range was added successfully
-
- // Check whether the range that we added to the selection is reflected in the last range extracted from
- // the selection
- if (api.config.checkSelectionRanges) {
- var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
- if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) {
- // Happens in WebKit with, for example, a selection placed at the start of a text node
- range = new WrappedRange(nativeRange);
- }
- }
- this._ranges[this.rangeCount - 1] = range;
- updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection));
- this.isCollapsed = selectionIsCollapsed(this);
- } else {
- // The range was not added successfully. The simplest thing is to refresh
- this.refresh();
- }
- }
- }
- };
- } else {
- selProto.addRange = function(range, backwards) {
- if (backwards && selectionHasExtend) {
- addRangeBackwards(this, range);
- } else {
- this.nativeSelection.addRange(getNativeRange(range));
- this.refresh();
- }
- };
- }
-
- selProto.setRanges = function(ranges) {
- if (implementsControlRange && ranges.length > 1) {
- createControlSelection(this, ranges);
- } else {
- this.removeAllRanges();
- for (var i = 0, len = ranges.length; i < len; ++i) {
- this.addRange(ranges[i]);
- }
- }
- };
- } else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") &&
- implementsControlRange && useDocumentSelection) {
-
- selProto.removeAllRanges = function() {
- // Added try/catch as fix for issue #21
- try {
- this.docSelection.empty();
-
- // Check for empty() not working (issue #24)
- if (this.docSelection.type != "None") {
- // Work around failure to empty a control selection by instead selecting a TextRange and then
- // calling empty()
- var doc;
- if (this.anchorNode) {
- doc = dom.getDocument(this.anchorNode);
- } else if (this.docSelection.type == CONTROL) {
- var controlRange = this.docSelection.createRange();
- if (controlRange.length) {
- doc = dom.getDocument(controlRange.item(0)).body.createTextRange();
- }
- }
- if (doc) {
- var textRange = doc.body.createTextRange();
- textRange.select();
- this.docSelection.empty();
- }
- }
- } catch(ex) {}
- updateEmptySelection(this);
- };
-
- selProto.addRange = function(range) {
- if (this.docSelection.type == CONTROL) {
- addRangeToControlSelection(this, range);
- } else {
- WrappedRange.rangeToTextRange(range).select();
- this._ranges[0] = range;
- this.rangeCount = 1;
- this.isCollapsed = this._ranges[0].collapsed;
- updateAnchorAndFocusFromRange(this, range, false);
- }
- };
-
- selProto.setRanges = function(ranges) {
- this.removeAllRanges();
- var rangeCount = ranges.length;
- if (rangeCount > 1) {
- createControlSelection(this, ranges);
- } else if (rangeCount) {
- this.addRange(ranges[0]);
- }
- };
- } else {
- module.fail("No means of selecting a Range or TextRange was found");
- return false;
- }
-
- selProto.getRangeAt = function(index) {
- if (index < 0 || index >= this.rangeCount) {
- throw new DOMException("INDEX_SIZE_ERR");
- } else {
- return this._ranges[index];
- }
- };
-
- var refreshSelection;
-
- if (useDocumentSelection) {
- refreshSelection = function(sel) {
- var range;
- if (api.isSelectionValid(sel.win)) {
- range = sel.docSelection.createRange();
- } else {
- range = dom.getBody(sel.win.document).createTextRange();
- range.collapse(true);
- }
-
-
- if (sel.docSelection.type == CONTROL) {
- updateControlSelection(sel);
- } else if (isTextRange(range)) {
- updateFromTextRange(sel, range);
- } else {
- updateEmptySelection(sel);
- }
- };
- } else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") {
- refreshSelection = function(sel) {
- if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
- updateControlSelection(sel);
- } else {
- sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
- if (sel.rangeCount) {
- for (var i = 0, len = sel.rangeCount; i < len; ++i) {
- sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
- }
- updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection));
- sel.isCollapsed = selectionIsCollapsed(sel);
- } else {
- updateEmptySelection(sel);
- }
- }
- };
- } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) {
- refreshSelection = function(sel) {
- var range, nativeSel = sel.nativeSelection;
- if (nativeSel.anchorNode) {
- range = getSelectionRangeAt(nativeSel, 0);
- sel._ranges = [range];
- sel.rangeCount = 1;
- updateAnchorAndFocusFromNativeSelection(sel);
- sel.isCollapsed = selectionIsCollapsed(sel);
- } else {
- updateEmptySelection(sel);
- }
- };
- } else {
- module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
- return false;
- }
-
- selProto.refresh = function(checkForChanges) {
- var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
- refreshSelection(this);
- if (checkForChanges) {
- var i = oldRanges.length;
- if (i != this._ranges.length) {
- return false;
- }
- while (i--) {
- if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) {
- return false;
- }
- }
- return true;
- }
- };
-
- // Removal of a single range
- var removeRangeManually = function(sel, range) {
- var ranges = sel.getAllRanges(), removed = false;
- sel.removeAllRanges();
- for (var i = 0, len = ranges.length; i < len; ++i) {
- if (removed || range !== ranges[i]) {
- sel.addRange(ranges[i]);
- } else {
- // According to the draft WHATWG Range spec, the same range may be added to the selection multiple
- // times. removeRange should only remove the first instance, so the following ensures only the first
- // instance is removed
- removed = true;
- }
- }
- if (!sel.rangeCount) {
- updateEmptySelection(sel);
- }
- };
-
- if (implementsControlRange) {
- selProto.removeRange = function(range) {
- if (this.docSelection.type == CONTROL) {
- var controlRange = this.docSelection.createRange();
- var rangeElement = getSingleElementFromRange(range);
-
- // Create a new ControlRange containing all the elements in the selected ControlRange minus the
- // element contained by the supplied range
- var doc = dom.getDocument(controlRange.item(0));
- var newControlRange = dom.getBody(doc).createControlRange();
- var el, removed = false;
- for (var i = 0, len = controlRange.length; i < len; ++i) {
- el = controlRange.item(i);
- if (el !== rangeElement || removed) {
- newControlRange.add(controlRange.item(i));
- } else {
- removed = true;
- }
- }
- newControlRange.select();
-
- // Update the wrapped selection based on what's now in the native selection
- updateControlSelection(this);
- } else {
- removeRangeManually(this, range);
- }
- };
- } else {
- selProto.removeRange = function(range) {
- removeRangeManually(this, range);
- };
- }
-
- // Detecting if a selection is backwards
- var selectionIsBackwards;
- if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) {
- selectionIsBackwards = function(sel) {
- var backwards = false;
- if (sel.anchorNode) {
- backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
- }
- return backwards;
- };
-
- selProto.isBackwards = function() {
- return selectionIsBackwards(this);
- };
- } else {
- selectionIsBackwards = selProto.isBackwards = function() {
- return false;
- };
- }
-
- // Selection text
- // This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation
- selProto.toString = function() {
-
- var rangeTexts = [];
- for (var i = 0, len = this.rangeCount; i < len; ++i) {
- rangeTexts[i] = "" + this._ranges[i];
- }
- return rangeTexts.join("");
- };
-
- function assertNodeInSameDocument(sel, node) {
- if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) {
- throw new DOMException("WRONG_DOCUMENT_ERR");
- }
- }
-
- // No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used
- selProto.collapse = function(node, offset) {
- assertNodeInSameDocument(this, node);
- var range = api.createRange(dom.getDocument(node));
- range.collapseToPoint(node, offset);
- this.removeAllRanges();
- this.addRange(range);
- this.isCollapsed = true;
- };
-
- selProto.collapseToStart = function() {
- if (this.rangeCount) {
- var range = this._ranges[0];
- this.collapse(range.startContainer, range.startOffset);
- } else {
- throw new DOMException("INVALID_STATE_ERR");
- }
- };
-
- selProto.collapseToEnd = function() {
- if (this.rangeCount) {
- var range = this._ranges[this.rangeCount - 1];
- this.collapse(range.endContainer, range.endOffset);
- } else {
- throw new DOMException("INVALID_STATE_ERR");
- }
- };
-
- // The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is
- // never used by Rangy.
- selProto.selectAllChildren = function(node) {
- assertNodeInSameDocument(this, node);
- var range = api.createRange(dom.getDocument(node));
- range.selectNodeContents(node);
- this.removeAllRanges();
- this.addRange(range);
- };
-
- selProto.deleteFromDocument = function() {
- // Sepcial behaviour required for Control selections
- if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
- var controlRange = this.docSelection.createRange();
- var element;
- while (controlRange.length) {
- element = controlRange.item(0);
- controlRange.remove(element);
- element.parentNode.removeChild(element);
- }
- this.refresh();
- } else if (this.rangeCount) {
- var ranges = this.getAllRanges();
- this.removeAllRanges();
- for (var i = 0, len = ranges.length; i < len; ++i) {
- ranges[i].deleteContents();
- }
- // The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each
- // range. Firefox moves the selection to where the final selected range was, so we emulate that
- this.addRange(ranges[len - 1]);
- }
- };
-
- // The following are non-standard extensions
- selProto.getAllRanges = function() {
- return this._ranges.slice(0);
- };
-
- selProto.setSingleRange = function(range) {
- this.setRanges( [range] );
- };
-
- selProto.containsNode = function(node, allowPartial) {
- for (var i = 0, len = this._ranges.length; i < len; ++i) {
- if (this._ranges[i].containsNode(node, allowPartial)) {
- return true;
- }
- }
- return false;
- };
-
- selProto.toHtml = function() {
- var html = "";
- if (this.rangeCount) {
- var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div");
- for (var i = 0, len = this._ranges.length; i < len; ++i) {
- container.appendChild(this._ranges[i].cloneContents());
- }
- html = container.innerHTML;
- }
- return html;
- };
-
- function inspect(sel) {
- var rangeInspects = [];
- var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
- var focus = new DomPosition(sel.focusNode, sel.focusOffset);
- var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";
-
- if (typeof sel.rangeCount != "undefined") {
- for (var i = 0, len = sel.rangeCount; i < len; ++i) {
- rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
- }
- }
- return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
- ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";
-
- }
-
- selProto.getName = function() {
- return "WrappedSelection";
- };
-
- selProto.inspect = function() {
- return inspect(this);
- };
-
- selProto.detach = function() {
- this.win[windowPropertyName] = null;
- this.win = this.anchorNode = this.focusNode = null;
- };
-
- WrappedSelection.inspect = inspect;
-
- api.Selection = WrappedSelection;
-
- api.selectionPrototype = selProto;
-
- api.addCreateMissingNativeApiListener(function(win) {
- if (typeof win.getSelection == "undefined") {
- win.getSelection = function() {
- return api.getSelection(this);
- };
- }
- win = null;
- });
-});
-/*
- Base.js, version 1.1a
- Copyright 2006-2010, Dean Edwards
- License: http://www.opensource.org/licenses/mit-license.php
-*/
-
-var Base = function() {
- // dummy
-};
-
-Base.extend = function(_instance, _static) { // subclass
- var extend = Base.prototype.extend;
-
- // build the prototype
- Base._prototyping = true;
- var proto = new this;
- extend.call(proto, _instance);
- proto.base = function() {
- // call this method from any other method to invoke that method's ancestor
- };
- delete Base._prototyping;
-
- // create the wrapper for the constructor function
- //var constructor = proto.constructor.valueOf(); //-dean
- var constructor = proto.constructor;
- var klass = proto.constructor = function() {
- if (!Base._prototyping) {
- if (this._constructing || this.constructor == klass) { // instantiation
- this._constructing = true;
- constructor.apply(this, arguments);
- delete this._constructing;
- } else if (arguments[0] != null) { // casting
- return (arguments[0].extend || extend).call(arguments[0], proto);
- }
- }
- };
-
- // build the class interface
- klass.ancestor = this;
- klass.extend = this.extend;
- klass.forEach = this.forEach;
- klass.implement = this.implement;
- klass.prototype = proto;
- klass.toString = this.toString;
- klass.valueOf = function(type) {
- //return (type == "object") ? klass : constructor; //-dean
- return (type == "object") ? klass : constructor.valueOf();
- };
- extend.call(klass, _static);
- // class initialisation
- if (typeof klass.init == "function") klass.init();
- return klass;
-};
-
-Base.prototype = {
- extend: function(source, value) {
- if (arguments.length > 1) { // extending with a name/value pair
- var ancestor = this[source];
- if (ancestor && (typeof value == "function") && // overriding a method?
- // the valueOf() comparison is to avoid circular references
- (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) &&
- /\bbase\b/.test(value)) {
- // get the underlying method
- var method = value.valueOf();
- // override
- value = function() {
- var previous = this.base || Base.prototype.base;
- this.base = ancestor;
- var returnValue = method.apply(this, arguments);
- this.base = previous;
- return returnValue;
- };
- // point to the underlying method
- value.valueOf = function(type) {
- return (type == "object") ? value : method;
- };
- value.toString = Base.toString;
- }
- this[source] = value;
- } else if (source) { // extending with an object literal
- var extend = Base.prototype.extend;
- // if this object has a customised extend method then use it
- if (!Base._prototyping && typeof this != "function") {
- extend = this.extend || extend;
- }
- var proto = {toSource: null};
- // do the "toString" and other methods manually
- var hidden = ["constructor", "toString", "valueOf"];
- // if we are prototyping then include the constructor
- var i = Base._prototyping ? 0 : 1;
- while (key = hidden[i++]) {
- if (source[key] != proto[key]) {
- extend.call(this, key, source[key]);
-
- }
- }
- // copy each of the source object's properties to this object
- for (var key in source) {
- if (!proto[key]) extend.call(this, key, source[key]);
- }
- }
- return this;
- }
-};
-
-// initialise
-Base = Base.extend({
- constructor: function() {
- this.extend(arguments[0]);
- }
-}, {
- ancestor: Object,
- version: "1.1",
-
- forEach: function(object, block, context) {
- for (var key in object) {
- if (this.prototype[key] === undefined) {
- block.call(context, object[key], key, object);
- }
- }
- },
-
- implement: function() {
- for (var i = 0; i < arguments.length; i++) {
- if (typeof arguments[i] == "function") {
- // if it's a function, call it
- arguments[i](this.prototype);
- } else {
- // add the interface using the extend method
- this.prototype.extend(arguments[i]);
- }
- }
- return this;
- },
-
- toString: function() {
- return String(this.valueOf());
- }
-});/**
- * Detect browser support for specific features
- */
-wysihtml5.browser = (function() {
- var userAgent = navigator.userAgent,
- testElement = document.createElement("div"),
- // Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect
- isIE = userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("Opera") === -1,
- isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1,
- isWebKit = userAgent.indexOf("AppleWebKit/") !== -1,
- isChrome = userAgent.indexOf("Chrome/") !== -1,
- isOpera = userAgent.indexOf("Opera/") !== -1;
-
- function iosVersion(userAgent) {
- return ((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [, 0])[1];
- }
-
- return {
- // Static variable needed, publicly accessible, to be able override it in unit tests
- USER_AGENT: userAgent,
-
- /**
- * Exclude browsers that are not capable of displaying and handling
- * contentEditable as desired:
- * - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable
- * - IE < 8 create invalid markup and crash randomly from time to time
- *
- * @return {Boolean}
- */
- supported: function() {
- var userAgent = this.USER_AGENT.toLowerCase(),
- // Essential for making html elements editable
- hasContentEditableSupport = "contentEditable" in testElement,
- // Following methods are needed in order to interact with the contentEditable area
- hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState,
- // document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+
- hasQuerySelectorSupport = document.querySelector && document.querySelectorAll,
- // contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05)
- isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1;
-
- return hasContentEditableSupport
- && hasEditingApiSupport
- && hasQuerySelectorSupport
- && !isIncompatibleMobileBrowser;
- },
-
- isTouchDevice: function() {
- return this.supportsEvent("touchmove");
- },
-
- isIos: function() {
- var userAgent = this.USER_AGENT.toLowerCase();
- return userAgent.indexOf("webkit") !== -1 && userAgent.indexOf("mobile") !== -1;
- },
-
- /**
- * Whether the browser supports sandboxed iframes
- * Currently only IE 6+ offers such feature <iframe security="restricted">
- *
- * http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx
- * http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx
- *
- * HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage)
- */
- supportsSandboxedIframes: function() {
- return isIE;
- },
-
- /**
- * IE6+7 throw a mixed content warning when the src of an iframe
- * is empty/unset or about:blank
- * window.querySelector is implemented as of IE8
- */
- throwsMixedContentWarningWhenIframeSrcIsEmpty: function() {
- return !("querySelector" in document);
- },
-
- /**
- * Whether the caret is correctly displayed in contentEditable elements
- * Firefox sometimes shows a huge caret in the beginning after focusing
- */
- displaysCaretInEmptyContentEditableCorrectly: function() {
- return !isGecko;
- },
-
- /**
- * Opera and IE are the only browsers who offer the css value
- * in the original unit, thx to the currentStyle object
- * All other browsers provide the computed style in px via window.getComputedStyle
- */
- hasCurrentStyleProperty: function() {
- return "currentStyle" in testElement;
- },
-
- /**
- * Whether the browser inserts a <br> when pressing enter in a contentEditable element
- */
- insertsLineBreaksOnReturn: function() {
- return isGecko;
- },
-
- supportsPlaceholderAttributeOn: function(element) {
- return "placeholder" in element;
- },
-
- supportsEvent: function(eventName) {
- return "on" + eventName in testElement || (function() {
- testElement.setAttribute("on" + eventName, "return;");
- return typeof(testElement["on" + eventName]) === "function";
- })();
- },
-
- /**
- * Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe
- */
- supportsEventsInIframeCorrectly: function() {
- return !isOpera;
- },
-
- /**
- * Chrome & Safari only fire the ondrop/ondragend/... events when the ondragover event is cancelled
- * with event.preventDefault
- * Firefox 3.6 fires those events anyway, but the mozilla doc says that the dragover/dragenter event needs
- * to be cancelled
- */
- firesOnDropOnlyWhenOnDragOverIsCancelled: function() {
- return isWebKit || isGecko;
- },
-
- /**
- * Whether the browser supports the event.dataTransfer property in a proper way
- */
- supportsDataTransfer: function() {
- try {
- // Firefox doesn't support dataTransfer in a safe way, it doesn't strip script code in the html payload (like Chrome does)
- return isWebKit && (window.Clipboard || window.DataTransfer).prototype.getData;
- } catch(e) {
- return false;
- }
- },
-
- /**
- * Everything below IE9 doesn't know how to treat HTML5 tags
- *
- * @param {Object} context The document object on which to check HTML5 support
- *
- * @example
- * wysihtml5.browser.supportsHTML5Tags(document);
- */
- supportsHTML5Tags: function(context) {
- var element = context.createElement("div"),
- html5 = "<article>foo</article>";
- element.innerHTML = html5;
- return element.innerHTML.toLowerCase() === html5;
- },
-
- /**
- * Checks whether a document supports a certain queryCommand
- * In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree
- * in oder to report correct results
- *
- * @param {Object} doc Document object on which to check for a query command
- * @param {String} command The query command to check for
- * @return {Boolean}
- *
- * @example
- * wysihtml5.browser.supportsCommand(document, "bold");
- */
- supportsCommand: (function() {
- // Following commands are supported but contain bugs in some browsers
- var buggyCommands = {
- // formatBlock fails with some tags (eg. <blockquote>)
- "formatBlock": isIE,
- // When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets
- // converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>)
- // IE and Opera act a bit different here as they convert the entire content of the current block element into a list
- "insertUnorderedList": isIE || isOpera || isWebKit,
- "insertOrderedList": isIE || isOpera || isWebKit
- };
-
- // Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands
- var supported = {
- "insertHTML": isGecko
- };
-
- return function(doc, command) {
- var isBuggy = buggyCommands[command];
- if (!isBuggy) {
- // Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled
- try {
- return doc.queryCommandSupported(command);
- } catch(e1) {}
-
- try {
- return doc.queryCommandEnabled(command);
- } catch(e2) {
- return !!supported[command];
- }
- }
- return false;
- };
- })(),
-
- /**
- * IE: URLs starting with:
- * www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://,
- * nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url:
- * will automatically be auto-linked when either the user inserts them via copy&paste or presses the
- * space bar when the caret is directly after such an url.
- * This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll
- * (related blog post on msdn
- * http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx).
- */
- doesAutoLinkingInContentEditable: function() {
- return isIE;
- },
-
- /**
- * As stated above, IE auto links urls typed into contentEditable elements
- * Since IE9 it's possible to prevent this behavior
- */
- canDisableAutoLinking: function() {
- return this.supportsCommand(document, "AutoUrlDetect");
- },
-
- /**
- * IE leaves an empty paragraph in the contentEditable element after clearing it
- * Chrome/Safari sometimes an empty <div>
- */
- clearsContentEditableCorrectly: function() {
- return isGecko || isOpera || isWebKit;
- },
-
- /**
- * IE gives wrong results for getAttribute
- */
- supportsGetAttributeCorrectly: function() {
- var td = document.createElement("td");
- return td.getAttribute("rowspan") != "1";
- },
-
- /**
- * When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them.
- * Chrome and Safari both don't support this
- */
- canSelectImagesInContentEditable: function() {
- return isGecko || isIE || isOpera;
- },
-
- /**
- * When the caret is in an empty list (<ul><li>|</li></ul>) which is the first child in an contentEditable container
- * pressing backspace doesn't remove the entire list as done in other browsers
- */
- clearsListsInContentEditableCorrectly: function() {
- return isGecko || isIE || isWebKit;
- },
-
- /**
- * All browsers except Safari and Chrome automatically scroll the range/caret position into view
- */
- autoScrollsToCaret: function() {
- return !isWebKit;
- },
-
- /**
- * Check whether the browser automatically closes tags that don't need to be opened
- */
- autoClosesUnclosedTags: function() {
- var clonedTestElement = testElement.cloneNode(false),
- returnValue,
- innerHTML;
-
- clonedTestElement.innerHTML = "<p><div></div>";
- innerHTML = clonedTestElement.innerHTML.toLowerCase();
- returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>";
-
- // Cache result by overwriting current function
- this.autoClosesUnclosedTags = function() { return returnValue; };
-
- return returnValue;
- },
-
- /**
- * Whether the browser supports the native document.getElementsByClassName which returns live NodeLists
- */
- supportsNativeGetElementsByClassName: function() {
- return String(document.getElementsByClassName).indexOf("[native code]") !== -1;
- },
-
- /**
- * As of now (19.04.2011) only supported by Firefox 4 and Chrome
- * See https://developer.mozilla.org/en/DOM/Selection/modify
- */
- supportsSelectionModify: function() {
- return "getSelection" in window && "modify" in window.getSelection();
- },
-
- /**
- * Whether the browser supports the classList object for fast className manipulation
- * See https://developer.mozilla.org/en/DOM/element.classList
- */
- supportsClassList: function() {
- return "classList" in testElement;
- },
-
- /**
- * Opera needs a white space after a <br> in order to position the caret correctly
- */
- needsSpaceAfterLineBreak: function() {
- return isOpera;
- },
-
- /**
- * Whether the browser supports the speech api on the given element
- * See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/
- *
- * @example
- * var input = document.createElement("input");
- * if (wysihtml5.browser.supportsSpeechApiOn(input)) {
- * // ...
- * }
- */
- supportsSpeechApiOn: function(input) {
- var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [, 0];
- return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input);
- },
-
- /**
- * IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest
- * See https://connect.microsoft.com/ie/feedback/details/650112
- * or try the POC http://tifftiff.de/ie9_crash/
- */
- crashesWhenDefineProperty: function(property) {
- return isIE && (property === "XMLHttpRequest" || property === "XDomainRequest");
- },
-
- /**
- * IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element
- */
- doesAsyncFocus: function() {
- return isIE;
- },
-
- /**
- * In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document
- */
- hasProblemsSettingCaretAfterImg: function() {
- return isIE;
- },
-
- hasUndoInContextMenu: function() {
- return isGecko || isChrome || isOpera;
- }
- };
-})();wysihtml5.lang.array = function(arr) {
- return {
- /**
- * Check whether a given object exists in an array
- *
- * @example
- * wysihtml5.lang.array([1, 2]).contains(1);
- * // => true
- */
- contains: function(needle) {
- if (arr.indexOf) {
- return arr.indexOf(needle) !== -1;
- } else {
- for (var i=0, length=arr.length; i<length; i++) {
- if (arr[i] === needle) { return true; }
- }
- return false;
- }
- },
-
- /**
- * Substract one array from another
- *
- * @example
- * wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]);
- * // => [1, 2]
- */
- without: function(arrayToSubstract) {
- arrayToSubstract = wysihtml5.lang.array(arrayToSubstract);
- var newArr = [],
- i = 0,
- length = arr.length;
- for (; i<length; i++) {
- if (!arrayToSubstract.contains(arr[i])) {
- newArr.push(arr[i]);
- }
- }
- return newArr;
- },
-
- /**
- * Return a clean native array
- *
- * Following will convert a Live NodeList to a proper Array
- * @example
- * var childNodes = wysihtml5.lang.array(document.body.childNodes).get();
- */
- get: function() {
- var i = 0,
- length = arr.length,
- newArray = [];
- for (; i<length; i++) {
- newArray.push(arr[i]);
- }
- return newArray;
- }
- };
-};wysihtml5.lang.Dispatcher = Base.extend(
- /** @scope wysihtml5.lang.Dialog.prototype */ {
- observe: function(eventName, handler) {
- this.events = this.events || {};
- this.events[eventName] = this.events[eventName] || [];
- this.events[eventName].push(handler);
- return this;
- },
-
- on: function() {
- return this.observe.apply(this, wysihtml5.lang.array(arguments).get());
- },
-
- fire: function(eventName, payload) {
- this.events = this.events || {};
- var handlers = this.events[eventName] || [],
- i = 0;
- for (; i<handlers.length; i++) {
- handlers[i].call(this, payload);
- }
- return this;
- },
-
- stopObserving: function(eventName, handler) {
- this.events = this.events || {};
- var i = 0,
- handlers,
- newHandlers;
- if (eventName) {
- handlers = this.events[eventName] || [],
- newHandlers = [];
- for (; i<handlers.length; i++) {
- if (handlers[i] !== handler && handler) {
- newHandlers.push(handlers[i]);
- }
- }
- this.events[eventName] = newHandlers;
- } else {
- // Clean up all events
- this.events = {};
- }
- return this;
- }
-});wysihtml5.lang.object = function(obj) {
- return {
- /**
- * @example
- * wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get();
- * // => { foo: 1, bar: 2, baz: 3 }
- */
- merge: function(otherObj) {
- for (var i in otherObj) {
- obj[i] = otherObj[i];
- }
- return this;
- },
-
- get: function() {
- return obj;
- },
-
- /**
- * @example
- * wysihtml5.lang.object({ foo: 1 }).clone();
- * // => { foo: 1 }
- */
- clone: function() {
- var newObj = {},
- i;
- for (i in obj) {
- newObj[i] = obj[i];
- }
- return newObj;
- },
-
- /**
- * @example
- * wysihtml5.lang.object([]).isArray();
- * // => true
- */
- isArray: function() {
- return Object.prototype.toString.call(obj) === "[object Array]";
- }
- };
-};(function() {
- var WHITE_SPACE_START = /^\s+/,
- WHITE_SPACE_END = /\s+$/;
- wysihtml5.lang.string = function(str) {
- str = String(str);
- return {
- /**
- * @example
- * wysihtml5.lang.string(" foo ").trim();
- * // => "foo"
- */
- trim: function() {
- return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, "");
- },
-
- /**
- * @example
- * wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" });
- * // => "Hello Christopher"
- */
- interpolate: function(vars) {
- for (var i in vars) {
- str = this.replace("#{" + i + "}").by(vars[i]);
- }
- return str;
- },
-
- /**
- * @example
- * wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans");
- * // => "Hello Hans"
- */
- replace: function(search) {
- return {
- by: function(replace) {
- return str.split(search).join(replace);
- }
- }
- }
- };
- };
-})();/**
- * Find urls in descendant text nodes of an element and auto-links them
- * Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/
- *
- * @param {Element} element Container element in which to search for urls
- *
- * @example
- * <div id="text-container">Please click here: www.google.com</div>
- * <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script>
- */
-(function(wysihtml5) {
- var /**
- * Don't auto-link urls that are contained in the following elements:
- */
- IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]),
- /**
- * revision 1:
- * /(\S+\.{1}[^\s\,\.\!]+)/g
- *
- * revision 2:
- * /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim
- *
- * put this in the beginning if you don't wan't to match within a word
- * (^|[\>\(\{\[\s\>])
- */
- URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi,
- TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i,
- MAX_DISPLAY_LENGTH = 100,
- BRACKETS = { ")": "(", "]": "[", "}": "{" };
-
- function autoLink(element) {
- if (_hasParentThatShouldBeIgnored(element)) {
- return element;
- }
-
- if (element === element.ownerDocument.documentElement) {
- element = element.ownerDocument.body;
- }
-
- return _parseNode(element);
- }
-
- /**
- * This is basically a rebuild of
- * the rails auto_link_urls text helper
- */
- function _convertUrlsToLinks(str) {
- return str.replace(URL_REG_EXP, function(match, url) {
- var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "",
- opening = BRACKETS[punctuation];
- url = url.replace(TRAILING_CHAR_REG_EXP, "");
-
- if (url.split(opening).length > url.split(punctuation).length) {
- url = url + punctuation;
- punctuation = "";
- }
- var realUrl = url,
- displayUrl = url;
- if (url.length > MAX_DISPLAY_LENGTH) {
- displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "...";
- }
- // Add http prefix if necessary
- if (realUrl.substr(0, 4) === "www.") {
- realUrl = "http://" + realUrl;
- }
-
- return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation;
- });
- }
-
- /**
- * Creates or (if already cached) returns a temp element
- * for the given document object
- */
- function _getTempElement(context) {
- var tempElement = context._wysihtml5_tempElement;
- if (!tempElement) {
- tempElement = context._wysihtml5_tempElement = context.createElement("div");
- }
- return tempElement;
- }
-
- /**
- * Replaces the original text nodes with the newly auto-linked dom tree
- */
- function _wrapMatchesInNode(textNode) {
- var parentNode = textNode.parentNode,
- tempElement = _getTempElement(parentNode.ownerDocument);
-
- // We need to insert an empty/temporary <span /> to fix IE quirks
- // Elsewise IE would strip white space in the beginning
- tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(textNode.data);
- tempElement.removeChild(tempElement.firstChild);
-
- while (tempElement.firstChild) {
- // inserts tempElement.firstChild before textNode
- parentNode.insertBefore(tempElement.firstChild, textNode);
- }
- parentNode.removeChild(textNode);
- }
-
- function _hasParentThatShouldBeIgnored(node) {
- var nodeName;
- while (node.parentNode) {
- node = node.parentNode;
- nodeName = node.nodeName;
- if (IGNORE_URLS_IN.contains(nodeName)) {
- return true;
- } else if (nodeName === "body") {
- return false;
- }
- }
- return false;
- }
-
- function _parseNode(element) {
- if (IGNORE_URLS_IN.contains(element.nodeName)) {
- return;
- }
-
- if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) {
- _wrapMatchesInNode(element);
- return;
- }
-
- var childNodes = wysihtml5.lang.array(element.childNodes).get(),
- childNodesLength = childNodes.length,
- i = 0;
-
- for (; i<childNodesLength; i++) {
- _parseNode(childNodes[i]);
- }
-
- return element;
- }
-
- wysihtml5.dom.autoLink = autoLink;
-
- // Reveal url reg exp to the outside
- wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP;
-})(wysihtml5);(function(wysihtml5) {
- var supportsClassList = wysihtml5.browser.supportsClassList(),
- api = wysihtml5.dom;
-
- api.addClass = function(element, className) {
- if (supportsClassList) {
- return element.classList.add(className);
- }
- if (api.hasClass(element, className)) {
- return;
- }
- element.className += " " + className;
- };
-
- api.removeClass = function(element, className) {
- if (supportsClassList) {
- return element.classList.remove(className);
- }
-
- element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " ");
- };
-
- api.hasClass = function(element, className) {
- if (supportsClassList) {
- return element.classList.contains(className);
- }
-
- var elementClassName = element.className;
- return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
- };
-})(wysihtml5);
-wysihtml5.dom.contains = (function() {
- var documentElement = document.documentElement;
- if (documentElement.contains) {
- return function(container, element) {
- if (element.nodeType !== wysihtml5.ELEMENT_NODE) {
- element = element.parentNode;
- }
- return container !== element && container.contains(element);
- };
- } else if (documentElement.compareDocumentPosition) {
- return function(container, element) {
- // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition
- return !!(container.compareDocumentPosition(element) & 16);
- };
- }
-})();/**
- * Converts an HTML fragment/element into a unordered/ordered list
- *
- * @param {Element} element The element which should be turned into a list
- * @param {String} listType The list type in which to convert the tree (either "ul" or "ol")
- * @return {Element} The created list
- *
- * @example
- * <!-- Assume the following dom: -->
- * <span id="pseudo-list">
- * eminem<br>
- * dr. dre
- * <div>50 Cent</div>
- * </span>
- *
- * <script>
- * wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul");
- * </script>
- *
- * <!-- Will result in: -->
- * <ul>
- * <li>eminem</li>
- * <li>dr. dre</li>
- * <li>50 Cent</li>
- * </ul>
- */
-wysihtml5.dom.convertToList = (function() {
- function _createListItem(doc, list) {
- var listItem = doc.createElement("li");
- list.appendChild(listItem);
- return listItem;
- }
-
- function _createList(doc, type) {
- return doc.createElement(type);
- }
-
- function convertToList(element, listType) {
- if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") {
- // Already a list
- return element;
- }
-
- var doc = element.ownerDocument,
- list = _createList(doc, listType),
- lineBreaks = element.querySelectorAll("br"),
- lineBreaksLength = lineBreaks.length,
- childNodes,
- childNodesLength,
- childNode,
- lineBreak,
- parentNode,
- isBlockElement,
- isLineBreak,
- currentListItem,
- i;
-
- // First find <br> at the end of inline elements and move them behind them
- for (i=0; i<lineBreaksLength; i++) {
- lineBreak = lineBreaks[i];
- while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) {
- if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") {
- parentNode.removeChild(lineBreak);
- break;
- }
- wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode);
- }
- }
-
- childNodes = wysihtml5.lang.array(element.childNodes).get();
- childNodesLength = childNodes.length;
-
- for (i=0; i<childNodesLength; i++) {
- currentListItem = currentListItem || _createListItem(doc, list);
- childNode = childNodes[i];
- isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block";
- isLineBreak = childNode.nodeName === "BR";
-
- if (isBlockElement) {
- // Append blockElement to current <li> if empty, otherwise create a new one
- currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem;
- currentListItem.appendChild(childNode);
- currentListItem = null;
- continue;
- }
-
- if (isLineBreak) {
- // Only create a new list item in the next iteration when the current one has already content
- currentListItem = currentListItem.firstChild ? null : currentListItem;
- continue;
- }
-
- currentListItem.appendChild(childNode);
- }
-
- element.parentNode.replaceChild(list, element);
- return list;
- }
-
- return convertToList;
-})();/**
- * Copy a set of attributes from one element to another
- *
- * @param {Array} attributesToCopy List of attributes which should be copied
- * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to
- * copy the attributes from., this again returns an object which provides a method named "to" which can be invoked
- * with the element where to copy the attributes to (see example)
- *
- * @example
- * var textarea = document.querySelector("textarea"),
- * div = document.querySelector("div[contenteditable=true]"),
- * anotherDiv = document.querySelector("div.preview");
- * wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv);
- *
- */
-wysihtml5.dom.copyAttributes = function(attributesToCopy) {
- return {
- from: function(elementToCopyFrom) {
- return {
- to: function(elementToCopyTo) {
- var attribute,
- i = 0,
- length = attributesToCopy.length;
- for (; i<length; i++) {
- attribute = attributesToCopy[i];
- if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") {
- elementToCopyTo[attribute] = elementToCopyFrom[attribute];
- }
- }
- return { andTo: arguments.callee };
- }
- };
- }
- };
-};/**
- * Copy a set of styles from one element to another
- * Please note that this only works properly across browsers when the element from which to copy the styles
- * is in the dom
- *
- * Interesting article on how to copy styles
- *
- * @param {Array} stylesToCopy List of styles which should be copied
- * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to
- * copy the styles from., this again returns an object which provides a method named "to" which can be invoked
- * with the element where to copy the styles to (see example)
- *
- * @example
- * var textarea = document.querySelector("textarea"),
- * div = document.querySelector("div[contenteditable=true]"),
- * anotherDiv = document.querySelector("div.preview");
- * wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv);
- *
- */
-(function(dom) {
-
- /**
- * Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set
- * So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then
- * its computed css width will be 198px
- */
- var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"];
-
- var shouldIgnoreBoxSizingBorderBox = function(element) {
- if (hasBoxSizingBorderBox(element)) {
- return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth;
- }
- return false;
- };
-
- var hasBoxSizingBorderBox = function(element) {
- var i = 0,
- length = BOX_SIZING_PROPERTIES.length;
- for (; i<length; i++) {
- if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") {
- return BOX_SIZING_PROPERTIES[i];
- }
- }
- };
-
- dom.copyStyles = function(stylesToCopy) {
- return {
- from: function(element) {
- if (shouldIgnoreBoxSizingBorderBox(element)) {
- stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES);
- }
-
- var cssText = "",
- length = stylesToCopy.length,
- i = 0,
- property;
- for (; i<length; i++) {
- property = stylesToCopy[i];
- cssText += property + ":" + dom.getStyle(property).from(element) + ";";
- }
-
- return {
- to: function(element) {
- dom.setStyles(cssText).on(element);
- return { andTo: arguments.callee };
- }
- };
- }
- };
- };
-})(wysihtml5.dom);/**
- * Event Delegation
- *
- * @example
- * wysihtml5.dom.delegate(document.body, "a", "click", function() {
- * // foo
- * });
- */
-(function(wysihtml5) {
-
- wysihtml5.dom.delegate = function(container, selector, eventName, handler) {
- return wysihtml5.dom.observe(container, eventName, function(event) {
- var target = event.target,
- match = wysihtml5.lang.array(container.querySelectorAll(selector));
-
- while (target && target !== container) {
- if (match.contains(target)) {
- handler.call(target, event);
- break;
- }
- target = target.parentNode;
- }
- });
- };
-
-})(wysihtml5);/**
- * Returns the given html wrapped in a div element
- *
- * Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly
- * when inserted via innerHTML
- *
- * @param {String} html The html which should be wrapped in a dom element
- * @param {Obejct} [context] Document object of the context the html belongs to
- *
- * @example
- * wysihtml5.dom.getAsDom("<article>foo</article>");
- */
-wysihtml5.dom.getAsDom = (function() {
-
- var _innerHTMLShiv = function(html, context) {
- var tempElement = context.createElement("div");
- tempElement.style.display = "none";
- context.body.appendChild(tempElement);
- // IE throws an exception when trying to insert <frameset></frameset> via innerHTML
- try { tempElement.innerHTML = html; } catch(e) {}
- context.body.removeChild(tempElement);
- return tempElement;
- };
-
- /**
- * Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element
- */
- var _ensureHTML5Compatibility = function(context) {
- if (context._wysihtml5_supportsHTML5Tags) {
- return;
- }
- for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) {
- context.createElement(HTML5_ELEMENTS[i]);
- }
- context._wysihtml5_supportsHTML5Tags = true;
- };
-
-
- /**
- * List of html5 tags
- * taken from http://simon.html5.org/html5-elements
- */
- var HTML5_ELEMENTS = [
- "abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption",
- "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress",
- "rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr"
- ];
-
- return function(html, context) {
- context = context || document;
- var tempElement;
- if (typeof(html) === "object" && html.nodeType) {
- tempElement = context.createElement("div");
- tempElement.appendChild(html);
- } else if (wysihtml5.browser.supportsHTML5Tags(context)) {
- tempElement = context.createElement("div");
- tempElement.innerHTML = html;
- } else {
- _ensureHTML5Compatibility(context);
- tempElement = _innerHTMLShiv(html, context);
- }
- return tempElement;
- };
-})();/**
- * Walks the dom tree from the given node up until it finds a match
- * Designed for optimal performance.
- *
- * @param {Element} node The from which to check the parent nodes
- * @param {Object} matchingSet Object to match against (possible properties: nodeName, className, classRegExp)
- * @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50)
- * @return {null|Element} Returns the first element that matched the desiredNodeName(s)
- * @example
- * var listElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: ["MENU", "UL", "OL"] });
- * // ... or ...
- * var unorderedListElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: "UL" });
- * // ... or ...
- * var coloredElement = wysihtml5.dom.getParentElement(myTextNode, { nodeName: "SPAN", className: "wysiwyg-color-red", classRegExp: /wysiwyg-color-[a-z]/g });
- */
-wysihtml5.dom.getParentElement = (function() {
-
- function _isSameNodeName(nodeName, desiredNodeNames) {
- if (!desiredNodeNames || !desiredNodeNames.length) {
- return true;
- }
-
- if (typeof(desiredNodeNames) === "string") {
- return nodeName === desiredNodeNames;
- } else {
- return wysihtml5.lang.array(desiredNodeNames).contains(nodeName);
- }
- }
-
- function _isElement(node) {
- return node.nodeType === wysihtml5.ELEMENT_NODE;
- }
-
- function _hasClassName(element, className, classRegExp) {
- var classNames = (element.className || "").match(classRegExp) || [];
- if (!className) {
- return !!classNames.length;
- }
- return classNames[classNames.length - 1] === className;
- }
-
- function _getParentElementWithNodeName(node, nodeName, levels) {
- while (levels-- && node && node.nodeName !== "BODY") {
- if (_isSameNodeName(node.nodeName, nodeName)) {
- return node;
- }
- node = node.parentNode;
- }
- return null;
- }
-
- function _getParentElementWithNodeNameAndClassName(node, nodeName, className, classRegExp, levels) {
- while (levels-- && node && node.nodeName !== "BODY") {
- if (_isElement(node) &&
- _isSameNodeName(node.nodeName, nodeName) &&
- _hasClassName(node, className, classRegExp)) {
- return node;
- }
- node = node.parentNode;
- }
- return null;
- }
-
- return function(node, matchingSet, levels) {
- levels = levels || 50; // Go max 50 nodes upwards from current node
- if (matchingSet.className || matchingSet.classRegExp) {
- return _getParentElementWithNodeNameAndClassName(
- node, matchingSet.nodeName, matchingSet.className, matchingSet.classRegExp, levels
- );
- } else {
- return _getParentElementWithNodeName(
- node, matchingSet.nodeName, levels
- );
- }
- };
-})();
-/**
- * Get element's style for a specific css property
- *
- * @param {Element} element The element on which to retrieve the style
- * @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...)
- *
- * @example
- * wysihtml5.dom.getStyle("display").from(document.body);
- * // => "block"
- */
-wysihtml5.dom.getStyle = (function() {
- var stylePropertyMapping = {
- "float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat"
- },
- REG_EXP_CAMELIZE = /\-[a-z]/g;
-
- function camelize(str) {
- return str.replace(REG_EXP_CAMELIZE, function(match) {
- return match.charAt(1).toUpperCase();
- });
- }
-
- return function(property) {
- return {
- from: function(element) {
- if (element.nodeType !== wysihtml5.ELEMENT_NODE) {
- return;
- }
-
- var doc = element.ownerDocument,
- camelizedProperty = stylePropertyMapping[property] || camelize(property),
- style = element.style,
- currentStyle = element.currentStyle,
- styleValue = style[camelizedProperty];
- if (styleValue) {
- return styleValue;
- }
-
- // currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant
- // window.getComputedStyle, since it returns css property values in their original unit:
- // If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle
- // gives you the original "50%".
- // Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio
- if (currentStyle) {
- try {
- return currentStyle[camelizedProperty];
- } catch(e) {
- //ie will occasionally fail for unknown reasons. swallowing exception
- }
- }
-
- var win = doc.defaultView || doc.parentWindow,
- needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA",
- originalOverflow,
- returnValue;
-
- if (win.getComputedStyle) {
- // Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars
- // therfore we remove and restore the scrollbar and calculate the value in between
- if (needsOverflowReset) {
- originalOverflow = style.overflow;
- style.overflow = "hidden";
- }
- returnValue = win.getComputedStyle(element, null).getPropertyValue(property);
- if (needsOverflowReset) {
- style.overflow = originalOverflow || "";
- }
- return returnValue;
- }
- }
- };
- };
-})();/**
- * High performant way to check whether an element with a specific tag name is in the given document
- * Optimized for being heavily executed
- * Unleashes the power of live node lists
- *
- * @param {Object} doc The document object of the context where to check
- * @param {String} tagName Upper cased tag name
- * @example
- * wysihtml5.dom.hasElementWithTagName(document, "IMG");
- */
-wysihtml5.dom.hasElementWithTagName = (function() {
- var LIVE_CACHE = {},
- DOCUMENT_IDENTIFIER = 1;
-
- function _getDocumentIdentifier(doc) {
- return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
- }
-
- return function(doc, tagName) {
- var key = _getDocumentIdentifier(doc) + ":" + tagName,
- cacheEntry = LIVE_CACHE[key];
- if (!cacheEntry) {
- cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName);
- }
-
- return cacheEntry.length > 0;
- };
-})();/**
- * High performant way to check whether an element with a specific class name is in the given document
- * Optimized for being heavily executed
- * Unleashes the power of live node lists
- *
- * @param {Object} doc The document object of the context where to check
- * @param {String} tagName Upper cased tag name
- * @example
- * wysihtml5.dom.hasElementWithClassName(document, "foobar");
- */
-(function(wysihtml5) {
- var LIVE_CACHE = {},
- DOCUMENT_IDENTIFIER = 1;
-
- function _getDocumentIdentifier(doc) {
- return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
- }
-
- wysihtml5.dom.hasElementWithClassName = function(doc, className) {
- // getElementsByClassName is not supported by IE<9
- // but is sometimes mocked via library code (which then doesn't return live node lists)
- if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) {
- return !!doc.querySelector("." + className);
- }
-
- var key = _getDocumentIdentifier(doc) + ":" + className,
- cacheEntry = LIVE_CACHE[key];
- if (!cacheEntry) {
- cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className);
- }
-
- return cacheEntry.length > 0;
- };
-})(wysihtml5);
-wysihtml5.dom.insert = function(elementToInsert) {
- return {
- after: function(element) {
- element.parentNode.insertBefore(elementToInsert, element.nextSibling);
- },
-
- before: function(element) {
- element.parentNode.insertBefore(elementToInsert, element);
- },
-
- into: function(element) {
- element.appendChild(elementToInsert);
- }
- };
-};wysihtml5.dom.insertCSS = function(rules) {
- rules = rules.join("\n");
-
- return {
- into: function(doc) {
- var head = doc.head || doc.getElementsByTagName("head")[0],
- styleElement = doc.createElement("style");
-
- styleElement.type = "text/css";
-
- if (styleElement.styleSheet) {
- styleElement.styleSheet.cssText = rules;
- } else {
- styleElement.appendChild(doc.createTextNode(rules));
- }
-
- if (head) {
- head.appendChild(styleElement);
- }
- }
- };
-};/**
- * Method to set dom events
- *
- * @example
- * wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... });
- */
-wysihtml5.dom.observe = function(element, eventNames, handler) {
- eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames;
-
- var handlerWrapper,
- eventName,
- i = 0,
- length = eventNames.length;
-
- for (; i<length; i++) {
- eventName = eventNames[i];
- if (element.addEventListener) {
- element.addEventListener(eventName, handler, false);
- } else {
- handlerWrapper = function(event) {
- if (!("target" in event)) {
- event.target = event.srcElement;
- }
- event.preventDefault = event.preventDefault || function() {
- this.returnValue = false;
- };
- event.stopPropagation = event.stopPropagation || function() {
- this.cancelBubble = true;
- };
- handler.call(element, event);
- };
- element.attachEvent("on" + eventName, handlerWrapper);
- }
- }
-
- return {
- stop: function() {
- var eventName,
- i = 0,
- length = eventNames.length;
- for (; i<length; i++) {
- eventName = eventNames[i];
- if (element.removeEventListener) {
- element.removeEventListener(eventName, handler, false);
- } else {
- element.detachEvent("on" + eventName, handlerWrapper);
- }
- }
- }
- };
-};
-/**
- * HTML Sanitizer
- * Rewrites the HTML based on given rules
- *
- * @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized
- * @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will
- * be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the
- * desired substitution.
- * @param {Object} context Document object in which to parse the html, needed to sandbox the parsing
- *
- * @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element.
- *
- * @example
- * var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>';
- * wysihtml5.dom.parse(userHTML, {
- * tags {
- * p: "div", // Rename p tags to div tags
- * font: "span" // Rename font tags to span tags
- * div: true, // Keep them, also possible (same result when passing: "div" or true)
- * script: undefined // Remove script elements
- * }
- * });
- * // => <div><div><span>foo bar</span></div></div>
- *
- * var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>';
- * wysihtml5.dom.parse(userHTML);
- * // => '<span><span><span><span>I'm a table!</span></span></span></span>'
- *
- * var userHTML = '<div>foobar<br>foobar</div>';
- * wysihtml5.dom.parse(userHTML, {
- * tags: {
- * div: undefined,
- * br: true
- * }
- * });
- * // => ''
- *
- * var userHTML = '<div class="red">foo</div><div class="pink">bar</div>';
- * wysihtml5.dom.parse(userHTML, {
- * classes: {
- * red: 1,
- * green: 1
- * },
- * tags: {
- * div: {
- * rename_tag: "p"
- * }
- * }
- * });
- * // => '<p class="red">foo</p><p>bar</p>'
- */
-wysihtml5.dom.parse = (function() {
-
- /**
- * It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML
- * new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the
- * node isn't closed
- *
- * Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML.
- */
- var NODE_TYPE_MAPPING = {
- "1": _handleElement,
- "3": _handleText
- },
- // Rename unknown tags to this
- DEFAULT_NODE_NAME = "span",
- WHITE_SPACE_REG_EXP = /\s+/,
- defaultRules = { tags: {}, classes: {} },
- currentRules = {};
-
- /**
- * Iterates over all childs of the element, recreates them, appends them into a document fragment
- * which later replaces the entire body content
- */
- function parse(elementOrHtml, rules, context, cleanUp) {
- wysihtml5.lang.object(currentRules).merge(defaultRules).merge(rules).get();
-
- context = context || elementOrHtml.ownerDocument || document;
- var fragment = context.createDocumentFragment(),
- isString = typeof(elementOrHtml) === "string",
- element,
- newNode,
- firstChild;
-
- if (isString) {
- element = wysihtml5.dom.getAsDom(elementOrHtml, context);
- } else {
- element = elementOrHtml;
- }
-
- while (element.firstChild) {
- firstChild = element.firstChild;
- element.removeChild(firstChild);
- newNode = _convert(firstChild, cleanUp);
- if (newNode) {
- fragment.appendChild(newNode);
- }
- }
-
- // Clear element contents
- element.innerHTML = "";
-
- // Insert new DOM tree
- element.appendChild(fragment);
-
- return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element;
- }
-
- function _convert(oldNode, cleanUp) {
- var oldNodeType = oldNode.nodeType,
- oldChilds = oldNode.childNodes,
- oldChildsLength = oldChilds.length,
- newNode,
- method = NODE_TYPE_MAPPING[oldNodeType],
- i = 0;
-
- newNode = method && method(oldNode);
-
- if (!newNode) {
- return null;
- }
-
- for (i=0; i<oldChildsLength; i++) {
- newChild = _convert(oldChilds[i], cleanUp);
- if (newChild) {
- newNode.appendChild(newChild);
- }
- }
-
- // Cleanup senseless <span> elements
- if (cleanUp &&
- newNode.childNodes.length <= 1 &&
- newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME &&
- !newNode.attributes.length) {
- return newNode.firstChild;
- }
-
- return newNode;
- }
-
- function _handleElement(oldNode) {
- var rule,
- newNode,
- endTag,
- tagRules = currentRules.tags,
- nodeName = oldNode.nodeName.toLowerCase(),
- scopeName = oldNode.scopeName;
-
- /**
- * We already parsed that element
- * ignore it! (yes, this sometimes happens in IE8 when the html is invalid)
- */
- if (oldNode._wysihtml5) {
- return null;
- }
- oldNode._wysihtml5 = 1;
-
- if (oldNode.className === "wysihtml5-temp") {
- return null;
- }
-
- /**
- * IE is the only browser who doesn't include the namespace in the
- * nodeName, that's why we have to prepend it by ourselves
- * scopeName is a proprietary IE feature
- * read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx
- */
- if (scopeName && scopeName != "HTML") {
- nodeName = scopeName + ":" + nodeName;
- }
-
- /**
- * Repair node
- * IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags
- * A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout
- */
- if ("outerHTML" in oldNode) {
- if (!wysihtml5.browser.autoClosesUnclosedTags() &&
- oldNode.nodeName === "P" &&
- oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") {
- nodeName = "div";
- }
- }
-
- if (nodeName in tagRules) {
- rule = tagRules[nodeName];
- if (!rule || rule.remove) {
- return null;
- }
-
- rule = typeof(rule) === "string" ? { rename_tag: rule } : rule;
- } else if (oldNode.firstChild) {
- rule = { rename_tag: DEFAULT_NODE_NAME };
- } else {
- // Remove empty unknown elements
- return null;
- }
-
- newNode = oldNode.ownerDocument.createElement(rule.rename_tag || nodeName);
- _handleAttributes(oldNode, newNode, rule);
-
- oldNode = null;
- return newNode;
- }
-
- function _handleAttributes(oldNode, newNode, rule) {
- var attributes = {}, // fresh new set of attributes to set on newNode
- setClass = rule.set_class, // classes to set
- addClass = rule.add_class, // add classes based on existing attributes
- setAttributes = rule.set_attributes, // attributes to set on the current node
- checkAttributes = rule.check_attributes, // check/convert values of attributes
- allowedClasses = currentRules.classes,
- i = 0,
- classes = [],
- newClasses = [],
- newUniqueClasses = [],
- oldClasses = [],
- classesLength,
- newClassesLength,
- currentClass,
- newClass,
- attributeName,
- newAttributeValue,
- method;
-
- if (setAttributes) {
- attributes = wysihtml5.lang.object(setAttributes).clone();
- }
-
- if (checkAttributes) {
- for (attributeName in checkAttributes) {
- method = attributeCheckMethods[checkAttributes[attributeName]];
- if (!method) {
- continue;
- }
- newAttributeValue = method(_getAttribute(oldNode, attributeName));
- if (typeof(newAttributeValue) === "string") {
- attributes[attributeName] = newAttributeValue;
- }
- }
- }
-
- if (setClass) {
- classes.push(setClass);
- }
-
- if (addClass) {
- for (attributeName in addClass) {
- method = addClassMethods[addClass[attributeName]];
- if (!method) {
- continue;
- }
- newClass = method(_getAttribute(oldNode, attributeName));
- if (typeof(newClass) === "string") {
- classes.push(newClass);
- }
- }
- }
-
- // make sure that wysihtml5 temp class doesn't get stripped out
- allowedClasses["_wysihtml5-temp-placeholder"] = 1;
-
- // add old classes last
- oldClasses = oldNode.getAttribute("class");
- if (oldClasses) {
- classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP));
- }
- classesLength = classes.length;
- for (; i<classesLength; i++) {
- currentClass = classes[i];
- if (allowedClasses[currentClass]) {
- newClasses.push(currentClass);
- }
- }
-
- // remove duplicate entries and preserve class specificity
- newClassesLength = newClasses.length;
- while (newClassesLength--) {
- currentClass = newClasses[newClassesLength];
- if (!wysihtml5.lang.array(newUniqueClasses).contains(currentClass)) {
- newUniqueClasses.unshift(currentClass);
- }
- }
-
- if (newUniqueClasses.length) {
- attributes["class"] = newUniqueClasses.join(" ");
- }
-
- // set attributes on newNode
- for (attributeName in attributes) {
- // Setting attributes can cause a js error in IE under certain circumstances
- // eg. on a <img> under https when it's new attribute value is non-https
- // TODO: Investigate this further and check for smarter handling
- try {
- newNode.setAttribute(attributeName, attributes[attributeName]);
- } catch(e) {}
- }
-
- // IE8 sometimes loses the width/height attributes when those are set before the "src"
- // so we make sure to set them again
- if (attributes.src) {
- if (typeof(attributes.width) !== "undefined") {
- newNode.setAttribute("width", attributes.width);
- }
- if (typeof(attributes.height) !== "undefined") {
- newNode.setAttribute("height", attributes.height);
- }
- }
- }
-
- /**
- * IE gives wrong results for hasAttribute/getAttribute, for example:
- * var td = document.createElement("td");
- * td.getAttribute("rowspan"); // => "1" in IE
- *
- * Therefore we have to check the element's outerHTML for the attribute
- */
- var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly();
- function _getAttribute(node, attributeName) {
- attributeName = attributeName.toLowerCase();
- var nodeName = node.nodeName;
- if (nodeName == "IMG" && attributeName == "src" && _isLoadedImage(node) === true) {
- // Get 'src' attribute value via object property since this will always contain the
- // full absolute url (http://...)
- // this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host
- // will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url)
- return node.src;
- } else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) {
- // Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML
- var outerHTML = node.outerHTML.toLowerCase(),
- // TODO: This might not work for attributes without value: <input disabled>
- hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1;
-
- return hasAttribute ? node.getAttribute(attributeName) : null;
- } else{
- return node.getAttribute(attributeName);
- }
- }
-
- /**
- * Check whether the given node is a proper loaded image
- * FIXME: Returns undefined when unknown (Chrome, Safari)
- */
- function _isLoadedImage(node) {
- try {
- return node.complete && !node.mozMatchesSelector(":-moz-broken");
- } catch(e) {
- if (node.complete && node.readyState === "complete") {
- return true;
- }
- }
- }
-
- function _handleText(oldNode) {
- return oldNode.ownerDocument.createTextNode(oldNode.data);
- }
-
-
- // ------------ attribute checks ------------ \\
- var attributeCheckMethods = {
- url: (function() {
- var REG_EXP = /^https?:\/\//i;
- return function(attributeValue) {
- if (!attributeValue || !attributeValue.match(REG_EXP)) {
- return null;
- }
- return attributeValue.replace(REG_EXP, function(match) {
- return match.toLowerCase();
- });
- };
- })(),
-
- alt: (function() {
- var REG_EXP = /[^ a-z0-9_\-]/gi;
- return function(attributeValue) {
- if (!attributeValue) {
- return "";
- }
- return attributeValue.replace(REG_EXP, "");
- };
- })(),
-
- numbers: (function() {
- var REG_EXP = /\D/g;
- return function(attributeValue) {
- attributeValue = (attributeValue || "").replace(REG_EXP, "");
- return attributeValue || null;
- };
- })()
- };
-
- // ------------ class converter (converts an html attribute to a class name) ------------ \\
- var addClassMethods = {
- align_img: (function() {
- var mapping = {
- left: "wysiwyg-float-left",
- right: "wysiwyg-float-right"
- };
- return function(attributeValue) {
- return mapping[String(attributeValue).toLowerCase()];
- };
- })(),
-
- align_text: (function() {
- var mapping = {
- left: "wysiwyg-text-align-left",
- right: "wysiwyg-text-align-right",
- center: "wysiwyg-text-align-center",
- justify: "wysiwyg-text-align-justify"
- };
- return function(attributeValue) {
- return mapping[String(attributeValue).toLowerCase()];
- };
- })(),
-
- clear_br: (function() {
- var mapping = {
- left: "wysiwyg-clear-left",
- right: "wysiwyg-clear-right",
- both: "wysiwyg-clear-both",
- all: "wysiwyg-clear-both"
- };
- return function(attributeValue) {
- return mapping[String(attributeValue).toLowerCase()];
- };
- })(),
-
- size_font: (function() {
- var mapping = {
- "1": "wysiwyg-font-size-xx-small",
- "2": "wysiwyg-font-size-small",
- "3": "wysiwyg-font-size-medium",
- "4": "wysiwyg-font-size-large",
- "5": "wysiwyg-font-size-x-large",
- "6": "wysiwyg-font-size-xx-large",
- "7": "wysiwyg-font-size-xx-large",
- "-": "wysiwyg-font-size-smaller",
- "+": "wysiwyg-font-size-larger"
- };
- return function(attributeValue) {
- return mapping[String(attributeValue).charAt(0)];
- };
- })()
- };
-
- return parse;
-})();/**
- * Checks for empty text node childs and removes them
- *
- * @param {Element} node The element in which to cleanup
- * @example
- * wysihtml5.dom.removeEmptyTextNodes(element);
- */
-wysihtml5.dom.removeEmptyTextNodes = function(node) {
- var childNode,
- childNodes = wysihtml5.lang.array(node.childNodes).get(),
- childNodesLength = childNodes.length,
- i = 0;
- for (; i<childNodesLength; i++) {
- childNode = childNodes[i];
- if (childNode.nodeType === wysihtml5.TEXT_NODE && childNode.data === "") {
- childNode.parentNode.removeChild(childNode);
- }
- }
-};
-/**
- * Renames an element (eg. a <div> to a <p>) and keeps its childs
- *
- * @param {Element} element The list element which should be renamed
- * @param {Element} newNodeName The desired tag name
- *
- * @example
- * <!-- Assume the following dom: -->
- * <ul id="list">
- * <li>eminem</li>
- * <li>dr. dre</li>
- * <li>50 Cent</li>
- * </ul>
- *
- * <script>
- * wysihtml5.dom.renameElement(document.getElementById("list"), "ol");
- * </script>
- *
- * <!-- Will result in: -->
- * <ol>
- * <li>eminem</li>
- * <li>dr. dre</li>
- * <li>50 Cent</li>
- * </ol>
- */
-wysihtml5.dom.renameElement = function(element, newNodeName) {
- var newElement = element.ownerDocument.createElement(newNodeName),
- firstChild;
- while (firstChild = element.firstChild) {
- newElement.appendChild(firstChild);
- }
- wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement);
- element.parentNode.replaceChild(newElement, element);
- return newElement;
-};/**
- * Takes an element, removes it and replaces it with it's childs
- *
- * @param {Object} node The node which to replace with it's child nodes
- * @example
- * <div id="foo">
- * <span>hello</span>
- * </div>
- * <script>
- * // Remove #foo and replace with it's children
- * wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo"));
- * </script>
- */
-wysihtml5.dom.replaceWithChildNodes = function(node) {
- if (!node.parentNode) {
- return;
- }
-
- if (!node.firstChild) {
- node.parentNode.removeChild(node);
- return;
- }
-
- var fragment = node.ownerDocument.createDocumentFragment();
- while (node.firstChild) {
- fragment.appendChild(node.firstChild);
- }
- node.parentNode.replaceChild(fragment, node);
- node = fragment = null;
-};
-/**
- * Unwraps an unordered/ordered list
- *
- * @param {Element} element The list element which should be unwrapped
- *
- * @example
- * <!-- Assume the following dom: -->
- * <ul id="list">
- * <li>eminem</li>
- * <li>dr. dre</li>
- * <li>50 Cent</li>
- * </ul>
- *
- * <script>
- * wysihtml5.dom.resolveList(document.getElementById("list"));
- * </script>
- *
- * <!-- Will result in: -->
- * eminem<br>
- * dr. dre<br>
- * 50 Cent<br>
- */
-(function(dom) {
- function _isBlockElement(node) {
- return dom.getStyle("display").from(node) === "block";
- }
-
- function _isLineBreak(node) {
- return node.nodeName === "BR";
- }
-
- function _appendLineBreak(element) {
- var lineBreak = element.ownerDocument.createElement("br");
- element.appendChild(lineBreak);
- }
-
- function resolveList(list) {
- if (list.nodeName !== "MENU" && list.nodeName !== "UL" && list.nodeName !== "OL") {
- return;
- }
-
- var doc = list.ownerDocument,
- fragment = doc.createDocumentFragment(),
- previousSibling = list.previousElementSibling || list.previousSibling,
- firstChild,
- lastChild,
- isLastChild,
- shouldAppendLineBreak,
- listItem;
-
- if (previousSibling && !_isBlockElement(previousSibling)) {
- _appendLineBreak(fragment);
- }
-
- while (listItem = list.firstChild) {
- lastChild = listItem.lastChild;
- while (firstChild = listItem.firstChild) {
- isLastChild = firstChild === lastChild;
- // This needs to be done before appending it to the fragment, as it otherwise will loose style information
- shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild);
- fragment.appendChild(firstChild);
- if (shouldAppendLineBreak) {
- _appendLineBreak(fragment);
- }
- }
-
- listItem.parentNode.removeChild(listItem);
- }
- list.parentNode.replaceChild(fragment, list);
- }
-
- dom.resolveList = resolveList;
-})(wysihtml5.dom);/**
- * Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way
- *
- * Browser Compatibility:
- * - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted"
- * - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...)
- *
- * Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons:
- * - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'")
- * - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...)
- * - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire
- * - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe
- * can do anything as if the sandbox attribute wasn't set
- *
- * @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready
- * @param {Object} [config] Optional parameters
- *
- * @example
- * new wysihtml5.dom.Sandbox(function(sandbox) {
- * sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">';
- * });
- */
-(function(wysihtml5) {
- var /**
- * Default configuration
- */
- doc = document,
- /**
- * Properties to unset/protect on the window object
- */
- windowProperties = [
- "parent", "top", "opener", "frameElement", "frames",
- "localStorage", "globalStorage", "sessionStorage", "indexedDB"
- ],
- /**
- * Properties on the window object which are set to an empty function
- */
- windowProperties2 = [
- "open", "close", "openDialog", "showModalDialog",
- "alert", "confirm", "prompt",
- "openDatabase", "postMessage",
- "XMLHttpRequest", "XDomainRequest"
- ],
- /**
- * Properties to unset/protect on the document object
- */
- documentProperties = [
- "referrer",
- "write", "open", "close"
- ];
-
- wysihtml5.dom.Sandbox = Base.extend(
- /** @scope wysihtml5.dom.Sandbox.prototype */ {
-
- constructor: function(readyCallback, config) {
- this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION;
- this.config = wysihtml5.lang.object({}).merge(config).get();
- this.iframe = this._createIframe();
- },
-
- insertInto: function(element) {
- if (typeof(element) === "string") {
- element = doc.getElementById(element);
- }
-
- element.appendChild(this.iframe);
- },
-
- getIframe: function() {
- return this.iframe;
- },
-
- getWindow: function() {
- this._readyError();
- },
-
- getDocument: function() {
- this._readyError();
- },
-
- destroy: function() {
- var iframe = this.getIframe();
- iframe.parentNode.removeChild(iframe);
- },
-
- _readyError: function() {
- throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet");
- },
-
- /**
- * Creates the sandbox iframe
- *
- * Some important notes:
- * - We can't use HTML5 sandbox for now:
- * setting it causes that the iframe's dom can't be accessed from the outside
- * Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom
- * But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired.
- * In order to make this happen we need to set the "allow-scripts" flag.
- * A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all.
- * - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document)
- * - IE needs to have the security="restricted" attribute set before the iframe is
- * inserted into the dom tree
- * - Believe it or not but in IE "security" in document.createElement("iframe") is false, even
- * though it supports it
- * - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore
- * - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely
- * on the onreadystatechange event
- */
- _createIframe: function() {
- var that = this,
- iframe = doc.createElement("iframe");
- iframe.className = "wysihtml5-sandbox";
- wysihtml5.dom.setAttributes({
- "security": "restricted",
- "allowtransparency": "true",
- "frameborder": 0,
- "width": 0,
- "height": 0,
- "marginwidth": 0,
- "marginheight": 0
- }).on(iframe);
-
- // Setting the src like this prevents ssl warnings in IE6
- if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) {
- iframe.src = "javascript:'<html></html>'";
- }
-
- iframe.onload = function() {
- iframe.onreadystatechange = iframe.onload = null;
- that._onLoadIframe(iframe);
- };
-
- iframe.onreadystatechange = function() {
- if (/loaded|complete/.test(iframe.readyState)) {
- iframe.onreadystatechange = iframe.onload = null;
- that._onLoadIframe(iframe);
- }
- };
-
- return iframe;
- },
-
- /**
- * Callback for when the iframe has finished loading
- */
- _onLoadIframe: function(iframe) {
- // don't resume when the iframe got unloaded (eg. by removing it from the dom)
- if (!wysihtml5.dom.contains(doc.documentElement, iframe)) {
- return;
- }
-
- var that = this,
- iframeWindow = iframe.contentWindow,
- iframeDocument = iframe.contentWindow.document,
- charset = doc.characterSet || doc.charset || "utf-8",
- sandboxHtml = this._getHtml({
- charset: charset,
- stylesheets: this.config.stylesheets
- });
-
- // Create the basic dom tree including proper DOCTYPE and charset
- iframeDocument.open("text/html", "replace");
- iframeDocument.write(sandboxHtml);
- iframeDocument.close();
-
- this.getWindow = function() { return iframe.contentWindow; };
- this.getDocument = function() { return iframe.contentWindow.document; };
-
- // Catch js errors and pass them to the parent's onerror event
- // addEventListener("error") doesn't work properly in some browsers
- // TODO: apparently this doesn't work in IE9!
- iframeWindow.onerror = function(errorMessage, fileName, lineNumber) {
- throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber);
- };
-
- if (!wysihtml5.browser.supportsSandboxedIframes()) {
- // Unset a bunch of sensitive variables
- // Please note: This isn't hack safe!
- // It more or less just takes care of basic attacks and prevents accidental theft of sensitive information
- // IE is secure though, which is the most important thing, since IE is the only browser, who
- // takes over scripts & styles into contentEditable elements when copied from external websites
- // or applications (Microsoft Word, ...)
- var i, length;
- for (i=0, length=windowProperties.length; i<length; i++) {
- this._unset(iframeWindow, windowProperties[i]);
- }
- for (i=0, length=windowProperties2.length; i<length; i++) {
- this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION);
- }
- for (i=0, length=documentProperties.length; i<length; i++) {
- this._unset(iframeDocument, documentProperties[i]);
- }
- // This doesn't work in Safari 5
- // See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit
- this._unset(iframeDocument, "cookie", "", true);
- }
-
- this.loaded = true;
-
- // Trigger the callback
- setTimeout(function() { that.callback(that); }, 0);
- },
-
- _getHtml: function(templateVars) {
- var stylesheets = templateVars.stylesheets,
- html = "",
- i = 0,
- length;
- stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets;
- if (stylesheets) {
- length = stylesheets.length;
- for (; i<length; i++) {
- html += '<link rel="stylesheet" href="' + stylesheets[i] + '">';
- }
- }
- templateVars.stylesheets = html;
-
- return wysihtml5.lang.string(
- '<!DOCTYPE html><html><head>'
- + '<meta charset="#{charset}">#{stylesheets}</head>'
- + '<body></body></html>'
- ).interpolate(templateVars);
- },
-
- /**
- * Method to unset/override existing variables
- * @example
- * // Make cookie unreadable and unwritable
- * this._unset(document, "cookie", "", true);
- */
- _unset: function(object, property, value, setter) {
- try { object[property] = value; } catch(e) {}
-
- try { object.__defineGetter__(property, function() { return value; }); } catch(e) {}
- if (setter) {
- try { object.__defineSetter__(property, function() {}); } catch(e) {}
- }
-
- if (!wysihtml5.browser.crashesWhenDefineProperty(property)) {
- try {
- var config = {
- get: function() { return value; }
- };
- if (setter) {
- config.set = function() {};
- }
- Object.defineProperty(object, property, config);
- } catch(e) {}
- }
- }
- });
-})(wysihtml5);
+var wysihtml5={version:"0.3.0",commands:{},dom:{},quirks:{},toolbar:{},lang:{},selection:{},views:{},INVISIBLE_SPACE:"",EMPTY_FUNCTION:function(){},ELEMENT_NODE:1,TEXT_NODE:3,BACKSPACE_KEY:8,ENTER_KEY:13,ESCAPE_KEY:27,SPACE_KEY:32,DELETE_KEY:46};window.rangy=function(){function a(a,b){var c=typeof a[b];return c==j||!(c!=i||!a[b])||"unknown"==c}function b(a,b){return!(typeof a[b]!=i||!a[b])}function c(a,b){return typeof a[b]!=k}function d(a){return function(b,c){for(var d=c.length;d--;)if(!a(b,c[d]))return!1;return!0}}function e(a){return a&&p(a,o)&&r(a,n)}function f(a){window.alert("Rangy not supported in your browser. Reason: "+a),s.initialized=!0,s.supported=!1}function g(){if(!s.initialized){var c,d=!1,g=!1;for(a(document,"createRange")&&(c=document.createRange(),p(c,m)&&r(c,l)&&(d=!0),c.detach()),(c=b(document,"body")?document.body:document.getElementsByTagName("body")[0])&&a(c,"createTextRange")&&(c=c.createTextRange(),e(c)&&(g=!0)),!d&&!g&&f("Neither Range nor TextRange are implemented"),s.initialized=!0,s.features={implementsDomRange:d,implementsTextRange:g},d=u.concat(t),g=0,c=d.length;c>g;++g)try{d[g](s)}catch(h){b(window,"console")&&a(window.console,"log")&&window.console.log("Init listener threw an exception. Continuing.",h)}}}function h(a){this.name=a,this.supported=this.initialized=!1}var i="object",j="function",k="undefined",l="startContainer startOffset endContainer endOffset collapsed commonAncestorContainer START_TO_START START_TO_END END_TO_START END_TO_END".split(" "),m="setStart setStartBefore setStartAfter setEnd setEndBefore setEndAfter collapse selectNode selectNodeContents compareBoundaryPoints deleteContents extractContents cloneContents insertNode surroundContents cloneRange toString detach".split(" "),n="boundingHeight boundingLeft boundingTop boundingWidth htmlText text".split(" "),o="collapse compareEndPoints duplicate getBookmark moveToBookmark moveToElementText parentElement pasteHTML select setEndPoint getBoundingClientRect".split(" "),p=d(a),q=d(b),r=d(c),s={version:"1.2.2",initialized:!1,supported:!0,util:{isHostMethod:a,isHostObject:b,isHostProperty:c,areHostMethods:p,areHostObjects:q,areHostProperties:r,isTextRange:e},features:{},modules:{},config:{alertOnWarn:!1,preferTextRange:!1}};s.fail=f,s.warn=function(a){a="Rangy warning: "+a,s.config.alertOnWarn?window.alert(a):typeof window.console!=k&&typeof window.console.log!=k&&window.console.log(a)},{}.hasOwnProperty?s.util.extend=function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c])}:f("hasOwnProperty not supported");var t=[],u=[];s.init=g,s.addInitListener=function(a){s.initialized?a(s):t.push(a)};var v=[];s.addCreateMissingNativeApiListener=function(a){v.push(a)},s.createMissingNativeApi=function(a){a=a||window,g();for(var b=0,c=v.length;c>b;++b)v[b](a)},h.prototype.fail=function(a){throw this.initialized=!0,this.supported=!1,Error("Module '"+this.name+"' failed to load: "+a)},h.prototype.warn=function(a){s.warn("Module "+this.name+": "+a)},h.prototype.createError=function(a){return Error("Error in Rangy "+this.name+" module: "+a)},s.createModule=function(a,b){var c=new h(a);s.modules[a]=c,u.push(function(a){b(a,c),c.initialized=!0,c.supported=!0})},s.requireModules=function(a){for(var b,c,d=0,e=a.length;e>d;++d){if(c=a[d],b=s.modules[c],!(b&&b instanceof h))throw Error("Module '"+c+"' not found");if(!b.supported)throw Error("Module '"+c+"' not supported")}};var w=!1,q=function(){w||(w=!0,s.initialized||g())};if(typeof window==k)f("No window found");else{if(typeof document!=k)return a(document,"addEventListener")&&document.addEventListener("DOMContentLoaded",q,!1),a(window,"addEventListener")?window.addEventListener("load",q,!1):a(window,"attachEvent")?window.attachEvent("onload",q):f("Window does not have required addEventListener or attachEvent method"),s;f("No document found")}}(),rangy.createModule("DomUtil",function(a,b){function c(a){for(var b=0;a=a.previousSibling;)b++;return b}function d(a,b){var c,d=[];for(c=a;c;c=c.parentNode)d.push(c);for(c=b;c;c=c.parentNode)if(p(d,c))return c;return null}function e(a,b,c){for(c=c?a:a.parentNode;c;){if(a=c.parentNode,a===b)return c;c=a}return null}function f(a){return a=a.nodeType,3==a||4==a||8==a}function g(a,b){var c=b.nextSibling,d=b.parentNode;return c?d.insertBefore(a,c):d.appendChild(a),a}function h(a){if(9==a.nodeType)return a;if(typeof a.ownerDocument!=m)return a.ownerDocument;if(typeof a.document!=m)return a.document;if(a.parentNode)return h(a.parentNode);throw Error("getDocument: no document found for node")}function i(a){return a?f(a)?'"'+a.data+'"':1==a.nodeType?"<"+a.nodeName+(a.id?' id="'+a.id+'"':"")+">["+a.childNodes.length+"]":a.nodeName:"[No node]"}function j(a){this._next=this.root=a}function k(a,b){this.node=a,this.offset=b}function l(a){this.code=this[a],this.codeName=a,this.message="DOMException: "+this.codeName}var m="undefined",n=a.util;n.areHostMethods(document,["createDocumentFragment","createElement","createTextNode"])||b.fail("document missing a Node creation method"),n.isHostMethod(document,"getElementsByTagName")||b.fail("document missing getElementsByTagName method");var o=document.createElement("div");n.areHostMethods(o,["insertBefore","appendChild","cloneNode"])||b.fail("Incomplete Element implementation"),n.isHostProperty(o,"innerHTML")||b.fail("Element is missing innerHTML property"),o=document.createTextNode("test"),n.areHostMethods(o,["splitText","deleteData","insertData","appendData","cloneNode"])||b.fail("Incomplete Text Node implementation");var p=function(a,b){for(var c=a.length;c--;)if(a[c]===b)return!0;return!1};j.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){var a,b=this._current=this._next;if(this._current){if(a=b.firstChild,!a)for(a=null;b!==this.root&&!(a=b.nextSibling);)b=b.parentNode;this._next=a}return this._current},detach:function(){this._current=this._next=this.root=null}},k.prototype={equals:function(a){return this.node===a.node&this.offset==a.offset},inspect:function(){return"[DomPosition("+i(this.node)+":"+this.offset+")]"}},l.prototype={INDEX_SIZE_ERR:1,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INVALID_STATE_ERR:11},l.prototype.toString=function(){return this.message},a.dom={arrayContains:p,isHtmlNamespace:function(a){var b;return typeof a.namespaceURI==m||null===(b=a.namespaceURI)||"http://www.w3.org/1999/xhtml"==b},parentElement:function(a){return a=a.parentNode,1==a.nodeType?a:null},getNodeIndex:c,getNodeLength:function(a){var b;return f(a)?a.length:(b=a.childNodes)?b.length:0},getCommonAncestor:d,isAncestorOf:function(a,b,c){for(b=c?b:b.parentNode;b;){if(b===a)return!0;b=b.parentNode}return!1},getClosestAncestorIn:e,isCharacterDataNode:f,insertAfter:g,splitDataNode:function(a,b){var c=a.cloneNode(!1);return c.deleteData(0,b),a.deleteData(b,a.length-b),g(c,a),c},getDocument:h,getWindow:function(a){if(a=h(a),typeof a.defaultView!=m)return a.defaultView;if(typeof a.parentWindow!=m)return a.parentWindow;throw Error("Cannot get a window object for node")},getIframeWindow:function(a){if(typeof a.contentWindow!=m)return a.contentWindow;if(typeof a.contentDocument!=m)return a.contentDocument.defaultView;throw Error("getIframeWindow: No Window object found for iframe element")},getIframeDocument:function(a){if(typeof a.contentDocument!=m)return a.contentDocument;if(typeof a.contentWindow!=m)return a.contentWindow.document;throw Error("getIframeWindow: No Document object found for iframe element")},getBody:function(a){return n.isHostObject(a,"body")?a.body:a.getElementsByTagName("body")[0]},getRootContainer:function(a){for(var b;b=a.parentNode;)a=b;return a},comparePoints:function(a,b,f,g){var h;if(a==f)return b===g?0:g>b?-1:1;if(h=e(f,a,!0))return b<=c(h)?-1:1;if(h=e(a,f,!0))return c(h)<g?-1:1;if(b=d(a,f),a=a===b?b:e(a,b,!0),f=f===b?b:e(f,b,!0),a===f)throw Error("comparePoints got to case 4 and childA and childB are the same!");for(b=b.firstChild;b;){if(b===a)return-1;if(b===f)return 1;b=b.nextSibling}throw Error("Should not be here!")},inspectNode:i,fragmentFromNodeChildren:function(a){for(var b,c=h(a).createDocumentFragment();b=a.firstChild;)c.appendChild(b);return c},createIterator:function(a){return new j(a)},DomPosition:k},a.DOMException=l}),rangy.createModule("DomRange",function(a){function b(a,b){return 3!=a.nodeType&&(H.isAncestorOf(a,b.startContainer,!0)||H.isAncestorOf(a,b.endContainer,!0))}function c(a){return H.getDocument(a.startContainer)}function d(a,b,c){if(b=a._listeners[b])for(var d=0,e=b.length;e>d;++d)b[d].call(a,{target:a,args:c})}function e(a){return new I(a.parentNode,H.getNodeIndex(a))}function f(a){return new I(a.parentNode,H.getNodeIndex(a)+1)}function g(a,b,c){var d=11==a.nodeType?a.firstChild:a;return H.isCharacterDataNode(b)?c==b.length?H.insertAfter(a,b):b.parentNode.insertBefore(a,0==c?b:H.splitDataNode(b,c)):c>=b.childNodes.length?b.appendChild(a):b.insertBefore(a,b.childNodes[c]),d}function h(a){for(var b,d,e=c(a.range).createDocumentFragment();d=a.next();){if(b=a.isPartiallySelectedSubtree(),d=d.cloneNode(!b),b&&(b=a.getSubtreeIterator(),d.appendChild(h(b)),b.detach(!0)),10==d.nodeType)throw new J("HIERARCHY_REQUEST_ERR");e.appendChild(d)}return e}function i(a,b,c){for(var d,e,c=c||{stop:!1};d=a.next();)if(a.isPartiallySelectedSubtree()){if(!1===b(d)){c.stop=!0;break}if(d=a.getSubtreeIterator(),i(d,b,c),d.detach(!0),c.stop)break}else for(d=H.createIterator(d);e=d.next();)if(!1===b(e))return void(c.stop=!0)}function j(a){for(var b;a.next();)a.isPartiallySelectedSubtree()?(b=a.getSubtreeIterator(),j(b),b.detach(!0)):a.remove()}function k(a){for(var b,d,e=c(a.range).createDocumentFragment();b=a.next();){if(a.isPartiallySelectedSubtree()?(b=b.cloneNode(!1),d=a.getSubtreeIterator(),b.appendChild(k(d)),d.detach(!0)):a.remove(),10==b.nodeType)throw new J("HIERARCHY_REQUEST_ERR");e.appendChild(b)}return e}function l(a,b,c){var d,e=!(!b||!b.length),f=!!c;e&&(d=RegExp("^("+b.join("|")+")$"));var g=[];return i(new n(a,!1),function(a){(!e||d.test(a.nodeType))&&(!f||c(a))&&g.push(a)}),g}function m(a){return"["+("undefined"==typeof a.getName?"Range":a.getName())+"("+H.inspectNode(a.startContainer)+":"+a.startOffset+", "+H.inspectNode(a.endContainer)+":"+a.endOffset+")]"}function n(a,b){if(this.range=a,this.clonePartiallySelectedTextNodes=b,!a.collapsed){this.sc=a.startContainer,this.so=a.startOffset,this.ec=a.endContainer,this.eo=a.endOffset;var c=a.commonAncestorContainer;this.sc===this.ec&&H.isCharacterDataNode(this.sc)?(this.isSingleCharacterDataNode=!0,this._first=this._last=this._next=this.sc):(this._first=this._next=this.sc!==c||H.isCharacterDataNode(this.sc)?H.getClosestAncestorIn(this.sc,c,!0):this.sc.childNodes[this.so],this._last=this.ec!==c||H.isCharacterDataNode(this.ec)?H.getClosestAncestorIn(this.ec,c,!0):this.ec.childNodes[this.eo-1])}}function o(a){this.code=this[a],this.codeName=a,this.message="RangeException: "+this.codeName}function p(a,b,c){this.nodes=l(a,b,c),this._next=this.nodes[0],this._position=0}function q(a){return function(b,c){for(var d,e=c?b:b.parentNode;e;){if(d=e.nodeType,H.arrayContains(a,d))return e;e=e.parentNode}return null}}function r(a,b){if(R(a,b))throw new o("INVALID_NODE_TYPE_ERR")}function s(a){if(!a.startContainer)throw new J("INVALID_STATE_ERR")}function t(a,b){if(!H.arrayContains(b,a.nodeType))throw new o("INVALID_NODE_TYPE_ERR")}function u(a,b){if(0>b||b>(H.isCharacterDataNode(a)?a.length:a.childNodes.length))throw new J("INDEX_SIZE_ERR")}function v(a,b){if(P(a,!0)!==P(b,!0))throw new J("WRONG_DOCUMENT_ERR")}function w(a){if(Q(a,!0))throw new J("NO_MODIFICATION_ALLOWED_ERR")}function x(a,b){if(!a)throw new J(b)}function y(a){if(s(a),!((H.arrayContains(L,a.startContainer.nodeType)||P(a.startContainer,!0))&&(H.arrayContains(L,a.endContainer.nodeType)||P(a.endContainer,!0))&&a.startOffset<=(H.isCharacterDataNode(a.startContainer)?a.startContainer.length:a.startContainer.childNodes.length)&&a.endOffset<=(H.isCharacterDataNode(a.endContainer)?a.endContainer.length:a.endContainer.childNodes.length)))throw Error("Range error: Range is no longer valid after DOM mutation ("+a.inspect()+")")}function z(){}function A(a){a.START_TO_START=W,a.START_TO_END=X,a.END_TO_END=Y,a.END_TO_START=Z,a.NODE_BEFORE=$,a.NODE_AFTER=_,a.NODE_BEFORE_AND_AFTER=ab,a.NODE_INSIDE=bb}function B(a){A(a),A(a.prototype)}function C(a,b){return function(){y(this);var c=this.startContainer,d=this.startOffset,e=this.commonAncestorContainer,g=new n(this,!0);return c!==e&&(c=H.getClosestAncestorIn(c,e,!0),d=f(c),c=d.node,d=d.offset),i(g,w),g.reset(),e=a(g),g.detach(),b(this,c,d,c,d),e}}function D(c,d,g){function h(a,b){return function(c){s(this),t(c,K),t(O(c),L),c=(a?e:f)(c),(b?i:l)(this,c.node,c.offset)}}function i(a,b,c){var e=a.endContainer,f=a.endOffset;(b!==a.startContainer||c!==a.startOffset)&&((O(b)!=O(e)||1==H.comparePoints(b,c,e,f))&&(e=b,f=c),d(a,b,c,e,f))}function l(a,b,c){var e=a.startContainer,f=a.startOffset;(b!==a.endContainer||c!==a.endOffset)&&((O(b)!=O(e)||-1==H.comparePoints(b,c,e,f))&&(e=b,f=c),d(a,e,f,b,c))}c.prototype=new z,a.util.extend(c.prototype,{setStart:function(a,b){s(this),r(a,!0),u(a,b),i(this,a,b)},setEnd:function(a,b){s(this),r(a,!0),u(a,b),l(this,a,b)},setStartBefore:h(!0,!0),setStartAfter:h(!1,!0),setEndBefore:h(!0,!1),setEndAfter:h(!1,!1),collapse:function(a){y(this),a?d(this,this.startContainer,this.startOffset,this.startContainer,this.startOffset):d(this,this.endContainer,this.endOffset,this.endContainer,this.endOffset)},selectNodeContents:function(a){s(this),r(a,!0),d(this,a,0,a,H.getNodeLength(a))},selectNode:function(a){s(this),r(a,!1),t(a,K);var b=e(a),a=f(a);d(this,b.node,b.offset,a.node,a.offset)},extractContents:C(k,d),deleteContents:C(j,d),canSurroundContents:function(){y(this),w(this.startContainer),w(this.endContainer);var a=new n(this,!0),c=a._first&&b(a._first,this)||a._last&&b(a._last,this);return a.detach(),!c},detach:function(){g(this)},splitBoundaries:function(){y(this);var a=this.startContainer,b=this.startOffset,c=this.endContainer,e=this.endOffset,f=a===c;H.isCharacterDataNode(c)&&e>0&&e<c.length&&H.splitDataNode(c,e),H.isCharacterDataNode(a)&&b>0&&b<a.length&&(a=H.splitDataNode(a,b),f?(e-=b,c=a):c==a.parentNode&&e>=H.getNodeIndex(a)&&e++,b=0),d(this,a,b,c,e)},normalizeBoundaries:function(){y(this);var a=this.startContainer,b=this.startOffset,c=this.endContainer,e=this.endOffset,f=function(a){var b=a.nextSibling;b&&b.nodeType==a.nodeType&&(c=a,e=a.length,a.appendData(b.data),b.parentNode.removeChild(b))},g=function(d){var f=d.previousSibling;if(f&&f.nodeType==d.nodeType){a=d;var g=d.length;b=f.length,d.insertData(0,f.data),f.parentNode.removeChild(f),a==c?(e+=b,c=a):c==d.parentNode&&(f=H.getNodeIndex(d),e==f?(c=d,e=g):e>f&&e--)}},h=!0;H.isCharacterDataNode(c)?c.length==e&&f(c):(e>0&&(h=c.childNodes[e-1])&&H.isCharacterDataNode(h)&&f(h),h=!this.collapsed),h?H.isCharacterDataNode(a)?0==b&&g(a):b<a.childNodes.length&&(f=a.childNodes[b])&&H.isCharacterDataNode(f)&&g(f):(a=c,b=e),d(this,a,b,c,e)},collapseToPoint:function(a,b){s(this),r(a,!0),u(a,b),(a!==this.startContainer||b!==this.startOffset||a!==this.endContainer||b!==this.endOffset)&&d(this,a,b,a,b)}}),B(c)}function E(a){a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset,a.commonAncestorContainer=a.collapsed?a.startContainer:H.getCommonAncestor(a.startContainer,a.endContainer)}function F(a,b,c,e,f){var g=a.startContainer!==b||a.startOffset!==c,h=a.endContainer!==e||a.endOffset!==f;a.startContainer=b,a.startOffset=c,a.endContainer=e,a.endOffset=f,E(a),d(a,"boundarychange",{startMoved:g,endMoved:h})}function G(a){this.startContainer=a,this.startOffset=0,this.endContainer=a,this.endOffset=0,this._listeners={boundarychange:[],detach:[]},E(this)}a.requireModules(["DomUtil"]);var H=a.dom,I=H.DomPosition,J=a.DOMException;n.prototype={_current:null,_next:null,_first:null,_last:null,isSingleCharacterDataNode:!1,reset:function(){this._current=null,this._next=this._first},hasNext:function(){return!!this._next},next:function(){var a=this._current=this._next;return a&&(this._next=a!==this._last?a.nextSibling:null,H.isCharacterDataNode(a)&&this.clonePartiallySelectedTextNodes&&(a===this.ec&&(a=a.cloneNode(!0)).deleteData(this.eo,a.length-this.eo),this._current===this.sc&&(a=a.cloneNode(!0)).deleteData(0,this.so))),a},remove:function(){var a,b,c=this._current;!H.isCharacterDataNode(c)||c!==this.sc&&c!==this.ec?c.parentNode&&c.parentNode.removeChild(c):(a=c===this.sc?this.so:0,b=c===this.ec?this.eo:c.length,a!=b&&c.deleteData(a,b-a))},isPartiallySelectedSubtree:function(){return b(this._current,this.range)},getSubtreeIterator:function(){var a;if(this.isSingleCharacterDataNode)a=this.range.cloneRange(),a.collapse();else{a=new G(c(this.range));var b=this._current,d=b,e=0,f=b,g=H.getNodeLength(b);H.isAncestorOf(b,this.sc,!0)&&(d=this.sc,e=this.so),H.isAncestorOf(b,this.ec,!0)&&(f=this.ec,g=this.eo),F(a,d,e,f,g)}return new n(a,this.clonePartiallySelectedTextNodes)},detach:function(a){a&&this.range.detach(),this.range=this._current=this._next=this._first=this._last=this.sc=this.so=this.ec=this.eo=null}},o.prototype={BAD_BOUNDARYPOINTS_ERR:1,INVALID_NODE_TYPE_ERR:2},o.prototype.toString=function(){return this.message},p.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){return this._current=this._next,this._next=this.nodes[++this._position],this._current},detach:function(){this._current=this._next=this.nodes=null}};var K=[1,3,4,5,7,8,10],L=[2,9,11],M=[1,3,4,5,7,8,10,11],N=[1,3,4,5,7,8],O=H.getRootContainer,P=q([9,11]),Q=q([5,6,10,12]),R=q([6,10,12]),S=document.createElement("style"),T=!1;try{S.innerHTML="<b>x</b>",T=3==S.firstChild.nodeType}catch(U){}a.features.htmlParsingConforms=T;var V="startContainer startOffset endContainer endOffset collapsed commonAncestorContainer".split(" "),W=0,X=1,Y=2,Z=3,$=0,_=1,ab=2,bb=3;z.prototype={attachListener:function(a,b){this._listeners[a].push(b)},compareBoundaryPoints:function(a,b){y(this),v(this.startContainer,b.startContainer);var c=a==Z||a==W?"start":"end",d=a==X||a==W?"start":"end";return H.comparePoints(this[c+"Container"],this[c+"Offset"],b[d+"Container"],b[d+"Offset"])},insertNode:function(a){if(y(this),t(a,M),w(this.startContainer),H.isAncestorOf(a,this.startContainer,!0))throw new J("HIERARCHY_REQUEST_ERR");this.setStartBefore(g(a,this.startContainer,this.startOffset))},cloneContents:function(){y(this);var a,b;return this.collapsed?c(this).createDocumentFragment():this.startContainer===this.endContainer&&H.isCharacterDataNode(this.startContainer)?(a=this.startContainer.cloneNode(!0),a.data=a.data.slice(this.startOffset,this.endOffset),b=c(this).createDocumentFragment(),b.appendChild(a),b):(b=new n(this,!0),a=h(b),b.detach(),a)},canSurroundContents:function(){y(this),w(this.startContainer),w(this.endContainer);var a=new n(this,!0),c=a._first&&b(a._first,this)||a._last&&b(a._last,this);return a.detach(),!c},surroundContents:function(a){if(t(a,N),!this.canSurroundContents())throw new o("BAD_BOUNDARYPOINTS_ERR");var b=this.extractContents();if(a.hasChildNodes())for(;a.lastChild;)a.removeChild(a.lastChild);g(a,this.startContainer,this.startOffset),a.appendChild(b),this.selectNode(a)},cloneRange:function(){y(this);for(var a,b=new G(c(this)),d=V.length;d--;)a=V[d],b[a]=this[a];return b},toString:function(){y(this);var a=this.startContainer;if(a===this.endContainer&&H.isCharacterDataNode(a))return 3==a.nodeType||4==a.nodeType?a.data.slice(this.startOffset,this.endOffset):"";var b=[],a=new n(this,!0);return i(a,function(a){(3==a.nodeType||4==a.nodeType)&&b.push(a.data)}),a.detach(),b.join("")},compareNode:function(a){y(this);var b=a.parentNode,c=H.getNodeIndex(a);if(!b)throw new J("NOT_FOUND_ERR");return a=this.comparePoint(b,c),b=this.comparePoint(b,c+1),0>a?b>0?ab:$:b>0?_:bb},comparePoint:function(a,b){return y(this),x(a,"HIERARCHY_REQUEST_ERR"),v(a,this.startContainer),0>H.comparePoints(a,b,this.startContainer,this.startOffset)?-1:0<H.comparePoints(a,b,this.endContainer,this.endOffset)?1:0},createContextualFragment:T?function(a){var b=this.startContainer,c=H.getDocument(b);if(!b)throw new J("INVALID_STATE_ERR");var d=null;return 1==b.nodeType?d=b:H.isCharacterDataNode(b)&&(d=H.parentElement(b)),d=null===d||"HTML"==d.nodeName&&H.isHtmlNamespace(H.getDocument(d).documentElement)&&H.isHtmlNamespace(d)?c.createElement("body"):d.cloneNode(!1),d.innerHTML=a,H.fragmentFromNodeChildren(d)}:function(a){s(this);var b=c(this).createElement("body");return b.innerHTML=a,H.fragmentFromNodeChildren(b)},toHtml:function(){y(this);var a=c(this).createElement("div");return a.appendChild(this.cloneContents()),a.innerHTML},intersectsNode:function(a,b){if(y(this),x(a,"NOT_FOUND_ERR"),H.getDocument(a)!==c(this))return!1;var d=a.parentNode,e=H.getNodeIndex(a);x(d,"NOT_FOUND_ERR");var f=H.comparePoints(d,e,this.endContainer,this.endOffset),d=H.comparePoints(d,e+1,this.startContainer,this.startOffset);return b?0>=f&&d>=0:0>f&&d>0},isPointInRange:function(a,b){return y(this),x(a,"HIERARCHY_REQUEST_ERR"),v(a,this.startContainer),0<=H.comparePoints(a,b,this.startContainer,this.startOffset)&&0>=H.comparePoints(a,b,this.endContainer,this.endOffset)},intersectsRange:function(a,b){if(y(this),c(a)!=c(this))throw new J("WRONG_DOCUMENT_ERR");var d=H.comparePoints(this.startContainer,this.startOffset,a.endContainer,a.endOffset),e=H.comparePoints(this.endContainer,this.endOffset,a.startContainer,a.startOffset);return b?0>=d&&e>=0:0>d&&e>0},intersection:function(a){if(this.intersectsRange(a)){var b=H.comparePoints(this.startContainer,this.startOffset,a.startContainer,a.startOffset),c=H.comparePoints(this.endContainer,this.endOffset,a.endContainer,a.endOffset),d=this.cloneRange();return-1==b&&d.setStart(a.startContainer,a.startOffset),1==c&&d.setEnd(a.endContainer,a.endOffset),d}return null},union:function(a){if(this.intersectsRange(a,!0)){var b=this.cloneRange();return-1==H.comparePoints(a.startContainer,a.startOffset,this.startContainer,this.startOffset)&&b.setStart(a.startContainer,a.startOffset),1==H.comparePoints(a.endContainer,a.endOffset,this.endContainer,this.endOffset)&&b.setEnd(a.endContainer,a.endOffset),b}throw new o("Ranges do not intersect")},containsNode:function(a,b){return b?this.intersectsNode(a,!1):this.compareNode(a)==bb},containsNodeContents:function(a){return 0<=this.comparePoint(a,0)&&0>=this.comparePoint(a,H.getNodeLength(a))},containsRange:function(a){return this.intersection(a).equals(a)},containsNodeText:function(a){var b=this.cloneRange();b.selectNode(a);var c=b.getNodes([3]);return 0<c.length?(b.setStart(c[0],0),a=c.pop(),b.setEnd(a,a.length),a=this.containsRange(b),b.detach(),a):this.containsNodeContents(a)},createNodeIterator:function(a,b){return y(this),new p(this,a,b)},getNodes:function(a,b){return y(this),l(this,a,b)},getDocument:function(){return c(this)},collapseBefore:function(a){s(this),this.setEndBefore(a),this.collapse(!1)},collapseAfter:function(a){s(this),this.setStartAfter(a),this.collapse(!0)},getName:function(){return"DomRange"},equals:function(a){return G.rangesEqual(this,a)},inspect:function(){return m(this)}},D(G,F,function(a){s(a),a.startContainer=a.startOffset=a.endContainer=a.endOffset=null,a.collapsed=a.commonAncestorContainer=null,d(a,"detach",null),a._listeners=null}),a.rangePrototype=z.prototype,G.rangeProperties=V,G.RangeIterator=n,G.copyComparisonConstants=B,G.createPrototypeRange=D,G.inspect=m,G.getRangeDocument=c,G.rangesEqual=function(a,b){return a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset},a.DomRange=G,a.RangeException=o}),rangy.createModule("WrappedRange",function(a){function b(a,b,c,d){var g=a.duplicate();g.collapse(c);var h=g.parentElement();if(e.isAncestorOf(b,h,!0)||(h=b),!h.canHaveHTML)return new f(h.parentNode,e.getNodeIndex(h));var i,b=e.getDocument(h).createElement("span"),j=c?"StartToStart":"StartToEnd";do h.insertBefore(b,b.previousSibling),g.moveToElementText(b);while(0<(i=g.compareEndPoints(j,a))&&b.previousSibling);if(j=b.nextSibling,-1==i&&j&&e.isCharacterDataNode(j)){if(g.setEndPoint(c?"EndToStart":"EndToEnd",a),/[\r\n]/.test(j.data))for(h=g.duplicate(),c=h.text.replace(/\r\n/g,"\r").length,c=h.moveStart("character",c);-1==h.compareEndPoints("StartToEnd",h);)c++,h.moveStart("character",1);else c=g.text.length;h=new f(j,c)}else j=(d||!c)&&b.previousSibling,h=(c=(d||c)&&b.nextSibling)&&e.isCharacterDataNode(c)?new f(c,0):j&&e.isCharacterDataNode(j)?new f(j,j.length):new f(h,e.getNodeIndex(b));return b.parentNode.removeChild(b),h}function c(a,b){var c,d,f=a.offset,g=e.getDocument(a.node),h=g.body.createTextRange(),i=e.isCharacterDataNode(a.node);return i?(c=a.node,d=c.parentNode):(c=a.node.childNodes,c=f<c.length?c[f]:null,d=a.node),g=g.createElement("span"),g.innerHTML="&#feff;",c?d.insertBefore(g,c):d.appendChild(g),h.moveToElementText(g),h.collapse(!b),d.removeChild(g),i&&h[b?"moveStart":"moveEnd"]("character",f),h}a.requireModules(["DomUtil","DomRange"]);var d,e=a.dom,f=e.DomPosition,g=a.DomRange;if(!a.features.implementsDomRange||a.features.implementsTextRange&&a.config.preferTextRange){if(a.features.implementsTextRange){d=function(a){this.textRange=a,this.refresh()},d.prototype=new g(document),d.prototype.refresh=function(){var a,c,d=this.textRange;a=d.parentElement();var f=d.duplicate();f.collapse(!0),c=f.parentElement(),f=d.duplicate(),f.collapse(!1),d=f.parentElement(),c=c==d?c:e.getCommonAncestor(c,d),c=c==a?c:e.getCommonAncestor(a,c),0==this.textRange.compareEndPoints("StartToEnd",this.textRange)?c=a=b(this.textRange,c,!0,!0):(a=b(this.textRange,c,!0,!1),c=b(this.textRange,c,!1,!1)),this.setStart(a.node,a.offset),this.setEnd(c.node,c.offset)},g.copyComparisonConstants(d);var h=function(){return this}();"undefined"==typeof h.Range&&(h.Range=d),a.createNativeRange=function(a){return a=a||document,a.body.createTextRange()}}}else(function(){function b(a){for(var b,c=h.length;c--;)b=h[c],a[b]=a.nativeRange[b]}var c,f,h=g.rangeProperties;d=function(a){if(!a)throw Error("Range must be specified");this.nativeRange=a,b(this)},g.createPrototypeRange(d,function(a,b,c,d,e){var f=a.endContainer!==d||a.endOffset!=e;(a.startContainer!==b||a.startOffset!=c||f)&&(a.setEnd(d,e),a.setStart(b,c))},function(a){a.nativeRange.detach(),a.detached=!0;for(var b,c=h.length;c--;)b=h[c],a[b]=null}),c=d.prototype,c.selectNode=function(a){this.nativeRange.selectNode(a),b(this)},c.deleteContents=function(){this.nativeRange.deleteContents(),b(this)},c.extractContents=function(){var a=this.nativeRange.extractContents();return b(this),a},c.cloneContents=function(){return this.nativeRange.cloneContents()},c.surroundContents=function(a){this.nativeRange.surroundContents(a),b(this)},c.collapse=function(a){this.nativeRange.collapse(a),b(this)},c.cloneRange=function(){return new d(this.nativeRange.cloneRange())},c.refresh=function(){b(this)},c.toString=function(){return this.nativeRange.toString()};var i=document.createTextNode("test");e.getBody(document).appendChild(i);var j=document.createRange();j.setStart(i,0),j.setEnd(i,0);try{j.setStart(i,1),c.setStart=function(a,c){this.nativeRange.setStart(a,c),b(this)},c.setEnd=function(a,c){this.nativeRange.setEnd(a,c),b(this)},f=function(a){return function(c){this.nativeRange[a](c),b(this)}}}catch(k){c.setStart=function(a,c){try{this.nativeRange.setStart(a,c)}catch(d){this.nativeRange.setEnd(a,c),this.nativeRange.setStart(a,c)}b(this)},c.setEnd=function(a,c){try{this.nativeRange.setEnd(a,c)}catch(d){this.nativeRange.setStart(a,c),this.nativeRange.setEnd(a,c)}b(this)},f=function(a,c){return function(d){try{this.nativeRange[a](d)}catch(e){this.nativeRange[c](d),this.nativeRange[a](d)}b(this)}}}c.setStartBefore=f("setStartBefore","setEndBefore"),c.setStartAfter=f("setStartAfter","setEndAfter"),c.setEndBefore=f("setEndBefore","setStartBefore"),c.setEndAfter=f("setEndAfter","setStartAfter"),j.selectNodeContents(i),c.selectNodeContents=j.startContainer==i&&j.endContainer==i&&0==j.startOffset&&j.endOffset==i.length?function(a){this.nativeRange.selectNodeContents(a),b(this)}:function(a){this.setStart(a,0),this.setEnd(a,g.getEndOffset(a))},j.selectNodeContents(i),j.setEnd(i,3),f=document.createRange(),f.selectNodeContents(i),f.setEnd(i,4),f.setStart(i,2),c.compareBoundaryPoints=-1==j.compareBoundaryPoints(j.START_TO_END,f)&1==j.compareBoundaryPoints(j.END_TO_START,f)?function(a,b){return b=b.nativeRange||b,a==b.START_TO_END?a=b.END_TO_START:a==b.END_TO_START&&(a=b.START_TO_END),this.nativeRange.compareBoundaryPoints(a,b)}:function(a,b){return this.nativeRange.compareBoundaryPoints(a,b.nativeRange||b)},a.util.isHostMethod(j,"createContextualFragment")&&(c.createContextualFragment=function(a){return this.nativeRange.createContextualFragment(a)}),e.getBody(document).removeChild(i),j.detach(),f.detach()})(),a.createNativeRange=function(a){return a=a||document,a.createRange()};a.features.implementsTextRange&&(d.rangeToTextRange=function(a){if(a.collapsed)return c(new f(a.startContainer,a.startOffset),!0);var b=c(new f(a.startContainer,a.startOffset),!0),d=c(new f(a.endContainer,a.endOffset),!1),a=e.getDocument(a.startContainer).body.createTextRange();return a.setEndPoint("StartToStart",b),a.setEndPoint("EndToEnd",d),a}),d.prototype.getName=function(){return"WrappedRange"},a.WrappedRange=d,a.createRange=function(b){return b=b||document,new d(a.createNativeRange(b))},a.createRangyRange=function(a){return a=a||document,new g(a)},a.createIframeRange=function(b){return a.createRange(e.getIframeDocument(b))},a.createIframeRangyRange=function(b){return a.createRangyRange(e.getIframeDocument(b))},a.addCreateMissingNativeApiListener(function(b){b=b.document,"undefined"==typeof b.createRange&&(b.createRange=function(){return a.createRange(this)}),b=b=null})}),rangy.createModule("WrappedSelection",function(a,b){function c(a){return(a||window).getSelection()}function d(a){return(a||window).document.selection}function e(a,b,c){var d=c?"end":"start",c=c?"start":"end";a.anchorNode=b[d+"Container"],a.anchorOffset=b[d+"Offset"],a.focusNode=b[c+"Container"],a.focusOffset=b[c+"Offset"]}function f(a){a.anchorNode=a.focusNode=null,a.anchorOffset=a.focusOffset=0,a.rangeCount=0,a.isCollapsed=!0,a._ranges.length=0}function g(b){var c;return b instanceof t?(c=b._selectionNativeRange,c||(c=a.createNativeRange(r.getDocument(b.startContainer)),c.setEnd(b.endContainer,b.endOffset),c.setStart(b.startContainer,b.startOffset),b._selectionNativeRange=c,b.attachListener("detach",function(){this._selectionNativeRange=null}))):b instanceof u?c=b.nativeRange:a.features.implementsDomRange&&b instanceof r.getWindow(b.startContainer).Range&&(c=b),c}function h(a){var b,c=a.getNodes();a:if(c.length&&1==c[0].nodeType){b=1;for(var d=c.length;d>b;++b)if(!r.isAncestorOf(c[0],c[b])){b=!1;break a}b=!0}else b=!1;if(!b)throw Error("getSingleElementFromRange: range "+a.inspect()+" did not consist of a single element");return c[0]}function i(a,b){var c=new u(b);a._ranges=[c],e(a,c,!1),a.rangeCount=1,a.isCollapsed=c.collapsed}function j(b){if(b._ranges.length=0,"None"==b.docSelection.type)f(b);else{var c=b.docSelection.createRange();if(c&&"undefined"!=typeof c.text)i(b,c);else{b.rangeCount=c.length;for(var d,g=r.getDocument(c.item(0)),h=0;h<b.rangeCount;++h)d=a.createRange(g),d.selectNode(c.item(h)),b._ranges.push(d);b.isCollapsed=1==b.rangeCount&&b._ranges[0].collapsed,e(b,b._ranges[b.rangeCount-1],!1)}}}function k(a,b){for(var c=a.docSelection.createRange(),d=h(b),e=r.getDocument(c.item(0)),e=r.getBody(e).createControlRange(),f=0,g=c.length;g>f;++f)e.add(c.item(f));try{e.add(d)}catch(i){throw Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)")}e.select(),j(a)}function l(a,b,c){this.nativeSelection=a,this.docSelection=b,this._ranges=[],this.win=c,this.refresh()}function m(a,b){for(var c,d=r.getDocument(b[0].startContainer),d=r.getBody(d).createControlRange(),e=0;rangeCount>e;++e){c=h(b[e]);
+try{d.add(c)}catch(f){throw Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)")}}d.select(),j(a)}function n(a,b){if(a.anchorNode&&r.getDocument(a.anchorNode)!==r.getDocument(b))throw new v("WRONG_DOCUMENT_ERR")}function o(a){var b=[],c=new w(a.anchorNode,a.anchorOffset),d=new w(a.focusNode,a.focusOffset),e="function"==typeof a.getName?a.getName():"Selection";if("undefined"!=typeof a.rangeCount)for(var f=0,g=a.rangeCount;g>f;++f)b[f]=t.inspect(a.getRangeAt(f));return"["+e+"(Ranges: "+b.join(", ")+")(anchor: "+c.inspect()+", focus: "+d.inspect()+"]"}a.requireModules(["DomUtil","DomRange","WrappedRange"]),a.config.checkSelectionRanges=!0;var p,q,r=a.dom,s=a.util,t=a.DomRange,u=a.WrappedRange,v=a.DOMException,w=r.DomPosition,x=a.util.isHostMethod(window,"getSelection"),y=a.util.isHostObject(document,"selection"),z=y&&(!x||a.config.preferTextRange);z?(p=d,a.isSelectionValid=function(a){var a=(a||window).document,b=a.selection;return"None"!=b.type||r.getDocument(b.createRange().parentElement())==a}):x?(p=c,a.isSelectionValid=function(){return!0}):b.fail("Neither document.selection or window.getSelection() detected."),a.getNativeSelection=p;var x=p(),A=a.createNativeRange(document),B=r.getBody(document),C=s.areHostObjects(x,s.areHostProperties(x,["anchorOffset","focusOffset"]));a.features.selectionHasAnchorAndFocus=C;var D=s.isHostMethod(x,"extend");a.features.selectionHasExtend=D;var E="number"==typeof x.rangeCount;a.features.selectionHasRangeCount=E;var F=!1,G=!0;s.areHostMethods(x,["addRange","getRangeAt","removeAllRanges"])&&"number"==typeof x.rangeCount&&a.features.implementsDomRange&&function(){var a=document.createElement("iframe");B.appendChild(a);var b=r.getIframeDocument(a);b.open(),b.write("<html><head></head><body>12</body></html>"),b.close();var c=r.getIframeWindow(a).getSelection(),d=b.documentElement.lastChild.firstChild,b=b.createRange();b.setStart(d,1),b.collapse(!0),c.addRange(b),G=1==c.rangeCount,c.removeAllRanges();var e=b.cloneRange();b.setStart(d,0),e.setEnd(d,2),c.addRange(b),c.addRange(e),F=2==c.rangeCount,b.detach(),e.detach(),B.removeChild(a)}(),a.features.selectionSupportsMultipleRanges=F,a.features.collapsedNonEditableSelectionsSupported=G;var H,I=!1;B&&s.isHostMethod(B,"createControlRange")&&(H=B.createControlRange(),s.areHostProperties(H,["item","add"])&&(I=!0)),a.features.implementsControlRange=I,q=C?function(a){return a.anchorNode===a.focusNode&&a.anchorOffset===a.focusOffset}:function(a){return a.rangeCount?a.getRangeAt(a.rangeCount-1).collapsed:!1};var J;if(s.isHostMethod(x,"getRangeAt")?J=function(a,b){try{return a.getRangeAt(b)}catch(c){return null}}:C&&(J=function(b){var c=r.getDocument(b.anchorNode),c=a.createRange(c);return c.setStart(b.anchorNode,b.anchorOffset),c.setEnd(b.focusNode,b.focusOffset),c.collapsed!==this.isCollapsed&&(c.setStart(b.focusNode,b.focusOffset),c.setEnd(b.anchorNode,b.anchorOffset)),c}),a.getSelection=function(a){var a=a||window,b=a._rangySelection,c=p(a),e=y?d(a):null;return b?(b.nativeSelection=c,b.docSelection=e,b.refresh(a)):(b=new l(c,e,a),a._rangySelection=b),b},a.getIframeSelection=function(b){return a.getSelection(r.getIframeWindow(b))},H=l.prototype,!z&&C&&s.areHostMethods(x,["removeAllRanges","addRange"])){H.removeAllRanges=function(){this.nativeSelection.removeAllRanges(),f(this)};var K=function(b,c){var d=t.getRangeDocument(c),d=a.createRange(d);d.collapseToPoint(c.endContainer,c.endOffset),b.nativeSelection.addRange(g(d)),b.nativeSelection.extend(c.startContainer,c.startOffset),b.refresh()};H.addRange=E?function(b,c){if(I&&y&&"Control"==this.docSelection.type)k(this,b);else if(c&&D)K(this,b);else{var d;F?d=this.rangeCount:(this.removeAllRanges(),d=0),this.nativeSelection.addRange(g(b)),this.rangeCount=this.nativeSelection.rangeCount,this.rangeCount==d+1?(a.config.checkSelectionRanges&&(d=J(this.nativeSelection,this.rangeCount-1))&&!t.rangesEqual(d,b)&&(b=new u(d)),this._ranges[this.rangeCount-1]=b,e(this,b,N(this.nativeSelection)),this.isCollapsed=q(this)):this.refresh()}}:function(a,b){b&&D?K(this,a):(this.nativeSelection.addRange(g(a)),this.refresh())},H.setRanges=function(a){if(I&&a.length>1)m(this,a);else{this.removeAllRanges();for(var b=0,c=a.length;c>b;++b)this.addRange(a[b])}}}else{if(!(s.isHostMethod(x,"empty")&&s.isHostMethod(A,"select")&&I&&z))return b.fail("No means of selecting a Range or TextRange was found"),!1;H.removeAllRanges=function(){try{if(this.docSelection.empty(),"None"!=this.docSelection.type){var a;if(this.anchorNode)a=r.getDocument(this.anchorNode);else if("Control"==this.docSelection.type){var b=this.docSelection.createRange();b.length&&(a=r.getDocument(b.item(0)).body.createTextRange())}a&&(a.body.createTextRange().select(),this.docSelection.empty())}}catch(c){}f(this)},H.addRange=function(a){"Control"==this.docSelection.type?k(this,a):(u.rangeToTextRange(a).select(),this._ranges[0]=a,this.rangeCount=1,this.isCollapsed=this._ranges[0].collapsed,e(this,a,!1))},H.setRanges=function(a){this.removeAllRanges();var b=a.length;b>1?m(this,a):b&&this.addRange(a[0])}}H.getRangeAt=function(a){if(0>a||a>=this.rangeCount)throw new v("INDEX_SIZE_ERR");return this._ranges[a]};var L;if(z)L=function(b){var c;a.isSelectionValid(b.win)?c=b.docSelection.createRange():(c=r.getBody(b.win.document).createTextRange(),c.collapse(!0)),"Control"==b.docSelection.type?j(b):c&&"undefined"!=typeof c.text?i(b,c):f(b)};else if(s.isHostMethod(x,"getRangeAt")&&"number"==typeof x.rangeCount)L=function(b){if(I&&y&&"Control"==b.docSelection.type)j(b);else if(b._ranges.length=b.rangeCount=b.nativeSelection.rangeCount,b.rangeCount){for(var c=0,d=b.rangeCount;d>c;++c)b._ranges[c]=new a.WrappedRange(b.nativeSelection.getRangeAt(c));e(b,b._ranges[b.rangeCount-1],N(b.nativeSelection)),b.isCollapsed=q(b)}else f(b)};else{if(!C||"boolean"!=typeof x.isCollapsed||"boolean"!=typeof A.collapsed||!a.features.implementsDomRange)return b.fail("No means of obtaining a Range or TextRange from the user's selection was found"),!1;L=function(a){var b;b=a.nativeSelection,b.anchorNode?(b=J(b,0),a._ranges=[b],a.rangeCount=1,b=a.nativeSelection,a.anchorNode=b.anchorNode,a.anchorOffset=b.anchorOffset,a.focusNode=b.focusNode,a.focusOffset=b.focusOffset,a.isCollapsed=q(a)):f(a)}}H.refresh=function(a){var b=a?this._ranges.slice(0):null;if(L(this),a){if(a=b.length,a!=this._ranges.length)return!1;for(;a--;)if(!t.rangesEqual(b[a],this._ranges[a]))return!1;return!0}};var M=function(a,b){var c=a.getAllRanges(),d=!1;a.removeAllRanges();for(var e=0,g=c.length;g>e;++e)d||b!==c[e]?a.addRange(c[e]):d=!0;a.rangeCount||f(a)};H.removeRange=I?function(a){if("Control"==this.docSelection.type){for(var b,c=this.docSelection.createRange(),a=h(a),d=r.getDocument(c.item(0)),d=r.getBody(d).createControlRange(),e=!1,f=0,g=c.length;g>f;++f)b=c.item(f),b!==a||e?d.add(c.item(f)):e=!0;d.select(),j(this)}else M(this,a)}:function(a){M(this,a)};var N;!z&&C&&a.features.implementsDomRange?(N=function(a){var b=!1;return a.anchorNode&&(b=1==r.comparePoints(a.anchorNode,a.anchorOffset,a.focusNode,a.focusOffset)),b},H.isBackwards=function(){return N(this)}):N=H.isBackwards=function(){return!1},H.toString=function(){for(var a=[],b=0,c=this.rangeCount;c>b;++b)a[b]=""+this._ranges[b];return a.join("")},H.collapse=function(b,c){n(this,b);var d=a.createRange(r.getDocument(b));d.collapseToPoint(b,c),this.removeAllRanges(),this.addRange(d),this.isCollapsed=!0},H.collapseToStart=function(){if(!this.rangeCount)throw new v("INVALID_STATE_ERR");var a=this._ranges[0];this.collapse(a.startContainer,a.startOffset)},H.collapseToEnd=function(){if(!this.rangeCount)throw new v("INVALID_STATE_ERR");var a=this._ranges[this.rangeCount-1];this.collapse(a.endContainer,a.endOffset)},H.selectAllChildren=function(b){n(this,b);var c=a.createRange(r.getDocument(b));c.selectNodeContents(b),this.removeAllRanges(),this.addRange(c)},H.deleteFromDocument=function(){if(I&&y&&"Control"==this.docSelection.type){for(var a,b=this.docSelection.createRange();b.length;)a=b.item(0),b.remove(a),a.parentNode.removeChild(a);this.refresh()}else if(this.rangeCount){b=this.getAllRanges(),this.removeAllRanges(),a=0;for(var c=b.length;c>a;++a)b[a].deleteContents();this.addRange(b[c-1])}},H.getAllRanges=function(){return this._ranges.slice(0)},H.setSingleRange=function(a){this.setRanges([a])},H.containsNode=function(a,b){for(var c=0,d=this._ranges.length;d>c;++c)if(this._ranges[c].containsNode(a,b))return!0;return!1},H.toHtml=function(){var a="";if(this.rangeCount){for(var a=t.getRangeDocument(this._ranges[0]).createElement("div"),b=0,c=this._ranges.length;c>b;++b)a.appendChild(this._ranges[b].cloneContents());a=a.innerHTML}return a},H.getName=function(){return"WrappedSelection"},H.inspect=function(){return o(this)},H.detach=function(){this.win=this.anchorNode=this.focusNode=this.win._rangySelection=null},l.inspect=o,a.Selection=l,a.selectionPrototype=H,a.addCreateMissingNativeApiListener(function(b){"undefined"==typeof b.getSelection&&(b.getSelection=function(){return a.getSelection(this)}),b=null})});var Base=function(){};Base.extend=function(a,b){var c=Base.prototype.extend;Base._prototyping=!0;var d=new this;c.call(d,a),d.base=function(){},delete Base._prototyping;var e=d.constructor,f=d.constructor=function(){if(!Base._prototyping)if(this._constructing||this.constructor==f)this._constructing=!0,e.apply(this,arguments),delete this._constructing;else if(null!=arguments[0])return(arguments[0].extend||c).call(arguments[0],d)};return f.ancestor=this,f.extend=this.extend,f.forEach=this.forEach,f.implement=this.implement,f.prototype=d,f.toString=this.toString,f.valueOf=function(a){return"object"==a?f:e.valueOf()},c.call(f,b),"function"==typeof f.init&&f.init(),f},Base.prototype={extend:function(a,b){if(1<arguments.length){var c=this[a];if(c&&"function"==typeof b&&(!c.valueOf||c.valueOf()!=b.valueOf())&&/\bbase\b/.test(b)){var d=b.valueOf(),b=function(){var a=this.base||Base.prototype.base;this.base=c;var b=d.apply(this,arguments);return this.base=a,b};b.valueOf=function(a){return"object"==a?b:d},b.toString=Base.toString}this[a]=b}else if(a){var e=Base.prototype.extend;!Base._prototyping&&"function"!=typeof this&&(e=this.extend||e);for(var f={toSource:null},g=["constructor","toString","valueOf"],h=Base._prototyping?0:1;i=g[h++];)a[i]!=f[i]&&e.call(this,i,a[i]);for(var i in a)f[i]||e.call(this,i,a[i])}return this}},Base=Base.extend({constructor:function(a){this.extend(a)}},{ancestor:Object,version:"1.1",forEach:function(a,b,c){for(var d in a)void 0===this.prototype[d]&&b.call(c,a[d],d,a)},implement:function(){for(var a=0;a<arguments.length;a++)"function"==typeof arguments[a]?arguments[a](this.prototype):this.prototype.extend(arguments[a]);return this},toString:function(){return""+this.valueOf()}}),wysihtml5.browser=function(){var a=navigator.userAgent,b=document.createElement("div"),c=-1!==a.indexOf("MSIE")&&-1===a.indexOf("Opera"),d=-1!==a.indexOf("Gecko")&&-1===a.indexOf("KHTML"),e=-1!==a.indexOf("AppleWebKit/"),f=-1!==a.indexOf("Chrome/"),g=-1!==a.indexOf("Opera/");return{USER_AGENT:a,supported:function(){var a=this.USER_AGENT.toLowerCase(),c="contentEditable"in b,d=document.execCommand&&document.queryCommandSupported&&document.queryCommandState,e=document.querySelector&&document.querySelectorAll,a=this.isIos()&&5>(/ipad|iphone|ipod/.test(a)&&a.match(/ os (\d+).+? like mac os x/)||[,0])[1]||-1!==a.indexOf("opera mobi")||-1!==a.indexOf("hpwos/");return c&&d&&e&&!a},isTouchDevice:function(){return this.supportsEvent("touchmove")},isIos:function(){var a=this.USER_AGENT.toLowerCase();return-1!==a.indexOf("webkit")&&-1!==a.indexOf("mobile")},supportsSandboxedIframes:function(){return c},throwsMixedContentWarningWhenIframeSrcIsEmpty:function(){return!("querySelector"in document)},displaysCaretInEmptyContentEditableCorrectly:function(){return!d},hasCurrentStyleProperty:function(){return"currentStyle"in b},insertsLineBreaksOnReturn:function(){return d},supportsPlaceholderAttributeOn:function(a){return"placeholder"in a},supportsEvent:function(a){var c;return(c="on"+a in b)||(b.setAttribute("on"+a,"return;"),c="function"==typeof b["on"+a]),c},supportsEventsInIframeCorrectly:function(){return!g},firesOnDropOnlyWhenOnDragOverIsCancelled:function(){return e||d},supportsDataTransfer:function(){try{return e&&(window.Clipboard||window.DataTransfer).prototype.getData}catch(a){return!1}},supportsHTML5Tags:function(a){return a=a.createElement("div"),a.innerHTML="<article>foo</article>","<article>foo</article>"===a.innerHTML.toLowerCase()},supportsCommand:function(){var a={formatBlock:c,insertUnorderedList:c||g||e,insertOrderedList:c||g||e},b={insertHTML:d};return function(c,d){if(!a[d]){try{return c.queryCommandSupported(d)}catch(e){}try{return c.queryCommandEnabled(d)}catch(f){return!!b[d]}}return!1}}(),doesAutoLinkingInContentEditable:function(){return c},canDisableAutoLinking:function(){return this.supportsCommand(document,"AutoUrlDetect")},clearsContentEditableCorrectly:function(){return d||g||e},supportsGetAttributeCorrectly:function(){return"1"!=document.createElement("td").getAttribute("rowspan")},canSelectImagesInContentEditable:function(){return d||c||g},clearsListsInContentEditableCorrectly:function(){return d||c||e},autoScrollsToCaret:function(){return!e},autoClosesUnclosedTags:function(){var a,c=b.cloneNode(!1);return c.innerHTML="<p><div></div>",c=c.innerHTML.toLowerCase(),a="<p></p><div></div>"===c||"<p><div></div></p>"===c,this.autoClosesUnclosedTags=function(){return a},a},supportsNativeGetElementsByClassName:function(){return-1!==(""+document.getElementsByClassName).indexOf("[native code]")},supportsSelectionModify:function(){return"getSelection"in window&&"modify"in window.getSelection()},supportsClassList:function(){return"classList"in b},needsSpaceAfterLineBreak:function(){return g},supportsSpeechApiOn:function(b){return 11<=(a.match(/Chrome\/(\d+)/)||[,0])[1]&&("onwebkitspeechchange"in b||"speech"in b)},crashesWhenDefineProperty:function(a){return c&&("XMLHttpRequest"===a||"XDomainRequest"===a)},doesAsyncFocus:function(){return c},hasProblemsSettingCaretAfterImg:function(){return c},hasUndoInContextMenu:function(){return d||f||g}}}(),wysihtml5.lang.array=function(a){return{contains:function(b){if(a.indexOf)return-1!==a.indexOf(b);for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return!0;return!1},without:function(b){for(var b=wysihtml5.lang.array(b),c=[],d=0,e=a.length;e>d;d++)b.contains(a[d])||c.push(a[d]);return c},get:function(){for(var b=0,c=a.length,d=[];c>b;b++)d.push(a[b]);return d}}},wysihtml5.lang.Dispatcher=Base.extend({observe:function(a,b){return this.events=this.events||{},this.events[a]=this.events[a]||[],this.events[a].push(b),this},on:function(){return this.observe.apply(this,wysihtml5.lang.array(arguments).get())},fire:function(a,b){this.events=this.events||{};for(var c=this.events[a]||[],d=0;d<c.length;d++)c[d].call(this,b);return this},stopObserving:function(a,b){this.events=this.events||{};var c,d,e=0;if(a){for(c=this.events[a]||[],d=[];e<c.length;e++)c[e]!==b&&b&&d.push(c[e]);this.events[a]=d}else this.events={};return this}}),wysihtml5.lang.object=function(a){return{merge:function(b){for(var c in b)a[c]=b[c];return this},get:function(){return a},clone:function(){var b,c={};for(b in a)c[b]=a[b];return c},isArray:function(){return"[object Array]"===Object.prototype.toString.call(a)}}},function(){var a=/^\s+/,b=/\s+$/;wysihtml5.lang.string=function(c){return c=""+c,{trim:function(){return c.replace(a,"").replace(b,"")},interpolate:function(a){for(var b in a)c=this.replace("#{"+b+"}").by(a[b]);return c},replace:function(a){return{by:function(b){return c.split(a).join(b)}}}}}}(),function(a){function b(a){return a.replace(e,function(a,b){var c=(b.match(f)||[])[1]||"",d=h[c],b=b.replace(f,"");b.split(d).length>b.split(c).length&&(b+=c,c="");var e=d=b;return b.length>g&&(e=e.substr(0,g)+"..."),"www."===d.substr(0,4)&&(d="http://"+d),'<a href="'+d+'">'+e+"</a>"+c})}function c(f){if(!d.contains(f.nodeName)){if(f.nodeType!==a.TEXT_NODE||!f.data.match(e)){for(h=a.lang.array(f.childNodes).get(),g=h.length,i=0;g>i;i++)c(h[i]);return f}var g,h=f.parentNode;g=h.ownerDocument;var i=g._wysihtml5_tempElement;for(i||(i=g._wysihtml5_tempElement=g.createElement("div")),g=i,g.innerHTML="<span></span>"+b(f.data),g.removeChild(g.firstChild);g.firstChild;)h.insertBefore(g.firstChild,f);h.removeChild(f)}}var d=a.lang.array("CODE PRE A SCRIPT HEAD TITLE STYLE".split(" ")),e=/((https?:\/\/|www\.)[^\s<]{3,})/gi,f=/([^\w\/\-](,?))$/i,g=100,h={")":"(","]":"[","}":"{"};a.dom.autoLink=function(a){var b;a:{b=a;for(var e;b.parentNode;){if(b=b.parentNode,e=b.nodeName,d.contains(e)){b=!0;break a}if("body"===e)break}b=!1}return b?a:(a===a.ownerDocument.documentElement&&(a=a.ownerDocument.body),c(a))},a.dom.autoLink.URL_REG_EXP=e}(wysihtml5),function(a){var b=a.browser.supportsClassList(),c=a.dom;c.addClass=function(a,d){return b?a.classList.add(d):void(c.hasClass(a,d)||(a.className+=" "+d))},c.removeClass=function(a,c){return b?a.classList.remove(c):void(a.className=a.className.replace(RegExp("(^|\\s+)"+c+"(\\s+|$)")," "))},c.hasClass=function(a,c){if(b)return a.classList.contains(c);var d=a.className;return 0<d.length&&(d==c||RegExp("(^|\\s)"+c+"(\\s|$)").test(d))}}(wysihtml5),wysihtml5.dom.contains=function(){var a=document.documentElement;return a.contains?function(a,b){return b.nodeType!==wysihtml5.ELEMENT_NODE&&(b=b.parentNode),a!==b&&a.contains(b)}:a.compareDocumentPosition?function(a,b){return!!(16&a.compareDocumentPosition(b))}:void 0}(),wysihtml5.dom.convertToList=function(){function a(a,b){var c=a.createElement("li");return b.appendChild(c),c}return function(b,c){if("UL"===b.nodeName||"OL"===b.nodeName||"MENU"===b.nodeName)return b;var d,e,f,g,h,i=b.ownerDocument,j=i.createElement(c),k=b.querySelectorAll("br"),l=k.length;for(h=0;l>h;h++)for(d=k[h];(e=d.parentNode)&&e!==b&&e.lastChild===d;){if("block"===wysihtml5.dom.getStyle("display").from(e)){e.removeChild(d);break}wysihtml5.dom.insert(d).after(d.parentNode)}for(k=wysihtml5.lang.array(b.childNodes).get(),l=k.length,h=0;l>h;h++)g=g||a(i,j),d=k[h],e="block"===wysihtml5.dom.getStyle("display").from(d),f="BR"===d.nodeName,e?(g=g.firstChild?a(i,j):g,g.appendChild(d),g=null):f?g=g.firstChild?null:g:g.appendChild(d);return b.parentNode.replaceChild(j,b),j}}(),wysihtml5.dom.copyAttributes=function(a){return{from:function(b){return{to:function(c){for(var d,e=0,f=a.length;f>e;e++)d=a[e],"undefined"!=typeof b[d]&&""!==b[d]&&(c[d]=b[d]);return{andTo:arguments.callee}}}}}},function(a){var b=["-webkit-box-sizing","-moz-box-sizing","-ms-box-sizing","box-sizing"],c=function(c){var d;a:for(var e=0,f=b.length;f>e;e++)if("border-box"===a.getStyle(b[e]).from(c)){d=b[e];break a}return d?parseInt(a.getStyle("width").from(c),10)<c.offsetWidth:!1};a.copyStyles=function(d){return{from:function(e){c(e)&&(d=wysihtml5.lang.array(d).without(b));for(var f,g="",h=d.length,i=0;h>i;i++)f=d[i],g+=f+":"+a.getStyle(f).from(e)+";";return{to:function(b){return a.setStyles(g).on(b),{andTo:arguments.callee}}}}}}}(wysihtml5.dom),function(a){a.dom.delegate=function(b,c,d,e){return a.dom.observe(b,d,function(d){for(var f=d.target,g=a.lang.array(b.querySelectorAll(c));f&&f!==b;){if(g.contains(f)){e.call(f,d);break}f=f.parentNode}})}}(wysihtml5),wysihtml5.dom.getAsDom=function(){var a="abbr article aside audio bdi canvas command datalist details figcaption figure footer header hgroup keygen mark meter nav output progress rp rt ruby svg section source summary time track video wbr".split(" ");return function(b,c){var d,c=c||document;if("object"==typeof b&&b.nodeType)d=c.createElement("div"),d.appendChild(b);else if(wysihtml5.browser.supportsHTML5Tags(c))d=c.createElement("div"),d.innerHTML=b;else{if(d=c,!d._wysihtml5_supportsHTML5Tags){for(var e=0,f=a.length;f>e;e++)d.createElement(a[e]);d._wysihtml5_supportsHTML5Tags=!0}d=c,e=d.createElement("div"),e.style.display="none",d.body.appendChild(e);try{e.innerHTML=b}catch(g){}d.body.removeChild(e),d=e}return d}}(),wysihtml5.dom.getParentElement=function(){function a(a,b){return b&&b.length?"string"==typeof b?a===b:wysihtml5.lang.array(b).contains(a):!0}return function(b,c,d){if(d=d||50,c.className||c.classRegExp){a:{for(var e=c.nodeName,f=c.className,c=c.classRegExp;d--&&b&&"BODY"!==b.nodeName;){var g;if((g=b.nodeType===wysihtml5.ELEMENT_NODE)&&(g=a(b.nodeName,e))){g=f;var h=(b.className||"").match(c)||[];g=g?h[h.length-1]===g:!!h.length}if(g)break a;b=b.parentNode}b=null}return b}a:{for(e=c.nodeName,f=d;f--&&b&&"BODY"!==b.nodeName;){if(a(b.nodeName,e))break a;b=b.parentNode}b=null}return b}}(),wysihtml5.dom.getStyle=function(){function a(a){return a.replace(c,function(a){return a.charAt(1).toUpperCase()})}var b={"float":"styleFloat"in document.createElement("div").style?"styleFloat":"cssFloat"},c=/\-[a-z]/g;return function(c){return{from:function(d){if(d.nodeType===wysihtml5.ELEMENT_NODE){var e=d.ownerDocument,f=b[c]||a(c),g=d.style,h=d.currentStyle,i=g[f];if(i)return i;if(h)try{return h[f]}catch(j){}var k,f=e.defaultView||e.parentWindow,e=("height"===c||"width"===c)&&"TEXTAREA"===d.nodeName;if(f.getComputedStyle)return e&&(k=g.overflow,g.overflow="hidden"),d=f.getComputedStyle(d,null).getPropertyValue(c),e&&(g.overflow=k||""),d}}}}}(),wysihtml5.dom.hasElementWithTagName=function(){var a={},b=1;return function(c,d){var e=(c._wysihtml5_identifier||(c._wysihtml5_identifier=b++))+":"+d,f=a[e];return f||(f=a[e]=c.getElementsByTagName(d)),0<f.length}}(),function(a){var b={},c=1;a.dom.hasElementWithClassName=function(d,e){if(!a.browser.supportsNativeGetElementsByClassName())return!!d.querySelector("."+e);var f=(d._wysihtml5_identifier||(d._wysihtml5_identifier=c++))+":"+e,g=b[f];return g||(g=b[f]=d.getElementsByClassName(e)),0<g.length}}(wysihtml5),wysihtml5.dom.insert=function(a){return{after:function(b){b.parentNode.insertBefore(a,b.nextSibling)},before:function(b){b.parentNode.insertBefore(a,b)},into:function(b){b.appendChild(a)}}},wysihtml5.dom.insertCSS=function(a){return a=a.join("\n"),{into:function(b){var c=b.head||b.getElementsByTagName("head")[0],d=b.createElement("style");d.type="text/css",d.styleSheet?d.styleSheet.cssText=a:d.appendChild(b.createTextNode(a)),c&&c.appendChild(d)}}},wysihtml5.dom.observe=function(a,b,c){for(var d,e,b="string"==typeof b?[b]:b,f=0,g=b.length;g>f;f++)e=b[f],a.addEventListener?a.addEventListener(e,c,!1):(d=function(b){"target"in b||(b.target=b.srcElement),b.preventDefault=b.preventDefault||function(){this.returnValue=!1},b.stopPropagation=b.stopPropagation||function(){this.cancelBubble=!0},c.call(a,b)},a.attachEvent("on"+e,d));return{stop:function(){for(var e,f=0,g=b.length;g>f;f++)e=b[f],a.removeEventListener?a.removeEventListener(e,c,!1):a.detachEvent("on"+e,d)}}},wysihtml5.dom.parse=function(){function a(b,e){var f,g=b.childNodes,h=g.length;f=c[b.nodeType];var i=0;if(f=f&&f(b),!f)return null;for(i=0;h>i;i++)(newChild=a(g[i],e))&&f.appendChild(newChild);return e&&1>=f.childNodes.length&&f.nodeName.toLowerCase()===d&&!f.attributes.length?f.firstChild:f}function b(a,b){var c,b=b.toLowerCase();if((c="IMG"==a.nodeName)&&(c="src"==b)){var d;try{d=a.complete&&!a.mozMatchesSelector(":-moz-broken")}catch(e){a.complete&&"complete"===a.readyState&&(d=!0)}c=!0===d}return c?a.src:h&&"outerHTML"in a?-1!=a.outerHTML.toLowerCase().indexOf(" "+b+"=")?a.getAttribute(b):null:a.getAttribute(b)}var c={1:function(a){var c,f,h=g.tags;if(f=a.nodeName.toLowerCase(),c=a.scopeName,a._wysihtml5)return null;if(a._wysihtml5=1,"wysihtml5-temp"===a.className)return null;if(c&&"HTML"!=c&&(f=c+":"+f),"outerHTML"in a&&!wysihtml5.browser.autoClosesUnclosedTags()&&"P"===a.nodeName&&"</p>"!==a.outerHTML.slice(-4).toLowerCase()&&(f="div"),f in h){if(c=h[f],!c||c.remove)return null;c="string"==typeof c?{rename_tag:c}:c}else{if(!a.firstChild)return null;c={rename_tag:d}}f=a.ownerDocument.createElement(c.rename_tag||f);var h={},k=c.set_class,l=c.add_class,m=c.set_attributes,n=c.check_attributes,o=g.classes,p=0,q=[];c=[];var r,s=[],t=[];if(m&&(h=wysihtml5.lang.object(m).clone()),n)for(r in n)(m=i[n[r]])&&(m=m(b(a,r)),"string"==typeof m&&(h[r]=m));if(k&&q.push(k),l)for(r in l)(m=j[l[r]])&&(k=m(b(a,r)),"string"==typeof k&&q.push(k));for(o["_wysihtml5-temp-placeholder"]=1,(t=a.getAttribute("class"))&&(q=q.concat(t.split(e))),l=q.length;l>p;p++)a=q[p],o[a]&&c.push(a);for(o=c.length;o--;)a=c[o],wysihtml5.lang.array(s).contains(a)||s.unshift(a);s.length&&(h["class"]=s.join(" "));for(r in h)try{f.setAttribute(r,h[r])}catch(u){}return h.src&&("undefined"!=typeof h.width&&f.setAttribute("width",h.width),"undefined"!=typeof h.height&&f.setAttribute("height",h.height)),f},3:function(a){return a.ownerDocument.createTextNode(a.data)}},d="span",e=/\s+/,f={tags:{},classes:{}},g={},h=!wysihtml5.browser.supportsGetAttributeCorrectly(),i={url:function(){var a=/^https?:\/\//i;return function(b){return b&&b.match(a)?b.replace(a,function(a){return a.toLowerCase()}):null}}(),alt:function(){var a=/[^ a-z0-9_\-]/gi;return function(b){return b?b.replace(a,""):""}}(),numbers:function(){var a=/\D/g;return function(b){return(b=(b||"").replace(a,""))||null}}()},j={align_img:function(){var a={left:"wysiwyg-float-left",right:"wysiwyg-float-right"};return function(b){return a[(""+b).toLowerCase()]}}(),align_text:function(){var a={left:"wysiwyg-text-align-left",right:"wysiwyg-text-align-right",center:"wysiwyg-text-align-center",justify:"wysiwyg-text-align-justify"};return function(b){return a[(""+b).toLowerCase()]}}(),clear_br:function(){var a={left:"wysiwyg-clear-left",right:"wysiwyg-clear-right",both:"wysiwyg-clear-both",all:"wysiwyg-clear-both"};return function(b){return a[(""+b).toLowerCase()]}}(),size_font:function(){var a={1:"wysiwyg-font-size-xx-small",2:"wysiwyg-font-size-small",3:"wysiwyg-font-size-medium",4:"wysiwyg-font-size-large",5:"wysiwyg-font-size-x-large",6:"wysiwyg-font-size-xx-large",7:"wysiwyg-font-size-xx-large","-":"wysiwyg-font-size-smaller","+":"wysiwyg-font-size-larger"};return function(b){return a[(""+b).charAt(0)]}}()};return function(b,c,d,e){wysihtml5.lang.object(g).merge(f).merge(c).get();for(var d=d||b.ownerDocument||document,c=d.createDocumentFragment(),h="string"==typeof b,b=h?wysihtml5.dom.getAsDom(b,d):b;b.firstChild;)d=b.firstChild,b.removeChild(d),(d=a(d,e))&&c.appendChild(d);return b.innerHTML="",b.appendChild(c),h?wysihtml5.quirks.getCorrectInnerHTML(b):b}}(),wysihtml5.dom.removeEmptyTextNodes=function(a){for(var b=wysihtml5.lang.array(a.childNodes).get(),c=b.length,d=0;c>d;d++)a=b[d],a.nodeType===wysihtml5.TEXT_NODE&&""===a.data&&a.parentNode.removeChild(a)},wysihtml5.dom.renameElement=function(a,b){for(var c,d=a.ownerDocument.createElement(b);c=a.firstChild;)d.appendChild(c);return wysihtml5.dom.copyAttributes(["align","className"]).from(a).to(d),a.parentNode.replaceChild(d,a),d},wysihtml5.dom.replaceWithChildNodes=function(a){if(a.parentNode)if(a.firstChild){for(var b=a.ownerDocument.createDocumentFragment();a.firstChild;)b.appendChild(a.firstChild);a.parentNode.replaceChild(b,a)}else a.parentNode.removeChild(a)},function(a){function b(a){var b=a.ownerDocument.createElement("br");a.appendChild(b)}a.resolveList=function(c){if("MENU"===c.nodeName||"UL"===c.nodeName||"OL"===c.nodeName){var d,e,f,g=c.ownerDocument.createDocumentFragment(),h=c.previousElementSibling||c.previousSibling;for(h&&"block"!==a.getStyle("display").from(h)&&b(g);f=c.firstChild;){for(d=f.lastChild;h=f.firstChild;)e=(e=h===d)&&"block"!==a.getStyle("display").from(h)&&"BR"!==h.nodeName,g.appendChild(h),e&&b(g);f.parentNode.removeChild(f)}c.parentNode.replaceChild(g,c)}}}(wysihtml5.dom),function(a){var b=document,c="parent top opener frameElement frames localStorage globalStorage sessionStorage indexedDB".split(" "),d="open close openDialog showModalDialog alert confirm prompt openDatabase postMessage XMLHttpRequest XDomainRequest".split(" "),e=["referrer","write","open","close"];a.dom.Sandbox=Base.extend({constructor:function(b,c){this.callback=b||a.EMPTY_FUNCTION,this.config=a.lang.object({}).merge(c).get(),this.iframe=this._createIframe()},insertInto:function(a){"string"==typeof a&&(a=b.getElementById(a)),a.appendChild(this.iframe)},getIframe:function(){return this.iframe},getWindow:function(){this._readyError()},getDocument:function(){this._readyError()},destroy:function(){var a=this.getIframe();a.parentNode.removeChild(a)},_readyError:function(){throw Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet")},_createIframe:function(){var c=this,d=b.createElement("iframe");return d.className="wysihtml5-sandbox",a.dom.setAttributes({security:"restricted",allowtransparency:"true",frameborder:0,width:0,height:0,marginwidth:0,marginheight:0}).on(d),a.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()&&(d.src="javascript:'<html></html>'"),d.onload=function(){d.onreadystatechange=d.onload=null,c._onLoadIframe(d)},d.onreadystatechange=function(){/loaded|complete/.test(d.readyState)&&(d.onreadystatechange=d.onload=null,c._onLoadIframe(d))},d},_onLoadIframe:function(f){if(a.dom.contains(b.documentElement,f)){var g=this,h=f.contentWindow,i=f.contentWindow.document,j=this._getHtml({charset:b.characterSet||b.charset||"utf-8",stylesheets:this.config.stylesheets});if(i.open("text/html","replace"),i.write(j),i.close(),this.getWindow=function(){return f.contentWindow},this.getDocument=function(){return f.contentWindow.document},h.onerror=function(a,b,c){throw Error("wysihtml5.Sandbox: "+a,b,c)},!a.browser.supportsSandboxedIframes()){var k,j=0;for(k=c.length;k>j;j++)this._unset(h,c[j]);for(j=0,k=d.length;k>j;j++)this._unset(h,d[j],a.EMPTY_FUNCTION);for(j=0,k=e.length;k>j;j++)this._unset(i,e[j]);this._unset(i,"cookie","",!0)}this.loaded=!0,setTimeout(function(){g.callback(g)},0)}},_getHtml:function(b){var c,d=b.stylesheets,e="",f=0;if(d="string"==typeof d?[d]:d)for(c=d.length;c>f;f++)e+='<link rel="stylesheet" href="'+d[f]+'">';return b.stylesheets=e,a.lang.string('<!DOCTYPE html><html><head><meta charset="#{charset}">#{stylesheets}</head><body></body></html>').interpolate(b)},_unset:function(b,c,d,e){try{b[c]=d}catch(f){}try{b.__defineGetter__(c,function(){return d})}catch(g){}if(e)try{b.__defineSetter__(c,function(){})}catch(h){}if(!a.browser.crashesWhenDefineProperty(c))try{var i={get:function(){return d}};e&&(i.set=function(){}),Object.defineProperty(b,c,i)}catch(j){}}})}(wysihtml5),function(){var a={className:"class"};wysihtml5.dom.setAttributes=function(b){return{on:function(c){for(var d in b)c.setAttribute(a[d]||d,b[d])}}}}(),wysihtml5.dom.setStyles=function(a){return{on:function(b){if(b=b.style,"string"==typeof a)b.cssText+=";"+a;else for(var c in a)"float"===c?(b.cssFloat=a[c],b.styleFloat=a[c]):b[c]=a[c]}}},function(a){a.simulatePlaceholder=function(b,c,d){var e=function(){c.hasPlaceholderSet()&&c.clear(),a.removeClass(c.element,"placeholder")},f=function(){c.isEmpty()&&(c.setValue(d),a.addClass(c.element,"placeholder"))};b.observe("set_placeholder",f).observe("unset_placeholder",e).observe("focus:composer",e).observe("paste:composer",e).observe("blur:composer",f),f()}}(wysihtml5.dom),function(a){var b=document.documentElement;"textContent"in b?(a.setTextContent=function(a,b){a.textContent=b},a.getTextContent=function(a){return a.textContent}):"innerText"in b?(a.setTextContent=function(a,b){a.innerText=b},a.getTextContent=function(a){return a.innerText}):(a.setTextContent=function(a,b){a.nodeValue=b},a.getTextContent=function(a){return a.nodeValue})}(wysihtml5.dom),wysihtml5.quirks.cleanPastedHTML=function(){var a={"a u":wysihtml5.dom.replaceWithChildNodes};return function(b,c,d){var e,f,g,c=c||a,d=d||b.ownerDocument||document,h="string"==typeof b,i=0,b=h?wysihtml5.dom.getAsDom(b,d):b;for(g in c)for(e=b.querySelectorAll(g),d=c[g],f=e.length;f>i;i++)d(e[i]);return h?b.innerHTML:b}}(),function(a){var b=a.dom;a.quirks.ensureProperClearing=function(){var a=function(){var a=this;setTimeout(function(){var b=a.innerHTML.toLowerCase();("<p> </p>"==b||"<p> </p><p> </p>"==b)&&(a.innerHTML="")
+},0)};return function(c){b.observe(c.element,["cut","keydown"],a)}}(),a.quirks.ensureProperClearingOfLists=function(){var c=["OL","UL","MENU"];return function(d){b.observe(d.element,"keydown",function(e){if(e.keyCode===a.BACKSPACE_KEY){var f=d.selection.getSelectedNode(),e=d.element;e.firstChild&&a.lang.array(c).contains(e.firstChild.nodeName)&&(f=b.getParentElement(f,{nodeName:c}))&&f==e.firstChild&&1>=f.childNodes.length&&(f.firstChild?""===f.firstChild.innerHTML:1)&&f.parentNode.removeChild(f)}})}}()}(wysihtml5),function(a){a.quirks.getCorrectInnerHTML=function(b){var c=b.innerHTML;if(-1===c.indexOf("%7E"))return c;var d,e,f,g,b=b.querySelectorAll("[href*='~'], [src*='~']");for(g=0,f=b.length;f>g;g++)d=b[g].href||b[g].src,e=a.lang.string(d).replace("~").by("%7E"),c=a.lang.string(c).replace(e).by(d);return c}}(wysihtml5),function(a){var b=a.dom,c="LI P H1 H2 H3 H4 H5 H6".split(" "),d=["UL","OL","MENU"];a.quirks.insertLineBreakOnReturn=function(e){function f(c){if(c=b.getParentElement(c,{nodeName:["P","DIV"]},2)){var d=document.createTextNode(a.INVISIBLE_SPACE);b.insert(d).before(c),b.replaceWithChildNodes(c),e.selection.selectNode(d)}}b.observe(e.element.ownerDocument,"keydown",function(g){var h=g.keyCode;if(!(g.shiftKey||h!==a.ENTER_KEY&&h!==a.BACKSPACE_KEY)){var i=e.selection.getSelectedNode();(i=b.getParentElement(i,{nodeName:c},4))?"LI"!==i.nodeName||h!==a.ENTER_KEY&&h!==a.BACKSPACE_KEY?i.nodeName.match(/H[1-6]/)&&h===a.ENTER_KEY&&setTimeout(function(){f(e.selection.getSelectedNode())},0):setTimeout(function(){var a,c=e.selection.getSelectedNode();c&&((a=b.getParentElement(c,{nodeName:d},2))||f(c))},0):h===a.ENTER_KEY&&!a.browser.insertsLineBreaksOnReturn()&&(e.commands.exec("insertLineBreak"),g.preventDefault())}})}}(wysihtml5),function(a){a.quirks.redraw=function(b){a.dom.addClass(b,"wysihtml5-quirks-redraw"),a.dom.removeClass(b,"wysihtml5-quirks-redraw");try{var c=b.ownerDocument;c.execCommand("italic",!1,null),c.execCommand("italic",!1,null)}catch(d){}}}(wysihtml5),function(a){var b=a.dom;a.Selection=Base.extend({constructor:function(a){window.rangy.init(),this.editor=a,this.composer=a.composer,this.doc=this.composer.doc},getBookmark:function(){var a=this.getRange();return a&&a.cloneRange()},setBookmark:function(a){a&&this.setSelection(a)},setBefore:function(a){var b=rangy.createRange(this.doc);return b.setStartBefore(a),b.setEndBefore(a),this.setSelection(b)},setAfter:function(a){var b=rangy.createRange(this.doc);return b.setStartAfter(a),b.setEndAfter(a),this.setSelection(b)},selectNode:function(c){var d=rangy.createRange(this.doc),e=c.nodeType===a.ELEMENT_NODE,f="canHaveHTML"in c?c.canHaveHTML:"IMG"!==c.nodeName,g=e?c.innerHTML:c.data,g=""===g||g===a.INVISIBLE_SPACE,h=b.getStyle("display").from(c),h="block"===h||"list-item"===h;if(g&&e&&f)try{c.innerHTML=a.INVISIBLE_SPACE}catch(i){}f?d.selectNodeContents(c):d.selectNode(c),f&&g&&e?d.collapse(h):f&&g&&(d.setStartAfter(c),d.setEndAfter(c)),this.setSelection(d)},getSelectedNode:function(a){return a&&this.doc.selection&&"Control"===this.doc.selection.type&&(a=this.doc.selection.createRange())&&a.length?a.item(0):(a=this.getSelection(this.doc),a.focusNode===a.anchorNode?a.focusNode:(a=this.getRange(this.doc))?a.commonAncestorContainer:this.doc.body)},executeAndRestore:function(b,c){var d=this.doc.body,e=c&&d.scrollTop,f=c&&d.scrollLeft,g='<span class="_wysihtml5-temp-placeholder">'+a.INVISIBLE_SPACE+"</span>",h=this.getRange(this.doc);if(h){g=h.createContextualFragment(g),h.insertNode(g);try{b(h.startContainer,h.endContainer)}catch(i){setTimeout(function(){throw i},0)}(caretPlaceholder=this.doc.querySelector("._wysihtml5-temp-placeholder"))?(h=rangy.createRange(this.doc),h.selectNode(caretPlaceholder),h.deleteContents(),this.setSelection(h)):d.focus(),c&&(d.scrollTop=e,d.scrollLeft=f);try{caretPlaceholder.parentNode.removeChild(caretPlaceholder)}catch(j){}}else b(d,d)},executeAndRestoreSimple:function(a){var b,c,d,e=this.getRange(),f=this.doc.body;if(e){b=e.getNodes([3]),f=b[0]||e.startContainer,d=b[b.length-1]||e.endContainer,b=f===e.startContainer?e.startOffset:0,c=d===e.endContainer?e.endOffset:d.length;try{a(e.startContainer,e.endContainer)}catch(g){setTimeout(function(){throw g},0)}a=rangy.createRange(this.doc);try{a.setStart(f,b)}catch(h){}try{a.setEnd(d,c)}catch(i){}try{this.setSelection(a)}catch(j){}}else a(f,f)},insertHTML:function(a){var a=rangy.createRange(this.doc).createContextualFragment(a),b=a.lastChild;this.insertNode(a),b&&this.setAfter(b)},insertNode:function(a){var b=this.getRange();b&&b.insertNode(a)},surround:function(a){var b=this.getRange();if(b)try{b.surroundContents(a),this.selectNode(a)}catch(c){a.appendChild(b.extractContents()),b.insertNode(a)}},scrollIntoView:function(){var b,c=this.doc,d=c.documentElement.scrollHeight>c.documentElement.offsetHeight;if((b=c._wysihtml5ScrollIntoViewElement)||(b=c.createElement("span"),b.innerHTML=a.INVISIBLE_SPACE),b=c._wysihtml5ScrollIntoViewElement=b,d){this.insertNode(b);var d=b,e=0;if(d.parentNode)do e+=d.offsetTop||0,d=d.offsetParent;while(d);d=e,b.parentNode.removeChild(b),d>c.body.scrollTop&&(c.body.scrollTop=d)}},selectLine:function(){a.browser.supportsSelectionModify()?this._selectLine_W3C():this.doc.selection&&this._selectLine_MSIE()},_selectLine_W3C:function(){var a=this.doc.defaultView.getSelection();a.modify("extend","left","lineboundary"),a.modify("extend","right","lineboundary")},_selectLine_MSIE:function(){var a,b=this.doc.selection.createRange(),c=b.boundingTop,d=this.doc.body.scrollWidth;if(b.moveToPoint){for(0===c&&(a=this.doc.createElement("span"),this.insertNode(a),c=a.offsetTop,a.parentNode.removeChild(a)),c+=1,a=-10;d>a;a+=2)try{b.moveToPoint(a,c);break}catch(e){}for(a=this.doc.selection.createRange();d>=0;d--)try{a.moveToPoint(d,c);break}catch(f){}b.setEndPoint("EndToEnd",a),b.select()}},getText:function(){var a=this.getSelection();return a?a.toString():""},getNodes:function(a,b){var c=this.getRange();return c?c.getNodes([a],b):[]},getRange:function(){var a=this.getSelection();return a&&a.rangeCount&&a.getRangeAt(0)},getSelection:function(){return rangy.getSelection(this.doc.defaultView||this.doc.parentWindow)},setSelection:function(a){return rangy.getSelection(this.doc.defaultView||this.doc.parentWindow).setSingleRange(a)}})}(wysihtml5),function(a,b){function c(a,c){return b.dom.isCharacterDataNode(a)?0==c?!!a.previousSibling:c==a.length?!!a.nextSibling:!0:c>0&&c<a.childNodes.length}function d(a,c,e){var f;if(b.dom.isCharacterDataNode(c)&&(0==e?(e=b.dom.getNodeIndex(c),c=c.parentNode):e==c.length?(e=b.dom.getNodeIndex(c)+1,c=c.parentNode):f=b.dom.splitDataNode(c,e)),!f){f=c.cloneNode(!1),f.id&&f.removeAttribute("id");for(var g;g=c.childNodes[e];)f.appendChild(g);b.dom.insertAfter(f,c)}return c==a?f:d(a,f.parentNode,b.dom.getNodeIndex(f))}function e(b){this.firstTextNode=(this.isElementMerge=b.nodeType==a.ELEMENT_NODE)?b.lastChild:b,this.textNodes=[this.firstTextNode]}function f(a,b,c,d){this.tagNames=a||[g],this.cssClass=b||"",this.similarClassRegExp=c,this.normalize=d,this.applyToAnyTagName=!1}var g="span",h=/\s+/g;e.prototype={doMerge:function(){for(var a,b,c=[],d=0,e=this.textNodes.length;e>d;++d)a=this.textNodes[d],b=a.parentNode,c[d]=a.data,d&&(b.removeChild(a),b.hasChildNodes()||b.parentNode.removeChild(b));return this.firstTextNode.data=c=c.join("")},getLength:function(){for(var a=this.textNodes.length,b=0;a--;)b+=this.textNodes[a].length;return b},toString:function(){for(var a=[],b=0,c=this.textNodes.length;c>b;++b)a[b]="'"+this.textNodes[b].data+"'";return"[Merge("+a.join(",")+")]"}},f.prototype={getAncestorWithClass:function(c){for(var d;c;){if(this.cssClass)if(d=this.cssClass,c.className){var e=c.className.match(this.similarClassRegExp)||[];d=e[e.length-1]===d}else d=!1;else d=!0;if(c.nodeType==a.ELEMENT_NODE&&b.dom.arrayContains(this.tagNames,c.tagName.toLowerCase())&&d)return c;c=c.parentNode}return!1},postApply:function(a,b){for(var c,d,f,g=a[0],h=a[a.length-1],i=[],j=g,k=h,l=0,m=h.length,n=0,o=a.length;o>n;++n)d=a[n],(f=this.getAdjacentMergeableTextNode(d.parentNode,!1))?(c||(c=new e(f),i.push(c)),c.textNodes.push(d),d===g&&(j=c.firstTextNode,l=j.length),d===h&&(k=c.firstTextNode,m=c.getLength())):c=null;if((g=this.getAdjacentMergeableTextNode(h.parentNode,!0))&&(c||(c=new e(h),i.push(c)),c.textNodes.push(g)),i.length){for(n=0,o=i.length;o>n;++n)i[n].doMerge();b.setStart(j,l),b.setEnd(k,m)}},getAdjacentMergeableTextNode:function(b,c){var d=b.nodeType==a.TEXT_NODE,e=d?b.parentNode:b,f=c?"nextSibling":"previousSibling";if(d){if((d=b[f])&&d.nodeType==a.TEXT_NODE)return d}else if((d=e[f])&&this.areElementsMergeable(b,d))return d[c?"firstChild":"lastChild"];return null},areElementsMergeable:function(a,c){var d;if((d=b.dom.arrayContains(this.tagNames,(a.tagName||"").toLowerCase()))&&(d=b.dom.arrayContains(this.tagNames,(c.tagName||"").toLowerCase()))&&(d=a.className.replace(h," ")==c.className.replace(h," ")))a:if(a.attributes.length!=c.attributes.length)d=!1;else{d=0;for(var e,f,g=a.attributes.length;g>d;++d)if(e=a.attributes[d],f=e.name,"class"!=f&&(f=c.attributes.getNamedItem(f),e.specified!=f.specified||e.specified&&e.nodeValue!==f.nodeValue)){d=!1;break a}d=!0}return d},createContainer:function(a){return a=a.createElement(this.tagNames[0]),this.cssClass&&(a.className=this.cssClass),a},applyToTextNode:function(a){var c=a.parentNode;1==c.childNodes.length&&b.dom.arrayContains(this.tagNames,c.tagName.toLowerCase())?this.cssClass&&(a=this.cssClass,c.className?(c.className&&(c.className=c.className.replace(this.similarClassRegExp,"")),c.className+=" "+a):c.className=a):(c=this.createContainer(b.dom.getDocument(a)),a.parentNode.insertBefore(c,a),c.appendChild(a))},isRemovable:function(c){return b.dom.arrayContains(this.tagNames,c.tagName.toLowerCase())&&a.lang.string(c.className).trim()==this.cssClass},undoToTextNode:function(a,b,e){if(b.containsNode(e)||(a=b.cloneRange(),a.selectNode(e),a.isPointInRange(b.endContainer,b.endOffset)&&c(b.endContainer,b.endOffset)&&(d(e,b.endContainer,b.endOffset),b.setEndAfter(e)),a.isPointInRange(b.startContainer,b.startOffset)&&c(b.startContainer,b.startOffset)&&(e=d(e,b.startContainer,b.startOffset))),this.similarClassRegExp&&e.className&&(e.className=e.className.replace(this.similarClassRegExp,"")),this.isRemovable(e)){for(b=e,e=b.parentNode;b.firstChild;)e.insertBefore(b.firstChild,b);e.removeChild(b)}},applyToRange:function(b){var c=b.getNodes([a.TEXT_NODE]);if(!c.length)try{var d=this.createContainer(b.endContainer.ownerDocument);return b.surroundContents(d),void this.selectNode(b,d)}catch(e){}if(b.splitBoundaries(),c=b.getNodes([a.TEXT_NODE]),c.length){for(var f=0,g=c.length;g>f;++f)d=c[f],this.getAncestorWithClass(d)||this.applyToTextNode(d);b.setStart(c[0],0),d=c[c.length-1],b.setEnd(d,d.length),this.normalize&&this.postApply(c,b)}},undoToRange:function(b){var c,d,e=b.getNodes([a.TEXT_NODE]);e.length?(b.splitBoundaries(),e=b.getNodes([a.TEXT_NODE])):(e=b.endContainer.ownerDocument.createTextNode(a.INVISIBLE_SPACE),b.insertNode(e),b.selectNode(e),e=[e]);for(var f=0,g=e.length;g>f;++f)c=e[f],(d=this.getAncestorWithClass(c))&&this.undoToTextNode(c,b,d);1==g?this.selectNode(b,e[0]):(b.setStart(e[0],0),c=e[e.length-1],b.setEnd(c,c.length),this.normalize&&this.postApply(e,b))},selectNode:function(b,c){var d=c.nodeType===a.ELEMENT_NODE,e="canHaveHTML"in c?c.canHaveHTML:!0,f=d?c.innerHTML:c.data;if((f=""===f||f===a.INVISIBLE_SPACE)&&d&&e)try{c.innerHTML=a.INVISIBLE_SPACE}catch(g){}b.selectNodeContents(c),f&&d?b.collapse(!1):f&&(b.setStartAfter(c),b.setEndAfter(c))},getTextSelectedByRange:function(a,b){var c=b.cloneRange();c.selectNodeContents(a);var d=c.intersection(b),d=d?d.toString():"";return c.detach(),d},isAppliedToRange:function(b){var c,d=[],e=b.getNodes([a.TEXT_NODE]);if(!e.length)return(c=this.getAncestorWithClass(b.startContainer))?[c]:!1;for(var f,g=0,h=e.length;h>g;++g){if(f=this.getTextSelectedByRange(e[g],b),c=this.getAncestorWithClass(e[g]),""!=f&&!c)return!1;d.push(c)}return d},toggleRange:function(a){this.isAppliedToRange(a)?this.undoToRange(a):this.applyToRange(a)}},a.selection.HTMLApplier=f}(wysihtml5,rangy),wysihtml5.Commands=Base.extend({constructor:function(a){this.editor=a,this.composer=a.composer,this.doc=this.composer.doc},support:function(a){return wysihtml5.browser.supportsCommand(this.doc,a)},exec:function(a,b){var c=wysihtml5.commands[a],d=wysihtml5.lang.array(arguments).get(),e=c&&c.exec,f=null;if(this.editor.fire("beforecommand:composer"),e)d.unshift(this.composer),f=e.apply(c,d);else try{f=this.doc.execCommand(a,!1,b)}catch(g){}return this.editor.fire("aftercommand:composer"),f},state:function(a){var b=wysihtml5.commands[a],c=wysihtml5.lang.array(arguments).get(),d=b&&b.state;if(d)return c.unshift(this.composer),d.apply(b,c);try{return this.doc.queryCommandState(a)}catch(e){return!1}},value:function(a){var b=wysihtml5.commands[a],c=b&&b.value;if(c)return c.call(b,this.composer,a);try{return this.doc.queryCommandValue(a)}catch(d){return null}}}),function(a){a.commands.bold={exec:function(b,c){return a.commands.formatInline.exec(b,c,"b")},state:function(b,c){return a.commands.formatInline.state(b,c,"b")},value:function(){}}}(wysihtml5),function(a){function b(b,f){var g,h,i,j=b.doc,k="_wysihtml5-temp-"+ +new Date,l=0;for(a.commands.formatInline.exec(b,c,d,k,/non-matching-class/g),g=j.querySelectorAll(d+"."+k),k=g.length;k>l;l++)for(i in h=g[l],h.removeAttribute("class"),f)h.setAttribute(i,f[i]);l=h,1===k&&(i=e.getTextContent(h),k=!!h.querySelector("*"),i=""===i||i===a.INVISIBLE_SPACE,!k&&i&&(e.setTextContent(h,f.text||h.href),j=j.createTextNode(" "),b.selection.setAfter(h),b.selection.insertNode(j),l=j)),b.selection.setAfter(l)}var c,d="A",e=a.dom;a.commands.createLink={exec:function(a,c,d){var f=this.state(a,c);f?a.selection.executeAndRestore(function(){for(var a,b,c,d=f.length,g=0;d>g;g++)a=f[g],b=e.getParentElement(a,{nodeName:"code"}),c=e.getTextContent(a),c.match(e.autoLink.URL_REG_EXP)&&!b?e.renameElement(a,"code"):e.replaceWithChildNodes(a)}):(d="object"==typeof d?d:{href:d},b(a,d))},state:function(b,c){return a.commands.formatInline.state(b,c,"A")},value:function(){return c}}}(wysihtml5),function(a){var b=/wysiwyg-font-size-[a-z\-]+/g;a.commands.fontSize={exec:function(c,d,e){return a.commands.formatInline.exec(c,d,"span","wysiwyg-font-size-"+e,b)},state:function(c,d,e){return a.commands.formatInline.state(c,d,"span","wysiwyg-font-size-"+e,b)},value:function(){}}}(wysihtml5),function(a){var b=/wysiwyg-color-[a-z]+/g;a.commands.foreColor={exec:function(c,d,e){return a.commands.formatInline.exec(c,d,"span","wysiwyg-color-"+e,b)},state:function(c,d,e){return a.commands.formatInline.state(c,d,"span","wysiwyg-color-"+e,b)},value:function(){}}}(wysihtml5),function(a){function b(b){for(b=b.previousSibling;b&&b.nodeType===a.TEXT_NODE&&!a.lang.string(b.data).trim();)b=b.previousSibling;return b}function c(b){for(b=b.nextSibling;b&&b.nodeType===a.TEXT_NODE&&!a.lang.string(b.data).trim();)b=b.nextSibling;return b}function d(a){return"BR"===a.nodeName||"block"===g.getStyle("display").from(a)?!0:!1}function e(b,c,d,e){if(e)var f=g.observe(b,"DOMNodeInserted",function(b){var c,b=b.target;b.nodeType===a.ELEMENT_NODE&&(c=g.getStyle("display").from(b),"inline"!==c.substr(0,6)&&(b.className+=" "+e))});b.execCommand(c,!1,d),f&&f.stop()}function f(a,d){a.selection.selectLine(),a.selection.surround(d);var e=c(d),f=b(d);e&&"BR"===e.nodeName&&e.parentNode.removeChild(e),f&&"BR"===f.nodeName&&f.parentNode.removeChild(f),(e=d.lastChild)&&"BR"===e.nodeName&&e.parentNode.removeChild(e),a.selection.selectNode(d)}var g=a.dom,h="H1 H2 H3 H4 H5 H6 P BLOCKQUOTE DIV".split(" ");a.commands.formatBlock={exec:function(i,j,k,l,m){var n,o=i.doc,p=this.state(i,j,k,l,m),k="string"==typeof k?k.toUpperCase():k;if(p)i.selection.executeAndRestoreSimple(function(){m&&(p.className=p.className.replace(m,""));var e=!!a.lang.string(p.className).trim();if(e||p.nodeName!==(k||"DIV"))e&&g.renameElement(p,"DIV");else{var e=p,f=e.ownerDocument,h=c(e),i=b(e);h&&!d(h)&&e.parentNode.insertBefore(f.createElement("br"),h),i&&!d(i)&&e.parentNode.insertBefore(f.createElement("br"),e),g.replaceWithChildNodes(p)}});else{if((null===k||a.lang.array(h).contains(k))&&(n=i.selection.getSelectedNode(),p=g.getParentElement(n,{nodeName:h})))return void i.selection.executeAndRestoreSimple(function(){if(k&&(p=g.renameElement(p,k)),l){var a=p;a.className?(a.className=a.className.replace(m,""),a.className+=" "+l):a.className=l}});i.commands.support(j)?e(o,j,k||"DIV",l):(p=o.createElement(k||"DIV"),l&&(p.className=l),f(i,p))}},state:function(a,b,c,d,e){return c="string"==typeof c?c.toUpperCase():c,a=a.selection.getSelectedNode(),g.getParentElement(a,{nodeName:c,className:d,classRegExp:e})},value:function(){}}}(wysihtml5),function(a){function b(b,e,f){var g=b+":"+e;if(!d[g]){var h=d,i=a.selection.HTMLApplier,j=c[b],b=j?[b.toLowerCase(),j.toLowerCase()]:[b.toLowerCase()];h[g]=new i(b,e,f,!0)}return d[g]}var c={strong:"b",em:"i",b:"strong",i:"em"},d={};a.commands.formatInline={exec:function(a,c,d,e,f){return(c=a.selection.getRange())?(b(d,e,f).toggleRange(c),void a.selection.setSelection(c)):!1},state:function(d,e,f,g,h){var e=d.doc,i=c[f]||f;return!a.dom.hasElementWithTagName(e,f)&&!a.dom.hasElementWithTagName(e,i)||g&&!a.dom.hasElementWithClassName(e,g)?!1:(d=d.selection.getRange(),d?b(f,g,h).isAppliedToRange(d):!1)},value:function(){}}}(wysihtml5),function(a){a.commands.insertHTML={exec:function(a,b,c){a.commands.support(b)?a.doc.execCommand(b,!1,c):a.selection.insertHTML(c)},state:function(){return!1},value:function(){}}}(wysihtml5),function(a){a.commands.insertImage={exec:function(b,c,d){var e,d="object"==typeof d?d:{src:d},f=b.doc,c=this.state(b);if(c)b.selection.setBefore(c),d=c.parentNode,d.removeChild(c),a.dom.removeEmptyTextNodes(d),"A"===d.nodeName&&!d.firstChild&&(b.selection.setAfter(d),d.parentNode.removeChild(d)),a.quirks.redraw(b.element);else{c=f.createElement("IMG");for(e in d)c[e]=d[e];b.selection.insertNode(c),a.browser.hasProblemsSettingCaretAfterImg()?(d=f.createTextNode(a.INVISIBLE_SPACE),b.selection.insertNode(d),b.selection.setAfter(d)):b.selection.setAfter(c)}},state:function(b){var c;return a.dom.hasElementWithTagName(b.doc,"IMG")&&(c=b.selection.getSelectedNode())?"IMG"===c.nodeName?c:c.nodeType!==a.ELEMENT_NODE?!1:(c=b.selection.getText(),(c=a.lang.string(c).trim())?!1:(b=b.selection.getNodes(a.ELEMENT_NODE,function(a){return"IMG"===a.nodeName}),1!==b.length?!1:b[0])):!1},value:function(a){return(a=this.state(a))&&a.src}}}(wysihtml5),function(a){var b="<br>"+(a.browser.needsSpaceAfterLineBreak()?" ":"");a.commands.insertLineBreak={exec:function(c,d){c.commands.support(d)?(c.doc.execCommand(d,!1,null),a.browser.autoScrollsToCaret()||c.selection.scrollIntoView()):c.commands.exec("insertHTML",b)},state:function(){return!1},value:function(){}}}(wysihtml5),function(a){a.commands.insertOrderedList={exec:function(b,c){var d,e=b.doc,f=b.selection.getSelectedNode(),g=a.dom.getParentElement(f,{nodeName:"OL"}),h=a.dom.getParentElement(f,{nodeName:"UL"}),f="_wysihtml5-temp-"+(new Date).getTime();b.commands.support(c)?e.execCommand(c,!1,null):g?b.selection.executeAndRestoreSimple(function(){a.dom.resolveList(g)}):h?b.selection.executeAndRestoreSimple(function(){a.dom.renameElement(h,"ol")}):(b.commands.exec("formatBlock","div",f),d=e.querySelector("."+f),e=""===d.innerHTML||d.innerHTML===a.INVISIBLE_SPACE,b.selection.executeAndRestoreSimple(function(){g=a.dom.convertToList(d,"ol")}),e&&b.selection.selectNode(g.querySelector("li")))},state:function(b){return b=b.selection.getSelectedNode(),a.dom.getParentElement(b,{nodeName:"OL"})},value:function(){}}}(wysihtml5),function(a){a.commands.insertUnorderedList={exec:function(b,c){var d,e=b.doc,f=b.selection.getSelectedNode(),g=a.dom.getParentElement(f,{nodeName:"UL"}),h=a.dom.getParentElement(f,{nodeName:"OL"}),f="_wysihtml5-temp-"+(new Date).getTime();b.commands.support(c)?e.execCommand(c,!1,null):g?b.selection.executeAndRestoreSimple(function(){a.dom.resolveList(g)}):h?b.selection.executeAndRestoreSimple(function(){a.dom.renameElement(h,"ul")}):(b.commands.exec("formatBlock","div",f),d=e.querySelector("."+f),e=""===d.innerHTML||d.innerHTML===a.INVISIBLE_SPACE,b.selection.executeAndRestoreSimple(function(){g=a.dom.convertToList(d,"ul")}),e&&b.selection.selectNode(g.querySelector("li")))},state:function(b){return b=b.selection.getSelectedNode(),a.dom.getParentElement(b,{nodeName:"UL"})},value:function(){}}}(wysihtml5),function(a){a.commands.italic={exec:function(b,c){return a.commands.formatInline.exec(b,c,"i")},state:function(b,c){return a.commands.formatInline.state(b,c,"i")},value:function(){}}}(wysihtml5),function(a){var b=/wysiwyg-text-align-[a-z]+/g;a.commands.justifyCenter={exec:function(c){return a.commands.formatBlock.exec(c,"formatBlock",null,"wysiwyg-text-align-center",b)},state:function(c){return a.commands.formatBlock.state(c,"formatBlock",null,"wysiwyg-text-align-center",b)},value:function(){}}}(wysihtml5),function(a){var b=/wysiwyg-text-align-[a-z]+/g;a.commands.justifyLeft={exec:function(c){return a.commands.formatBlock.exec(c,"formatBlock",null,"wysiwyg-text-align-left",b)},state:function(c){return a.commands.formatBlock.state(c,"formatBlock",null,"wysiwyg-text-align-left",b)},value:function(){}}}(wysihtml5),function(a){var b=/wysiwyg-text-align-[a-z]+/g;a.commands.justifyRight={exec:function(c){return a.commands.formatBlock.exec(c,"formatBlock",null,"wysiwyg-text-align-right",b)},state:function(c){return a.commands.formatBlock.state(c,"formatBlock",null,"wysiwyg-text-align-right",b)},value:function(){}}}(wysihtml5),function(a){a.commands.underline={exec:function(b,c){return a.commands.formatInline.exec(b,c,"u")},state:function(b,c){return a.commands.formatInline.state(b,c,"u")},value:function(){}}}(wysihtml5),function(a){var b='<span id="_wysihtml5-undo" class="_wysihtml5-temp">'+a.INVISIBLE_SPACE+"</span>",c='<span id="_wysihtml5-redo" class="_wysihtml5-temp">'+a.INVISIBLE_SPACE+"</span>",d=a.dom;a.UndoManager=a.lang.Dispatcher.extend({constructor:function(a){this.editor=a,this.composer=a.composer,this.element=this.composer.element,this.history=[this.composer.getValue()],this.position=1,this.composer.commands.support("insertHTML")&&this._observe()},_observe:function(){var e,f=this,g=this.composer.sandbox.getDocument();if(d.observe(this.element,"keydown",function(a){if(!a.altKey&&(a.ctrlKey||a.metaKey)){var b=a.keyCode,c=90===b&&a.shiftKey||89===b;90!==b||a.shiftKey?c&&(f.redo(),a.preventDefault()):(f.undo(),a.preventDefault())}}),d.observe(this.element,"keydown",function(a){a=a.keyCode,a!==e&&(e=a,(8===a||46===a)&&f.transact())}),a.browser.hasUndoInContextMenu()){var h,i,j=function(){for(var a;a=g.querySelector("._wysihtml5-temp");)a.parentNode.removeChild(a);clearInterval(h)};d.observe(this.element,"contextmenu",function(){j(),f.composer.selection.executeAndRestoreSimple(function(){f.element.lastChild&&f.composer.selection.setAfter(f.element.lastChild),g.execCommand("insertHTML",!1,b),g.execCommand("insertHTML",!1,c),g.execCommand("undo",!1,null)}),h=setInterval(function(){g.getElementById("_wysihtml5-redo")?(j(),f.redo()):g.getElementById("_wysihtml5-undo")||(j(),f.undo())},400),i||(i=!0,d.observe(document,"mousedown",j),d.observe(g,["mousedown","paste","cut","copy"],j))})}this.editor.observe("newword:composer",function(){f.transact()}).observe("beforecommand:composer",function(){f.transact()})},transact:function(){var a=this.history[this.position-1],b=this.composer.getValue();b!=a&&(40<(this.history.length=this.position)&&(this.history.shift(),this.position--),this.position++,this.history.push(b))},undo:function(){this.transact(),1>=this.position||(this.set(this.history[--this.position-1]),this.editor.fire("undo:composer"))},redo:function(){this.position>=this.history.length||(this.set(this.history[++this.position-1]),this.editor.fire("redo:composer"))},set:function(a){this.composer.setValue(a),this.editor.focus(!0)}})}(wysihtml5),wysihtml5.views.View=Base.extend({constructor:function(a,b,c){this.parent=a,this.element=b,this.config=c,this._observeViewChange()},_observeViewChange:function(){var a=this;this.parent.observe("beforeload",function(){a.parent.observe("change_view",function(b){b===a.name?(a.parent.currentView=a,a.show(),setTimeout(function(){a.focus()},0)):a.hide()})})},focus:function(){if(this.element.ownerDocument.querySelector(":focus")!==this.element)try{this.element.focus()}catch(a){}},hide:function(){this.element.style.display="none"},show:function(){this.element.style.display=""},disable:function(){this.element.setAttribute("disabled","disabled")},enable:function(){this.element.removeAttribute("disabled")}}),function(a){var b=a.dom,c=a.browser;a.views.Composer=a.views.View.extend({name:"composer",CARET_HACK:"<br>",constructor:function(a,b,c){this.base(a,b,c),this.textarea=this.parent.textarea,this._initSandbox()},clear:function(){this.element.innerHTML=c.displaysCaretInEmptyContentEditableCorrectly()?"":this.CARET_HACK},getValue:function(b){var c=this.isEmpty()?"":a.quirks.getCorrectInnerHTML(this.element);return b&&(c=this.parent.parse(c)),c=a.lang.string(c).replace(a.INVISIBLE_SPACE).by("")},setValue:function(a,b){b&&(a=this.parent.parse(a)),this.element.innerHTML=a},show:function(){this.iframe.style.display=this._displayStyle||"",this.disable(),this.enable()},hide:function(){this._displayStyle=b.getStyle("display").from(this.iframe),"none"===this._displayStyle&&(this._displayStyle=null),this.iframe.style.display="none"},disable:function(){this.element.removeAttribute("contentEditable"),this.base()},enable:function(){this.element.setAttribute("contentEditable","true"),this.base()},focus:function(b){a.browser.doesAsyncFocus()&&this.hasPlaceholderSet()&&this.clear(),this.base();var c=this.element.lastChild;b&&c&&("BR"===c.nodeName?this.selection.setBefore(this.element.lastChild):this.selection.setAfter(this.element.lastChild))},getTextContent:function(){return b.getTextContent(this.element)},hasPlaceholderSet:function(){return this.getTextContent()==this.textarea.element.getAttribute("placeholder")},isEmpty:function(){var a=this.element.innerHTML;return""===a||a===this.CARET_HACK||this.hasPlaceholderSet()||""===this.getTextContent()&&!this.element.querySelector("blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea")},_initSandbox:function(){var a=this;this.sandbox=new b.Sandbox(function(){a._create()},{stylesheets:this.config.stylesheets}),this.iframe=this.sandbox.getIframe();var c=document.createElement("input");c.type="hidden",c.name="_wysihtml5_mode",c.value=1;var d=this.textarea.element;b.insert(this.iframe).after(d),b.insert(c).after(d)},_create:function(){var d=this;this.doc=this.sandbox.getDocument(),this.element=this.doc.body,this.textarea=this.parent.textarea,this.element.innerHTML=this.textarea.getValue(!0),this.enable(),this.selection=new a.Selection(this.parent),this.commands=new a.Commands(this.parent),b.copyAttributes("className spellcheck title lang dir accessKey".split(" ")).from(this.textarea.element).to(this.element),b.addClass(this.element,this.config.composerClassName),this.config.style&&this.style(),this.observe();var e=this.config.name;e&&(b.addClass(this.element,e),b.addClass(this.iframe,e)),(e="string"==typeof this.config.placeholder?this.config.placeholder:this.textarea.element.getAttribute("placeholder"))&&b.simulatePlaceholder(this.parent,this,e),this.commands.exec("styleWithCSS",!1),this._initAutoLinking(),this._initObjectResizing(),this._initUndoManager(),(this.textarea.element.hasAttribute("autofocus")||document.querySelector(":focus")==this.textarea.element)&&setTimeout(function(){d.focus()},100),a.quirks.insertLineBreakOnReturn(this),c.clearsContentEditableCorrectly()||a.quirks.ensureProperClearing(this),c.clearsListsInContentEditableCorrectly()||a.quirks.ensureProperClearingOfLists(this),this.initSync&&this.config.sync&&this.initSync(),this.textarea.hide(),this.parent.fire("beforeload").fire("load")},_initAutoLinking:function(){var d=this,e=c.canDisableAutoLinking(),f=c.doesAutoLinkingInContentEditable();if(e&&this.commands.exec("autoUrlDetect",!1),this.config.autoLink){(!f||f&&e)&&this.parent.observe("newword:composer",function(){d.selection.executeAndRestore(function(a,c){b.autoLink(c.parentNode)})});var g=this.sandbox.getDocument().getElementsByTagName("a"),h=b.autoLink.URL_REG_EXP,i=function(c){return c=a.lang.string(b.getTextContent(c)).trim(),"www."===c.substr(0,4)&&(c="http://"+c),c};b.observe(this.element,"keydown",function(a){if(g.length){var c,a=d.selection.getSelectedNode(a.target.ownerDocument),e=b.getParentElement(a,{nodeName:"A"},4);e&&(c=i(e),setTimeout(function(){var a=i(e);a!==c&&a.match(h)&&e.setAttribute("href",a)},0))}})}},_initObjectResizing:function(){var d=["width","height"],e=d.length,f=this.element;this.commands.exec("enableObjectResizing",this.config.allowObjectResizing),this.config.allowObjectResizing?c.supportsEvent("resizeend")&&b.observe(f,"resizeend",function(b){for(var c,b=b.target||b.srcElement,g=b.style,h=0;e>h;h++)c=d[h],g[c]&&(b.setAttribute(c,parseInt(g[c],10)),g[c]="");a.quirks.redraw(f)}):c.supportsEvent("resizestart")&&b.observe(f,"resizestart",function(a){a.preventDefault()})},_initUndoManager:function(){new a.UndoManager(this.parent)}})}(wysihtml5),function(a){var b=a.dom,c=document,d=window,e=c.createElement("div"),f="background-color color cursor font-family font-size font-style font-variant font-weight line-height letter-spacing text-align text-decoration text-indent text-rendering word-break word-wrap word-spacing".split(" "),g="background-color border-collapse border-bottom-color border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color border-top-style border-top-width clear display float margin-bottom margin-left margin-right margin-top outline-color outline-offset outline-width outline-style padding-left padding-right padding-top padding-bottom position top left right bottom z-index vertical-align text-align -webkit-box-sizing -moz-box-sizing -ms-box-sizing box-sizing -webkit-box-shadow -moz-box-shadow -ms-box-shadow box-shadow -webkit-border-top-right-radius -moz-border-radius-topright border-top-right-radius -webkit-border-bottom-right-radius -moz-border-radius-bottomright border-bottom-right-radius -webkit-border-bottom-left-radius -moz-border-radius-bottomleft border-bottom-left-radius -webkit-border-top-left-radius -moz-border-radius-topleft border-top-left-radius width height".split(" "),h="width height top left right bottom".split(" "),i=["html { height: 100%; }","body { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }","._wysihtml5-temp { display: none; }",a.browser.isGecko?"body.placeholder { color: graytext !important; }":"body.placeholder { color: #a9a9a9 !important; }","body[disabled] { background-color: #eee !important; color: #999 !important; cursor: default !important; }","img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }"],j=function(a){if(a.setActive)try{a.setActive()}catch(e){}else{var f=a.style,g=c.documentElement.scrollTop||c.body.scrollTop,h=c.documentElement.scrollLeft||c.body.scrollLeft,f={position:f.position,top:f.top,left:f.left,WebkitUserSelect:f.WebkitUserSelect};b.setStyles({position:"absolute",top:"-99999px",left:"-99999px",WebkitUserSelect:"none"}).on(a),a.focus(),b.setStyles(f).on(a),d.scrollTo&&d.scrollTo(h,g)}};a.views.Composer.prototype.style=function(){var k=this,l=c.querySelector(":focus"),m=this.textarea.element,n=m.hasAttribute("placeholder"),o=n&&m.getAttribute("placeholder");this.focusStylesHost=this.focusStylesHost||e.cloneNode(!1),this.blurStylesHost=this.blurStylesHost||e.cloneNode(!1),n&&m.removeAttribute("placeholder"),m===l&&m.blur(),b.copyStyles(g).from(m).to(this.iframe).andTo(this.blurStylesHost),b.copyStyles(f).from(m).to(this.element).andTo(this.blurStylesHost),b.insertCSS(i).into(this.element.ownerDocument),j(m),b.copyStyles(g).from(m).to(this.focusStylesHost),b.copyStyles(f).from(m).to(this.focusStylesHost);
+var p=a.lang.array(g).without(["display"]);if(l?l.focus():m.blur(),n&&m.setAttribute("placeholder",o),!a.browser.hasCurrentStyleProperty())var q=b.observe(d,"resize",function(){if(b.contains(document.documentElement,k.iframe)){var a=b.getStyle("display").from(m),c=b.getStyle("display").from(k.iframe);m.style.display="",k.iframe.style.display="none",b.copyStyles(h).from(m).to(k.iframe).andTo(k.focusStylesHost).andTo(k.blurStylesHost),k.iframe.style.display=c,m.style.display=a}else q.stop()});return this.parent.observe("focus:composer",function(){b.copyStyles(p).from(k.focusStylesHost).to(k.iframe),b.copyStyles(f).from(k.focusStylesHost).to(k.element)}),this.parent.observe("blur:composer",function(){b.copyStyles(p).from(k.blurStylesHost).to(k.iframe),b.copyStyles(f).from(k.blurStylesHost).to(k.element)}),this}}(wysihtml5),function(a){var b=a.dom,c=a.browser,d={66:"bold",73:"italic",85:"underline"};a.views.Composer.prototype.observe=function(){var e=this,f=this.getValue(),g=this.sandbox.getIframe(),h=this.element,i=c.supportsEventsInIframeCorrectly()?h:this.sandbox.getWindow(),j=c.supportsEvent("drop")?["drop","paste"]:["dragdrop","paste"];b.observe(g,"DOMNodeRemoved",function(){clearInterval(k),e.parent.fire("destroy:composer")});var k=setInterval(function(){b.contains(document.documentElement,g)||(clearInterval(k),e.parent.fire("destroy:composer"))},250);b.observe(i,"focus",function(){e.parent.fire("focus").fire("focus:composer"),setTimeout(function(){f=e.getValue()},0)}),b.observe(i,"blur",function(){f!==e.getValue()&&e.parent.fire("change").fire("change:composer"),e.parent.fire("blur").fire("blur:composer")}),a.browser.isIos()&&b.observe(h,"blur",function(){var a=h.ownerDocument.createElement("input"),b=document.documentElement.scrollTop||document.body.scrollTop,c=document.documentElement.scrollLeft||document.body.scrollLeft;try{e.selection.insertNode(a)}catch(d){h.appendChild(a)}a.focus(),a.parentNode.removeChild(a),window.scrollTo(c,b)}),b.observe(h,"dragenter",function(){e.parent.fire("unset_placeholder")}),c.firesOnDropOnlyWhenOnDragOverIsCancelled()&&b.observe(h,["dragover","dragenter"],function(a){a.preventDefault()}),b.observe(h,j,function(a){var b,d=a.dataTransfer;d&&c.supportsDataTransfer()&&(b=d.getData("text/html")||d.getData("text/plain")),b?(h.focus(),e.commands.exec("insertHTML",b),e.parent.fire("paste").fire("paste:composer"),a.stopPropagation(),a.preventDefault()):setTimeout(function(){e.parent.fire("paste").fire("paste:composer")},0)}),b.observe(h,"keyup",function(b){b=b.keyCode,(b===a.SPACE_KEY||b===a.ENTER_KEY)&&e.parent.fire("newword:composer")}),this.parent.observe("paste:composer",function(){setTimeout(function(){e.parent.fire("newword:composer")},0)}),c.canSelectImagesInContentEditable()||b.observe(h,"mousedown",function(a){var b=a.target;"IMG"===b.nodeName&&(e.selection.selectNode(b),a.preventDefault())}),b.observe(h,"keydown",function(a){var b=d[a.keyCode];(a.ctrlKey||a.metaKey)&&!a.altKey&&b&&(e.commands.exec(b),a.preventDefault())}),b.observe(h,"keydown",function(b){var c=e.selection.getSelectedNode(!0),d=b.keyCode;!c||"IMG"!==c.nodeName||d!==a.BACKSPACE_KEY&&d!==a.DELETE_KEY||(d=c.parentNode,d.removeChild(c),"A"===d.nodeName&&!d.firstChild&&d.parentNode.removeChild(d),setTimeout(function(){a.quirks.redraw(h)},0),b.preventDefault())});var l={IMG:"Image: ",A:"Link: "};b.observe(h,"mouseover",function(a){var a=a.target,b=a.nodeName;!("A"!==b&&"IMG"!==b)&&!a.hasAttribute("title")&&(b=l[b]+(a.getAttribute("href")||a.getAttribute("src")),a.setAttribute("title",b))})}}(wysihtml5),function(a){a.views.Synchronizer=Base.extend({constructor:function(a,b,c){this.editor=a,this.textarea=b,this.composer=c,this._observe()},fromComposerToTextarea:function(b){this.textarea.setValue(a.lang.string(this.composer.getValue()).trim(),b)},fromTextareaToComposer:function(a){var b=this.textarea.getValue();b?this.composer.setValue(b,a):(this.composer.clear(),this.editor.fire("set_placeholder"))},sync:function(a){"textarea"===this.editor.currentView.name?this.fromTextareaToComposer(a):this.fromComposerToTextarea(a)},_observe:function(){var b,c=this,d=this.textarea.element.form,e=function(){b=setInterval(function(){c.fromComposerToTextarea()},400)},f=function(){clearInterval(b),b=null};e(),d&&(a.dom.observe(d,"submit",function(){c.sync(!0)}),a.dom.observe(d,"reset",function(){setTimeout(function(){c.fromTextareaToComposer()},0)})),this.editor.observe("change_view",function(a){"composer"!==a||b?"textarea"===a&&(c.fromComposerToTextarea(!0),f()):(c.fromTextareaToComposer(!0),e())}),this.editor.observe("destroy:composer",f)}})}(wysihtml5),wysihtml5.views.Textarea=wysihtml5.views.View.extend({name:"textarea",constructor:function(a,b,c){this.base(a,b,c),this._observe()},clear:function(){this.element.value=""},getValue:function(a){var b=this.isEmpty()?"":this.element.value;return a&&(b=this.parent.parse(b)),b},setValue:function(a,b){b&&(a=this.parent.parse(a)),this.element.value=a},hasPlaceholderSet:function(){var a=wysihtml5.browser.supportsPlaceholderAttributeOn(this.element),b=this.element.getAttribute("placeholder")||null,c=this.element.value;return a&&!c||c===b},isEmpty:function(){return!wysihtml5.lang.string(this.element.value).trim()||this.hasPlaceholderSet()},_observe:function(){var a=this.element,b=this.parent,c={focusin:"focus",focusout:"blur"},d=wysihtml5.browser.supportsEvent("focusin")?["focusin","focusout","change"]:["focus","blur","change"];b.observe("beforeload",function(){wysihtml5.dom.observe(a,d,function(a){a=c[a.type]||a.type,b.fire(a).fire(a+":textarea")}),wysihtml5.dom.observe(a,["paste","drop"],function(){setTimeout(function(){b.fire("paste").fire("paste:textarea")},0)})})}}),function(a){var b=a.dom;a.toolbar.Dialog=a.lang.Dispatcher.extend({constructor:function(a,b){this.link=a,this.container=b},_observe:function(){if(!this._observed){var c=this,d=function(a){var b=c._serialize();b==c.elementToChange?c.fire("edit",b):c.fire("save",b),c.hide(),a.preventDefault(),a.stopPropagation()};b.observe(c.link,"click",function(){b.hasClass(c.link,"wysihtml5-command-dialog-opened")&&setTimeout(function(){c.hide()},0)}),b.observe(this.container,"keydown",function(b){var e=b.keyCode;e===a.ENTER_KEY&&d(b),e===a.ESCAPE_KEY&&c.hide()}),b.delegate(this.container,"[data-wysihtml5-dialog-action=save]","click",d),b.delegate(this.container,"[data-wysihtml5-dialog-action=cancel]","click",function(a){c.fire("cancel"),c.hide(),a.preventDefault(),a.stopPropagation()});for(var e=this.container.querySelectorAll("input, select, textarea"),f=0,g=e.length,h=function(){clearInterval(c.interval)};g>f;f++)b.observe(e[f],"change",h);this._observed=!0}},_serialize:function(){for(var a=this.elementToChange||{},b=this.container.querySelectorAll("[data-wysihtml5-dialog-field]"),c=b.length,d=0;c>d;d++)a[b[d].getAttribute("data-wysihtml5-dialog-field")]=b[d].value;return a},_interpolate:function(a){for(var b,c,d=document.querySelector(":focus"),e=this.container.querySelectorAll("[data-wysihtml5-dialog-field]"),f=e.length,g=0;f>g;g++)b=e[g],b!==d&&!(a&&"hidden"===b.type)&&(c=b.getAttribute("data-wysihtml5-dialog-field"),c=this.elementToChange?this.elementToChange[c]||"":b.defaultValue,b.value=c)},show:function(a){var c=this,d=this.container.querySelector("input, select, textarea");if(this.elementToChange=a,this._observe(),this._interpolate(),a&&(this.interval=setInterval(function(){c._interpolate(!0)},500)),b.addClass(this.link,"wysihtml5-command-dialog-opened"),this.container.style.display="",this.fire("show"),d&&!a)try{d.focus()}catch(e){}},hide:function(){clearInterval(this.interval),this.elementToChange=null,b.removeClass(this.link,"wysihtml5-command-dialog-opened"),this.container.style.display="none",this.fire("hide")}})}(wysihtml5),function(a){var b=a.dom,c={position:"relative"},d={left:0,margin:0,opacity:0,overflow:"hidden",padding:0,position:"absolute",top:0,zIndex:1},e={cursor:"inherit",fontSize:"50px",height:"50px",marginTop:"-25px",outline:0,padding:0,position:"absolute",right:"-4px",top:"50%"},f={"x-webkit-speech":"",speech:""};a.toolbar.Speech=function(g,h){var i=document.createElement("input");if(a.browser.supportsSpeechApiOn(i)){var j=document.createElement("div");a.lang.object(d).merge({width:h.offsetWidth+"px",height:h.offsetHeight+"px"}),b.insert(i).into(j),b.insert(j).into(h),b.setStyles(e).on(i),b.setAttributes(f).on(i),b.setStyles(d).on(j),b.setStyles(c).on(h),b.observe(i,"onwebkitspeechchange"in i?"webkitspeechchange":"speechchange",function(){g.execCommand("insertText",i.value),i.value=""}),b.observe(i,"click",function(a){b.hasClass(h,"wysihtml5-command-disabled")&&a.preventDefault(),a.stopPropagation()})}else h.style.display="none"}}(wysihtml5),function(a){var b=a.dom;a.toolbar.Toolbar=Base.extend({constructor:function(b,c){this.editor=b,this.container="string"==typeof c?document.getElementById(c):c,this.composer=b.composer,this._getLinks("command"),this._getLinks("action"),this._observe(),this.show();for(var d=this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"),e=d.length,f=0;e>f;f++)new a.toolbar.Speech(this,d[f])},_getLinks:function(b){for(var c,d,e,f,g,h=this[b+"Links"]=a.lang.array(this.container.querySelectorAll("[data-wysihtml5-"+b+"]")).get(),i=h.length,j=0,k=this[b+"Mapping"]={};i>j;j++)c=h[j],e=c.getAttribute("data-wysihtml5-"+b),f=c.getAttribute("data-wysihtml5-"+b+"-value"),d=this.container.querySelector("[data-wysihtml5-"+b+"-group='"+e+"']"),g=this._getDialog(c,e),k[e+":"+f]={link:c,group:d,name:e,value:f,dialog:g,state:!1}},_getDialog:function(b,c){var d,e,f=this,g=this.container.querySelector("[data-wysihtml5-dialog='"+c+"']");return g&&(d=new a.toolbar.Dialog(b,g),d.observe("show",function(){e=f.composer.selection.getBookmark(),f.editor.fire("show:dialog",{command:c,dialogContainer:g,commandLink:b})}),d.observe("save",function(a){e&&f.composer.selection.setBookmark(e),f._execCommand(c,a),f.editor.fire("save:dialog",{command:c,dialogContainer:g,commandLink:b})}),d.observe("cancel",function(){f.editor.focus(!1),f.editor.fire("cancel:dialog",{command:c,dialogContainer:g,commandLink:b})})),d},execCommand:function(a,b){if(!this.commandsDisabled){var c=this.commandMapping[a+":"+b];c&&c.dialog&&!c.state?c.dialog.show():this._execCommand(a,b)}},_execCommand:function(a,b){this.editor.focus(!1),this.composer.commands.exec(a,b),this._updateLinkStates()},execAction:function(a){var b=this.editor;switch(a){case"change_view":b.currentView===b.textarea?b.fire("change_view","composer"):b.fire("change_view","textarea")}},_observe:function(){for(var a=this,c=this.editor,d=this.container,e=this.commandLinks.concat(this.actionLinks),f=e.length,g=0;f>g;g++)b.setAttributes({href:"javascript:;",unselectable:"on"}).on(e[g]);b.delegate(d,"[data-wysihtml5-command]","mousedown",function(a){a.preventDefault()}),b.delegate(d,"[data-wysihtml5-command]","click",function(b){var c=this.getAttribute("data-wysihtml5-command"),d=this.getAttribute("data-wysihtml5-command-value");a.execCommand(c,d),b.preventDefault()}),b.delegate(d,"[data-wysihtml5-action]","click",function(b){var c=this.getAttribute("data-wysihtml5-action");a.execAction(c),b.preventDefault()}),c.observe("focus:composer",function(){a.bookmark=null,clearInterval(a.interval),a.interval=setInterval(function(){a._updateLinkStates()},500)}),c.observe("blur:composer",function(){clearInterval(a.interval)}),c.observe("destroy:composer",function(){clearInterval(a.interval)}),c.observe("change_view",function(c){setTimeout(function(){a.commandsDisabled="composer"!==c,a._updateLinkStates(),a.commandsDisabled?b.addClass(d,"wysihtml5-commands-disabled"):b.removeClass(d,"wysihtml5-commands-disabled")},0)})},_updateLinkStates:function(){var c,d,e,f=this.commandMapping,g=this.actionMapping;for(c in f)e=f[c],this.commandsDisabled?(d=!1,b.removeClass(e.link,"wysihtml5-command-active"),e.group&&b.removeClass(e.group,"wysihtml5-command-active"),e.dialog&&e.dialog.hide()):(d=this.composer.commands.state(e.name,e.value),a.lang.object(d).isArray()&&(d=1===d.length?d[0]:!0),b.removeClass(e.link,"wysihtml5-command-disabled"),e.group&&b.removeClass(e.group,"wysihtml5-command-disabled")),e.state!==d&&((e.state=d)?(b.addClass(e.link,"wysihtml5-command-active"),e.group&&b.addClass(e.group,"wysihtml5-command-active"),e.dialog&&("object"==typeof d?e.dialog.show(d):e.dialog.hide())):(b.removeClass(e.link,"wysihtml5-command-active"),e.group&&b.removeClass(e.group,"wysihtml5-command-active"),e.dialog&&e.dialog.hide()));for(c in g)f=g[c],"change_view"===f.name&&(f.state=this.editor.currentView===this.editor.textarea,f.state?b.addClass(f.link,"wysihtml5-action-active"):b.removeClass(f.link,"wysihtml5-action-active"))},show:function(){this.container.style.display=""},hide:function(){this.container.style.display="none"}})}(wysihtml5),function(a){var b={name:void 0,style:!0,toolbar:void 0,autoLink:!0,parserRules:{tags:{br:{},span:{},div:{},p:{}},classes:{}},parser:a.dom.parse,composerClassName:"wysihtml5-editor",bodyClassName:"wysihtml5-supported",stylesheets:[],placeholderText:void 0,allowObjectResizing:!0,supportTouchDevices:!0};a.Editor=a.lang.Dispatcher.extend({constructor:function(c,d){if(this.textareaElement="string"==typeof c?document.getElementById(c):c,this.config=a.lang.object({}).merge(b).merge(d).get(),this.currentView=this.textarea=new a.views.Textarea(this,this.textareaElement,this.config),this._isCompatible=a.browser.supported(),!this._isCompatible||!this.config.supportTouchDevices&&a.browser.isTouchDevice()){var e=this;setTimeout(function(){e.fire("beforeload").fire("load")},0)}else{a.dom.addClass(document.body,this.config.bodyClassName),this.currentView=this.composer=new a.views.Composer(this,this.textareaElement,this.config),"function"==typeof this.config.parser&&this._initParser(),this.observe("beforeload",function(){this.synchronizer=new a.views.Synchronizer(this,this.textarea,this.composer),this.config.toolbar&&(this.toolbar=new a.toolbar.Toolbar(this,this.config.toolbar))});try{console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5")}catch(f){}}},isCompatible:function(){return this._isCompatible},clear:function(){return this.currentView.clear(),this},getValue:function(a){return this.currentView.getValue(a)},setValue:function(a,b){return a?(this.currentView.setValue(a,b),this):this.clear()},focus:function(a){return this.currentView.focus(a),this},disable:function(){return this.currentView.disable(),this},enable:function(){return this.currentView.enable(),this},isEmpty:function(){return this.currentView.isEmpty()},hasPlaceholderSet:function(){return this.currentView.hasPlaceholderSet()},parse:function(b){var c=this.config.parser(b,this.config.parserRules,this.composer.sandbox.getDocument(),!0);return"object"==typeof b&&a.quirks.redraw(b),c},_initParser:function(){this.observe("paste:composer",function(){var b=this;b.composer.selection.executeAndRestore(function(){a.quirks.cleanPastedHTML(b.composer.element),b.parse(b.composer.element)},!0)}),this.observe("paste:textarea",function(){this.textarea.setValue(this.parse(this.textarea.getValue()))})}})}(wysihtml5);var Handlebars=function(){var a=function(){"use strict";function a(a){this.string=a}var b;return a.prototype.toString=function(){return""+this.string},b=a}(),b=function(a){"use strict";function b(a){return h[a]||"&"}function c(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c])}function d(a){return a instanceof g?a.toString():a||0===a?(a=""+a,j.test(a)?a.replace(i,b):a):""}function e(a){return a||0===a?m(a)&&0===a.length?!0:!1:!0}var f={},g=a,h={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},i=/[&<>"'`]/g,j=/[&<>"'`]/;f.extend=c;var k=Object.prototype.toString;f.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;f.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};return f.isArray=m,f.escapeExpression=d,f.isEmpty=e,f}(a),c=function(){"use strict";function a(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f<c.length;f++)this[c[f]]=e[c[f]];d&&(this.lineNumber=d,this.column=b.firstColumn)}var b,c=["description","fileName","lineNumber","message","name","number","stack"];return a.prototype=new Error,b=a}(),d=function(a,b){"use strict";function c(a,b){this.helpers=a||{},this.partials=b||{},d(this)}function d(a){a.registerHelper("helperMissing",function(a){if(2===arguments.length)return void 0;throw new h("Missing helper: '"+a+"'")}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse||function(){},e=c.fn;return m(b)&&(b=b.call(this)),b===!0?e(this):b===!1||null==b?d(this):l(b)?b.length>0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function e(a,b){p.log(a,b)}var f={},g=a,h=b,i="1.3.0";f.VERSION=i;var j=4;f.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};f.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";f.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:p,log:e,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};f.logger=p,f.log=e;var q=function(a){var b={};return g.extend(b,a),b};return f.createFrame=q,f}(b,c),e=function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=g(a,b,c):d||(d=this.programs[a]=g(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function f(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function g(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function h(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function i(){return""}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;return j.checkRevision=d,j.template=e,j.programWithDepth=f,j.program=g,j.invokePartial=h,j.noop=i,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,f=m}(d,a,c,b,e);return f}(),glob="undefined"==typeof window?global:window,Handlebars=glob.Handlebars||require("handlebars");this.wysihtml5=this.wysihtml5||{},this.wysihtml5.tpl=this.wysihtml5.tpl||{},this.wysihtml5.tpl.blockquote=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li>\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="blockquote" data-wysihtml5-display-format-name="false" tabindex="-1">\n <span class="glyphicon glyphicon-quote"></span>\n </a>\n</li>\n'}),this.wysihtml5.tpl.color=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li class="dropdown">\n <a class="btn btn-default dropdown-toggle ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+='" data-toggle="dropdown" tabindex="-1">\n <span class="current-color">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.black,typeof g===j?g.apply(b):g))+'</span>\n <b class="caret"></b>\n </a>\n <ul class="dropdown-menu">\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="black"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="black">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.black,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="silver"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="silver">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.silver,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="gray"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="gray">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.gray,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="maroon"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="maroon">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.maroon,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="red"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="red">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.red,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="purple"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="purple">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.purple,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="green"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="green">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.green,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="olive"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="olive">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.olive,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="navy"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="navy">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.navy,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="blue"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="blue">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.blue,typeof g===j?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="orange"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="orange">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.orange,typeof g===j?g.apply(b):g))+"</a></li>\n </ul>\n</li>\n"}),this.wysihtml5.tpl.emphasis=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b))}function g(a,b){var d,e,g="";return g+='\n <a class="btn ',e=c["if"].call(a,(d=a&&a.options,null==d||d===!1?d:d.size),{hash:{},inverse:m.noop,fn:m.program(1,f,b),data:b}),(e||0===e)&&(g+=e),g+=' btn-default" data-wysihtml5-command="small" title="CTRL+S" tabindex="-1">'+l((d=a&&a.locale,d=null==d||d===!1?d:d.emphasis,d=null==d||d===!1?d:d.small,typeof d===k?d.apply(a):d))+"</a>\n "}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var h,i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li>\n <div class="btn-group">\n <a class="btn ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="bold" title="CTRL+B" tabindex="-1">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.bold,typeof h===k?h.apply(b):h))+'</a>\n <a class="btn ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="italic" title="CTRL+I" tabindex="-1">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.italic,typeof h===k?h.apply(b):h))+'</a>\n <a class="btn ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="underline" title="CTRL+U" tabindex="-1">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.underline,typeof h===k?h.apply(b):h))+"</a>\n ",i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.emSmall),{hash:{},inverse:m.noop,fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+="\n </div>\n</li>\n"}),this.wysihtml5.tpl["font-styles"]=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li class="dropdown">\n <a class="btn btn-default dropdown-toggle ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+='" data-toggle="dropdown">\n <span class="glyphicon glyphicon-font"></span>\n <span class="current-font">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.normal,typeof g===j?g.apply(b):g))+'</span>\n <b class="caret"></b>\n </a>\n <ul class="dropdown-menu">\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="p" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.normal,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h1,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h2" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h2,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h3" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h3,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h4" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h4,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h5" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h5,typeof g===j?g.apply(b):g))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h6" tabindex="-1">'+k((g=b&&b.locale,g=null==g||g===!1?g:g.font_styles,g=null==g||g===!1?g:g.h6,typeof g===j?g.apply(b):g))+"</a></li>\n </ul>\n</li>\n"}),this.wysihtml5.tpl.html=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li>\n <div class="btn-group">\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-action="change_view" title="'+k((g=b&&b.locale,g=null==g||g===!1?g:g.html,g=null==g||g===!1?g:g.edit,typeof g===j?g.apply(b):g))+'" tabindex="-1">\n <span class="glyphicon glyphicon-pencil"></span>\n </a>\n </div>\n</li>\n'}),this.wysihtml5.tpl.image=Handlebars.template(function(a,b,c,d,e){function f(){return"modal-sm"}function g(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var h,i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li>\n <div class="bootstrap-wysihtml5-insert-image-modal modal fade">\n <div class="modal-dialog ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.smallmodals),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+='">\n <div class="modal-content">\n <div class="modal-header">\n <a class="close" data-dismiss="modal">×</a>\n <h3>'+l((h=b&&b.locale,h=null==h||h===!1?h:h.image,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'</h3>\n </div>\n <div class="modal-body">\n <input value="http://" class="bootstrap-wysihtml5-insert-image-url form-control">\n </div>\n <div class="modal-footer">\n <a class="btn btn-default" data-dismiss="modal">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.image,h=null==h||h===!1?h:h.cancel,typeof h===k?h.apply(b):h))+'</a>\n <a class="btn btn-primary" data-dismiss="modal">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.image,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'</a>\n </div>\n </div>\n </div>\n </div>\n <a class="btn ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.size),{hash:{},inverse:m.noop,fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="insertImage" title="'+l((h=b&&b.locale,h=null==h||h===!1?h:h.image,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'" tabindex="-1">\n <span class="glyphicon glyphicon-picture"></span>\n </a>\n</li>\n'
+}),this.wysihtml5.tpl.link=Handlebars.template(function(a,b,c,d,e){function f(){return"modal-sm"}function g(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var h,i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li>\n <div class="bootstrap-wysihtml5-insert-link-modal modal fade">\n <div class="modal-dialog ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.smallmodals),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+='">\n <div class="modal-content">\n <div class="modal-header">\n <a class="close" data-dismiss="modal">×</a>\n <h3>'+l((h=b&&b.locale,h=null==h||h===!1?h:h.link,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'</h3>\n </div>\n <div class="modal-body">\n <input value="http://" class="bootstrap-wysihtml5-insert-link-url form-control">\n <label class="checkbox"> <input type="checkbox" class="bootstrap-wysihtml5-insert-link-target" checked>'+l((h=b&&b.locale,h=null==h||h===!1?h:h.link,h=null==h||h===!1?h:h.target,typeof h===k?h.apply(b):h))+'</label>\n </div>\n <div class="modal-footer">\n <a class="btn btn-default" data-dismiss="modal">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.link,h=null==h||h===!1?h:h.cancel,typeof h===k?h.apply(b):h))+'</a>\n <a href="#" class="btn btn-primary" data-dismiss="modal">'+l((h=b&&b.locale,h=null==h||h===!1?h:h.link,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'</a>\n </div>\n </div>\n </div>\n </div>\n <a class="btn ',i=c["if"].call(b,(h=b&&b.options,null==h||h===!1?h:h.size),{hash:{},inverse:m.noop,fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="createLink" title="'+l((h=b&&b.locale,h=null==h||h===!1?h:h.link,h=null==h||h===!1?h:h.insert,typeof h===k?h.apply(b):h))+'" tabindex="-1">\n <span class="glyphicon glyphicon-share"></span>\n </a>\n</li>\n'}),this.wysihtml5.tpl.lists=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b))}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li>\n <div class="btn-group">\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="insertUnorderedList" title="'+k((g=b&&b.locale,g=null==g||g===!1?g:g.lists,g=null==g||g===!1?g:g.unordered,typeof g===j?g.apply(b):g))+'" tabindex="-1"><span class="glyphicon glyphicon-list"></span></a>\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="insertOrderedList" title="'+k((g=b&&b.locale,g=null==g||g===!1?g:g.lists,g=null==g||g===!1?g:g.ordered,typeof g===j?g.apply(b):g))+'" tabindex="-1"><span class="glyphicon glyphicon-th-list"></span></a>\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="Outdent" title="'+k((g=b&&b.locale,g=null==g||g===!1?g:g.lists,g=null==g||g===!1?g:g.outdent,typeof g===j?g.apply(b):g))+'" tabindex="-1"><span class="glyphicon glyphicon-indent-right"></span></a>\n <a class="btn ',h=c["if"].call(b,(g=b&&b.options,null==g||g===!1?g:g.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="Indent" title="'+k((g=b&&b.locale,g=null==g||g===!1?g:g.lists,g=null==g||g===!1?g:g.indent,typeof g===j?g.apply(b):g))+'" tabindex="-1"><span class="glyphicon glyphicon-indent-left"></span></a>\n </div>\n</li>\n'}),"object"==typeof exports&&exports&&(module.exports=this.wysihtml5.tpl),!function(a,b){"use strict";var c=function(a,c,d){return b.tpl[a]?b.tpl[a]({locale:c,options:d}):void 0},d=function(c,d){this.el=c;var e=a.extend(!0,{},f,d);a.extend(e.shortcuts,f.shortcuts);for(var g in e.customTemplates)b.tpl[g]=e.customTemplates[g];this.toolbar=this.createToolbar(c,e),this.editor=this.createEditor(e),window.editor=this.editor,a("iframe.wysihtml5-sandbox").each(function(b,c){a(c.contentWindow).off("focus.wysihtml5").on({"focus.wysihtml5":function(){a("li.dropdown").removeClass("open")}})})};d.prototype={constructor:d,createEditor:function(c){c=c||{},c=a.extend(!0,{},c),c.toolbar=this.toolbar[0];var d=new b.Editor(this.el[0],c);if(this.addMoreShortcuts(d,d.currentView.iframe.contentDocument.body||d.currentView.iframe.contentDocument,c.shortcuts),c&&c.events)for(var e in c.events)d.on(e,c.events[e]);return d},createToolbar:function(b,d){var e=this,h=a("<ul/>",{"class":"wysihtml5-toolbar",style:"display:none"}),i=d.locale||f.locale||"en";g.hasOwnProperty(i)||(console.debug("Locale '"+i+"' not found. Available locales are: "+Object.keys(g)+". Falling back to 'en'."),i="en");var j=a.extend(!0,{},g.en,g[i]);for(var k in d){var l=!1;void 0!==d[k]?d[k]===!0&&(l=!0):l=f[k],l===!0&&(h.append(c(k,j,d)),"html"===k&&this.initHtml(h),"link"===k&&this.initInsertLink(h),"image"===k&&this.initInsertImage(h))}if(d.toolbar)for(k in d.toolbar)h.append(d.toolbar[k]);return h.find('a[data-wysihtml5-command="formatBlock"]').click(function(b){var c=b.delegateTarget||b.target||b.srcElement,d=a(c),f=d.data("wysihtml5-display-format-name"),g=d.data("wysihtml5-format-name")||d.html();(void 0===f||"true"===f)&&e.toolbar.find(".current-font").text(g)}),h.find('a[data-wysihtml5-command="foreColor"]').click(function(b){var c=b.target||b.srcElement,d=a(c);e.toolbar.find(".current-color").text(d.html())}),this.el.before(h),h},initHtml:function(a){var b='a[data-wysihtml5-action="change_view"]';a.find(b).click(function(){a.find("a.btn").not(b).toggleClass("disabled")})},initInsertImage:function(b){var c,d=this,e=b.find(".bootstrap-wysihtml5-insert-image-modal"),f=e.find(".bootstrap-wysihtml5-insert-image-url"),g=e.find("a.btn-primary"),h=f.val(),i=function(){var a=f.val();f.val(h),d.editor.currentView.element.focus(),c&&(d.editor.composer.selection.setBookmark(c),c=null),d.editor.composer.commands.exec("insertImage",a)};f.keypress(function(a){13==a.which&&(i(),e.modal("hide"))}),g.click(i),e.on("shown",function(){f.focus()}),e.on("hide",function(){d.editor.currentView.element.focus()}),b.find("a[data-wysihtml5-command=insertImage]").click(function(){var b=a(this).hasClass("wysihtml5-command-active");return b?!0:(d.editor.currentView.element.focus(!1),c=d.editor.composer.selection.getBookmark(),e.appendTo("body").modal("show"),e.on("click.dismiss.modal",'[data-dismiss="modal"]',function(a){a.stopPropagation()}),!1)})},initInsertLink:function(b){var c,d=this,e=b.find(".bootstrap-wysihtml5-insert-link-modal"),f=e.find(".bootstrap-wysihtml5-insert-link-url"),g=e.find(".bootstrap-wysihtml5-insert-link-target"),h=e.find("a.btn-primary"),i=f.val(),j=function(){var a=f.val();f.val(i),d.editor.currentView.element.focus(),c&&(d.editor.composer.selection.setBookmark(c),c=null);var b=g.prop("checked");d.editor.composer.commands.exec("createLink",{href:a,target:b?"_blank":"_self",rel:b?"nofollow":""})};f.keypress(function(a){13==a.which&&(j(),e.modal("hide"))}),h.click(j),e.on("shown",function(){f.focus()}),e.on("hide",function(){d.editor.currentView.element.focus()}),b.find("a[data-wysihtml5-command=createLink]").click(function(){var b=a(this).hasClass("wysihtml5-command-active");return b?!0:(d.editor.currentView.element.focus(!1),c=d.editor.composer.selection.getBookmark(),e.appendTo("body").modal("show"),e.on("click.dismiss.modal",'[data-dismiss="modal"]',function(a){a.stopPropagation()}),!1)})},addMoreShortcuts:function(a,c,d){b.dom.observe(c,"keydown",function(c){var e=c.keyCode,f=d[e];(c.ctrlKey||c.metaKey)&&!c.altKey&&f&&b.commands[f]&&(b.commands[f].exec(a.composer,f),c.preventDefault())})}};var e={resetDefaults:function(){a.fn.wysihtml5.defaultOptions=a.extend(!0,{},a.fn.wysihtml5.defaultOptionsCache)},bypassDefaults:function(b){return this.each(function(){var c=a(this);c.data("wysihtml5",new d(c,b))})},shallowExtend:function(b){var c=a.extend({},a.fn.wysihtml5.defaultOptions,b||{},a(this).data()),d=this;return e.bypassDefaults.apply(d,[c])},deepExtend:function(b){var c=a.extend(!0,{},a.fn.wysihtml5.defaultOptions,b||{}),d=this;return e.bypassDefaults.apply(d,[c])},init:function(a){var b=this;return e.shallowExtend.apply(b,[a])}};a.fn.wysihtml5=function(b){return e[b]?e[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("Method "+b+" does not exist on jQuery.wysihtml5"):e.init.apply(this,arguments)},a.fn.wysihtml5.Constructor=d;var f=a.fn.wysihtml5.defaultOptions={"font-styles":!0,color:!1,emphasis:!0,blockquote:!0,lists:!0,html:!1,link:!0,image:!0,smallmodals:!1,events:{},parserRules:{classes:{"wysiwyg-color-silver":1,"wysiwyg-color-gray":1,"wysiwyg-color-white":1,"wysiwyg-color-maroon":1,"wysiwyg-color-red":1,"wysiwyg-color-purple":1,"wysiwyg-color-fuchsia":1,"wysiwyg-color-green":1,"wysiwyg-color-lime":1,"wysiwyg-color-olive":1,"wysiwyg-color-yellow":1,"wysiwyg-color-navy":1,"wysiwyg-color-blue":1,"wysiwyg-color-teal":1,"wysiwyg-color-aqua":1,"wysiwyg-color-orange":1},tags:{b:{},i:{},strong:{},em:{},p:{},br:{},ol:{},ul:{},li:{},h1:{},h2:{},h3:{},h4:{},h5:{},h6:{},blockquote:{},u:1,img:{check_attributes:{width:"numbers",alt:"alt",src:"url",height:"numbers"}},a:{check_attributes:{href:"url"},set_attributes:{target:"_blank",rel:"nofollow"}},span:1,div:1,small:1,code:1,pre:1}},emSmall:1,locale:"en",shortcuts:{83:"small"}};"undefined"==typeof a.fn.wysihtml5.defaultOptionsCache&&(a.fn.wysihtml5.defaultOptionsCache=a.extend(!0,{},a.fn.wysihtml5.defaultOptions));var g=a.fn.wysihtml5.locale={}}(window.jQuery,window.wysihtml5),function(a){var b;a.commands.small={exec:function(b,c){return a.commands.formatInline.exec(b,c,"small")},state:function(b,c){return a.commands.formatInline.state(b,c,"small")},value:function(){return b}}}(wysihtml5),function(a){a.fn.wysihtml5.locale.en=a.fn.wysihtml5.locale["en-US"]={font_styles:{normal:"Normal text",h1:"Heading 1",h2:"Heading 2",h3:"Heading 3",h4:"Heading 4",h5:"Heading 5",h6:"Heading 6"},emphasis:{bold:"Bold",italic:"Italic",underline:"Underline",small:"Small"},lists:{unordered:"Unordered list",ordered:"Ordered list",outdent:"Outdent",indent:"Indent"},link:{insert:"Insert link",cancel:"Cancel",target:"Open link in new window"},image:{insert:"Insert image",cancel:"Cancel"},html:{edit:"Edit HTML"},colours:{black:"Black",silver:"Silver",gray:"Grey",maroon:"Maroon",red:"Red",purple:"Purple",green:"Green",olive:"Olive",navy:"Navy",blue:"Blue",orange:"Orange"}}}(jQuery);
(function() {
- var mapping = {
- "className": "class"
- };
- wysihtml5.dom.setAttributes = function(attributes) {
- return {
- on: function(element) {
- for (var i in attributes) {
- element.setAttribute(mapping[i] || i, attributes[i]);
- }
- }
- }
- };
-})();wysihtml5.dom.setStyles = function(styles) {
- return {
- on: function(element) {
- var style = element.style;
- if (typeof(styles) === "string") {
- style.cssText += ";" + styles;
- return;
- }
- for (var i in styles) {
- if (i === "float") {
- style.cssFloat = styles[i];
- style.styleFloat = styles[i];
- } else {
- style[i] = styles[i];
- }
- }
- }
- };
-};/**
- * Simulate HTML5 placeholder attribute
- *
- * Needed since
- * - div[contentEditable] elements don't support it
- * - older browsers (such as IE8 and Firefox 3.6) don't support it at all
- *
- * @param {Object} parent Instance of main wysihtml5.Editor class
- * @param {Element} view Instance of wysihtml5.views.* class
- * @param {String} placeholderText
- *
- * @example
- * wysihtml.dom.simulatePlaceholder(this, composer, "Foobar");
- */
-(function(dom) {
- dom.simulatePlaceholder = function(editor, view, placeholderText) {
- var CLASS_NAME = "placeholder",
- unset = function() {
- if (view.hasPlaceholderSet()) {
- view.clear();
- }
- dom.removeClass(view.element, CLASS_NAME);
- },
- set = function() {
- if (view.isEmpty()) {
- view.setValue(placeholderText);
- dom.addClass(view.element, CLASS_NAME);
- }
- };
-
- editor
- .observe("set_placeholder", set)
- .observe("unset_placeholder", unset)
- .observe("focus:composer", unset)
- .observe("paste:composer", unset)
- .observe("blur:composer", set);
-
- set();
- };
-})(wysihtml5.dom);
-(function(dom) {
- var documentElement = document.documentElement;
- if ("textContent" in documentElement) {
- dom.setTextContent = function(element, text) {
- element.textContent = text;
- };
-
- dom.getTextContent = function(element) {
- return element.textContent;
- };
- } else if ("innerText" in documentElement) {
- dom.setTextContent = function(element, text) {
- element.innerText = text;
- };
-
- dom.getTextContent = function(element) {
- return element.innerText;
- };
- } else {
- dom.setTextContent = function(element, text) {
- element.nodeValue = text;
- };
-
- dom.getTextContent = function(element) {
- return element.nodeValue;
- };
- }
-})(wysihtml5.dom);
-
-/**
- * Fix most common html formatting misbehaviors of browsers implementation when inserting
- * content via copy & paste contentEditable
- *
- * @author Christopher Blum
- */
-wysihtml5.quirks.cleanPastedHTML = (function() {
- // TODO: We probably need more rules here
- var defaultRules = {
- // When pasting underlined links <a> into a contentEditable, IE thinks, it has to insert <u> to keep the styling
- "a u": wysihtml5.dom.replaceWithChildNodes
- };
-
- function cleanPastedHTML(elementOrHtml, rules, context) {
- rules = rules || defaultRules;
- context = context || elementOrHtml.ownerDocument || document;
-
- var element,
- isString = typeof(elementOrHtml) === "string",
- method,
- matches,
- matchesLength,
- i,
- j = 0;
- if (isString) {
- element = wysihtml5.dom.getAsDom(elementOrHtml, context);
- } else {
- element = elementOrHtml;
- }
-
- for (i in rules) {
- matches = element.querySelectorAll(i);
- method = rules[i];
- matchesLength = matches.length;
- for (; j<matchesLength; j++) {
- method(matches[j]);
- }
- }
-
- matches = elementOrHtml = rules = null;
-
- return isString ? element.innerHTML : element;
- }
-
- return cleanPastedHTML;
-})();/**
- * IE and Opera leave an empty paragraph in the contentEditable element after clearing it
- *
- * @param {Object} contentEditableElement The contentEditable element to observe for clearing events
- * @exaple
- * wysihtml5.quirks.ensureProperClearing(myContentEditableElement);
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom;
-
- wysihtml5.quirks.ensureProperClearing = (function() {
- var clearIfNecessary = function(event) {
- var element = this;
- setTimeout(function() {
- var innerHTML = element.innerHTML.toLowerCase();
- if (innerHTML == "<p> </p>" ||
- innerHTML == "<p> </p><p> </p>") {
- element.innerHTML = "";
- }
- }, 0);
- };
-
- return function(composer) {
- dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary);
- };
- })();
-
-
-
- /**
- * In Opera when the caret is in the first and only item of a list (<ul><li>|</li></ul>) and the list is the first child of the contentEditable element, it's impossible to delete the list by hitting backspace
- *
- * @param {Object} contentEditableElement The contentEditable element to observe for clearing events
- * @exaple
- * wysihtml5.quirks.ensureProperClearing(myContentEditableElement);
- */
- wysihtml5.quirks.ensureProperClearingOfLists = (function() {
- var ELEMENTS_THAT_CONTAIN_LI = ["OL", "UL", "MENU"];
-
- var clearIfNecessary = function(element, contentEditableElement) {
- if (!contentEditableElement.firstChild || !wysihtml5.lang.array(ELEMENTS_THAT_CONTAIN_LI).contains(contentEditableElement.firstChild.nodeName)) {
- return;
- }
-
- var list = dom.getParentElement(element, { nodeName: ELEMENTS_THAT_CONTAIN_LI });
- if (!list) {
- return;
- }
-
- var listIsFirstChildOfContentEditable = list == contentEditableElement.firstChild;
- if (!listIsFirstChildOfContentEditable) {
- return;
- }
-
- var hasOnlyOneListItem = list.childNodes.length <= 1;
- if (!hasOnlyOneListItem) {
- return;
- }
-
- var onlyListItemIsEmpty = list.firstChild ? list.firstChild.innerHTML === "" : true;
- if (!onlyListItemIsEmpty) {
- return;
- }
-
- list.parentNode.removeChild(list);
- };
-
- return function(composer) {
- dom.observe(composer.element, "keydown", function(event) {
- if (event.keyCode !== wysihtml5.BACKSPACE_KEY) {
- return;
- }
-
- var element = composer.selection.getSelectedNode();
- clearIfNecessary(element, composer.element);
- });
- };
- })();
-
-})(wysihtml5);
-// See https://bugzilla.mozilla.org/show_bug.cgi?id=664398
-//
-// In Firefox this:
-// var d = document.createElement("div");
-// d.innerHTML ='<a href="~"></a>';
-// d.innerHTML;
-// will result in:
-// <a href="%7E"></a>
-// which is wrong
-(function(wysihtml5) {
- var TILDE_ESCAPED = "%7E";
- wysihtml5.quirks.getCorrectInnerHTML = function(element) {
- var innerHTML = element.innerHTML;
- if (innerHTML.indexOf(TILDE_ESCAPED) === -1) {
- return innerHTML;
- }
-
- var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"),
- url,
- urlToSearch,
- length,
- i;
- for (i=0, length=elementsWithTilde.length; i<length; i++) {
- url = elementsWithTilde[i].href || elementsWithTilde[i].src;
- urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED);
- innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url);
- }
- return innerHTML;
- };
-})(wysihtml5);/**
- * Some browsers don't insert line breaks when hitting return in a contentEditable element
- * - Opera & IE insert new <p> on return
- * - Chrome & Safari insert new <div> on return
- * - Firefox inserts <br> on return (yippie!)
- *
- * @param {Element} element
- *
- * @example
- * wysihtml5.quirks.insertLineBreakOnReturn(element);
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom,
- USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS = ["LI", "P", "H1", "H2", "H3", "H4", "H5", "H6"],
- LIST_TAGS = ["UL", "OL", "MENU"];
-
- wysihtml5.quirks.insertLineBreakOnReturn = function(composer) {
- function unwrap(selectedNode) {
- var parentElement = dom.getParentElement(selectedNode, { nodeName: ["P", "DIV"] }, 2);
- if (!parentElement) {
- return;
- }
-
- var invisibleSpace = document.createTextNode(wysihtml5.INVISIBLE_SPACE);
- dom.insert(invisibleSpace).before(parentElement);
- dom.replaceWithChildNodes(parentElement);
- composer.selection.selectNode(invisibleSpace);
- }
-
- function keyDown(event) {
- var keyCode = event.keyCode;
- if (event.shiftKey || (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY)) {
- return;
- }
-
- var element = event.target,
- selectedNode = composer.selection.getSelectedNode(),
- blockElement = dom.getParentElement(selectedNode, { nodeName: USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS }, 4);
- if (blockElement) {
- // Some browsers create <p> elements after leaving a list
- // check after keydown of backspace and return whether a <p> got inserted and unwrap it
- if (blockElement.nodeName === "LI" && (keyCode === wysihtml5.ENTER_KEY || keyCode === wysihtml5.BACKSPACE_KEY)) {
- setTimeout(function() {
- var selectedNode = composer.selection.getSelectedNode(),
- list,
- div;
- if (!selectedNode) {
- return;
- }
-
- list = dom.getParentElement(selectedNode, {
- nodeName: LIST_TAGS
- }, 2);
-
- if (list) {
- return;
- }
-
- unwrap(selectedNode);
- }, 0);
- } else if (blockElement.nodeName.match(/H[1-6]/) && keyCode === wysihtml5.ENTER_KEY) {
- setTimeout(function() {
- unwrap(composer.selection.getSelectedNode());
- }, 0);
- }
- return;
- }
-
- if (keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) {
- composer.commands.exec("insertLineBreak");
- event.preventDefault();
- }
- }
-
- // keypress doesn't fire when you hit backspace
- dom.observe(composer.element.ownerDocument, "keydown", keyDown);
- };
-})(wysihtml5);/**
- * Force rerendering of a given element
- * Needed to fix display misbehaviors of IE
- *
- * @param {Element} element The element object which needs to be rerendered
- * @example
- * wysihtml5.quirks.redraw(document.body);
- */
-(function(wysihtml5) {
- var CLASS_NAME = "wysihtml5-quirks-redraw";
-
- wysihtml5.quirks.redraw = function(element) {
- wysihtml5.dom.addClass(element, CLASS_NAME);
- wysihtml5.dom.removeClass(element, CLASS_NAME);
-
- // Following hack is needed for firefox to make sure that image resize handles are properly removed
- try {
- var doc = element.ownerDocument;
- doc.execCommand("italic", false, null);
- doc.execCommand("italic", false, null);
- } catch(e) {}
- };
-})(wysihtml5);/**
- * Selection API
- *
- * @example
- * var selection = new wysihtml5.Selection(editor);
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom;
-
- function _getCumulativeOffsetTop(element) {
- var top = 0;
- if (element.parentNode) {
- do {
- top += element.offsetTop || 0;
- element = element.offsetParent;
- } while (element);
- }
- return top;
- }
-
- wysihtml5.Selection = Base.extend(
- /** @scope wysihtml5.Selection.prototype */ {
- constructor: function(editor) {
- // Make sure that our external range library is initialized
- window.rangy.init();
-
- this.editor = editor;
- this.composer = editor.composer;
- this.doc = this.composer.doc;
- },
-
- /**
- * Get the current selection as a bookmark to be able to later restore it
- *
- * @return {Object} An object that represents the current selection
- */
- getBookmark: function() {
- var range = this.getRange();
- return range && range.cloneRange();
- },
-
- /**
- * Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark
- *
- * @param {Object} bookmark An object that represents the current selection
- */
- setBookmark: function(bookmark) {
- if (!bookmark) {
- return;
- }
-
- this.setSelection(bookmark);
- },
-
- /**
- * Set the caret in front of the given node
- *
- * @param {Object} node The element or text node where to position the caret in front of
- * @example
- * selection.setBefore(myElement);
- */
- setBefore: function(node) {
- var range = rangy.createRange(this.doc);
- range.setStartBefore(node);
- range.setEndBefore(node);
- return this.setSelection(range);
- },
-
- /**
- * Set the caret after the given node
- *
- * @param {Object} node The element or text node where to position the caret in front of
- * @example
- * selection.setBefore(myElement);
- */
- setAfter: function(node) {
- var range = rangy.createRange(this.doc);
- range.setStartAfter(node);
- range.setEndAfter(node);
- return this.setSelection(range);
- },
-
- /**
- * Ability to select/mark nodes
- *
- * @param {Element} node The node/element to select
- * @example
- * selection.selectNode(document.getElementById("my-image"));
- */
- selectNode: function(node) {
- var range = rangy.createRange(this.doc),
- isElement = node.nodeType === wysihtml5.ELEMENT_NODE,
- canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"),
- content = isElement ? node.innerHTML : node.data,
- isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE),
- displayStyle = dom.getStyle("display").from(node),
- isBlockElement = (displayStyle === "block" || displayStyle === "list-item");
-
- if (isEmpty && isElement && canHaveHTML) {
- // Make sure that caret is visible in node by inserting a zero width no breaking space
- try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {}
- }
-
- if (canHaveHTML) {
- range.selectNodeContents(node);
- } else {
- range.selectNode(node);
- }
-
- if (canHaveHTML && isEmpty && isElement) {
- range.collapse(isBlockElement);
- } else if (canHaveHTML && isEmpty) {
- range.setStartAfter(node);
- range.setEndAfter(node);
- }
-
- this.setSelection(range);
- },
-
- /**
- * Get the node which contains the selection
- *
- * @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange"
- * @return {Object} The node that contains the caret
- * @example
- * var nodeThatContainsCaret = selection.getSelectedNode();
- */
- getSelectedNode: function(controlRange) {
- var selection,
- range;
-
- if (controlRange && this.doc.selection && this.doc.selection.type === "Control") {
- range = this.doc.selection.createRange();
- if (range && range.length) {
- return range.item(0);
- }
- }
-
- selection = this.getSelection(this.doc);
- if (selection.focusNode === selection.anchorNode) {
- return selection.focusNode;
- } else {
- range = this.getRange(this.doc);
- return range ? range.commonAncestorContainer : this.doc.body;
- }
- },
-
- executeAndRestore: function(method, restoreScrollPosition) {
- var body = this.doc.body,
- oldScrollTop = restoreScrollPosition && body.scrollTop,
- oldScrollLeft = restoreScrollPosition && body.scrollLeft,
- className = "_wysihtml5-temp-placeholder",
- placeholderHTML = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>',
- range = this.getRange(this.doc),
- newRange;
-
- // Nothing selected, execute and say goodbye
- if (!range) {
- method(body, body);
- return;
- }
-
- var node = range.createContextualFragment(placeholderHTML);
- range.insertNode(node);
-
- // Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder
- try {
- method(range.startContainer, range.endContainer);
- } catch(e3) {
- setTimeout(function() { throw e3; }, 0);
- }
-
- caretPlaceholder = this.doc.querySelector("." + className);
- if (caretPlaceholder) {
- newRange = rangy.createRange(this.doc);
- newRange.selectNode(caretPlaceholder);
- newRange.deleteContents();
- this.setSelection(newRange);
- } else {
- // fallback for when all hell breaks loose
- body.focus();
- }
-
- if (restoreScrollPosition) {
- body.scrollTop = oldScrollTop;
- body.scrollLeft = oldScrollLeft;
- }
-
- // Remove it again, just to make sure that the placeholder is definitely out of the dom tree
- try {
- caretPlaceholder.parentNode.removeChild(caretPlaceholder);
- } catch(e4) {}
- },
-
- /**
- * Different approach of preserving the selection (doesn't modify the dom)
- * Takes all text nodes in the selection and saves the selection position in the first and last one
- */
- executeAndRestoreSimple: function(method) {
- var range = this.getRange(),
- body = this.doc.body,
- newRange,
- firstNode,
- lastNode,
- textNodes,
- rangeBackup;
-
- // Nothing selected, execute and say goodbye
- if (!range) {
- method(body, body);
- return;
- }
-
- textNodes = range.getNodes([3]);
- firstNode = textNodes[0] || range.startContainer;
- lastNode = textNodes[textNodes.length - 1] || range.endContainer;
-
- rangeBackup = {
- collapsed: range.collapsed,
- startContainer: firstNode,
- startOffset: firstNode === range.startContainer ? range.startOffset : 0,
- endContainer: lastNode,
- endOffset: lastNode === range.endContainer ? range.endOffset : lastNode.length
- };
-
- try {
- method(range.startContainer, range.endContainer);
- } catch(e) {
- setTimeout(function() { throw e; }, 0);
- }
-
- newRange = rangy.createRange(this.doc);
- try { newRange.setStart(rangeBackup.startContainer, rangeBackup.startOffset); } catch(e1) {}
- try { newRange.setEnd(rangeBackup.endContainer, rangeBackup.endOffset); } catch(e2) {}
- try { this.setSelection(newRange); } catch(e3) {}
- },
-
- /**
- * Insert html at the caret position and move the cursor after the inserted html
- *
- * @param {String} html HTML string to insert
- * @example
- * selection.insertHTML("<p>foobar</p>");
- */
- insertHTML: function(html) {
- var range = rangy.createRange(this.doc),
- node = range.createContextualFragment(html),
- lastChild = node.lastChild;
- this.insertNode(node);
- if (lastChild) {
- this.setAfter(lastChild);
- }
- },
-
- /**
- * Insert a node at the caret position and move the cursor behind it
- *
- * @param {Object} node HTML string to insert
- * @example
- * selection.insertNode(document.createTextNode("foobar"));
- */
- insertNode: function(node) {
- var range = this.getRange();
- if (range) {
- range.insertNode(node);
- }
- },
-
- /**
- * Wraps current selection with the given node
- *
- * @param {Object} node The node to surround the selected elements with
- */
- surround: function(node) {
- var range = this.getRange();
- if (!range) {
- return;
- }
-
- try {
- // This only works when the range boundaries are not overlapping other elements
- range.surroundContents(node);
- this.selectNode(node);
- } catch(e) {
- // fallback
- node.appendChild(range.extractContents());
- range.insertNode(node);
- }
- },
-
- /**
- * Scroll the current caret position into the view
- * FIXME: This is a bit hacky, there might be a smarter way of doing this
- *
- * @example
- * selection.scrollIntoView();
- */
- scrollIntoView: function() {
- var doc = this.doc,
- hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight,
- tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() {
- var element = doc.createElement("span");
- // The element needs content in order to be able to calculate it's position properly
- element.innerHTML = wysihtml5.INVISIBLE_SPACE;
- return element;
- })(),
- offsetTop;
-
- if (hasScrollBars) {
- this.insertNode(tempElement);
- offsetTop = _getCumulativeOffsetTop(tempElement);
- tempElement.parentNode.removeChild(tempElement);
- if (offsetTop > doc.body.scrollTop) {
- doc.body.scrollTop = offsetTop;
- }
- }
- },
-
- /**
- * Select line where the caret is in
- */
- selectLine: function() {
- if (wysihtml5.browser.supportsSelectionModify()) {
- this._selectLine_W3C();
- } else if (this.doc.selection) {
- this._selectLine_MSIE();
- }
- },
-
- /**
- * See https://developer.mozilla.org/en/DOM/Selection/modify
- */
- _selectLine_W3C: function() {
- var win = this.doc.defaultView,
- selection = win.getSelection();
- selection.modify("extend", "left", "lineboundary");
- selection.modify("extend", "right", "lineboundary");
- },
-
- _selectLine_MSIE: function() {
- var range = this.doc.selection.createRange(),
- rangeTop = range.boundingTop,
- rangeHeight = range.boundingHeight,
- scrollWidth = this.doc.body.scrollWidth,
- rangeBottom,
- rangeEnd,
- measureNode,
- i,
- j;
-
- if (!range.moveToPoint) {
- return;
- }
-
- if (rangeTop === 0) {
- // Don't know why, but when the selection ends at the end of a line
- // range.boundingTop is 0
- measureNode = this.doc.createElement("span");
- this.insertNode(measureNode);
- rangeTop = measureNode.offsetTop;
- measureNode.parentNode.removeChild(measureNode);
- }
-
- rangeTop += 1;
-
- for (i=-10; i<scrollWidth; i+=2) {
- try {
- range.moveToPoint(i, rangeTop);
- break;
- } catch(e1) {}
- }
-
- // Investigate the following in order to handle multi line selections
- // rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0);
- rangeBottom = rangeTop;
- rangeEnd = this.doc.selection.createRange();
- for (j=scrollWidth; j>=0; j--) {
- try {
- rangeEnd.moveToPoint(j, rangeBottom);
- break;
- } catch(e2) {}
- }
-
- range.setEndPoint("EndToEnd", rangeEnd);
- range.select();
- },
-
- getText: function() {
- var selection = this.getSelection();
- return selection ? selection.toString() : "";
- },
-
- getNodes: function(nodeType, filter) {
- var range = this.getRange();
- if (range) {
- return range.getNodes([nodeType], filter);
- } else {
- return [];
- }
- },
-
- getRange: function() {
- var selection = this.getSelection();
- return selection && selection.rangeCount && selection.getRangeAt(0);
- },
-
- getSelection: function() {
- return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow);
- },
-
- setSelection: function(range) {
- var win = this.doc.defaultView || this.doc.parentWindow,
- selection = rangy.getSelection(win);
- return selection.setSingleRange(range);
- }
- });
-
-})(wysihtml5);
-/**
- * Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license.
- * http://code.google.com/p/rangy/
- *
- * changed in order to be able ...
- * - to use custom tags
- * - to detect and replace similar css classes via reg exp
- */
-(function(wysihtml5, rangy) {
- var defaultTagName = "span";
-
- var REG_EXP_WHITE_SPACE = /\s+/g;
-
- function hasClass(el, cssClass, regExp) {
- if (!el.className) {
- return false;
- }
-
- var matchingClassNames = el.className.match(regExp) || [];
- return matchingClassNames[matchingClassNames.length - 1] === cssClass;
- }
-
- function addClass(el, cssClass, regExp) {
- if (el.className) {
- removeClass(el, regExp);
- el.className += " " + cssClass;
- } else {
- el.className = cssClass;
- }
- }
-
- function removeClass(el, regExp) {
- if (el.className) {
- el.className = el.className.replace(regExp, "");
- }
- }
-
- function hasSameClasses(el1, el2) {
- return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " ");
- }
-
- function replaceWithOwnChildren(el) {
- var parent = el.parentNode;
- while (el.firstChild) {
- parent.insertBefore(el.firstChild, el);
- }
- parent.removeChild(el);
- }
-
- function elementsHaveSameNonClassAttributes(el1, el2) {
- if (el1.attributes.length != el2.attributes.length) {
- return false;
- }
- for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) {
- attr1 = el1.attributes[i];
- name = attr1.name;
- if (name != "class") {
- attr2 = el2.attributes.getNamedItem(name);
- if (attr1.specified != attr2.specified) {
- return false;
- }
- if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) {
- return false;
- }
- }
- }
- return true;
- }
-
- function isSplitPoint(node, offset) {
- if (rangy.dom.isCharacterDataNode(node)) {
- if (offset == 0) {
- return !!node.previousSibling;
- } else if (offset == node.length) {
- return !!node.nextSibling;
- } else {
- return true;
- }
- }
-
- return offset > 0 && offset < node.childNodes.length;
- }
-
- function splitNodeAt(node, descendantNode, descendantOffset) {
- var newNode;
- if (rangy.dom.isCharacterDataNode(descendantNode)) {
- if (descendantOffset == 0) {
- descendantOffset = rangy.dom.getNodeIndex(descendantNode);
- descendantNode = descendantNode.parentNode;
- } else if (descendantOffset == descendantNode.length) {
- descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1;
- descendantNode = descendantNode.parentNode;
- } else {
- newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset);
- }
- }
- if (!newNode) {
- newNode = descendantNode.cloneNode(false);
- if (newNode.id) {
- newNode.removeAttribute("id");
- }
- var child;
- while ((child = descendantNode.childNodes[descendantOffset])) {
- newNode.appendChild(child);
- }
- rangy.dom.insertAfter(newNode, descendantNode);
- }
- return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode));
- }
-
- function Merge(firstNode) {
- this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE);
- this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode;
- this.textNodes = [this.firstTextNode];
- }
-
- Merge.prototype = {
- doMerge: function() {
- var textBits = [], textNode, parent, text;
- for (var i = 0, len = this.textNodes.length; i < len; ++i) {
- textNode = this.textNodes[i];
- parent = textNode.parentNode;
- textBits[i] = textNode.data;
- if (i) {
- parent.removeChild(textNode);
- if (!parent.hasChildNodes()) {
- parent.parentNode.removeChild(parent);
- }
- }
- }
- this.firstTextNode.data = text = textBits.join("");
- return text;
- },
-
- getLength: function() {
- var i = this.textNodes.length, len = 0;
- while (i--) {
- len += this.textNodes[i].length;
- }
- return len;
- },
-
- toString: function() {
- var textBits = [];
- for (var i = 0, len = this.textNodes.length; i < len; ++i) {
- textBits[i] = "'" + this.textNodes[i].data + "'";
- }
- return "[Merge(" + textBits.join(",") + ")]";
- }
- };
-
- function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize) {
- this.tagNames = tagNames || [defaultTagName];
- this.cssClass = cssClass || "";
- this.similarClassRegExp = similarClassRegExp;
- this.normalize = normalize;
- this.applyToAnyTagName = false;
- }
-
- HTMLApplier.prototype = {
- getAncestorWithClass: function(node) {
- var cssClassMatch;
- while (node) {
- cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : true;
- if (node.nodeType == wysihtml5.ELEMENT_NODE && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) {
- return node;
- }
- node = node.parentNode;
- }
- return false;
- },
-
- // Normalizes nodes after applying a CSS class to a Range.
- postApply: function(textNodes, range) {
- var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];
-
- var merges = [], currentMerge;
-
- var rangeStartNode = firstNode, rangeEndNode = lastNode;
- var rangeStartOffset = 0, rangeEndOffset = lastNode.length;
-
- var textNode, precedingTextNode;
-
- for (var i = 0, len = textNodes.length; i < len; ++i) {
- textNode = textNodes[i];
- precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false);
- if (precedingTextNode) {
- if (!currentMerge) {
- currentMerge = new Merge(precedingTextNode);
- merges.push(currentMerge);
- }
- currentMerge.textNodes.push(textNode);
- if (textNode === firstNode) {
- rangeStartNode = currentMerge.firstTextNode;
- rangeStartOffset = rangeStartNode.length;
- }
- if (textNode === lastNode) {
- rangeEndNode = currentMerge.firstTextNode;
- rangeEndOffset = currentMerge.getLength();
- }
- } else {
- currentMerge = null;
- }
- }
-
- // Test whether the first node after the range needs merging
- var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true);
- if (nextTextNode) {
- if (!currentMerge) {
- currentMerge = new Merge(lastNode);
- merges.push(currentMerge);
- }
- currentMerge.textNodes.push(nextTextNode);
- }
-
- // Do the merges
- if (merges.length) {
- for (i = 0, len = merges.length; i < len; ++i) {
- merges[i].doMerge();
- }
- // Set the range boundaries
- range.setStart(rangeStartNode, rangeStartOffset);
- range.setEnd(rangeEndNode, rangeEndOffset);
- }
- },
-
- getAdjacentMergeableTextNode: function(node, forward) {
- var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE);
- var el = isTextNode ? node.parentNode : node;
- var adjacentNode;
- var propName = forward ? "nextSibling" : "previousSibling";
- if (isTextNode) {
- // Can merge if the node's previous/next sibling is a text node
- adjacentNode = node[propName];
- if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) {
- return adjacentNode;
- }
- } else {
- // Compare element with its sibling
- adjacentNode = el[propName];
- if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) {
- return adjacentNode[forward ? "firstChild" : "lastChild"];
- }
- }
- return null;
- },
-
- areElementsMergeable: function(el1, el2) {
- return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase())
- && rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase())
- && hasSameClasses(el1, el2)
- && elementsHaveSameNonClassAttributes(el1, el2);
- },
-
- createContainer: function(doc) {
- var el = doc.createElement(this.tagNames[0]);
- if (this.cssClass) {
- el.className = this.cssClass;
- }
- return el;
- },
-
- applyToTextNode: function(textNode) {
- var parent = textNode.parentNode;
- if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) {
- if (this.cssClass) {
- addClass(parent, this.cssClass, this.similarClassRegExp);
- }
- } else {
- var el = this.createContainer(rangy.dom.getDocument(textNode));
- textNode.parentNode.insertBefore(el, textNode);
- el.appendChild(textNode);
- }
- },
-
- isRemovable: function(el) {
- return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() == this.cssClass;
- },
-
- undoToTextNode: function(textNode, range, ancestorWithClass) {
- if (!range.containsNode(ancestorWithClass)) {
- // Split out the portion of the ancestor from which we can remove the CSS class
- var ancestorRange = range.cloneRange();
- ancestorRange.selectNode(ancestorWithClass);
-
- if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) {
- splitNodeAt(ancestorWithClass, range.endContainer, range.endOffset);
- range.setEndAfter(ancestorWithClass);
- }
- if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) {
- ancestorWithClass = splitNodeAt(ancestorWithClass, range.startContainer, range.startOffset);
- }
- }
-
- if (this.similarClassRegExp) {
- removeClass(ancestorWithClass, this.similarClassRegExp);
- }
- if (this.isRemovable(ancestorWithClass)) {
- replaceWithOwnChildren(ancestorWithClass);
- }
- },
-
- applyToRange: function(range) {
- var textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
- if (!textNodes.length) {
- try {
- var node = this.createContainer(range.endContainer.ownerDocument);
- range.surroundContents(node);
- this.selectNode(range, node);
- return;
- } catch(e) {}
- }
-
- range.splitBoundaries();
- textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
-
- if (textNodes.length) {
- var textNode;
-
- for (var i = 0, len = textNodes.length; i < len; ++i) {
- textNode = textNodes[i];
- if (!this.getAncestorWithClass(textNode)) {
- this.applyToTextNode(textNode);
- }
- }
-
- range.setStart(textNodes[0], 0);
- textNode = textNodes[textNodes.length - 1];
- range.setEnd(textNode, textNode.length);
-
- if (this.normalize) {
- this.postApply(textNodes, range);
- }
- }
- },
-
- undoToRange: function(range) {
- var textNodes = range.getNodes([wysihtml5.TEXT_NODE]), textNode, ancestorWithClass;
- if (textNodes.length) {
- range.splitBoundaries();
- textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
- } else {
- var doc = range.endContainer.ownerDocument,
- node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
- range.insertNode(node);
- range.selectNode(node);
- textNodes = [node];
- }
-
- for (var i = 0, len = textNodes.length; i < len; ++i) {
- textNode = textNodes[i];
- ancestorWithClass = this.getAncestorWithClass(textNode);
- if (ancestorWithClass) {
- this.undoToTextNode(textNode, range, ancestorWithClass);
- }
- }
-
- if (len == 1) {
- this.selectNode(range, textNodes[0]);
- } else {
- range.setStart(textNodes[0], 0);
- textNode = textNodes[textNodes.length - 1];
- range.setEnd(textNode, textNode.length);
-
- if (this.normalize) {
- this.postApply(textNodes, range);
- }
- }
- },
-
- selectNode: function(range, node) {
- var isElement = node.nodeType === wysihtml5.ELEMENT_NODE,
- canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true,
- content = isElement ? node.innerHTML : node.data,
- isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE);
-
- if (isEmpty && isElement && canHaveHTML) {
- // Make sure that caret is visible in node by inserting a zero width no breaking space
- try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {}
- }
- range.selectNodeContents(node);
- if (isEmpty && isElement) {
- range.collapse(false);
- } else if (isEmpty) {
- range.setStartAfter(node);
- range.setEndAfter(node);
- }
- },
-
- getTextSelectedByRange: function(textNode, range) {
- var textRange = range.cloneRange();
- textRange.selectNodeContents(textNode);
-
- var intersectionRange = textRange.intersection(range);
- var text = intersectionRange ? intersectionRange.toString() : "";
- textRange.detach();
-
- return text;
- },
-
- isAppliedToRange: function(range) {
- var ancestors = [],
- ancestor,
- textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
- if (!textNodes.length) {
- ancestor = this.getAncestorWithClass(range.startContainer);
- return ancestor ? [ancestor] : false;
- }
-
- for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) {
- selectedText = this.getTextSelectedByRange(textNodes[i], range);
- ancestor = this.getAncestorWithClass(textNodes[i]);
- if (selectedText != "" && !ancestor) {
- return false;
- } else {
- ancestors.push(ancestor);
- }
- }
- return ancestors;
- },
-
- toggleRange: function(range) {
- if (this.isAppliedToRange(range)) {
- this.undoToRange(range);
- } else {
- this.applyToRange(range);
- }
- }
- };
-
- wysihtml5.selection.HTMLApplier = HTMLApplier;
-
-})(wysihtml5, rangy);/**
- * Rich Text Query/Formatting Commands
- *
- * @example
- * var commands = new wysihtml5.Commands(editor);
- */
-wysihtml5.Commands = Base.extend(
- /** @scope wysihtml5.Commands.prototype */ {
- constructor: function(editor) {
- this.editor = editor;
- this.composer = editor.composer;
- this.doc = this.composer.doc;
- },
-
- /**
- * Check whether the browser supports the given command
- *
- * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList")
- * @example
- * commands.supports("createLink");
- */
- support: function(command) {
- return wysihtml5.browser.supportsCommand(this.doc, command);
- },
-
- /**
- * Check whether the browser supports the given command
- *
- * @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList")
- * @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...)
- * @example
- * commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg");
- */
- exec: function(command, value) {
- var obj = wysihtml5.commands[command],
- args = wysihtml5.lang.array(arguments).get(),
- method = obj && obj.exec,
- result = null;
-
- this.editor.fire("beforecommand:composer");
-
- if (method) {
- args.unshift(this.composer);
- result = method.apply(obj, args);
- } else {
- try {
- // try/catch for buggy firefox
- result = this.doc.execCommand(command, false, value);
- } catch(e) {}
- }
-
- this.editor.fire("aftercommand:composer");
- return result;
- },
-
- /**
- * Check whether the current command is active
- * If the caret is within a bold text, then calling this with command "bold" should return true
- *
- * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList")
- * @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src)
- * @return {Boolean} Whether the command is active
- * @example
- * var isCurrentSelectionBold = commands.state("bold");
- */
- state: function(command, commandValue) {
- var obj = wysihtml5.commands[command],
- args = wysihtml5.lang.array(arguments).get(),
- method = obj && obj.state;
- if (method) {
- args.unshift(this.composer);
- return method.apply(obj, args);
- } else {
- try {
- // try/catch for buggy firefox
- return this.doc.queryCommandState(command);
- } catch(e) {
- return false;
- }
- }
- },
-
- /**
- * Get the current command's value
- *
- * @param {String} command The command string which to check (eg. "formatBlock")
- * @return {String} The command value
- * @example
- * var currentBlockElement = commands.value("formatBlock");
- */
- value: function(command) {
- var obj = wysihtml5.commands[command],
- method = obj && obj.value;
- if (method) {
- return method.call(obj, this.composer, command);
- } else {
- try {
- // try/catch for buggy firefox
- return this.doc.queryCommandValue(command);
- } catch(e) {
- return null;
- }
- }
- }
-});
-(function(wysihtml5) {
- var undef;
-
- wysihtml5.commands.bold = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatInline.exec(composer, command, "b");
- },
-
- state: function(composer, command, color) {
- // element.ownerDocument.queryCommandState("bold") results:
- // firefox: only <b>
- // chrome: <b>, <strong>, <h1>, <h2>, ...
- // ie: <b>, <strong>
- // opera: <b>, <strong>
- return wysihtml5.commands.formatInline.state(composer, command, "b");
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);
-
-(function(wysihtml5) {
- var undef,
- NODE_NAME = "A",
- dom = wysihtml5.dom;
-
- function _removeFormat(composer, anchors) {
- var length = anchors.length,
- i = 0,
- anchor,
- codeElement,
- textContent;
- for (; i<length; i++) {
- anchor = anchors[i];
- codeElement = dom.getParentElement(anchor, { nodeName: "code" });
- textContent = dom.getTextContent(anchor);
-
- // if <a> contains url-like text content, rename it to <code> to prevent re-autolinking
- // else replace <a> with its childNodes
- if (textContent.match(dom.autoLink.URL_REG_EXP) && !codeElement) {
- // <code> element is used to prevent later auto-linking of the content
- codeElement = dom.renameElement(anchor, "code");
- } else {
- dom.replaceWithChildNodes(anchor);
- }
- }
- }
-
- function _format(composer, attributes) {
- var doc = composer.doc,
- tempClass = "_wysihtml5-temp-" + (+new Date()),
- tempClassRegExp = /non-matching-class/g,
- i = 0,
- length,
- anchors,
- anchor,
- hasElementChild,
- isEmpty,
- elementToSetCaretAfter,
- textContent,
- whiteSpace,
- j;
- wysihtml5.commands.formatInline.exec(composer, undef, NODE_NAME, tempClass, tempClassRegExp);
- anchors = doc.querySelectorAll(NODE_NAME + "." + tempClass);
- length = anchors.length;
- for (; i<length; i++) {
- anchor = anchors[i];
- anchor.removeAttribute("class");
- for (j in attributes) {
- anchor.setAttribute(j, attributes[j]);
- }
- }
-
- elementToSetCaretAfter = anchor;
- if (length === 1) {
- textContent = dom.getTextContent(anchor);
- hasElementChild = !!anchor.querySelector("*");
- isEmpty = textContent === "" || textContent === wysihtml5.INVISIBLE_SPACE;
- if (!hasElementChild && isEmpty) {
- dom.setTextContent(anchor, attributes.text || anchor.href);
- whiteSpace = doc.createTextNode(" ");
- composer.selection.setAfter(anchor);
- composer.selection.insertNode(whiteSpace);
- elementToSetCaretAfter = whiteSpace;
- }
- }
- composer.selection.setAfter(elementToSetCaretAfter);
- }
-
- wysihtml5.commands.createLink = {
- /**
- * TODO: Use HTMLApplier or formatInline here
- *
- * Turns selection into a link
- * If selection is already a link, it removes the link and wraps it with a <code> element
- * The <code> element is needed to avoid auto linking
- *
- * @example
- * // either ...
- * wysihtml5.commands.createLink.exec(composer, "createLink", "http://www.google.de");
- * // ... or ...
- * wysihtml5.commands.createLink.exec(composer, "createLink", { href: "http://www.google.de", target: "_blank" });
- */
- exec: function(composer, command, value) {
- var anchors = this.state(composer, command);
- if (anchors) {
- // Selection contains links
- composer.selection.executeAndRestore(function() {
- _removeFormat(composer, anchors);
- });
- } else {
- // Create links
- value = typeof(value) === "object" ? value : { href: value };
- _format(composer, value);
- }
- },
-
- state: function(composer, command) {
- return wysihtml5.commands.formatInline.state(composer, command, "A");
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);/**
- * document.execCommand("fontSize") will create either inline styles (firefox, chrome) or use font tags
- * which we don't want
- * Instead we set a css class
- */
-(function(wysihtml5) {
- var undef,
- REG_EXP = /wysiwyg-font-size-[a-z\-]+/g;
-
- wysihtml5.commands.fontSize = {
- exec: function(composer, command, size) {
- return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP);
- },
-
- state: function(composer, command, size) {
- return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);
-/**
- * document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags
- * which we don't want
- * Instead we set a css class
- */
-(function(wysihtml5) {
- var undef,
- REG_EXP = /wysiwyg-color-[a-z]+/g;
-
- wysihtml5.commands.foreColor = {
- exec: function(composer, command, color) {
- return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-color-" + color, REG_EXP);
- },
-
- state: function(composer, command, color) {
- return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-color-" + color, REG_EXP);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef,
- dom = wysihtml5.dom,
- DEFAULT_NODE_NAME = "DIV",
- // Following elements are grouped
- // when the caret is within a H1 and the H4 is invoked, the H1 should turn into H4
- // instead of creating a H4 within a H1 which would result in semantically invalid html
- BLOCK_ELEMENTS_GROUP = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "BLOCKQUOTE", DEFAULT_NODE_NAME];
-
- /**
- * Remove similiar classes (based on classRegExp)
- * and add the desired class name
- */
- function _addClass(element, className, classRegExp) {
- if (element.className) {
- _removeClass(element, classRegExp);
- element.className += " " + className;
- } else {
- element.className = className;
- }
- }
-
- function _removeClass(element, classRegExp) {
- element.className = element.className.replace(classRegExp, "");
- }
-
- /**
- * Check whether given node is a text node and whether it's empty
- */
- function _isBlankTextNode(node) {
- return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim();
- }
-
- /**
- * Returns previous sibling node that is not a blank text node
- */
- function _getPreviousSiblingThatIsNotBlank(node) {
- var previousSibling = node.previousSibling;
- while (previousSibling && _isBlankTextNode(previousSibling)) {
- previousSibling = previousSibling.previousSibling;
- }
- return previousSibling;
- }
-
- /**
- * Returns next sibling node that is not a blank text node
- */
- function _getNextSiblingThatIsNotBlank(node) {
- var nextSibling = node.nextSibling;
- while (nextSibling && _isBlankTextNode(nextSibling)) {
- nextSibling = nextSibling.nextSibling;
- }
- return nextSibling;
- }
-
- /**
- * Adds line breaks before and after the given node if the previous and next siblings
- * aren't already causing a visual line break (block element or <br>)
- */
- function _addLineBreakBeforeAndAfter(node) {
- var doc = node.ownerDocument,
- nextSibling = _getNextSiblingThatIsNotBlank(node),
- previousSibling = _getPreviousSiblingThatIsNotBlank(node);
-
- if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) {
- node.parentNode.insertBefore(doc.createElement("br"), nextSibling);
- }
- if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) {
- node.parentNode.insertBefore(doc.createElement("br"), node);
- }
- }
-
- /**
- * Removes line breaks before and after the given node
- */
- function _removeLineBreakBeforeAndAfter(node) {
- var nextSibling = _getNextSiblingThatIsNotBlank(node),
- previousSibling = _getPreviousSiblingThatIsNotBlank(node);
-
- if (nextSibling && _isLineBreak(nextSibling)) {
- nextSibling.parentNode.removeChild(nextSibling);
- }
- if (previousSibling && _isLineBreak(previousSibling)) {
- previousSibling.parentNode.removeChild(previousSibling);
- }
- }
-
- function _removeLastChildIfLineBreak(node) {
- var lastChild = node.lastChild;
- if (lastChild && _isLineBreak(lastChild)) {
- lastChild.parentNode.removeChild(lastChild);
- }
- }
-
- function _isLineBreak(node) {
- return node.nodeName === "BR";
- }
-
- /**
- * Checks whether the elment causes a visual line break
- * (<br> or block elements)
- */
- function _isLineBreakOrBlockElement(element) {
- if (_isLineBreak(element)) {
- return true;
- }
-
- if (dom.getStyle("display").from(element) === "block") {
- return true;
- }
-
- return false;
- }
-
- /**
- * Execute native query command
- * and if necessary modify the inserted node's className
- */
- function _execCommand(doc, command, nodeName, className) {
- if (className) {
- var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) {
- var target = event.target,
- displayStyle;
- if (target.nodeType !== wysihtml5.ELEMENT_NODE) {
- return;
- }
- displayStyle = dom.getStyle("display").from(target);
- if (displayStyle.substr(0, 6) !== "inline") {
- // Make sure that only block elements receive the given class
- target.className += " " + className;
- }
- });
- }
- doc.execCommand(command, false, nodeName);
- if (eventListener) {
- eventListener.stop();
- }
- }
-
- function _selectLineAndWrap(composer, element) {
- composer.selection.selectLine();
- composer.selection.surround(element);
- _removeLineBreakBeforeAndAfter(element);
- _removeLastChildIfLineBreak(element);
- composer.selection.selectNode(element);
- }
-
- function _hasClasses(element) {
- return !!wysihtml5.lang.string(element.className).trim();
- }
-
- wysihtml5.commands.formatBlock = {
- exec: function(composer, command, nodeName, className, classRegExp) {
- var doc = composer.doc,
- blockElement = this.state(composer, command, nodeName, className, classRegExp),
- selectedNode;
-
- nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName;
-
- if (blockElement) {
- composer.selection.executeAndRestoreSimple(function() {
- if (classRegExp) {
- _removeClass(blockElement, classRegExp);
- }
- var hasClasses = _hasClasses(blockElement);
- if (!hasClasses && blockElement.nodeName === (nodeName || DEFAULT_NODE_NAME)) {
- // Insert a line break afterwards and beforewards when there are siblings
- // that are not of type line break or block element
- _addLineBreakBeforeAndAfter(blockElement);
- dom.replaceWithChildNodes(blockElement);
- } else if (hasClasses) {
- // Make sure that styling is kept by renaming the element to <div> and copying over the class name
- dom.renameElement(blockElement, DEFAULT_NODE_NAME);
- }
- });
- return;
- }
-
- // Find similiar block element and rename it (<h2 class="foo"></h2> => <h1 class="foo"></h1>)
- if (nodeName === null || wysihtml5.lang.array(BLOCK_ELEMENTS_GROUP).contains(nodeName)) {
- selectedNode = composer.selection.getSelectedNode();
- blockElement = dom.getParentElement(selectedNode, {
- nodeName: BLOCK_ELEMENTS_GROUP
- });
-
- if (blockElement) {
- composer.selection.executeAndRestoreSimple(function() {
- // Rename current block element to new block element and add class
- if (nodeName) {
- blockElement = dom.renameElement(blockElement, nodeName);
- }
- if (className) {
- _addClass(blockElement, className, classRegExp);
- }
- });
- return;
- }
- }
-
- if (composer.commands.support(command)) {
- _execCommand(doc, command, nodeName || DEFAULT_NODE_NAME, className);
- return;
- }
-
- blockElement = doc.createElement(nodeName || DEFAULT_NODE_NAME);
- if (className) {
- blockElement.className = className;
- }
- _selectLineAndWrap(composer, blockElement);
- },
-
- state: function(composer, command, nodeName, className, classRegExp) {
- nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName;
- var selectedNode = composer.selection.getSelectedNode();
- return dom.getParentElement(selectedNode, {
- nodeName: nodeName,
- className: className,
- classRegExp: classRegExp
- });
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);/**
- * formatInline scenarios for tag "B" (| = caret, |foo| = selected text)
- *
- * #1 caret in unformatted text:
- * abcdefg|
- * output:
- * abcdefg<b>|</b>
- *
- * #2 unformatted text selected:
- * abc|deg|h
- * output:
- * abc<b>|deg|</b>h
- *
- * #3 unformatted text selected across boundaries:
- * ab|c <span>defg|h</span>
- * output:
- * ab<b>|c </b><span><b>defg</b>|h</span>
- *
- * #4 formatted text entirely selected
- * <b>|abc|</b>
- * output:
- * |abc|
- *
- * #5 formatted text partially selected
- * <b>ab|c|</b>
- * output:
- * <b>ab</b>|c|
- *
- * #6 formatted text selected across boundaries
- * <span>ab|c</span> <b>de|fgh</b>
- * output:
- * <span>ab|c</span> de|<b>fgh</b>
- */
-(function(wysihtml5) {
- var undef,
- // Treat <b> as <strong> and vice versa
- ALIAS_MAPPING = {
- "strong": "b",
- "em": "i",
- "b": "strong",
- "i": "em"
- },
- htmlApplier = {};
-
- function _getTagNames(tagName) {
- var alias = ALIAS_MAPPING[tagName];
- return alias ? [tagName.toLowerCase(), alias.toLowerCase()] : [tagName.toLowerCase()];
- }
-
- function _getApplier(tagName, className, classRegExp) {
- var identifier = tagName + ":" + className;
- if (!htmlApplier[identifier]) {
- htmlApplier[identifier] = new wysihtml5.selection.HTMLApplier(_getTagNames(tagName), className, classRegExp, true);
- }
- return htmlApplier[identifier];
- }
-
- wysihtml5.commands.formatInline = {
- exec: function(composer, command, tagName, className, classRegExp) {
- var range = composer.selection.getRange();
- if (!range) {
- return false;
- }
- _getApplier(tagName, className, classRegExp).toggleRange(range);
- composer.selection.setSelection(range);
- },
-
- state: function(composer, command, tagName, className, classRegExp) {
- var doc = composer.doc,
- aliasTagName = ALIAS_MAPPING[tagName] || tagName,
- range;
-
- // Check whether the document contains a node with the desired tagName
- if (!wysihtml5.dom.hasElementWithTagName(doc, tagName) &&
- !wysihtml5.dom.hasElementWithTagName(doc, aliasTagName)) {
- return false;
- }
-
- // Check whether the document contains a node with the desired className
- if (className && !wysihtml5.dom.hasElementWithClassName(doc, className)) {
- return false;
- }
-
- range = composer.selection.getRange();
- if (!range) {
- return false;
- }
-
- return _getApplier(tagName, className, classRegExp).isAppliedToRange(range);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef;
-
- wysihtml5.commands.insertHTML = {
- exec: function(composer, command, html) {
- if (composer.commands.support(command)) {
- composer.doc.execCommand(command, false, html);
- } else {
- composer.selection.insertHTML(html);
- }
- },
-
- state: function() {
- return false;
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var NODE_NAME = "IMG";
-
- wysihtml5.commands.insertImage = {
- /**
- * Inserts an <img>
- * If selection is already an image link, it removes it
- *
- * @example
- * // either ...
- * wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg");
- * // ... or ...
- * wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" });
- */
- exec: function(composer, command, value) {
- value = typeof(value) === "object" ? value : { src: value };
-
- var doc = composer.doc,
- image = this.state(composer),
- textNode,
- i,
- parent;
-
- if (image) {
- // Image already selected, set the caret before it and delete it
- composer.selection.setBefore(image);
- parent = image.parentNode;
- parent.removeChild(image);
-
- // and it's parent <a> too if it hasn't got any other relevant child nodes
- wysihtml5.dom.removeEmptyTextNodes(parent);
- if (parent.nodeName === "A" && !parent.firstChild) {
- composer.selection.setAfter(parent);
- parent.parentNode.removeChild(parent);
- }
-
- // firefox and ie sometimes don't remove the image handles, even though the image got removed
- wysihtml5.quirks.redraw(composer.element);
- return;
- }
-
- image = doc.createElement(NODE_NAME);
-
- for (i in value) {
- image[i] = value[i];
- }
-
- composer.selection.insertNode(image);
- if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) {
- textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
- composer.selection.insertNode(textNode);
- composer.selection.setAfter(textNode);
- } else {
- composer.selection.setAfter(image);
- }
- },
-
- state: function(composer) {
- var doc = composer.doc,
- selectedNode,
- text,
- imagesInSelection;
-
- if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) {
- return false;
- }
-
- selectedNode = composer.selection.getSelectedNode();
- if (!selectedNode) {
- return false;
- }
-
- if (selectedNode.nodeName === NODE_NAME) {
- // This works perfectly in IE
- return selectedNode;
- }
-
- if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) {
- return false;
- }
-
- text = composer.selection.getText();
- text = wysihtml5.lang.string(text).trim();
- if (text) {
- return false;
- }
-
- imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) {
- return node.nodeName === "IMG";
- });
-
- if (imagesInSelection.length !== 1) {
- return false;
- }
-
- return imagesInSelection[0];
- },
-
- value: function(composer) {
- var image = this.state(composer);
- return image && image.src;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef,
- LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : "");
-
- wysihtml5.commands.insertLineBreak = {
- exec: function(composer, command) {
- if (composer.commands.support(command)) {
- composer.doc.execCommand(command, false, null);
- if (!wysihtml5.browser.autoScrollsToCaret()) {
- composer.selection.scrollIntoView();
- }
- } else {
- composer.commands.exec("insertHTML", LINE_BREAK);
- }
- },
-
- state: function() {
- return false;
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef;
-
- wysihtml5.commands.insertOrderedList = {
- exec: function(composer, command) {
- var doc = composer.doc,
- selectedNode = composer.selection.getSelectedNode(),
- list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }),
- otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }),
- tempClassName = "_wysihtml5-temp-" + new Date().getTime(),
- isEmpty,
- tempElement;
-
- if (composer.commands.support(command)) {
- doc.execCommand(command, false, null);
- return;
- }
-
- if (list) {
- // Unwrap list
- // <ol><li>foo</li><li>bar</li></ol>
- // becomes:
- // foo<br>bar<br>
- composer.selection.executeAndRestoreSimple(function() {
- wysihtml5.dom.resolveList(list);
- });
- } else if (otherList) {
- // Turn an unordered list into an ordered list
- // <ul><li>foo</li><li>bar</li></ul>
- // becomes:
- // <ol><li>foo</li><li>bar</li></ol>
- composer.selection.executeAndRestoreSimple(function() {
- wysihtml5.dom.renameElement(otherList, "ol");
- });
- } else {
- // Create list
- composer.commands.exec("formatBlock", "div", tempClassName);
- tempElement = doc.querySelector("." + tempClassName);
- isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE;
- composer.selection.executeAndRestoreSimple(function() {
- list = wysihtml5.dom.convertToList(tempElement, "ol");
- });
- if (isEmpty) {
- composer.selection.selectNode(list.querySelector("li"));
- }
- }
- },
-
- state: function(composer) {
- var selectedNode = composer.selection.getSelectedNode();
- return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" });
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef;
-
- wysihtml5.commands.insertUnorderedList = {
- exec: function(composer, command) {
- var doc = composer.doc,
- selectedNode = composer.selection.getSelectedNode(),
- list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }),
- otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }),
- tempClassName = "_wysihtml5-temp-" + new Date().getTime(),
- isEmpty,
- tempElement;
-
- if (composer.commands.support(command)) {
- doc.execCommand(command, false, null);
- return;
- }
-
- if (list) {
- // Unwrap list
- // <ul><li>foo</li><li>bar</li></ul>
- // becomes:
- // foo<br>bar<br>
- composer.selection.executeAndRestoreSimple(function() {
- wysihtml5.dom.resolveList(list);
- });
- } else if (otherList) {
- // Turn an ordered list into an unordered list
- // <ol><li>foo</li><li>bar</li></ol>
- // becomes:
- // <ul><li>foo</li><li>bar</li></ul>
- composer.selection.executeAndRestoreSimple(function() {
- wysihtml5.dom.renameElement(otherList, "ul");
- });
- } else {
- // Create list
- composer.commands.exec("formatBlock", "div", tempClassName);
- tempElement = doc.querySelector("." + tempClassName);
- isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE;
- composer.selection.executeAndRestoreSimple(function() {
- list = wysihtml5.dom.convertToList(tempElement, "ul");
- });
- if (isEmpty) {
- composer.selection.selectNode(list.querySelector("li"));
- }
- }
- },
-
- state: function(composer) {
- var selectedNode = composer.selection.getSelectedNode();
- return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" });
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef;
-
- wysihtml5.commands.italic = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatInline.exec(composer, command, "i");
- },
-
- state: function(composer, command, color) {
- // element.ownerDocument.queryCommandState("italic") results:
- // firefox: only <i>
- // chrome: <i>, <em>, <blockquote>, ...
- // ie: <i>, <em>
- // opera: only <i>
- return wysihtml5.commands.formatInline.state(composer, command, "i");
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef,
- CLASS_NAME = "wysiwyg-text-align-center",
- REG_EXP = /wysiwyg-text-align-[a-z]+/g;
-
- wysihtml5.commands.justifyCenter = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- state: function(composer, command) {
- return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef,
- CLASS_NAME = "wysiwyg-text-align-left",
- REG_EXP = /wysiwyg-text-align-[a-z]+/g;
-
- wysihtml5.commands.justifyLeft = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- state: function(composer, command) {
- return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef,
- CLASS_NAME = "wysiwyg-text-align-right",
- REG_EXP = /wysiwyg-text-align-[a-z]+/g;
-
- wysihtml5.commands.justifyRight = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- state: function(composer, command) {
- return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);(function(wysihtml5) {
- var undef;
- wysihtml5.commands.underline = {
- exec: function(composer, command) {
- return wysihtml5.commands.formatInline.exec(composer, command, "u");
- },
-
- state: function(composer, command) {
- return wysihtml5.commands.formatInline.state(composer, command, "u");
- },
-
- value: function() {
- return undef;
- }
- };
-})(wysihtml5);/**
- * Undo Manager for wysihtml5
- * slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface
- */
-(function(wysihtml5) {
- var Z_KEY = 90,
- Y_KEY = 89,
- BACKSPACE_KEY = 8,
- DELETE_KEY = 46,
- MAX_HISTORY_ENTRIES = 40,
- UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>',
- REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>',
- dom = wysihtml5.dom;
-
- function cleanTempElements(doc) {
- var tempElement;
- while (tempElement = doc.querySelector("._wysihtml5-temp")) {
- tempElement.parentNode.removeChild(tempElement);
- }
- }
-
- wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend(
- /** @scope wysihtml5.UndoManager.prototype */ {
- constructor: function(editor) {
- this.editor = editor;
- this.composer = editor.composer;
- this.element = this.composer.element;
- this.history = [this.composer.getValue()];
- this.position = 1;
-
- // Undo manager currently only supported in browsers who have the insertHTML command (not IE)
- if (this.composer.commands.support("insertHTML")) {
- this._observe();
- }
- },
-
- _observe: function() {
- var that = this,
- doc = this.composer.sandbox.getDocument(),
- lastKey;
-
- // Catch CTRL+Z and CTRL+Y
- dom.observe(this.element, "keydown", function(event) {
- if (event.altKey || (!event.ctrlKey && !event.metaKey)) {
- return;
- }
-
- var keyCode = event.keyCode,
- isUndo = keyCode === Z_KEY && !event.shiftKey,
- isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY);
-
- if (isUndo) {
- that.undo();
- event.preventDefault();
- } else if (isRedo) {
- that.redo();
- event.preventDefault();
- }
- });
-
- // Catch delete and backspace
- dom.observe(this.element, "keydown", function(event) {
- var keyCode = event.keyCode;
- if (keyCode === lastKey) {
- return;
- }
-
- lastKey = keyCode;
-
- if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) {
- that.transact();
- }
- });
-
- // Now this is very hacky:
- // These days browsers don't offer a undo/redo event which we could hook into
- // to be notified when the user hits undo/redo in the contextmenu.
- // Therefore we simply insert two elements as soon as the contextmenu gets opened.
- // The last element being inserted will be immediately be removed again by a exexCommand("undo")
- // => When the second element appears in the dom tree then we know the user clicked "redo" in the context menu
- // => When the first element disappears from the dom tree then we know the user clicked "undo" in the context menu
- if (wysihtml5.browser.hasUndoInContextMenu()) {
- var interval, observed, cleanUp = function() {
- cleanTempElements(doc);
- clearInterval(interval);
- };
-
- dom.observe(this.element, "contextmenu", function() {
- cleanUp();
- that.composer.selection.executeAndRestoreSimple(function() {
- if (that.element.lastChild) {
- that.composer.selection.setAfter(that.element.lastChild);
- }
-
- // enable undo button in context menu
- doc.execCommand("insertHTML", false, UNDO_HTML);
- // enable redo button in context menu
- doc.execCommand("insertHTML", false, REDO_HTML);
- doc.execCommand("undo", false, null);
- });
-
- interval = setInterval(function() {
- if (doc.getElementById("_wysihtml5-redo")) {
- cleanUp();
- that.redo();
- } else if (!doc.getElementById("_wysihtml5-undo")) {
- cleanUp();
- that.undo();
- }
- }, 400);
-
- if (!observed) {
- observed = true;
- dom.observe(document, "mousedown", cleanUp);
- dom.observe(doc, ["mousedown", "paste", "cut", "copy"], cleanUp);
- }
- });
- }
-
- this.editor
- .observe("newword:composer", function() {
- that.transact();
- })
-
- .observe("beforecommand:composer", function() {
- that.transact();
- });
- },
-
- transact: function() {
- var previousHtml = this.history[this.position - 1],
- currentHtml = this.composer.getValue();
-
- if (currentHtml == previousHtml) {
- return;
- }
-
- var length = this.history.length = this.position;
- if (length > MAX_HISTORY_ENTRIES) {
- this.history.shift();
- this.position--;
- }
-
- this.position++;
- this.history.push(currentHtml);
- },
-
- undo: function() {
- this.transact();
-
- if (this.position <= 1) {
- return;
- }
-
- this.set(this.history[--this.position - 1]);
- this.editor.fire("undo:composer");
- },
-
- redo: function() {
- if (this.position >= this.history.length) {
- return;
- }
-
- this.set(this.history[++this.position - 1]);
- this.editor.fire("redo:composer");
- },
-
- set: function(html) {
- this.composer.setValue(html);
- this.editor.focus(true);
- }
- });
-})(wysihtml5);
-/**
- * TODO: the following methods still need unit test coverage
- */
-wysihtml5.views.View = Base.extend(
- /** @scope wysihtml5.views.View.prototype */ {
- constructor: function(parent, textareaElement, config) {
- this.parent = parent;
- this.element = textareaElement;
- this.config = config;
-
- this._observeViewChange();
- },
-
- _observeViewChange: function() {
- var that = this;
- this.parent.observe("beforeload", function() {
- that.parent.observe("change_view", function(view) {
- if (view === that.name) {
- that.parent.currentView = that;
- that.show();
- // Using tiny delay here to make sure that the placeholder is set before focusing
- setTimeout(function() { that.focus(); }, 0);
- } else {
- that.hide();
- }
- });
- });
- },
-
- focus: function() {
- if (this.element.ownerDocument.querySelector(":focus") === this.element) {
- return;
- }
-
- try { this.element.focus(); } catch(e) {}
- },
-
- hide: function() {
- this.element.style.display = "none";
- },
-
- show: function() {
- this.element.style.display = "";
- },
-
- disable: function() {
- this.element.setAttribute("disabled", "disabled");
- },
-
- enable: function() {
- this.element.removeAttribute("disabled");
- }
-});(function(wysihtml5) {
- var dom = wysihtml5.dom,
- browser = wysihtml5.browser;
-
- wysihtml5.views.Composer = wysihtml5.views.View.extend(
- /** @scope wysihtml5.views.Composer.prototype */ {
- name: "composer",
-
- // Needed for firefox in order to display a proper caret in an empty contentEditable
- CARET_HACK: "<br>",
-
- constructor: function(parent, textareaElement, config) {
- this.base(parent, textareaElement, config);
- this.textarea = this.parent.textarea;
- this._initSandbox();
- },
-
- clear: function() {
- this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK;
- },
-
- getValue: function(parse) {
- var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element);
-
- if (parse) {
- value = this.parent.parse(value);
- }
-
- // Replace all "zero width no breaking space" chars
- // which are used as hacks to enable some functionalities
- // Also remove all CARET hacks that somehow got left
- value = wysihtml5.lang.string(value).replace(wysihtml5.INVISIBLE_SPACE).by("");
-
- return value;
- },
-
- setValue: function(html, parse) {
- if (parse) {
- html = this.parent.parse(html);
- }
- this.element.innerHTML = html;
- },
-
- show: function() {
- this.iframe.style.display = this._displayStyle || "";
-
- // Firefox needs this, otherwise contentEditable becomes uneditable
- this.disable();
- this.enable();
- },
-
- hide: function() {
- this._displayStyle = dom.getStyle("display").from(this.iframe);
- if (this._displayStyle === "none") {
- this._displayStyle = null;
- }
- this.iframe.style.display = "none";
- },
-
- disable: function() {
- this.element.removeAttribute("contentEditable");
- this.base();
- },
-
- enable: function() {
- this.element.setAttribute("contentEditable", "true");
- this.base();
- },
-
- focus: function(setToEnd) {
- // IE 8 fires the focus event after .focus()
- // This is needed by our simulate_placeholder.js to work
- // therefore we clear it ourselves this time
- if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) {
- this.clear();
- }
-
- this.base();
-
- var lastChild = this.element.lastChild;
- if (setToEnd && lastChild) {
- if (lastChild.nodeName === "BR") {
- this.selection.setBefore(this.element.lastChild);
- } else {
- this.selection.setAfter(this.element.lastChild);
- }
- }
- },
-
- getTextContent: function() {
- return dom.getTextContent(this.element);
- },
-
- hasPlaceholderSet: function() {
- return this.getTextContent() == this.textarea.element.getAttribute("placeholder");
- },
-
- isEmpty: function() {
- var innerHTML = this.element.innerHTML,
- elementsWithVisualValue = "blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea";
- return innerHTML === "" ||
- innerHTML === this.CARET_HACK ||
- this.hasPlaceholderSet() ||
- (this.getTextContent() === "" && !this.element.querySelector(elementsWithVisualValue));
- },
-
- _initSandbox: function() {
- var that = this;
-
- this.sandbox = new dom.Sandbox(function() {
- that._create();
- }, {
- stylesheets: this.config.stylesheets
- });
- this.iframe = this.sandbox.getIframe();
-
- // Create hidden field which tells the server after submit, that the user used an wysiwyg editor
- var hiddenField = document.createElement("input");
- hiddenField.type = "hidden";
- hiddenField.name = "_wysihtml5_mode";
- hiddenField.value = 1;
-
- // Store reference to current wysihtml5 instance on the textarea element
- var textareaElement = this.textarea.element;
- dom.insert(this.iframe).after(textareaElement);
- dom.insert(hiddenField).after(textareaElement);
- },
-
- _create: function() {
- var that = this;
-
- this.doc = this.sandbox.getDocument();
- this.element = this.doc.body;
- this.textarea = this.parent.textarea;
- this.element.innerHTML = this.textarea.getValue(true);
- this.enable();
-
- // Make sure our selection handler is ready
- this.selection = new wysihtml5.Selection(this.parent);
-
- // Make sure commands dispatcher is ready
- this.commands = new wysihtml5.Commands(this.parent);
-
- dom.copyAttributes([
- "className", "spellcheck", "title", "lang", "dir", "accessKey"
- ]).from(this.textarea.element).to(this.element);
-
- dom.addClass(this.element, this.config.composerClassName);
-
- // Make the editor look like the original textarea, by syncing styles
- if (this.config.style) {
- this.style();
- }
-
- this.observe();
-
- var name = this.config.name;
- if (name) {
- dom.addClass(this.element, name);
- dom.addClass(this.iframe, name);
- }
-
- // Simulate html5 placeholder attribute on contentEditable element
- var placeholderText = typeof(this.config.placeholder) === "string"
- ? this.config.placeholder
- : this.textarea.element.getAttribute("placeholder");
- if (placeholderText) {
- dom.simulatePlaceholder(this.parent, this, placeholderText);
- }
-
- // Make sure that the browser avoids using inline styles whenever possible
- this.commands.exec("styleWithCSS", false);
-
- this._initAutoLinking();
- this._initObjectResizing();
- this._initUndoManager();
-
- // Simulate html5 autofocus on contentEditable element
- if (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) {
- setTimeout(function() { that.focus(); }, 100);
- }
-
- wysihtml5.quirks.insertLineBreakOnReturn(this);
-
- // IE sometimes leaves a single paragraph, which can't be removed by the user
- if (!browser.clearsContentEditableCorrectly()) {
- wysihtml5.quirks.ensureProperClearing(this);
- }
-
- if (!browser.clearsListsInContentEditableCorrectly()) {
- wysihtml5.quirks.ensureProperClearingOfLists(this);
- }
-
- // Set up a sync that makes sure that textarea and editor have the same content
- if (this.initSync && this.config.sync) {
- this.initSync();
- }
-
- // Okay hide the textarea, we are ready to go
- this.textarea.hide();
-
- // Fire global (before-)load event
- this.parent.fire("beforeload").fire("load");
- },
-
- _initAutoLinking: function() {
- var that = this,
- supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(),
- supportsAutoLinking = browser.doesAutoLinkingInContentEditable();
- if (supportsDisablingOfAutoLinking) {
- this.commands.exec("autoUrlDetect", false);
- }
-
- if (!this.config.autoLink) {
- return;
- }
-
- // Only do the auto linking by ourselves when the browser doesn't support auto linking
- // OR when he supports auto linking but we were able to turn it off (IE9+)
- if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) {
- this.parent.observe("newword:composer", function() {
- that.selection.executeAndRestore(function(startContainer, endContainer) {
- dom.autoLink(endContainer.parentNode);
- });
- });
- }
-
- // Assuming we have the following:
- // <a href="http://www.google.de">http://www.google.de</a>
- // If a user now changes the url in the innerHTML we want to make sure that
- // it's synchronized with the href attribute (as long as the innerHTML is still a url)
- var // Use a live NodeList to check whether there are any links in the document
- links = this.sandbox.getDocument().getElementsByTagName("a"),
- // The autoLink helper method reveals a reg exp to detect correct urls
- urlRegExp = dom.autoLink.URL_REG_EXP,
- getTextContent = function(element) {
- var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim();
- if (textContent.substr(0, 4) === "www.") {
- textContent = "http://" + textContent;
- }
- return textContent;
- };
-
- dom.observe(this.element, "keydown", function(event) {
- if (!links.length) {
- return;
- }
-
- var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument),
- link = dom.getParentElement(selectedNode, { nodeName: "A" }, 4),
- textContent;
-
- if (!link) {
- return;
- }
-
- textContent = getTextContent(link);
- // keydown is fired before the actual content is changed
- // therefore we set a timeout to change the href
- setTimeout(function() {
- var newTextContent = getTextContent(link);
- if (newTextContent === textContent) {
- return;
- }
-
- // Only set href when new href looks like a valid url
- if (newTextContent.match(urlRegExp)) {
- link.setAttribute("href", newTextContent);
- }
- }, 0);
- });
- },
-
- _initObjectResizing: function() {
- var properties = ["width", "height"],
- propertiesLength = properties.length,
- element = this.element;
-
- this.commands.exec("enableObjectResizing", this.config.allowObjectResizing);
-
- if (this.config.allowObjectResizing) {
- // IE sets inline styles after resizing objects
- // The following lines make sure that the width/height css properties
- // are copied over to the width/height attributes
- if (browser.supportsEvent("resizeend")) {
- dom.observe(element, "resizeend", function(event) {
- var target = event.target || event.srcElement,
- style = target.style,
- i = 0,
- property;
- for(; i<propertiesLength; i++) {
- property = properties[i];
- if (style[property]) {
- target.setAttribute(property, parseInt(style[property], 10));
- style[property] = "";
- }
- }
- // After resizing IE sometimes forgets to remove the old resize handles
- wysihtml5.quirks.redraw(element);
- });
- }
- } else {
- if (browser.supportsEvent("resizestart")) {
- dom.observe(element, "resizestart", function(event) { event.preventDefault(); });
- }
- }
- },
-
- _initUndoManager: function() {
- new wysihtml5.UndoManager(this.parent);
- }
- });
-})(wysihtml5);(function(wysihtml5) {
- var dom = wysihtml5.dom,
- doc = document,
- win = window,
- HOST_TEMPLATE = doc.createElement("div"),
- /**
- * Styles to copy from textarea to the composer element
- */
- TEXT_FORMATTING = [
- "background-color",
- "color", "cursor",
- "font-family", "font-size", "font-style", "font-variant", "font-weight",
- "line-height", "letter-spacing",
- "text-align", "text-decoration", "text-indent", "text-rendering",
- "word-break", "word-wrap", "word-spacing"
- ],
- /**
- * Styles to copy from textarea to the iframe
- */
- BOX_FORMATTING = [
- "background-color",
- "border-collapse",
- "border-bottom-color", "border-bottom-style", "border-bottom-width",
- "border-left-color", "border-left-style", "border-left-width",
- "border-right-color", "border-right-style", "border-right-width",
- "border-top-color", "border-top-style", "border-top-width",
- "clear", "display", "float",
- "margin-bottom", "margin-left", "margin-right", "margin-top",
- "outline-color", "outline-offset", "outline-width", "outline-style",
- "padding-left", "padding-right", "padding-top", "padding-bottom",
- "position", "top", "left", "right", "bottom", "z-index",
- "vertical-align", "text-align",
- "-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing",
- "-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow",
- "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius",
- "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius",
- "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius",
- "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius",
- "width", "height"
- ],
- /**
- * Styles to sync while the window gets resized
- */
- RESIZE_STYLE = [
- "width", "height",
- "top", "left", "right", "bottom"
- ],
- ADDITIONAL_CSS_RULES = [
- "html { height: 100%; }",
- "body { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }",
- "._wysihtml5-temp { display: none; }",
- wysihtml5.browser.isGecko ?
- "body.placeholder { color: graytext !important; }" :
- "body.placeholder { color: #a9a9a9 !important; }",
- "body[disabled] { background-color: #eee !important; color: #999 !important; cursor: default !important; }",
- // Ensure that user see's broken images and can delete them
- "img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }"
- ];
-
- /**
- * With "setActive" IE offers a smart way of focusing elements without scrolling them into view:
- * http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx
- *
- * Other browsers need a more hacky way: (pssst don't tell my mama)
- * In order to prevent the element being scrolled into view when focusing it, we simply
- * move it out of the scrollable area, focus it, and reset it's position
- */
- var focusWithoutScrolling = function(element) {
- if (element.setActive) {
- // Following line could cause a js error when the textarea is invisible
- // See https://github.com/xing/wysihtml5/issues/9
- try { element.setActive(); } catch(e) {}
- } else {
- var elementStyle = element.style,
- originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop,
- originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft,
- originalStyles = {
- position: elementStyle.position,
- top: elementStyle.top,
- left: elementStyle.left,
- WebkitUserSelect: elementStyle.WebkitUserSelect
- };
-
- dom.setStyles({
- position: "absolute",
- top: "-99999px",
- left: "-99999px",
- // Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother
- WebkitUserSelect: "none"
- }).on(element);
-
- element.focus();
-
- dom.setStyles(originalStyles).on(element);
-
- if (win.scrollTo) {
- // Some browser extensions unset this method to prevent annoyances
- // "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100
- // Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1
- win.scrollTo(originalScrollLeft, originalScrollTop);
- }
- }
- };
-
-
- wysihtml5.views.Composer.prototype.style = function() {
- var that = this,
- originalActiveElement = doc.querySelector(":focus"),
- textareaElement = this.textarea.element,
- hasPlaceholder = textareaElement.hasAttribute("placeholder"),
- originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder");
- this.focusStylesHost = this.focusStylesHost || HOST_TEMPLATE.cloneNode(false);
- this.blurStylesHost = this.blurStylesHost || HOST_TEMPLATE.cloneNode(false);
-
- // Remove placeholder before copying (as the placeholder has an affect on the computed style)
- if (hasPlaceholder) {
- textareaElement.removeAttribute("placeholder");
- }
-
- if (textareaElement === originalActiveElement) {
- textareaElement.blur();
- }
-
- // --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) ---------
- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.iframe).andTo(this.blurStylesHost);
-
- // --------- editor styles ---------
- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost);
-
- // --------- apply standard rules ---------
- dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument);
-
- // --------- :focus styles ---------
- focusWithoutScrolling(textareaElement);
- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost);
- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost);
-
- // Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus
- // this is needed for when the change_view event is fired where the iframe is hidden and then
- // the blur event fires and re-displays it
- var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]);
-
- // --------- restore focus ---------
- if (originalActiveElement) {
- originalActiveElement.focus();
- } else {
- textareaElement.blur();
- }
-
- // --------- restore placeholder ---------
- if (hasPlaceholder) {
- textareaElement.setAttribute("placeholder", originalPlaceholder);
- }
-
- // When copying styles, we only get the computed style which is never returned in percent unit
- // Therefore we've to recalculate style onresize
- if (!wysihtml5.browser.hasCurrentStyleProperty()) {
- var winObserver = dom.observe(win, "resize", function() {
- // Remove event listener if composer doesn't exist anymore
- if (!dom.contains(document.documentElement, that.iframe)) {
- winObserver.stop();
- return;
- }
- var originalTextareaDisplayStyle = dom.getStyle("display").from(textareaElement),
- originalComposerDisplayStyle = dom.getStyle("display").from(that.iframe);
- textareaElement.style.display = "";
- that.iframe.style.display = "none";
- dom.copyStyles(RESIZE_STYLE)
- .from(textareaElement)
- .to(that.iframe)
- .andTo(that.focusStylesHost)
- .andTo(that.blurStylesHost);
- that.iframe.style.display = originalComposerDisplayStyle;
- textareaElement.style.display = originalTextareaDisplayStyle;
- });
- }
-
- // --------- Sync focus/blur styles ---------
- this.parent.observe("focus:composer", function() {
- dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.iframe);
- dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element);
- });
-
- this.parent.observe("blur:composer", function() {
- dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.iframe);
- dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element);
- });
-
- return this;
- };
-})(wysihtml5);/**
- * Taking care of events
- * - Simulating 'change' event on contentEditable element
- * - Handling drag & drop logic
- * - Catch paste events
- * - Dispatch proprietary newword:composer event
- * - Keyboard shortcuts
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom,
- browser = wysihtml5.browser,
- /**
- * Map keyCodes to query commands
- */
- shortcuts = {
- "66": "bold", // B
- "73": "italic", // I
- "85": "underline" // U
- };
-
- wysihtml5.views.Composer.prototype.observe = function() {
- var that = this,
- state = this.getValue(),
- iframe = this.sandbox.getIframe(),
- element = this.element,
- focusBlurElement = browser.supportsEventsInIframeCorrectly() ? element : this.sandbox.getWindow(),
- // Firefox < 3.5 doesn't support the drop event, instead it supports a so called "dragdrop" event which behaves almost the same
- pasteEvents = browser.supportsEvent("drop") ? ["drop", "paste"] : ["dragdrop", "paste"];
-
- // --------- destroy:composer event ---------
- dom.observe(iframe, "DOMNodeRemoved", function() {
- clearInterval(domNodeRemovedInterval);
- that.parent.fire("destroy:composer");
- });
-
- // DOMNodeRemoved event is not supported in IE 8
- var domNodeRemovedInterval = setInterval(function() {
- if (!dom.contains(document.documentElement, iframe)) {
- clearInterval(domNodeRemovedInterval);
- that.parent.fire("destroy:composer");
- }
- }, 250);
-
-
- // --------- Focus & blur logic ---------
- dom.observe(focusBlurElement, "focus", function() {
- that.parent.fire("focus").fire("focus:composer");
-
- // Delay storing of state until all focus handler are fired
- // especially the one which resets the placeholder
- setTimeout(function() { state = that.getValue(); }, 0);
- });
-
- dom.observe(focusBlurElement, "blur", function() {
- if (state !== that.getValue()) {
- that.parent.fire("change").fire("change:composer");
- }
- that.parent.fire("blur").fire("blur:composer");
- });
-
- if (wysihtml5.browser.isIos()) {
- // When on iPad/iPhone/IPod after clicking outside of editor, the editor loses focus
- // but the UI still acts as if the editor has focus (blinking caret and onscreen keyboard visible)
- // We prevent that by focusing a temporary input element which immediately loses focus
- dom.observe(element, "blur", function() {
- var input = element.ownerDocument.createElement("input"),
- originalScrollTop = document.documentElement.scrollTop || document.body.scrollTop,
- originalScrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
- try {
- that.selection.insertNode(input);
- } catch(e) {
- element.appendChild(input);
- }
- input.focus();
- input.parentNode.removeChild(input);
-
- window.scrollTo(originalScrollLeft, originalScrollTop);
- });
- }
-
- // --------- Drag & Drop logic ---------
- dom.observe(element, "dragenter", function() {
- that.parent.fire("unset_placeholder");
- });
-
- if (browser.firesOnDropOnlyWhenOnDragOverIsCancelled()) {
- dom.observe(element, ["dragover", "dragenter"], function(event) {
- event.preventDefault();
- });
- }
-
- dom.observe(element, pasteEvents, function(event) {
- var dataTransfer = event.dataTransfer,
- data;
-
-
- console.log('PASTED', event);
- if (dataTransfer && browser.supportsDataTransfer()) {
- data = dataTransfer.getData("text/html") || dataTransfer.getData("text/plain");
- }
- if (data) {
- element.focus();
- that.commands.exec("insertHTML", data);
- that.parent.fire("paste").fire("paste:composer");
- event.stopPropagation();
- event.preventDefault();
- } else {
- setTimeout(function() {
- that.parent.fire("paste").fire("paste:composer");
- }, 0);
- }
- });
-
- // --------- neword event ---------
- dom.observe(element, "keyup", function(event) {
- var keyCode = event.keyCode;
- if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) {
- that.parent.fire("newword:composer");
- }
- });
-
- this.parent.observe("paste:composer", function() {
- setTimeout(function() { that.parent.fire("newword:composer"); }, 0);
- });
-
- // --------- Make sure that images are selected when clicking on them ---------
- if (!browser.canSelectImagesInContentEditable()) {
- dom.observe(element, "mousedown", function(event) {
- var target = event.target;
- if (target.nodeName === "IMG") {
- that.selection.selectNode(target);
- event.preventDefault();
- }
- });
- }
-
- // --------- Shortcut logic ---------
- dom.observe(element, "keydown", function(event) {
- var keyCode = event.keyCode,
- command = shortcuts[keyCode];
- if ((event.ctrlKey || event.metaKey) && !event.altKey && command) {
- that.commands.exec(command);
- event.preventDefault();
- }
- });
-
- // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor ---------
- dom.observe(element, "keydown", function(event) {
- var target = that.selection.getSelectedNode(true),
- keyCode = event.keyCode,
- parent;
- if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete
- parent = target.parentNode;
- // delete the <img>
- parent.removeChild(target);
- // and it's parent <a> too if it hasn't got any other child nodes
- if (parent.nodeName === "A" && !parent.firstChild) {
- parent.parentNode.removeChild(parent);
- }
-
- setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0);
- event.preventDefault();
- }
- });
-
- // --------- Show url in tooltip when hovering links or images ---------
- var titlePrefixes = {
- IMG: "Image: ",
- A: "Link: "
- };
-
- dom.observe(element, "mouseover", function(event) {
- var target = event.target,
- nodeName = target.nodeName,
- title;
- if (nodeName !== "A" && nodeName !== "IMG") {
- return;
- }
- var hasTitle = target.hasAttribute("title");
- if(!hasTitle){
- title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src"));
- target.setAttribute("title", title);
- }
- });
- };
-})(wysihtml5);/**
- * Class that takes care that the value of the composer and the textarea is always in sync
- */
-(function(wysihtml5) {
- var INTERVAL = 400;
-
- wysihtml5.views.Synchronizer = Base.extend(
- /** @scope wysihtml5.views.Synchronizer.prototype */ {
-
- constructor: function(editor, textarea, composer) {
- this.editor = editor;
- this.textarea = textarea;
- this.composer = composer;
-
- this._observe();
- },
-
- /**
- * Sync html from composer to textarea
- * Takes care of placeholders
- * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea
- */
- fromComposerToTextarea: function(shouldParseHtml) {
- this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue()).trim(), shouldParseHtml);
- },
-
- /**
- * Sync value of textarea to composer
- * Takes care of placeholders
- * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer
- */
- fromTextareaToComposer: function(shouldParseHtml) {
- var textareaValue = this.textarea.getValue();
- if (textareaValue) {
- this.composer.setValue(textareaValue, shouldParseHtml);
- } else {
- this.composer.clear();
- this.editor.fire("set_placeholder");
- }
- },
-
- /**
- * Invoke syncing based on view state
- * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea
- */
- sync: function(shouldParseHtml) {
- if (this.editor.currentView.name === "textarea") {
- this.fromTextareaToComposer(shouldParseHtml);
- } else {
- this.fromComposerToTextarea(shouldParseHtml);
- }
- },
-
- /**
- * Initializes interval-based syncing
- * also makes sure that on-submit the composer's content is synced with the textarea
- * immediately when the form gets submitted
- */
- _observe: function() {
- var interval,
- that = this,
- form = this.textarea.element.form,
- startInterval = function() {
- interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL);
- },
- stopInterval = function() {
- clearInterval(interval);
- interval = null;
- };
-
- startInterval();
-
- if (form) {
- // If the textarea is in a form make sure that after onreset and onsubmit the composer
- // has the correct state
- wysihtml5.dom.observe(form, "submit", function() {
- that.sync(true);
- });
- wysihtml5.dom.observe(form, "reset", function() {
- setTimeout(function() { that.fromTextareaToComposer(); }, 0);
- });
- }
-
- this.editor.observe("change_view", function(view) {
- if (view === "composer" && !interval) {
- that.fromTextareaToComposer(true);
- startInterval();
- } else if (view === "textarea") {
- that.fromComposerToTextarea(true);
- stopInterval();
- }
- });
-
- this.editor.observe("destroy:composer", stopInterval);
- }
- });
-})(wysihtml5);
-wysihtml5.views.Textarea = wysihtml5.views.View.extend(
- /** @scope wysihtml5.views.Textarea.prototype */ {
- name: "textarea",
-
- constructor: function(parent, textareaElement, config) {
- this.base(parent, textareaElement, config);
-
- this._observe();
- },
-
- clear: function() {
- this.element.value = "";
- },
-
- getValue: function(parse) {
- var value = this.isEmpty() ? "" : this.element.value;
- if (parse) {
- value = this.parent.parse(value);
- }
- return value;
- },
-
- setValue: function(html, parse) {
- if (parse) {
- html = this.parent.parse(html);
- }
- this.element.value = html;
- },
-
- hasPlaceholderSet: function() {
- var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element),
- placeholderText = this.element.getAttribute("placeholder") || null,
- value = this.element.value,
- isEmpty = !value;
- return (supportsPlaceholder && isEmpty) || (value === placeholderText);
- },
-
- isEmpty: function() {
- return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet();
- },
-
- _observe: function() {
- var element = this.element,
- parent = this.parent,
- eventMapping = {
- focusin: "focus",
- focusout: "blur"
- },
- /**
- * Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events
- * This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai
- */
- events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"];
-
- parent.observe("beforeload", function() {
- wysihtml5.dom.observe(element, events, function(event) {
- var eventName = eventMapping[event.type] || event.type;
- parent.fire(eventName).fire(eventName + ":textarea");
- });
-
- wysihtml5.dom.observe(element, ["paste", "drop"], function() {
- setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0);
- });
- });
- }
-});/**
- * Toolbar Dialog
- *
- * @param {Element} link The toolbar link which causes the dialog to show up
- * @param {Element} container The dialog container
- *
- * @example
- * <!-- Toolbar link -->
- * <a data-wysihtml5-command="insertImage">insert an image</a>
- *
- * <!-- Dialog -->
- * <div data-wysihtml5-dialog="insertImage" style="display: none;">
- * <label>
- * URL: <input data-wysihtml5-dialog-field="src" value="http://">
- * </label>
- * <label>
- * Alternative text: <input data-wysihtml5-dialog-field="alt" value="">
- * </label>
- * </div>
- *
- * <script>
- * var dialog = new wysihtml5.toolbar.Dialog(
- * document.querySelector("[data-wysihtml5-command='insertImage']"),
- * document.querySelector("[data-wysihtml5-dialog='insertImage']")
- * );
- * dialog.observe("save", function(attributes) {
- * // do something
- * });
- * </script>
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom,
- CLASS_NAME_OPENED = "wysihtml5-command-dialog-opened",
- SELECTOR_FORM_ELEMENTS = "input, select, textarea",
- SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]",
- ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field";
-
-
- wysihtml5.toolbar.Dialog = wysihtml5.lang.Dispatcher.extend(
- /** @scope wysihtml5.toolbar.Dialog.prototype */ {
- constructor: function(link, container) {
- this.link = link;
- this.container = container;
- },
-
- _observe: function() {
- if (this._observed) {
- return;
- }
-
- var that = this,
- callbackWrapper = function(event) {
- var attributes = that._serialize();
- if (attributes == that.elementToChange) {
- that.fire("edit", attributes);
- } else {
- that.fire("save", attributes);
- }
- that.hide();
- event.preventDefault();
- event.stopPropagation();
- };
-
- dom.observe(that.link, "click", function(event) {
- if (dom.hasClass(that.link, CLASS_NAME_OPENED)) {
- setTimeout(function() { that.hide(); }, 0);
- }
- });
-
- dom.observe(this.container, "keydown", function(event) {
- var keyCode = event.keyCode;
- if (keyCode === wysihtml5.ENTER_KEY) {
- callbackWrapper(event);
- }
- if (keyCode === wysihtml5.ESCAPE_KEY) {
- that.hide();
- }
- });
-
- dom.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", callbackWrapper);
-
- dom.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function(event) {
- that.fire("cancel");
- that.hide();
- event.preventDefault();
- event.stopPropagation();
- });
-
- var formElements = this.container.querySelectorAll(SELECTOR_FORM_ELEMENTS),
- i = 0,
- length = formElements.length,
- _clearInterval = function() { clearInterval(that.interval); };
- for (; i<length; i++) {
- dom.observe(formElements[i], "change", _clearInterval);
- }
-
- this._observed = true;
- },
-
- /**
- * Grabs all fields in the dialog and puts them in key=>value style in an object which
- * then gets returned
- */
- _serialize: function() {
- var data = this.elementToChange || {},
- fields = this.container.querySelectorAll(SELECTOR_FIELDS),
- length = fields.length,
- i = 0;
- for (; i<length; i++) {
- data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value;
- }
- return data;
- },
-
- /**
- * Takes the attributes of the "elementToChange"
- * and inserts them in their corresponding dialog input fields
- *
- * Assume the "elementToChange" looks like this:
- * <a href="http://www.google.com" target="_blank">foo</a>
- *
- * and we have the following dialog:
- * <input type="text" data-wysihtml5-dialog-field="href" value="">
- * <input type="text" data-wysihtml5-dialog-field="target" value="">
- *
- * after calling _interpolate() the dialog will look like this
- * <input type="text" data-wysihtml5-dialog-field="href" value="http://www.google.com">
- * <input type="text" data-wysihtml5-dialog-field="target" value="_blank">
- *
- * Basically it adopted the attribute values into the corresponding input fields
- *
- */
- _interpolate: function(avoidHiddenFields) {
- var field,
- fieldName,
- newValue,
- focusedElement = document.querySelector(":focus"),
- fields = this.container.querySelectorAll(SELECTOR_FIELDS),
- length = fields.length,
- i = 0;
- for (; i<length; i++) {
- field = fields[i];
-
- // Never change elements where the user is currently typing in
- if (field === focusedElement) {
- continue;
- }
-
- // Don't update hidden fields
- // See https://github.com/xing/wysihtml5/pull/14
- if (avoidHiddenFields && field.type === "hidden") {
- continue;
- }
-
- fieldName = field.getAttribute(ATTRIBUTE_FIELDS);
- newValue = this.elementToChange ? (this.elementToChange[fieldName] || "") : field.defaultValue;
- field.value = newValue;
- }
- },
-
- /**
- * Show the dialog element
- */
- show: function(elementToChange) {
- var that = this,
- firstField = this.container.querySelector(SELECTOR_FORM_ELEMENTS);
- this.elementToChange = elementToChange;
- this._observe();
- this._interpolate();
- if (elementToChange) {
- this.interval = setInterval(function() { that._interpolate(true); }, 500);
- }
- dom.addClass(this.link, CLASS_NAME_OPENED);
- this.container.style.display = "";
- this.fire("show");
- if (firstField && !elementToChange) {
- try {
- firstField.focus();
- } catch(e) {}
- }
- },
-
- /**
- * Hide the dialog element
- */
- hide: function() {
- clearInterval(this.interval);
- this.elementToChange = null;
- dom.removeClass(this.link, CLASS_NAME_OPENED);
- this.container.style.display = "none";
- this.fire("hide");
- }
- });
-})(wysihtml5);
-/**
- * Converts speech-to-text and inserts this into the editor
- * As of now (2011/03/25) this only is supported in Chrome >= 11
- *
- * Note that it sends the recorded audio to the google speech recognition api:
- * http://stackoverflow.com/questions/4361826/does-chrome-have-buil-in-speech-recognition-for-input-type-text-x-webkit-speec
- *
- * Current HTML5 draft can be found here
- * http://lists.w3.org/Archives/Public/public-xg-htmlspeech/2011Feb/att-0020/api-draft.html
- *
- * "Accessing Google Speech API Chrome 11"
- * http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/
- */
-(function(wysihtml5) {
- var dom = wysihtml5.dom;
-
- var linkStyles = {
- position: "relative"
- };
-
- var wrapperStyles = {
- left: 0,
- margin: 0,
- opacity: 0,
- overflow: "hidden",
- padding: 0,
- position: "absolute",
- top: 0,
- zIndex: 1
- };
-
- var inputStyles = {
- cursor: "inherit",
- fontSize: "50px",
- height: "50px",
- marginTop: "-25px",
- outline: 0,
- padding: 0,
- position: "absolute",
- right: "-4px",
- top: "50%"
- };
-
- var inputAttributes = {
- "x-webkit-speech": "",
- "speech": ""
- };
-
- wysihtml5.toolbar.Speech = function(parent, link) {
- var input = document.createElement("input");
- if (!wysihtml5.browser.supportsSpeechApiOn(input)) {
- link.style.display = "none";
- return;
- }
-
- var wrapper = document.createElement("div");
-
- wysihtml5.lang.object(wrapperStyles).merge({
- width: link.offsetWidth + "px",
- height: link.offsetHeight + "px"
- });
-
- dom.insert(input).into(wrapper);
- dom.insert(wrapper).into(link);
-
- dom.setStyles(inputStyles).on(input);
- dom.setAttributes(inputAttributes).on(input)
-
- dom.setStyles(wrapperStyles).on(wrapper);
- dom.setStyles(linkStyles).on(link);
-
- var eventName = "onwebkitspeechchange" in input ? "webkitspeechchange" : "speechchange";
- dom.observe(input, eventName, function() {
- parent.execCommand("insertText", input.value);
- input.value = "";
- });
-
- dom.observe(input, "click", function(event) {
- if (dom.hasClass(link, "wysihtml5-command-disabled")) {
- event.preventDefault();
- }
-
- event.stopPropagation();
- });
- };
-})(wysihtml5);/**
- * Toolbar
- *
- * @param {Object} parent Reference to instance of Editor instance
- * @param {Element} container Reference to the toolbar container element
- *
- * @example
- * <div id="toolbar">
- * <a data-wysihtml5-command="createLink">insert link</a>
- * <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a>
- * </div>
- *
- * <script>
- * var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar"));
- * </script>
- */
-(function(wysihtml5) {
- var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled",
- CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled",
- CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active",
- CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active",
- dom = wysihtml5.dom;
-
- wysihtml5.toolbar.Toolbar = Base.extend(
- /** @scope wysihtml5.toolbar.Toolbar.prototype */ {
- constructor: function(editor, container) {
- this.editor = editor;
- this.container = typeof(container) === "string" ? document.getElementById(container) : container;
- this.composer = editor.composer;
-
- this._getLinks("command");
- this._getLinks("action");
-
- this._observe();
- this.show();
-
- var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"),
- length = speechInputLinks.length,
- i = 0;
- for (; i<length; i++) {
- new wysihtml5.toolbar.Speech(this, speechInputLinks[i]);
- }
- },
-
- _getLinks: function(type) {
- var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(),
- length = links.length,
- i = 0,
- mapping = this[type + "Mapping"] = {},
- link,
- group,
- name,
- value,
- dialog;
- for (; i<length; i++) {
- link = links[i];
- name = link.getAttribute("data-wysihtml5-" + type);
- value = link.getAttribute("data-wysihtml5-" + type + "-value");
- group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']");
- dialog = this._getDialog(link, name);
-
- mapping[name + ":" + value] = {
- link: link,
- group: group,
- name: name,
- value: value,
- dialog: dialog,
- state: false
- };
- }
- },
-
- _getDialog: function(link, command) {
- var that = this,
- dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"),
- dialog,
- caretBookmark;
-
- if (dialogElement) {
- dialog = new wysihtml5.toolbar.Dialog(link, dialogElement);
-
- dialog.observe("show", function() {
- caretBookmark = that.composer.selection.getBookmark();
-
- that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
- });
-
- dialog.observe("save", function(attributes) {
- if (caretBookmark) {
- that.composer.selection.setBookmark(caretBookmark);
- }
- that._execCommand(command, attributes);
-
- that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
- });
-
- dialog.observe("cancel", function() {
- that.editor.focus(false);
- that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
- });
- }
- return dialog;
- },
-
- /**
- * @example
- * var toolbar = new wysihtml5.Toolbar();
- * // Insert a <blockquote> element or wrap current selection in <blockquote>
- * toolbar.execCommand("formatBlock", "blockquote");
- */
- execCommand: function(command, commandValue) {
- if (this.commandsDisabled) {
- return;
- }
-
- var commandObj = this.commandMapping[command + ":" + commandValue];
-
- // Show dialog when available
- if (commandObj && commandObj.dialog && !commandObj.state) {
- commandObj.dialog.show();
- } else {
- this._execCommand(command, commandValue);
- }
- },
-
- _execCommand: function(command, commandValue) {
- // Make sure that composer is focussed (false => don't move caret to the end)
- this.editor.focus(false);
-
- this.composer.commands.exec(command, commandValue);
- this._updateLinkStates();
- },
-
- execAction: function(action) {
- var editor = this.editor;
- switch(action) {
- case "change_view":
- if (editor.currentView === editor.textarea) {
- editor.fire("change_view", "composer");
- } else {
- editor.fire("change_view", "textarea");
- }
- break;
- }
- },
-
- _observe: function() {
- var that = this,
- editor = this.editor,
- container = this.container,
- links = this.commandLinks.concat(this.actionLinks),
- length = links.length,
- i = 0;
-
- for (; i<length; i++) {
- // 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied
- // (you know, a:link { ... } doesn't match anchors with missing href attribute)
- dom.setAttributes({
- href: "javascript:;",
- unselectable: "on"
- }).on(links[i]);
- }
-
- // Needed for opera
- dom.delegate(container, "[data-wysihtml5-command]", "mousedown", function(event) { event.preventDefault(); });
-
- dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) {
- var link = this,
- command = link.getAttribute("data-wysihtml5-command"),
- commandValue = link.getAttribute("data-wysihtml5-command-value");
- that.execCommand(command, commandValue);
- event.preventDefault();
- });
-
- dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) {
- var action = this.getAttribute("data-wysihtml5-action");
- that.execAction(action);
- event.preventDefault();
- });
-
- editor.observe("focus:composer", function() {
- that.bookmark = null;
- clearInterval(that.interval);
- that.interval = setInterval(function() { that._updateLinkStates(); }, 500);
- });
-
- editor.observe("blur:composer", function() {
- clearInterval(that.interval);
- });
-
- editor.observe("destroy:composer", function() {
- clearInterval(that.interval);
- });
-
- editor.observe("change_view", function(currentView) {
- // Set timeout needed in order to let the blur event fire first
- setTimeout(function() {
- that.commandsDisabled = (currentView !== "composer");
- that._updateLinkStates();
- if (that.commandsDisabled) {
- dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED);
- } else {
- dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED);
- }
- }, 0);
- });
- },
-
- _updateLinkStates: function() {
- var element = this.composer.element,
- commandMapping = this.commandMapping,
- actionMapping = this.actionMapping,
- i,
- state,
- action,
- command;
- // every millisecond counts... this is executed quite often
- for (i in commandMapping) {
- command = commandMapping[i];
- if (this.commandsDisabled) {
- state = false;
- dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
- if (command.group) {
- dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
- }
- if (command.dialog) {
- command.dialog.hide();
- }
- } else {
- state = this.composer.commands.state(command.name, command.value);
- if (wysihtml5.lang.object(state).isArray()) {
- // Grab first and only object/element in state array, otherwise convert state into boolean
- // to avoid showing a dialog for multiple selected elements which may have different attributes
- // eg. when two links with different href are selected, the state will be an array consisting of both link elements
- // but the dialog interface can only update one
- state = state.length === 1 ? state[0] : true;
- }
- dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED);
- if (command.group) {
- dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED);
- }
- }
-
- if (command.state === state) {
- continue;
- }
-
- command.state = state;
- if (state) {
- dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
- if (command.group) {
- dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
- }
- if (command.dialog) {
- if (typeof(state) === "object") {
- command.dialog.show(state);
- } else {
- command.dialog.hide();
- }
- }
- } else {
- dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
- if (command.group) {
- dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
- }
- if (command.dialog) {
- command.dialog.hide();
- }
- }
- }
-
- for (i in actionMapping) {
- action = actionMapping[i];
-
- if (action.name === "change_view") {
- action.state = this.editor.currentView === this.editor.textarea;
- if (action.state) {
- dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE);
- } else {
- dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE);
- }
- }
- }
- },
-
- show: function() {
- this.container.style.display = "";
- },
-
- hide: function() {
- this.container.style.display = "none";
- }
- });
-
-})(wysihtml5);
-/**
- * WYSIHTML5 Editor
- *
- * @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface
- * @param {Object} [config] See defaultConfig object below for explanation of each individual config option
- *
- * @events
- * load
- * beforeload (for internal use only)
- * focus
- * focus:composer
- * focus:textarea
- * blur
- * blur:composer
- * blur:textarea
- * change
- * change:composer
- * change:textarea
- * paste
- * paste:composer
- * paste:textarea
- * newword:composer
- * destroy:composer
- * undo:composer
- * redo:composer
- * beforecommand:composer
- * aftercommand:composer
- * change_view
- */
-(function(wysihtml5) {
- var undef;
-
- var defaultConfig = {
- // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body
- name: undef,
- // Whether the editor should look like the textarea (by adopting styles)
- style: true,
- // Id of the toolbar element, pass falsey value if you don't want any toolbar logic
- toolbar: undef,
- // Whether urls, entered by the user should automatically become clickable-links
- autoLink: true,
- // Object which includes parser rules to apply when html gets inserted via copy & paste
- // See parser_rules/*.js for examples
- parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} },
- // Parser method to use when the user inserts content via copy & paste
- parser: wysihtml5.dom.parse,
- // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option
- composerClassName: "wysihtml5-editor",
- // Class name to add to the body when the wysihtml5 editor is supported
- bodyClassName: "wysihtml5-supported",
- // Array (or single string) of stylesheet urls to be loaded in the editor's iframe
- stylesheets: [],
- // Placeholder text to use, defaults to the placeholder attribute on the textarea element
- placeholderText: undef,
- // Whether the composer should allow the user to manually resize images, tables etc.
- allowObjectResizing: true,
- // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5)
- supportTouchDevices: true
- };
-
- wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend(
- /** @scope wysihtml5.Editor.prototype */ {
- constructor: function(textareaElement, config) {
- this.textareaElement = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement;
- this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get();
- this.textarea = new wysihtml5.views.Textarea(this, this.textareaElement, this.config);
- this.currentView = this.textarea;
- this._isCompatible = wysihtml5.browser.supported();
-
- // Sort out unsupported/unwanted browsers here
- if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) {
- var that = this;
- setTimeout(function() { that.fire("beforeload").fire("load"); }, 0);
- return;
- }
-
- // Add class name to body, to indicate that the editor is supported
- wysihtml5.dom.addClass(document.body, this.config.bodyClassName);
-
- this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config);
- this.currentView = this.composer;
-
- if (typeof(this.config.parser) === "function") {
- this._initParser();
- }
-
- this.observe("beforeload", function() {
- this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer);
- if (this.config.toolbar) {
- this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar);
- }
- });
-
- try {
- console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5");
- } catch(e) {}
- },
-
- isCompatible: function() {
- return this._isCompatible;
- },
-
- clear: function() {
- this.currentView.clear();
- return this;
- },
-
- getValue: function(parse) {
- return this.currentView.getValue(parse);
- },
-
- setValue: function(html, parse) {
- if (!html) {
- return this.clear();
- }
- this.currentView.setValue(html, parse);
- return this;
- },
-
- focus: function(setToEnd) {
- this.currentView.focus(setToEnd);
- return this;
- },
-
- /**
- * Deactivate editor (make it readonly)
- */
- disable: function() {
- this.currentView.disable();
- return this;
- },
-
- /**
- * Activate editor
- */
- enable: function() {
- this.currentView.enable();
- return this;
- },
-
- isEmpty: function() {
- return this.currentView.isEmpty();
- },
-
- hasPlaceholderSet: function() {
- return this.currentView.hasPlaceholderSet();
- },
-
- parse: function(htmlOrElement) {
- var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true);
- if (typeof(htmlOrElement) === "object") {
- wysihtml5.quirks.redraw(htmlOrElement);
- }
- return returnValue;
- },
-
- /**
- * Prepare html parser logic
- * - Observes for paste and drop
- */
- _initParser: function() {
- this.observe("paste:composer", function() {
- var keepScrollPosition = true,
- that = this;
- that.composer.selection.executeAndRestore(function() {
- wysihtml5.quirks.cleanPastedHTML(that.composer.element);
- that.parse(that.composer.element);
- }, keepScrollPosition);
- });
-
- this.observe("paste:textarea", function() {
- var value = this.textarea.getValue(),
- newValue;
- newValue = this.parse(value);
- this.textarea.setValue(newValue);
- });
- }
- });
-})(wysihtml5);
-
-!function($, wysi) {
- "use strict";
-
- var tpl = {
- "font-styles": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li class='dropdown'>" +
- "<a class='btn dropdown-toggle" + size + "' data-toggle='dropdown' href='#'>" +
- "<i class='icon-font'></i> <span class='current-font'>" + locale.font_styles.normal + "</span> <b class='caret'></b>" +
- "</a>" +
- "<ul class='dropdown-menu'>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='div' tabindex='-1'>" + locale.font_styles.normal + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h1' tabindex='-1'>" + locale.font_styles.h1 + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h2' tabindex='-1'>" + locale.font_styles.h2 + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h3' tabindex='-1'>" + locale.font_styles.h3 + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h4'>" + locale.font_styles.h4 + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h5'>" + locale.font_styles.h5 + "</a></li>" +
- "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h6'>" + locale.font_styles.h6 + "</a></li>" +
- "</ul>" +
- "</li>";
- },
-
- "emphasis": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li>" +
- "<div class='btn-group'>" +
- "<a class='btn" + size + "' data-wysihtml5-command='bold' title='CTRL+B' tabindex='-1'>" + locale.emphasis.bold + "</a>" +
- "<a class='btn" + size + "' data-wysihtml5-command='italic' title='CTRL+I' tabindex='-1'>" + locale.emphasis.italic + "</a>" +
- "<a class='btn" + size + "' data-wysihtml5-command='underline' title='CTRL+U' tabindex='-1'>" + locale.emphasis.underline + "</a>" +
- "</div>" +
- "</li>";
- },
-
- "lists": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li>" +
- "<div class='btn-group'>" +
- "<a class='btn" + size + "' data-wysihtml5-command='insertUnorderedList' title='" + locale.lists.unordered + "' tabindex='-1'><i class='icon-list'></i></a>" +
- "<a class='btn" + size + "' data-wysihtml5-command='insertOrderedList' title='" + locale.lists.ordered + "' tabindex='-1'><i class='icon-th-list'></i></a>" +
- "<a class='btn" + size + "' data-wysihtml5-command='Outdent' title='" + locale.lists.outdent + "' tabindex='-1'><i class='icon-indent-right'></i></a>" +
- "<a class='btn" + size + "' data-wysihtml5-command='Indent' title='" + locale.lists.indent + "' tabindex='-1'><i class='icon-indent-left'></i></a>" +
- "</div>" +
- "</li>";
- },
-
- "link": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li>" +
- "<div class='bootstrap-wysihtml5-insert-link-modal modal hide fade'>" +
- "<div class='modal-header'>" +
- "<a class='close' data-dismiss='modal'>×</a>" +
- "<h3>" + locale.link.insert + "</h3>" +
- "</div>" +
- "<div class='modal-body'>" +
- "<input value='http://' class='bootstrap-wysihtml5-insert-link-url input-xlarge'>" +
- "<label class='checkbox'> <input type='checkbox' class='bootstrap-wysihtml5-insert-link-target' checked>" + locale.link.target + "</label>" +
- "</div>" +
- "<div class='modal-footer'>" +
- "<a href='#' class='btn' data-dismiss='modal'>" + locale.link.cancel + "</a>" +
- "<a href='#' class='btn btn-primary' data-dismiss='modal'>" + locale.link.insert + "</a>" +
- "</div>" +
- "</div>" +
- "<a class='btn" + size + "' data-wysihtml5-command='createLink' title='" + locale.link.insert + "' tabindex='-1'><i class='icon-share'></i></a>" +
- "</li>";
- },
-
- "image": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li>" +
- "<div class='bootstrap-wysihtml5-insert-image-modal modal hide fade'>" +
- "<div class='modal-header'>" +
- "<a class='close' data-dismiss='modal'>×</a>" +
- "<h3>" + locale.image.insert + "</h3>" +
- "</div>" +
- "<div class='modal-body'>" +
- "<input value='http://' class='bootstrap-wysihtml5-insert-image-url input-xlarge'>" +
- "</div>" +
- "<div class='modal-footer'>" +
- "<a href='#' class='btn' data-dismiss='modal'>" + locale.image.cancel + "</a>" +
- "<a href='#' class='btn btn-primary' data-dismiss='modal'>" + locale.image.insert + "</a>" +
- "</div>" +
- "</div>" +
- "<a class='btn" + size + "' data-wysihtml5-command='insertImage' title='" + locale.image.insert + "' tabindex='-1'><i class='icon-picture'></i></a>" +
- "</li>";
- },
-
- "html": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li>" +
- "<div class='btn-group'>" +
- "<a class='btn" + size + "' data-wysihtml5-action='change_view' title='" + locale.html.edit + "' tabindex='-1'><i class='icon-pencil'></i></a>" +
- "</div>" +
- "</li>";
- },
-
- "color": function(locale, options) {
- var size = (options && options.size) ? ' btn-'+options.size : '';
- return "<li class='dropdown'>" +
- "<a class='btn dropdown-toggle" + size + "' data-toggle='dropdown' href='#' tabindex='-1'>" +
- "<span class='current-color'>" + locale.colours.black + "</span> <b class='caret'></b>" +
- "</a>" +
- "<ul class='dropdown-menu'>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='black'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='black'>" + locale.colours.black + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='silver'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='silver'>" + locale.colours.silver + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='gray'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='gray'>" + locale.colours.gray + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='maroon'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='maroon'>" + locale.colours.maroon + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='red'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='red'>" + locale.colours.red + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='purple'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='purple'>" + locale.colours.purple + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='green'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='green'>" + locale.colours.green + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='olive'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='olive'>" + locale.colours.olive + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='navy'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='navy'>" + locale.colours.navy + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='blue'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='blue'>" + locale.colours.blue + "</a></li>" +
- "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='orange'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='orange'>" + locale.colours.orange + "</a></li>" +
- "</ul>" +
- "</li>";
- }
- };
-
- var templates = function(key, locale, options) {
- return tpl[key](locale, options);
- };
-
-
- var Wysihtml5 = function(el, options) {
- this.el = el;
- var toolbarOpts = options || defaultOptions;
- for(var t in toolbarOpts.customTemplates) {
- tpl[t] = toolbarOpts.customTemplates[t];
- }
- this.toolbar = this.createToolbar(el, toolbarOpts);
- this.editor = this.createEditor(options);
-
- window.editor = this.editor;
-
- $('iframe.wysihtml5-sandbox').each(function(i, el){
- $(el.contentWindow).off('focus.wysihtml5').on({
- 'focus.wysihtml5' : function(){
- $('li.dropdown').removeClass('open');
- }
- });
- });
- };
-
- Wysihtml5.prototype = {
-
- constructor: Wysihtml5,
-
- createEditor: function(options) {
- options = options || {};
-
- // Add the toolbar to a clone of the options object so multiple instances
- // of the WYISYWG don't break because "toolbar" is already defined
- options = $.extend(true, {}, options);
- options.toolbar = this.toolbar[0];
-
- var editor = new wysi.Editor(this.el[0], options);
-
- if(options && options.events) {
- for(var eventName in options.events) {
- editor.on(eventName, options.events[eventName]);
- }
- }
- return editor;
- },
-
- createToolbar: function(el, options) {
- var self = this;
- var toolbar = $("<ul/>", {
- 'class' : "wysihtml5-toolbar",
- 'style': "display:none"
- });
- var culture = options.locale || defaultOptions.locale || "en";
- for(var key in defaultOptions) {
- var value = false;
-
- if(options[key] !== undefined) {
- if(options[key] === true) {
- value = true;
- }
- } else {
- value = defaultOptions[key];
- }
-
- if(value === true) {
- toolbar.append(templates(key, locale[culture], options));
-
- if(key === "html") {
- this.initHtml(toolbar);
- }
-
- if(key === "link") {
- this.initInsertLink(toolbar);
- }
-
- if(key === "image") {
- this.initInsertImage(toolbar);
- }
- }
- }
-
- if(options.toolbar) {
- for(key in options.toolbar) {
- toolbar.append(options.toolbar[key]);
- }
- }
-
- toolbar.find("a[data-wysihtml5-command='formatBlock']").click(function(e) {
- var target = e.target || e.srcElement;
- var el = $(target);
- self.toolbar.find('.current-font').text(el.html());
- });
-
- toolbar.find("a[data-wysihtml5-command='foreColor']").click(function(e) {
- var target = e.target || e.srcElement;
- var el = $(target);
- self.toolbar.find('.current-color').text(el.html());
- });
-
- this.el.before(toolbar);
-
- return toolbar;
- },
-
- initHtml: function(toolbar) {
- var changeViewSelector = "a[data-wysihtml5-action='change_view']";
- toolbar.find(changeViewSelector).click(function(e) {
- toolbar.find('a.btn').not(changeViewSelector).toggleClass('disabled');
- });
- },
-
- initInsertImage: function(toolbar) {
- var self = this;
- var insertImageModal = toolbar.find('.bootstrap-wysihtml5-insert-image-modal');
- var urlInput = insertImageModal.find('.bootstrap-wysihtml5-insert-image-url');
- var insertButton = insertImageModal.find('a.btn-primary');
- var initialValue = urlInput.val();
- var caretBookmark;
-
- var insertImage = function() {
- var url = urlInput.val();
- urlInput.val(initialValue);
- self.editor.currentView.element.focus();
- if (caretBookmark) {
- self.editor.composer.selection.setBookmark(caretBookmark);
- caretBookmark = null;
- }
- self.editor.composer.commands.exec("insertImage", url);
- };
-
- urlInput.keypress(function(e) {
- if(e.which == 13) {
- insertImage();
- insertImageModal.modal('hide');
- }
- });
-
- insertButton.click(insertImage);
-
- insertImageModal.on('shown', function() {
- urlInput.focus();
- });
-
- insertImageModal.on('hide', function() {
- self.editor.currentView.element.focus();
- });
-
- toolbar.find('a[data-wysihtml5-command=insertImage]').click(function() {
- var activeButton = $(this).hasClass("wysihtml5-command-active");
-
- if (!activeButton) {
- self.editor.currentView.element.focus(false);
- caretBookmark = self.editor.composer.selection.getBookmark();
- insertImageModal.appendTo('body').modal('show');
- insertImageModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
- e.stopPropagation();
- });
- return false;
- }
- else {
- return true;
- }
- });
- },
-
- initInsertLink: function(toolbar) {
- var self = this;
- var insertLinkModal = toolbar.find('.bootstrap-wysihtml5-insert-link-modal');
- var urlInput = insertLinkModal.find('.bootstrap-wysihtml5-insert-link-url');
- var targetInput = insertLinkModal.find('.bootstrap-wysihtml5-insert-link-target');
- var insertButton = insertLinkModal.find('a.btn-primary');
- var initialValue = urlInput.val();
- var caretBookmark;
-
- var insertLink = function() {
- var url = urlInput.val();
- urlInput.val(initialValue);
- self.editor.currentView.element.focus();
- if (caretBookmark) {
- self.editor.composer.selection.setBookmark(caretBookmark);
- caretBookmark = null;
- }
-
- var newWindow = targetInput.prop("checked");
- self.editor.composer.commands.exec("createLink", {
- 'href' : url,
- 'target' : (newWindow ? '_blank' : '_self'),
- 'rel' : (newWindow ? 'nofollow' : '')
- });
- };
- var pressedEnter = false;
-
- urlInput.keypress(function(e) {
- if(e.which == 13) {
- insertLink();
- insertLinkModal.modal('hide');
- }
- });
-
- insertButton.click(insertLink);
-
- insertLinkModal.on('shown', function() {
- urlInput.focus();
- });
-
- insertLinkModal.on('hide', function() {
- self.editor.currentView.element.focus();
- });
-
- toolbar.find('a[data-wysihtml5-command=createLink]').click(function() {
- var activeButton = $(this).hasClass("wysihtml5-command-active");
-
- if (!activeButton) {
- self.editor.currentView.element.focus(false);
- caretBookmark = self.editor.composer.selection.getBookmark();
- insertLinkModal.appendTo('body').modal('show');
- insertLinkModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) {
- e.stopPropagation();
- });
- return false;
- }
- else {
- return true;
- }
- });
- }
- };
-
- // these define our public api
- var methods = {
- resetDefaults: function() {
- $.fn.wysihtml5.defaultOptions = $.extend(true, {}, $.fn.wysihtml5.defaultOptionsCache);
- },
- bypassDefaults: function(options) {
- return this.each(function () {
- var $this = $(this);
- $this.data('wysihtml5', new Wysihtml5($this, options));
- });
- },
- shallowExtend: function (options) {
- var settings = $.extend({}, $.fn.wysihtml5.defaultOptions, options || {}, $(this).data());
- var that = this;
- return methods.bypassDefaults.apply(that, [settings]);
- },
- deepExtend: function(options) {
- var settings = $.extend(true, {}, $.fn.wysihtml5.defaultOptions, options || {});
- var that = this;
- return methods.bypassDefaults.apply(that, [settings]);
- },
- init: function(options) {
- var that = this;
- return methods.shallowExtend.apply(that, [options]);
- }
- };
-
- $.fn.wysihtml5 = function ( method ) {
- if ( methods[method] ) {
- return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
- } else if ( typeof method === 'object' || ! method ) {
- return methods.init.apply( this, arguments );
- } else {
- $.error( 'Method ' + method + ' does not exist on jQuery.wysihtml5' );
- }
- };
-
- $.fn.wysihtml5.Constructor = Wysihtml5;
-
- var defaultOptions = $.fn.wysihtml5.defaultOptions = {
- "font-styles": true,
- "color": false,
- "emphasis": true,
- "lists": true,
- "html": false,
- "link": true,
- "image": true,
- events: {},
- parserRules: {
- classes: {
- // (path_to_project/lib/css/wysiwyg-color.css)
- "wysiwyg-color-silver" : 1,
- "wysiwyg-color-gray" : 1,
- "wysiwyg-color-white" : 1,
- "wysiwyg-color-maroon" : 1,
- "wysiwyg-color-red" : 1,
- "wysiwyg-color-purple" : 1,
- "wysiwyg-color-fuchsia" : 1,
- "wysiwyg-color-green" : 1,
- "wysiwyg-color-lime" : 1,
- "wysiwyg-color-olive" : 1,
- "wysiwyg-color-yellow" : 1,
- "wysiwyg-color-navy" : 1,
- "wysiwyg-color-blue" : 1,
- "wysiwyg-color-teal" : 1,
- "wysiwyg-color-aqua" : 1,
- "wysiwyg-color-orange" : 1
- },
- tags: {
- "b": {},
- "i": {},
- "br": {},
- "ol": {},
- "ul": {},
- "li": {},
- "h1": {},
- "h2": {},
- "h3": {},
- "h4": {},
- "h5": {},
- "h6": {},
- "blockquote": {},
- "u": 1,
- "img": {
- "check_attributes": {
- "width": "numbers",
- "alt": "alt",
- "src": "url",
- "height": "numbers"
- }
- },
- "a": {
- check_attributes: {
- 'href': "url", // important to avoid XSS
- 'target': 'alt',
- 'rel': 'alt'
- }
- },
- "span": 1,
- "div": 1,
- // to allow save and edit files with code tag hacks
- "code": 1,
- "pre": 1
- }
- },
- stylesheets: ["/assets/bootstrap-wysihtml5/wysiwyg-color.css"], // (path_to_project/lib/css/wysiwyg-color.css)
- locale: "en"
- };
-
- if (typeof $.fn.wysihtml5.defaultOptionsCache === 'undefined') {
- $.fn.wysihtml5.defaultOptionsCache = $.extend(true, {}, $.fn.wysihtml5.defaultOptions);
- }
-
- var locale = $.fn.wysihtml5.locale = {
- en: {
- font_styles: {
- normal: "Normal text",
- h1: "Heading 1",
- h2: "Heading 2",
- h3: "Heading 3",
- h4: "Heading 4",
- h5: "Heading 5",
- h6: "Heading 6"
- },
- emphasis: {
- bold: "Bold",
- italic: "Italic",
- underline: "Underline"
- },
- lists: {
- unordered: "Unordered list",
- ordered: "Ordered list",
- outdent: "Outdent",
- indent: "Indent"
- },
- link: {
- insert: "Insert link",
- cancel: "Cancel",
- target: "Open link in new window"
- },
- image: {
- insert: "Insert image",
- cancel: "Cancel"
- },
- html: {
- edit: "Edit HTML"
- },
- colours: {
- black: "Black",
- silver: "Silver",
- gray: "Grey",
- maroon: "Maroon",
- red: "Red",
- purple: "Purple",
- green: "Green",
- olive: "Olive",
- navy: "Navy",
- blue: "Blue",
- orange: "Orange"
- }
- }
- };
-
-}(window.jQuery, window.wysihtml5);
-
-
-(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
$.fn.findExtended = function(selector) {
if (_.str.startsWith(selector, "parent=")) {
@@ -48524,14 +44685,102 @@
})(Basepack.Form.Plugin);
/**
+ * @name DynamicRemoteField automatically re-renders field(s) depending on the change of other field
+
+ * @description takes all elements with data-dynamic-remote-field which identifies select on which value change
+ this element (with data-dynamic-remote-field attribute) is rerendered with values of remote call
+
+ NOTE: parameters are brought from html data attributes
+ * @param {String} data-dynamic-remote-field identification of the field which changes are watched
+ * @param {String} dependant-param additional parameter that is send to remote
+ * @param {Object} options contains url adress (remote_sourece key) to which ajax request is made to obtain data (html template)
+
+ * @returns {html} returns html template
+
+ * @example on the field gift_packages following html data attribues are added
+
+ * this is haml
+ .accordion{:data=>{
+ "dynamic-remote-field"=>"#subscription_order_order_template_id",
+ "dependant-param"=>"subscription_order[order_template_id]",
+ "options"=>"{\"remote_source\":\"/subscription_orders/gift_packages_partial\"}"}
+ }
+ %div.content Custom content
+
+ * this is the order_template field definition in meta data
+ field :order_template do
+ help ''
+ param = "f[main_magazine_magazine_group_id_eq]"
+ options_source_params do
+ { param => bindings[:object].magazine_group.try(:id) || -1,
+ 'f[offerable]' => true,
+ 'f[s]' => 'price asc'
+ }
+ end
+ html_attributes do
+ {
+ data: {
+ "dependant-filteringselect" => "#subscription_order_magazine_group_id",
+ "dependant-param" => param,
+ :placeholder => "Vyberte, prosÃm"
+ }
+ }
+ end
+ end
+ */
+
+ Basepack.Form.Plugins.DynamicRemoteField = (function(_super) {
+ __extends(DynamicRemoteField, _super);
+
+ function DynamicRemoteField() {
+ return DynamicRemoteField.__super__.constructor.apply(this, arguments);
+ }
+
+ DynamicRemoteField.prototype.bind = function() {
+ var plugin;
+ plugin = this;
+ return this.form.find('[data-dynamic-remote-field]').each(function() {
+ var dependsOn, group, that;
+ that = $(this);
+ group = that.parents('.control-group:first');
+ dependsOn = that.findExtended(that.data('dynamic-remote-field'));
+ return dependsOn.on('change', function(e) {
+ var options;
+ options = _.clone(that.data('options'));
+ if (e.val !== "" && (e.val != null)) {
+ options.remote_source_params = _.clone(options.remote_source_params) || {};
+ options.remote_source_params[that.data('dependantParam')] = e.val;
+ return plugin.ajax(options, group);
+ }
+ });
+ });
+ };
+
+ DynamicRemoteField.prototype.ajax = function(options, group) {
+ return $.ajax(options.remote_source, {
+ data: $.extend({}, options.remote_source_params),
+ dataType: "html"
+ }).done(function(data) {
+ return group.html(data);
+ }).fail(function() {
+ return group.html('<div class="alert alert-error">Could not load data from server. We are sorry.</div>');
+ });
+ };
+
+ return DynamicRemoteField;
+
+ })(Basepack.Form.Plugin);
+
+
+ /**
* Dynamically show/hide fields based on other field value.
* takes all elements with data-dynamic-fields and use this data attribute as an configuration:
- @param{data-dynamic-fields} array of actions. Each action is a hash with keys:
+ @param{data-dynamic-fields} array of actions. Each action is a hash with keys:
condition - condition which should be met (Stirng: field has to equal, Array: field has to match one of item of array)
field_actions - hash. Keys are other fields on which are taken action.
* Exmaple:
[{"condition":["aaa","hide"],"field_actions":{"www":{"visible":false}}},{"condition":"xxx","field_actions":{"www":{"visible":true}}}]
@@ -48625,13 +44874,11 @@
function Orderable() {
return Orderable.__super__.constructor.apply(this, arguments);
}
Orderable.prototype.update_sort_order = function() {
- console.log('volam update_sort_order');
return this.form.find('.fields').each(function(idx, fields) {
- console.log('updatuji: ' + idx);
return $(fields).find('input[name$="[position]"]').val(idx + 1);
});
};
Orderable.prototype.bind = function() {
@@ -48917,10 +45164,11 @@
+// x= xrequire fancytree/jquery.fancytree.gridnav.js
@@ -48930,11 +45178,11 @@
-
+;
(function() {
var CSRFToken, Click, ComponentUrl, Link, browserCompatibleDocumentParser, browserIsntBuggy, browserSupportsCustomEvents, browserSupportsPushState, browserSupportsTurbolinks, bypassOnLoadPopstate, cacheCurrentPage, cacheSize, changePage, constrainPageCacheTo, createDocument, currentState, enableTransitionCache, executeScriptTags, extractTitleAndBody, fetch, fetchHistory, fetchReplacement, historyStateIsDefined, initializeTurbolinks, installDocumentReadyPageEventTriggers, installHistoryChangeHandler, installJqueryAjaxSuccessPageUpdateTrigger, loadedAssets, pageCache, pageChangePrevented, pagesCached, popCookie, processResponse, recallScrollPosition, referer, reflectNewUrl, reflectRedirectedUrl, rememberCurrentState, rememberCurrentUrl, rememberReferer, removeNoscriptTags, requestMethodIsSafe, resetScrollPosition, transitionCacheEnabled, transitionCacheFor, triggerEvent, visit, xhr, _ref,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
@@ -49542,6 +45790,6 @@
//
;
-; TI"required_assets_digest; TI"%f97e3afe413558695afd8183ca7b68ec; FI"
_version; TI"%361c512b9086418778df946c0d278f91; F
+; TI"required_assets_digest; TI"%470b7a3b30a1172e8cf200acd48f45d2; FI"
_version; TI"%361c512b9086418778df946c0d278f91; F
\ No newline at end of file