/*! * jQuery JavaScript Library v1.11.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:42Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "
"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = ""; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = ""; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = "
a"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = ""; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "" ], legend: [ 1, "
", "
" ], area: [ 1, "", "" ], param: [ 1, "", "" ], thead: [ 1, "", "
" ], tr: [ 2, "", "
" ], col: [ 2, "", "
" ], td: [ 3, "", "
" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted from table fragments if ( !support.tbody ) { // String was a , *may* have spurious elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare or wrap[1] === "
" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "\n \n \n\n \n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["details_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["editable_workspace_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return "scrivito_green"; },"3":function(container,depth0,helpers,partials,data) { var stack1; return "
\n \n \n
\n"; },"4":function(container,depth0,helpers,partials,data) { var stack1; return " \n"; },"5":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression(container.lambda((depth0 != null ? depth0.title : depth0), depth0)) + "\n"; },"7":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar.empty_workspace_title",{"name":"translate","hash":{},"data":data})) + "\n"; },"9":function(container,depth0,helpers,partials,data) { var stack1; return "
\n \n \n
\n"; },"10":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"editable_ws_dialog.or_create_new",{"name":"translate","hash":{},"data":data})) + "\n"; },"12":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"editable_ws_dialog.create_new",{"name":"translate","hash":{},"data":data})) + "\n"; },"14":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"cancel",{"name":"translate","hash":{},"data":data})) + "\n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"confirm",{"name":"translate","hash":{},"data":data})) + "\n"; },"16":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"close",{"name":"translate","hash":{},"data":data})) + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
\n
\n \n

\n " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "\n

\n
\n
\n
\n " + container.escapeExpression(((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description","hash":{},"data":data}) : helper))) + "\n
\n
\n  \n
\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.workspaces : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.can_create : depth0),{"name":"if","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
\n
\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.can_select_or_create : depth0),{"name":"if","hash":{},"fn":container.program(14, data, 0),"inverse":container.program(16, data, 0),"data":data})) != null ? stack1 : "") + "
\n
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["editable_workspace_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["element_overlay"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["element_overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["error_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return " " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"error_dialog.toggle_details",{"name":"translate","hash":{},"data":data})) + "\n"; },"3":function(container,depth0,helpers,partials,data) { var stack1; return "
\n

" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"error_dialog.error_details",{"name":"translate","hash":{},"data":data})) + ":

\n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.details : depth0),{"name":"each","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
\n"; },"4":function(container,depth0,helpers,partials,data) { return "
" + container.escapeExpression(container.lambda(depth0, depth0)) + "
\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
\n
\n \n

\n " + container.escapeExpression(((helper = (helper = helpers.message || (depth0 != null ? depth0.message : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"message","hash":{},"data":data}) : helper))) + "\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.details : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "

\n
\n\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.details : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n \n
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["error_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["iframe_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var helper; return "scrivito_" + container.escapeExpression(((helper = (helper = helpers.color || (depth0 != null ? depth0.color : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"color","hash":{},"data":data}) : helper))); },"3":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["with"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.cancel : depth0),{"name":"with","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"4":function(container,depth0,helpers,partials,data) { var stack1; return " \n " + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.title : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : "") + "\n \n"; },"5":function(container,depth0,helpers,partials,data) { var helper; return container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))); },"7":function(container,depth0,helpers,partials,data) { return container.escapeExpression(container.lambda(depth0, depth0)); },"9":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["with"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.confirm : depth0),{"name":"with","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"10":function(container,depth0,helpers,partials,data) { var stack1; return " \n " + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.title : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : "") + "\n \n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
\n
\n
\n" + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.disable_cancel : depth0),{"name":"unless","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.disable_confirm : depth0),{"name":"unless","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
\n
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["iframe_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["inplace_marker"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var helper; return " " + container.escapeExpression(((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description","hash":{},"data":data}) : helper))) + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "\n \n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.description : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["inplace_marker"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var stack1; return " " + ((stack1 = container.lambda((depth0 != null ? depth0.render : depth0), depth0)) != null ? stack1 : "") + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
\n
    \n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.menu_items : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
  • \n
\n
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_browse_content"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_browse_content"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "\n \n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator/conflict"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
  • \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar_conflict_indicator.conflict_headline",{"name":"translate","hash":{},"data":data})) + "\n
  • \n
  • \n " + ((stack1 = (helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar_conflict_indicator.conflict_description",{"name":"translate","hash":{},"data":data})) != null ? stack1 : "") + "\n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator/conflict"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator/warn"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return "
  • \n " + container.escapeExpression(((helper = (helper = helpers.headline || (depth0 != null ? depth0.headline : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"headline","hash":{},"data":data}) : helper))) + "\n
  • \n
  • \n " + container.escapeExpression(((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description","hash":{},"data":data}) : helper))) + "\n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_conflict_indicator/warn"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_device_toggle"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return "\n \n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_device_toggle"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_display_mode_toggle"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
    \n \n " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "\n
    \n"; },"2":function(container,depth0,helpers,partials,data) { return "scrivito_disabled"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
    \n \n\n
    \n \n " + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.switch_to_view_mode_command : depth0)) != null ? stack1.title : stack1), depth0)) + "\n
    \n\n" + ((stack1 = helpers["with"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.switch_to_editing_mode_command : depth0),{"name":"with","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    \n \n \n " + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.switch_to_comparing_mode_command : depth0)) != null ? stack1.title : stack1), depth0)) + " \n \n
    \n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_display_mode_toggle"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_warning"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "\n \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar_warning.warning",{"name":"translate","hash":{},"data":data})) + "\n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_bar_warning"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return "scrivito_disabled"; },"3":function(container,depth0,helpers,partials,data) { var helper; return container.escapeExpression(((helper = (helper = helpers.tooltip || (depth0 != null ? depth0.tooltip : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"tooltip","hash":{},"data":data}) : helper))); },"5":function(container,depth0,helpers,partials,data) { var helper; return container.escapeExpression(((helper = (helper = helpers.reason_for_being_disabled || (depth0 != null ? depth0.reason_for_being_disabled : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"reason_for_being_disabled","hash":{},"data":data}) : helper))); },"7":function(container,depth0,helpers,partials,data) { var helper; return " " + container.escapeExpression(((helper = (helper = helpers.subtitle || (depth0 != null ? depth0.subtitle : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"subtitle","hash":{},"data":data}) : helper))) + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
  • \n \n " + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.subtitle : depth0),{"name":"if","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + " \n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/icon"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item/icon"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/icon_hex"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "" + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item/icon_hex"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/icon_sci"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item/icon_sci"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/separator"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var helper; return "" + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + ""; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
  • \n " + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.title : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item/separator"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/spinner"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return "
  • \n \n \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_item.spinner.loading",{"name":"translate","hash":{},"data":data})) + "\n \n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["menu_item/spinner"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["obj_menu"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return " scrivito_new\n"; },"3":function(container,depth0,helpers,partials,data) { return " scrivito_changed\n"; },"5":function(container,depth0,helpers,partials,data) { return " scrivito_deleted\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["obj_menu"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["obj_sorting_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var helper; return "
  • " + container.escapeExpression(((helper = (helper = helpers.description_for_editor || (depth0 != null ? depth0.description_for_editor : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description_for_editor","hash":{},"data":data}) : helper))) + "
  • \n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
    \n\n
    \n

    " + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"obj_sorting_dialog.title",{"name":"translate","hash":{},"data":data})) + "

    \n
    \n\n
    \n
      \n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.child_list : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
    \n
    \n\n \n\n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["obj_sorting_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["option_marker"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return "scrivito_visible"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "\n \n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["option_marker"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["overlay"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["prompt_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var helper; return "scrivito_" + container.escapeExpression(((helper = (helper = helpers.color || (depth0 != null ? depth0.color : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"color","hash":{},"data":data}) : helper))); },"3":function(container,depth0,helpers,partials,data) { var helper; return "

    " + container.escapeExpression(((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description","hash":{},"data":data}) : helper))) + "

    \n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
    \n
    \n " + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n

    " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "

    \n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.description : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
    \n
    \n \n
    \n \n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["prompt_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["saving_indicator"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "\n \n \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"saving_indicator_item.saving",{"name":"translate","hash":{},"data":data})) + "\n \n\n \n \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"saving_indicator_item.saved",{"name":"translate","hash":{},"data":data})) + "\n \n"; },"useData":true}); return this.ScrivitoHandlebarsTemplates["saving_indicator"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["saving_overlay"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return "
    \n \n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["saving_overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["title"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return "

    " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "

    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["title"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["transfer_changes_dialog"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { return ""; },"useData":true}); return this.ScrivitoHandlebarsTemplates["transfer_changes_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["transfer_changes_dialog/body"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
    \n \n \n\n \n\n \n \n\n \n \n"; },"2":function(container,depth0,helpers,partials,data) { var helper; return "data-scrivito-obj-id=\"" + container.escapeExpression(((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"id","hash":{},"data":data}) : helper))) + "\""; },"4":function(container,depth0,helpers,partials,data) { return "scrivito_disabled"; },"6":function(container,depth0,helpers,partials,data) { return "scrivito_active"; },"8":function(container,depth0,helpers,partials,data) { return "conflict"; },"10":function(container,depth0,helpers,partials,data) { var stack1; return " \n"; },"12":function(container,depth0,helpers,partials,data) { return " \n"; },"14":function(container,depth0,helpers,partials,data) { var helper; return " \n \n \n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "
    \n \n \n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.has_restriction : depth0),{"name":"if","hash":{},"fn":container.program(10, data, 0),"inverse":container.program(12, data, 0),"data":data})) != null ? stack1 : "") + " " + container.escapeExpression(((helper = (helper = helpers.description_for_editor || (depth0 != null ? depth0.description_for_editor : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description_for_editor","hash":{},"data":data}) : helper))) + "" + container.escapeExpression(((helper = (helper = helpers.obj_class || (depth0 != null ? depth0.obj_class : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"obj_class","hash":{},"data":data}) : helper))) + "\n" + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.is_deleted : depth0),{"name":"unless","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
    \n \n \n \n \n \n \n \n \n \n \n\n \n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.objs : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + " \n
    " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_changes_dialog.modification",{"name":"translate","hash":{},"data":data})) + "" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_changes_dialog.rights",{"name":"translate","hash":{},"data":data})) + "" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_changes_dialog.description_for_editor",{"name":"translate","hash":{},"data":data})) + "" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_changes_dialog.obj_class",{"name":"translate","hash":{},"data":data})) + "" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_changes_dialog.last_changed",{"name":"translate","hash":{},"data":data})) + "
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["transfer_changes_dialog/body"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["transfer_errors_dialog"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var stack1; return "

    " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_errors_dialog.modified",{"name":"translate","hash":{},"data":data})) + "

    \n
      \n " + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.modified : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    \n"; },"2":function(container,depth0,helpers,partials,data) { var helper; return "
  • " + container.escapeExpression(((helper = (helper = helpers.description_for_editor || (depth0 != null ? depth0.description_for_editor : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"description_for_editor","hash":{},"data":data}) : helper))) + "
  • "; },"4":function(container,depth0,helpers,partials,data) { var stack1; return "

    " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"transfer_errors_dialog.conflicting",{"name":"translate","hash":{},"data":data})) + "

    \n
      \n " + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.conflicting : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    \n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.modified : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.conflicting : depth0),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"useData":true}); return this.ScrivitoHandlebarsTemplates["transfer_errors_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { var stack1, helper; return " " + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + "\n " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "\n"; },"3":function(container,depth0,helpers,partials,data) { var stack1; return "
  • \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select.this_workspace",{"name":"translate","hash":{},"data":data})) + "\n
  • \n\n" + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},((stack1 = (depth0 != null ? depth0.commands : depth0)) != null ? stack1.for_editable : stack1),{"name":"each","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "
  • \n"; },"4":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.is_present : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"5":function(container,depth0,helpers,partials,data) { var stack1; return " " + ((stack1 = (helpers.render || (depth0 && depth0.render) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select/menu_item",depth0,{"name":"render","hash":{},"data":data})) != null ? stack1 : "") + "\n"; },"7":function(container,depth0,helpers,partials,data) { var stack1; return "
  • \n " + ((stack1 = (helpers.render || (depth0 && depth0.render) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select/menu_item",((stack1 = (depth0 != null ? depth0.commands : depth0)) != null ? stack1.select_published : stack1),{"name":"render","hash":{},"data":data})) != null ? stack1 : "") + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["with"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.selected_workspace : depth0),{"name":"with","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    \n
      \n " + ((stack1 = (helpers.render || (depth0 && depth0.render) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select/menu_item",((stack1 = (depth0 != null ? depth0.commands : depth0)) != null ? stack1.create_workspace : stack1),{"name":"render","hash":{},"data":data})) != null ? stack1 : "") + "\n " + ((stack1 = (helpers.render || (depth0 && depth0.render) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select/menu_item",((stack1 = (depth0 != null ? depth0.commands : depth0)) != null ? stack1.publish_history : stack1),{"name":"render","hash":{},"data":data})) != null ? stack1 : "") + "\n\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},((stack1 = (depth0 != null ? depth0.selected_workspace : depth0)) != null ? stack1.is_editable : stack1),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    • \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select.other_workspaces",{"name":"translate","hash":{},"data":data})) + "\n
    • \n\n" + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : {},((stack1 = (depth0 != null ? depth0.selected_workspace : depth0)) != null ? stack1.is_published : stack1),{"name":"unless","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + "\n
    • \n \n \n " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar.loading_workspaces",{"name":"translate","hash":{},"data":data})) + "\n \n
    • \n\n
    • \n
    \n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["workspace_select"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select/menu_item"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return "scrivito_highlight"; },"3":function(container,depth0,helpers,partials,data) { return "scrivito_disabled"; },"5":function(container,depth0,helpers,partials,data) { var helper; return container.escapeExpression(((helper = (helper = helpers.tooltip || (depth0 != null ? depth0.tooltip : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"tooltip","hash":{},"data":data}) : helper))); },"7":function(container,depth0,helpers,partials,data) { var helper; return container.escapeExpression(((helper = (helper = helpers.reason_for_being_disabled || (depth0 != null ? depth0.reason_for_being_disabled : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"reason_for_being_disabled","hash":{},"data":data}) : helper))); },"9":function(container,depth0,helpers,partials,data) { var helper; return " " + container.escapeExpression(((helper = (helper = helpers.subtitle || (depth0 != null ? depth0.subtitle : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"subtitle","hash":{},"data":data}) : helper))) + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1, helper; return "
  • \n \n " + ((stack1 = ((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"icon","hash":{},"data":data}) : helper))) != null ? stack1 : "") + " " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "\n" + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.subtitle : depth0),{"name":"if","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + " \n
  • "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["workspace_select/menu_item"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select/other_workspaces"] = Handlebars.template({"1":function(container,depth0,helpers,partials,data) { return "
  • \n"; },"3":function(container,depth0,helpers,partials,data) { var stack1; return " " + ((stack1 = (helpers.render || (depth0 && depth0.render) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_select/menu_item",depth0,{"name":"render","hash":{},"data":data})) != null ? stack1 : "") + "\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.has_separator : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") + ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.commands : depth0),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"useData":true}); return this.ScrivitoHandlebarsTemplates["workspace_select/other_workspaces"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_settings_dialog"] = Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var helper; return "
    \n
    \n

    " + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) + "

    \n
    \n\n
    \n

    " + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"workspace_settings_dialog.owners",{"name":"translate","hash":{},"data":data})) + "

    \n \n
    \n\n \n
    "; },"useData":true}); return this.ScrivitoHandlebarsTemplates["workspace_settings_dialog"]; }).call(this); $.i18n().load({ 'confirm': 'Bestätigen', 'cancel': 'Abbrechen', 'save': 'Speichern', 'welcome': 'Willkommen', 'welcome_x': 'Willkommen $1', 'accept': 'Übernehmen', 'close': 'Schließen', 'done': 'Fertig', 'loading': 'Lade...', 'current_page': 'Aktuelle Seite', 'ok': 'Ok', 'obj.tooltip.is_new': 'Diese Seite ist neu.', 'obj.tooltip.is_edited': 'Diese Seite wurde geändert.', 'obj.tooltip.is_deleted': 'Diese Seite wurde gelöscht.', 'workspace.title_published': 'Veröffentlichte Inhalte', 'workspace.empty_title': '', 'workspace.publish_error.exceeds_obj_limit': 'Diese Arbeitskopie kann nicht veröffentlicht werden, weil die maximale Anzahl der in Ihrem Tarif enthaltenen CMS-Objekte überschritten wurde.', 'workspace_settings_dialog.owners': 'Besitzer', 'workspace_settings_dialog.nothing_found': 'Nichts gefunden', 'workspace_settings_dialog.searching': 'Suche...', 'workspace_settings_dialog.too_short': 'Benutzer suchen...', 'workspace_select.this_workspace': 'Diese Arbeitskopie', 'workspace_select.other_workspaces': 'Andere Arbeitskopien', 'menu_item.spinner.loading': 'Laden...', 'choose_obj_class_dialog.add_child_page.title': 'Seitenvorlage auswählen', 'choose_obj_class_dialog.create_page.title': 'Seitenvorlage auswählen', 'choose_obj_class_dialog.create_widget.title': 'Widget auswählen', 'choose_obj_class_dialog.last_used': 'Zuletzt verwendet', 'choose_obj_class_dialog.popular': 'Oft verwendet', 'choose_obj_class_dialog.all': 'Alle', 'editable_ws_dialog.view_mode.title.select_or_create': 'Arbeitskopie wählen', 'editable_ws_dialog.view_mode.title.select': 'Arbeitskopie auswählen', 'editable_ws_dialog.view_mode.title.create': 'Arbeitskopie anlegen', 'editable_ws_dialog.view_mode.title.forbidden': 'Keine Arbeitskopie verfügbar', 'editable_ws_dialog.view_mode.description.select_or_create': 'Wählen Sie eine Arbeitskopie aus oder legen Sie eine neue an, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.view_mode.description.select': 'Wählen Sie eine Arbeitskopie aus, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.view_mode.description.create': 'Legen Sie eine neue Arbeitskopie an, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.view_mode.description.forbidden': 'Es gibt keine Arbeitskopie, in der Sie Inhalte ändern könnten. Auch wurde es Ihnen nicht ermöglicht, Arbeitskopien anzulegen.', 'editable_ws_dialog.transfer_changes.title.select_or_create': 'Ziel-Arbeitskopie auswählen', 'editable_ws_dialog.transfer_changes.title.select': 'Ziel-Arbeitskopie auswählen', 'editable_ws_dialog.transfer_changes.title.create': 'Ziel-Arbeitskopie anlegen', 'editable_ws_dialog.transfer_changes.title.forbidden': 'Keine Arbeitskopie verfügbar', 'editable_ws_dialog.transfer_changes.description.select_or_create': 'Die Änderungen können in eine bestehende oder in eine neue Arbeitskopie verschoben werden.', 'editable_ws_dialog.transfer_changes.description.select': 'Die Änderungen werden in die ausgewählte Arbeitskopie verschoben.', 'editable_ws_dialog.transfer_changes.description.create': 'Bitte erstellen Sie die Ziel-Arbeitskopie', 'editable_ws_dialog.transfer_changes.description.forbidden': 'Sie sind nicht dazu berechtigt, Änderungen in eine bestehende Arbeitskopie zu verschieben.', 'editable_ws_dialog.choose_existing': 'Wählen Sie eine bestehende Arbeitskopie aus:', 'editable_ws_dialog.create_new': 'Legen Sie eine neue Arbeitskopie an:', 'editable_ws_dialog.or_create_new': 'Oder legen Sie eine neue an:', 'editable_ws_dialog.create_new_playholder': 'Titel der neuen Arbeitskopie', 'editable_ws_dialog.select': 'Auswählen', 'publish_history_dialog.changes_count': 'Geändert', 'publish_history_dialog.changes_count.not_available': 'Nicht verfügbar', 'publish_history_dialog.changes_count.one': '1 Objekt', 'publish_history_dialog.changes_count.many': '$1 Objekte', 'publish_history_dialog.close': 'Schließen', 'publish_history_dialog.error': 'Beim Laden des Veröffentlichungsverlaufs ist ein Fehler aufgetreten. Bitte versuchen Sie es später erneut. Falls das Problem bestehen bleibt, wenden Sie sich bitte an Ihren technischen Ansprechpartner für diese Website.', 'publish_history_dialog.not_restorable': 'Dies sind die aktuell veröffentlichten Inhalte.', 'publish_history_dialog.published_at': 'Veröffentlicht ', 'publish_history_dialog.title': 'Veröffentlichungsverlauf', 'publish_history_dialog.info': 'Wählen Sie aus der Liste eine Arbeitskopie, um einen archivierten Stand Ihrer Website zu sehen. Lernen Sie mehr über den ', 'publish_history_dialog.link': 'Veröffentlichungsverlauf', 'publish_history_dialog.is_limited': 'Es werden nur $1 Einträge des Verlaufs angezeigt. Stufen Sie Ihren Account hoch, um mehr Einträge zu sehen.', 'resource_dialog.title': 'Eigenschaften der Ressource "$1"', 'resource_dialog.commands.restore_obj.title': 'Ressource wiederherstellen', 'resource_dialog.commands.mark_resolved_obj.title': 'Parallele Änderungen an der Ressource überschreiben', 'resource_dialog.commands.mark_resolved_obj.dialog.description': 'Diese Ressource wurde in einer anderen, inzwischen veröffentlichten Arbeitskopie geändert. Bitte bestätigen Sie, dass Ihre Änderungen erhalten und die parallel durchgeführten Änderungen verworfen werden.', 'resource_dialog.commands.delete_obj.title': 'Ressource löschen', 'resource_dialog.commands.delete_obj.dialog.title': 'Wirklich diese Ressource löschen?', 'resource_dialog.commands.delete_obj.dialog.description': 'Änderungen an einer gelöschten Ressource können nicht wiederhergestellt werden.', 'menu_bar.loading_workspaces': 'Lade Arbeitskopien', 'menu_bar.create': 'Anlegen', 'menu_bar.move': 'Verschieben', 'menu_bar.copy': 'Kopieren', 'saving_indicator_item.saving': 'Wird gespeichert...', 'saving_indicator_item.saved': 'Änderungen gespeichert', 'menu_bar_warning.warning': 'JS-Konsole überprüfen', 'menu_bar_warning.open_console': 'Es gibt Warnhinweise. Bitte öffnen Sie die JavaScript-Konsole, um Details zu erfahren.', 'menu_bar_conflict_indicator.conflict_description': 'Eine andere Version dieser Seite wurde zwischenzeitlich veröffentlicht. Lösen Sie den Konflikt, um diese Arbeitskopie veröffentlichen zu können.', 'menu_bar_conflict_indicator.conflict_headline': 'Konflikt', 'menu_bar_conflict_indicator.outdated_description': 'Eine neue Version dieser Seite wurde veröffentlicht. Aktualisieren Sie diese Arbeitskopie jetzt, um einen Konflikt zu vermeiden.', 'menu_bar_conflict_indicator.outdated_headline': 'Neue Version', 'menu_bar_conflict_indicator.warn_description': 'Änderungen an dieser Seite führen beim Veröffentlichen zu einem Konflikt. Die Seite wurde bereits in folgenden Arbeitskopien geändert:', 'menu_bar_conflict_indicator.warn_headline': 'Potenzieller Konflikt', 'menu_bar_device_toggle.description': 'Vorschaugröße', 'menu_bar_device_toggle.command.title.mobile': 'Mobiltelefon im Hochformat', 'menu_bar_device_toggle.command.title.tablet': 'Tablet im Hochformat', 'menu_bar_device_toggle.command.title.laptop': 'Laptop', 'menu_bar_device_toggle.command.title.desktop': 'Desktop', 'menu_bar_device_toggle.command.disabled': 'Aktuell ausgewählte Größe', 'inplace_marker.overlapping': 'Zwei oder mehrere Menü-Handles überschneiden sich. Bitte passen Sie Ihr CSS an. Die folgenden Menü-Handles überschneiden sich:', 'widget_marker.widget_is_new': 'Widget ist neu', 'widget_marker.widget_is_edited': 'Widget wurde geändert', 'widget_marker.widget_is_edited_and_dragged_here': 'Widget wurde geändert und hierher gezogen', 'widget_marker.widget_is_edited_and_dragged_away': 'Widget wurde geändert und von hier weggezogen', 'widget_marker.widget_is_deleted': 'Widget wurde gelöscht', 'widget_marker.widget_is_dragged_here': 'Widget wurde hierher gezogen', 'widget_marker.widget_is_dragged_away': 'Widget wurde von hier weggezogen', 'child_list_menu.description': 'Elemente von $1', 'changes_dialog.title': 'Änderungen von "$1"', 'changes_dialog.empty': 'In dieser Arbeitskopie wurde nichts geändert.', 'changes_dialog.more': 'Mehr...', 'changes_dialog.modification': 'Änderung', 'changes_dialog.rights': 'Veröffentlichen erlaubt', 'changes_dialog.description_for_editor': 'Titel', 'changes_dialog.obj_class': 'Typ', 'changes_dialog.last_changed': 'Letzte Änderung', 'changes_dialog.open_transfer_dialog': 'Änderungen verschieben', 'transfer_changes_dialog.title': 'Inhalte mit zu verschiebenden Änderungen auswählen', 'transfer_changes_dialog.select_transfer_target': 'Ziel-Arbeitskopie auswählen', 'transfer_changes_dialog.back': 'Zurück', 'transfer_changes_dialog.modification': 'Änderung', 'transfer_changes_dialog.rights': 'Veröffentlichen erlaubt', 'transfer_changes_dialog.description_for_editor': 'Titel', 'transfer_changes_dialog.obj_class': 'Typ', 'transfer_changes_dialog.last_changed': 'Letzte Änderung', 'transfer_errors_dialog.title': 'Fehler beim Verschieben von Änderungen', 'transfer_errors_dialog.modified': 'Einige der Änderungen konnten nicht verschoben werden, weil die betreffenden Inhalte auch in der Ziel-Arbeitskopie modifiziert wurden.', 'transfer_errors_dialog.conflicting': 'Einige der Änderungen wurden nicht verschoben, weil die betreffenden Inhalte in der Ziel-Arbeitskopie nicht aktuell sind. Die Änderungen auf diese Inhalte anzuwenden, würde zu einem Konflikt führen. Bitte stellen Sie sicher, dass beide Arbeitskopien aktualisiert wurden und konfliktfrei sind.', 'current_page_link_dialog.title': 'Diese Seite teilen', 'current_page_link_dialog.description': 'Mit dieser URL können Sie die aktuelle Seite als Teil dieser Arbeitskopie teilen. Die Empfänger müssen angemeldet sein und Zugriff auf die Arbeitskopie haben.', 'error_dialog.toggle_details': 'Technische Details', 'error_dialog.error_details': 'Technische Details', 'commands.current_page_link.title': 'Diese Seite teilen', 'commands.current_page_link.is_deleted': 'Eine gelöschte Seite kann nicht geteilt werden, weil sie in der Vorschau nicht zugänglich ist', 'commands.create_workspace.forbidden': 'Eine Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht angelegt werden.', 'commands.create_workspace.title': 'Arbeitskopie anlegen', 'commands.create_workspace.dialog.title': 'Arbeitskopie anlegen', 'commands.create_workspace.dialog.description': 'Bitte geben Sie den Titel der neuen Arbeitskopie ein.', 'commands.create_workspace.dialog.placeholder': 'Neuer Titel', 'commands.create_workspace.dialog.accept': 'Anlegen', 'commands.publish_history.title': 'Veröffentlichungsverlauf anzeigen', 'commands.open_user_guide.title': 'Hilfe öffnen', 'commands.rename_workspace.forbidden': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht umbenannt werden.', 'commands.rename_workspace.title': 'Umbenennen', 'commands.rename_workspace.dialog.title': '"$1" umbenennen', 'commands.rename_workspace.dialog.description': 'Bitte geben Sie den neuen Titel der Arbeitskopie ein.', 'commands.rename_workspace.dialog.accept': 'Umbenennen', 'commands.rebase_workspace.forbidden': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht aktualisiert werden.', 'commands.rebase_workspace.title': 'Aktualisieren', 'commands.rebase_workspace.tooltip': 'Arbeitskopie "$1" is veraltet. Bitte aktualisieren Sie sie.', 'commands.rebase_workspace.uptodate': 'Arbeitskopie "$1" muss nicht aktualisiert werden.', 'commands.rebase_workspace.has_conflicts.title': 'Geänderte Inhalte wurden zwischenzeitlich veröffentlicht', 'commands.rebase_workspace.has_conflicts.description': 'Ihre Arbeitskopie konnte nicht vollständig aktualisiert werden. Einige Inhalte wurden auch in einer anderen Arbeitskopie geändert, die inzwischen veröffentlicht wurde. Bitte entnehmen Sie die Details der Liste der Änderungen.', 'commands.rebase_workspace.open_changes_dialog': 'Änderungen anzeigen', 'commands.delete_workspace.forbidden': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht gelöscht werden.', 'commands.delete_workspace.title': 'Löschen', 'commands.delete_workspace.dialog.title': 'Wirklich "$1" löschen?', 'commands.delete_workspace.dialog.description': 'Eine gelöschte Arbeitskopie kann nicht wiederhergestellt werden.', 'commands.delete_workspace.dialog.confirm': 'Löschen', 'commands.restore_workspace.dialog.confirm': 'Anlegen', 'commands.restore_workspace.dialog.description': 'Dies legt eine Arbeitskopie an, die den archivierten Stand Ihrer Website enthält, nachdem "$1" veröffentlicht wurde.', 'commands.restore_workspace.dialog.title': '"$1" anlegen?', 'commands.restore_workspace.workspace_title': 'Archiviert: $1', 'commands.workspace_settings.forbidden': 'Die Einstellungen der Arbeitskopie können aufgrund fehlender Benutzerrechte nicht bearbeitet werden.', 'commands.workspace_settings.title': 'Einstellungen bearbeiten', 'commands.workspace_settings.dialog.title': 'Einstellungen von "$1"', 'commands.workspace_changes.title': 'Änderungen anzeigen', 'commands.obj_details.title_edit': 'Seiteneigenschaften bearbeiten', 'commands.obj_details.title_view': 'Seiteneigenschaften anzeigen', 'commands.obj_details.dialog.title_edit': 'Eigenschaften von "$1" bearbeiten', 'commands.obj_details.dialog.title_view': 'Eigenschaften von "$1" anzeigen', 'commands.save_obj_to_clipboard.title': 'Seite kopieren oder verschieben', 'commands.save_obj_to_clipboard.has_children': 'Seiten mit Unterseiten können noch nicht verschoben oder kopiert werden.', 'commands.delete_obj.title': 'Seite löschen', 'commands.delete_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden.', 'commands.delete_obj.has_children': 'Seiten mit Unterseiten können noch nicht gelöscht werden.', 'commands.delete_obj.dialog.title': 'Wirklich diese Seite löschen?', 'commands.delete_obj.dialog.description': 'Änderungen an einer gelöschten Seite können nicht wiederhergestellt werden.', 'commands.delete_obj.dialog.confirm': 'Löschen', 'commands.revert_obj.title': 'Änderungen an Seite verwerfen', 'commands.revert_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden. Daher gibt es nichts zu verwerfen.', 'commands.revert_obj.is_new': 'Dies ist eine neue Seite. Um die Erstellung dieser Seite rückgängig zu machen, löschen Sie sie bitte.', 'commands.revert_obj.unmodified': 'Diese Seite wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'commands.revert_obj.dialog.title': 'Wirklich Änderungen an dieser Seite verwerfen?', 'commands.revert_obj.dialog.description': 'Verworfene Änderungen können nicht wiederhergestellt werden.', 'commands.revert_obj.dialog.confirm': 'Verwerfen', 'commands.revert_resource.title': 'Änderungen an Ressource verwerfen', 'commands.revert_resource.is_new': 'Dies ist eine neue Ressource. Um die Erstellung dieser Ressource rückgängig zu machen, löschen Sie sie bitte.', 'commands.revert_resource.unmodified': 'Diese Ressource wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'commands.revert_resource.dialog.title': 'Wirklich Änderungen an dieser Ressource verwerfen?', 'commands.revert_resource.dialog.description': 'Verworfene Änderungen können nicht wiederhergestellt werden.', 'commands.revert_resource.dialog.confirm': 'Verwerfen', 'commands.revert_widget.title': 'Änderungen am Widget verwerfen', 'commands.revert_widget.is_new': 'Dies ist ein neues Widget. Um die Erstellung dieses Widgets rückgängig zu machen, löschen Sie es bitte.', 'commands.revert_widget.is_not_modified': 'Dieses Widget wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'commands.revert_widget.dialog.title': 'Wirklich Änderungen an diesem Widget verwerfen?', 'commands.revert_widget.dialog.description': 'Verworfene Änderungen können nicht wiederhergestellt werden.', 'commands.revert_widget.dialog.confirm': 'Verwerfen', 'commands.restore_widget.title': 'Widget wiederherstellen', 'commands.restore_obj.title': 'Seite wiederherstellen', 'commands.mark_resolved_obj.title': 'Parallele Änderungen an der Seite überschreiben', 'commands.mark_resolved_obj.dialog.title': 'Wirklich parallele Änderungen an der Seite überschreiben?', 'commands.mark_resolved_obj.dialog.description': 'Diese Seite wurde in einer anderen, inzwischen veröffentlichten Arbeitskopie geändert. Bitte bestätigen Sie, dass Ihre Änderungen erhalten und die parallel durchgeführten Änderungen verworfen werden.', 'commands.mark_resolved_obj.dialog.confirm': 'Änderungen überschreiben', 'commands.duplicate_obj.title': 'Seite duplizieren', 'commands.duplicate_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden.', 'commands.duplicate_obj.has_children': 'Seiten mit Unterseiten können noch nicht dupliziert werden.', 'commands.duplicate_widget.title': 'Widget duplizieren', 'commands.create_page.title': 'Neue Seite', 'commands.create_page.published_workspace': 'Verwenden Sie eine Arbeitskopie, um Seiten anzulegen oder bestehende Inhalte zu ändern.', 'commands.create_page.deleted_mode': 'Sie können keine Seiten anlegen, während gelöschte Inhalte angezeigt werden.', 'commands.add_subpage.title': 'Seite hinzufügen', 'commands.add_subpage.tooltip': 'Seite zu "$1" hinzufügen', 'commands.copy_obj_from_clipboard.title': 'Markierte Seite hierher kopieren', 'commands.copy_obj_from_clipboard.paste_forbidden': 'Aufgrund ihres Typs kann die Seite hier nicht eingefügt werden. Nur Seiten der folgenden Typen können hierher verschoben oder kopiert werden: $1', 'commands.move_obj_from_clipboard.title': 'Markierte Seite hierher verschieben', 'commands.move_obj_from_clipboard.paste_forbidden': 'Aufgrund ihres Typs kann die Seite hier nicht eingefügt werden. Nur Seiten der folgenden Typen können hierher verschoben oder kopiert werden: $1', 'commands.move_obj_from_clipboard.source_not_found': 'Das Objekt, welches verschoben werden soll, konnte in der aktuellen Arbeitskopie nicht gefunden werden.', 'obj_sorting_dialog.title': 'Elemente sortieren', 'commands.sort_items.title': 'Elemente sortieren', 'commands.sort_items.tooltip': 'Reihenfolge der Elemente unterhalb $1 bearbeiten', 'commands.sort_items.auto_sort': 'Diese Navigation wird automatisch sortiert.', 'commands.sort_items.too_less_children': 'Die Navigation kann nicht sortiert werden, weil sie weniger als zwei Elemente enthält.', 'commands.select_workspace.x_and_1_owner': '$1 und 1 weiterer Besitzer', 'commands.select_workspace.x_and_n_owners': '$1 und $2 weitere Besitzer', 'commands.select_workspace.disabled': 'Diese Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht ausgewählt werden', 'commands.choose_and_create_widget.title': 'Widget einfügen', 'commands.choose_and_create_widget.disabled': 'Sie können hier keine Widgets einfügen.', 'commands.create_widget.title': '$1 einfügen', 'commands.widget_details.title': 'Widget-Eigenschaften', 'commands.widget_details.no_details_view': 'Dieses Widget hat keine Eigenschaften', 'commands.widget_details.dialog.title': 'Eigenschaften von "$1"', 'commands.save_widget_to_clipboard.title': 'Widget kopieren', 'commands.copy_widget_from_clipboard.title': 'Widget einfügen', 'commands.copy_widget_from_clipboard.paste_forbidden': 'Aufgrund seines Typs kann das Widget hier nicht eingefügt werden. Nur Widgets der folgenden Typen können hierher verschoben oder kopiert werden: $1.', 'commands.delete_widget.title': 'Widget löschen', 'commands.delete_widget.dialog.title': 'Wirklich dieses Widget löschen?', 'commands.delete_widget.dialog.description': 'Ein gelöschtes Widget kann nicht wiederhergestellt werden.', 'commands.delete_widget.dialog.confirm': 'Löschen', 'commands.switch_mode.view': 'Vorschau', 'commands.switch_mode.editing': 'Bearbeiten', 'commands.switch_mode.diff': 'Vergleichen', 'commands.switch_mode.added': 'Hinzugefügt', 'commands.switch_mode.deleted': 'Gelöscht', 'commands.switch_mode.disabled': 'Aktuell ausgewählter Anzeigemodus', 'commands.publish_workspace.title': 'Veröffentlichen', 'commands.publish_workspace.permission_denied': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht veröffentlicht werden.', 'commands.publish_workspace.dialog.confirm': 'Veröffentlichen', 'commands.publish_workspace.dialog.title': '"$1" veröffentlichen?', 'commands.publish_workspace.dialog.description': 'Sie können diese Veröffentlichung mit Hilfe des Veröffentlichungsverlaufs rückgängig machen.', 'commands.publish_workspace.error_dialog.title': 'Arbeitskopie konnte nicht veröffentlicht werden', 'commands.publish_workspace.error_dialog.description': 'Bitte entnehmen Sie die Details der Liste der Änderungen.', 'commands.publish_workspace.error_dialog.confirm': 'Liste der Änderungen', 'commands.publish_workspace.alert.invalid_certificates': 'Die Arbeitskopie konnte nicht veröffentlicht werden, weil mindestens ein Benutzer gerade Inhalte darin ändert.', 'ajax_error': 'Die Kommunikation mit dem CMS ist aufgrund eines Fehlers fehlgeschlagen: $1', 'ajax_error.communication': 'Die Kommunikation mit dem CMS ist fehlgeschlagen. Bitte überprüfen Sie Ihre Netzwerkverbindung.', 'ajax_error.message_for_editor': 'Bei Ihrer letzten Aktion ist ein technischer Fehler aufgetreten. Bitte versuchen Sie es später noch einmal. Falls das Problem bestehen bleibt, wenden Sie sich bitte an Ihren technischen Ansprechpartner für diese Website und geben Sie bitte die technischen Details an.', 'workspace_limit_exceeded.message': 'In Ihrem Tarif sind keine weiteren Arbeitskopien verfügbar.', 'warn_before_unloading': 'Es gibt nicht gespeicherte Änderungen! Möchten Sie das Browserfenster trotzdem schließen?', 'widgetlist_field_element.markup_error': 'Scrivito hat festgestellt, dass eines der Widgets invalides Markup aufweist. Bitte laden Sie die Seite neu und versuchen Sie es noch einmal. Falls das Problem bestehen bleibt, wenden Sie sich bitte an Ihren technischen Ansprechpartner für diese Website.' }, 'de'); $.i18n().load({ 'confirm': 'Confirm', 'cancel': 'Cancel', 'save': 'Save', 'welcome': 'Welcome', 'welcome_x': 'Welcome $1', 'accept': 'Accept', 'close': 'Close', 'done': 'Done', 'loading': 'Loading...', 'current_page': 'current page', 'ok': 'Ok', 'obj.tooltip.is_new': 'This page is new.', 'obj.tooltip.is_edited': 'This page has been modified.', 'obj.tooltip.is_deleted': 'This page has been deleted.', 'workspace.title_published': 'Published content', 'workspace.empty_title': '', 'workspace.publish_error.exceeds_obj_limit': 'This working copy cannot be published because the maximum number of CMS objects included in your plan has been exceeded.', 'workspace_settings_dialog.owners': 'Owners', 'workspace_settings_dialog.nothing_found': 'Nothing found', 'workspace_settings_dialog.searching': 'Searching...', 'workspace_settings_dialog.too_short': 'Find user...', 'workspace_select.this_workspace': 'This working copy', 'workspace_select.other_workspaces': 'Other working copies', 'menu_item.spinner.loading': 'Loading...', 'choose_obj_class_dialog.add_child_page.title': 'Select Page Type', 'choose_obj_class_dialog.create_page.title': 'Select Page Type', 'choose_obj_class_dialog.create_widget.title': 'Select Widget', 'choose_obj_class_dialog.last_used': 'Last used', 'choose_obj_class_dialog.popular': 'Often used', 'choose_obj_class_dialog.all': 'All', 'editable_ws_dialog.view_mode.title.select_or_create': 'Choose a working copy', 'editable_ws_dialog.view_mode.title.select': 'Select a working copy', 'editable_ws_dialog.view_mode.title.create': 'Create a working copy', 'editable_ws_dialog.view_mode.title.forbidden': 'No working copy available', 'editable_ws_dialog.view_mode.description.select_or_create': 'To alter content, select or create a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.view_mode.description.select': 'To alter content, select a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.view_mode.description.create': 'To alter content, create a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.view_mode.description.forbidden': 'There is no working copy you could use to alter content. Also, creating working copies has not been enabled for you.', 'editable_ws_dialog.transfer_changes.title.select_or_create': 'Select target working copy', 'editable_ws_dialog.transfer_changes.title.select': 'Select target working copy', 'editable_ws_dialog.transfer_changes.title.create': 'Create target working copy', 'editable_ws_dialog.transfer_changes.title.forbidden': 'No working copy available', 'editable_ws_dialog.transfer_changes.description.select_or_create': 'The changes can be moved to an existing working copy or to a new one.', 'editable_ws_dialog.transfer_changes.description.select': 'The changes will be moved to the selected working copy.', 'editable_ws_dialog.transfer_changes.description.create': 'Please create the target working copy', 'editable_ws_dialog.transfer_changes.description.forbidden': 'You are not permitted to move changes to one of the available working copies.', 'editable_ws_dialog.choose_existing': 'Select an existing working copy:', 'editable_ws_dialog.create_new': 'Create a new working copy:', 'editable_ws_dialog.or_create_new': 'Or, create a new one:', 'editable_ws_dialog.create_new_playholder': 'new working copy title', 'editable_ws_dialog.select': 'Select', 'publish_history_dialog.changes_count': 'Changed', 'publish_history_dialog.changes_count.not_available': 'Not available', 'publish_history_dialog.changes_count.one': '1 object', 'publish_history_dialog.changes_count.many': '$1 objects', 'publish_history_dialog.close': 'Close', 'publish_history_dialog.error': 'An error occurred while retrieving the publishing history. Please try again later. If the problem persists, contact a technician familiar with this website.', 'publish_history_dialog.not_restorable': 'This is the currently published content.', 'publish_history_dialog.published_at': 'Published ', 'publish_history_dialog.title': 'Publishing history', 'publish_history_dialog.info': 'Pick a working copy from the list to view an archived state of your website. Learn more about the ', 'publish_history_dialog.link': 'publishing history', 'publish_history_dialog.is_limited': 'Displaying only $1 history items. Upgrade your account if you want to see more.', 'resource_dialog.title': 'Properties of resource "$1"', 'resource_dialog.commands.restore_obj.title': 'Restore resource', 'resource_dialog.commands.mark_resolved_obj.title': 'Override concurrent changes to resource', 'resource_dialog.commands.mark_resolved_obj.dialog.description': 'This resource was altered in a different working copy that has been published. Please confirm that you want to keep your changes and discard the ones concurrently made by others.', 'resource_dialog.commands.delete_obj.title': 'Delete resource', 'resource_dialog.commands.delete_obj.dialog.title': 'Really delete this resource?', 'resource_dialog.commands.delete_obj.dialog.description': 'Changes to a deleted resource cannot be restored.', 'menu_bar.loading_workspaces': 'Loading working copies', 'menu_bar.create': 'Create', 'menu_bar.move': 'Move', 'menu_bar.copy': 'Copy', 'saving_indicator_item.saving': 'Saving...', 'saving_indicator_item.saved': 'Changes saved', 'menu_bar_warning.warning': 'Check JS console', 'menu_bar_warning.open_console': 'There are warnings. Please open the JavaScript console for details.', 'menu_bar_conflict_indicator.conflict_description': 'A different version of this page has been published in the meantime. Resolve the conflict to be able to publish this working copy.', 'menu_bar_conflict_indicator.conflict_headline': 'Conflict', 'menu_bar_conflict_indicator.outdated_description': 'A new version of this page has been published. Update this working copy now to avoid a conflict.', 'menu_bar_conflict_indicator.outdated_headline': 'New version', 'menu_bar_conflict_indicator.warn_description': 'Changes to this page will cause a conflict when publishing. The page has already been modified in these working copies:', 'menu_bar_conflict_indicator.warn_headline': 'Potential conflict', 'menu_bar_device_toggle.description': 'Preview size', 'menu_bar_device_toggle.command.title.mobile': 'Mobile phone, portrait', 'menu_bar_device_toggle.command.title.tablet': 'Tablet, portrait', 'menu_bar_device_toggle.command.title.laptop': 'Laptop', 'menu_bar_device_toggle.command.title.desktop': 'Desktop', 'menu_bar_device_toggle.command.disabled': 'Currently selected size', 'inplace_marker.overlapping': 'Two or more menu handles are overlapping. Please adjust your CSS. The following menu handles are overlapping:', 'widget_marker.widget_is_new': 'Widget is new', 'widget_marker.widget_is_edited': 'Widget has been modified', 'widget_marker.widget_is_edited_and_dragged_here': 'Widget has been modified and dragged here', 'widget_marker.widget_is_edited_and_dragged_away': 'Widget has been modified and dragged away from here', 'widget_marker.widget_is_deleted': 'Widget has been deleted', 'widget_marker.widget_is_dragged_here': 'Widget has been dragged here', 'widget_marker.widget_is_dragged_away': 'Widget has been dragged away from here', 'child_list_menu.description': 'Items of $1', 'changes_dialog.title': 'Changes to "$1"', 'changes_dialog.empty': 'Nothing was changed in this working copy.', 'changes_dialog.more': 'More...', 'changes_dialog.modification': 'Change', 'changes_dialog.rights': 'Publishing permitted', 'changes_dialog.description_for_editor': 'Title', 'changes_dialog.obj_class': 'Type', 'changes_dialog.last_changed': 'Last change', 'changes_dialog.open_transfer_dialog': 'Move changes', 'transfer_changes_dialog.title': 'Select content changes to be moved', 'transfer_changes_dialog.select_transfer_target': 'Select target working copy', 'transfer_changes_dialog.back': 'Back', 'transfer_changes_dialog.modification': 'Change', 'transfer_changes_dialog.rights': 'Publishing permitted', 'transfer_changes_dialog.description_for_editor': 'Title', 'transfer_changes_dialog.obj_class': 'Type', 'transfer_changes_dialog.last_changed': 'Last change', 'transfer_errors_dialog.title': 'Errors while moving content changes', 'transfer_errors_dialog.modified': 'Some of the changes could not be moved because the content concerned has also been modified in the target working copy.', 'transfer_errors_dialog.conflicting': 'Some of the changes have not been moved because the respective content in the target working copy is outdated and applying changes to it would cause a conflict. Please make sure that both working copies have been updated and are free of conflicts.', 'current_page_link_dialog.title': 'Share this page', 'current_page_link_dialog.description': 'Using the URL below, you can share the current page as part of this working copy. The recipients need to be logged in and have access to the working copy.', 'error_dialog.toggle_details': 'Toggle details', 'error_dialog.error_details': 'Error details', 'commands.current_page_link.title': 'Share this page', 'commands.current_page_link.is_deleted': 'A deleted page cannot be shared because it is inaccessible in preview mode', 'commands.create_workspace.forbidden': 'You cannot create a workspace due to missing user permissions.', 'commands.create_workspace.title': 'Create working copy', 'commands.create_workspace.dialog.title': 'Create working copy', 'commands.create_workspace.dialog.description': 'Please enter the title of the new working copy.', 'commands.create_workspace.dialog.placeholder': 'new title', 'commands.create_workspace.dialog.accept': 'Create', 'commands.publish_history.title': 'Show publishing history', 'commands.open_user_guide.title': 'Open help', 'commands.rename_workspace.forbidden': 'You cannot rename the workspace due to missing user permissions.', 'commands.rename_workspace.title': 'Rename', 'commands.rename_workspace.dialog.title': 'Rename "$1"', 'commands.rename_workspace.dialog.description': 'Please enter the new title of the working copy.', 'commands.rename_workspace.dialog.accept': 'Rename', 'commands.rebase_workspace.forbidden': 'You cannot rebase the workspace due to missing user permissions.', 'commands.rebase_workspace.title': 'Update', 'commands.rebase_workspace.tooltip': 'Working copy "$1" is outdated. Please update it.', 'commands.rebase_workspace.uptodate': 'Working copy "$1" is up to date.', 'commands.rebase_workspace.has_conflicts.title': 'Changed content has been published intermediately', 'commands.rebase_workspace.has_conflicts.description': 'Your working copy could not be fully updated. Some of its content has also been altered in a different working copy that has been published in the meantime. Please refer to the changes list for details.', 'commands.rebase_workspace.open_changes_dialog': 'Show changes', 'commands.delete_workspace.forbidden': 'You cannot delete the workspace due to missing user permissions.', 'commands.delete_workspace.title': 'Delete', 'commands.delete_workspace.dialog.title': 'Really delete "$1"?', 'commands.delete_workspace.dialog.description': 'A deleted working copy cannot be restored.', 'commands.delete_workspace.dialog.confirm': 'Delete', 'commands.restore_workspace.dialog.confirm': 'Create', 'commands.restore_workspace.dialog.description': 'This creates a working copy that reflects the archived state of your website after "$1" was published.', 'commands.restore_workspace.dialog.title': 'Create "$1"?', 'commands.restore_workspace.workspace_title': 'Archived: $1', 'commands.workspace_settings.forbidden': 'You cannot change the settings of the workspace due to missing user permissions.', 'commands.workspace_settings.title': 'Edit settings', 'commands.workspace_settings.dialog.title': 'Settings for "$1"', 'commands.workspace_changes.title': 'Show changes', 'commands.obj_details.title_edit': 'Edit page properties', 'commands.obj_details.title_view': 'View page properties', 'commands.obj_details.dialog.title_edit': 'Edit properties of "$1"', 'commands.obj_details.dialog.title_view': 'View properties of "$1"', 'commands.save_obj_to_clipboard.title': 'Copy or move page', 'commands.save_obj_to_clipboard.has_children': 'Pages with subpages cannot be copied or moved yet.', 'commands.delete_obj.title': 'Delete page', 'commands.delete_obj.published_workspace': 'Since this is the published content, nothing can be modified.', 'commands.delete_obj.has_children': 'Pages with subpages cannot be deleted yet.', 'commands.delete_obj.dialog.title': 'Really delete this page?', 'commands.delete_obj.dialog.description': 'Changes to a deleted page cannot be restored.', 'commands.delete_obj.dialog.confirm': 'Delete', 'commands.revert_obj.title': 'Discard changes to page', 'commands.revert_obj.published_workspace': 'Since this is the published content, nothing has been modified. Therefore, nothing can be discarded.', 'commands.revert_obj.is_new': 'This is a new page. To discard the creation of this page, please delete it.', 'commands.revert_obj.unmodified': 'This page has not been modified. Therefore, nothing can be discarded.', 'commands.revert_obj.dialog.title': 'Really discard changes to this page?', 'commands.revert_obj.dialog.description': 'Discarded changes cannot be restored.', 'commands.revert_obj.dialog.confirm': 'Discard', 'commands.revert_resource.title': 'Discard changes to resource', 'commands.revert_resource.is_new': 'This is a new resource. To discard the creation of this resource, please delete it.', 'commands.revert_resource.dialog.title': 'Really discard changes to this resource?', 'commands.revert_resource.dialog.description': 'Discarded changes cannot be restored.', 'commands.revert_resource.dialog.confirm': 'Discard', 'commands.revert_widget.title': 'Discard changes to widget', 'commands.revert_widget.is_new': 'This is a new widget. To discard the creation of this widget, please delete it.', 'commands.revert_widget.is_not_modified': 'This widget has not been modified. Therefore, nothing can be discarded.', 'commands.revert_widget.dialog.title': 'Really discard changes to this widget?', 'commands.revert_widget.dialog.description': 'Discarded changes cannot be restored.', 'commands.revert_widget.dialog.confirm': 'Discard', 'commands.restore_widget.title': 'Restore widget', 'commands.restore_obj.title': 'Restore page', 'commands.mark_resolved_obj.title': 'Override concurrent changes to page', 'commands.mark_resolved_obj.dialog.confirm': 'Override changes', 'commands.mark_resolved_obj.dialog.title': 'Really override changes made by others in the meantime?', 'commands.mark_resolved_obj.dialog.description': 'This page was altered in a different working copy that has been published. Please confirm that you want to keep your changes and discard the ones concurrently made by others.', 'commands.duplicate_obj.title': 'Duplicate page', 'commands.duplicate_obj.published_workspace': 'Since this is the published content, nothing can be modified.', 'commands.duplicate_obj.has_children': 'Pages with subpages cannot be duplicated yet.', 'commands.duplicate_widget.title': 'Duplicate widget', 'commands.create_page.title': 'Create page', 'commands.create_page.published_workspace': 'Use a working copy for creating pages or editing existing content.', 'commands.create_page.deleted_mode': 'You cannot create pages while deleted content is being displayed.', 'commands.add_subpage.title': 'Add page', 'commands.add_subpage.tooltip': 'Add page to "$1"', 'commands.copy_obj_from_clipboard.title': 'Copy marked page here', 'commands.copy_obj_from_clipboard.paste_forbidden': 'Due to its type, the page cannot be moved or copied here. Only pages of the following types can be inserted here: $1', 'commands.move_obj_from_clipboard.title': 'Move marked page here', 'commands.move_obj_from_clipboard.paste_forbidden': 'Due to its type, the page cannot be moved or copied here. Only pages of the following types can be inserted here: $1', 'commands.move_obj_from_clipboard.source_not_found': 'Object to move could not be found in the current working copy.', 'obj_sorting_dialog.title': 'Sort items', 'commands.sort_items.title': 'Sort items', 'commands.sort_items.tooltip': 'Edit order of items underneath $1', 'commands.sort_items.auto_sort': 'This navigation is sorted automatically.', 'commands.sort_items.too_less_children': 'This navigation cannot be sorted because it consists of less than two items.', 'commands.select_workspace.x_and_1_owner': '$1 and 1 other owner', 'commands.select_workspace.x_and_n_owners': '$1 and $2 other owners', 'commands.select_workspace.disabled': 'This working copy can not be selected due to missing user permissions.', 'commands.choose_and_create_widget.title': 'Insert widget', 'commands.choose_and_create_widget.disabled': 'You cannot insert any widgets here.', 'commands.create_widget.title': 'Insert $1', 'commands.widget_details.title': 'Widget properties', 'commands.widget_details.no_details_view': 'This widget has no properties', 'commands.widget_details.dialog.title': 'Properties of "$1"', 'commands.save_widget_to_clipboard.title': 'Copy widget', 'commands.copy_widget_from_clipboard.title': 'Paste widget', 'commands.copy_widget_from_clipboard.paste_forbidden': 'Due to its type, the widget cannot be moved or copied here. Only widgets of the following types can be inserted here: $1.', 'commands.delete_widget.title': 'Delete widget', 'commands.delete_widget.dialog.title': 'Really delete this widget?', 'commands.delete_widget.dialog.description': 'A deleted widget cannot be restored.', 'commands.delete_widget.dialog.confirm': 'Delete', 'commands.switch_mode.view': 'Preview', 'commands.switch_mode.editing': 'Edit', 'commands.switch_mode.diff': 'All changes', 'commands.switch_mode.added': 'Additions', 'commands.switch_mode.deleted': 'Deletions', 'commands.switch_mode.disabled': 'Currently selected display mode', 'commands.publish_workspace.title': 'Publish', 'commands.publish_workspace.permission_denied': 'The working copy can not be published due to missing user permissions.', 'commands.publish_workspace.dialog.confirm': 'Publish', 'commands.publish_workspace.dialog.title': 'Publish "$1"?', 'commands.publish_workspace.dialog.description': 'You can undo this publishing action using the publishing history.', 'commands.publish_workspace.error_dialog.title': 'Working copy could not be published', 'commands.publish_workspace.error_dialog.description': 'Please check the changes list for details.', 'commands.publish_workspace.error_dialog.confirm': 'Open changes list', 'commands.publish_workspace.alert.invalid_certificates': 'The working copy could not be published because at least one user is currently modifying content in it.', 'ajax_error': 'Communication with the CMS failed with error: $1', 'ajax_error.communication': 'Communication with the CMS failed. Please check your network connectivity.', 'ajax_error.message_for_editor': 'During your last action, a technical error occurred. Please try again later. If the problem persists, please contact a technician familiar with this website and provide the error details.', 'workspace_limit_exceeded.message': 'You have reached the maximum number of working copies included in your plan.', 'warn_before_unloading': 'There are unsaved changes! Are you sure you want to close the page?', 'widgetlist_field_element.markup_error': 'Scrivito found a widget with invalid markup. Please reload the page and try again. If the problem persists, please contact a technician familiar with this website.', 'test.two_arguments': '$1, $2', 'test.four_arguments': '$1, $2, $3, $4' }, 'en'); var scrivito = {}; // jshint ignore:line (function() { var inited = false; var ui_config_attr_name = 'data-scrivito-private-ui-config'; var wait_until_write_ends = function() { var deferred = $.Deferred(); if (scrivito.write_monitor.is_writing()) { scrivito.write_monitor.on('end_write', function() { wait_until_write_ends().done(function() { deferred.resolve(); }); }); } else { deferred.resolve(); } return deferred; }; var convert_internal_error = function(error) { // message is the only field of an error that is public API return {message: error.message}; }; var restore_prior_attr = function(promise, dom_element, attr_name) { var prior_attr = dom_element.attr(attr_name); promise.always(function() { if (prior_attr) { dom_element.attr(attr_name, prior_attr); } else { // jQuery#removeAttr violates CSP by assigning an empty value. dom_element.get(0).removeAttribute(attr_name); } }); }; _.extend(scrivito, { suppress_alerts: false, popular_obj_classes: [], alert: function(message) { if (!scrivito.suppress_alerts) { window.alert(message); } }, warn: function() { if (scrivito.isDevelopmentMode) { scrivito.menu_bar_warning.show(); } if (window.console) { window.console.warn.apply(window.console, arguments); } }, logError: function() { if (window.console) { window.console.error.apply(window.console, arguments); } }, log_info: function() { if (window.console) { window.console.info.apply(window.console, arguments); } }, throw_error: function(message, options) { options = options || {}; var params = options.params || []; params.unshift(message); scrivito.logError.apply(null, params); if (options.description) { scrivito.alertDialog(options.description); } $.error(message); }, redirect_to: function(location, target_window) { wait_until_write_ends().done(function() { scrivito.change_location(location, target_window); }); return $.Deferred(); }, // For test purpose only. open: function() { window.open.apply(null, arguments); }, change_editing_context: function(params) { return scrivito.redirect_to(scrivito.editing_context.location(params).href()); }, open_obj: function(obj) { if (obj.is_binary() && ( obj.is_edited() || obj.is_new() && !scrivito.editing_context.is_deleted_mode() || obj.is_deleted() && scrivito.editing_context.is_deleted_mode())) { return scrivito.resource_dialog.open(obj); } else { var url = scrivito.root_path(); var params = {}; if (obj.is_binary()) { url = '/__scrivito/resource_details/'; params.return_to = document.URL; } if (obj.is_new() && scrivito.editing_context.is_deleted_mode()) { params._scrivito_display_mode = 'added'; } if (obj.is_deleted() && !scrivito.editing_context.is_deleted_mode()) { params._scrivito_display_mode = 'deleted'; } url += obj.id(); if (!_.isEmpty(params)) { url += '?'+$.param(params); } return scrivito.withSavingOverlay(scrivito.redirect_to(url)); } }, // For testing purpose only. location: function() { return window.location; }, // For testing purpose only. change_location: function(location, target_window) { (target_window || window).location = location; }, wait: function(seconds) { // this is a proxy method, so we can stub it easier. return scrivito.waitMs(seconds * 1000); }, waitMs: function(milliseconds) { // this is a proxy method, so we can stub it easier. return $.Deferred(function(dfd) { setTimeout(dfd.resolve, milliseconds); }); }, parseDate: function(dateString) { return scrivito.types.parseStringToDate(dateString); }, run_new_event: function(method) { scrivito.wait(0).done(method); }, reload: function(target_window) { wait_until_write_ends().done(function() { scrivito.reload_location(target_window); }); return $.Deferred(); }, // For testing purpose only. reload_location: function(target_window) { (target_window || window).location.reload(); }, center: function(elem) { if (elem.length === 1) { elem.css({ marginLeft: -elem.innerWidth() / 2, marginTop: -elem.innerHeight() / 2, left: '50%' }); } }, ensure_fully_visible_within: function(dom_element, viewport_container, viewport_height) { var viewport_offset = viewport_container.scrollTop(); var dom_element_offset = dom_element.offset().top; var dom_element_height = dom_element.height(); var scroll_top; if (viewport_offset > dom_element_offset) { scroll_top = dom_element_offset - 50; } else if (dom_element_offset + dom_element_height > viewport_offset + viewport_height) { scroll_top = dom_element_height + dom_element_offset + 50 - viewport_height; } if (scroll_top) { viewport_container.animate({scrollTop: scroll_top}); } }, ensure_fully_visible_within_window: function(dom_element) { var cms_document = scrivito.cms_document.from(dom_element); scrivito.ensure_fully_visible_within(dom_element, cms_document.dom_element().find('body'), $(cms_document.browser_window()).height() ); }, describe_element: function(elem) { var description = elem.get(0).nodeName; if (elem.attr("id")) { description += "#"+elem.attr("id"); } var css_class = elem.attr('class'); if (css_class) { _(css_class.split(" ")).each(function(class_name) { description += "."+class_name; }); } return "["+description+"]"; }, remove_enter_and_escape_action: function() { $(document).off('keyup.scrivito_enter_escape_action'); }, random_hex: function() { var hex = Math.floor(Math.random() * Math.pow(16, 8)).toString(16); while (hex.length < 8) { hex = '0' + hex; } return hex; }, // 16 chars hex string random_id: function() { return scrivito.random_hex() + scrivito.random_hex(); }, deprecation_warning: function(subject, alternative) { var message = 'DEPRECATION WARNING: "' + subject + '" is deprecated.'; if (alternative) { message += ' Please use "' + alternative + '" instead.'; } scrivito.warn(message); }, on: function(event, callback) { if (event === 'load') { scrivito.gui.on('open', function() { callback(); }); if (scrivito.gui.is_started()) { scrivito.run_new_event(function() { callback(); }); } } else if (event === 'content') { scrivito.gui.on('content', function(dom_element) { callback(dom_element); }); } else { $.error('Unknown event "' + event + '"'); } }, create_obj: function(attributes) { return scrivito.obj.create(attributes).then(function(obj) { return {id: obj.id()}; }, convert_internal_error); }, delete_obj: function(id) { if (id) { return scrivito.obj.create_instance({id: id}).destroy() .then(null, convert_internal_error); } else { $.error("Can't delete without ID"); } }, is_current_page_restricted: function() { var current_page = scrivito.application_document().page(); if (current_page) { return current_page.has_restriction(); } }, never_resolve: function() { return $.Deferred(); }, trigger: function(event_name, dom_element) { if (event_name === 'content') { _.each($(dom_element), function(e) { scrivito.gui.new_content(e); }); } else if (event_name === 'new_content') { scrivito.deprecation_warning( 'scrivito.trigger("new_content")', 'scrivito.trigger("content")'); scrivito.trigger('content', dom_element); } else { $.error('Unknown event "' + event_name + '"'); } }, in_editable_view: function() { return scrivito.editing_context.display_mode === 'editing' && scrivito.editing_context.visible_workspace.is_editable(); }, open_resource_dialog: function(obj_id) { return scrivito.resource_dialog.open(obj_id); }, // See http://underscorejs.org/#throttle throttle: function(fn, ms) { return scrivito.bypass_throttle ? fn : _.throttle(fn, ms); }, json_parse_base64: function(base64_string) { // See http://mzl.la/1p1zI9k. var dom_string = decodeURIComponent(window.escape(atob(base64_string))); return JSON.parse(dom_string); }, json_stringify_base64: function(object) { var dom_string = JSON.stringify(object); // See http://mzl.la/1p1zI9k. return btoa(window.unescape(encodeURIComponent(dom_string))); }, t: function() { return scrivito.i18n.translate.apply(null, arguments); }, // proxy function so that other gems need no knowledge of `cms_document` registerPublicApi: function() { return scrivito.cms_document.registerPublicApi.apply(this, arguments); }, is_inited: function() { return inited; }, application_document: function() { return scrivito.application_window.document(); }, root_path: function() { return scrivito.application_window.is_frame() ? '/scrivito/' : '/'; }, details_url_for_obj_id: function(id) { return scrivito.obj.create_instance({id: id}).details_src(); }, workspace_limit_exceeded: function() { scrivito.info_dialog(scrivito.t('workspace_limit_exceeded.message')); }, register_default_obj_class_for_content_type: function(mapping) { scrivito.obj_class_defaults.register(mapping); }, default_obj_class_for_content_type: function(content_type) { return scrivito.obj_class_defaults.lookup(content_type); }, pattern_sort: function(items, patterns) { if (patterns && patterns.length) { var results = []; _.each(patterns, function(pattern, index) { if (!pattern.match(/(.*)\.\*$/)) { var hit = _.find(items, function(item) { return item.id() === pattern; }); if (hit) { results[index] = hit; items = _.without(items, hit); } } }); _.each(patterns, function(pattern, index) { if (pattern.match(/(.*)\.\*$/)) { var hits = _.select(items, function(item) { return !item.id().indexOf(pattern.replace('.*', '')); }); if (hits.length) { results[index] = hits; items = _.difference(items, hits); } } }); return _.flatten(_.compact(results.concat(items))); } else { return items; } }, page_menu: function(cms_document) { return scrivito.menu_builder.create_instance(cms_document); }, custom_dialog: function(iframe, doc, content, options) { var dialog = scrivito.iframe_dialog.open(iframe, options); dialog.when_open.done(function(dialog_body) { var panel = scrivito.full_screen_panel(doc, dialog.when_closed); panel.css('background-color', dialog_body.css('background-color')); panel.append(content); }); return {when_closed: dialog.when_closed}; }, registerBrowseContent: function(browseContent) { scrivito.browseContent = browseContent; }, registerTranslations: function(locale, translations) { scrivito.i18n.load(locale, translations); }, translate: function() { return scrivito.i18n.translate.apply(null, arguments); }, ui_config: function() { return scrivito.dom_config.read($('body'), ui_config_attr_name); }, // For test purpose only. mock_ui_config: function(config) { if (config) { scrivito.dom_config.write($('body'), ui_config_attr_name, config); } else { $('body').removeAttr(ui_config_attr_name); } }, restore_styles_afterwards: function(promise, dom_element) { restore_prior_attr(promise, dom_element, 'class'); restore_prior_attr(promise, dom_element, 'style'); }, description_for_editor: function(obj_ids) { var chainable_search = scrivito.obj_where('id', 'equals', obj_ids) .batch_size(obj_ids.length).format('_default'); return chainable_search.load_batch().then(function(result) { return _.map(obj_ids, function(obj_id) { var hit = _.findWhere(result.hits, {id: obj_id}); return hit && hit.description_for_editor || null; }); }); }, isDevelopmentMode: false, init: function(config) { scrivito.config = config; scrivito.forgery_protection.init(); scrivito.editing_context.init(config.editing_context); scrivito.i18n.init(config.i18n); scrivito.resource_dialog.init(config.resource_dialog); scrivito.user.init(config.user); scrivito.user_permissions.init(config.user_permissions); scrivito.SessionKeeper.init(config.session); scrivito.CmsRestApi.init(config.backend_endpoint, config.tenant); scrivito.ObjClass.init(config.obj_class); scrivito.WidgetClass.init(config.widget_class); scrivito.Revision.init(config.revision); scrivito.ObjReplicationTracking.init(); scrivito.ObjQueryStore.init(); scrivito.isDevelopmentMode = config.is_development_mode; scrivito.inplace_marker.init(); scrivito.option_marker.init(); scrivito.menu_bar_saving_indicator.init(); scrivito.menu_bar_device_toggle.init(); scrivito.menu_bar_warning.init(); scrivito.menu_bar_display_mode_toggle.init(); scrivito.currentPageMenu.init(); scrivito.menuBarBrowseContent.init(); scrivito.menuBarConflictIndicator.init(); scrivito.current_page_restriction.init(); scrivito.workspace_select.init(); scrivito.menu_bar.init(); scrivito.editor_selection.init(); scrivito.child_list_commands.init(); scrivito.currentPageCommands.init(); scrivito.widget_commands.init(); scrivito.widgetlist_field_commands.init(); scrivito.child_list_marker.init(); scrivito.widgetlist_field_menu.init(); scrivito.widget_marker.init(); scrivito.context_menu.init(); scrivito.external_links.init(); scrivito.widget_reloading.init(); scrivito.no_turbolinks.init(); scrivito.reloading.init(); if (window.location.hash === '#__scrivito_enable_drag_n_drool') { scrivito.enableColDragDrool = true; } scrivito.dragDrool.init(); scrivito.dragScroll.init(); scrivito.widgetlistFieldPlaceholder.init(); window.onbeforeunload = scrivito.warn_before_unloading; scrivito.url_update(scrivito.application_window, scrivito.cms_window.from(window)); scrivito.application_window.use_fragment_of(scrivito.cms_window.from(window)); inited = true; } }); }()); 'use strict'; (function () { function provideAsyncInstanceMethods(klass, methods) { return provideAsyncMethods(klass.prototype, methods); } function provideAsyncMethods(klass, methods) { _.each(methods, function (asyncName, syncName) { klass[asyncName] = asyncMethodFor(syncName); }); } function asyncMethodFor(syncName) { return function asyncMethod() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return scrivito.PublicPromise.resolve(scrivito.loadAsync(function () { return _this[syncName].apply(_this, args); })); }; } function asyncMethodStub() { throw new scrivito.InternalError('this method is supposed to be overwritten by calling provideAsyncMethods'); } // export scrivito.provideAsyncMethods = provideAsyncMethods; scrivito.provideAsyncClassMethods = provideAsyncMethods; scrivito.provideAsyncInstanceMethods = provideAsyncInstanceMethods; scrivito.asyncMethodStub = asyncMethodStub; })(); "use strict"; (function () { // Access the LoadableData synchronously, assuming it is available. // If the LoadableData is failed, the error is thrown. // If the LoadableData is idle or loading, // a NotLoadedError is thrown, with the provided loader function. function getWithLoader(loadableData, loader) { if (loadableData.isAvailable()) { return loadableData.get(); } if (loadableData.isFailed()) { throw loadableData.getError(); } throw new scrivito.NotLoadedError(function () { if (loadableData.isAvailable() || loadableData.isFailed()) { return scrivito.Promise.resolve(); } if (loadableData.isIdle()) { triggerLoader(loadableData, loader); } return promiseForNextChangeTo(loadableData); }); } function triggerLoader(loadableData, loader) { // construct a unique JS object to identify this load operation var loadId = {}; function ifUnchanged(fn) { if (loadableData.getLoading() === loadId) { fn(); } } loader().then(function (result) { return ifUnchanged(function () { return loadableData.set(result); }); }, function (error) { return ifUnchanged(function () { return loadableData.setError(error); }); }); loadableData.setLoading(loadId); } function promiseForNextChangeTo(loadableData) { var deferred = new scrivito.Deferred(); var unsubscribe = loadableData.subscribe(function () { deferred.resolve(); unsubscribe(); }); return deferred.promise; } // export scrivito.getWithLoader = getWithLoader; })(); "use strict"; (function () { // loadAsync triggers the loading of all resource that the passed in // function needs and returns a Promise to the result of the function. // // It can be used to convert synchronous code (the loadable function) // into asynchronous code (Promise to the return value). // // A loadable function is a function that: // * may throw a NotLoadedError // * is pure, i.e. idempotent, doesn't perform I/O, is free of side-effects // // loadAsync will run the provided function as many times as needed, // and trigger loading of any NotLoadedError that should occur. // // It returns a Promise that fulfills once the function returns a value. // If the function throws an Exception (other than NotLoadedError), // the Promise is rejected. function loadAsync(loadableFunction) { return new scrivito.Promise(function (resolve, reject) { function tryToSettle() { try { resolve(loadableFunction()); } catch (error) { if (error instanceof scrivito.NotLoadedError) { error.load(tryToSettle); } else { reject(error); } } } tryToSettle(); }); } // export scrivito.loadAsync = loadAsync; })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { // A wrapper around data that is retrieved asynchronously. // This class is stateless and (almost) pure: // * it does not perform any I/O // * the only side-effect it has is changing the provided state container // * it does not keep any state itself // * state is replaced, not mutated // * it does not use Promises // An instance of LoadableData might be in one of these states: var IDLE = 'IDLE'; var LOADING = 'LOADING'; var AVAILABLE = 'AVAILABLE'; var FAILED = 'FAILED'; // Usually, the data goes through the following transitions: // idle -> loading -> available // However when something goes wrong, this transition might occur: // idle -> loading -> error // // Other transitions are also valid, // i.e. all possible transtions may eventually occur. var LoadableData = (function () { // stateContainer is where the LoadableData should store its state. function LoadableData(stateContainer) { _classCallCheck(this, LoadableData); if (!stateContainer) { throw new scrivito.InternalError('LoadableData needs stateContainer'); } this._container = stateContainer; } // export // get the data, should only be called if available _createClass(LoadableData, [{ key: 'get', value: function get() { if (this.isAvailable()) { return this._currentValue(); } } // set the data. this makes the data available. }, { key: 'set', value: function set(data) { this._transitionTo(AVAILABLE, data); } // set the error and transitions to failed. }, { key: 'setError', value: function setError(error) { this._transitionTo(FAILED, error); } // returns the error. should only be called if failed. }, { key: 'getError', value: function getError() { if (this.isFailed()) { return this._currentValue(); } } // transition to loading. // store a loadId to identify the load operation. // this allows you to distinguish different load operations // to facilitate concurrency protection, like optimistic locking. // loadId may be any kind of JS object. }, { key: 'setLoading', value: function setLoading(loadId) { this._transitionTo(LOADING, loadId); } // return the current loadId. should only be called if loading. }, { key: 'getLoading', value: function getLoading() { if (this.isLoading()) { return this._currentValue(); } } // transition back to idle, removes any data or errors. }, { key: 'reset', value: function reset() { this._transitionTo(IDLE); } // returns true iff the data is idle }, { key: 'isIdle', value: function isIdle() { return this._currentState() === IDLE; } // returns true iff the data not available and not failed, but // has started loading. }, { key: 'isLoading', value: function isLoading() { return this._currentState() === LOADING; } // return true iff data is available. }, { key: 'isAvailable', value: function isAvailable() { return this._currentState() === AVAILABLE; } // return true iff an error was set. }, { key: 'isFailed', value: function isFailed() { return this._currentState() === FAILED; } }, { key: 'subscribe', value: function subscribe(listener) { return this._container.subscribe(listener); } }, { key: '_currentState', value: function _currentState() { var state = this._container.get(); if (!state) { return IDLE; } return state[0]; } }, { key: '_currentValue', value: function _currentValue() { var state = this._container.get(); if (!state) { return undefined; } return state[1]; } }, { key: '_transitionTo', value: function _transitionTo(state, value) { this._container.set([state, value]); } }]); return LoadableData; })(); scrivito.LoadableData = LoadableData; })(); 'use strict'; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { // abstract interface for managing state var AbstractStateStore = (function () { function AbstractStateStore() { _classCallCheck(this, AbstractStateStore); } // a state tree, which can be used to store state. // this is the root of the tree, which keeps the state of the entire tree. _createClass(AbstractStateStore, [{ key: 'get', // return current state value: function get() { throw scrivito.InternalError('implement in subclass'); } // change state }, { key: 'set', value: function set(newState) { throw scrivito.InternalError('implement in subclass'); } // subscribe to changes to state // the listener will be called at least once after each state change. // returns a function that should be invoked to unsubscribe. // proper unsubscription is important to avoid leaking memory. }, { key: 'subscribe', value: function subscribe(listener) { throw new scrivito.InternalError('implement in subclass'); } }, { key: 'subState', value: function subState(key) { return new StateTreeNode(this, key); } }, { key: 'setSubState', value: function setSubState(key, newState) { var priorState = this.get(); if (!priorState) { this.set(Immutable.Map(_defineProperty({}, key, newState))); } else { this.set(priorState.set(key, newState)); } } }, { key: 'getSubState', value: function getSubState(key) { var state = this.get(); if (state) { return state.get(key); } } }]); return AbstractStateStore; })(); var StateTree = (function (_AbstractStateStore) { _inherits(StateTree, _AbstractStateStore); function StateTree() { _classCallCheck(this, StateTree); _get(Object.getPrototypeOf(StateTree.prototype), 'constructor', this).call(this); this._listeners = Immutable.Set(); } // a node of a state tree. // does not actually keep state, but provides // access scoped to a subtree of a StateTree. _createClass(StateTree, [{ key: 'get', value: function get() { return this._state; } }, { key: 'set', value: function set(newState) { this._state = newState; this._listeners.forEach(function (listener) { return listener(); }); } }, { key: 'subscribe', value: function subscribe(listener) { var _this = this; if (!listener) { throw new scrivito.InternalError('subscribe needs an argument'); } this._listeners = this._listeners.add(listener); return function () { _this._listeners = _this._listeners.remove(listener); }; } // for test purposes only }, { key: 'listenerCount', value: function listenerCount() { return this._listeners.size; } }]); return StateTree; })(AbstractStateStore); var StateTreeNode = (function (_AbstractStateStore2) { _inherits(StateTreeNode, _AbstractStateStore2); function StateTreeNode(parentState, key) { _classCallCheck(this, StateTreeNode); if (!_.isString(key)) { throw new scrivito.InternalError(key + ' is not a string'); } _get(Object.getPrototypeOf(StateTreeNode.prototype), 'constructor', this).call(this); this._parentState = parentState; this._key = key; } // export class _createClass(StateTreeNode, [{ key: 'get', value: function get() { return this._parentState.getSubState(this._key); } }, { key: 'set', value: function set(newState) { this._parentState.setSubState(this._key, newState); } }, { key: 'subscribe', value: function subscribe(listener) { var _this2 = this; if (!listener) { throw new scrivito.InternalError('subscribe needs an argument'); } var lastState = this.get(); return this._parentState.subscribe(function () { var currentState = _this2.get(); if (currentState !== lastState) { listener(); lastState = currentState; } }); } }]); return StateTreeNode; })(AbstractStateStore); scrivito.StateTree = StateTree; // singleton instance, to be used by the data layer scrivito.modelState = new StateTree(); })(); (function() { var handle_task = function(task) { switch (task.status) { case 'success': return $.Deferred().resolve(task.result); case 'error': return $.Deferred().reject({ message: task.message, code: task.code }); case 'open': return scrivito.wait(2).then(function() { return single_ajax('GET', 'tasks/' + task.id).then(function(data) { return handle_task(data); }); }); default: throw { message: "Invalid task (unknown status)", task: task }; } }; var single_ajax = function(type, path, options) { var base_url = window.location.protocol + '//' + window.location.host + '/__scrivito/'; if (options && options.data) { options.data = JSON.stringify(options.data); } return $.ajax(base_url + path, _.extend({ type: type, dataType: 'json', contentType: 'application/json; charset=utf-8', cache: false // Don't cache GET requests. }, options || {})).then( function(result, text_status, xhr) { return $.Deferred().resolve(result); }, function(xhr, text_status, xhr_error) { try { return $.Deferred().reject(JSON.parse(xhr.responseText)); } catch (SyntaxError) { return $.Deferred().reject(xhr_error); } } ); }; _.extend(scrivito, { silent_ajax: function(type, path, options) { var is_write_request = type === 'PUT' || type === 'POST' || type === 'DELETE'; var skip_write_monitor = options && options.skip_write_monitor; if (is_write_request) { options = options || {}; options.timeout = 15000; // miliseconds if (!skip_write_monitor) { scrivito.write_monitor.start_write(); } } var ajax_promise = single_ajax(type, path, options).then(function(result) { if (result && result.task && _.size(result) === 1) { return handle_task(result.task); } else { return $.Deferred().resolve(result); } }); if (is_write_request && !skip_write_monitor) { ajax_promise.always(function() { scrivito.write_monitor.end_write(); }); } return ajax_promise; }, ajax: function(type, path, options) { return scrivito.silent_ajax(type, path, options).fail(function(error) { scrivito.display_ajax_error(error); }); }, display_ajax_error: function(error) { var message, message_for_editor; if (_.isObject(error)) { message = scrivito.t('ajax_error', error.message); message_for_editor = error.message_for_editor; } else if (_.contains(['abort', 'parsererror', 'timeout'], error)) { message = scrivito.t('ajax_error.communication'); } else { message = scrivito.t('ajax_error', error); } if (scrivito.isDevelopmentMode) { scrivito.alertDialog(message); } else { scrivito.logError(message); scrivito.errorDialog(message_for_editor || scrivito.t('ajax_error.message_for_editor'), [error.timestamp, message]); } } }); }()); (function() { var auto_height_dirty = false; var relevant_siblings_for = function(elem) { return elem.siblings().filter(":not(.hover):visible"); }; var target_height_for = function(elem, dont_store_height) { var parent = elem.parent(); var heightOfParent = parent.innerHeight(); if (!dont_store_height) { parent.data("scrivito_last_inner_height", heightOfParent); } var heightOfAllSiblings = _(relevant_siblings_for(elem)) .chain() .map($) .reduce(function(sum, sibling) { var height = sibling.outerHeight(true); if (!dont_store_height) { sibling.data("scrivito_last_outer_height", height); } return sum + height; }, 0).value() ; return Math.max(0, heightOfParent - heightOfAllSiblings); }; var set_auto_height_for = function(elem) { elem.css('height', target_height_for(elem)); elem.addClass("scrivito_height_done"); }; var sibling_height_changes = function(elem) { return _(relevant_siblings_for(elem)).map(function(sibling) { sibling = $(sibling); var last = sibling.data("scrivito_last_outer_height"); var actual = sibling.outerHeight(true); if (last !== actual) { return scrivito.describe_element(sibling) + " unexpectantly changed it's height from " + (last === undefined ? "" : last) + " to " + actual ; } }); }; var parent_height_changes = function(elem) { var parent = elem.parent(); var last = parent.data("scrivito_last_inner_height"); var actual = parent.innerHeight(); if (last !== actual) { return scrivito.describe_element(parent) + " unexpectantly changed it's height from " + (last || "") + " to " + actual ; } }; _.extend(scrivito, { updateAutoHeightFor: function(root_element) { var elements = root_element.find('.scrivito_auto_height:visible'); if (root_element.hasClass("scrivito_auto_height")) { elements = elements.add(root_element); } elements.not(".scrivito_height_done").each(function (i, elem) { set_auto_height_for($(elem)); }); }, invalidate_auto_height: function() { $(".scrivito_height_done").removeClass("scrivito_height_done"); auto_height_dirty = true; }, invalidate_auto_height_for: function(elem) { elem.find(".scrivito_height_done").removeClass("scrivito_height_done"); }, process_auto_height: function() { if (auto_height_dirty) { scrivito.updateAutoHeightFor($("body")); auto_height_dirty = false; } }, auto_height_errors: function() { return _($(".scrivito_auto_height:visible")).chain().map($).map(function(elem) { var expected = target_height_for(elem, true); var actual = parseInt(elem.css('height'), 10); if (actual !== expected) { if (!elem.hasClass("scrivito_height_done")) { return [scrivito.describe_element(elem) + " was never updated"]; } else { var errors = sibling_height_changes(elem); errors.push(parent_height_changes(elem)); return _(errors).compact(); } } }).compact().flatten().value(); } }); }()); (function() { _.extend(scrivito, { path_for_id: function(id) { return '/__scrivito/' + id; }, id_from_path: function(url) { var match = /__scrivito\/([a-z0-9]{16})/.exec(url); if (match) { return match[1]; } } }); })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); (function () { scrivito.ContentConversion = { convertHtml: function convertHtml(input) { var parsedHtml = $($.parseHTML('
    ' + input + '
    ', context(), false)); var unknownUrls = convertUrls(parsedHtml, 'a', 'href'); unknownUrls = unknownUrls.concat(convertUrls(parsedHtml, 'img', 'src')); return result(parsedHtml.html(), unknownUrls); }, convertLink: function convertLink(primitiveLink) { var unknownUrls = []; var _lookupLink = lookupLink(primitiveLink); var _lookupLink2 = _slicedToArray(_lookupLink, 2); var newPrimitiveLink = _lookupLink2[0]; var unknownUrl = _lookupLink2[1]; if (unknownUrl) { unknownUrls.push(unknownUrl); } return result(newPrimitiveLink, unknownUrls); }, convertLinklist: function convertLinklist(primitiveLinks) { var unknownUrls = []; var newPrimitiveLinks = _.map(primitiveLinks, function (primitiveLink) { var _lookupLink3 = lookupLink(primitiveLink); var _lookupLink32 = _slicedToArray(_lookupLink3, 2); var newPrimitiveLink = _lookupLink32[0]; var unknownUrl = _lookupLink32[1]; if (unknownUrl) { unknownUrls.push(unknownUrl); } return newPrimitiveLink; }); return result(newPrimitiveLinks, unknownUrls); } }; function result(result, unknownUrls) { return { result: result, unknownUrls: _.uniq(unknownUrls) }; } function lookupLink(primitiveLink) { if (!primitiveLink.url) { return [primitiveLink]; } var internalUrl = scrivito.resolveUrl(primitiveLink.url); if (internalUrl === undefined) { return [primitiveLink, primitiveLink.url]; } if (internalUrl === null) { return [primitiveLink]; } var newPrimitiveLink = { obj_id: internalUrl.id, fragment: internalUrl.fragment, query: internalUrl.query, target: primitiveLink.target, title: primitiveLink.title }; return [newPrimitiveLink]; } function convertUrls(parsedHtml, tagName, attribute) { var unknownUrls = []; _.each(parsedHtml.find(tagName), function (tag) { var value = $(tag).attr(attribute); if (value.match(/^objid:/)) { return; } var internalUrl = scrivito.resolveUrl(value); if (internalUrl === undefined) { unknownUrls.push(value); return; } if (internalUrl === null) { return; } var newUrl = new URI('objid:' + internalUrl.id); if (internalUrl.fragment) { newUrl.fragment(internalUrl.fragment); } if (internalUrl.query) { newUrl.query(internalUrl.query); } $(tag).attr(attribute, newUrl.href()); }); return unknownUrls; } // jQuery version 3 creates a new context for each $.parseHTML for security reasons. // For details see https://github.com/jquery/jquery/pull/1505. // Since current jQuery version (1.x) does not have this yet, I backported the feature. // inspired by https://git.io/vo12V function context() { var newContext = document.implementation.createHTMLDocument(''); setBase(newContext); if (!allowsFormSiblings()) { return document; } return newContext; } // jQuery issue: https://github.com/jquery/jquery/issues/2965 function setBase(newContext) { var base = newContext.createElement('base'); base.href = document.location.href; newContext.head.appendChild(base); } // checks https://bugs.webkit.org/show_bug.cgi?id=137337 // inspired by https://github.com/jquery/jquery/blob/master/src/core/support.js var allowsFormSiblings = _.once(function () { var newContext = document.implementation.createHTMLDocument(''); var body = newContext.body; body.innerHTML = '
    '; return body.childNodes.length === 2; }); })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var cache = {}; scrivito.LinkResolution = (function () { _createClass(LinkResolution, null, [{ key: 'for', value: function _for(objData) { var key = objData._id; if (!cache[key]) { cache[key] = new scrivito.LinkResolution(objData); } return cache[key]; } // For test purposes only }, { key: 'clearCache', value: function clearCache() { cache = {}; } }]); function LinkResolution(objData) { _classCallCheck(this, LinkResolution); this._objData = objData; this._currentWorkers = []; } _createClass(LinkResolution, [{ key: 'start', value: function start() { this._resolveData(this._objData.current); } }, { key: 'finishResolving', value: function finishResolving() { var currentPromises = _.invoke(this._currentWorkers, 'finish'); this._currentWorkers = _.select(this._currentWorkers, function (worker) { return worker.finish().isPending(); }); return scrivito.Promise.all(currentPromises); } // For test purposes only }, { key: 'anyCurrentWorkerPresent', value: function anyCurrentWorkerPresent() { return !!this._currentWorkers.length; } }, { key: '_resolveData', value: function _resolveData(data, widgetId) { var _this = this; _.each(data, function (attrData, attrName) { if (attrName === '_widget_pool') { _.each(attrData, function (widgetData, newWidgetId) { _this._resolveData(widgetData, newWidgetId); }); } else { _this._resolveAttribute(attrName, attrData, widgetId); } }); } }, { key: '_resolveAttribute', value: function _resolveAttribute(attrName, attrData, widgetId) { if (scrivito.Attribute.isSystemAttribute(attrName)) { return; } var _attrData = _slicedToArray(attrData, 2); var type = _attrData[0]; var value = _attrData[1]; if (_.contains(['html', 'link', 'linklist'], type) && !_.isEmpty(value)) { var worker = new scrivito.LinkResolutionWorker(this._objData, attrName, widgetId); worker.start(); this._currentWorkers.push(worker); } } }]); return LinkResolution; })(); })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.LinkResolutionWorker = (function () { function LinkResolutionWorker(objData, attributeName, widgetId) { _classCallCheck(this, LinkResolutionWorker); this._objData = objData; this._attributeName = attributeName; this._widgetId = widgetId; this._deferred = new scrivito.Deferred(); var _currentAttributeData2 = this._currentAttributeData(); var _currentAttributeData22 = _slicedToArray(_currentAttributeData2, 2); this._attributeType = _currentAttributeData22[0]; this._attributeValue = _currentAttributeData22[1]; } _createClass(LinkResolutionWorker, [{ key: 'finish', value: function finish() { return this._deferred.promise; } }, { key: 'start', value: function start() { var _this = this; if (!this._deferred.promise.isPending()) { return; } if (this._isConcurrentUpdate()) { this._deferred.resolve(); return; } var conversion = this._convertValue(); if (_.isEmpty(conversion.unknownUrls)) { this._updateAttributeValue(conversion.result); this._deferred.resolve(); } else { scrivito.write_monitor.start_write(); scrivito.preloadResolvedUrls(conversion.unknownUrls).then(function () { scrivito.write_monitor.end_write(); _this.start(); })['catch'](function (fail) { scrivito.write_monitor.end_write(); _this._deferred.reject(fail); }); } } }, { key: '_convertValue', value: function _convertValue() { switch (this._attributeType) { case 'html': return scrivito.ContentConversion.convertHtml(this._attributeValue); case 'link': return scrivito.ContentConversion.convertLink(this._attributeValue); case 'linklist': return scrivito.ContentConversion.convertLinklist(this._attributeValue); default: throw new scrivito.InternalError('Attribute type "' + this._attributeType + '" is not supported.'); } } }, { key: '_currentAttributeData', value: function _currentAttributeData() { if (this._widgetId) { var widgetPool = this._objData.current._widget_pool || {}; var widgetData = widgetPool[this._widgetId] || {}; return widgetData[this._attributeName] || []; } return this._objData.current[this._attributeName] || []; } }, { key: '_isConcurrentUpdate', value: function _isConcurrentUpdate() { var previousAttributeData = [this._attributeType, this._attributeValue]; return !_.isEqual(this._currentAttributeData(), previousAttributeData); } }, { key: '_updateAttributeValue', value: function _updateAttributeValue(newValue) { if (newValue !== this._attributeValue) { var patch = _defineProperty({}, this._attributeName, [this._attributeType, newValue]); if (this._widgetId) { patch = { _widget_pool: _defineProperty({}, this._widgetId, patch) }; } this._objData.update(patch); } } }]); return LinkResolutionWorker; })(); })(); (function() { _.extend(scrivito, { dom_config: { read: function(dom_element, attr_name) { var selector = '[' + attr_name + ']'; var config = dom_element.find(selector).addBack(selector).attr(attr_name); if (config) { return JSON.parse(config); } }, write: function(dom_element, attr_name, config) { dom_element.attr(attr_name, JSON.stringify(config)); } } }); }()); (function() { _.extend(scrivito, { editing_context: { display_mode: null, selected_workspace: null, visible_workspace: null, init: function(config) { scrivito.editing_context.display_mode = config.display_mode; var visible_workspace = scrivito.workspace.from_data(config.visible_workspace); var selected_workspace = scrivito.workspace.from_data(config.selected_workspace); scrivito.editing_context.visible_workspace = visible_workspace; scrivito.editing_context.selected_workspace = selected_workspace; if (document.hasFocus()) { scrivito.editing_context.write_cookie(); } $.ajaxPrefilter(scrivito.editing_context.ajax_prefilter); scrivito.gui.on('document', function(cms_document) { cms_document.local_jquery().ajaxPrefilter(scrivito.editing_context.ajax_prefilter); }); // This can not be unit tested, since it is not possible to trigger a 'focus' // event on a 'window' object with JavaScript. $(window).focus(function() { scrivito.editing_context.write_cookie(); }); }, location: function(params) { var uri = new URI(scrivito.location()); if (params.workspace_id) { uri.setQuery('_scrivito_workspace_id', params.workspace_id); } if (params.display_mode) { uri.setQuery('_scrivito_display_mode', params.display_mode); } return uri; }, is_view_mode: function() { return scrivito.editing_context.display_mode === 'view'; }, is_editing_mode: function() { return scrivito.editing_context.display_mode === 'editing'; }, is_added_mode: function() { return scrivito.editing_context.display_mode === 'added'; }, is_deleted_mode: function() { return scrivito.editing_context.display_mode === 'deleted'; }, is_diff_mode: function() { return scrivito.editing_context.display_mode === 'diff'; }, is_comparing_mode: function() { return scrivito.editing_context.is_added_mode() || scrivito.editing_context.is_deleted_mode() || scrivito.editing_context.is_diff_mode(); }, ajax_prefilter: function(options, originalOptions, xhr) { if (!options.crossDomain) { xhr.setRequestHeader('Scrivito-Editing-Context', serialize()); } }, write_cookie: function() { $.cookie('scrivito_editing_context', serialize(), {path: '/'}); }, comparing_mode: function() { var storage_key = 'editing_context.comparing_mode'; if (scrivito.editing_context.is_comparing_mode()) { var mode = scrivito.editing_context.display_mode; scrivito.storage.set(storage_key, mode); return mode; } else { if (scrivito.storage.hasKey(storage_key)) { return scrivito.storage.get(storage_key); } else { return 'diff'; } } }, reason_for_display_mode_being_disabled: function(mode) { if (mode === "editing") { return scrivito.editing_mode.reason_for_being_disabled(); } } } }); var serialize = function() { return JSON.stringify({ display_mode: scrivito.editing_context.display_mode, workspace_id: scrivito.editing_context.selected_workspace.id() }); }; }()); (function() { var reason_storage_key = "edit_mode_disabled.reason"; _.extend(scrivito, { editing_mode: { disable: function(reason) { var old_reason = scrivito.editing_mode.reason_for_being_disabled(); scrivito.storage.set(reason_storage_key, reason); if (scrivito.editing_context.is_editing_mode()) { return scrivito.withSavingOverlay( scrivito.change_editing_context({display_mode: 'view'})); } if (old_reason !== reason) { reload_ui(); } }, enable: function() { if (!scrivito.editing_mode.is_enabled()) { scrivito.storage.remove(reason_storage_key); reload_ui(); } }, is_enabled: function() { return !scrivito.editing_mode.reason_for_being_disabled(); }, reason_for_being_disabled: function() { return scrivito.storage.get(reason_storage_key); } } }); var reload_ui = function() { scrivito.withSavingOverlay(scrivito.reload()); }; })(); (function() { _.extend(scrivito, { editor_selection: { init: function() { scrivito.gui.on('editor_selection', function(content) { if (scrivito.in_editable_view()) { var root_element = $(content); var cms_document = scrivito.cms_document.from(root_element); var dom_elements = root_element.find('[data-scrivito-field-type]') .addBack('[data-scrivito-field-type]'); var editor_selection = scrivito.editor_selection.create_instance(cms_document); _.each(dom_elements, function(dom_element) { editor_selection.activate(dom_element); }); } }); }, create_instance: function(cms_document) { var that = { define: function(name, editor) { var editors = cms_document.editors || {}; editors[name] = editor; cms_document.editors = editors; }, activate: function(dom_element) { var selected_editor, is_disabled; var editors = cms_document.editors || {}; var editor_name = $(dom_element).data('scrivito-private-editor'); if (editor_name === false) { return; } if (editor_name && can_edit(editors[editor_name], dom_element)) { selected_editor = editors[editor_name]; } else { if (cms_document.select_editor) { cms_document.select_editor(dom_element, { use: function(editor_name) { if (!selected_editor && can_edit(editors[editor_name], dom_element)) { selected_editor = editors[editor_name]; } }, disable: function() { if (!selected_editor) { is_disabled = true; } } }); if (is_disabled) { return; } } if (!selected_editor && can_edit(editors['default'], dom_element)) { selected_editor = editors['default']; } } if (selected_editor) { scrivito.run_new_event(function() { selected_editor.activate(dom_element); }); } }, // For test purpose only. reset: function() { delete cms_document.editors; delete cms_document.selected_editor; } }; var can_edit = function(editor, dom_element) { if (!editor) { return false; } if (!editor.can_edit) { return true; } try { return editor.can_edit(dom_element); } catch(error) { scrivito.logError(error); return false; } }; return that; } } }); }()); 'use strict'; (function () { scrivito.forgery_protection = { init: function init() { $.ajaxPrefilter(function (options, originalOptions, xhr) { if (options.crossDomain) { return; } // copied from rails/jquery-ujs to avoid a dependency // compare: https://git.io/v2MNH var token = $('meta[name=csrf-token]').attr('content'); if (token) { xhr.setRequestHeader('X-CSRF-Token', token); } else { scrivito.logError('Missing CSRF Token in UI, AJAX may fail!'); } }); } }; })(); (function() { var is_started = false; var callbacks = {}; var run_callbacks = function(name, dom_element) { if (callbacks[name]) { _.each(callbacks[name], function(callback) { callback(dom_element); }); } }; _.extend(scrivito, { gui: { start: function() { scrivito.gui.on('document', function(document) { var body = document.dom_element().find('body'); body.attr('data-scrivito-display-mode', scrivito.editing_context.display_mode); _.each(['dragenter', 'dragover', 'drop'], function(e) { body.on(e, false); }); }); $('body').append( '
    ' + '
    ' + '
    ' ); run_callbacks('open'); run_callbacks('content', window.document); // For test purpose only. is_started = true; }, // For test purpose only. stop: function() { is_started = false; }, // For test purpose only. clean_up: function() { $('#scrivito_editing').remove(); }, new_content: function(dom_element) { if (dom_element) { preload(dom_element).then(function() { run_callbacks('content', dom_element); var promises = scrivito.cms_document.from($(dom_element)) .notify_new_content(dom_element); if (promises.length) { $.when.apply(null, promises) .then(function() { run_callbacks('editor_selection', dom_element); }); } else { run_callbacks('editor_selection', dom_element); } }); } }, new_document: function(document) { _.each(callbacks.document, function(callback) { callback(document); }); document.window().notify_new_document(document); }, on: function(event_name, callback) { if (callbacks[event_name] === undefined) { callbacks[event_name] = []; } callbacks[event_name].push(callback); }, // For testing purpose only. reset_callbacks: function() { callbacks = {}; }, is_started: function() { return is_started; } } }); function preload(dom_element) { if (scrivito.editing_context.is_editing_mode()) { return scrivito.cms_field_element.preload($(dom_element)); } return scrivito.Promise.resolve(); } }()); (function() { _.extend(scrivito, { hotkeys: { add: function(promise, key_map) { var key_actions = {13: key_map.enter, 27: key_map.escape}; $(document).on('keyup.scrivito_hotkeys', function(e) { if (scrivito.savingOverlay.isPresent()) { return; } if (key_actions[e.keyCode]) { e.preventDefault(); key_actions[e.keyCode](e); } }); return promise.always(function() { $(document).off('keyup.scrivito_hotkeys'); }); } } }); }()); (function() { var valid_locale = ['en', 'de']; var language; _.extend(scrivito, { i18n: { init: function(config) { scrivito.i18n.set_locale(config.locale); }, locale: function() { return language; }, load: function(locale, translations) { $.i18n().load(translations, locale); }, set_locale: function(locale) { if($.inArray(locale, valid_locale) !== -1) { language = locale; } else { language = 'en'; } moment.locale(language); }, // In addition to the key you can pass multiple parameters that will be interpolated into // the translated string. translate: function(key) { if (!scrivito.i18n.locale()) { $.error('scrivito.i18n locale not yet set!'); } $.i18n().locale = scrivito.i18n.locale(); return $.i18n.apply(0, arguments); }, // localize_date localizes an ISO6801 date string according to the current locale. localize_date: function(date_string) { return moment(date_string).format('LLLL'); }, // localizeDateRelative converts an ISO6801 date string to a relative time and localizes it // according to the current locale. localizeDateRelative: function(date_string) { return moment(date_string).fromNow(); }, // Test purpose only. reset_locale: function() { language = undefined; } } }); }()); (function() { var assert_valid_dom_element = function(dom_element) { if (dom_element.length < 1) { $.error('Can not call "scrivito" method on an empty element'); } if (dom_element.length > 1) { $.error('Can not call "scrivito" method on more than one tag'); } }; var build_cms_element = function(dom_element) { return scrivito.cms_element.from_dom_element(dom_element); }; var save_content = function(dom_element, content) { if (dom_element.length > 0) { if (dom_element.length === 1) { if (content === undefined) { $.error('Can not call "save" with no content'); } else { var cms_element = build_cms_element(dom_element); cms_element.set_original_content(content); return cms_element.save(content).then(function() { return; }, function(error) { return {message: error.message}; }); } } else { $.error('Can not call "scrivito" method on more than one tag'); } } }; var get_original_content = function(dom_element) { assert_valid_dom_element(dom_element); return build_cms_element(dom_element).original_content(); }; var get_valid_values = function(dom_element) { assert_valid_dom_element(dom_element); return build_cms_element(dom_element).valid_values(); }; var get_valid_classes = function(dom_element) { assert_valid_dom_element(dom_element); return build_cms_element(dom_element).valid_classes(); }; var get_menu = function(dom_element) { assert_valid_dom_element(dom_element); var cms_element = build_cms_element(dom_element); return scrivito.menu_builder.create_instance(cms_element); }; var reload = function(dom_element) { assert_valid_dom_element(dom_element); build_cms_element(dom_element); $(dom_element).trigger('reload.scrivito'); }; _.extend(scrivito, { // @api public jquery_plugin: function(method, content) { var dom_element = $(this); switch (method) { case 'save': return save_content(dom_element, content); case 'content': return get_original_content(dom_element); case 'valid_values': return get_valid_values(dom_element); case 'valid_classes': return get_valid_classes(dom_element); case 'menu': return get_menu(dom_element); case 'reload': reload(dom_element); break; default: $.error('Unknown method "' + method + '"'); } } }); $.fn.scrivito = scrivito.jquery_plugin; }()); (function() { _.extend(scrivito, { menu_builder: { create_instance: function(cms_element) { return { list: function() { return cms_element.menu(); }, add: function(id, params) { var menu = cms_element.menu(); menu.push(scrivito.command.create_instance(_.extend(params, {id: id}))); cms_element.set_menu(menu); }, update: function(id, params) { var menu = cms_element.menu(); _.find(menu, function(command, index) { if (command.id() === id) { return command.update_params(params); } }); cms_element.set_menu(menu); }, replace: function(id, params) { var menu = cms_element.menu(); _.find(menu, function(command, index) { if (command.id() === id) { menu[index] = scrivito.command.create_instance(_.extend(params, {id: id})); return menu[index]; } }); cms_element.set_menu(menu); }, remove: function(id) { var menu = cms_element.menu(); var command = _.find(menu, function(command) { return command.id() === id; }); cms_element.set_menu(_.without(menu, command)); } }; } } }); }()); (function() { _.extend(scrivito, { no_turbolinks: { init: function() { scrivito.gui.on('document', function(cms_document) { if (cms_document.browser_window().Turbolinks) { scrivito.alertDialog( 'You have Turbolinks enabled. ' + 'Scrivito does not yet support Turbolinks. ' + 'Please remove it from your assets.' ); } }); } } }); }()); (function() { var defaults; _.extend(scrivito, { obj_class_defaults: { register: function(mapping) { _.extend(defaults, mapping); }, lookup: function(content_type) { return defaults[content_type] || defaults[content_type.split('/')[0] + '/*'] || defaults['*/*']; }, reset: function() { defaults = {}; scrivito.obj_class_defaults.register({'image/*': 'Image', '*/*': 'Download'}); } } }); scrivito.obj_class_defaults.reset(); }()); (function() { _.extend(scrivito, { obj_class_selection: { store: function(obj_class) { var new_storage = get_storage(); new_storage.unshift(obj_class); new_storage = _.uniq(new_storage); new_storage = _.take(new_storage, 200); scrivito.storage.set(scrivito.obj_class_selection.storage_key, new_storage); }, recent: function(valid_obj_classes) { var recent_valid_obj_classes = _.intersection(get_storage(), valid_obj_classes); return _.take(recent_valid_obj_classes, 5); }, // for testing only storage_key: 'obj_class_selection.used_classes' } }); var get_storage = function() { return scrivito.storage.get(scrivito.obj_class_selection.storage_key) || []; }; }()); 'use strict'; (function () { var STORAGE_KEY = 'obj_clipboard'; scrivito.objClipboard = Object.defineProperties({ save: function save(obj) { scrivito.storage.set(STORAGE_KEY, obj.serializeAttributes()); }, isPresent: function isPresent() { return scrivito.storage.hasKey(STORAGE_KEY); }, clear: function clear() { scrivito.storage.remove(STORAGE_KEY); } }, { serializedAttributes: { get: function get() { if (!this.isPresent()) { throw new scrivito.InternalError('Obj clipboard is empty'); } return scrivito.storage.get(STORAGE_KEY); }, configurable: true, enumerable: true } }); })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function () { var SIZE_PER_CHUNK = 20; var resolvedUrlCache = {}; var requestCache = {}; scrivito.resolveUrl = function (url) { return resolvedUrlCache[url]; }; scrivito.preloadResolvedUrls = function (unresolvedUrls) { var _classifyUrls = classifyUrls(unresolvedUrls); var _classifyUrls2 = _slicedToArray(_classifyUrls, 2); var requestsInFlight = _classifyUrls2[0]; var missingUrls = _classifyUrls2[1]; if (!missingUrls.length) { return scrivito.Promise.all(requestsInFlight); } var currentChunk = missingUrls.slice(0, SIZE_PER_CHUNK); var remainingUrls = missingUrls.slice(SIZE_PER_CHUNK); var chunkRequest = preloadChunk(currentChunk); return scrivito.Promise.all([].concat(_toConsumableArray(requestsInFlight), [chunkRequest])).then(function () { return scrivito.preloadResolvedUrls(remainingUrls); }); }; // for testing purposes only! scrivito.setResolvedUrl = function (url, resolution) { resolvedUrlCache[url] = resolution; }; // for testing purposes only! scrivito.clearResolvedUrlCache = function () { resolvedUrlCache = {}; requestCache = {}; }; // for testing purposes only! scrivito.resolvedUrlRequestCacheIsEmpty = function () { return _.isEmpty(requestCache); }; function classifyUrls(unresolvedUrls) { var inFlight = []; var missingUrls = []; _.each(unresolvedUrls, function (unresolvedUrl) { var request = requestCache[unresolvedUrl]; if (request) { inFlight.push(request); } else { missingUrls.push(unresolvedUrl); } }); return [inFlight, missingUrls]; } function cleanupRequestCache(unresolvedUrls) { _.each(unresolvedUrls, function (unresolvedUrl) { return delete requestCache[unresolvedUrl]; }); } function preloadChunk(chunk) { var ajaxRequest = scrivito.silent_ajax('PUT', 'resolve_paths', { data: { paths: chunk } }); var promise = scrivito.Promise.resolve(ajaxRequest); _.each(chunk, function (item) { requestCache[item] = promise; }); return promise.then(function (resolvedUrls) { chunk.forEach(function (unresolvedUrl, index) { resolvedUrlCache[unresolvedUrl] = resolvedUrls[index]; }); cleanupRequestCache(chunk); return null; })['catch'](function (arg) { cleanupRequestCache(chunk); throw arg; }); } })(); "use strict"; (function () { scrivito.ObjSerializer = { serialize: function serialize(objId, attrs) { var promise = serializeWidgetPool(objId, attrs._widget_pool).then(function (widgetPool) { return serializeAttrs(objId, attrs).then(function (serializedAttrs) { if (widgetPool) { serializedAttrs._widget_pool = widgetPool; } return serializedAttrs; }); }); return scrivito.promise.wrapInJqueryDeferred(promise); }, serializeValue: function serializeValue(value) { if (_.isDate(value)) { return moment.utc(value).toISOString(); } return value; } }; function serializeWidgetPool(objId, widgetPool) { if (widgetPool) { var promises = _.map(widgetPool, function (attrs, widgetId) { return serializeAttrs(objId, attrs).then(function (serializedAttrs) { return [widgetId, serializedAttrs]; }); }); return scrivito.Promise.all(promises).then(function (serializedWidgetPool) { return _.object(serializedWidgetPool); }); } return scrivito.Promise.resolve(widgetPool); } function serializeAttrs(objId, attrs) { var promises = _.map(attrs, function (attrValue, attrName) { return serializeAttr(objId, attrName, attrValue); }); return scrivito.Promise.all(promises).then(function (serializedAttrs) { return _.object(serializedAttrs); }); } function serializeAttr(objId, attrName, attrValue) { if (scrivito.BinaryUtils.isFile(attrValue)) { return serializeFile(objId, attrName, attrValue); } if (attrValue instanceof scrivito.UploadedBlob) { return serializeUploadedBlob(objId, attrName, attrValue); } if (attrValue instanceof scrivito.FutureBinary) { return serializeFutureBinary(objId, attrName, attrValue); } return scrivito.Promise.resolve([attrName, scrivito.ObjSerializer.serializeValue(attrValue)]); } function serializeFile(objId, attrName, file) { return serializeFutureBinary(objId, attrName, scrivito.Binary.upload(file)); } function serializeUploadedBlob(objId, attrName, uploadedBlob) { return serializeFutureBinary(objId, attrName, uploadedBlob.copy()); } function serializeFutureBinary(objId, attrName, futureBinary) { return futureBinary.into(objId).then(function (binary) { return [attrName, { id: binary.id }]; }); } })(); "use strict"; (function () { scrivito.prettyPrint = function (object) { return JSON.stringify(object); }; })(); 'use strict'; (function () { var NAMESPACE = 'scrivito'; scrivito.storage = { set: function set(key, object) { localStorage.setItem(expandKey(key), JSON.stringify(object)); }, get: function get(key) { return JSON.parse(localStorage.getItem(expandKey(key))); }, hasKey: function hasKey(key) { return !!this.get(key); }, remove: function remove(key) { localStorage.removeItem(expandKey(key)); } }; function expandKey(key) { return NAMESPACE + '.' + key; } })(); (function() { var cache = {}; _.extend(scrivito, { suggest_completion: function(attribute, prefix) { return fetch_suggestions(attribute).then(function(suggestions) { return _.filter(suggestions, function(suggestion) { return suggestion.toLowerCase().indexOf(prefix.toLowerCase()) === 0; }); }); } }); _.extend(scrivito.suggest_completion, { // For test purpose only. clear_cache: function() { cache = {}; } }); var fetch_suggestions = function(attribute) { var suggestions = cache[attribute]; if (suggestions) { return $.Deferred().resolve(suggestions); } else { var param = $.param({attribute: attribute}); return scrivito.ajax('GET', 'suggest_completion?' + param).then(function(suggestions) { cache[attribute] = suggestions; return suggestions; }); } }; }()); (function() { Handlebars.registerHelper('translate', scrivito.i18n.translate); Handlebars.registerHelper('localize_date', function(date_value_function) { return scrivito.i18n.localize_date(date_value_function()); }); Handlebars.registerHelper('localizeDateRelative', function(date_value_function) { return scrivito.i18n.localizeDateRelative(date_value_function()); }); Handlebars.registerHelper('array_to_title', function(array_fn) { var escaped_array = array_fn().map(function(text) { return Handlebars.Utils.escapeExpression(text); }); return new Handlebars.SafeString(escaped_array.join(' ')); }); Handlebars.registerHelper('render', function(template_path, object) { return new Handlebars.SafeString(scrivito.template.render(template_path, object)); }); _.extend(scrivito, { template: { load_templates_from_server: false, template_cache: {}, render: function(template_path, data) { var template; if (window.ScrivitoHandlebarsTemplates) { template = ScrivitoHandlebarsTemplates[template_path]; } if (window.__hbs__ && __hbs__[template_path]) { template = Handlebars.compile(__hbs__[template_path]); } if (!template) { if (scrivito.template.load_templates_from_server) { template = scrivito.template.template_cache[template_path]; if (!template) { var url = '/app/assets/javascripts/templates/'+template_path+'.hbs?'+Math.random(); var source = jQuery.ajax(url, {async: false}).responseText; template = Handlebars.compile(source); scrivito.template.template_cache[template_path] = template; } } else { $.error('Could not load template: '+template_path); } } return template(data); } } }); }()); (function() { _.extend(scrivito, { transfer_changes: function(objs) { var fetch_workspaces = scrivito.editing_context.selected_workspace.other_editable(); return scrivito.withSavingOverlay(fetch_workspaces).then(function(workspaces) { var select_workspace = scrivito.editable_workspace_dialog(workspaces, 'transfer_changes'); return select_workspace.then(function(workspace_id) { var transfer_modifications = scrivito.obj.transfer_modifications(objs, workspace_id); return scrivito.withSavingOverlay(transfer_modifications).then(function(errors) { if (errors.length) { scrivito.transfer_errors_dialog.open(errors); } return errors; }); }); }); } }); })(); 'use strict'; (function () { var INTEGER_RANGE_START = -9007199254740991; var INTEGER_RANGE_END = 9007199254740991; var BACKEND_DATE_FORMAT = 'YYYYMMDDHHmmss'; scrivito.types = { isValidInteger: function isValidInteger(value) { return isInteger(value) && INTEGER_RANGE_START <= value && value <= INTEGER_RANGE_END; }, isValidFloat: function isValidFloat(value) { return _.isNumber(value) && _.isFinite(value); }, parseStringToDate: function parseStringToDate(dateString) { return moment.utc(dateString, BACKEND_DATE_FORMAT).toDate(); }, formatDateToString: function formatDateToString(date) { return moment.utc(date).format(BACKEND_DATE_FORMAT); }, isValidDateString: function isValidDateString(dateString) { return _.isString(dateString) && dateString.match(/^\d{14}$/); } }; var isInteger = function isInteger(value) { return _.isNumber(value) && _.isFinite(value) && Math.floor(value) === value; }; })(); (function() { _.extend(scrivito, { /* * This component has two main purposes: * * 1. It wraps a function triggering a CSS transition * in an additional javascript event, so that that * transition will be executed even if associated target * has just been added to the DOM. * * 2. It skips any transitions and immediately executes * all functions in correct order if configured to do so, * e.g. in specs. */ transition: function(target, trigger_fn) { var deferred = $.Deferred(); if (!scrivito.transition.immediate_mode) { target.on('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd', function() { deferred.resolve(); }); setTimeout(trigger_fn, 0); } else { trigger_fn(); deferred.resolve(); } return deferred; } }); _.extend(scrivito.transition, {immediate_mode: false}); }()); (function() { _.extend(scrivito, { url_update: function(application_cms_window, ui_cms_window) { if (application_cms_window === ui_cms_window) { return; } application_cms_window.on('document', function(application_document) { var ui_window = ui_cms_window.browser_window(); var application_window = application_document.browser_window(); var ui_url = ui_window.location.origin + '/scrivito' + application_window.location.pathname + application_window.location.search + application_window.location.hash; ui_window.history.replaceState({}, '', ui_url); }); } }); }()); (function() { var permissions; _.extend(scrivito, { user_permissions: { init: function(config) { permissions = config; }, can: function(action) { return permissions && permissions[action]; } } }); }()); (function() { _.extend(scrivito, { warn_before_unloading: function() { if (scrivito.write_monitor.is_writing()) { return scrivito.t('warn_before_unloading'); } } }); }()); 'use strict'; (function () { var STORAGE_KEY = 'widget_clipboard'; scrivito.widgetClipboard = { saveWidget: function saveWidget(widget) { scrivito.storage.set(STORAGE_KEY, { widgetAttributes: widget.serializeAttributes(), objClass: widget.objClass }); }, isPresent: function isPresent() { return !!scrivito.storage.hasKey(STORAGE_KEY); }, widget: function widget() { var data = scrivito.storage.get(STORAGE_KEY); if (data && data.widgetAttributes) { return scrivito.BasicWidget.newWithSerializedAttributes(data.widgetAttributes); } }, objClass: function objClass() { var data = scrivito.storage.get(STORAGE_KEY); return data && data.objClass; }, clear: function clear() { scrivito.storage.remove(STORAGE_KEY); } }; })(); (function() { var callbacks = {}; var current_token = 0; var counter = 0; var run_callbacks = function(event_name) { _.each(callbacks[event_name], function(callback) { callback(); }); }; _.extend(scrivito, { write_monitor: { on: function(event_name, callback) { if (callbacks[event_name] === undefined) { callbacks[event_name] = {}; } current_token += 1; callbacks[event_name][current_token] = callback; return current_token; }, off: function(token) { _.each(callbacks, function(event_callbacks) { delete event_callbacks[token]; }); }, is_writing: function() { return counter > 0; }, start_write: function() { if (!scrivito.write_monitor.is_writing()) { run_callbacks('start_write'); } counter += 1; }, end_write: function() { counter -= 1; if (!scrivito.write_monitor.is_writing()) { scrivito.run_new_event(function() { if (!scrivito.write_monitor.is_writing()) { run_callbacks('end_write'); } }); } }, track_changes: function(fn, on_change_callback) { var has_changes = false; var changes_finished = false; var start_token = scrivito.write_monitor.on('start_write', function() { has_changes = true; changes_finished = false; }); var end_token = scrivito.write_monitor.on('end_write', function() { changes_finished = true; }); return fn().done(function() { scrivito.write_monitor.off(start_token); scrivito.write_monitor.off(end_token); if (has_changes) { if (changes_finished) { on_change_callback(); } else { var saving_promise = $.Deferred(); var final_end_token = scrivito.write_monitor.on('end_write', function() { scrivito.write_monitor.off(final_end_token); saving_promise.resolve(); on_change_callback(); }); scrivito.withSavingOverlay(saving_promise); } } }); }, // For test purpose only. simulate_changes: function() { scrivito.write_monitor.start_write(); scrivito.write_monitor.end_write(); }, // For test purpose only. reset_callbacks: function() { callbacks = {}; current_token = 0; }, // For test purpose only. reset_counter: function() { counter = 0; } } }); }()); "use strict"; (function () { var Bluebird = P.noConflict(); Bluebird.config({ warnings: false, longStackTraces: false }); _.extend(scrivito, { Promise: Bluebird, promise: { enableDebugMode: function enableDebugMode() { Bluebird.config({ warnings: true, longStackTraces: true }); }, wrapInJqueryDeferred: function wrapInJqueryDeferred(promise) { var d = $.Deferred(); promise.then(function (data) { return d.resolve(data); }, function (error) { d.reject(error); }); return d; }, capturePromises: function capturePromises() { Bluebird.setScheduler(function (promiseCallback) { scrivito.nextTick(promiseCallback); }); } } }); })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.PublicPromise = (function () { _createClass(Promise, null, [{ key: "all", value: function all(promises) { return new scrivito.PublicPromise(scrivito.Promise.all(promises)); } }, { key: "race", value: function race(promises) { return new scrivito.PublicPromise(scrivito.Promise.race(promises)); } }, { key: "resolve", value: function resolve(valueOrThenable) { return new scrivito.PublicPromise(scrivito.Promise.resolve(valueOrThenable)); } }, { key: "reject", value: function reject(valueOrThenable) { return new scrivito.PublicPromise(scrivito.Promise.reject(valueOrThenable)); } }]); function Promise(promise) { _classCallCheck(this, Promise); this._internalPromise = promise; } _createClass(Promise, [{ key: "then", value: function then(resolve, reject) { return new scrivito.PublicPromise(this._internalPromise.then(resolve, reject)); } }, { key: "catch", value: function _catch(reject) { return new scrivito.PublicPromise(this._internalPromise["catch"](reject)); } }]); return Promise; })(); })(); "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.Deferred = function Deferred() { var _this = this; _classCallCheck(this, Deferred); this.promise = new scrivito.Promise(function (resolveFn, rejectFn) { _this.resolve = resolveFn; _this.reject = rejectFn; }); }; })(); "use strict"; (function () { var capturedDelayedFunctions = []; var captureEnabled = undefined; _.extend(scrivito, { nextTick: function nextTick(delayedFunction) { if (captureEnabled) { capturedDelayedFunctions.push(delayedFunction); } else { setTimeout(delayedFunction, 0); } }, // For test purposes only simulateNextTicks: function simulateNextTicks() { var exceptions = []; while (capturedDelayedFunctions.length) { var currentFunctions = _.shuffle(capturedDelayedFunctions); capturedDelayedFunctions = []; _.each(currentFunctions, function (delayedFunction) { try { delayedFunction(); } catch (e) { exceptions.push(e); } }); } if (exceptions.length > 0) { throw exceptions[0]; } }, // For test purposes only enableNextTickCapture: function enableNextTickCapture() { captureEnabled = true; } }); })(); 'use strict'; (function () { scrivito.BinaryRequest = { upload: function upload(objId, blob, filename, contentType) { return getUploadPermission().then(function (permission) { scrivito.write_monitor.start_write(); return uploadToS3(blob, permission).then(function (uploadedBlob) { return activateUpload(objId, uploadedBlob, filename, contentType); })['finally'](scrivito.write_monitor.end_write); }); }, copy: function copy(copyId, objId, filename, contentType) { var encodedCopyId = encodeURIComponent(copyId); var params = {}; if (filename) { params.filename = filename; } if (contentType) { params.content_type = contentType; } params.destination_obj_id = objId; return scrivito.CmsRestApi.put('blobs/' + encodedCopyId + '/copy', params); }, // For testing purpose only. getFormData: function getFormData() { return new FormData(); } }; function getUploadPermission() { return scrivito.CmsRestApi.get('blobs/upload_permission'); } function uploadToS3(blob, permission) { var formData = scrivito.BinaryRequest.getFormData(); _.each(permission.fields, function (value, name) { return formData.append(name, value); }); // File must be appended last, otherwise S3 will complain. formData.append('file', blob); return scrivito.Promise.resolve($.ajax({ method: 'POST', url: permission.url, data: formData, // These are needed in order for jQuery to work properly with a FormData. contentType: false, processData: false })).then(function () { return permission.blob; }); } function activateUpload(objId, blob, filename, contentType) { return scrivito.CmsRestApi.put('blobs/activate_upload', { obj_id: objId, upload: blob, filename: filename, content_type: contentType }); } })(); 'use strict'; (function () { scrivito.BinaryUtils = { validateBinaryOptions: function validateBinaryOptions(options) { if (_.has(options, 'filename') && !options.filename) { throw new scrivito.ArgumentError('filename cannot be blank'); } if (_.has(options, 'content_type') && !options.content_type) { throw new scrivito.ArgumentError('content_type cannot be blank'); } if (_.has(options, 'contentType') && !options.contentType) { throw new scrivito.ArgumentError('contentType cannot be blank'); } }, isBlob: function isBlob(obj) { return !!obj && _.isNumber(obj.size) && _.isString(obj.type); }, isFile: function isFile(obj) { return this.isBlob(obj) && _.isDate(obj.lastModifiedDate) && _.isString(obj.name); } }; })(); "use strict"; (function () { scrivito.createReactClass = function (params) { var originalRender = params.render; return React.createClass(_.extend(params, { render: function render() { var _this = this; var handleError = function handleError(error) { scrivito.nextTick(function () { throw error; }); return _this.renderOnError(); }; try { return originalRender(); } catch (error) { if (error instanceof scrivito.NotLoadedError) { try { error.load(function () { if (_this.isMounted()) { _this.forceUpdate(); } }); } catch (error) { return handleError(error); } return this.renderWhileLoading(); } return handleError(error); } } })); }; })(); "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function () { _.extend(scrivito, { iterable: { collectValuesFromIterator: function collectValuesFromIterator(iterator) { var result = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var _iterator$next = iterator.next(); var value = _iterator$next.value; var done = _iterator$next.done; if (done) { return result; } return this.collectValuesFromIterator(iterator, [].concat(_toConsumableArray(result), [value])); }, firstValueFromIterator: function firstValueFromIterator(iterator) { var _iterator$next2 = iterator.next(); var value = _iterator$next2.value; return value || null; } } }); })(); "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function () { _.extend(scrivito, { oncePerFrame: function oncePerFrame(fn) { var lastArguments = false; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var scheduled = lastArguments; lastArguments = args; if (!scheduled) { scrivito.requestAnimationFrame(function () { fn.apply(undefined, _toConsumableArray(lastArguments)); lastArguments = false; }); } }; }, // wrapper intended for testing purposes requestAnimationFrame: function requestAnimationFrame(fn) { window.requestAnimationFrame(fn); } }); })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { // From https://phabricator.babeljs.io/T3083#65595 function ExtendableError() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } Error.apply(this, args); } ExtendableError.prototype = Object.create(Error.prototype); if (Object.setPrototypeOf) { Object.setPrototypeOf(ExtendableError, Error); } else { ExtendableError.__proto__ = Error; } scrivito.ScrivitoError = (function (_ExtendableError) { _inherits(ScrivitoError, _ExtendableError); function ScrivitoError(message) { _classCallCheck(this, ScrivitoError); _get(Object.getPrototypeOf(ScrivitoError.prototype), 'constructor', this).call(this); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Object.defineProperty(this, 'stack', { value: new Error().stack }); } this.message = message; } _createClass(ScrivitoError, [{ key: 'name', get: function get() { return this.constructor.name; } }]); return ScrivitoError; })(ExtendableError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { scrivito.CommunicationError = (function (_scrivito$ScrivitoError) { _inherits(CommunicationError, _scrivito$ScrivitoError); function CommunicationError(message, httpCode) { _classCallCheck(this, CommunicationError); _get(Object.getPrototypeOf(CommunicationError.prototype), "constructor", this).call(this, message); this.httpCode = httpCode; } return CommunicationError; })(scrivito.ScrivitoError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request fails due to an error caused by the client. */ scrivito.ClientError = (function (_scrivito$ScrivitoError) { _inherits(ClientError, _scrivito$ScrivitoError); /** * The constructor is not part of the public API and should **not** be used. */ function ClientError(message, httpCode, backendCode) { if (httpCode === undefined) httpCode = 412; _classCallCheck(this, ClientError); _get(Object.getPrototypeOf(ClientError.prototype), "constructor", this).call(this, message); this.httpCode = httpCode; this.backendCode = backendCode; } return ClientError; })(scrivito.ScrivitoError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a given Scrivito resource is not found. */ scrivito.ResourceNotFoundError = (function (_scrivito$ScrivitoError) { _inherits(ResourceNotFoundError, _scrivito$ScrivitoError); /** * The constructor is not part of the public API and should **not** be used. */ function ResourceNotFoundError(message) { _classCallCheck(this, ResourceNotFoundError); _get(Object.getPrototypeOf(ResourceNotFoundError.prototype), "constructor", this).call(this, message); } return ResourceNotFoundError; })(scrivito.ScrivitoError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request from the UI is denied access. */ scrivito.UnauthorizedError = (function (_scrivito$ClientError) { _inherits(UnauthorizedError, _scrivito$ClientError); /** * The constructor is not part of the public API and should **not** be used. */ function UnauthorizedError(message, httpCode, backendCode) { _classCallCheck(this, UnauthorizedError); _get(Object.getPrototypeOf(UnauthorizedError.prototype), "constructor", this).call(this, message, httpCode, backendCode); } return UnauthorizedError; })(scrivito.ClientError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request from the UI * is denied access to a specific resource. */ scrivito.AccessDeniedError = (function (_scrivito$ClientError) { _inherits(AccessDeniedError, _scrivito$ClientError); /** * The constructor is not part of the public API and should **not** be used. */ function AccessDeniedError(message, httpCode, backendCode) { _classCallCheck(this, AccessDeniedError); _get(Object.getPrototypeOf(AccessDeniedError.prototype), "constructor", this).call(this, message, httpCode, backendCode); } return AccessDeniedError; })(scrivito.ClientError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request from the UI * exceeds the rate limit of the backend. */ scrivito.RateLimitExceededError = (function (_scrivito$CommunicationError) { _inherits(RateLimitExceededError, _scrivito$CommunicationError); /** * The constructor is not part of the public API and should **not** be used. */ function RateLimitExceededError(message, httpCode) { _classCallCheck(this, RateLimitExceededError); _get(Object.getPrototypeOf(RateLimitExceededError.prototype), "constructor", this).call(this, message, httpCode); } return RateLimitExceededError; })(scrivito.CommunicationError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request from the UI * fails due to network problems. */ scrivito.NetworkError = (function (_scrivito$CommunicationError) { _inherits(NetworkError, _scrivito$CommunicationError); /** * The constructor is not part of the public API and should **not** be used. */ function NetworkError(message, httpCode) { _classCallCheck(this, NetworkError); _get(Object.getPrototypeOf(NetworkError.prototype), "constructor", this).call(this, message, httpCode); } return NetworkError; })(scrivito.CommunicationError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case a backend request from the UI * fails due to an internal server error. */ scrivito.BackendError = (function (_scrivito$CommunicationError) { _inherits(BackendError, _scrivito$CommunicationError); /** * The constructor is not part of the public API and should **not** be used. */ function BackendError(message, httpCode) { _classCallCheck(this, BackendError); _get(Object.getPrototypeOf(BackendError.prototype), "constructor", this).call(this, message, httpCode); } return BackendError; })(scrivito.CommunicationError); })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * A `NotLoadedError` is thrown when data is accessed in a synchronous fashion but is not yet * available locally. For example {@link scrivito.BasicObj.get} throws a `NotLoadedError` * whenever a CMS object is accessed that is not yet cached in the browser. */ scrivito.NotLoadedError = (function (_scrivito$ScrivitoError) { _inherits(NotLoadedError, _scrivito$ScrivitoError); /** * The constructor is not part of the public API and should **not** be used. */ function NotLoadedError(loader) { _classCallCheck(this, NotLoadedError); _get(Object.getPrototypeOf(NotLoadedError.prototype), 'constructor', this).call(this, 'Data is not yet loaded. Call the instance method "load" to load data.'); this._loader = loader; } _createClass(NotLoadedError, [{ key: 'load', value: function load(onLoadingDone) { var loadPromise = this._loader(); if (onLoadingDone) { var done = function done() { scrivito.nextTick(onLoadingDone); }; loadPromise.then(done, done); } } }]); return NotLoadedError; })(scrivito.ScrivitoError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * An error thrown in case wrong arguments are passed to an SDK function. */ scrivito.ArgumentError = (function (_scrivito$ScrivitoError) { _inherits(ArgumentError, _scrivito$ScrivitoError); /** * The constructor is not part of the public API and should **not** be used. */ function ArgumentError(message) { _classCallCheck(this, ArgumentError); _get(Object.getPrototypeOf(ArgumentError.prototype), "constructor", this).call(this, message); } return ArgumentError; })(scrivito.ScrivitoError); })(); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * This error is raised if scrivito detects an internal problem. * These errors should never occur when using the public API of the SDK. */ scrivito.InternalError = (function (_scrivito$ScrivitoError) { _inherits(InternalError, _scrivito$ScrivitoError); /** * The constructor is not part of the public API and should **not** be used. */ function InternalError(message) { _classCallCheck(this, InternalError); _get(Object.getPrototypeOf(InternalError.prototype), "constructor", this).call(this, message); } return InternalError; })(scrivito.ScrivitoError); })(); 'use strict'; (function () { _.extend(scrivito, { handleAjaxError: function handleAjaxError(error) { var message = undefined; if (error.message) { message = scrivito.t('ajax_error', error.message); } else { message = scrivito.t('ajax_error.communication'); } if (scrivito.isDevelopmentMode) { scrivito.alertDialog(message); } else { scrivito.errorDialog(scrivito.t('ajax_error.message_for_editor'), [message]); } scrivito.logError(error); }, withAjaxErrorHandling: function withAjaxErrorHandling(promise) { return promise['catch'](scrivito.handleAjaxError); } }); })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var session = undefined; var sessionRenewalPromise = undefined; var timeoutId = undefined; scrivito.SessionKeeper = (function () { function SessionKeeper() { _classCallCheck(this, SessionKeeper); } _createClass(SessionKeeper, null, [{ key: 'init', value: function init(initialSession) { setSession(initialSession); } }, { key: 'performWithToken', value: function performWithToken(callback) { return scrivito.Promise.resolve(callback(session.token))['catch'](function (error) { if (error instanceof scrivito.UnauthorizedError) { if (!sessionRenewalPromise) { clearTimeout(timeoutId); sessionRenewalPromise = renewSession(); } return sessionRenewalPromise.then(function () { return callback(session.token); }); } throw error; }); } }, { key: '_session', value: function _session() { return session; } }, { key: 'userId', get: function get() { return session.user_id; } }, { key: 'permissions', get: function get() { return session.permissions; } }]); return SessionKeeper; })(); function renewSession() { return requestSession().then(function (newSession) { sessionRenewalPromise = null; setSession(newSession); })['catch'](function (error) { sessionRenewalPromise = null; throw new scrivito.UnauthorizedError('Failed to renew session.'); }); } function setSession(newSession) { session = newSession; timeoutId = setTimeout(function () { sessionRenewalPromise = renewSession()['catch'](function () { // Catch so no unhandled rejection message is logged }); }, (session.maxage - 10) * 1000); } function requestSession() { return scrivito.Promise.resolve(scrivito.silent_ajax('PUT', 'sessions/' + session.id, { skip_write_monitor: true })); } })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var MIN_REQUEST_TIME = 5; var DEFAULT_REQUEST_TIMEOUT = 15000; var backendEndpoint = undefined; var tenant = undefined; scrivito.CmsRestApi = { init: function init(endpoint, initTenant) { backendEndpoint = endpoint; tenant = initTenant; }, get: function get(path, requestParams) { return fetch('GET', path, requestParams); }, put: function put(path, requestParams) { return fetch('PUT', path, requestParams); }, post: function post(path, requestParams) { return fetch('POST', path, requestParams); }, 'delete': function _delete(path) { return fetch('DELETE', path); } }; var Timer = (function () { function Timer() { var timeout = arguments.length <= 0 || arguments[0] === undefined ? DEFAULT_REQUEST_TIMEOUT : arguments[0]; _classCallCheck(this, Timer); this.timesOutAt = Date.now() + timeout; } _createClass(Timer, [{ key: 'timedOut', value: function timedOut() { return this.remainingTime() < MIN_REQUEST_TIME; } }, { key: 'remainingTime', value: function remainingTime() { return Math.max(this.timesOutAt - Date.now(), 0); } }, { key: 'cover', value: function cover(time) { return time <= this.timesOutAt - MIN_REQUEST_TIME; } }]); return Timer; })(); function fetch(method, path, requestParams) { return request(method, path, requestParams).then(function (result) { if (result && result.task && _.size(result) === 1) { return handleTask(result.task); } return result; }); } function request(method, path, requestParams) { var timer = new Timer(); return retryOnceOnError(timer, method, function () { return retryOnRateLimit(timer, function () { return scrivito.SessionKeeper.performWithToken(function (token) { var ajaxDeferred = ajax(method, path, requestParams, timer.remainingTime(), token); return scrivito.Promise.resolve(ajaxDeferred)['catch'](checkAuthorization); }); })['catch'](function (error) { return raiseError(error); }); }); } function retryOnceOnError(timer, method, requestCallback) { if (method === 'POST') { return requestCallback(); } return requestCallback()['catch'](function (error) { if (!timer.timedOut()) { if (error instanceof scrivito.BackendError) { return requestCallback(); } if (error instanceof scrivito.NetworkError) { return requestCallback(); } } throw error; }); } function retryOnRateLimit(timer, requestCallback) { var retry = function retry(retryCount) { return requestCallback()['catch'](function (error) { if (error.status === 429) { var timeout = calculateTimeout(error.getResponseHeader('Retry-After'), retryCount); if (timer.cover(Date.now() + timeout)) { return scrivito.Promise.resolve(scrivito.waitMs(timeout)).then(function () { return retry(retryCount + 1); }); } throw new scrivito.RateLimitExceededError('rate limit exceeded', 429); } throw error; }); }; return retry(0); } function calculateTimeout(retryAfter, retryCount) { var calculatedTimeout = Math.pow(2, retryCount) * 0.5 * 1000; return Math.max(calculatedTimeout, retryAfter * 1000); } function raiseError(error) { if (error.status === undefined || !_.isNumber(error.status)) { throw error; } else if (error.status === 0) { throw new scrivito.NetworkError(error.statusText, error.status); } var errorBody = parseError(error); var specificOutput = errorBody.error; if (error.status === 403) { throw new scrivito.AccessDeniedError(specificOutput, error.status, errorBody.code); } else if (error.status.toString()[0] === '4' && specificOutput) { throw new scrivito.ClientError(specificOutput, error.status, errorBody.code); } else if (error.status === 500 && specificOutput) { throw new scrivito.BackendError(specificOutput, error.status); } throw new scrivito.NetworkError(error.responseText, error.status); } function checkAuthorization(error) { if (error.status === 401) { var errorBody = parseError(error); var specificOutput = errorBody.error; throw new scrivito.UnauthorizedError(specificOutput, error.status, errorBody.code); } throw error; } function parseError(error) { try { return JSON.parse(error.responseText); } catch (err) { if (err instanceof SyntaxError) { throw new scrivito.NetworkError(error.responseText, error.status); } throw err; } } function prepareAjaxParams(method, path) { var requestParams = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var ajaxParams = { path: path, verb: method, params: requestParams }; return { data: JSON.stringify(ajaxParams) }; } function ajax(method, path, requestParams, timeout, token) { var ajaxParams = prepareAjaxParams(method, path, requestParams); var ajaxMethod = method === 'POST' ? 'POST' : 'PUT'; var url = 'https://' + backendEndpoint + '/tenants/' + tenant + '/perform'; return $.ajax(_.extend({ url: url, method: ajaxMethod, contentType: 'application/json; charset=utf-8', dataType: 'json', headers: { Authorization: 'Session ' + token }, timeout: timeout, cache: false, // Don't cache GET requests. xhrFields: { withCredentials: true } }, ajaxParams)).then(function (result, textStatus, xhr) { return $.Deferred().resolve(result); }, function (xhr, textStatus, xhrError) { return $.Deferred().reject(xhr); }); } function handleTask(task) { switch (task.status) { case 'success': return task.result; case 'error': throw new scrivito.ClientError(task.message, undefined, task.code); case 'open': return scrivito.wait(2).then(function () { return request('GET', 'tasks/' + task.id).then(function (result) { return handleTask(result); }); }); default: throw new scrivito.ScrivitoError('Invalid task response (unknown status)'); } } })(); 'use strict'; (function () { scrivito.AttributeSerializer = { serialize: function serialize(objClass, attributes) { return _.mapObject(attributes, function (value, name) { if (scrivito.Attribute.isSystemAttribute(name)) { return value; } var attribute = objClass && objClass.attribute(name); if (!attribute) { throw new scrivito.ScrivitoError('Attribute "' + name + '" is not defined for obj class "' + objClass.name + '".'); } return [serializeAttributeType(attribute.type, name), serializeAttributeValue(attribute, value, name)]; }); } }; function serializeAttributeType(type, name) { switch (type) { case 'enum': return 'string'; case 'float': case 'integer': return 'number'; case 'multienum': return 'stringlist'; case 'binary': case 'date': case 'html': case 'link': case 'linklist': case 'reference': case 'referencelist': case 'string': case 'stringlist': case 'widgetlist': return type; default: throw new scrivito.ScrivitoError('Attribute "' + name + '" is of unsupported type "' + type + '".'); } } function serializeAttributeValue(attribute, value, name) { if (value === null) { return value; } switch (attribute.type) { case 'binary': return serializeBinaryAttributeValue(value, name); case 'date': return serializeDateAttributeValue(value, name); case 'enum': return serializeEnumAttributeValue(attribute, value, name); case 'float': return serializeFloatAttributeValue(value, name); case 'integer': return serializeIntegerAttributeValue(value, name); case 'link': return serializeLinkAttributeValue(value, name); case 'linklist': return serializeLinklistAttributeValue(value, name); case 'multienum': return serializeMultienumAttributeValue(attribute, value, name); case 'reference': return serializeReferenceAttributeValue(value, name); case 'referencelist': return serializeReferencelistAttributeValue(value, name); case 'widgetlist': return serializeWidgetlistAttributeValue(value); default: return value; } } function invalidAttributeValue(value, name, expected) { throw new scrivito.ScrivitoError('Unexpected value ' + scrivito.prettyPrint(value) + ' for' + (' attribute "' + name + '". Expected: ' + expected)); } function serializeBinaryAttributeValue(value, name) { if (!(value instanceof scrivito.Binary)) { invalidAttributeValue(value, name, 'A Binary.'); } return { id: value.id }; } function serializeDateAttributeValue(value, name) { if (_.isDate(value)) { return scrivito.types.formatDateToString(value); } if (scrivito.types.isValidDateString(value)) { return value; } invalidAttributeValue(value, name, 'A Date.'); } function serializeEnumAttributeValue(attribute, value, name) { var validValues = attribute.validValues(); if (!_.contains(validValues, value)) { var e = 'Valid attribute values are contained in its "validValues" array [' + validValues + '].'; invalidAttributeValue(value, name, e); } return value; } function serializeFloatAttributeValue(value, name) { if (!scrivito.types.isValidFloat(value)) { var invalidValue = value; if (_.isNumber(value)) { invalidValue = String(value); } invalidAttributeValue(invalidValue, name, 'A Number, that is #isFinite().'); } return value; } function serializeIntegerAttributeValue(value, name) { if (!scrivito.types.isValidInteger(value)) { invalidAttributeValue(value, name, 'A Number, that is #isSafeInteger().'); } return value; } function serializeLinkAttributeValue(value, name) { if (!validLinkObject(value)) { invalidAttributeValue(value, name, 'A scrivito.Link instance.'); } return convertLinkToCmsApi(value); } function serializeLinklistAttributeValue(value, name) { if (!Array.isArray(value) || !_.all(value, validLinkObject)) { invalidAttributeValue(value, name, 'An array of scrivito.Link instances.'); } return _.map(value, convertLinkToCmsApi); } function validLinkObject(value) { if (value instanceof scrivito.Link) { return true; } // check if value is backend compatible if (!_.isObject(value)) { return false; } var invalidKeys = _.without(_.keys(value), 'fragment', 'obj_id', 'query', 'target', 'title', 'url'); return _.isEmpty(invalidKeys); } function convertLinkToCmsApi(value) { var backendLink = { fragment: value.fragment, query: value.query, target: value.target, title: value.title, url: value.url }; backendLink.obj_id = value.objId || value.obj_id; return _.mapObject(backendLink, function (v) { return v || null; }); } function serializeMultienumAttributeValue(attribute, value, name) { var validValues = attribute.validValues(); var errorMessage = 'An array with values from ' + scrivito.prettyPrint(validValues) + '.'; if (!Array.isArray(value) || !_.all(value, _.isString)) { invalidAttributeValue(value, name, errorMessage); } var forbiddenValues = _.difference(value, validValues); if (forbiddenValues.length) { var e = errorMessage + ' Forbidden values: ' + scrivito.prettyPrint(forbiddenValues) + '.'; invalidAttributeValue(value, name, e); } return value; } function serializeReferenceAttributeValue(value, name) { if (!isValidReference(value)) { invalidAttributeValue(value, name, 'A BasicObj or a String ID.'); } return serializeSingleReferenceValue(value); } function serializeReferencelistAttributeValue(value, name) { if (!isValidReferencelistValue(value)) { invalidAttributeValue(value, name, 'An array with BasicObjs or String IDs.'); } return _.map(value, serializeSingleReferenceValue); } function serializeSingleReferenceValue(value) { if (value instanceof scrivito.BasicObj) { return value.id; } return value; } function isValidReference(value) { return _.isString(value) || value instanceof scrivito.BasicObj; } function isValidReferencelistValue(value) { return _.isArray(value) && _.every(value, function (v) { return isValidReference(v); }); } function serializeWidgetlistAttributeValue(value) { return _.pluck(value, 'id'); } })(); "use strict"; (function () { var idsToDeferred = {}; scrivito.ObjRetrieval = { retrieveObj: function retrieveObj(id) { if (_.isEmpty(idsToDeferred)) { scrivito.nextTick(function () { return performRetrieval(); }); } if (!idsToDeferred[id]) { var deferred = new scrivito.Deferred(); idsToDeferred[id] = deferred; } return idsToDeferred[id].promise; }, // For test purposes only reset: function reset() { idsToDeferred = {}; } }; function performRetrieval() { var curIdsToDeferred = idsToDeferred; idsToDeferred = {}; var ids = _.keys(curIdsToDeferred); var workspaceId = scrivito.editing_context.selected_workspace.id(); scrivito.CmsRestApi.get("workspaces/" + workspaceId + "/objs/mget", { ids: ids, include_deleted: true }).then(function (response) { var results = response.results; _.each(ids, function (id, index) { var deferred = curIdsToDeferred[id]; if (index < results.length) { handleIncludedResult(deferred, id, results[index]); } else { scrivito.ObjRetrieval.retrieveObj(id).then(deferred.resolve, deferred.reject); } }); }, function (error) { _.each(curIdsToDeferred, function (deferred, id) { return deferred.reject(error); }); }); } function handleIncludedResult(deferred, id, value) { if (value) { deferred.resolve(value); } else { deferred.reject(new scrivito.ResourceNotFoundError("Obj with id \"" + id + "\" not found.")); } } })(); 'use strict'; (function () { scrivito.ObjQueryRetrieval = { retrieve: function retrieve(params) { var workspaceId = scrivito.editing_context.selected_workspace.id(); var consistentParams = _.extend({ consistent: true }, params); return scrivito.CmsRestApi.get('workspaces/' + workspaceId + '/objs/search', consistentParams).then(function (response) { response.results = _.pluck(response.results, 'id'); return _.pick(response, 'results', 'continuation'); }); } }; })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjQuery = (function () { function ObjQuery(params) { _classCallCheck(this, ObjQuery); this._params = params; } _createClass(ObjQuery, [{ key: "iterator", value: function iterator(batchSize) { var _this = this; var i = 0; return { next: function next() { var iteratorResult = _this._getIteratorResult(i, batchSize); if (!iteratorResult.done) { i++; } return iteratorResult; } }; } }, { key: "_loadNextBatch", value: function _loadNextBatch(size) { var _this2 = this; if (!this._requestInFlight) { var searchParams = _.extend({}, this._params, { size: size, continuation: this._continuation }); this._requestInFlight = scrivito.ObjQueryRetrieval.retrieve(searchParams).then(function (_ref) { var results = _ref.results; var continuation = _ref.continuation; if (!_this2._results) { _this2._results = []; } _this2._results = _.uniq(_this2._results.concat(results)); _this2._preloadObjData(results); _this2._continuation = continuation; _this2._requestInFlight = undefined; })["catch"](function (error) { _this2._lastLoadError = error; }); } return this._requestInFlight; } }, { key: "_preloadObjData", value: function _preloadObjData(ids) { _.each(ids, function (id) { return scrivito.ObjDataStore.preload(id); }); } }, { key: "_ensureNoLoadError", value: function _ensureNoLoadError() { if (this._lastLoadError) { throw this._lastLoadError; } } }, { key: "_getIteratorResult", value: function _getIteratorResult(index, batchSize) { var _this3 = this; if (this._isIdLoaded(index)) { return { done: false, value: this._results[index] }; } if (this._continuation || this._results === undefined) { this._ensureNoLoadError(); throw new scrivito.NotLoadedError(function () { return _this3._loadNextBatch(batchSize); }); } else { return { done: true }; } } }, { key: "_isIdLoaded", value: function _isIdLoaded(index) { return _.isArray(this._results) && index < this._results.length; } }]); return ObjQuery; })(); })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjQueryIterator = (function () { function ObjQueryIterator(query, batchSize) { _classCallCheck(this, ObjQueryIterator); this._iterator = query.iterator(batchSize); } _createClass(ObjQueryIterator, [{ key: "next", value: function next() { var id = this._fetchNextId(); if (!id) { return { done: true }; } try { var objData = scrivito.ObjDataStore.get(id); this._nextId = null; return { value: objData, done: false }; } catch (error) { if (error instanceof scrivito.ResourceNotFoundError) { this._nextId = null; return this.next(); } throw error; } } }, { key: "_fetchNextId", value: function _fetchNextId() { if (!this._nextId) { var _iterator$next = this._iterator.next(); var value = _iterator$next.value; this._nextId = value; } return this._nextId; } }]); return ObjQueryIterator; })(); })(); "use strict"; (function () { var cache = {}; scrivito.ObjQueryStore = { computeCacheKey: function computeCacheKey(obj) { var normalizedObj = normalizeData(obj); return JSON.stringify(normalizedObj); }, get: function get(params, batchSize) { var objQuery = getObjQuery(params); return new scrivito.ObjQueryIterator(objQuery, batchSize); }, // For test purposes only clearCache: function clearCache() { cache = {}; }, init: function init() { scrivito.ObjReplication.subscribeWrites(function () { cache = {}; }); } }; function getObjQuery(params) { var cacheKey = scrivito.ObjQueryStore.computeCacheKey(params); if (!cache[cacheKey]) { var objQuery = new scrivito.ObjQuery(params); cache[cacheKey] = objQuery; } return cache[cacheKey]; } function normalizeData(data) { if (_.isArray(data)) { return _.map(data, normalizeData); } if (_.isObject(data)) { return _.chain(data).mapObject(normalizeData).pairs().sortBy(_.first); } return data; } })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var replicationCache = {}; var disabled = undefined; var writeCallbacks = {}; var subscriptionToken = 0; scrivito.ObjReplication = (function () { _createClass(ObjReplication, null, [{ key: 'get', value: function get(id) { if (!replicationCache[id]) { replicationCache[id] = new scrivito.ObjReplication(id); } return replicationCache[id]; } }]); function ObjReplication(id) { _classCallCheck(this, ObjReplication); this._id = id; this._replicationActive = false; this._scheduledReplication = false; this._currentRequestDeferred = null; this._nextRequestDeferred = null; } _createClass(ObjReplication, [{ key: 'notifyLocalState', value: function notifyLocalState(localState) { if (this._backendState === undefined) { throw new scrivito.InternalError('Can not set local state before backend state.'); } this._localState = localState; this._startReplication(); } }, { key: 'notifyBackendState', value: function notifyBackendState(backendState) { if (this._localState) { throw new scrivito.InternalError('Can not set backend state after local state was set.'); } this._backendState = backendState; } }, { key: 'finishSaving', value: function finishSaving() { var finishSavingPromise = undefined; if (this._nextRequestDeferred) { finishSavingPromise = this._nextRequestDeferred.promise; } else if (this._currentRequestDeferred) { finishSavingPromise = this._currentRequestDeferred.promise; } else { return scrivito.Promise.resolve(); } return finishSavingPromise['catch'](function () { return scrivito.Promise.reject(); }); } }, { key: '_startReplication', value: function _startReplication() { var _this = this; if (disabled) { return; } if (!_.isEmpty(this._computePatch())) { if (!this._replicationActive) { if (!this._scheduledReplication) { this._scheduledReplication = true; this._initDeferredForRequest(); writeStarted(this._currentRequestDeferred.promise); scrivito.nextTick(function () { return _this._performReplication(); }); } } else { if (!this._nextRequestDeferred) { this._nextRequestDeferred = new scrivito.Deferred(); } } } else { if (this._nextRequestDeferred) { this._nextRequestDeferred.resolve(); this._nextRequestDeferred = null; } } } }, { key: '_performReplication', value: function _performReplication() { var _this2 = this; var localState = this._localState; var patch = this._computePatch(); var workspaceId = scrivito.editing_context.selected_workspace.id(); var path = 'workspaces/' + workspaceId + '/objs/' + this._id; this._scheduledReplication = false; this._replicationActive = true; scrivito.CmsRestApi.put(path, { obj: patch }).then(function (backendState) { _this2._handleBackendUpdate(localState, backendState); _this2._currentRequestDeferred.resolve(); _this2._currentRequestDeferred = null; _this2._replicationActive = false; _this2._startReplication(); }, function (error) { _this2._currentRequestDeferred.reject(error); _this2._currentRequestDeferred = null; _this2._replicationActive = false; }); } }, { key: '_computePatch', value: function _computePatch() { return scrivito.ObjPatch.diff(this._backendState, this._localState); } }, { key: '_initDeferredForRequest', value: function _initDeferredForRequest() { if (this._nextRequestDeferred) { var currentDeferred = this._nextRequestDeferred; this._nextRequestDeferred = null; this._currentRequestDeferred = currentDeferred; } else { this._currentRequestDeferred = new scrivito.Deferred(); } } }, { key: '_handleBackendUpdate', value: function _handleBackendUpdate(replicatedState, backendState) { var bufferedLocalChanges = scrivito.ObjPatch.diff(replicatedState, this._localState); this._backendState = backendState; this._localState = scrivito.ObjPatch.apply(backendState, bufferedLocalChanges); scrivito.ObjDataStore.get(this._id).set(this._localState); } // For test purpose only }, { key: 'isNotStoredInBackend', value: function isNotStoredInBackend() { return this._backendState === null; } // For test purpose only }, { key: 'isRequestInFlight', value: function isRequestInFlight() { return this._replicationActive; } // For test purpose only }], [{ key: 'subscribeWrites', value: function subscribeWrites(callback) { subscriptionToken += 1; writeCallbacks[subscriptionToken] = callback; return subscriptionToken; } }, { key: 'unsubscribeWrites', value: function unsubscribeWrites(token) { delete writeCallbacks[token]; } }, { key: 'disableReplication', value: function disableReplication() { disabled = true; } // For test purpose only }, { key: 'enableReplication', value: function enableReplication() { disabled = false; } // For test purpose only }, { key: 'clearWriteCallbacks', value: function clearWriteCallbacks() { writeCallbacks = {}; } // For test purpose only }, { key: 'clearCache', value: function clearCache() { replicationCache = {}; } }]); return ObjReplication; })(); function writeStarted(promise) { _.each(writeCallbacks, function (callback) { callback(promise); }); } })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.BufferedWriter = (function () { function BufferedWriter(preprocessor) { _classCallCheck(this, BufferedWriter); this._preprocessor = preprocessor; this._valueOfWriteInProcess = null; } _createClass(BufferedWriter, [{ key: "write", value: function write(value, writeCallback) { var deferred = this._storeNextWrite(value, writeCallback); if (!this._hasRunningWrite()) { this._initiateWrite(); } return deferred.promise; } }, { key: "pendingWrite", value: function pendingWrite() { if (this._nextWrite) { return this._nextWrite.value; } return this._valueOfWriteInProcess; } }, { key: "_storeNextWrite", value: function _storeNextWrite(value, writeCallback) { if (!this._nextWrite) { this._nextWrite = { deferred: new scrivito.Deferred() }; } this._nextWrite.value = value; this._nextWrite.writeCallback = writeCallback; return this._nextWrite.deferred; } }, { key: "_initiateWrite", value: function _initiateWrite() { var _this = this; var _nextWrite = this._nextWrite; var value = _nextWrite.value; var writeCallback = _nextWrite.writeCallback; var deferred = _nextWrite.deferred; this._nextWrite = null; this._valueOfWriteInProcess = value; return this._preprocess(value).then(function (preprocessedValue) { if (writeCallback) { writeCallback(preprocessedValue); } return preprocessedValue; }).then(function (preprocessedValue) { _this._finishWrite(); deferred.resolve(preprocessedValue); })["catch"](function (error) { _this._finishWrite(); deferred.reject(error); }); } }, { key: "_hasRunningWrite", value: function _hasRunningWrite() { return !!this._valueOfWriteInProcess; } }, { key: "_finishWrite", value: function _finishWrite() { if (this._nextWrite) { this._initiateWrite(); } else { this._valueOfWriteInProcess = null; } } }, { key: "_preprocess", value: function _preprocess(value) { var _this2 = this; return new scrivito.Promise(function (resolve, reject) { resolve(_this2._preprocessor(value)); }); } }]); return BufferedWriter; })(); })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjData = (function () { function ObjData(id, state) { _classCallCheck(this, ObjData); this._loadableData = new scrivito.LoadableData(state); this._id = id; } _createClass(ObjData, [{ key: "set", value: function set(newState) { this._loadableData.set(newState); } }, { key: "setError", value: function setError(error) { this._loadableData.setError(error); } }, { key: "ensureAvailable", value: function ensureAvailable() { var _this = this; scrivito.getWithLoader(this._loadableData, function () { return _this._load(); }); } }, { key: "isAvailable", value: function isAvailable() { return this._loadableData.isAvailable(); } }, { key: "update", value: function update(objPatch) { var newState = scrivito.ObjPatch.apply(this.current, objPatch); this._loadableData.set(newState); this._replication().notifyLocalState(newState); } }, { key: "finishSaving", value: function finishSaving() { return this._replication().finishSaving(); } }, { key: "_replication", value: function _replication() { return scrivito.ObjReplication.get(this._id); } }, { key: "_load", value: function _load() { var _this2 = this; return scrivito.ObjRetrieval.retrieveObj(this._id).then(function (data) { scrivito.ObjReplication.get(_this2._id).notifyBackendState(data); return data; }); } }, { key: "current", get: function get() { return this._loadableData.get(); } }]); return ObjData; })(); })(); 'use strict'; (function () { var eachKeyFrom = function eachKeyFrom(objectA, objectB, handler) { var combinedKeys = _.union(_.keys(objectA), _.keys(objectB)); _.each(combinedKeys, function (key) { return handler(key, objectA[key], objectB[key]); }); }; var buildUpdatedWidgetPool = function buildUpdatedWidgetPool(widgetPool, widgetPoolPatch, updatedPrimitiveObj) { if (!widgetPoolPatch || _.isEmpty(widgetPoolPatch)) { return widgetPool; } var updatedWidgetPool = {}; eachKeyFrom(widgetPool || {}, widgetPoolPatch || {}, function (id, widget, widgetPatch) { if (widgetPoolPatch.hasOwnProperty(id)) { if (widgetPatch && !widget) { updatedWidgetPool[id] = widgetPatch; } else if (widgetPatch) { updatedWidgetPool[id] = scrivito.ObjPatch.apply(widget, widgetPatch); } } else { updatedWidgetPool[id] = widget; } }); return updatedWidgetPool; }; var buildPatchEntry = function buildPatchEntry(key, valueA, valueB, fnHandleBoth) { if (!valueA && valueB) { return valueB; } if (valueA && !valueB) { return null; } if (valueA && valueB) { return fnHandleBoth(); } }; var buildWidgetPoolPatch = function buildWidgetPoolPatch(widgetPoolA, widgetPoolB) { if (widgetPoolA === widgetPoolB) { return {}; } var patch = {}; eachKeyFrom(widgetPoolA, widgetPoolB, function (widgetId, widgetA, widgetB) { var widgetValue = buildPatchEntry(widgetId, widgetA, widgetB, function () { var widgetPatch = scrivito.ObjPatch.diff(widgetA, widgetB); if (!_.isEmpty(widgetPatch)) { return widgetPatch; } }); if (widgetValue !== undefined) { patch[widgetId] = widgetValue; } }); return patch; }; scrivito.ObjPatch = { apply: function apply(primitiveObj, patch) { if (!primitiveObj) { return patch; } if (!patch) { return null; } var updatedPrimitiveObj = {}; eachKeyFrom(primitiveObj, patch, function (attribute, objValue, patchValue) { if (attribute === '_widget_pool') { updatedPrimitiveObj._widget_pool = buildUpdatedWidgetPool(objValue, patchValue, updatedPrimitiveObj); } else if (patch.hasOwnProperty(attribute)) { if (patchValue) { updatedPrimitiveObj[attribute] = patchValue; } } else { updatedPrimitiveObj[attribute] = primitiveObj[attribute]; } }); return updatedPrimitiveObj; }, diff: function diff(primitiveObjA, primitiveObjB) { if (!primitiveObjA) { return primitiveObjB; } if (!primitiveObjB) { return null; } var patch = {}; eachKeyFrom(primitiveObjA, primitiveObjB, function (attribute, valueInA, valueInB) { if (attribute === '_widget_pool') { var widgetPoolPatch = buildWidgetPoolPatch(valueInA, valueInB); if (!_.isEmpty(widgetPoolPatch)) { patch._widget_pool = widgetPoolPatch; } } else { var patchValue = buildPatchEntry(attribute, valueInA, valueInB, function () { if (!_.isEqual(valueInA, valueInB)) { return valueInB; } }); if (patchValue !== undefined) { patch[attribute] = patchValue; } } }); return patch; } }; })(); 'use strict'; (function () { scrivito.ObjDataStore = { preload: function preload(id) { var _this = this; scrivito.loadAsync(function () { return _this.get(id); }); }, createObjData: function createObjData(id) { var objData = objDataFor(id); objData.set(null); scrivito.ObjReplication.get(id).notifyBackendState(null); return objData; }, store: function store(primitiveObj) { var id = primitiveObj._id; if (!objDataFor(id).isAvailable()) { this.set(id, primitiveObj); scrivito.ObjReplication.get(id).notifyBackendState(primitiveObj); } }, set: function set(id, primitiveObj) { objDataFor(id).set(primitiveObj); }, // test method only! setError: function setError(id, error) { objDataFor(id).setError(error); }, get: function get(id) { objDataFor(id).ensureAvailable(); return objDataFor(id); }, clearCache: function clearCache() { cacheStore().set(undefined); } }; function cacheStore() { return scrivito.modelState.subState('objData'); } function objDataFor(id) { return new scrivito.ObjData(id, cacheStore().subState(id)); } })(); "use strict"; (function () { scrivito.ObjReplicationTracking = { init: function init() { subscribeWriteMonitor(); trackWriteFailure(); } }; function subscribeWriteMonitor() { scrivito.ObjReplication.subscribeWrites(function (promise) { scrivito.write_monitor.start_write(); promise["finally"](scrivito.write_monitor.end_write); }); } function trackWriteFailure() { scrivito.ObjReplication.subscribeWrites(scrivito.withAjaxErrorHandling); } })(); (function() { var expando = "scrivito_cms_element"; _.extend(scrivito, { cms_element: { create_instance: function(dom_element) { var that = { dom_element: function() { return dom_element; }, equals: function(cms_element) { return cms_element.dom_element().get(0) === that.dom_element().get(0); }, menu: function() { var menu = dom_element.data('scrivito-menu'); if (!menu) { menu = []; that.set_menu(menu); } return menu; }, set_menu: function(menu) { dom_element.data('scrivito-menu', menu); } }; return that; }, from_dom_element: function(dom_element) { if (!dom_element || !dom_element.jquery) { dom_element = $(dom_element); } if (dom_element.length === 0) { $.error("Expected a jquery instance with exactly one element, " + "instead got " + dom_element); } var instance = dom_element[0][expando]; if (!instance) { var cms_element = scrivito.cms_element.create_instance(dom_element); _.find(scrivito.cms_element.definitions, function(definition) { instance = definition.create_instance(cms_element); return instance; }); if (!instance) { $.error("This dom element is not a scrivito tag."); } dom_element[0][expando] = instance; } return instance; }, definitions: [], all: function(selector, root_element) { return _.map(root_element.find(selector).addBack(selector), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); }()); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.AttributeContent = (function () { function AttributeContent() { _classCallCheck(this, AttributeContent); } _createClass(AttributeContent, [{ key: 'get', /** * Allows accessing the custom attributes of a CMS object or widget. Passing an invalid * attribute will return `undefined`. * * @param {String} attributeName - the name of the attribute * @throws {scrivito.NotLoadedError} If a reference is not yet loaded. * @returns {?(Date|Number|String|String[]| * scrivito.BasicObj|scrivito.BasicObj[]|scrivito.BasicWidget[]| * scrivito.Binary|scrivito.Link|scrivito.Link[])} * the value of the attribute */ value: function get(attributeName) { if (_.has(this._systemAttributes, attributeName)) { return this[this._systemAttributes[attributeName]]; } var attributeDefinition = this._objClass.attribute(attributeName); var rawValue = this._current[attributeName]; if (!rawValue || !_.isArray(rawValue)) { rawValue = []; } return scrivito.AttributeDeserializer.deserialize(this, rawValue, attributeDefinition); } }, { key: 'widget', value: function widget(id) { throw new TypeError('Override in subclass.'); } }, { key: 'serializeAttributes', value: function serializeAttributes() { var _this = this; var serializedAttrs = {}; _.each(this._current, function (value, name) { if (_.isArray(value) && _.first(value) === 'widgetlist') { var attribute = _this._objClass.attribute(name); if (attribute && attribute.type === 'widgetlist') { var serializedAttributes = _.invoke(_this.get(name), 'serializeAttributes'); serializedAttrs[name] = ['widgetlist', serializedAttributes]; } return; } serializedAttrs[name] = value; }); return serializedAttrs; } }, { key: '_persistWidgets', value: function _persistWidgets(obj, objClass, attributes) { _.each(attributes, function (value, name) { if (objClass.attribute(name) && objClass.attribute(name).type === 'widgetlist') { _.each(value, function (widget) { if (!widget.isPersisted()) { widget.persistInObj(obj); } }); } }); } }, { key: '_objClass', get: function get() { throw new TypeError('Override in subclass.'); } }, { key: '_current', get: function get() { throw new TypeError('Override in subclass.'); } }]); return AttributeContent; })(); })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); (function () { var INTEGER_DEFAULT_VALUE = 0; var FLOAT_DEFAULT_VALUE = 0; scrivito.AttributeDeserializer = { deserialize: function deserialize(model, rawValue, attributeDefinition) { if (!attributeDefinition) { return; } var _rawValue = _slicedToArray(rawValue, 2); var typeFromBackend = _rawValue[0]; var valueFromBackend = _rawValue[1]; switch (attributeDefinition.type) { case 'binary': return deserializeBinaryValue(typeFromBackend, valueFromBackend); case 'date': return deserializeDateValue(typeFromBackend, valueFromBackend); case 'float': return deserializeFloatValue(typeFromBackend, valueFromBackend); case 'enum': return deserializeEnumValue(typeFromBackend, valueFromBackend, attributeDefinition); case 'html': return deserializeHtmlValue(typeFromBackend, valueFromBackend); case 'integer': return deserializeIntegerValue(typeFromBackend, valueFromBackend); case 'link': return deserializeLinkValue(typeFromBackend, valueFromBackend); case 'linklist': return deserializeLinklistValue(typeFromBackend, valueFromBackend); case 'multienum': return deserializeMultienumValue(typeFromBackend, valueFromBackend, attributeDefinition); case 'reference': return deserializeReferenceValue(typeFromBackend, valueFromBackend); case 'referencelist': return deserializeReferencelistValue(typeFromBackend, valueFromBackend); case 'string': return deserializeStringValue(typeFromBackend, valueFromBackend); case 'stringlist': return deserializeStringlistValue(typeFromBackend, valueFromBackend); case 'widgetlist': return deserializeWidgetlistValue(typeFromBackend, valueFromBackend, model); } } }; function deserializeBinaryValue(typeFromBackend, valueFromBackend) { if (typeFromBackend === 'binary' && valueFromBackend) { return new scrivito.Binary(valueFromBackend.id); } return null; } function deserializeDateValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'date' || !_.isString(valueFromBackend)) { return null; } if (!scrivito.types.isValidDateString(valueFromBackend)) { throw new scrivito.InternalError('The value is not a valid ISO date time: "' + valueFromBackend + '"'); } return scrivito.parseDate(valueFromBackend); } function deserializeHtmlValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'html' || !_.isString(valueFromBackend)) { return ''; } return valueFromBackend; } function deserializeEnumValue(typeFromBackend, valueFromBackend, attributeDefinition) { var validValues = attributeDefinition.validValues(); if (typeFromBackend === 'string' && _.contains(validValues, valueFromBackend)) { return valueFromBackend; } return null; } function deserializeMultienumValue(typeFromBackend, valueFromBackend, attributeDefinition) { var validValues = attributeDefinition.validValues(); if (typeFromBackend !== 'stringlist' || !Array.isArray(valueFromBackend)) { return []; } return _.intersection(valueFromBackend, validValues); } function deserializeFloatValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': if (valueFromBackend.match(/^-?\d+(\.\d+)?$/)) { return convertToFloat(valueFromBackend); } return FLOAT_DEFAULT_VALUE; case 'number': return convertToFloat(valueFromBackend); default: return FLOAT_DEFAULT_VALUE; } } function convertToFloat(valueFromBackend) { var floatValue = parseFloat(valueFromBackend); if (scrivito.types.isValidFloat(floatValue)) { return floatValue; } return FLOAT_DEFAULT_VALUE; } function deserializeIntegerValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': if (valueFromBackend.match(/^-?\d+$/)) { return convertToInteger(valueFromBackend); } return INTEGER_DEFAULT_VALUE; case 'number': return convertToInteger(valueFromBackend); default: return INTEGER_DEFAULT_VALUE; } } function deserializeLinkValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'link' || !_.isObject(valueFromBackend)) { return null; } return convertToLink(valueFromBackend); } function deserializeLinklistValue(typeFromBackend, valueFromBackend) { if (!_.isArray(valueFromBackend)) { return []; } return _.map(valueFromBackend, convertToLink); } function convertToLink(valueFromBackend) { var linkParams = _.pick(valueFromBackend, 'title', 'query', 'fragment', 'target', 'url'); linkParams.objId = valueFromBackend.obj_id; return scrivito.Link.build(linkParams); } function convertToInteger(valueFromBackend) { var intValue = parseInt(valueFromBackend, 10); if (intValue === 0) { return 0; // otherwise -0 could be returned. } else if (scrivito.types.isValidInteger(intValue)) { return intValue; } return INTEGER_DEFAULT_VALUE; } function convertReferenceToBasicObj(valueFromBackend) { try { return scrivito.BasicObj.get(valueFromBackend); } catch (e) { if (e instanceof scrivito.ResourceNotFoundError) { return null; } throw e; } } function deserializeReferenceValue(typeFromBackend, valueFromBackend) { if (typeFromBackend === 'reference' && valueFromBackend) { return convertReferenceToBasicObj(valueFromBackend); } return null; } function deserializeReferencelistValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'referencelist') { return []; } var objs = _.map(valueFromBackend, convertReferenceToBasicObj); return _.compact(objs); } function deserializeStringValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': case 'html': if (_.isString(valueFromBackend)) { return valueFromBackend; } break; } return ''; } function deserializeStringlistValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'stringlist' || !Array.isArray(valueFromBackend)) { return []; } return valueFromBackend; } function deserializeWidgetlistValue(typeFromBackend, valueFromBackend, model) { if (typeFromBackend !== 'widgetlist') { return []; } return _.map(valueFromBackend, function (widgetId) { return model.widget(widgetId); }); } })(); 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { var SYSTEM_ATTRIBUTES = { _id: 'id', _obj_class: 'objClass', _path: 'path', _permalink: 'permalink', _last_changed: 'lastChanged' }; /** * The base class for CMS objects. * * A CMS object is a collection of properties and their values, as defined * by its object class. * * @borrows scrivito.AttributeContent#get as #get */ scrivito.BasicObj = (function (_scrivito$AttributeContent) { _inherits(BasicObj, _scrivito$AttributeContent); _createClass(BasicObj, null, [{ key: 'fetch', /** * Fetch a given Obj by its `id`. * * @param {string} id - The id of the Obj * @returns {Promise} A promise that resolves to the obj with the given * id. In case no CMS object with the given `id` exists, the promise is rejected with * a {@link scrivito.ResourceNotFoundError}. */ value: function fetch(id) { scrivito.asyncMethodStub(); } /** * Get a given Obj by its `id`. * * @param {string} id - The id of the Obj * @throws {scrivito.ResourceNotFoundError} If the CMS object with the given `id` * does not exists. * @throws {scrivito.NotLoadedError} If the CMS object is not yet loaded. * @returns {scrivito.BasicObj} */ }, { key: 'get', value: function get(id) { var objData = scrivito.ObjDataStore.get(id); return new scrivito.BasicObj(objData); } /** * Create a new {@link scrivito.BasicObj Obj}. * * @param attributes the new obj's attributes. The `_obj_class` has to be provided * * @return {scrivito.BasicObj} the newly created obj. * @throws {scrivito.ArgumentError} if the `_obj_class` is missing or invalid. */ }, { key: 'create', value: function create(attributes) { ensureObjClassExists(attributes._obj_class); if (!attributes._id) { attributes._id = this.generateId(); } return this.createWithSerializedAttributes(_.pick(attributes, '_obj_class', '_id'), attributes); } }, { key: 'createWithDefaults', value: function createWithDefaults(_ref) { var _this = this; var _obj_class = _ref._obj_class; var _path = _ref._path; var attributes = undefined; if (_path) { attributes = { _path: _path }; } return scrivito.ObjClass.find(_obj_class).fetchDefaults(attributes).then(function (serializedAttributes) { return _this.createWithSerializedAttributes(serializedAttributes); }).then(function (obj) { return obj.finishSaving().then(function () { return obj; }); }); } }, { key: 'addChildWithSerializedAttributes', value: function addChildWithSerializedAttributes(parentPath, serializedAttributes) { var objId = scrivito.BasicObj.generateId(); return this.createWithSerializedAttributes(_.extend({}, serializedAttributes, { _id: objId, _path: parentPath + '/' + objId })); } }, { key: 'createWithSerializedAttributes', value: function createWithSerializedAttributes(serializedAttributes, attributeDict) { if (!attributeDict) { return this.createWithSerializedAttributes.apply(this, _toConsumableArray(extractAttributeDict(serializedAttributes))); } var objData = scrivito.ObjDataStore.createObjData(serializedAttributes._id); objData.update(serializedAttributes); var obj = new scrivito.BasicObj(objData); obj.update(attributeDict); return obj; } }, { key: 'generateId', value: function generateId() { return scrivito.random_id(); } /** * Returns an {@link scrivito.ObjSearchIterable} of all {@link scrivito.BasicObj}s. * @return {scrivito.ObjSearchIterable} */ }, { key: 'all', value: function all() { return new scrivito.ObjSearchIterable().batchSize(1000); } /** * Returns an {@link scrivito.ObjSearchIterable} with the given initial subquery consisting * of the four arguments. * * Note that `field` and `value` can also be arrays for searching several fields or searching * for several values. For detailed information see {@link scrivito.ObjSearchIterable}. * * @example * // Look for objects with left-over "Lorem", boosting headline matches: * scrivito.BasicObj.where(:*, :contains, 'Lorem', headline: 2) * * @param {String|String[]} field See {@link scrivito.ObjSearchIterable#and} for details * @param {String} operator See {@link scrivito.ObjSearchIterable#and} for details * @param {String|String[]} value See {@link scrivito.ObjSearchIterable#and} for details * @param {Object} [boost] See {@link scrivito.ObjSearchIterable#and} for details * @return {scrivito.ObjSearchIterable} */ }, { key: 'where', value: function where(field, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; return new scrivito.ObjSearchIterable().and(field, operator, value, boost); } /** * Find the {@link scrivito.BasicObj Obj} with the given path. * Returns `null` if no matching Obj exists. * @param {String} path Path of the {@link scrivito.BasicObj Obj}. * @return {scrivito.BasicObj?} * @throws {scrivito.NotLoadedError} If the CMS object is not yet loaded. */ }, { key: 'findByPath', value: function findByPath(path) { return scrivito.iterable.firstValueFromIterator(this.where('_path', 'equals', path).iterator()); } /** * Returns the {@link scrivito.BasicObj Obj} with the given permalink, or `null` if no * matching Obj exists. * @param {String} permalink The permalink of the {@link scrivito.BasicObj Obj}. * @return {scrivito.BasicObj?} * @throws {scrivito.NotLoadedError} If the CMS object is not yet loaded. */ }, { key: 'findByPermalink', value: function findByPermalink(permalink) { var iterator = this.where('_permalink', 'equals', permalink).iterator(); return scrivito.iterable.firstValueFromIterator(iterator); } /** * The constructor is not part of the public API and should **not** be used. * * Please use {@link scrivito.BasicObj.fetch} to access existing CMS objects or * {@link scrivito.BasicObj.create} to create a new one. */ }]); function BasicObj(objData) { _classCallCheck(this, BasicObj); _get(Object.getPrototypeOf(BasicObj.prototype), 'constructor', this).call(this); this.objData = objData; } /** * The `id` of the CMS object * @type {String} */ _createClass(BasicObj, [{ key: 'getParent', value: function getParent() { if (this._hasParent()) { return scrivito.BasicObj.findByPath(computeParentPath(this.path)); } return null; } }, { key: 'hasConflicts', value: function hasConflicts() { return !!this._current._conflicts; } }, { key: 'fetchParent', /** * Fetches the {@link scrivito.BasicObj} that is the parent of this Obj. * * @returns {Promise} A promise that resolves to the parent Obj. * Resolves to `null` if the obj has no parent. */ value: function fetchParent() { scrivito.asyncMethodStub(); } /** * Returns a list of all child {@link scrivito.BasicObj Objs} * * Throws a {@link scrivito.NotLoadedError} if the children are not yet loaded. * * @type {scrivito.BasicObj[]} */ }, { key: 'update', /** * Updates the attributes of the current CMS object. * * @param {Object} attributes - the new attributes * * @example * // Change the permalink of a CMS object * obj.update({_permalink: '/blog'}); * * @example * // Change a string and reorder widgets * obj.update({title: 'New Title', body: obj.get('body').reverse()}); */ value: function update(attributes) { this._persistWidgets(this, this._objClass, attributes); var patch = scrivito.AttributeSerializer.serialize(this._objClass, attributes); this.objData.update(patch); this._linkResolution.start(); } }, { key: 'copyAsync', value: function copyAsync() { var copyOptions = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; assertValidCopyOptions(copyOptions); return this._copyAttributes().then(function (copiedAttributes) { var serializedAttributes = _.extend(copiedAttributes, copyOptions); var obj = scrivito.BasicObj.createWithSerializedAttributes(serializedAttributes); return obj.finishSaving().then(function () { return obj; }); }); } }, { key: 'moveToAsync', value: function moveToAsync(parentPath) { this.update({ _path: parentPath + '/' + this.id }); return this.finishSaving(); } }, { key: 'markResolvedAsync', value: function markResolvedAsync() { this.update({ _conflicts: null }); return this.finishSaving(); } /** * Resolves when all previous {@link scrivito.BasicObj#update updates} have been persisted. * If an update fails the promise is rejected. * * @returns {Promise} */ }, { key: 'finishSaving', value: function finishSaving() { var _this2 = this; var finish = this._linkResolution.finishResolving().then(function () { return _this2.objData.finishSaving(); }); return new scrivito.PublicPromise(finish); } /** * Access widgets by their ids * * @param {String} id - the widget's id * @returns {?scrivito.BasicWidget} */ }, { key: 'widget', value: function widget(id) { if (this.widgetData(id)) { return scrivito.BasicWidget.build(id, this); } return null; } /** * Returns all widgets of the given CMS object * * @returns {scrivito.BasicWidget[]} */ }, { key: 'widgets', value: function widgets() { var _this3 = this; return _.map(_.keys(this._widgetPool), function (id) { return _this3.widget(id); }); } }, { key: 'widgetData', value: function widgetData(id) { return this._widgetPool[id]; } }, { key: 'generateWidgetId', value: function generateWidgetId() { for (var i = 0; i < 10; i++) { var id = scrivito.random_hex(); if (!this.widget(id)) { return id; } } $.error('Could not generate a new unused widget id.'); } }, { key: 'serializeAttributes', value: function serializeAttributes() { var serializedAttributes = _get(Object.getPrototypeOf(BasicObj.prototype), 'serializeAttributes', this).call(this); delete serializedAttributes._conflicts; delete serializedAttributes._modification; delete serializedAttributes._last_changed; return serializedAttributes; } }, { key: '_hasParent', value: function _hasParent() { return this.path && this.path !== '/'; } }, { key: '_copyAttributes', value: function _copyAttributes() { var objId = scrivito.BasicObj.generateId(); var serializedAttributes = this.serializeAttributes(); var uploadPromises = []; _.each(serializedAttributes, function (typeAndValue, name) { if (name[0] === '_') { delete serializedAttributes[name]; return; } var _typeAndValue = _slicedToArray(typeAndValue, 2); var type = _typeAndValue[0]; var value = _typeAndValue[1]; if (type === 'binary' && value) { var futureBinary = new scrivito.FutureBinary({ idToCopy: value.id }); var promise = futureBinary.into(objId).then(function (binary) { return { name: name, binary: binary }; }); uploadPromises.push(promise); } }); serializedAttributes._id = objId; serializedAttributes._obj_class = this.objClass; serializedAttributes._path = this.path; return scrivito.PublicPromise.all(uploadPromises).then(function (binaries) { _.each(binaries, function (_ref2) { var name = _ref2.name; var binary = _ref2.binary; serializedAttributes[name] = ['binary', { id: binary.id }]; }); return serializedAttributes; }); } }, { key: 'id', get: function get() { return this._current._id; } /** * The object class name of the CMS object * @type {String} */ }, { key: 'objClass', get: function get() { return this._current._obj_class; } /** * The date the CMS object was last changed. * Returns `null` if the obj has not been changed yet. * @type {?Date} */ }, { key: 'lastChanged', get: function get() { if (this._current._last_changed) { return scrivito.parseDate(this._current._last_changed); } return null; } /** * The path of the CMS object * @type {?String} */ }, { key: 'path', get: function get() { return this._current._path || null; } /** * The permalink of the CMS object * @type {?String} */ }, { key: 'permalink', get: function get() { return this._current._permalink || null; } /** * Returns the {@link scrivito.BasicObj} that is the parent of this Obj. * Returns `null` if the obj has no `path` or is the root Obj. * * Throws a {@link scrivito.NotLoadedError} if the parent is not yet loaded. * * @type {?scrivito.BasicObj} */ }, { key: 'parent', get: function get() { return this.getParent(); } }, { key: 'modification', get: function get() { return this._current._modification || null; } }, { key: 'children', get: function get() { if (this.path) { var iterator = scrivito.BasicObj.where('_parent_path', 'equals', this.path).iterator(); return scrivito.iterable.collectValuesFromIterator(iterator); } return []; } /** * Returns an Array of all the ancestor {@link scrivito.BasicObj Objs}, starting at the * root and ending at the parent of this object. * * Throws a {@link scrivito.NotLoadedError} if the ancestors are not yet loaded. * * @type {scrivito.BasicObj[]} */ }, { key: 'ancestors', get: function get() { if (this._hasParent()) { var parentPath = computeParentPath(this.path); return collectPathComponents(parentPath).map(function (ancestorPath) { return scrivito.BasicObj.findByPath(ancestorPath); }); } return []; } }, { key: '_widgetPool', get: function get() { return this._current._widget_pool || {}; } }, { key: '_systemAttributes', get: function get() { return SYSTEM_ATTRIBUTES; } }, { key: '_current', get: function get() { return this.objData.current; } }, { key: '_objClass', get: function get() { return scrivito.ObjClass.find(this.objClass); } }, { key: '_linkResolution', get: function get() { return scrivito.LinkResolution['for'](this.objData); } }]); return BasicObj; })(scrivito.AttributeContent); scrivito.provideAsyncClassMethods(scrivito.BasicObj, { get: 'fetch' }); scrivito.provideAsyncInstanceMethods(scrivito.BasicObj, { getParent: 'fetchParent' }); function ensureObjClassExists(objClass) { if (!objClass) { throw new scrivito.ArgumentError('Please provide an obj class as the "_obj_class" property.'); } if (!scrivito.ObjClass.find(objClass)) { throw new scrivito.ArgumentError('The obj class "' + objClass + '" does not exist.'); } } function extractAttributeDict(attributes) { var serializedAttributes = {}; var attributeDict = {}; _.each(attributes, function (serializedValue, name) { if (_.isArray(serializedValue) && _.first(serializedValue) === 'widgetlist') { var widgetlist = _.last(serializedValue); attributeDict[name] = _.map(widgetlist, function (serializedWidgetAttributes) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidgetAttributes); }); } else { serializedAttributes[name] = serializedValue; } }); if (!serializedAttributes._id) { serializedAttributes._id = scrivito.BasicObj.generateId(); } return [serializedAttributes, attributeDict]; } function collectPathComponents(_x7) { var _arguments2 = arguments; var _again2 = true; _function2: while (_again2) { var path = _x7; _again2 = false; var results = _arguments2.length <= 1 || _arguments2[1] === undefined ? [] : _arguments2[1]; if (path === '/') { return ['/'].concat(_toConsumableArray(results)); } _arguments2 = [_x7 = computeParentPath(path), [path].concat(_toConsumableArray(results))]; _again2 = true; results = undefined; continue _function2; } } function computeParentPath(path) { var pathComponents = path.split('/'); pathComponents.pop(); if (pathComponents.length === 1) { return '/'; } return pathComponents.join('/'); } function assertValidCopyOptions(copyOptions) { var validCopyOptions = ['_path']; if (_.difference(_.keys(copyOptions), validCopyOptions).length) { throw new scrivito.ArgumentError('Currently only "_path" copy option is supported.'); } } })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { var SYSTEM_ATTRIBUTES = { _id: 'id', _obj_class: 'objClass' }; /** * The base class for widgets. * * @example * // Creating and attaching a widget * let widget = new scrivito.BasicWidget({_obj_class: 'TextWidget', text: 'Hello World'}); * obj.update({my_widgetlist: [widget]}); * * @borrows scrivito.AttributeContent#get as #get */ scrivito.BasicWidget = (function (_scrivito$AttributeContent) { _inherits(_class, _scrivito$AttributeContent); _createClass(_class, null, [{ key: 'build', value: function build(id, obj) { var instance = Object.create(scrivito.BasicWidget.prototype); instance._obj = obj; instance._id = id; return instance; } }, { key: 'newWithDefaults', value: function newWithDefaults(widgetClassName) { var widgetClass = scrivito.WidgetClass.find(widgetClassName); return widgetClass.fetchDefaults().then(function (widgetDefaults) { return scrivito.BasicWidget.newWithSerializedAttributes(widgetDefaults); }); } }, { key: 'newWithSerializedAttributes', value: function newWithSerializedAttributes(attributes) { var unserializedAttributes = {}; var serializedAttributes = {}; var objClass = scrivito.WidgetClass.find(attributes._obj_class); _.each(attributes, function (value, name) { if (name === '_obj_class') { unserializedAttributes[name] = value; return; } if (_.isArray(value) && _.first(value) === 'widgetlist') { var attribute = objClass.attribute(name); if (attribute && attribute.type === 'widgetlist') { unserializedAttributes[name] = _.map(_.last(value), function (serializedWidget) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidget); }); } return; } serializedAttributes[name] = value; }); var widget = new scrivito.BasicWidget(unserializedAttributes); widget.preserializedAttributes = serializedAttributes; return widget; } /** * Create a new Widget. * The new Widget must be stored inside a container (i.e. an Obj or another Widget) * before it can be used. * * A widget can be stored inside a container by adding it to widget list by means of * {@link scrivito.BasicObj#update} or {@link scrivito.BasicWidget#update}. * * @param {Object} attributes - the new widget's attributes. The `_obj_class` has to be * provided. */ }]); function _class(attributes) { _classCallCheck(this, _class); _get(Object.getPrototypeOf(_class.prototype), 'constructor', this).call(this); this._attributesToBeSaved = attributes; ensureWidgetClassExists(attributes._obj_class); } /** * The `id` of the widget * @type {String} */ _createClass(_class, [{ key: 'widget', value: function widget(id) { return this.obj.widget(id); } /** * Updates the attributes of the widget. * * @param {Object} attributes - the new attributes * * @example * // Change a string attribute * widget.update({title: 'My new title'}); */ }, { key: 'update', value: function update(attributes) { this._persistWidgets(this.obj, this._objClass, attributes); var patch = scrivito.AttributeSerializer.serialize(this._objClass, attributes); this._updateSelf(patch); } /** * Create a copy of a {@link scrivito.BasicWidget Widget}. * * The copy will have all the attributes of the original widget including its widgets. * Its attributes can be accessed only after it has been stored in a `widgetlist` field * of an {@link scrivito.BasicObj Obj}, since initially the copy is not stored in such a * field. * * @return {scrivito.BasicWidget} a copy of the widget */ }, { key: 'copy', value: function copy() { var serializedAttributes = this.serializeAttributes(); return scrivito.BasicWidget.newWithSerializedAttributes(serializedAttributes); } }, { key: 'persistInObj', value: function persistInObj(obj) { var objClass = scrivito.WidgetClass.find(this._attributesToBeSaved._obj_class); this._persistWidgets(obj, objClass, this._attributesToBeSaved); var patch = scrivito.AttributeSerializer.serialize(objClass, this._attributesToBeSaved); _.extend(patch, this.preserializedAttributes || {}); this._obj = obj; this._id = obj.generateWidgetId(); this._updateSelf(patch); } }, { key: 'isPersisted', value: function isPersisted() { return !!this._obj; } }, { key: 'finishSaving', /** * Resolves when all previous {@link scrivito.BasicWidget#update updates} have been * persisted. If an update fails the promise is rejected. * * @returns {Promise} */ value: function finishSaving() { return this.obj.finishSaving(); } }, { key: '_throwUnpersistedError', value: function _throwUnpersistedError() { throw new scrivito.ScrivitoError('Can not access a new widget before it has been saved.'); } }, { key: '_updateSelf', value: function _updateSelf(patch) { var widgetPoolPatch = { _widget_pool: _defineProperty({}, this.id, patch) }; this.obj.update(widgetPoolPatch); } }, { key: 'id', get: function get() { if (this.isPersisted()) { return this._id; } this._throwUnpersistedError(); } /** * The object class name of the widget * @type {String} */ }, { key: 'objClass', get: function get() { return this._current._obj_class; } /** * The CMS object the widget is contained in * @type {scrivito.BasicObj} */ }, { key: 'obj', get: function get() { if (this.isPersisted()) { return this._obj; } this._throwUnpersistedError(); } }, { key: 'attributesToBeSaved', get: function get() { return this._attributesToBeSaved; } }, { key: '_current', get: function get() { if (this.isPersisted()) { return this.obj.widgetData(this.id); } throw new scrivito.ScrivitoError('Can not access an unpersisted widget.'); } }, { key: '_systemAttributes', get: function get() { return SYSTEM_ATTRIBUTES; } }, { key: '_objClass', get: function get() { return scrivito.WidgetClass.find(this.objClass); } }]); return _class; })(scrivito.AttributeContent); function ensureWidgetClassExists(objClass) { if (!objClass) { throw new scrivito.ArgumentError('Please provide a widget class as the "_obj_class" property.'); } if (!scrivito.WidgetClass.find(objClass)) { throw new scrivito.ArgumentError('The widget class "' + objClass + '" does not exist.'); } } })(); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { /** * The Binary class represents the data stored in a binary attribute * of an [Obj]{@link scrivito.BasicObj} or [Widget]{@link scrivito.BasicWidget}. */ scrivito.Binary = (function () { /** * This `constructor` is not part of the public API and should **not** be used. * * See `{@link scrivito.Binary.upload}` and `{@link scrivito.FutureBinary#into}` * for information on how to create a `Binary`. */ function Binary(id) { _classCallCheck(this, Binary); this.id = id; } /** * Prepares local data for upload to Scrivito. By default, the `type` property of the * passed-in `[Uploadable]{@link scrivito.Binary~Uploadable}` is used as the * content type but can be overridden by `[BinaryOptions]{@link scrivito.Binary~BinaryOptions}`. * If `Uploadable` is a `Blob`, be sure to specify a filename in `BinaryOptions`. * For `File` objects the filename falls back to `File#file`. * * Note: This does not perform the actual upload but returns a `{@link scrivito.FutureBinary}`. * The actual upload can be triggered by putting the FutureBinary `into` a * `{@link scrivito.BasicObj}`. * * @example Using the updateAsync method is the easiest way of uploading "into" an Obj. * * myObj.updateAsync({blob: scrivito.Binary.upload(myLocalFile)}); * * @example It is also possible to update synchronously. * scrivito.Binary.upload(myLocalBlob, myOptions).into(myObj) * .then((uploadedBinary) => myObj.update({blob: uploadedBinary})); * * @example The same applies to object creation. * scrivito.BasicObj.createAsync({ * _obj_class: "Image", * blob: scrivito.Binary.upload(myLocalFile), * }); * * @example This can also be done synchronously. * const myObj = scrivito.BasicObj.create({_obj_class: "Image"}); * * scrivito.Binary.upload(myLocalFile).into(myObj) * .then((uploadedBinary) => myObj.update({blob: uploadedBinary})); * * @param {scrivito.Binary~Uploadable} source * @param {scrivito.Binary~BinaryOptions} [options] * @returns {scrivito.FutureBinary} * @throws {scrivito.ArgumentError} If any of the passed-in `BinaryOptions` is blank * @throws {scrivito.ArgumentError} If the source is not an `Uploadable` * @throws {scrivito.ArgumentError} If `Uploadable` is a `Blob` and no filename was specified */ _createClass(Binary, [{ key: "copy", /** * Prepares the `Binary` for copying. * * Note: This does not perform the actual copying but returns a `{@link scrivito.FutureBinary}`. * The actual copying can be triggered by putting the FutureBinary `into` a * `{@link scrivito.BasicObj}`. * * @example Copying can be done in the same context as scrivito.Binary#upload. * * scrivito.BasicObj * .createAsync({_obj_class: "Image", blob: myBinary.copy(myOptions)}); * * @param {scrivito.Binary~BinaryOptions} [options] * @returns {scrivito.FutureBinary} * @throws {scrivito.ArgumentError} If any of the passed-in * [BinaryOptions]{@link scrivito.Binary~BinaryOptions} is blank */ value: function copy() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; options.idToCopy = this.id; return new scrivito.FutureBinary(options); } }], [{ key: "upload", value: function upload(source) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; options.source = source; return new scrivito.FutureBinary(options); } }]); return Binary; })(); /** * Options to pass when uploading or copying a `Binary`. * @typedef {Object} scrivito.Binary~BinaryOptions * @property {string} filename - The filename to be used for the new Binary; mandatory for blobs. * @property {string} contentType - A content type for overriding the type of the `Uploadable`. */ /** * Local data that can be uploaded to a `Binary` - See * [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}, * [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File}. * @typedef {(Blob|File)} scrivito.Binary~Uploadable */ })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { /** * The FutureBinary class represents the data to be stored in a binary field. * See {@link scrivito.Binary.upload} and {@link scrivito.Binary#copy} for details. */ scrivito.FutureBinary = (function () { /** * This `constructor` is not part of the public API and should **not** be used. * * See `{@link scrivito.Binary.upload}` and `{@link scrivito.Binary#copy}` * for information on how to create a `FutureBinary`. */ function FutureBinary() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, FutureBinary); if (options.idToCopy) { this.idToCopy = options.idToCopy; } else { validateParams(options); this.source = options.source; } if (options.filename) { this.filename = options.filename.replace(/[^\w\-_\.$]/g, '-'); } this.contentType = options.contentType; } /** * This performs the actual upload or copy operation and puts the `FutureBinary` * into the specified `{@link scrivito.BasicObj}`. * * See `{@link scrivito.Binary.upload}` for usage examples. * * @param {scrivito.BasicObj} target - The object you want to upload into * @returns {Promise} */ _createClass(FutureBinary, [{ key: 'into', value: function into(target) { var targetId = undefined; if (_.isString(target)) { targetId = target; } else { targetId = target.id; } var binaryPromise = undefined; if (this.idToCopy) { binaryPromise = scrivito.BinaryRequest.copy(this.idToCopy, targetId, this.filename, this.contentType); } else { binaryPromise = scrivito.BinaryRequest.upload(targetId, this.source, this.filename, this.contentType); } return binaryPromise.then(function (_ref) { var id = _ref.id; return new scrivito.Binary(id); }); } }]); return FutureBinary; })(); function validateParams(options) { if (!scrivito.BinaryUtils.isBlob(options.source)) { throw new scrivito.ArgumentError('Expected a Blob or File as the source.'); } if (!options.contentType) { options.contentType = options.source.type; } if (!options.filename) { if (!scrivito.BinaryUtils.isFile(options.source)) { throw new scrivito.ArgumentError('Expected a filename to be passed with Blob as the source.'); } options.filename = options.source.name; } } })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var NEGATEABLE_OPERATORS = ['equals', 'starts_with', 'is_greater_than', 'is_less_than']; var BOOSTABLE_PARAMETERS = ['contains', 'contains_prefix']; var DEFAULT_BATCH_SIZE = 10; /** * Allows iterating over the results of searches for CMS objects to retrieve instances of * {@link scrivito.BasicObj}. The returned iterator is lazy, meaning it will only as many * objects as are actually needed. * * ## Available fields and their values * * - `'*'` - Searches all fields * - `'_id'` - Id of an {@link scrivito.BasicObj}. This is a `string` field. * - `'_path'` - Path of an {@link scrivito.BasicObj}. This is a `string` field. * - `'_obj_class'` - Object class of an {@link scrivito.BasicObj}. This is a `string` field. * - `'_permalink'` - Permalink of an {@link scrivito.BasicObj}. This is a `string` field. * - `'_last_changed'` - Date of last change to an {@link scrivito.BasicObj}. * - every custom_attribute Custom attribute of an {@link scrivito.BasicObj}. Note that * depending on the attribute type (e.g. an `html` field), some operators cannot be * applied. * * ## Available operators * * ### `contains` and `contains_prefix` * * These operators are intended for full text search of natural language texts. * They are applicable to `string`, `stringlist`, `enum`, `multienum` and `html` fields. * * For `contains` and `contains_prefix`, the examples are based on the following field value: * "Behind every cloud is another cloud." * * **contains** * * Searches for one or more whole words. Each word needs to be present. * * Example subquery values: * * ✔ "behind cloud" (case insensitive) * * ✘ "behi clo" (not whole words) * * ✘ "behind everything" (second word does not match) * * **contains_prefix** * Searches for a word prefix. * * Example subquery values: * * ✔ "Clou" (case insensitive) * * ✔ "Every" (case insensitive) * * **equals** * * The `equals` operator is intended for programmatic comparisons of string and date values. * * The operator has some limits with regard to string length. String values are only guaranteed * to be considered if they are at most 1000 characters in length. * String values of more than 1000 characters may be ignored by these operators. * * For `equals`, the examples are based on the following field value: * "Some content." * * The `field` value needs to be identical to the `value` of this subquery. * * Applicable to `string`, `stringlist`, `enum`, `multienum` and `date` fields. * * Example subquery values: * * ✔ "Some content." (exact value) * * ✘ "Some" (not exact value) * * **starts_with** * * The `starts_with` is intended for programmatic comparions of string values. * * The `starts_with` operator has a precision limit: * Only prefixes of up to 20 characters are guaranteed to be matched. * If you supply a prefix of more than 20 characters, the additional characters may be ignored. * * When combined with the system attribute `_path`, the operator `starts_with` has some special * functionality: * There is not precision limit, i.e. a prefix of arbitrary length may be used to match on * `_path`. * Also, prefix matching on `_path` automatically matches entire path components, * i.e. the prefix matching is delimited by slashes (the character `'/'`). * * For `starts_with`, the examples are based on the following field value: * "Some content." * * The `field` value needs to start exactly with the `value` of this subquery. * * Applicable to `string`, `stringlist`, `enum` and `multienum` fields. * * Example subquery values: * * ✔ "Som" (prefix of the value) * * ✘ "som" (incorrect case of prefix) * * ✘ "content" (not prefix of the whole value) * * **`is_less_than` and `is_greater_than`** * * These operators are intended for comparing `date` or numerical values. They can also be * applied to numerical metadata, for example the width of an image. * It only considers attributes of {@link scrivito.BasicObj Objs} and **not** of * {@link scrivito.BasicWidget Widgets}. Therefore, Widget attributes are not searchable * using the `is_less_than` and `is_greater_than` operators. * * For `is_less_than` and `is_greater_than`, the examples are based on the following date value: * `new Date(2000, 0, 1, 0, 0, 0)` * * **is_less_than** * * Matches if the field value is less than the subquery date value. * * Example subquery values: * * ✔ `new Date(1999, 11, 31, 23, 59, 59)` (is less than) * * ✘ `new Date(2000, 0, 1, 0, 0, 0)` (equal, not less than) * * **is_greater_than** * * Matches if the field value is greater than the subquery string value. * * Example subquery values: * * ✔ `new Date(2000, 0, 1, 0, 0, 1)` (is greater than) * * ✘ `new Date(2000, 0, 1, 0, 0, 0)` (equal, not greater than) * * ### Matching `multienum` and `stringlist` * * Attributes of type `multienum` and `stringlist` contain an array of strings. * Each of these strings is searched individually. * A search query matches a `multienum` or `stringlist`, if at least one string in the list * matches. Example: A query using the operator `:equals` and the value `"Eggs"` matches an * Obj containing `["Spam","Eggs"]` in a `stringlist` or `multienum` attribute. * */ scrivito.ObjSearchIterable = (function () { /** * The constructor is not part of the public API and should **not** be used. * * Please use {@link scrivito.BasicObj.where} or {@link scrivito.BasicObj.all} to initiate * a search. */ function ObjSearchIterable() { _classCallCheck(this, ObjSearchIterable); this._query = []; this._batchSize = DEFAULT_BATCH_SIZE; } /** * Adds the given AND subquery to this {@link scrivito.ObjSearchIterable}. * * Compares the `field(s)` with the `value(s)` using the `operator` of this subquery. * All CMS objects to which this criterion applies remain in the result set. * * @param {String|String[]} field Name(s) of the field(s) to be searched. * For arrays, the subquery matches if one or more of these fields meet this criterion. * @param {String} operator See "Currently available operators" above. * @param {String|Date|Time|Number|String[]|Date[]|Time[]|Number[]} value The value(s) * to compare with the field value(s) using the `operator` of this subquery. For arrays, * the subquery matches if the condition is met for one or more of the array elements. * @param {Object} [boost={}] A hash where the keys are field names and their values are * boosting factors. Boosting factors must be in the range from 1 to 10. Boosting can only * be applied to subqueries in which the `contains` or `contains_prefix` operator is used. * @return {scrivito.ObjSearchIterable} itself * * @example * // Searching for the string "scrivito" and boosting the fields "headline" and "keywords" * scrivito.BasicObj.where('*', 'contains', 'scrivito', { headline: 5, keywords: 10 }); */ _createClass(ObjSearchIterable, [{ key: 'and', value: function and(field, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var subQuery = buildSubQuery(field, operator, value); if (boost) { ensureBoostableOperator(operator); subQuery.boost = boost; } this._query.push(subQuery); return this; } /** * Adds the given negated AND subquery to this {@link scrivito.ObjSearchIterable}. * * Compares the `field(s)` with the `value(s)` using the negated `operator` of this subquery. * All CMS objects to which this criterion applies are removed from the result set. * * @param {String|String[]} field Name(s) of the field(s) to be searched. * For arrays, the subquery matches if one or more of these fields meet this criterion. * @param {String} operator Must be one of: `equals`, `starts_with`, `is_greater_than`, * `is_less_than`. (See "Available operators" above). * @param {String|Date|Time|Number|String[]|Date[]|Time[]|Number[]} value The value(s) to * compare with the field value(s) using the `operator` of this subquery. For arrays, * the subquery matches if the condition is met for one or more of the array elements. * @return {scrivito.ObjSearchIterable} itself */ }, { key: 'andNot', value: function andNot(field, operator, value) { var subQuery = buildSubQuery(field, operator, value); ensureNegetableOperator(operator); subQuery.negate = true; this._query.push(subQuery); return this; } /** * The `offset` from which a given set of objs are yielded. Mostly used to build * paginations. * * @param {Integer} offset * @return {scrivito.ObjSearchIterable} itself */ }, { key: 'offset', value: function offset(_offset) { this._offset = _offset; return this; } /** * Orders the results by `field_name`. * * Applicable to the attribute types `string`, `enum` and `date`. * * There is a precision limit when sorting string values: * Only the first 50 characters of a string are guaranteed to be considered when sorting * search results. * * @param {String} field This parameter specifies the field by which the hits are * sorted (e.g. `'_path'`). * * @param {String} [direction='asc'] This parameter specifies in which direction the * search results are ordered. Valid values are `asc` and `desc`. * * @example * scrivito.BasicObj.all.order('_last_changed', 'desc') * * @return {scrivito.ObjSearchIterable} itself */ }, { key: 'order', value: function order(field) { var direction = arguments.length <= 1 || arguments[1] === undefined ? 'asc' : arguments[1]; this._sortBy = field; this._sortDirection = direction; return this; } /** * Number of search results to be returned by each of the internal search requests. If the * `batchSize` is not specified, it defaults to `10`. * * @param {Integer} batchSize number of search results to be returned by each of the * internal search requests. The batch size is capped at `100`. * * @return {scrivito.ObjSearchIterable} itself */ }, { key: 'batchSize', value: function batchSize(_batchSize) { this._batchSize = _batchSize; return this; } /** * Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator). * Calling the iterators `next` function will either return a {@link scrivito.BasicObj} or * throw a {@link scrivito.NotLoadedError} error, if the data is not available locally. * * By calling the {@link scrivito.NotLoadedError#load load} function of the thrown data * the next batch of objs is fetched and iteration can continue. * * @throws {scrivito.NotLoadedError} If some of the data is not yet loaded. * @return {Iterator} An iterator over the search results. */ }, { key: 'iterator', value: function iterator() { var queryIterator = scrivito.ObjQueryStore.get(this._params, this._batchSize); return { next: function next() { var _queryIterator$next = queryIterator.next(); var done = _queryIterator$next.done; var value = _queryIterator$next.value; if (done) { return { done: done }; } return { done: done, value: new scrivito.BasicObj(value) }; } }; } // For test purposes only }, { key: 'getBatchSize', // For test purposes only value: function getBatchSize() { return this._batchSize; } }, { key: 'params', get: function get() { return this._params; } }, { key: '_params', get: function get() { return removeUndefined({ query: this._query, offset: this._offset, sort_by: this._sortBy, sort_order: this._sortDirection }); } }]); return ObjSearchIterable; })(); function removeUndefined(obj) { return _.pick(obj, function (item) { return item !== undefined; }); } function buildSubQuery(field, publicOperator, unserializedValue) { var operator = convertOperator(publicOperator); var value = convertValue(unserializedValue); return { field: field, operator: operator, value: value }; } function ensureBoostableOperator(operator) { if (!_.contains(BOOSTABLE_PARAMETERS, operator)) { throw new scrivito.ArgumentError('Boosting operator "' + operator + '" is invalid.'); } } function ensureNegetableOperator(operator) { if (!_.contains(NEGATEABLE_OPERATORS, operator)) { throw new scrivito.ArgumentError('Negating operator "' + operator + '" is invalid.'); } } function convertValue(value) { if (_.isArray(value)) { return _.map(value, convertSingleValue); } return convertSingleValue(value); } function convertSingleValue(value) { if (_.isDate(value)) { return scrivito.types.formatDateToString(value); } return value; } function convertOperator(operator) { switch (operator) { case 'contains': return 'search'; case 'contains_prefix': return 'prefix_search'; case 'equals': return 'equal'; case 'starts_with': return 'prefix'; case 'is_greater_than': return 'greater_than'; case 'is_less_than': return 'less_than'; default: throw new scrivito.ArgumentError('Operator "' + operator + '" is invalid.'); } } })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.Attribute = (function () { _createClass(Attribute, null, [{ key: 'isSystemAttribute', value: function isSystemAttribute(name) { return name[0] === '_'; } }]); function Attribute(attributeData) { _classCallCheck(this, Attribute); this.name = attributeData.name; this.type = attributeData.type; this._validClassNames = attributeData.validClasses; this._validValues = attributeData.validValues; } // public _createClass(Attribute, [{ key: 'validValues', value: function validValues() { this._assertValidTypes(['enum', 'multienum'], 'Only enum and multienum attributes can have valid values'); return this._validValues || []; } }, { key: 'validClasses', value: function validClasses() { this._assertValidTypes(['reference', 'referencelist'], 'Only reference and referencelist attributes can have valid classes'); if (this._validClassNames) { return _.map(this._validClassNames, function (name) { return scrivito.ObjClass.find(name); }); } } // private }, { key: '_assertValidTypes', value: function _assertValidTypes(validTypes, errorMessage) { if (!_.include(validTypes, this.type)) { $.error(errorMessage); } } }]); return Attribute; })(); })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.AttributeContentClass = (function () { _createClass(AttributeContentClass, null, [{ key: 'init', value: function init(classDatas) { var _this = this; this.objClasses = _.map(classDatas, function (classData) { return new _this(classData); }); } }, { key: 'find', value: function find(name) { return _.findWhere(this.objClasses, { name: name }); } }]); function AttributeContentClass(classData) { _classCallCheck(this, AttributeContentClass); this.name = classData.name; this.descriptionForEditor = classData.descriptionForEditor; this.attributes = _.map(classData.attributes, function (attributeData) { return new scrivito.Attribute(attributeData); }); } // public _createClass(AttributeContentClass, [{ key: 'attribute', value: function attribute(name) { return _.findWhere(this.attributes, { name: name }); } }, { key: 'fetchDefaults', value: function fetchDefaults(attributes) { this._ensureDefaultAttributesAreValid(attributes); var path = 'obj_class/' + this.name + '/defaults'; if (attributes) { path += '?' + $.param({ attributes: attributes }); } var request = scrivito.ajax('GET', path); return scrivito.Promise.resolve(request); } }, { key: '_ensureDefaultAttributesAreValid', value: function _ensureDefaultAttributesAreValid(attributes) { if (attributes && !_.isEqual(_.keys(attributes), ['_path'])) { throw new scrivito.InternalError('Currently only "_path" as attribute is supported'); } } }]); return AttributeContentClass; })(); })(); 'use strict'; (function () { scrivito.binaryFieldElement = { create_instance: function create_instance(cmsElement) { if (cmsElement.dom_element().attr('data-scrivito-field-type') === 'binary') { var _ret = (function () { var that = scrivito.cms_field_element.create_instance(cmsElement); var bufferedWriter = new scrivito.BufferedWriter(function (value) { if (scrivito.BinaryUtils.isFile(value)) { return scrivito.Binary.upload(value).into(that.basic_obj()); } if (value instanceof scrivito.FutureBinary) { return value.into(that.basic_obj()); } return scrivito.Promise.resolve(value); }); _.extend(that, { preprocess: function preprocess(value) { return bufferedWriter.write(value)['catch'](function (error) { scrivito.handleAjaxError(error); throw error; }); } }); return { v: that }; })(); if (typeof _ret === 'object') return _ret.v; } } }; scrivito.cms_element.definitions.push(scrivito.binaryFieldElement); })(); (function() { _.extend(scrivito, { child_list_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-child-list-path')) { var that = cms_element; _.extend(that, { path: function() { return that.dom_element().attr('data-scrivito-private-child-list-path'); }, obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-child-list-order-obj-id'), description_for_editor: that.dom_element() .attr('data-scrivito-private-obj-description-for-editor') }); }, fetch_page_class_selection: function() { return scrivito.obj.fetch_page_class_selection({parent_path: that.path()}); }, allowed_classes: function() { return JSON.parse( that.dom_element().attr('data-scrivito-private-child-list-allowed-classes')); }, create_child: function(obj_class) { var id = scrivito.random_id(); return scrivito.obj.create({ _id: id, _path: that.path() + '/' + id, _obj_class: obj_class }); }, children: function() { return _.map(that.dom_element().find('>[data-scrivito-private-obj-id]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); }, has_child_order: function() { return !!that.dom_element().attr('data-scrivito-private-child-list-order-obj-id'); }, save_order: function() { if (that.has_child_order()) { var new_child_order = _.map(that.children(), function(child) { return child.obj().id(); }); return that.obj().save({child_order: new_child_order}); } else { $.error("Can't save order, when child order is not allowed!"); } }, is_valid_child_class: function(obj_class) { var allowed_classes = that.allowed_classes(); if (allowed_classes) { return _.contains(allowed_classes, obj_class); } else { return true; } } }); return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-private-child-list-path]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.child_list_element); }()); (function() { _.extend(scrivito, { cms_document: { // return offset of given element relative to scrivito window offset: function(dom_element) { var document = scrivito.cms_document.from(dom_element); return document.offset(dom_element); }, local_jquery: function(dom_element) { return scrivito.cms_document.from($(dom_element)).local_jquery(dom_element); }, from: function(dom_element) { var element_document; if (!dom_element.jquery) { dom_element = $(dom_element); } if (dom_element.length === 0) { $.error("empty jquery instance given"); } if (dom_element[0].ownerDocument) { element_document = $(dom_element[0].ownerDocument); } else if (dom_element[0].nodeType === 9) { element_document = dom_element; } else { $.error("scrivito.cms_document.from must be called with " + "a dom element"); } return scrivito.cms_element.from_dom_element(element_document); }, create_instance: function(cms_element) { if (cms_element.dom_element()[0].nodeType === 9) { return create_instance(cms_element); } }, // for testing purposes only resetPublicApi: function() { additionaPublicApi = {}; }, registerPublicApi: function(namespace, implementationFactory) { additionaPublicApi[namespace] = implementationFactory; } } }); var additionaPublicApi = {}; var page_config_attr_name = 'data-scrivito-private-page-config'; var create_instance = function(cms_element) { var that = cms_element; // PUBLIC _.extend(that, { installPublicApi: function() { local_$().fn.scrivito = scrivito.jquery_plugin; browser_window.scrivito = _.extend({}, that.additionaPublicApi(), { // @api public on: local_on_function, trigger: scrivito.trigger, create_obj: scrivito.create_obj, delete_obj: scrivito.delete_obj, obj_where: scrivito.obj_where, is_current_page_restricted: scrivito.is_current_page_restricted, in_editable_view: scrivito.in_editable_view, register_default_obj_class_for_content_type: scrivito.register_default_obj_class_for_content_type, default_obj_class_for_content_type: scrivito.default_obj_class_for_content_type, page_menu: function() { return scrivito.page_menu(that); }, define_editor: function(name, editor) { scrivito.editor_selection.create_instance(that).define(name, editor); }, select_editor: function(select_editor) { that.select_editor = select_editor; }, upload_binary: function(params) { return scrivito.Binary.upload(params.blob || params.file, { filename: params.filename, contentType: params.content_type, }); }, suggest_completion: scrivito.suggest_completion, description_for_editor: scrivito.description_for_editor, // @api protected path_for_id: scrivito.path_for_id, id_from_path: scrivito.id_from_path, // @api protected dialog: function(content, options) { var iframe = that.window().iframe(); return scrivito.custom_dialog(iframe, browser_document, content, options); } }); // @api public public_getter_setter(browser_window.scrivito, [ 'menu_order', 'popular_obj_classes' ]); }, additionaPublicApi: function() { var publicApi = {}; var doc = that.dom_element()[0]; _.each(additionaPublicApi, function(implementationFactory, namespace) { publicApi[namespace] = implementationFactory(doc); }); return publicApi; }, assert_user_logged_in: function() { if (that.user_id() !== scrivito.user.current.id()) { // editing is either no longer allowed, or user changed => closing UI scrivito.change_location(window.location, window.parent); } }, connect: function() { if (connect_initiated) { $.error("document connected twice!"); } if (scrivito.cms_window.is_living_window(browser_window)) { connect_initiated = true; return that.preload_objs().then(function() { _.each(load_callbacks, function(callback) { scrivito.run_new_event(callback); }); connected = true; scrivito.gui.new_document(that); scrivito.gui.new_content(that.dom_element()[0]); }); } else { scrivito.log_info("document inside closed window, " + "refusing to connect"); } }, preload_objs: function() { if (scrivito.editing_context.is_editing_mode()) { _.each(that.preloaded_obj_data(), function(obj_data) { return scrivito.ObjDataStore.store(obj_data); }); return scrivito.cms_field_element.preload(that.dom_element()); } return scrivito.Promise.resolve(); }, notify_new_content: function(content) { return connected && _.map(content_callbacks, function(callback) { var promise = $.Deferred(); scrivito.run_new_event(function() { try { callback.apply(this, [content]); } finally { promise.resolve(); } }); return promise; }); }, add_app_extensions: function() { var app_extension_tags = scrivito.ui_config().app_extension_tags; browser_window.document.write(app_extension_tags); }, window: function() { return scrivito.cms_window.from(browser_window); }, // return the given dom element using the local jQuery lib or the lib itself. local_jquery: function(element) { return element ? local_$()(element) : local_$(); }, browser_window: function() { return browser_window; }, // Return offset of given element relative to scrivito window. offset: function(dom_element) { var element_offset = $(dom_element).offset(); var iframe_offset = $(that.window().iframe()).offset(); if (iframe_offset) { return { top: iframe_offset.top - $(browser_window.document).scrollTop() + element_offset.top, left: iframe_offset.left - $(browser_window.document).scrollLeft() + element_offset.left }; } else { return element_offset; } }, page: function() { var config = that.page_config(); if (config && !_.isEmpty(config.current_page)) { return scrivito.obj.create_instance(config.current_page); } }, user_id: function() { var config = that.page_config(); if (config) { return config.user_id; } }, preloaded_obj_data: function() { var config = that.page_config(); if (config) { return config.preloaded_obj_data; } }, page_config: function() { return scrivito.dom_config.read(that.dom_element().find('body'), page_config_attr_name); }, // For test purpose only. mock_page_config: function(config) { if (config) { scrivito.dom_config.write(that.dom_element().find('body'), page_config_attr_name, config); } else { that.dom_element().find('body').removeAttr(page_config_attr_name); } }, // For test purpose only. mock_current_page: function(attrs) { that.mock_page_config({current_page: attrs}); } }); // PRIVATE var browser_document = cms_element.dom_element()[0]; var browser_window = browser_document.defaultView; var local_$ = function() { if (browser_window.jQuery) { return browser_window.jQuery; } else { var jquery_missing = 'jQuery is missing! ' + 'In order for Scrivito to work, jQuery is needed. ' + 'Please add jQuery to your assets.'; scrivito.alertDialog(jquery_missing); $.error(jquery_missing); } }; var connected = false; var connect_initiated = false; var load_callbacks = []; var content_callbacks = []; var local_on_function = function(event, callback) { if (event === "load") { if (!connected) { load_callbacks.push(callback); } else { scrivito.run_new_event(callback); } } else if (event === "content") { content_callbacks.push(callback); if (connected) { scrivito.run_new_event(function() { callback(browser_document); }); } } else { $.error("unknown event " + event); } }; return that; }; var public_getter_setter = function(item, attributes) { _.each(attributes, function(attribute) { Object.defineProperty(item, attribute, { get: function() { return scrivito[attribute]; }, set: function(new_value) { scrivito[attribute] = new_value; } }); }); }; scrivito.cms_element.definitions.push(scrivito.cms_document); }()); (function() { var has_original_content = function(field_type) { return _.contains([ 'binary', 'date', 'enum', 'html', 'link', 'linklist', 'multienum', 'reference', 'referencelist', 'string', 'stringlist' ], field_type); }; var has_save_via_model = function(field_type) { return _.contains([ 'binary', 'date', 'enum', 'html', 'link', 'linklist', 'multienum', 'reference', 'referencelist', 'string', 'stringlist', ], field_type); }; _.extend(scrivito, { cms_field_element: { create_instance: function(cms_element) { var that = cms_element; var to_be_saved_data; var basic_obj; _.extend(that, { field_name: function() { return that.dom_element().attr('data-scrivito-field-name'); }, field_type: function() { return that.dom_element().attr('data-scrivito-field-type'); }, obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-field-obj-id'), obj_class: that.dom_element().attr('data-scrivito-field-obj-class') }); }, workspace_id: function() { return that.dom_element().attr('data-scrivito-private-field-workspace-id'); }, widget: function() { var widget_id = that.dom_element().attr('data-scrivito-private-field-widget-id'); if (widget_id) { return scrivito.widget.create_instance(that.obj(), widget_id, that.dom_element().attr('data-scrivito-widget-obj-class')); } }, save: function(content) { assert_valid_workspace_id(); if (content === undefined) { if (that.content) { content = that.content(); } else { $.error("Can't save without content"); } } if (has_save_via_model(that.field_type())) { return save_via_model(content, that.container()); } else { return queue_save_request(content); } }, preprocess: function(value) { return scrivito.Promise.resolve(value); }, preload_model: function() { var id = that.dom_element().attr('data-scrivito-private-field-obj-id'); return scrivito.BasicObj.fetch(id).then(function(obj) { basic_obj = obj; }); }, // For test purposes only inject_basic_obj: function(obj) { basic_obj = obj; }, basic_obj: function() { if (!basic_obj) { $.error('#basic_obj accessed before it was loaded'); } return basic_obj; }, basic_widget: function() { var widget_id = that.dom_element().attr('data-scrivito-private-field-widget-id'); var basic_obj = that.basic_obj(); if (widget_id) { return basic_obj.widget(widget_id); } }, container: function() { return that.basic_widget() || that.basic_obj(); }, original_content: function() { assert_valid_workspace_id(); if (has_original_content(that.field_type())) { var raw_value = scrivito.json_parse_base64( that.dom_element().attr('data-scrivito-private-field-original-content')); return prepare_original_content(raw_value, that.field_type()); } else { $.error('Fields of type ' + that.field_type() + ' do not support original content'); } }, set_original_content: function(content) { if (has_original_content(that.field_type())) { that.dom_element().attr('data-scrivito-private-field-original-content', scrivito.json_stringify_base64(content)); } }, valid_values: function() { return that.dom_element().data('scrivito-private-field-allowed-values'); }, valid_classes: function() { var model = that.widget() || that.obj(); var model_class = model.model_class(); var attribute = model_class.attribute(that.field_name()); return _.pluck(attribute.validClasses(), 'name'); } }); var assert_valid_workspace_id = function() { if (that.workspace_id() !== scrivito.editing_context.selected_workspace.id()) { $.error('Tried to edit cms data from wrong workspace!'); } }; var save_via_model = function(content, container) { var saving_promise = that.preprocess(content).then(function(value) { var changes = {}; changes[that.field_name()] = value; container.update(changes); return container.finishSaving().catch(function() { throw new Error(scrivito.t('ajax_error.communication')); }); }); return scrivito.promise.wrapInJqueryDeferred(saving_promise); }; var queue_save_request = function(content) { var request_promise = $.Deferred(); var to_be_saved = to_be_saved_data || {}; to_be_saved.value = content; to_be_saved.promises = to_be_saved.promises || []; to_be_saved.promises.push(request_promise); to_be_saved_data = to_be_saved; if (!currently_saving()) { next_save_request(); } return request_promise.then(function(model_data) { return model_data[that.field_name()]; }); }; var next_save_request = function() { currently_saving(true); var to_be_saved = to_be_saved_data; to_be_saved_data = undefined; var changes = {}; changes[that.field_name()] = to_be_saved.value; var widget = that.widget(); var save_promise = widget ? widget.save(changes) : that.obj().save(changes); save_promise.done(function(result) { _.each(to_be_saved.promises, function(succeeding_promise) { succeeding_promise.resolve(result); }); if (to_be_saved_data) { next_save_request(); } else { remove_currently_saving(); } }).fail(function(error) { var new_promises = (to_be_saved_data || {}).promises; var failing_promises = to_be_saved.promises.concat(new_promises || []); _.each(failing_promises, function(failing_promise) { failing_promise.reject(error); }); to_be_saved_data = undefined; remove_currently_saving(); }); }; var currently_saving = function(new_currently_saving) { if (new_currently_saving) { return that.dom_element().data('scrivito-currently-saving', new_currently_saving); } else { return that.dom_element().data('scrivito-currently-saving'); } }; var remove_currently_saving = function() { that.dom_element().removeData('scrivito-currently-saving'); }; var prepare_original_content = function(value, field_type) { if (value && field_type === 'date') { var DateClass = scrivito.cms_document.from(that.dom_element()).browser_window().Date; return new DateClass(value); } if (value && field_type === 'binary') { return new scrivito.UploadedBlob( value.id, value.url, value.filename, that.obj().id(), that.field_name()); } return value; }; return that; }, preload: function(root_element) { var all_cms_elements = scrivito.cms_element.all( '[data-scrivito-field-type]', root_element); var preload_promises = []; _.each(all_cms_elements, function(cms_element) { if (cms_element.preload_model) { preload_promises.push(cms_element.preload_model()); } }); var all_preloads = scrivito.Promise.all(preload_promises); all_preloads.catch(function(error) { scrivito.errorDialog( 'An error occured while loading some of the page contents. Please reload.', error.message ); }); return all_preloads; } } }); }()); (function() { scrivito.cms_window = { from: function(element) { if (!element) { $.error("no element given!"); } var browser_window; if (element.jquery && element[0].tagName === "IFRAME") { var doc = $(element).contents()[0]; browser_window = doc.defaultView; } else { browser_window = element; } if (!scrivito.cms_window.is_living_window(browser_window)) { $.error("element is a closed browser window or " + "not a window element at all"); } var instance = find_instance(browser_window); if (!instance) { instance = create_instance(browser_window); store_instance(instance); } return instance; }, is_living_window: function(maybe_window) { if (!$.isWindow(maybe_window)) { return false; } // IE frees iframe resources once removed from the DOM // this way you can still test if the window is closed if (maybe_window.parent === maybe_window.self) { return maybe_window.self === top; } return !maybe_window.closed; }, // for test purposes only! instances: function() { return instances; } }; var instances = []; var create_instance = function(browser_window) { // PUBLIC var that = { document: function() { return scrivito.cms_element.from_dom_element($(browser_window.document)); }, on: function(event, callback) { if (event !== "document") { $.error("invalid event name: " + event); } document_callbacks.push(callback); }, notify_new_document: function(document) { _.each(document_callbacks, function(callback) { callback(document); }); }, browser_window: function() { return browser_window; }, reload: function() { return withSavingOverlay(scrivito.reload(browser_window)); }, redirect_to: function(location) { return withSavingOverlay(scrivito.redirect_to(location, browser_window)); }, use_fragment_of: function(other_cms_window) { if (that === other_cms_window) { return; } var ui_hash = other_cms_window.browser_window().location.hash; if (ui_hash) { var src_uri = new URI(that.iframe().src); src_uri.fragment(ui_hash); that.iframe().src = src_uri.href(); } }, is_frame: function() { return browser_window.parent !== browser_window; }, iframe: _.once(function() { return _.find($(browser_window.parent.document).find('iframe'), function(iframe) { // Remove this try-catch after non-iframe mode has been disabled. try { return $(iframe).contents()[0].defaultView === browser_window; } catch (e) { // Ignore cross-origin security errors. } }); }) }; // PRIVATE var document_callbacks = []; var withSavingOverlay = function(promise) { promise = scrivito.withSavingOverlay(promise); var my_frame = that.iframe(); if (my_frame) { $(my_frame).one('load', function() { promise.resolve(); }); } return promise; }; return that; }; var cleanup_instances = function() { // remove closed windows to allow the garbage collector to reap them instances = _.reject(instances, function(instance) { var win = instance.browser_window(); var closed = true; if (win) { try { closed = !scrivito.cms_window.is_living_window(win); } catch(e) { // some browser prevent us from accessing closed windows // by throwing an error } } return closed; }); }; var find_instance = function(browser_window) { cleanup_instances(); return _.detect(instances, function(instance) { return instance.browser_window() === browser_window; }); }; var store_instance = function(instance) { instances.push(instance); }; }()); (function() { _.extend(scrivito, { date_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'date') { return scrivito.cms_field_element.create_instance(cms_element); } }, all: function() { return _.map($('[data-scrivito-field-type="date"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.date_field_element); }()); (function() { _.extend(scrivito, { html_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'html') { var that = scrivito.cms_field_element.create_instance(cms_element); _.extend(that, { content: function() { var content = that.dom_element().html(); return $.trim(content); } }); return that; } }, all: function() { return _.map($('[data-scrivito-field-type="html"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.html_field_element); }()); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var allowedAttributes = ['fragment', 'obj', 'query', 'target', 'title', 'url']; /** * This class represents individual external or internal links Scrivito is able to identify and * to process. */ scrivito.Link = (function () { _createClass(Link, null, [{ key: 'build', /** * This method is not part of the public API and should **not** be used. */ value: function build(attributes) { var objId = attributes.objId; delete attributes.objId; var link = new scrivito.Link(attributes); if (objId) { link._objId = objId; } return link; } /** * Create a new Link. * The new Link must be stored inside a container (i.e. a CMS object or a Widget) * before it can be used. * * A Link can be stored inside a container by adding it to a `link` or `linklist` attribute * by means of {@link scrivito.BasicObj#update} or {@link scrivito.BasicWidget#update}. * * @param {Object} attributes - the attributes of the new Link. * @throws {scrivito.ArgumentError} If invalid attributes are given. */ }]); function Link(attributes) { _classCallCheck(this, Link); ensureValidPublicAttributes(attributes); this._fragment = attributes.fragment || null; this._query = attributes.query || null; this._target = attributes.target || null; this._title = attributes.title || null; this._url = attributes.url || null; this._objId = null; if (attributes.obj) { this._objId = attributes.obj.id; } } /** * The `title` of the Link object. * @type {?String} */ _createClass(Link, [{ key: 'fetchObj', /** * Fetch the {@link scrivito.BasicObj|CMS object} this link references. * @returns {Promise} A promise that resolves to the obj that this link * references. In case no CMS object with the given `id` exists, the promise is rejected with * a {@link scrivito.ResourceNotFoundError}. In case the link is external, the promise is * rejected with a {@link scrivito.ScrivitoError}. */ value: function fetchObj() { if (this.isExternal()) { return scrivito.PublicPromise.reject(new scrivito.ScrivitoError('The link is external and does not reference an object.')); } return scrivito.BasicObj.fetch(this.objId); } /** * Does this Link object point to an external location? * @returns {Boolean} `true` if this Link points to an external location. */ }, { key: 'isExternal', value: function isExternal() { return !!this.url; } /** * Does this Link object point to a CMS object? * @returns {Boolean} `true` if this Link points to a CMS object. */ }, { key: 'isInternal', value: function isInternal() { return !this.isExternal(); } /** * Copies this Link and changes some attributes. * @param {Object} attributes - the attributes of the new Link. * @throws {scrivito.ArgumentError} If invalid attributes are given. * @returns {scrivito.Link} */ }, { key: 'copy', value: function copy(attributes) { ensureValidPublicAttributes(attributes); var newAttributes = _.pick(this, 'title', 'query', 'fragment', 'target', 'url', 'objId'); if (_.has(attributes, 'obj')) { delete newAttributes.objId; } _.extend(newAttributes, attributes); return scrivito.Link.build(newAttributes); } }, { key: 'title', get: function get() { return this._title; } /** * The `query` string of the Link object as in "index.html?query". * See {@link http://www.ietf.org/rfc/rfc3986.txt|RFC3986} for details. * @type {?String} */ }, { key: 'query', get: function get() { return this._query; } /** * The `fragment` string of the Link object as in "index.html#fragment". * See {@link http://www.ietf.org/rfc/rfc3986.txt|RFC3986} for details. * @type {?String} */ }, { key: 'fragment', get: function get() { return this._fragment; } /** * The `target` of the Link object. * `target` refers to the equally-named HTML attribute, not the link destination. * @type {?String} */ }, { key: 'target', get: function get() { return this._target; } /** * The external `url` of the Link object. Returns `null` if the link is internal. * @type {?String} */ }, { key: 'url', get: function get() { return this._url; } /** * The ID of the {@link scrivito.BasicObj|CMS object} this link references. * Returns `null` if the link is external. * @type {?String} */ }, { key: 'objId', get: function get() { return this._objId; } /** * The {@link scrivito.BasicObj|CMS object} this link references. * Returns `null` if the link is external. * @throws {scrivito.NotLoadedError} If the CMS object is not yet loaded. * @throws {scrivito.ResourceNotFoundError} If the CMS object does not exists. * @type {?scrivito.BasicObj} */ }, { key: 'obj', get: function get() { if (this.objId) { return scrivito.BasicObj.get(this.objId); } return null; } }]); return Link; })(); function ensureValidPublicAttributes(attributes) { var _ref; var unknownAttrs = (_ref = _).without.apply(_ref, [_.keys(attributes)].concat(allowedAttributes)); if (!_.isEmpty(unknownAttrs)) { throw new scrivito.ArgumentError('Unexpected attributes ' + scrivito.prettyPrint(unknownAttrs) + '.' + (' Available attributes: ' + scrivito.prettyPrint(allowedAttributes))); } } })(); (function() { var write_promises = {}; _.extend(scrivito, { obj: { create_instance: function(params) { var that = { id: function() { return params.id; }, obj_class: function() { return params.obj_class; }, model_class: function() { return scrivito.ObjClass.find(params.obj_class); }, description_for_editor: function() { return params.description_for_editor; }, modification: function() { return params.modification; }, is_new: function() { return that.modification() === 'new'; }, is_edited: function() { return that.modification() === 'edited'; }, is_deleted: function() { return that.modification() === 'deleted'; }, has_children: function() { return !!params.has_children; }, has_conflict: function() { return !!params.has_conflict; }, has_restriction : function() { return that.restriction_messages().length > 0; }, restriction_messages: function() { return params.restriction_messages || []; }, is_binary: function() { return !!params.is_binary; }, has_details_view: function() { return !!params.has_details_view; }, tooltip: function() { if (editing_state()) { return scrivito.t('obj.tooltip.' + editing_state()); } }, last_changed: function() { return params.last_changed; }, parent_path: function() { return params.parent_path; }, save: function(attrs) { return scrivito.ObjSerializer.serialize(that.id(), attrs) .then(function(serialized_attrs) { return that.enqueue_ajax('PUT', 'objs/'+that.id(), {data: {obj: serialized_attrs}}); }); }, destroy: function() { return that.enqueue_ajax('DELETE', 'objs/'+that.id()).then(function(result) { return result.redirect_to; }); }, revert: function() { return that.enqueue_ajax('PUT', 'objs/'+that.id()+'/revert'); }, revert_widget: function(widget_id) { return that.enqueue_ajax('PUT', 'objs/'+that.id()+'/revert_widget?widget_id='+widget_id); }, conflicting_workspaces: function() { return that.enqueue_ajax('GET', 'objs/'+that.id()+'/conflicting_workspaces') .then(function(workspace_datas) { return scrivito.workspace.from_data_collection(workspace_datas); }); }, restore: function() { return that.enqueue_ajax('PUT', 'objs/'+that.id()+'/restore'); }, restore_widget: function(widget_id) { return that.enqueue_ajax('PUT', 'objs/'+that.id()+'/restore_widget?widget_id='+widget_id); }, details_src: function() { // TODO unify with ajax url generation return '/__scrivito/page_details/' + that.id(); }, transfer_modifications_to: function(workspace_id) { return that.enqueue_ajax('PUT', 'objs/'+that.id()+'/transfer_modifications', {data: {workspace_id: workspace_id}}); }, reload: function() { return that.enqueue_ajax('GET', 'objs/'+that.id()).then(function(data) { params.has_conflict = data.has_conflict; params.modification = data.modification; }); }, reload_widget: function(widget_id) { return that.enqueue_ajax('GET', 'objs/'+that.id()+'/widget?widget_id='+widget_id); }, enqueue_ajax: function() { var args = arguments; var ajax = function() { return scrivito.ajax.apply(null, args); }; if (args[0] === 'GET') { return ajax(); } var promise = $.Deferred(); (write_promises[that.id()] || $.Deferred().resolve()).always(function() { ajax().then( function() { promise.resolve.apply(promise, arguments); }, function() { promise.reject.apply(promise, arguments); } ); }); write_promises[that.id()] = promise; return promise; } }; var editing_state = function() { if (that.is_new()) { return 'is_new'; } if (that.is_edited()) { return 'is_edited'; } if (that.is_deleted()) { return 'is_deleted'; } }; return that; }, fetch_class_selection: function(path, params) { if (params) { path += '?'+$.param(params); } return scrivito.ajax('GET', path).then(function(selection) { var names = _.pluck(selection, 'name'); var recent = scrivito.obj_class_selection.recent(names); var all_popular_valid_obj_classes = _.intersection(scrivito.popular_obj_classes, names); var popular = _.take(all_popular_valid_obj_classes, 5); return { all: _.sortBy(selection, 'name'), recent: _.map(recent, function(name) { return _.findWhere(selection, {name: name}); }), popular: _.map(popular, function(name) { return _.findWhere(selection, {name: name}); }) }; }); }, fetch_page_class_selection: function(params) { return scrivito.obj.fetch_class_selection('objs/page_class_selection', params); }, create: function(attrs) { attrs._id = scrivito.random_id(); return scrivito.ObjSerializer.serialize(attrs._id, attrs).then(function(serialized_attrs) { var params = {data: {obj: serialized_attrs}}; return scrivito.ajax('POST', 'objs', params).then(function(obj_data) { scrivito.obj_class_selection.store(serialized_attrs._obj_class); return scrivito.obj.create_instance(obj_data); }); }); }, transfer_modifications: function(objs, workspace_id) { return $.when.apply(null, _.map(objs, function(obj) { return obj.transfer_modifications_to(workspace_id).then(function(result) { if (result.status !== 'success') { return {obj: obj, reason: result.reason}; } }); })).then(function() { return $.Deferred().resolve(_.compact(arguments)); }); }, // For test purpose only. clear_write_promises: function() { write_promises = {}; } } }); }()); (function() { _.extend(scrivito, { obj_changes: function() { return scrivito.obj_where('_modification', 'equals', ['new', 'edited', 'deleted']). batch_size(100). order('_last_changed'). reverse_order(). format('_default'). include_deleted(); } }); }()); "use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { scrivito.ObjClass = (function (_scrivito$AttributeContentClass) { _inherits(ObjClass, _scrivito$AttributeContentClass); function ObjClass() { _classCallCheck(this, ObjClass); _get(Object.getPrototypeOf(ObjClass.prototype), "constructor", this).apply(this, arguments); } return ObjClass; })(scrivito.AttributeContentClass); })(); (function() { _.extend(scrivito, { obj_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-obj-id')) { var that = cms_element; _.extend(that, { obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-obj-id'), description_for_editor: that.dom_element() .attr('data-scrivito-private-obj-description-for-editor') }); } }); return that; } }, // for testing purposes only all: function() { return _.map($('[data-scrivito-private-obj-id]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.obj_element); }()); (function() { _.extend(scrivito, { chainable_search: { create_instance: function(build_query, continuation, fetched_ids) { var query = build_query || {predicates: []}; fetched_ids = fetched_ids || []; var add_predicate = function(field, operator, value, boost, negate) { var new_query = { field: field, operator: operator, value: serialize_values(value) }; if (negate) { new_query.negate = true; } if (boost) { new_query.boost = boost; } query.predicates.push(new_query); return that; }; var execute_search = function(query, action) { var get_params = { query: JSON.stringify(query), query_action: action }; if (continuation) { get_params.continuation = continuation; } return scrivito.ajax('GET', 'objs/search?' + $.param(get_params)); }; var that = { // @api public query: function() { return query; }, // @api public and: function(field_or_search, operator, value, boost) { if (_.isString(field_or_search)) { add_predicate(field_or_search, operator, value, boost); } else { var other_predicates = field_or_search.query().predicates; query.predicates = query.predicates.concat(other_predicates); } return that; }, // @api public and_not: function(field, operator, value) { add_predicate(field, operator, value, undefined, true); return that; }, // @api public offset: function(offset) { query.offset = offset; return that; }, // @api public order: function(order) { if (_.isString(order)) { query.order = [order, 'asc']; } else { query.order = _.first(_.pairs(order)); } return that; }, // @api public reverse_order: function() { if (query.order) { query.order[1] = query.order[1] === 'asc' ? 'desc' : 'asc'; return that; } else { $.error("A search order has to be specified before reverse_order can be applied."); } }, // @api public batch_size: function(batch_size) { query.batch_size = batch_size; return that; }, // @api public format: function(name) { query.format = name; return that; }, // @api public include_deleted: function() { query.include_deleted = true; return that; }, // @api beta facet: function(attribute_name, options) { return scrivito.ajax('GET', 'objs/search?' + $.param({ query: JSON.stringify(query), facet: JSON.stringify({attribute: attribute_name, options: options || {}}) })); }, // @api public load_batch: function() { var offset = query.offset || 0; var next; return execute_search(query).then(function(result) { var batch_size = result.hits.length; var total_matches = result.total; var next_continuation = result.continuation; result = filter_duplicates(result, fetched_ids); if (next_continuation) { next = scrivito.chainable_search.create_instance( query, next_continuation, result.fetched_ids ); } else { total_matches = result.fetched_ids.length; next = undefined; } var public_result = {total: total_matches, hits: result.hits}; return $.Deferred().resolve(public_result, next); }); }, // @api public size: function() { return execute_search(query, 'size').then(function(result) { return $.Deferred().resolve(result.total); }); }, // @api public clone: function() { var cloned_query = $.extend(true, {}, query); return scrivito.chainable_search.create_instance(cloned_query); } }; return that; } } }); var filter_duplicates = function(result, fetched_ids) { var filtered_result = { hits: [], fetched_ids: _.clone(fetched_ids || []) }; _.each(result.hits, function(hit) { if(!_.contains(filtered_result.fetched_ids, hit.id)) { filtered_result.hits.push(hit.serialized_obj); filtered_result.fetched_ids.push(hit.id); } }); return filtered_result; }; var serialize_values = function(values) { if (!_.isArray(values)) { values = [values]; } return _.map(values, function(value) { return [type_of_value(value), convert_value(value)]; }); }; var convert_value = function(value) { var serialized_value = scrivito.ObjSerializer.serializeValue(value); if (serialized_value === null) { return serialized_value; } else { return String(serialized_value); } }; var type_of_value = function(value) { if (_.isDate(value)) { return 'date'; } else { return 'string'; } }; }()); (function() { _.extend(scrivito, { // @api public obj_where: function(field, operator, value, boost) { return scrivito.chainable_search.create_instance().and(field, operator, value, boost); } }); }()); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var cache = {}; var publishedRevisionId = undefined; scrivito.Revision = (function () { function Revision(attributes) { _classCallCheck(this, Revision); this._attributes = attributes; } _createClass(Revision, [{ key: 'id', get: function get() { return this._attributes.id; } }, { key: 'title', get: function get() { return this._attributes.title || this.publishedAtForEditor; } }, { key: 'publishedAt', get: function get() { return scrivito.parseDate(this._attributes.published_at); } }, { key: 'changesCount', get: function get() { return this._attributes.changes_count; } }, { key: 'isPublished', get: function get() { return this.id === publishedRevisionId; } }, { key: 'publishedAtForEditor', get: function get() { return moment(this.publishedAt).format('lll'); } }], [{ key: 'init', value: function init(config) { publishedRevisionId = config.published_revision_id; } }, { key: 'getRecent', value: function getRecent() { if (cache.revisions) { return cache.revisions; } if (cache.error) { throw cache.error; } throw new scrivito.NotLoadedError(loadRecent); } // For test purpose only. }, { key: 'clearCache', // For test purpose only. value: function clearCache() { cache = {}; } }, { key: 'cache', get: function get() { return cache; }, // For test purpose only. set: function set(newCache) { cache = newCache; } }]); return Revision; })(); function loadRecent() { return scrivito.CmsRestApi.get('workspaces/published/revisions').then(function (response) { cache.revisions = _.map(response.results, function (attributes) { return new scrivito.Revision(attributes); }); cache.revisions.isLimited = response.limited; })['catch'](function (error) { cache = { error: error }; }); } })(); (function() { var field_types = [ 'enum', 'link', 'linklist', 'multienum', 'reference', 'referencelist', 'stringlist' ]; _.extend(scrivito, { standard_field_element: { create_instance: function(cms_element) { if (_.include(field_types, cms_element.dom_element().attr('data-scrivito-field-type'))) { return scrivito.cms_field_element.create_instance(cms_element); } } } }); scrivito.cms_element.definitions.push(scrivito.standard_field_element); }()); (function() { _.extend(scrivito, { string_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'string') { var that = scrivito.cms_field_element.create_instance(cms_element); _.extend(that, { content: function() { var content = that.dom_element().text(); return $.trim(content); } }); return that; } }, all: function() { return _.map($('[data-scrivito-field-type="string"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.string_field_element); }()); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.UploadedBlob = (function () { function UploadedBlob(id, url, filename, objId, fieldName) { _classCallCheck(this, UploadedBlob); this._id = id; this.url = url; this.filename = filename; this._objId = objId; this._fieldName = fieldName; } _createClass(UploadedBlob, [{ key: 'noCacheUrl', value: function noCacheUrl() { var path = 'objs/' + this._objId + '/binary_no_cache?' + $.param({ attribute_name: this._fieldName }); return scrivito.ajax('GET', path).then(function (response) { return response.no_cache_url; }); } }, { key: 'copy', value: function copy() { var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return new scrivito.FutureBinary({ idToCopy: this._id, filename: params.filename, contentType: params.content_type }); } }]); return UploadedBlob; })(); })(); (function() { _.extend(scrivito, { user: { init: function(config) { scrivito.user.current = scrivito.user.create_instance(config.current); }, create_instance: function(params) { var that = { id: function() { return params.id; }, description: function() { return params.description; } }; return that; }, suggest: function(input) { return scrivito.ajax('GET', 'users/suggest?input=' + input); } } }); }()); (function() { _.extend(scrivito, { widget: { create_instance: function(obj, id, widget_class_name, options) { options = options || {}; var that = { id: function() { return id; }, obj: function() { return obj; }, widget_class_name: function() { return widget_class_name; }, model_class: function() { return scrivito.WidgetClass.find(that.widget_class_name()); }, modification: function() { return options.modification; }, placement_modification: function() { return options.placement_modification; }, description_for_editor: function() { return options.description_for_editor; }, is_modified: function() { return !!that.modification(); }, is_new: function() { return that.modification() === 'new'; }, is_edited: function() { return that.modification() === 'edited'; }, is_deleted: function() { return that.modification() === 'deleted'; }, is_placement_modified: function() { return !!that.placement_modification(); }, save: function(widget_attributes) { var obj_attributes = build_obj_attributes(widget_attributes); return that.obj().save(obj_attributes).then(function(obj_data) { return obj_data._widget_pool[that.id()]; }); }, details_src: function() { // TODO unify with ajax url generation return "/__scrivito/" + markup_url('widget_details'); }, revert: function() { return that.obj().revert_widget(that.id()).then(function() { options.modification = null; }); }, restore: function() { return that.obj().restore_widget(that.id()).then(function() { options.modification = null; }); }, fetch_markup: function(template_name, inner_tag) { var params = { template_name: template_name, inner_tag: inner_tag }; return scrivito.ajax('GET', markup_url('show_widget') + '?' + $.param(params), {dataType: 'html'}); }, reload: function() { return that.obj().reload_widget(that.id()).then(function(data) { options.modification = data.modification; }); } }; var build_obj_attributes = function(widget_attributes) { var obj_attributes = {_widget_pool: {}}; obj_attributes._widget_pool[that.id()] = widget_attributes; return obj_attributes; }; var markup_url = function(action_name) { var obj_id = that.obj().id(); var widget_id = that.id(); return 'render_widget/'+obj_id+'/'+action_name+'/'+widget_id; }; return that; } } }); }()); "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { scrivito.WidgetClass = (function (_scrivito$AttributeContentClass) { _inherits(WidgetClass, _scrivito$AttributeContentClass); function WidgetClass(classData) { _classCallCheck(this, WidgetClass); _get(Object.getPrototypeOf(WidgetClass.prototype), "constructor", this).call(this, classData); this.embeds = classData.embeds; this._embeddingAttribute = classData.embeddingAttribute; } // public _createClass(WidgetClass, [{ key: "embeddingAttribute", value: function embeddingAttribute() { if (this.embeds) { return this.attribute(this._embeddingAttribute); } } }]); return WidgetClass; })(scrivito.AttributeContentClass); })(); (function() { _.extend(scrivito, { widget_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-widget-id')) { var that = cms_element; var basic_obj; _.extend(that, { widget: function() { var dom_element = that.dom_element(); return scrivito.widget.create_instance(that.widget_field().obj(), dom_element.attr('data-scrivito-private-widget-id'), dom_element.attr('data-scrivito-widget-obj-class'), { modification: dom_element.attr('data-scrivito-private-widget-modification'), placement_modification: dom_element.attr( 'data-scrivito-private-widget-placement-modification'), description_for_editor: dom_element.attr( 'data-scrivito-private-widget-description-for-editor') } ); }, widget_field: function() { return scrivito.cms_element.from_dom_element(that.dom_element().parent()); }, has_details_view: function() { return !!that.dom_element().attr('data-scrivito-private-widget-has-details-view'); }, fetch_markup: function() { var template_name = that.widget_field().template_name(); var inner_tag = that.widget_field().inner_tag(); return that.widget().fetch_markup(template_name, inner_tag); }, details_src: function() { return that.widget().details_src(); }, field_name: function() { return that.widget_field().field_name(); }, has_widgetlist: function() { return !!that.dom_element().find('[data-scrivito-field-type=widgetlist]').length; }, basic_widget: function() { var widget_id = that.dom_element().attr('data-scrivito-private-widget-id'); return that.widget_field().basic_obj().widget(widget_id); } }); return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-private-widget-id]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.widget_element); }()); (function() { _.extend(scrivito, { widgetlist_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'widgetlist') { var that = scrivito.cms_field_element.create_instance(cms_element); _.extend(that, { content: function() { return _.map(that.widget_elements(), function(widget_element) { return widget_element.widget().id(); }); }, widget_elements: function() { return _.map(that.dom_element().children(), function(element) { var dom_element = $(element); if (dom_element.is('[data-scrivito-private-widget-id]')) { return scrivito.cms_element.from_dom_element(dom_element); } else { // Remove the "scrivito_skip_widget_markup_validation"-hack after drag_n_drool // took place of widget_sorting. if (!dom_element.hasClass('scrivito_skip_widget_markup_validation')) { scrivito.throw_error('Scrivito found a widget with invalid markup', { params: [element], description: scrivito.t('widgetlist_field_element.markup_error') }); } } }); }, is_empty: function() { return that.widget_elements().length === 0; }, add_widget: function(widget, widget_element, position) { var current_widgets = that.container().get(that.field_name()) || []; var index; if (widget_element) { index = widget_element.dom_element() .prevAll('[data-scrivito-private-widget-id]').length; if (position === 'bottom') { index += 1; } } else { index = that.widget_elements().length; } current_widgets.splice(index, 0, widget); var update_params = {}; update_params[that.field_name()] = current_widgets; that.container().update(update_params); return that.container().finishSaving().then(function() { scrivito.obj_class_selection.store(widget.objClass); var old_widget = scrivito.widget.create_instance(that.obj(), widget.id); return insert_widget(old_widget, widget_element, position); }); }, remove_widget: function(widget_element) { var current_widgets = that.container().get(that.field_name()) || []; var widget_id = widget_element.basic_widget().id; var new_widgets = _.reject(current_widgets, function(widget) { return widget.id === widget_id; }); var update_params = {}; update_params[that.field_name()] = new_widgets; that.container().update(update_params); widget_element.dom_element().remove(); scrivito.widgetlistFieldPlaceholder.update(that); return that.container().finishSaving(); }, fetch_widget_class_selection: function() { var params = {field_name: that.field_name()}; if (that.widget()) { params.widget_id = that.widget().id(); } return scrivito.obj.fetch_class_selection( 'objs/'+that.obj().id()+'/widget_class_selection', params); }, allowed_classes: function() { return _.map(allowed_classes_json(), function(obj_class) { return obj_class.name; }); }, allowed_classes_for_create: function() { return that.allowed_classes(); }, can_create_widget: function() { return that.allowed_classes_for_create().length !== 0; }, can_choose_widget_class: function() { return that.allowed_classes_for_create().length > 1; }, description_for_allowed_classes: function() { return _.map(allowed_classes_json(), function(allowed_class_json) { return allowed_class_json.description; }); }, description_for_allowed_class: function(class_name) { var allowed_class = _.findWhere(allowed_classes_json(), {name: class_name}); if (allowed_class) { return allowed_class.description; } }, is_valid_child_class: function(widget_class_name) { var allowed_classes = that.allowed_classes(); if (allowed_classes) { return _.contains(allowed_classes, widget_class_name); } else { return true; } }, template_name: function() { return that.dom_element().attr('data-scrivito-private-field-widget-template'); }, inner_tag: function() { return that.dom_element().attr('data-scrivito-private-field-widget-inner-tag'); } }); var allowed_classes_json = function() { return JSON.parse(that.dom_element() .attr('data-scrivito-private-field-widget-allowed-classes')); }; var insert_widget = function(widget, widget_element, position) { return widget.fetch_markup(that.template_name(), that.inner_tag()).then( function(widget_markup) { var dom_element = $($.trim(widget_markup)); if (widget_element) { if (position === 'bottom') { widget_element.dom_element().after(dom_element); } else { widget_element.dom_element().before(dom_element); } } else { that.dom_element().prepend(dom_element); } scrivito.gui.new_content(dom_element.get(0)); scrivito.ensure_fully_visible_within_window(dom_element); scrivito.widgetlistFieldPlaceholder.update(that); return widget; }); }; return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-field-type="widgetlist"]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.widgetlist_field_element); }()); (function() { _.extend(scrivito, { workspace: { from_data: function(data) { var that = { id: function() { return data.id; }, title: function() { return that.original_title() || default_title(); }, original_title: function() { return data.title; }, icon: function() { return that.is_published() ? '' : ''; }, memberships: function() { return data.memberships; }, is_published: function() { return that.id() === 'published'; }, is_auto_update: function() { return data.auto_update; }, is_editable: function() { return !that.is_published(); }, check: function() { return check(0).then(function(result) { return handle_check_result(result, []); }); }, publish_approval: function(certificates) { return scrivito.silent_ajax('PUT', 'workspaces/' + that.id() + '/publish_approval', { data: { certificates: certificates } }); }, check_and_publish: function() { var maximum_check_duration_in_ms = 20000; return check_and_publish(Date.now() + maximum_check_duration_in_ms); }, rebase: function() { var promise = scrivito.withAjaxErrorHandling( scrivito.CmsRestApi.put('workspaces/' + that.id() + '/rebase')); return scrivito.promise.wrapInJqueryDeferred(promise); }, rename: function(title) { var promise = scrivito.withAjaxErrorHandling( scrivito.CmsRestApi.put('workspaces/' + that.id(), {workspace: {title: title}})); return scrivito.promise.wrapInJqueryDeferred(promise); }, update_memberships: function(memberships) { var promise = scrivito.withAjaxErrorHandling( scrivito.CmsRestApi.put('workspaces/' + that.id(), {workspace: {memberships: memberships}})); return scrivito.promise.wrapInJqueryDeferred(promise); }, destroy: function() { var promise = scrivito.withAjaxErrorHandling( scrivito.CmsRestApi.delete('workspaces/' + that.id())); return scrivito.promise.wrapInJqueryDeferred(promise); }, has_conflicts: function() { return scrivito.obj_where('_conflicts', 'equals', true).size().then(function(size) { var promise = $.Deferred(); return size === 0 ? promise.reject() : promise.resolve(); }); }, owners: function() { return _.map(_.where(that.memberships(), {role: 'owner'}), function(membership) { return scrivito.user.create_instance({ id: membership.user_id, description: membership.description }); }); }, is_accessible: function() { return data.id === 'published' || data.is_accessible; }, other_editable: function() { return scrivito.workspace.editable().then(function(workspaces) { return _.reject(workspaces, function(workspace) { return workspace.id() === that.id(); }); }); }, sort_value: function() { return that.is_published() ? '' : that.title().toUpperCase(); } }; var check_and_publish = function(retry_until_in_ms) { return scrivito.Promise.resolve(that.check()).then(function(certificates) { if (certificates) { return that.publish_approval(certificates); } else { return scrivito.Promise.reject({ type: 'check_failed' }); } }).then(function(approval) { return scrivito.CmsRestApi.put('workspaces/' + that.id() + '/publish', approval); }).catch(function(error) { return handle_check_and_publish_error(error, retry_until_in_ms); }); }; var check = function(offset) { return scrivito.silent_ajax('GET', 'workspaces/' + that.id() + '/check?from=' + offset); }; var handle_check_result = function(result, certificates) { if (result.result === 'fail') { return $.Deferred().resolve(false); } certificates.push(result.certificate); if (result.pass.until === 'END') { return $.Deferred().resolve(certificates); } else { var offset = parseInt(result.pass.until, 10) + 1; return check(offset).then(function(result) { return handle_check_result(result, certificates); }); } }; var handle_outdated_error = function(error) { if (that.is_auto_update()) { return that.check_and_publish(); } else { scrivito.logError(error.message); scrivito.alertDialog(error.message); return scrivito.Promise.reject(error); } }; var handle_check_and_publish_error = function(error, retry_until_in_ms) { var backend_code = error.backend_code; var contentStateError = 'precondition_not_verifiable.workspace.publish.content_state_id'; if (error.type == 'check_failed') { return scrivito.Promise.reject(error); } if (backend_code === contentStateError) { return handle_outdated_error(error); } if (backend_code === 'precondition_not_met.workspace.publish.content_state_id') { // The workspace has been changed since last check. if (Date.now() > retry_until_in_ms) { // retried check_and_publish for too long. return $.Deferred().reject({type: 'outdated_certificates'}); } else { // retry again return scrivito.wait(1).then(function() { return check_and_publish(retry_until_in_ms); }); } } else if (backend_code === 'precondition_not_met.workspace.publish.exceeds_obj_limit') { scrivito.logError(error.message); scrivito.errorDialog(scrivito.t('workspace.publish_error.exceeds_obj_limit'), [error.timestamp, error.message]); return scrivito.Promise.reject(error); } else { scrivito.display_ajax_error(error); return scrivito.Promise.reject(error); } }; var default_title = function() { if (that.is_published()) { return scrivito.t('workspace.title_published'); } else { return scrivito.t('workspace.empty_title'); } }; return that; }, from_data_collection: function(workspace_datas) { return _.chain(workspace_datas) .map(function(data) { return scrivito.workspace.from_data(data); }) .sortBy(function(workspace) { return workspace.sort_value(); }) .value(); }, all: function() { return scrivito.ajax('GET', 'workspaces').then(function(workspace_datas) { return scrivito.workspace.from_data_collection(workspace_datas); }); }, editable: function() { return scrivito.workspace.all().then(function(workspaces) { return _.select(workspaces, function(workspace) { return workspace.is_editable(); }); }); }, published: function() { return scrivito.workspace.from_data({id: 'published'}); }, create: function(title, revision_id) { var params = {workspace: { title: title, auto_update: true, restore_revision: revision_id }}; var userId = scrivito.SessionKeeper.userId; if (userId !== null) { params.workspace.memberships = {}; params.workspace.memberships[userId] = {role: 'owner'}; } var promise = scrivito.CmsRestApi.post('workspaces', params).then(function(ws_data) { return scrivito.workspace.from_data(ws_data); }, function(error) { if (error.backendCode === 'precondition_not_met.workspace.create.exceeds_limit') { scrivito.workspace_limit_exceeded(); } else { scrivito.handleAjaxError(error); } return scrivito.Promise.reject(); }); return scrivito.promise.wrapInJqueryDeferred(promise); } } }); }()); 'use strict'; (function () { scrivito.addSubpageCommand = function (childListElement) { return scrivito.command.create_instance({ id: 'scrivito.sdk.add_subpage', title: scrivito.t('commands.add_subpage.title'), icon: '', tooltip: scrivito.t('commands.add_subpage.tooltip', childListElement.obj().description_for_editor()), execute: function execute() { var classSelection = childListElement.fetch_page_class_selection(); var chooseObjClass = scrivito.chooseObjClassDialog(classSelection, 'add_child_page'); return chooseObjClass.then(function (objClass) { var addSubpage = scrivito.BasicObj.createWithDefaults({ _obj_class: objClass, _path: childListElement.path() + '/' + scrivito.random_id() }); return scrivito.withSavingOverlay(addSubpage); }).then(function (obj) { return scrivito.application_window.redirect_to(scrivito.path_for_id(obj.id)); }); } }); }; })(); (function() { _.extend(scrivito, { child_list_commands: { init: function() { if (scrivito.editing_context.is_editing_mode()) { scrivito.on('content', function(content) { _.each(scrivito.child_list_element.all($(content)), function(child_list_element) { child_list_element.set_menu([ scrivito.addSubpageCommand(child_list_element), scrivito.copyObjFromClipboardCommand(child_list_element), scrivito.moveObjFromClipboardCommand(child_list_element), scrivito.sort_items_command(child_list_element) ].concat(child_list_element.menu())); }); }); } } } }); }()); (function() { _.extend(scrivito, { choose_and_create_widget_command: function(cms_element, position) { var widgetlist_field_element, widget_element; if (cms_element.widget_field) { widget_element = cms_element; widgetlist_field_element = widget_element.widget_field(); } else { widgetlist_field_element = cms_element; } return scrivito.command.create_instance({ id: 'scrivito.sdk.choose_and_create_widget', title: scrivito.t('commands.choose_and_create_widget.title'), icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && (widget_element || widgetlist_field_element.is_empty()) && (widgetlist_field_element.can_choose_widget_class() || !widgetlist_field_element.can_create_widget()); }, disabled: function() { if (!widgetlist_field_element.can_create_widget()) { return scrivito.t('commands.choose_and_create_widget.disabled'); } }, execute: function() { var choose_obj_class = scrivito.chooseObjClassDialog( widgetlist_field_element.fetch_widget_class_selection(), 'create_widget'); return choose_obj_class.then(function(obj_class) { scrivito.obj_class_selection.store(obj_class); var add_widget = scrivito.BasicWidget.newWithDefaults(obj_class) .then(function(new_widget) { return widgetlist_field_element.add_widget(new_widget, widget_element, position); }); return scrivito.withSavingOverlay(add_widget); }); } }); } }); }()); (function() { _.extend(scrivito, { command: { create_instance: function(params) { var that = { id: function() { return params.id; }, dom_id: function() { return params.id.replace(/\./g, '_'); }, title: function() { var title = params.title; return typeof title === 'function' ? title() : title; }, icon: function() { return params.icon || ''; }, subtitle: function() { return params.subtitle; }, tooltip: function() { return params.tooltip; }, is_present: function() { var is_present = params.present; switch (typeof is_present) { case 'undefined': return true; case 'function': return !!is_present(); default: return !!is_present; } }, is_enabled: function() { return !that.is_disabled(); }, is_disabled: function() { return !!that.reason_for_being_disabled(); }, is_action_required: function() { var is_action_required = params.action_required; return typeof is_action_required === 'function' && is_action_required(); }, reason_for_being_disabled: function() { var reason_for_being_disabled = params.disabled; if (typeof reason_for_being_disabled === 'function') { return reason_for_being_disabled(); } }, update: function() { if (that.needs_update()) { return params.update(); } }, needs_update: function() { return !!params.update; }, execute: function() { if (that.is_present() && that.is_enabled()) { params.execute(); return true; } return false; }, update_params: function(new_params) { return _.extend(params, new_params); } }; return that; } } }); }()); (function() { _.extend(scrivito, { command_separator: { create_instance: function(params) { return { id: function() { return params.id; }, title: function() { return params.title; }, update_params: function(new_params) { return _.extend(params, new_params); } }; } } }); }()); 'use strict'; (function () { scrivito.copyObjFromClipboardCommand = function (childListElement) { return scrivito.command.create_instance({ id: 'scrivito.sdk.copy_obj_from_clipboard', title: scrivito.t('commands.copy_obj_from_clipboard.title'), icon: '', present: function present() { return scrivito.objClipboard.isPresent(); }, disabled: function disabled() { var objClass = scrivito.objClipboard.serializedAttributes._obj_class; if (!childListElement.is_valid_child_class(objClass)) { return scrivito.t('commands.copy_obj_from_clipboard.paste_forbidden', childListElement.allowed_classes().join(', ')); } }, execute: function execute() { return scrivito.withSavingOverlay(createObj(childListElement.path())).then(redirectToObj); } }); }; function createObj(parentPath) { var attributes = scrivito.objClipboard.serializedAttributes; var obj = scrivito.BasicObj.addChildWithSerializedAttributes(parentPath, attributes); return obj.finishSaving().then(function () { return obj.id; }); } function redirectToObj(objId) { return scrivito.application_window.redirect_to(scrivito.path_for_id(objId)); } })(); (function() { _.extend(scrivito, { copy_widget_from_clipboard_command: function(cms_element) { var widgetlist_field_element, widget_element; if (cms_element.widget_field) { widget_element = cms_element; } else { widgetlist_field_element = cms_element; } return scrivito.command.create_instance({ id: 'scrivito.sdk.copy_widget_from_clipboard', title: function() { return scrivito.t('commands.copy_widget_from_clipboard.title'); }, icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && scrivito.widgetClipboard.isPresent() && (widget_element || widgetlist_field_element.is_empty()); }, disabled: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widget_field(); } var widget_class_name = scrivito.widgetClipboard.objClass(); if (!widgetlist_field_element.is_valid_child_class(widget_class_name)) { return scrivito.t('commands.copy_widget_from_clipboard.paste_forbidden', widgetlist_field_element.description_for_allowed_classes().join(', ')); } }, execute: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widget_field(); } var widget = scrivito.widgetClipboard.widget(); return scrivito.withSavingOverlay( widgetlist_field_element.add_widget(widget, widget_element) ); } }); } }); }()); 'use strict'; (function () { scrivito.createPageCommand = function () { return scrivito.command.create_instance({ id: 'scrivito.sdk.create_page', title: scrivito.t('commands.create_page.title'), icon: '', disabled: function disabled() { if (!scrivito.editing_context.selected_workspace.is_editable()) { return scrivito.t('commands.create_page.published_workspace'); } if (scrivito.editing_context.is_deleted_mode()) { return scrivito.t('commands.create_page.deleted_mode'); } }, execute: function execute() { chooseObjClass().then(createPage).then(redirectToPage); } }); }; function chooseObjClass() { var classSelection = scrivito.obj.fetch_page_class_selection(); return scrivito.chooseObjClassDialog(classSelection, 'create_page'); } function createPage(objClass) { return scrivito.withSavingOverlay(scrivito.BasicObj.createWithDefaults({ _obj_class: objClass })); } function redirectToPage(page) { return scrivito.application_window.redirect_to(scrivito.path_for_id(page.id)); } })(); (function() { _.extend(scrivito, { create_widget_command: function(cms_element, position) { var widgetlist_field_element, widget_element, description, obj_class; if (cms_element.widget_field) { widget_element = cms_element; widgetlist_field_element = widget_element.widget_field(); } else { widgetlist_field_element = cms_element; } obj_class = widgetlist_field_element.allowed_classes_for_create()[0]; description = widgetlist_field_element.description_for_allowed_class(obj_class); return scrivito.command.create_instance({ id: 'scrivito.sdk.create_widget', title: scrivito.t('commands.create_widget.title', description), icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && (widget_element || widgetlist_field_element.is_empty()) && widgetlist_field_element.can_create_widget() && !widgetlist_field_element.can_choose_widget_class(); }, execute: function() { var add_widget = scrivito.BasicWidget.newWithDefaults(obj_class).then(function(widget) { return widgetlist_field_element.add_widget(widget, widget_element, position); }); return scrivito.withSavingOverlay(add_widget); } }); } }); }()); (function() { _.extend(scrivito, { create_workspace_command: function() { return scrivito.command.create_instance({ id: 'scrivito.sdk.create_workspace', title: scrivito.t('commands.create_workspace.title'), icon: '', disabled: function() { if (!scrivito.user_permissions.can('create_workspace')) { return scrivito.t('commands.create_workspace.forbidden'); } }, execute: function() { scrivito.prompt_dialog({ title: scrivito.t('commands.create_workspace.dialog.title'), description: scrivito.t('commands.create_workspace.dialog.description'), placeholder: scrivito.t('commands.create_workspace.dialog.placeholder'), icon: '', color: 'green', accept_button_text: scrivito.t('commands.create_workspace.dialog.accept'), accept_button_color: 'green', allow_blank: true, }).then(function(title) { scrivito.withSavingOverlay(scrivito.workspace.create(title)).then(function(workspace) { var params = {workspace_id: workspace.id()}; if (!scrivito.editing_context.selected_workspace.is_editable()) { params.display_mode = 'editing'; } return scrivito.change_editing_context(params); }); }); } }); } }); }()); 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function () { scrivito.currentPageCommands = { init: function init() { scrivito.gui.on('document', function (cmsDocument) { var currentPage = cmsDocument.page(); var commands = [scrivito.createPageCommand()]; if (currentPage) { commands = commands.concat([scrivito.obj_details_command(currentPage), scrivito.current_page_link_command(), createCommandSeparator(1), scrivito.saveObjToClipboardCommand(currentPage), scrivito.duplicateObjCommand(currentPage), createCommandSeparator(2), scrivito.markResolvedObjCommand(currentPage), scrivito.restore_obj_command(currentPage), scrivito.revert_obj_command(currentPage), scrivito.delete_obj_command(currentPage)]); } commands = [].concat(_toConsumableArray(commands), [createCommandSeparator(3), scrivito.openUserGuideCommand()], _toConsumableArray(cmsDocument.menu())); cmsDocument.set_menu(commands); }); } }; function createCommandSeparator(index) { var id = 'scrivito.sdk.currentPageCommands.separator' + index; return scrivito.command_separator.create_instance({ id: id }); } })(); (function() { _.extend(scrivito, { current_page_link_command: function() { return scrivito.command.create_instance({ id: 'scrivito.sdk.current_page_link', icon: 'scrivito_icon_link', title: scrivito.t('commands.current_page_link.title'), disabled: function() { if (scrivito.application_document().page().is_deleted()) { return scrivito.t('commands.current_page_link.is_deleted'); } }, execute: function() { scrivito.current_page_link_dialog(); } }); } }); }()); (function() { _.extend(scrivito, { delete_obj_command: function(obj, translations_namespace, redirect_target) { if (!translations_namespace) { translations_namespace = 'commands.delete_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return obj && !scrivito.editing_context.is_deleted_mode(); }, disabled: function() { if (!scrivito.editing_context.selected_workspace.is_editable()) { return scrivito.t('commands.delete_obj.published_workspace'); } if (obj.has_children()) { return scrivito.t('commands.delete_obj.has_children'); } }, execute: function() { scrivito.confirmation_dialog({ title: scrivito.t(translations_namespace + '.dialog.title'), description: scrivito.t(translations_namespace + '.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.withSavingOverlay(obj.destroy().then(function(redirect_to) { var redirect_uri = URI(redirect_target || redirect_to); redirect_uri.path(scrivito.root_path() + redirect_uri.path()); return scrivito.redirect_to(redirect_uri.normalizePath().toString()); })); }); } }); } }); }()); (function() { _.extend(scrivito, { delete_widget_command: function(widget_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_widget', title: scrivito.t('commands.delete_widget.title'), icon: '', present: function() { return scrivito.editing_context.is_editing_mode(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.delete_widget.dialog.title'), description: scrivito.t('commands.delete_widget.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_widget.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return widget_element.widget_field().remove_widget(widget_element); }); } }); } }); }()); (function() { _.extend(scrivito, { delete_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_workspace', title: scrivito.t('commands.delete_workspace.title'), icon: '', disabled: function() { if (!scrivito.user_permissions.can('delete_workspace')) { return scrivito.t('commands.delete_workspace.forbidden'); } }, execute: function() { scrivito.confirmation_dialog({ title: scrivito.t('commands.delete_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.delete_workspace.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_workspace.dialog.confirm'), confirm_button_color: 'red' }).done(function() { scrivito.withSavingOverlay(workspace.destroy().then(function() { return scrivito.change_editing_context({workspace_id: 'published'}); })); }); } }); } }); }()); 'use strict'; (function () { scrivito.duplicateObjCommand = function (obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.duplicate_obj', title: scrivito.t('commands.duplicate_obj.title'), icon: '', present: function present() { return !scrivito.editing_context.is_deleted_mode(); }, disabled: function disabled() { if (!scrivito.editing_context.selected_workspace.is_editable()) { return scrivito.t('commands.duplicate_obj.published_workspace'); } if (obj.has_children()) { return scrivito.t('commands.duplicate_obj.has_children'); } }, execute: function execute() { scrivito.withSavingOverlay(duplicateObj(obj.id())).then(redirectToObj); } }); }; function duplicateObj(objId) { return scrivito.BasicObj.fetch(objId).then(function (obj) { return obj.copyAsync().then(function (copiedObj) { return copiedObj.id; }); }); } function redirectToObj(objId) { return scrivito.application_window.redirect_to(scrivito.path_for_id(objId)); } })(); 'use strict'; (function () { scrivito.duplicate_widget_command = function (widgetElement) { return scrivito.command.create_instance({ id: 'scrivito.sdk.duplicate_widget', title: scrivito.t('commands.duplicate_widget.title'), icon: '', present: function present() { return scrivito.editing_context.is_editing_mode(); }, execute: function execute() { var widgetlistFieldElement = widgetElement.widget_field(); var widget = widgetElement.basic_widget(); return scrivito.withSavingOverlay(widgetlistFieldElement.add_widget(widget.copy(), widgetElement, 'bottom')); } }); }; })(); 'use strict'; (function () { scrivito.markResolvedObjCommand = function (obj) { var translateNamespace = arguments.length <= 1 || arguments[1] === undefined ? 'commands.mark_resolved_obj' : arguments[1]; return scrivito.command.create_instance({ id: 'scrivito.sdk.mark_resolved_obj', title: scrivito.t(translateNamespace + '.title'), icon: '', present: function present() { return obj.has_conflict(); }, execute: function execute() { askForConfirmation(translateNamespace).then(function () { return scrivito.withSavingOverlay(markResolved(obj.id()).then(scrivito.application_window.reload)); }); } }); }; function askForConfirmation(translateNamespace) { return scrivito.confirmation_dialog({ title: scrivito.t('commands.mark_resolved_obj.dialog.title'), description: scrivito.t(translateNamespace + '.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.mark_resolved_obj.dialog.confirm'), confirm_button_color: 'red' }); } function markResolved(objId) { return scrivito.BasicObj.fetch(objId).then(function (basicObj) { return basicObj.markResolvedAsync(); }); } })(); 'use strict'; (function () { scrivito.moveObjFromClipboardCommand = function (childListElement) { return scrivito.command.create_instance({ id: 'scrivito.sdk.move_obj_from_clipboard', title: scrivito.t('commands.move_obj_from_clipboard.title'), icon: '', present: function present() { return scrivito.objClipboard.isPresent(); }, disabled: function disabled() { var objClass = scrivito.objClipboard.serializedAttributes._obj_class; if (!childListElement.is_valid_child_class(objClass)) { return scrivito.t('commands.move_obj_from_clipboard.paste_forbidden', childListElement.allowed_classes().join(', ')); } }, execute: function execute() { scrivito.withSavingOverlay(moveObjTo(childListElement.path()).then(function () { scrivito.objClipboard.clear(); return scrivito.application_window.reload(); }))['catch'](onError); } }); }; function moveObjTo(parentPath) { return scrivito.BasicObj.fetch(scrivito.objClipboard.serializedAttributes._id).then(function (obj) { return obj.moveToAsync(parentPath); }); } function onError(e) { if (e instanceof scrivito.ResourceNotFoundError) { scrivito.alertDialog(scrivito.t('commands.move_obj_from_clipboard.source_not_found')); } } })(); (function() { _.extend(scrivito, { obj_details_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.obj_details', title: function() { if (scrivito.editing_context.is_editing_mode()) { return scrivito.t('commands.obj_details.title_edit'); } else { return scrivito.t('commands.obj_details.title_view'); } }, icon: '', present: function() { return obj.has_details_view(); }, execute: function() { var title_locale; if (scrivito.editing_context.is_editing_mode()) { title_locale = 'commands.obj_details.dialog.title_edit'; } else { title_locale = 'commands.obj_details.dialog.title_view'; } return scrivito.write_monitor.track_changes(function() { return scrivito.details_dialog.open(obj.details_src(), scrivito.t(title_locale, obj.description_for_editor())); }, function() { scrivito.application_window.redirect_to(scrivito.path_for_id(obj.id())); }); } }); } }); }()); 'use strict'; (function () { scrivito.openUserGuideCommand = function () { return scrivito.command.create_instance({ id: 'scrivito.sdk.open_user_guide', title: scrivito.t('commands.open_user_guide.title'), icon: '', execute: function execute() { scrivito.open('https://scrivito.com/user-guide', 'blank'); } }); }; })(); 'use strict'; (function () { scrivito.publishHistoryCommand = function () { return scrivito.command.create_instance({ id: 'scrivito.sdk.publish_history', title: scrivito.t('commands.publish_history.title'), icon: '', execute: function execute() { scrivito.PublishHistoryDialog.open(); } }); }; })(); (function() { _.extend(scrivito, { publish_workspace_command: function(workspace) { var open_confirmation_dialog = function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.publish_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.publish_workspace.dialog.description'), icon: '', color: 'green', confirm_button_text: scrivito.t('commands.publish_workspace.dialog.confirm'), confirm_button_color: 'green' }); }; var open_check_failed_dialog = function() { scrivito.confirmation_dialog({ title: scrivito.t('commands.publish_workspace.error_dialog.title'), description: scrivito.t('commands.publish_workspace.error_dialog.description'), icon: '', confirm_button_text: scrivito.t('commands.publish_workspace.error_dialog.confirm') }).then(function() { scrivito.changes_dialog.open(); }); }; return scrivito.command.create_instance({ id: 'scrivito.sdk.publish_workspace', title: scrivito.t('commands.publish_workspace.title'), icon: '', tooltip: scrivito.t('commands.publish_workspace.title', workspace.title()), disabled: function() { if (!scrivito.user_permissions.can('publish_workspace')) { return scrivito.t('commands.publish_workspace.permission_denied'); } }, execute: function() { if (scrivito.user_permissions.can('publish_workspace')) { open_confirmation_dialog().then(function() { scrivito.withSavingOverlay(workspace.check_and_publish().then(function() { return scrivito.change_editing_context({workspace_id: 'published'}); }).catch(function(error) { if (error.type === 'check_failed') { open_check_failed_dialog(); } else if (error.type === 'outdated_certificates') { scrivito.alertDialog( scrivito.t('commands.publish_workspace.alert.invalid_certificates')); } })); }); } } }); } }); }()); (function() { _.extend(scrivito, { rebase_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.rebase_workspace', title: scrivito.t('commands.rebase_workspace.title'), icon: '', tooltip: scrivito.t('commands.rebase_workspace.tooltip', workspace.title()), present: function() { return !workspace.is_auto_update(); }, disabled: function() { if (!scrivito.user_permissions.can('rebase_workspace')) { return scrivito.t('commands.rebase_workspace.forbidden'); } }, execute: function() { var rebase_promise = workspace.rebase(); scrivito.withSavingOverlay(rebase_promise); rebase_promise.then(function() { return workspace.has_conflicts().then(function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.rebase_workspace.has_conflicts.title'), description: scrivito.t('commands.rebase_workspace.has_conflicts.description'), confirm_button_text: scrivito.t('commands.rebase_workspace.open_changes_dialog'), cancel_button_text: scrivito.t('close') }).then(function() { return scrivito.changes_dialog.open(); }); }).always(function() { scrivito.withSavingOverlay($.Deferred()); scrivito.reload(); }); }); } }); } }); }()); (function() { _.extend(scrivito, { rename_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.rename_workspace', title: scrivito.t('commands.rename_workspace.title'), icon: '', disabled: function() { if (!scrivito.user_permissions.can('rename_workspace')) { return scrivito.t('commands.rename_workspace.forbidden'); } }, execute: function() { scrivito.prompt_dialog({ title: scrivito.t('commands.rename_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.rename_workspace.dialog.description'), value: workspace.original_title(), icon: '', color: 'green', accept_button_text: scrivito.t('commands.rename_workspace.dialog.accept'), accept_button_color: 'green' }).done(function(new_title) { scrivito.withSavingOverlay(workspace.rename(new_title).then(function() { return scrivito.reload(); })); }); } }); } }); }()); (function() { _.extend(scrivito, { restore_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.restore_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.restore_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return obj && obj.is_deleted(); }, execute: function() { scrivito.withSavingOverlay(obj.restore().then(function() { return scrivito.reload(); })); } }); } }); }()); (function() { _.extend(scrivito, { restore_widget_command: function(widget_element) { var widget = widget_element.widget(); return scrivito.command.create_instance({ id: 'scrivito.sdk.restore_widget', title: scrivito.t('commands.restore_widget.title'), icon: '', present: function() { return widget.is_deleted(); }, execute: function() { scrivito.withSavingOverlay(widget.restore()).then(function() { scrivito.application_window.reload(); }); } }); } }); }()); 'use strict'; (function () { scrivito.restoreWorkspaceCommand = function (revision) { return scrivito.command.create_instance({ id: 'scrivito.sdk.restore_workspace', execute: function execute() { askForConfirmation(revision).then(function () { return restoreWorkspace(revision); }); } }); }; function askForConfirmation(revision) { return scrivito.confirmation_dialog({ title: scrivito.t('commands.restore_workspace.dialog.title', workspaceTitle(revision)), description: scrivito.t('commands.restore_workspace.dialog.description', revision.title), icon: '', color: 'green', confirm_button_text: scrivito.t('commands.restore_workspace.dialog.confirm'), confirm_button_color: 'green' }); } function restoreWorkspace(revision) { scrivito.withSavingOverlay(scrivito.workspace.create(workspaceTitle(revision), revision.id).then(function (workspace) { return scrivito.change_editing_context({ workspace_id: workspace.id(), display_mode: 'editing' }); })); } function workspaceTitle(revision) { return scrivito.t('commands.restore_workspace.workspace_title', revision.publishedAtForEditor); } })(); (function() { _.extend(scrivito, { revert_obj_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.revert_obj', title: scrivito.t('commands.revert_obj.title'), icon: '', present: function() { return scrivito.editing_context.selected_workspace.is_editable() && obj && !obj.is_deleted(); }, disabled: function() { if (!obj.modification()) { return scrivito.t('commands.revert_obj.unmodified'); } if (obj.is_new()) { return scrivito.t('commands.revert_obj.is_new'); } }, update: function() { return obj.reload(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.revert_obj.dialog.title'), description: scrivito.t('commands.revert_obj.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.revert_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.withSavingOverlay(obj.revert()) .then(function() { scrivito.application_window.reload(); }); }); } }); } }); }()); (function() { _.extend(scrivito, { revert_resource_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.revert_resource', title: scrivito.t('commands.revert_resource.title'), icon: '', present: function() { return scrivito.editing_context.selected_workspace.is_editable() && !obj.is_deleted(); }, disabled: function() { if (obj.is_new()) { return scrivito.t('commands.revert_resource.is_new'); } }, update: function() { return obj.reload(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.revert_resource.dialog.title'), description: scrivito.t('commands.revert_resource.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.revert_resource.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.withSavingOverlay(obj.revert()).then(function() { scrivito.application_window.reload(); scrivito.cms_window.from($('iframe[name=scrivito_details_dialog]')).reload(); }); }); } }); } }); }()); (function() { _.extend(scrivito, { revert_widget_command: function(widget_element) { var widget = widget_element.widget(); return scrivito.command.create_instance({ id: 'scrivito.sdk.revert_widget', title: scrivito.t('commands.revert_widget.title'), icon: '', present: function() { return scrivito.editing_context.selected_workspace.is_editable() && !widget.is_deleted(); }, disabled: function() { if (widget.is_new()) { return scrivito.t('commands.revert_widget.is_new'); } if (!widget.is_modified()) { return scrivito.t('commands.revert_widget.is_not_modified'); } }, update: function() { return widget.reload(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.revert_widget.dialog.title'), description: scrivito.t('commands.revert_widget.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.revert_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { var dom_element = widget_element.dom_element(); scrivito.with_element_overlay(dom_element, widget.revert().then(function() { dom_element.scrivito('reload'); })); }); } }); } }); }()); 'use strict'; (function () { scrivito.saveObjToClipboardCommand = function (obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.save_obj_to_clipboard', title: scrivito.t('commands.save_obj_to_clipboard.title'), icon: '', present: function present() { return !scrivito.editing_context.is_deleted_mode(); }, disabled: function disabled() { if (obj.has_children()) { return scrivito.t('commands.save_obj_to_clipboard.has_children'); } }, execute: function execute() { scrivito.BasicObj.fetch(obj.id()).then(function (basicObj) { return scrivito.objClipboard.save(basicObj); }); } }); }; })(); 'use strict'; (function () { scrivito.saveWidgetToClipboardCommand = function (widgetElement) { return scrivito.command.create_instance({ id: 'scrivito.sdk.save_widget_to_clipboard', title: scrivito.t('commands.save_widget_to_clipboard.title'), icon: '', present: function present() { return scrivito.editing_context.is_editing_mode(); }, execute: function execute() { scrivito.widgetClipboard.saveWidget(widgetElement.basic_widget()); } }); }; })(); (function() { _.extend(scrivito, { select_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.select_workspace_'+workspace.id(), title: workspace.title(), icon: workspace.icon(), subtitle: subtitle(workspace), tooltip: workspace.title(), disabled: function() { if (!workspace.is_accessible()) { return scrivito.t('commands.select_workspace.disabled'); } }, execute: function() { scrivito.withSavingOverlay( scrivito.change_editing_context({workspace_id: workspace.id()})); } }); } }); var subtitle = function(workspace) { var owners = workspace.owners(); var owner = owners[0]; switch (owners.length) { case 0: return undefined; case 1: return owner.description(); case 2: return scrivito.t('commands.select_workspace.x_and_1_owner', owner.description()); default: return scrivito.t('commands.select_workspace.x_and_n_owners', owner.description(), owners.length - 1); } }; }()); (function() { _.extend(scrivito, { sort_items_command: function(child_list_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.sort_items', title: scrivito.t('commands.sort_items.title'), icon: '', tooltip: scrivito.t('commands.sort_items.tooltip', child_list_element.obj().description_for_editor()), disabled: function() { if (!child_list_element.has_child_order()) { return scrivito.t('commands.sort_items.auto_sort'); } if (child_list_element.children().length < 2) { return scrivito.t('commands.sort_items.too_less_children'); } }, execute: function() { var children = child_list_element.children(); return scrivito.obj_sorting_dialog.open(children).then(function(sorted_children) { var dom_element = child_list_element.dom_element(); _.each(sorted_children, function(sorted_child) { dom_element.append(sorted_child.dom_element()); }); return child_list_element.save_order(); }); } }); } }); }()); (function() { _.extend(scrivito, { switch_mode_command: function(mode) { var icon; switch (mode) { case 'diff': icon = ''; break; case 'added': icon = ''; break; case 'deleted': icon = ''; break; } return scrivito.command.create_instance({ id: 'scrivito.sdk.switch_to_' + mode + '_mode', title: scrivito.t('commands.switch_mode.' + mode), icon: icon, disabled: function() { if (scrivito.editing_context.display_mode === mode) { return scrivito.t('commands.switch_mode.disabled'); } return scrivito.editing_context.reason_for_display_mode_being_disabled(mode); }, execute: function() { if (mode !== 'view' && !scrivito.editing_context.selected_workspace.is_editable()) { scrivito.withSavingOverlay(scrivito.workspace.editable()).then(function(workspaces) { scrivito.editable_workspace_dialog(workspaces, 'view_mode').then(function(workspace_id) { redirect_to(mode, workspace_id); }); }); } else { redirect_to(mode); } } }); } }); var redirect_to = function(dispaly_mode, workspace_id) { var promise = scrivito.change_editing_context( {workspace_id: workspace_id, display_mode: dispaly_mode}); scrivito.withSavingOverlay(promise); }; }()); (function() { var create_command_separator = function(index) { return scrivito.command_separator .create_instance({id: 'scrivito.sdk.widget_commands.separator'+index}); }; _.extend(scrivito, { widget_commands: { init: function() { if (!scrivito.editing_context.is_view_mode()) { scrivito.on('content', function(content) { _.each(scrivito.widget_element.all($(content)), function(widget_element) { widget_element.set_menu([ scrivito.widget_details_command(widget_element), create_command_separator(1), scrivito.duplicate_widget_command(widget_element), scrivito.saveWidgetToClipboardCommand(widget_element), scrivito.copy_widget_from_clipboard_command(widget_element), create_command_separator(2), scrivito.restore_widget_command(widget_element), scrivito.revert_widget_command(widget_element), scrivito.delete_widget_command(widget_element) ].concat(widget_element.menu())); }); }); } } } }); }()); (function() { _.extend(scrivito, { widget_details_command: function(widget_element) { var widget = function() { return widget_element.widget(); }; return scrivito.command.create_instance({ id: 'scrivito.sdk.widget_details', title: scrivito.t('commands.widget_details.title'), icon: '', present: function() { return widget_element.widget_field().template_name() === 'show' && ( scrivito.editing_context.is_editing_mode() || widget().is_modified() || widget().is_placement_modified() ); }, disabled: function() { if (!widget_element.has_details_view()) { return scrivito.t('commands.widget_details.no_details_view'); } }, execute: function() { return scrivito.write_monitor.track_changes(function() { return scrivito.details_dialog.open(widget_element.details_src(), scrivito.t('commands.widget_details.dialog.title', widget().description_for_editor())); }, function() { widget_element.dom_element().scrivito('reload'); }); } }); } }); }()); (function() { _.extend(scrivito, { widgetlist_field_commands: { init: function() { if (scrivito.editing_context.is_editing_mode()) { scrivito.on('content', function(content) { _.each(scrivito.widgetlist_field_element.all($(content)), function(widgetlist_field_element) { widgetlist_field_element.set_menu([ scrivito.create_widget_command(widgetlist_field_element), scrivito.choose_and_create_widget_command(widgetlist_field_element), scrivito.copy_widget_from_clipboard_command(widgetlist_field_element) ].concat(widgetlist_field_element.menu())); }); }); } } } }); }()); (function() { _.extend(scrivito, { workspace_changes_command: function() { return scrivito.command.create_instance({ id: 'scrivito.sdk.workspace_changes', title: scrivito.t('commands.workspace_changes.title'), icon: '', execute: function() { scrivito.changes_dialog.open().then(function(transferred_obj_ids) { var page = scrivito.application_document().page(); if (transferred_obj_ids.length) { if (_.contains(transferred_obj_ids, page.id()) && page.is_new()) { scrivito.redirect_to(page.parent_path() || '/'); } else { scrivito.reload(); } } }); } }); } }); }()); (function() { _.extend(scrivito, { workspace_settings_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.workspace_settings', title: scrivito.t('commands.workspace_settings.title'), icon: '', disabled: function() { if (!scrivito.user_permissions.can('invite_to_workspace')) { return scrivito.t('commands.workspace_settings.forbidden'); } }, execute: function() { var title = scrivito.t('commands.workspace_settings.dialog.title', workspace.title()); scrivito.workspace_settings_dialog.open(title, workspace.memberships()).then( function(memberships) { scrivito.withSavingOverlay( workspace.update_memberships(memberships).then(function() { return scrivito.reload(); }) ); } ); } }); } }); }()); (function() { _.extend(scrivito, { alertDialog: function(message) { return scrivito.alertDialog.open(message); } }); _.extend(scrivito.alertDialog, { open: function(message, options) { var view = $(scrivito.template.render('alert_dialog', _.extend({message: message, color: 'red', icon: ''}, options || {}))); view.appendTo($('#scrivito_editing')); var promise = $.Deferred(); var close = function() { scrivito.dialog.close_with_transition(view); promise.resolve(); return false; }; view.find('.scrivito_close').on('click', close); scrivito.dialog.open_and_center_with_transition(view); return scrivito.withDialogBehaviour(view, promise, {enter: close, escape: close}); }, // For test purpose only. remove_all: function() { $('.scrivito_alert_dialog').remove(); } }); }()); (function() { var dialog, promise, transferred; _.extend(scrivito, { changes_dialog: { open: function() { promise = $.Deferred(); transferred = []; dialog = $(scrivito.template.render('changes_dialog')).appendTo($('#scrivito_editing')); open_batch(scrivito.obj_changes()); scrivito.dialog.open_and_adjust_without_transition(dialog); return scrivito.withDialogBehaviour(dialog, promise, {escape: close}); } } }); var open_batch = function(chainable_search, objs) { render(chainable_search); chainable_search.load_batch().then(function(result, next) { objs = (objs || []).concat(_.map(result.hits, function(hit) { return scrivito.obj.create_instance(hit); })); render(chainable_search, result, objs, next); }); }; var render = function(chainable_search, result, objs, next) { dialog.html(scrivito.template.render('changes_dialog/content', { title: scrivito.t('changes_dialog.title', scrivito.editing_context.selected_workspace.title()), is_loaded: !!result, total: result && result.total, objs: objs, has_more: !!next })); scrivito.updateAutoHeightFor(dialog.find('.scrivito_changes_dialog_content')); dialog.find('[data-scrivito-sort-by="'+chainable_search.query().order+'"]') .addClass('scrivito_'+(chainable_search.query().reverse_order ? 'sort_down' : 'sort_up')); dialog.find('[data-scrivito-sort-by]').on('click', function() { var sortable = $(this); var chainable_search = scrivito.obj_changes(); chainable_search.order(sortable.attr('data-scrivito-sort-by')); if (sortable.hasClass('scrivito_sort_down')) { chainable_search.reverse_order(); } open_batch(chainable_search); return false; }); dialog.find('[data-scrivito-obj-id]').on('click', function() { var obj_id = $(this).attr('data-scrivito-obj-id'); scrivito.write_monitor.track_changes(function() { return scrivito.open_obj(_.find(objs, function(obj) { return obj.id() === obj_id; })); }, function() { open_batch(chainable_search.clone()); }); return false; }); dialog.find('.scrivito_load_more').on('click', function() { open_batch(next, objs); return false; }); dialog.find('.scrivito_transfer_changes').on('click', function() { scrivito.transfer_changes_dialog.open(objs).then(function(transferred_objs) { transferred = transferred.concat(_.invoke(transferred_objs, 'id')); if (transferred_objs.length) { open_batch(chainable_search.clone()); } }); return false; }); dialog.find('.scrivito_cancel').on('click', close); }; var close = function() { scrivito.dialog.close_without_transition(dialog); promise.resolve(transferred); return false; }; }()); (function() { _.extend(scrivito, { child_list_marker: { init: function() { scrivito.inplace_marker.define(function(inplace_marker, root_element) { if (scrivito.editing_context.is_editing_mode()) { _.each(scrivito.child_list_element.all(root_element), function(child_list_element) { var description = scrivito.t('child_list_menu.description', child_list_element.obj().description_for_editor()); inplace_marker.activate_for(child_list_element, {description: description}); }); } }); } } }); }()); 'use strict'; (function () { scrivito.chooseObjClassDialog = function (objClassesDeferred, localePath) { var deferred = new scrivito.Deferred(); var view = $(scrivito.template.render('choose_obj_class_dialog', { title: scrivito.t('choose_obj_class_dialog.' + localePath + '.title'), description: scrivito.t('choose_obj_class_dialog.' + localePath + '.description') })); objClassesDeferred.done(function (objClassSelection) { view.find('#scrivito_replace_with_real_obj_classes').replaceWith(scrivito.template.render('choose_obj_class_dialog/list', { objClassSelection: objClassSelection })); view.on('click', '.scrivito_obj_class_thumbnail', function (e) { scrivito.dialog.close_without_transition(view); deferred.resolve($(e.currentTarget).attr('data-scrivito-private-obj-class')); return false; }); }); $('#scrivito_editing').append(view); var cancel = function cancel() { scrivito.dialog.close_without_transition(view); deferred.reject(); return false; }; view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust_without_transition(view); scrivito.withDialogBehaviour(view, scrivito.promise.wrapInJqueryDeferred(deferred.promise), { escape: cancel }); return deferred.promise; }; })(); (function() { _.extend(scrivito, { confirmation_dialog: function(options) { return scrivito.confirmation_dialog.open(options); } }); _.extend(scrivito.confirmation_dialog, { open: function(options) { var view = $(scrivito.template.render('confirmation_dialog', _.extend({ icon: '', cancel_button_text: scrivito.t('cancel'), confirm_button_text: scrivito.t('confirm') }, options || {}))); $('#scrivito_editing').append(view); var deferred = $.Deferred(); var accept = function() { scrivito.dialog.close_with_transition(view); deferred.resolve(); return false; }; var cancel = function() { scrivito.dialog.close_with_transition(view); deferred.reject(); return false; }; view.find('.scrivito_confirm').on('click', accept); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_center_with_transition(view); return scrivito.withDialogBehaviour(view, deferred, {enter: accept, escape: cancel}); }, // Test purpose only. remove_all: function() { $('.scrivito_confirmation_dialog').remove(); } }); }()); (function() { var menu; _.extend(scrivito, { context_menu: { init: function() { scrivito.gui.on('document', function(cms_document) { var browser_window = $(cms_document.browser_window()); _.each(['resize', 'scroll', 'load'], function(event) { browser_window.on(event, function() { scrivito.context_menu.update_position(); }); }); }); }, toggle: function(dom_element, commands, options) { if (menu) { close(); } else { open(dom_element, commands, options || {}); } }, update_position: function() { if (menu) { menu.update_position(); } }, close: function() { if (menu) { close(); } } } }); var open = function(dom_element, commands, options) { menu = render(commands); setup_commands(commands); setup_update(dom_element, options.anchor); setup_close(dom_element); show(dom_element, options.css_class); }; var close = function() { menu.remove(); menu = null; return false; }; var render = function(commands) { return $(scrivito.template.render('menu', { menu_items: _.map(scrivito.pattern_sort(commands, scrivito.menu_order), function(command) { return scrivito.menu_item.create_instance(command); }) })); }; var setup_commands = function(commands) { _.each(commands, function(command) { if (command.dom_id) { menu.on('click', '.'+command.dom_id(), function() { if (command.is_enabled()) { close(); } command.execute(); return false; }); } }); }; var setup_update = function(dom_element, anchor) { menu.update_position = function() { var offset = scrivito.cms_document.offset(dom_element); if (anchor) { offset.left += anchor.x * dom_element.width(); offset.top += anchor.y * dom_element.height(); } menu.offset(offset); }; if (anchor) { menu.addClass('scrivito_precise_offset'); } }; var setup_close = function(dom_element) { menu.find('.scrivito_menu_box_overlay').on('click', close); }; var show = function(dom_element, css_class) { var box = menu.find('.scrivito_menu_box'); if (css_class) { box.addClass('scrivito_'+css_class); } menu.appendTo($('#scrivito_editing')); menu.update_position(); // Bugfix IE: can't set offset before append. var viewport = $(scrivito.application_window.browser_window()); if (dom_element.offset().left + box.width() > viewport.scrollLeft() + viewport.width()) { box.addClass('scrivito_left'); } if (dom_element.offset().top + box.height() > viewport.scrollTop() + viewport.height() && (dom_element.offset().top - viewport.scrollTop()) > box.height()) { box.addClass('scrivito_top'); } box.fadeIn(500); }; }()); (function() { _.extend(scrivito, { current_page_link_dialog: function() { var workspace_id = scrivito.editing_context.selected_workspace.id(); var current_page_link = scrivito.editing_context.location({ workspace_id: workspace_id, display_mode: "view" }); var view = $(scrivito.template.render('current_page_link_dialog', { current_page_link: current_page_link })); var deferred = $.Deferred(); $('#scrivito_editing').append(view); view.find('input').focus().select(); var done = function() { scrivito.dialog.close_with_transition(view); deferred.resolve(); return false; }; view.find('.scrivito_done').on('click', done); scrivito.dialog.open_and_adjust_with_transition(view); scrivito.withDialogBehaviour(view, deferred, {enter: done, escape: done}); } }); }()); 'use strict'; (function () { scrivito.currentPageMenu = { init: function init() { scrivito.menu_bar.register_item_renderer(function (menuBar) { var currentPage = scrivito.application_document().page(); var $domElement = menuBar.find('#scrivito_current_page_menu'); scrivito.obj_menu.create($domElement, currentPage, function () { return scrivito.application_document().menu(); }); }); } }; })(); (function() { _.extend(scrivito, { current_page_restriction: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { var current_page = scrivito.application_document().page(); if (current_page && current_page.has_restriction()) { $(scrivito.template.render('current_page_restriction', { restriction_messages: current_page.restriction_messages })).appendTo(menu_bar.find('#scrivito_current_page_restriction')); } }); } } }); }()); (function() { _.extend(scrivito, { details_dialog: { open: function(src, title, obj, commands) { var deferred = $.Deferred(); var view = $(scrivito.template.render('details_dialog', {src: src, title: title, obj: obj})); if (obj) { scrivito.obj_menu.create(view.find('.scrivito_obj_menu'), obj, commands); } $('#scrivito_editing').append(view); var indicator = scrivito.saving_indicator.create(view.find('.scrivito_saving_indicator')); var spinner = view.find('.scrivito_modal_body .scrivito_spinning'); var iframe = view.find('iframe'); iframe.on('load', function() { if (iframe.contents().find('body').hasClass('scrivito_dialog') && !iframe.contents().get(0).defaultView.scrivito) { scrivito.alertDialog('Missing required Scrivito assets in the details dialog. ' + 'Are you sure your "scrivito_dialog.html.*" sources the Scrivito assets?'); } spinner.hide(); var size_attr = 'data-scrivito-modal-size'; var modal_size = iframe.contents().find('['+size_attr+']').attr(size_attr); if (_.contains(['small', 'medium', 'large'], modal_size)) { view.removeClass('scrivito_modal_medium'); view.addClass('scrivito_modal_' + modal_size); } scrivito.dialog.adjust(view); }); var cancel = function() { indicator.destroy(); scrivito.dialog.close_without_transition(view); deferred.resolve(); return false; }; view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust_without_transition(view); return scrivito.withDialogBehaviour(view, deferred, {escape: cancel}); } } }); }()); /* eslint-env es6 */ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); (function () { scrivito.detectGesture = function (mouse, root, dragging) { var targets = findGestureTargets(mouse, root, dragging); var boxes = adjustBoxes(findIntersectingBoxes(_.map(targets, boundingRectangle))); var edges = []; _.each(targets, function (target, index) { var box = boxes[index]; if (box) { edges = edges.concat(buildEdgesFor(target, box)); } }); var closestEdge = _.min(edges, function (edge) { return distancePointRectangle(mouse, edge.rectangle); }); var target = closestEdge.target; var edgeName = closestEdge.name; var isWrapping = edgeName === 'left' && isWrapBefore($(target)) || edgeName === 'right' && isWrapAfter($(target)); return { target: target, edgeName: edgeName, isWrapFree: !isWrapping }; }; var boundingRectangle = function boundingRectangle(el) { // given a dom element, return it's bounding rectangle var element = $(el); var offset = element.offset(); var height = undefined; var parent = element.parent(); if (scrivito.enableColDragDrool && element.is('[data-scrivito-widget-obj-class=ColumnWidget]') && !isContainerWrapping(parent)) { // The column should occupy the entire available height unless its container is wrapping. height = parent.outerHeight(); } else { height = element.outerHeight(); } return { x1: offset.left, y1: offset.top, x2: offset.left + element.outerWidth(), y2: offset.top + height }; }; var findGestureTargets = function findGestureTargets(mouse, root, dragging) { var selectableTargets = findSelectableTargets(root); var target = detectClosest(mouse, selectableTargets); if (!target) { return []; } if (target === dragging) { return [target]; } return [target].concat(findGestureTargets(mouse, target, dragging)); }; var findSelectableTargets = function findSelectableTargets(el) { var root = $(el); if (scrivito.enableColDragDrool) { if (root.is('[data-scrivito-widget-obj-class=ColumnWidget]') || root.is('[data-scrivito-widget-obj-class=ColumnContainerWidget]')) { return root.children(); } } var widgetlists = root.find('[data-scrivito-field-type=widgetlist]'); widgetlists = _.reject(widgetlists, function (widgetlist) { // Reject if not a top-level widgetlist. var wrappingWidgetlist = $(widgetlist).parent().closest('[data-scrivito-field-type=widgetlist]').get(0); return wrappingWidgetlist && $.contains(root.get(0), wrappingWidgetlist); }); var selectableTargets = []; _.each(widgetlists, function (widgetlist) { var widgets = $(widgetlist).children(); if (widgets.length) { selectableTargets = selectableTargets.concat(widgets.toArray()); } else { selectableTargets.push(widgetlist); } }); return selectableTargets; }; // which of the given dom elements is closest to the given point? var detectClosest = function detectClosest(point, elems) { if (elems.length) { var _ret = (function () { // Following code is ugly by intention! // It asserts that if there are several equally distant elemts, then the a random will be // detected. This way we asserting that in case of wrong detection, at least in some % of the // test runs an error will be raised. var closest = undefined; var minDist = undefined; _.each(elems, function (elem) { if (closest) { var dist = distancePointRectangle(point, boundingRectangle(elem)); if (dist < minDist) { closest = elem; minDist = dist; } else if (dist === minDist) { var _$random = _slicedToArray([[closest, minDist], [elem, dist]][_.random(1)], 2); closest = _$random[0]; minDist = _$random[1]; } } else { closest = elem; minDist = distancePointRectangle(point, boundingRectangle(elem)); } }); return { v: closest }; })(); if (typeof _ret === 'object') return _ret.v; } }; // distance between point and rectangle // returns 0 if point is inside rectangle var distancePointRectangle = function distancePointRectangle(point, rect) { var clampedX = Math.max(Math.min(point.x, rect.x2), rect.x1); var clampedY = Math.max(Math.min(point.y, rect.y2), rect.y1); var distX = point.x - clampedX; var distY = point.y - clampedY; return Math.sqrt(distX * distX + distY * distY); }; var findIntersectingBoxes = function findIntersectingBoxes(boxes) { var intersectingBoxes = []; var commonIntersectionBox = boxes[0]; // The outermost box has zero height or zero width. if (areaOfBox(commonIntersectionBox) === 0) { return [commonIntersectionBox]; } _.each(boxes, function (box) { commonIntersectionBox = cropRectangle(commonIntersectionBox, box); if (areaOfBox(commonIntersectionBox) > 0) { intersectingBoxes.push(box); } else { return intersectingBoxes; } }); return intersectingBoxes; }; var adjustBoxes = function adjustBoxes(boxes) { var innermostBox = boxes[boxes.length - 1]; // crop innermost box to lie inside all outer boxes _.each(boxes, function (box) { innermostBox = cropRectangle(innermostBox, box); }); return disperseBoxes(centerOfRectangle(innermostBox), boxes); }; // given a list of boxes containing each other and the center, // calculate an adjusted list of boxes so that the edges of successive boxes // do not touch each other, i.e. there is free space between successive boxes. // the boxes are adjusted by making successor boxes smaller to create space. // the first box is never adjusted. // if the overall space is to tight to create the desired amount of space, // as much as possible is created, distributed equally between all boxes. // all adjustments are made with respect to the center, // i.e. box edges are moved towards the center, but never across the center. var disperseBoxes = function disperseBoxes(center, boxes) { var box = boxes[0]; var successorBox = boxes[1]; if (!successorBox) { return boxes; } // the desired amount of space between edges of successive boxes, in pixels. var desiredSpace = 20; // calculate maximum amount of adjustment for each edge // in order to leave enough space for successive boxes. var maxX1 = (center.x - box.x1) / boxes.length; var maxY1 = (center.y - box.y1) / boxes.length; var maxX2 = (box.x2 - center.x) / boxes.length; var maxY2 = (box.y2 - center.y) / boxes.length; // the largest possible box within `box` that leaves enough space var maximumBox = { x1: box.x1 + Math.min(desiredSpace, maxX1), y1: box.y1 + Math.min(desiredSpace, maxY1), x2: box.x2 - Math.min(desiredSpace, maxX2), y2: box.y2 - Math.min(desiredSpace, maxY2) }; // crop successorBox to fit inside the largest possible box var adjustedBox = cropRectangle(successorBox, maximumBox); // recurse on remaining boxes var remainingBoxes = [adjustedBox].concat(boxes.slice(2)); return [box].concat(disperseBoxes(center, remainingBoxes)); }; // calculate the rectangle that results from cropping the rectangle `rect` // to be inside the rectangle `crop`. var cropRectangle = function cropRectangle(rect, crop) { return { x1: Math.min(crop.x2, Math.max(crop.x1, rect.x1)), y1: Math.min(crop.y2, Math.max(crop.y1, rect.y1)), x2: Math.min(crop.x2, Math.max(crop.x1, rect.x2)), y2: Math.min(crop.y2, Math.max(crop.y1, rect.y2)) }; }; // given a rectangle, calculate it's center var centerOfRectangle = function centerOfRectangle(rect) { return { x: (rect.x1 + rect.x2) / 2, y: (rect.y1 + rect.y2) / 2 }; }; var buildEdgesFor = function buildEdgesFor(el, box) { var target = $(el); var boxEdges = edgesOfRectangle(box); if (scrivito.enableColDragDrool) { if (target.is('[data-scrivito-widget-obj-class=ColumnWidget]')) { // inserting directly above or below does not make sense // for a Column (user should insert inside the Column instead) delete boxEdges.top; delete boxEdges.bottom; } if (target.is('[data-scrivito-widget-obj-class=ColumnContainerWidget]')) { // inserting directly left or right does not make sense // for a ColumnContainer // (user should insert a new Column inside the Container instead) delete boxEdges.left; delete boxEdges.right; } if (target.parent().is('[data-scrivito-widget-obj-class=ColumnWidget]') && target.siblings().length === 0) { // inserting directly left or right does not make sense // for the only item inside a Column // (user should insert a new Column instead) delete boxEdges.left; delete boxEdges.right; } } if (target.is('[data-scrivito-field-type=widgetlist]')) { // inserting left, right or at the bottom does not make sense // for an empty widgetlist // (user should insert a first Row before inserting Columns) delete boxEdges.left; delete boxEdges.right; delete boxEdges.bottom; } return _.map(boxEdges, function (rectangle, name) { return { rectangle: rectangle, target: target, name: name }; }); }; // given a rectangle, return it's edges. // the edges are returned as rectangles with either // width=0 for left and right, or // heigth=0 for top and bottom. var edgesOfRectangle = function edgesOfRectangle(rect) { return { left: { x1: rect.x1, y1: rect.y1, x2: rect.x1, y2: rect.y2 }, right: { x1: rect.x2, y1: rect.y1, x2: rect.x2, y2: rect.y2 }, top: { x1: rect.x1, y1: rect.y1, x2: rect.x2, y2: rect.y1 }, bottom: { x1: rect.x1, y1: rect.y2, x2: rect.x2, y2: rect.y2 } }; }; var areaOfBox = function areaOfBox(box) { return (box.x2 - box.x1) * (box.y2 - box.y1); }; var isWrapBetween = function isWrapBetween(column, nextColumn) { var columnOffset = column.offset(); var nextColumnOffset = nextColumn.offset(); var diffX = nextColumnOffset.left - columnOffset.left; var diffY = nextColumnOffset.top - columnOffset.top; return diffY > diffX; }; var isWrapBefore = function isWrapBefore(column) { var prevColumn = column.prev(); if (prevColumn.length) { return isWrapBetween(prevColumn, column); } return false; }; var isWrapAfter = function isWrapAfter(column) { var nextColumn = column.next(); if (nextColumn.length) { return isWrapBetween(column, nextColumn); } return false; }; var isContainerWrapping = function isContainerWrapping(columnContainer) { return !!_.find(columnContainer.children(), function (col) { var column = $(col); var nextColumn = column.next(); if (nextColumn.length) { return isWrapBetween(column, nextColumn); } }); }; })(); (function() { _.extend(scrivito, { dialog: { open_without_transition: function(view) { view.addClass('scrivito_show'); }, open_and_adjust_without_transition: function(view) { scrivito.dialog.open_without_transition(view); scrivito.dialog.adjust(view); }, open_with_transition: function(view) { return scrivito.transition(view, function() { scrivito.dialog.open_without_transition(view); }); }, open_and_adjust_with_transition: function(view) { return scrivito.dialog.open_with_transition(view).then(function() { scrivito.dialog.adjust(view); }); }, open_and_center_with_transition: function(view) { return scrivito.dialog.open_with_transition(view).then(function() { scrivito.center(view); }); }, close_with_transition: function(view) { scrivito.transition(view, function() { view.removeClass('scrivito_show'); }).then(function() { view.remove(); view = null; }); }, close_without_transition: function(view) { view.removeClass('scrivito_show'); view.remove(); view = null; }, adjust: function(view) { scrivito.invalidate_auto_height_for(view); scrivito.updateAutoHeightFor(view); } } }); $(window).on('resize', function() { _.each($('.adjust_dialog'), function(elem) { scrivito.dialog.adjust($(elem)); }); _.each($('.scrivito_center_dialog'), function(elem) { scrivito.center($(elem)); }); }); }()); (function() { _.extend(scrivito, { withDialogBehaviour: function(dom_element, promise, key_map) { return scrivito.with_dialog_overlay(dom_element, scrivito.hotkeys.add(promise, key_map)); } }); }()); (function() { _.extend(scrivito, { with_dialog_overlay: function(dom_element, promise) { var token = scrivito.dialog_overlay.create(dom_element); return promise.always(function() { scrivito.dialog_overlay.destroy(token); }); }, dialog_overlay: { create: function(dom_element) { var predecessor = $('.scrivito_overlay').last(); predecessor.removeClass('scrivito_show'); var overlay = $(scrivito.template.render('overlay')); dom_element.before(overlay); scrivito.transition(overlay, function() { overlay.addClass('scrivito_show'); }); return {overlay: overlay, predecessor: predecessor}; }, destroy: function(token) { var overlay = token.overlay; var predecessor = token.predecessor; scrivito.transition(overlay, function() { overlay.removeClass('scrivito_show'); }).then(function() { overlay.remove(); if (predecessor.length) { predecessor.addClass('scrivito_show'); } }); }, // Test purpose only. remove_all: function() { $('.scrivito_overlay').remove(); } } }); }()); 'use strict'; (function () { var $cursor = undefined; var state = {}; // State variables: gesture, widgetDrag. scrivito.dragDrool = Object.defineProperties({ init: function init() { $cursor = $('
    '); $cursor.hide(); $('body').append($cursor); scrivito.gui.on('document', function (cmsDocument) { if (scrivito.in_editable_view()) { (function () { var $body = cmsDocument.dom_element().find('body'); $body.on('dragover', function (e) { return scrivito.dragDrool.onDragover(e, $body); }); $body.on('drop', function (e) { return scrivito.dragDrool.onDrop(e); }); })(); } }); scrivito.on('content', function (content) { if (scrivito.in_editable_view()) { var cmsDocument = scrivito.cms_document.from($(content)); _.each(scrivito.widget_element.all(cmsDocument.dom_element()), function (widgetElement) { var $markers = widgetElement.dom_element().find('> .scrivito_editing_marker'); $markers.attr('draggable', 'true'); $markers.on('dragstart', function (e) { return scrivito.dragDrool.onDragstart(e); }); $markers.on('dragend', function (e) { return scrivito.dragDrool.onDragend(e); }); }); } }); }, onDragstart: function onDragstart(e) { e.originalEvent.dataTransfer.effectAllowed = 'move'; // Is required in order to dragover event is triggered in FF and Safari. // http://stackoverflow.com/questions/21507189/dragenter-dragover-and-drop-events-not-working-in-firefox // IE 11 however does not allow to set the data, which results in a security exception. try { e.originalEvent.dataTransfer.setData('text/plain', e.originalEvent.target.id); } catch (error) { // Ignore. } var $draggedWidget = $(e.originalEvent.target).parent(); var widgetDrag = new scrivito.WidgetDrag($draggedWidget); this.setState({ widgetDrag: widgetDrag }); }, onDragover: function onDragover(e, $body) { if (!scrivito.dragDrool.buildDrag(e)) { return; } e.originalEvent.dataTransfer.dropEffect = 'move'; if (e.preventDefault) { e.preventDefault(); // Necessary: Allows us to drop. } // Using originalEvent as a workaround. // See https://github.com/jquery/jquery/issues/1925. var mouse = { x: e.originalEvent.pageX, y: e.originalEvent.pageY }; this._updateCursorDebounced(mouse, $body, e); }, _updateCursorDebounced: scrivito.oncePerFrame(function () { var _scrivito$dragDrool; (_scrivito$dragDrool = scrivito.dragDrool)._updateCursor.apply(_scrivito$dragDrool, arguments); }), _updateCursor: function _updateCursor(mouse, $body, e) { var drag = scrivito.dragDrool.buildDrag(e); if (!drag) { return; } drag.onDragover(); var gesture = scrivito.detectGesture(mouse, $body, drag.domElement); var $target = $(gesture.target); // This should NEVER happen! if (!$target.length) { scrivito.logError('Missing target!'); return; } var edgeName = gesture.edgeName; if (edgeName === 'top' || edgeName === 'bottom') { scrivito.dragDrool.showRowCursor(edgeName, $target, drag); } else if (edgeName === 'left' || edgeName === 'right') { scrivito.dragDrool.showColCursor(edgeName, $target, drag, gesture.isWrapFree); } else { // This should NEVER happen! $.error('Unknown gesture: ' + gesture); } scrivito.dragDrool.setState({ gesture: gesture }); }, onDrop: function onDrop(e) { var drag = this.buildDrag(e); if (!drag) { return false; } var gesture = this.state.gesture; if (!gesture || !gesture.target || !drag.canDropInto(gesture.target)) { drag.onCancel(); } else if (gesture.target) { drag.dropInto(gesture.target, gesture.edgeName); } this._cleanup(); return false; }, onDragend: function onDragend(e) { var drag = this.buildDrag(e); if (drag) { drag.onCancel(); } this._cleanup(); }, showRowCursor: function showRowCursor(edgeName, $target, drag) { $cursor.height('0px'); $cursor.width($target.parent().outerWidth()); // TODO: Update cursor position on scroll. var offset = scrivito.cms_document.offset($target); if (edgeName === 'top') { var $prevRow = $target.prev(); if ($prevRow.length) { var prevRowOffset = scrivito.cms_document.offset($prevRow); offset.top = offsetCenter($prevRow, prevRowOffset, offset).top; } } else { var $nextRow = $target.next(); if ($nextRow.length) { var nextRowOffset = scrivito.cms_document.offset($nextRow); offset.top = offsetCenter($target, offset, nextRowOffset).top; } else { offset.top += $target.outerHeight(); } } offset.left = scrivito.cms_document.offset($target.parent()).left; $cursor.offset(offset); showCursor($target, drag); }, showColCursor: function showColCursor(edgeName, $target, drag, isWrapFree) { if (!scrivito.enableColDragDrool) { return; } $cursor.height($target.outerHeight()); $cursor.width('0px'); // TODO: Update cursor position on scroll. var offset = scrivito.cms_document.offset($target); if (edgeName === 'left') { var $prevCol = $target.prev(); if ($prevCol.length && isWrapFree) { var documentOffset = scrivito.cms_document.offset($prevCol); offset.left = offsetCenter($prevCol, documentOffset, offset).left; $cursor.height($target.parent().outerHeight()); } } else { var $nextCol = $target.next(); if ($nextCol.length && isWrapFree) { var documentOffset = scrivito.cms_document.offset($nextCol); offset.left = offsetCenter($target, offset, documentOffset).left; $cursor.height($target.parent().outerHeight()); } else { offset.left += $target.outerWidth(); } } $cursor.offset(offset); showCursor($target, drag); }, // Public for test purpose only. buildDrag: function buildDrag(e) { return this.state.widgetDrag; }, setState: function setState(newState) { state = _.extend(state, newState); }, // For test purpose only. reset: function reset() { if ($cursor) { $cursor.remove(); } state = {}; }, _cleanup: function _cleanup() { $cursor.hide(); this.setState({ widgetDrag: null }); } }, { state: { get: function get() { return state; }, configurable: true, enumerable: true } }); function showCursor($target, drag) { if (drag.canDropInto($target)) { $cursor.removeClass('scrivito_dnd_forbidden'); } else { $cursor.addClass('scrivito_dnd_forbidden'); } if (drag.isStructureWidget()) { $cursor.addClass('scrivito_dnd_structure'); } else { $cursor.removeClass('scrivito_dnd_structure'); } if ($target.hasClass('scrivito_empty_widget_field')) { $cursor.height($target.height()); } $cursor.show(); } function offsetCenter($element, elementOffset, nextElemOffset) { var leftBoundary = elementOffset.left + $element.outerWidth(); var rightBoundary = nextElemOffset.left; var horizOffset = (rightBoundary - leftBoundary) / 2; var left = leftBoundary + horizOffset; var topBoundary = elementOffset.top + $element.outerHeight(); var bottomBoundary = nextElemOffset.top; var vertOffset = (bottomBoundary - topBoundary) / 2; var top = topBoundary + vertOffset; return { left: left, top: top }; } })(); 'use strict'; (function () { var bodyOffset = undefined; scrivito.dragScroll = { SENSIVITY: 30, SPEED: 25, init: function init() { var _this = this; bodyOffset = $('body').offset().top; scrivito.gui.on('document', function (cmsDocument) { var $document = cmsDocument.dom_element(); $document.find('body').on('dragover', function (e) { return _this.dragover(e, $document); }); }); }, dragover: function dragover(e, $document) { var mouseY = e.originalEvent.pageY; var documentScrollTop = $document.scrollTop(); if (mouseY - documentScrollTop < this.SENSIVITY) { $document.scrollTop(documentScrollTop - this.SPEED); return; } var windowHeight = $(window).height(); if (windowHeight - mouseY + documentScrollTop - bodyOffset < this.SENSIVITY) { $document.scrollTop(documentScrollTop + this.SPEED); } } }; })(); (function() { _.extend(scrivito, { editable_workspace_dialog: function(workspaces, locale_path) { var can_select = workspaces.length; var can_create = scrivito.user_permissions.can('create_workspace'); var locale_prefix = 'editable_ws_dialog.' + locale_path; var view = $(scrivito.template.render('editable_workspace_dialog', { workspaces: workspaces, can_select: can_select, can_create: can_create, can_select_or_create: can_select || can_create, title: translate_prefix(locale_prefix + '.title', can_select, can_create), description: translate_prefix(locale_prefix + '.description', can_select, can_create) })); $('#scrivito_editing').append(view); var create_new_ws = false; view.on('focus click', '.scrivito_input_list_of_ws', function(e) { create_new_ws = false; view.find(".scrivito_confirm").html(scrivito.t('editable_ws_dialog.select')); view.find(".scrivito_disabled").removeClass("scrivito_disabled"); view.find(".scrivito_input_new_ws_name label, .scrivito_input_new_ws_name input").addClass("scrivito_disabled"); }); view.on('focus click', '.scrivito_input_new_ws_name', function(e) { create_new_ws = true; view.find(".scrivito_confirm").html(scrivito.t('menu_bar.create')); view.find(".scrivito_disabled").removeClass("scrivito_disabled"); view.find(".scrivito_input_list_of_ws label, .scrivito_input_list_of_ws select").addClass("scrivito_disabled"); }); var deferred = $.Deferred(); var confirm_action = function() { if (create_new_ws) { create_workspace(); } else { select_workspace(); } return false; }; var create_workspace = function() { var title = $('#scrivito_new_ws_name').val(); scrivito.dialog.close_with_transition(view); scrivito.withSavingOverlay(scrivito.workspace.create(title)).then(function(workspace) { deferred.resolve(workspace.id()); }, function() { deferred.reject(); }); }; var select_workspace = function() { var ws_id = $('select#scrivito_list_of_ws').val(); scrivito.dialog.close_with_transition(view); deferred.resolve(ws_id); }; var cancel_action = function() { scrivito.dialog.close_with_transition(view); deferred.reject(); return false; }; view.find('.scrivito_confirm').on('click', confirm_action); view.find('.scrivito_cancel').on('click', cancel_action); scrivito.dialog.open_and_center_with_transition(view); if (can_select) { view.find('.scrivito_input_list_of_ws').click(); view.find('#scrivito_list_of_ws').focus(); } else if (can_create) { view.find('.scrivito_input_new_ws_name').click(); view.find('#scrivito_new_ws_name').focus(); } return scrivito.withDialogBehaviour(view, deferred, { enter: confirm_action, escape: cancel_action }); } }); var translate_prefix = function(prefix, can_select, can_create) { if (can_select && can_create) { return scrivito.t(prefix + '.select_or_create'); } else if (can_select) { return scrivito.t(prefix + '.select'); } else if (can_create) { return scrivito.t(prefix + '.create'); } else { return scrivito.t(prefix + '.forbidden'); } }; }()); (function() { _.extend(scrivito, { with_element_overlay: function(dom_element, promise) { var element_overlay = scrivito.element_overlay.create(dom_element); return promise.always(function() { element_overlay.remove(); }); }, element_overlay: { create: function(dom_element) { var dom_element_position = dom_element.position(); var view = $(scrivito.template.render('element_overlay')).css({ position: 'absolute', // Required for unit tests to pass without an extra CSS file. top: 0, left: dom_element_position.left, width: dom_element.width(), height: dom_element.height() }); dom_element.append(view); return view; } } }); }()); (function() { _.extend(scrivito, { errorDialog: function(message, details) { var promise = $.Deferred(); var view = $(scrivito.template.render('error_dialog', {message: message, details: details})); view.appendTo($('#scrivito_editing')); var close = function() { scrivito.dialog.close_with_transition(view); promise.resolve(); return false; }; view.find('.scrivito_close').on('click', close); view.find('.scrivito_toggle_details').on('click', function() { view.find('.scrivito_modal_body').toggle(); }); scrivito.dialog.open_and_center_with_transition(view); return scrivito.withDialogBehaviour(view, promise, {enter: close, escape: close}); } }); _.extend(scrivito.errorDialog, { // For test purpose only. remove_all: function() { $('.scrivito_error_dialog').remove(); } }); }()); (function() { _.extend(scrivito, { external_links: { init: function() { scrivito.gui.on('document', function(cms_document) { var new_document = cms_document.dom_element(); var base = new_document.find('head > base'); if (!base.length) { base = $(''); new_document.find('head').prepend(base); } base.attr('target', '_top'); }); scrivito.on('content', function(content) { content = $(content); _.each(content.find('a').not( '[data-scrivito-display-mode="editing"] [data-scrivito-field-type="html"] a'), function(link) { var element = $(link); var target = convert_target(link, element.attr('target')); element.attr('target', target); }); _.each(content.find('form').not( '[data-scrivito-display-mode="editing"] [data-scrivito-field-type="html"] form'), function(form) { var element = $(form); var link = document.createElement('a'); link.href = form.action; var target = convert_target(link, element.attr('target')); element.attr('target', target); }); }); } } }); var convert_target = function(link, target) { if (link.protocol === window.location.protocol && link.host === window.location.host) { if (!target) { return '_self'; } } else { if ( target === '' || target === '_self' || target === '_parent' || (/^scrivito/).test(target) ) { return '_top'; } } return target; }; }()); (function() { _.extend(scrivito, { full_screen_panel: function(doc, promise) { var body = $(doc).find('body'); var panel = $('
    '); body.append(panel); promise.always(function() { panel.detach(); }); scrivito.restore_styles_afterwards(promise, body); body.css('overflow', 'hidden'); return panel; } }); }()); (function() { _.extend(scrivito, { iframe_dialog: { open: function(iframe, options) { iframe = $(iframe); options = options || {}; var iframe_container; if (!iframe.parent().is('body')) { iframe_container = iframe.closest('#scrivito_editing > div'); } var view = $(scrivito.template.render('iframe_dialog', { color: options.color, confirm: options.confirm || scrivito.t('confirm'), cancel: options.cancel || scrivito.t('cancel'), disable_confirm: options.confirm === false, disable_cancel: options.cancel === false })); $('#scrivito_editing').append(view); var dialog_body = view.find('.scrivito_modal_body'); var when_closed = $.Deferred(); var confirm = function() { scrivito.dialog.close_without_transition(view); when_closed.resolve(); return false; }; var cancel = function() { scrivito.dialog.close_without_transition(view); when_closed.reject(); return false; }; view.find('.scrivito_confirm').on('click', confirm); view.find('.scrivito_cancel').on('click', cancel); scrivito.withDialogBehaviour(view, when_closed, {enter: confirm, escape: cancel}); scrivito.dialog.open_and_adjust_without_transition(view); scrivito.restore_styles_afterwards(when_closed, iframe); iframe.css('z-index', scrivito.iframe_dialog.z_index(view) + 1); if (iframe_container) { scrivito.restore_styles_afterwards(when_closed, iframe_container); iframe_container.addClass('scrivito_dialog_mode'); } else { iframe.attr('class', ''); // Remove device toggle classes. } var adjust = function() { // Make sure to never manipulate the iFrame after the dialog has been closed. if (when_closed.state() !== 'pending') { return; } iframe.width(dialog_body.width()); iframe.height(dialog_body.height()); iframe.offset(dialog_body.offset()); }; $(window).on('resize', adjust); adjust(); return { when_open: $.Deferred().resolve(dialog_body), when_closed: when_closed.promise() }; }, // For test purpose only. z_index: function(view) { return parseInt(view.css('z-index'), 10); } } }); }()); (function() { _.extend(scrivito, { info_dialog: function(message) { return scrivito.alertDialog.open(message, {color: 'yellow', icon: ''}); } }); }()); (function() { var callbacks = []; _.extend(scrivito, { inplace_marker: { init: function() { scrivito.on('content', function(content) { scrivito.inplace_marker.refresh(scrivito.cms_document.from($(content)).dom_element()); }); }, define: function(callback) { callbacks.push(callback); }, refresh: function(root_element) { if (!scrivito.editing_context.is_view_mode()) { root_element.find('.scrivito_editing_marker').remove(); _.each(callbacks, function(callback) { callback(builder, root_element); }); scrivito.context_menu.update_position(); } }, are_overlapping: function(dom_element1, dom_element2) { var a = dom_element1.getBoundingClientRect(); var b = dom_element2.getBoundingClientRect(); return a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom; }, // For test purpose only. reset_callbacks: function() { callbacks = []; } } }); var warn_overlapping = function(dom_element) { var other_dom_elements = $($(dom_element).closest('body')).find('.scrivito_editing_marker').not(dom_element); var overlapping_dom_elements = _.filter(other_dom_elements, function(other_dom_element) { return scrivito.inplace_marker.are_overlapping(dom_element, other_dom_element); }); if (overlapping_dom_elements.length) { scrivito.warn.apply(null, [scrivito.t('inplace_marker.overlapping'), dom_element].concat(overlapping_dom_elements)); } }; var lights_on = function(highlightable_element) { highlightable_element.addClass('scrivito_active scrivito_entered'); var timer = setTimeout(function() { highlightable_element.removeClass('scrivito_entered'); }, 2000); highlightable_element.data('scrivito-entered-timer', timer); }; var lights_off = function(document) { document.find('.scrivito_active').removeClass('scrivito_active'); document.find('.scrivito_entered').removeClass('scrivito_entered').each(function () { clearTimeout($(this).data('scrivito-entered-timer')); }); }; var enable_highlighting_for = function(marker_container) { if (marker_container.data('scrivito-highlightable')) { return; } marker_container.data('scrivito-highlightable', true); var document = scrivito.cms_document.from(marker_container).dom_element(); marker_container.on('mouseenter', function(event) { var target = $(event.target).closest(':data(scrivito-highlightable)'); if (target.is(marker_container)) { lights_off(document); lights_on(marker_container); } }); marker_container.on('mouseleave', function(event) { lights_off(document); var target = $(event.relatedTarget).closest(':data(scrivito-highlightable)'); if (target.length) { lights_on(target); } }); }; var builder = { activate_for: function(cms_element, options) { var marker = $(scrivito.template.render('inplace_marker', options || {})); marker.on('click', function() { if (scrivito.isDevelopmentMode) { warn_overlapping(marker.get(0)); } scrivito.context_menu.toggle(marker, cms_element.menu()); return false; }); var marker_container = cms_element.dom_element(); marker.prependTo(marker_container); enable_highlighting_for(marker_container); } }; }()); (function() { var menu_bar_items_renderer = []; _.extend(scrivito, { menu_bar: { init: function() { // Add the corresponding CSS class to all documents (including iframe in details dialog). scrivito.gui.on('document', function(document) { document.dom_element().find('body').addClass('scrivito_editing_active'); }); // Re-render the menu bar if the application window changes. scrivito.application_window.on('document', function(document) { scrivito.menu_bar.render(); }); }, register_item_renderer: function(item_renderer) { menu_bar_items_renderer.push(item_renderer); }, render: function() { var view = $(scrivito.template.render('menu_bar')); _.each(menu_bar_items_renderer, function(item_renderer) { item_renderer(view); }); var menu_bar = $('.scrivito_topbar'); if (menu_bar.length) { menu_bar.replaceWith(view); } else { $('body').append(view); } }, // For test purpose only. reset_items_renderer: function() { menu_bar_items_renderer = []; }, // For test purpose only. remove: function() { $('.scrivito_topbar').remove(); } } }); }()); 'use strict'; (function () { scrivito.menuBarBrowseContent = { init: function init() { scrivito.menu_bar.register_item_renderer(function (menuBar) { if (scrivito.browseContent) { (function () { var button = menuBar.find('#scrivito_menu_bar_browse_content'); button.addClass('scrivito_button_bar scrivito_right'); button.append(scrivito.template.render('menu_bar_browse_content')); var doc = scrivito.application_document().dom_element()[0]; button.on('click', function () { scrivito.browseContent(doc); return false; }); })(); } }); } }; })(); 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function () { var render = undefined; var currentPage = undefined; scrivito.menuBarConflictIndicator = { init: function init() { scrivito.menu_bar.register_item_renderer(function (menuBar) { render = function (color, commands) { var target = $(scrivito.template.render('menu_bar_conflict_indicator')); target.appendTo(menuBar.find('#scrivito_menu_bar_conflict_indicator')); target.show(); target.find('.scrivito_icon').addClass('scrivito_' + color); target.on('click', function () { scrivito.context_menu.toggle(target, commands, { css_class: 'conflict_indicator' }); }); }; currentPage = scrivito.application_document().page(); if (currentPage && scrivito.editing_context.selected_workspace.is_editable()) { checkConflict(checkPotentialConflicts); } }); } }; function checkConflict(next) { if (currentPage.has_conflict()) { renderConflict(); } else { next(); } } function checkPotentialConflicts() { currentPage.conflicting_workspaces().done(function (workspaces) { if (workspaces.length) { renderPotentialConflict(workspaces); } }); } function renderConflict() { render('red', [{ id: function id() { return 'scrivito.menu_bar_conflict_indicator.header'; }, render: function render() { return scrivito.template.render('menu_bar_conflict_indicator/conflict'); } }]); } function renderPotentialConflict(workspaces) { render('yellow', [{ id: function id() { return 'scrivito.menu_bar_conflict_indicator.header'; }, render: function render() { return scrivito.template.render('menu_bar_conflict_indicator/warn', { headlineColor: 'yellow', headline: scrivito.t('menu_bar_conflict_indicator.warn_headline'), description: scrivito.t('menu_bar_conflict_indicator.warn_description') }); } }].concat(_toConsumableArray(_.map(workspaces, scrivito.select_workspace_command)))); } })(); (function() { _.extend(scrivito, { menu_bar_device_toggle: { init: function() { var device_toggle; var current_device = function() { return scrivito.storage.get('menu_bar_device_toggle.current_device') || 'desktop'; }; var toggle_device = function(device) { scrivito.storage.set('menu_bar_device_toggle.current_device', device); $('iframe[name=scrivito_application]').attr('class', 'scrivito_iframe_'+device); device_toggle.find('> .scrivito_icon') .attr('class', 'scrivito_icon scrivito_icon_'+device); }; scrivito.menu_bar.register_item_renderer(function(menu_bar) { $('#scrivito_ui').addClass('scrivito_iframe_resize_bg'); device_toggle = $(scrivito.template.render('menu_bar_device_toggle', {device: current_device()} )).appendTo(menu_bar.find('#scrivito_menu_bar_device_toggle')); toggle_device(current_device()); var commands = _.map(['mobile', 'tablet', 'laptop', 'desktop'], function(device) { return scrivito.command.create_instance({ id: 'scrivito.sdk.switch_to_'+device+'_device', title: scrivito.t('menu_bar_device_toggle.command.title.'+device), icon: 'scrivito_icon_'+device, disabled: function() { if (device === current_device()) { return scrivito.t('menu_bar_device_toggle.command.disabled'); } }, execute: function() { var iframe = $('iframe[name=scrivito_application]'); scrivito.transition(iframe, function() { toggle_device(device); iframe.addClass('scrivito_iframe_animate_resize'); }).done(function() { iframe.removeClass('scrivito_iframe_animate_resize'); }); } }); }); commands = [ scrivito.command_separator.create_instance({ id: 'scrivito.sdk.menu_bar_device_toggle.description', title: scrivito.t('menu_bar_device_toggle.description') }) ].concat(commands); device_toggle.on('click', function() { scrivito.context_menu.toggle(device_toggle, commands, {css_class: 'device_toggle'}); return false; }); }); } } }); }()); (function() { _.extend(scrivito, { menu_bar_display_mode_toggle: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { var comparing_mode = scrivito.editing_context.comparing_mode(); var switch_to_view_mode_command = scrivito.switch_mode_command('view'); var switch_to_editing_mode_command = scrivito.switch_mode_command('editing'); var switch_to_comparing_mode_command = scrivito.switch_mode_command(comparing_mode); var template = scrivito.template.render('menu_bar_display_mode_toggle', { mode: scrivito.editing_context.display_mode, comparing_mode: comparing_mode, switch_to_view_mode_command: switch_to_view_mode_command, switch_to_editing_mode_command: switch_to_editing_mode_command, switch_to_comparing_mode_command: switch_to_comparing_mode_command, }); var menu_bar_display_mode_toggle = menu_bar.find('#scrivito_menu_bar_display_mode_toggle').html(template); _.each([ switch_to_view_mode_command, switch_to_editing_mode_command, switch_to_comparing_mode_command ], function(command) { menu_bar_display_mode_toggle.find('.'+command.dom_id()).on('click', function() { command.execute(); return false; }); }); menu_bar_display_mode_toggle.find('.scrivito_comparing_mode_toggle').on('click', function() { scrivito.context_menu.toggle($(this), [ scrivito.switch_mode_command('diff'), scrivito.switch_mode_command('added'), scrivito.switch_mode_command('deleted') ]); return false; }); }); } } }); }()); (function() { _.extend(scrivito, { menu_bar_saving_indicator: { init: function() { scrivito.menu_bar.register_item_renderer(function(parent_view) { scrivito.saving_indicator.create(parent_view.find('#scrivito_menu_bar_saving_indicator')); }); } } }); }()); (function() { _.extend(scrivito, { menu_bar_warning: { init: function() { scrivito.menu_bar.register_item_renderer(function(parent_view) { scrivito.menu_bar_warning.create( parent_view.find('#scrivito_menu_bar_warning')); }); }, create: function(parent_view) { parent_view.append(scrivito.template.render('menu_bar_warning')); $(parent_view).on('click', function() { scrivito.alertDialog(scrivito.t('menu_bar_warning.open_console')); scrivito.menu_bar_warning.hide(); }); }, show: function() { $('.scrivito_menu_bar_warning').show(); }, hide: function() { $('.scrivito_menu_bar_warning').hide(); } } }); }()); (function() { _.extend(scrivito, { menu_item: { create_instance: function(item) { if (item.execute) { return from_command(item); } else if (item.render) { return item; } else { return from_separator(item); } } } }); var from_command = function(command) { var icon = command.icon(); var icon_template = 'menu_item/icon'; if (icon.indexOf('&') === 0) { icon_template += '_hex'; } else if (!(/^scrivito_icon_/).test(icon)) { icon_template += '_sci'; } var render_menu_item = function() { return scrivito.template.render('menu_item', _.extend({}, command, {icon: function() { return scrivito.template.render(icon_template, {icon: icon}); }})); }; return { render: function() { if (command.is_present()) { var view; if (command.needs_update()) { var id = _.uniqueId(command.dom_id()); view = scrivito.template.render('menu_item/spinner', {id: id}); command.update().then(function() { $('#'+id).replaceWith(render_menu_item()); }); } else { view = render_menu_item(); } return view; } } }; }; var from_separator = function(separator) { return { render: function() { return scrivito.template.render('menu_item/separator', separator); } }; }; }()); (function() { _.extend(scrivito, { obj_menu: { create: function(dom_element, obj, commands) { dom_element.append(scrivito.template.render('obj_menu', {obj: obj})); dom_element.on('click', function() { commands = _.isFunction(commands) ? commands() : commands; scrivito.context_menu.toggle(dom_element, commands, {css_class: 'obj_menu'}); return false; }); } } }); }()); (function() { _.extend(scrivito, { obj_sorting_dialog: { open: function(children) { var child_list = _.map(children, function(child) { return child.obj(); }); var view = $(scrivito.template.render('obj_sorting_dialog', { icon: '', child_list: child_list })); $('#scrivito_editing').append(view); $('#scrivito_obj_sorting_sortable').sortable({ placeholder: 'scrivito_obj_sorting_placeholder' }); var deferred = $.Deferred(); var confirm_action = function(e) { var new_id_order = _.map($('#scrivito_obj_sorting_sortable li'), function(child) { return $(child).attr('data-scrivito-private-obj-id'); }); var sorted_children = _.sortBy(children, function(child) { return _.indexOf(new_id_order, child.obj().id()); }); deferred.resolve(sorted_children); scrivito.dialog.close_without_transition(view); return false; }; var cancel_action = function(e) { deferred.reject(); scrivito.dialog.close_without_transition(view); return false; }; view.find('.scrivito_confirm').on('click', confirm_action); view.find('.scrivito_cancel').on('click', cancel_action); scrivito.dialog.open_and_adjust_without_transition(view); return scrivito.withDialogBehaviour(view, deferred, { enter: confirm_action, escape: cancel_action }); } } }); }()); (function() { _.extend(scrivito, { option_marker: { init: function() { scrivito.on('content', function(content) { if (scrivito.editing_context.is_editing_mode()) { _.each(scrivito.widget_element.all($(content)), function(widget_element) { scrivito.option_marker.create(widget_element, 'top'); scrivito.option_marker.create(widget_element, 'bottom'); }); } }); }, create: function(widget_element, position) { var marker = $(scrivito.template.render('option_marker', { position: position, always_visible: scrivito.option_marker.always_visible })); marker.appendTo(widget_element.dom_element()); marker.on('click', function() { var widgetlist_field_element = widget_element.widget_field(); if (widgetlist_field_element.can_choose_widget_class()) { scrivito.choose_and_create_widget_command(widget_element, position).execute(); } else { scrivito.create_widget_command(widget_element, position).execute(); } return false; }); } } }); }()); (function() { _.extend(scrivito, { prompt_dialog: function(options) { return scrivito.prompt_dialog.open(options); } }); _.extend(scrivito.prompt_dialog, { open: function(options) { var view = $(scrivito.template.render('prompt_dialog', _.extend({ icon: '', accept_button_text: scrivito.t('accept'), cancel_button_text: scrivito.t('cancel') }, options || {}))); $('#scrivito_editing').append(view); var deferred = $.Deferred(); var accept = function() { var val = view.find('input').val(); if (options.allow_blank || val) { scrivito.dialog.close_with_transition(view); deferred.resolve(val); } return false; }; var cancel = function() { scrivito.dialog.close_with_transition(view); deferred.reject(); return false; }; view.find('.scrivito_accept').on('click', accept); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_center_with_transition(view).then(function() { view.find('input').focus(); }); return scrivito.withDialogBehaviour(view, deferred, {enter: accept, escape: cancel}); }, // Test purpose only. remove_all: function() { $('.scrivito_prompt_dialog').remove(); } }); }()); (function () { var $mountNode = undefined; var dialogPromise = undefined; scrivito.PublishHistoryDialog = React.createClass({ displayName: 'PublishHistoryDialog', statics: { open: function () { $mountNode = $('#publish_history_dialog'); dialogPromise = $.Deferred(); scrivito.withDialogBehaviour($mountNode, dialogPromise, { escape: close }); ReactDOM.render(React.createElement(scrivito.PublishHistoryDialog, null), $mountNode.get(0)); } }, componentDidMount: function () { this.updateHeight(); }, componentDidUpdate: function () { this.updateHeight(); }, updateHeight: function () { var $modalBody = $(ReactDOM.findDOMNode(this)).find('.scrivito_modal_body'); scrivito.updateAutoHeightFor($modalBody); }, render: function () { return React.createElement( 'div', { className: 'publish_history scrivito_modal_large scrivito_show adjust_dialog' }, React.createElement( 'div', { className: 'scrivito_modal_header' }, React.createElement( 'h3', null, React.createElement('i', { className: 'scrivito_icon scrivito_icon_history' }), scrivito.t('publish_history_dialog.title') ) ), React.createElement( 'div', { className: 'scrivito_modal_body scrivito_dialog scrivito_auto_height' }, React.createElement(InfoBox, null), React.createElement(RevisionList, null) ), React.createElement( 'div', { className: 'scrivito_modal_footer' }, React.createElement( 'a', { className: 'scrivito_button scrivito_cancel', onClick: close }, scrivito.t('publish_history_dialog.close') ) ) ); } }); var InfoBox = React.createClass({ displayName: 'InfoBox', render: function () { return React.createElement( 'div', { className: 'scrivito_notice scrivito_blue' }, React.createElement( 'div', { className: 'scrivito_notice_icon' }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_question' }) ), React.createElement( 'div', { className: 'scrivito_notice_body' }, scrivito.t('publish_history_dialog.info'), React.createElement( 'a', { href: 'https://scrivito.com/publishing-history', target: '_blank' }, scrivito.t('publish_history_dialog.link') ), '.' ) ); } }); var RevisionList = scrivito.createReactClass({ render: function () { return React.createElement( 'div', null, React.createElement( 'ul', { className: 'scrivito_list_big' }, scrivito.Revision.getRecent().map(function (revision) { return React.createElement(RevisionListItem, { revision: revision, key: revision.id }); }) ), React.createElement(NoticeBox, { isLimited: scrivito.Revision.getRecent().isLimited }) ); }, renderWhileLoading: function () { return React.createElement( 'i', { className: 'scrivito_icon scrivito_spinning' }, '' ); }, renderOnError: function () { return React.createElement( 'div', { className: 'scrivito_notice scrivito_red' }, React.createElement( 'div', { className: 'scrivito_notice_icon' }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_not_available' }) ), React.createElement( 'div', { className: 'scrivito_notice_body' }, scrivito.t('publish_history_dialog.error') ) ); } }); var RevisionListItem = React.createClass({ displayName: 'RevisionListItem', isPublished: function () { return this.props.revision.isPublished; }, className: function () { if (this.isPublished()) { return 'is_published'; } }, subtitle: function () { if (this.isPublished()) { return scrivito.t('publish_history_dialog.not_restorable'); } }, publishedAtLabel: function () { return scrivito.t('publish_history_dialog.published_at') + scrivito.i18n.localizeDateRelative(this.props.revision.publishedAt); }, changesCount: function () { var changesCount = this.props.revision.changesCount; if (changesCount === null) { return scrivito.t('publish_history_dialog.changes_count.not_available'); } if (changesCount === 1) { return scrivito.t('publish_history_dialog.changes_count.one'); } return scrivito.t('publish_history_dialog.changes_count.many', changesCount); }, restoreWorkspace: function () { if (!this.isPublished()) { scrivito.restoreWorkspaceCommand(this.props.revision).execute(); } }, render: function () { return React.createElement( 'li', { className: this.className(), onClick: this.restoreWorkspace }, React.createElement( 'span', { className: 'scrivito_list_group' }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_ws' }) ), React.createElement( 'span', { className: 'scrivito_list_group' }, React.createElement( 'span', { className: 'scrivito_list_topic' }, this.props.revision.title ), React.createElement( 'span', { className: 'scrivito_list_meta' }, this.subtitle() ) ), React.createElement( 'span', { className: 'scrivito_list_group scrivito_pull_right' }, React.createElement( 'span', { className: 'scrivito_list_label' }, scrivito.t('publish_history_dialog.changes_count') ), React.createElement( 'span', { className: 'scrivito_list_value' }, this.changesCount() ) ), React.createElement( 'span', { className: 'scrivito_list_group scrivito_pull_right' }, React.createElement( 'span', { className: 'scrivito_list_label' }, this.publishedAtLabel() ), React.createElement( 'span', { className: 'scrivito_list_value' }, this.props.revision.publishedAtForEditor ) ) ); } }); var NoticeBox = React.createClass({ displayName: 'NoticeBox', render: function () { if (this.props.isLimited) { return React.createElement( 'div', { className: 'scrivito_limited_notice' }, React.createElement( 'div', { className: 'scrivito_notice_icon' }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_attention' }) ), React.createElement( 'div', { className: 'scrivito_notice_body' }, scrivito.t('publish_history_dialog.is_limited', scrivito.Revision.getRecent().length) ) ); } return null; } }); function close() { ReactDOM.unmountComponentAtNode($mountNode.get(0)); dialogPromise.resolve(); } })(); (function() { _.extend(scrivito, { reloading: { init: function() { scrivito.gui.on('document', function(cms_document) { var body = cms_document.dom_element().find('body'); $(body).on('reload.scrivito', function() { cms_document.window().reload(); }); }); } } }); }()); (function() { _.extend(scrivito, { resource_dialog: { init: function(config) { if (config.obj) { var obj = scrivito.obj.create_instance(config.obj); scrivito.gui.on('open', function() { scrivito.resource_dialog.open(obj, config.return_to).then(function() { return scrivito.withSavingOverlay(scrivito.redirect_to(config.return_to)); }); }); } }, open: function(obj, return_to) { var title = scrivito.t('resource_dialog.title', obj.description_for_editor()); return scrivito.details_dialog.open(obj.details_src(), title, obj, [ scrivito.revert_resource_command(obj), scrivito.restore_obj_command(obj, 'resource_dialog.commands.restore_obj'), scrivito.markResolvedObjCommand(obj, 'resource_dialog.commands.mark_resolved_obj'), scrivito.delete_obj_command(obj, 'resource_dialog.commands.delete_obj', return_to || scrivito.path_for_id(scrivito.application_document().page().id())) ]); } } }); }()); (function() { _.extend(scrivito, { saving_indicator: { create: function(parent_view) { var target_selector = '.scrivito_saving_indicator'; var saving_in_progress_selector = target_selector + ' .scrivito_saving_in_progress'; var saving_done_selector = target_selector + ' .scrivito_saving_done'; parent_view.append(scrivito.template.render('saving_indicator')); var start_write_token = scrivito.write_monitor.on('start_write', function() { parent_view.find(saving_in_progress_selector).show(); parent_view.find(saving_done_selector).hide(); }); var end_write_token = scrivito.write_monitor.on('end_write', function() { if (!scrivito.write_monitor.is_writing()) { parent_view.find(saving_in_progress_selector).hide(); var saving_done_element = parent_view.find(saving_done_selector); saving_done_element.show(); if (!scrivito.transition.immediate_mode) { setTimeout(function() { saving_done_element.fadeOut(1000); }, 3000); } } }); return { destroy: function() { scrivito.write_monitor.off(start_write_token); scrivito.write_monitor.off(end_write_token); parent_view.find(target_selector).remove(); }, // Test purpose only. start_write_token: start_write_token, end_write_token: end_write_token }; } } }); }()); 'use strict'; (function () { var view = undefined; _.extend(scrivito, { withSavingOverlay: function withSavingOverlay(promise) { scrivito.savingOverlay.show(); if (_.isFunction(promise.always)) { return promise.always(function () { return scrivito.savingOverlay.hide(); }); } promise.then(scrivito.savingOverlay.hide)['catch'](scrivito.savingOverlay.hide); return promise; }, savingOverlay: { show: function show() { if (!view) { view = $(scrivito.template.render('saving_overlay')); $('#scrivito_editing').append(view); } scrivito.transition(view, function () { return view.addClass('scrivito_show'); }); }, hide: function hide() { if (view) { view.remove(); view = null; } }, // Test purpose only. removeAll: function removeAll() { $('.scrivito_saving_overlay').remove(); view = null; }, isPresent: function isPresent() { return !!view; } } }); })(); (function() { var dialog, objs, transferred, promise; _.extend(scrivito, { transfer_changes_dialog: { open: function(original_objs) { promise = $.Deferred(); objs = _.map(original_objs, function(obj) { return _.extend({}, obj); }); transferred = []; dialog = $(scrivito.template.render('transfer_changes_dialog')); dialog.appendTo($('#scrivito_editing')); render(); dialog.find('.scrivito_confirm').on('click', function() { transfer_changes(); return false; }); dialog.find('.scrivito_cancel').on('click', close); scrivito.dialog.open_and_adjust_without_transition(dialog); return scrivito.withDialogBehaviour(dialog, promise, {escape: close}); } } }); var render = function() { var body = dialog.find('.scrivito_modal_body'); body.html(scrivito.template.render('transfer_changes_dialog/body', {objs: objs})); scrivito.updateAutoHeightFor(body); dialog.find('[data-scrivito-obj-id]').on('click', function() { toggle($(this)); return false; }); }; var toggle = function(dom_element) { dom_element.toggleClass('scrivito_active'); var confirm_button = dialog.find('.scrivito_confirm'); if (dialog.find('.scrivito_active').length) { confirm_button.removeClass('scrivito_disabled'); } else { confirm_button.addClass('scrivito_disabled'); } }; var transfer_changes = function() { _.each(objs, function(obj) { obj.is_selected = dialog.find('[data-scrivito-obj-id='+obj.id()+']').is('.scrivito_active'); }); var selected_objs = _.where(objs, {is_selected: true}); if (selected_objs.length) { scrivito.transfer_changes(selected_objs).then(function(errors) { if (errors.length) { var transferred_objs = _.filter(objs, function(obj) { return obj.is_selected && !_.any(errors, function(error) { return error.obj.id() === obj.id(); }); }); transferred = transferred.concat(transferred_objs); objs = _.difference(objs, transferred_objs); render(); } else { transferred = transferred.concat(selected_objs); close(); } }); } }; var close = function() { scrivito.dialog.close_without_transition(dialog); promise.resolve(transferred); return false; }; })(); (function() { _.extend(scrivito, { transfer_errors_dialog: { open: function(errors) { scrivito.alertDialog.open(scrivito.t('transfer_errors_dialog.title'), { body: scrivito.template.render('transfer_errors_dialog', { modified: _.pluck(_.where(errors, {reason: 'modified'}), 'obj'), conflicting: _.pluck(_.where(errors, {reason: 'conflict'}), 'obj') }) }); } } }); })(); 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.WidgetDrag = (function () { function WidgetDrag(object) { _classCallCheck(this, WidgetDrag); if (object instanceof jQuery) { this._domElement = object.get(0); this._$domElement = object; } else { this._domElement = object; this._$domElement = $(object); } this._isHidden = false; } _createClass(WidgetDrag, [{ key: 'isHidden', // For test purpose only. value: function isHidden() { return this._isHidden; } }, { key: 'canDropInto', value: function canDropInto($target) { if (scrivito.enableColDragDrool) { return true; } var targetElement = scrivito.cms_element.from_dom_element($target); if (targetElement.widget_field) { targetElement = targetElement.widget_field(); } var draggedElement = scrivito.cms_element.from_dom_element(this._$domElement); return targetElement.is_valid_child_class(draggedElement.widget().widget_class_name()); } }, { key: 'isStructureWidget', value: function isStructureWidget() { return this._$domElement.is('[data-scrivito-private-structure-widget]'); } }, { key: 'onDragover', value: function onDragover() { if (!this._isHidden) { // jQuery's "css" function does not work correctly in a Chrome + Jasmine environment, // so we need to use the low-level accessors in order to test the behavior. this._domElement.style.opacity = '0.5'; this._isHidden = true; } } }, { key: 'dropInto', value: function dropInto($target, edgeName) { // Dropped the widget back. if ($target.is(this._$domElement)) { return this.onCancel(); } if (edgeName === 'top' || edgeName === 'bottom') { var $sourceList = this._$domElement.parent(); this.insertRow($target, edgeName); var $targetList = this._$domElement.parent(); this.save($sourceList, $targetList); } else { if (scrivito.enableColDragDrool) { this.insertCol($target, edgeName); } else { this.onCancel(); } } } // Public only for test purpose. }, { key: 'insertRow', value: function insertRow($target, edgeName) { var $sourceList = this._$domElement.parent(); this._$domElement.hide(); if ($target.is('[data-scrivito-field-type=widgetlist]')) { $target.append(this._$domElement); } else { $target[edgeName === 'top' ? 'before' : 'after'](this._$domElement); } this._domElement.style.opacity = 1; this._$domElement.slideDown(100); if (scrivito.enableColDragDrool) { this._garbageCollect($sourceList); } } // Public only for test purpose. }, { key: 'insertCol', value: function insertCol($target, edgeName) { var $sourceList = this._$domElement.parent(); var $actualTarget = $target; var insertAtObjClass = $actualTarget.attr('data-scrivito-widget-obj-class'); if (insertAtObjClass !== 'ColumnWidget') { $actualTarget.wrap('
    ' + '
    ' + '
    '); $actualTarget = $target.parent(); } this._$domElement.detach(); this._$domElement.wrap('
    '); var insertionMethod = edgeName === 'left' ? 'before' : 'after'; $actualTarget[insertionMethod](this._$domElement.parent()); this._$domElement.css('opacity', '1'); this._$domElement.show(100); this._garbageCollect($sourceList); this._resizeRow($actualTarget.closest('.row')); } // Public only for test purpose. }, { key: 'save', value: function save($source, $target) { if (scrivito.enableColDragDrool) { return; } var sourceField = scrivito.cms_element.from_dom_element($source); var targetField = scrivito.cms_element.from_dom_element($target); scrivito.widgetlistFieldPlaceholder.update(sourceField); scrivito.widgetlistFieldPlaceholder.update(targetField); this._updateModelFor(sourceField); this._updateModelFor(targetField); var widgetElement = scrivito.cms_element.from_dom_element(this._$domElement); if (!widgetElement.dom_element().is(targetField.inner_tag())) { scrivito.widget_reloading.reload_widget(widgetElement); } } }, { key: 'onCancel', value: function onCancel() { this._domElement.style.opacity = 1; } }, { key: '_resizeRow', value: function _resizeRow($row) { var cols = $row.children().toArray(); var space = 12; while (cols.length > 0) { var size = Math.round(space / cols.length); space -= size; var col = cols.shift(); this._changeColClass($(col), 'col-md-' + size, 100); } } }, { key: '_garbageCollect', value: function _garbageCollect($elem) { if ($elem.attr('data-scrivito-widget-obj-class') === 'ColumnWidget') { if ($elem.children().length === 0) { // remove empty column var $container = $elem.parent(); $elem.remove(); var $leftoverCols = $container.children(); if ($leftoverCols.length > 1) { this._resizeRow($container); } else { // unwrap last column var $lastCol = $leftoverCols.eq(0); var $widgetsToUnwrap = $lastCol.children(); if ($widgetsToUnwrap.length === 0) { // last column is empty. // this should never happen, but better safe than sorry... $container.remove(); } else { // remove column widget $widgetsToUnwrap.unwrap(); // remove column container widget $widgetsToUnwrap.unwrap(); } } } else { var $childWidgets = $elem.children(); if ($childWidgets.length === 1) { var $lonelyChildWidget = $childWidgets.eq(0); if ($lonelyChildWidget.is('[data-scrivito-widget-obj-class=ColumnContainerWidget]')) { var $colsToUnwrap = $lonelyChildWidget.children(); if ($colsToUnwrap.length) { $elem.replaceWith($colsToUnwrap); } } } } } } }, { key: '_changeColClass', value: function _changeColClass($col, newClass) { var animation = arguments.length <= 2 || arguments[2] === undefined ? 100 : arguments[2]; var isOldClassFound = undefined; _.each(_.range(1, 13), function (i) { var oldClass = 'col-md-' + i; if ($col.hasClass(oldClass)) { isOldClassFound = true; if (oldClass !== newClass) { $col.switchClass(oldClass, newClass, animation); } } }); if (!isOldClassFound) { $col.addClass(newClass, animation); } } }, { key: '_updateModelFor', value: function _updateModelFor(fieldElement) { var container = fieldElement.container(); var widgets = _.map(fieldElement.content(), function (id) { return container.widget(id); }); container.update(_defineProperty({}, fieldElement.field_name(), widgets)); } }, { key: 'domElement', get: function get() { return this._domElement; } }]); return WidgetDrag; })(); })(); (function() { _.extend(scrivito, { widget_marker: { init: function() { scrivito.inplace_marker.define(function(inplace_marker, root_element) { if (scrivito.editing_context.selected_workspace.is_editable()) { var widgetlist_field_elements = scrivito.widgetlist_field_element.all(root_element); _.each(widgetlist_field_elements, function(widgetlist_field_element) { _.each(widgetlist_field_element.widget_elements(), function(widget_element) { var show_as_modified = widget_element.widget().is_modified() || widget_element.widget().is_placement_modified(); if (scrivito.editing_context.is_editing_mode() || scrivito.editing_context.is_comparing_mode() && show_as_modified) { if (widget_element.has_widgetlist()) { widget_element.dom_element().attr('data-scrivito-private-structure-widget', true); } inplace_marker.activate_for(widget_element, inplace_marker_options(widget_element)); } }); }); } }); } } }); var inplace_marker_options = function(widget_element) { var options = {}; if (widget_element.has_widgetlist()) { options.icon = 'scrivito_icon_structure_widget'; } if (scrivito.editing_context.is_comparing_mode()) { var tooltip_translation_key; var modification = widget_element.widget().modification(); var placement_modification = widget_element.widget().placement_modification(); switch (modification) { case 'new': tooltip_translation_key = 'widget_is_new'; options.icon = 'scrivito_icon_inv_plus'; break; case 'deleted': tooltip_translation_key = 'widget_is_deleted'; options.icon = 'scrivito_icon_trash'; break; case 'edited': options.icon = 'scrivito_icon_edited'; switch (placement_modification) { case 'new': tooltip_translation_key = 'widget_is_edited_and_dragged_here'; options.css_classes = 'scrivito_widget_moved_icon'; break; case 'deleted': tooltip_translation_key = 'widget_is_edited_and_dragged_away'; options.css_classes = 'scrivito_widget_moved_icon'; break; default: tooltip_translation_key = 'widget_is_edited'; } break; default: options.icon = 'scrivito_icon_moved'; switch (placement_modification) { case 'new': tooltip_translation_key = 'widget_is_dragged_here'; break; case 'deleted': tooltip_translation_key = 'widget_is_dragged_away'; break; } } if (tooltip_translation_key) { options.tooltip = scrivito.t('widget_marker.' + tooltip_translation_key); } } options.description = widget_element.widget().description_for_editor(); return options; }; }()); (function() { _.extend(scrivito, { widget_reloading: { init: function() { scrivito.on('content', function(dom_element) { if (scrivito.in_editable_view()) { var jquery_object = $(dom_element); if (jquery_object.attr('data-scrivito-private-widget-id')) { activate_for(jquery_object); } _.each(jquery_object.find('[data-scrivito-private-widget-id]'), function(dom_element) { activate_for($(dom_element)); }); } }); }, reload_widget: function(widget_element){ scrivito.with_element_overlay(widget_element.dom_element(), widget_element.fetch_markup().then(function(show_markup) { var new_jquery_object = $(show_markup); widget_element.dom_element().replaceWith(new_jquery_object); scrivito.gui.new_content(new_jquery_object); }) ); } } }); var activate_for = function(jquery_object) { var activate = function() { var widget_element = scrivito.cms_element.from_dom_element(jquery_object); scrivito.widget_reloading.reload_widget(widget_element); return false; }; $(jquery_object).on('reload.scrivito', function() { activate(); return false; }); }; }()); (function() { _.extend(scrivito, { widgetlist_field_menu: { init: function() { scrivito.on('content', function(content) { if (scrivito.editing_context.is_editing_mode()) { var widgetlist_field_elements = scrivito.widgetlist_field_element.all($(content)); _.each(widgetlist_field_elements, function(widgetlist_field_element) { activate_menu_for(widgetlist_field_element); }); } }); } } }); var activate_menu_for = function(widgetlist_field_element) { var container = widgetlist_field_element.dom_element(); container.on('click.scrivito', function(e) { if (!widgetlist_field_element.is_empty()) { return; } var container_offset = container.offset(); var relative_offset = { left: e.pageX - container_offset.left, top: e.pageY - container_offset.top }; var anchor = { x: relative_offset.left / container.width(), y: relative_offset.top / container.height() }; scrivito.context_menu.toggle(container, widgetlist_field_element.menu(), {anchor: anchor}); return false; }); }; }()); 'use strict'; (function () { scrivito.widgetlistFieldPlaceholder = { init: function init() { scrivito.on('content', function (content) { _.each(scrivito.widgetlist_field_element.all($(content)), function (fieldElement) { scrivito.widgetlistFieldPlaceholder.update(fieldElement); }); }); }, update: function update(fieldElement) { var $domElement = fieldElement.dom_element(); if (fieldElement.widget_elements().length) { $domElement.removeClass('scrivito_empty_widget_field'); } else { $domElement.addClass('scrivito_empty_widget_field'); } } }; })(); (function() { _.extend(scrivito, { workspace_select: { init: function() { var selected_workspace = scrivito.editing_context.selected_workspace; var commands = { create_workspace: scrivito.create_workspace_command(), select_published: scrivito.select_workspace_command(scrivito.workspace.published()), publish_history: scrivito.publishHistoryCommand(), for_editable: [ scrivito.workspace_changes_command(), scrivito.workspace_settings_command(selected_workspace), scrivito.rename_workspace_command(selected_workspace), scrivito.rebase_workspace_command(selected_workspace), scrivito.publish_workspace_command(selected_workspace), scrivito.delete_workspace_command(selected_workspace) ] }; scrivito.menu_bar.register_item_renderer(function(menu_bar) { var workspace_select = menu_bar.find('#scrivito_workspace_select'); workspace_select.attr('title', selected_workspace.title()); workspace_select.append(scrivito.template.render('workspace_select', { selected_workspace: selected_workspace, commands: commands })); var bind_command = function(command) { workspace_select.on('click', '#'+command.dom_id(), function() { return command.execute(); }); }; bind_command(commands.create_workspace); bind_command(commands.select_published); bind_command(commands.publish_history); _.each(commands.for_editable, function(command) { bind_command(command); }); workspace_select.on('click', function() { var menu_box = workspace_select.find('.scrivito_menu_box'); menu_box.fadeToggle('50'); var workspace_list = menu_box.find('.scrivito_workspace_list'); var spinner = workspace_list.find('.scrivito_spinning'); if (spinner.length && !spinner.attr('data-scrivito-private-loading')) { spinner.attr('data-scrivito-private-loading', true); selected_workspace.other_editable().then(function(workspaces) { var commands = _.map(workspaces, function(workspace) { return scrivito.select_workspace_command(workspace); }); workspace_list.replaceWith(scrivito.template.render( 'workspace_select/other_workspaces', { has_separator: selected_workspace.is_published() && commands.length, commands: commands } )); _.each(commands, function(command) { bind_command(command); }); }).always(function() { spinner.removeAttr('data-scrivito-private-loading'); }); } return false; }); }); } } }); }()); (function() { _.extend(scrivito, { workspace_settings_dialog: { open: function(title, memberships) { var promise = $.Deferred(); var view = $(scrivito.template.render('workspace_settings_dialog', { title: title, owners: _.pluck(_.where(memberships, {role: 'owner'}), 'user_id').join() })); view.appendTo($('#scrivito_editing')); var select_owners = view.find('.scrivito_select_owners'); var confirm = function() { var new_memberships = {}; _.each(select_owners.select2('val'), function(user_id) { new_memberships[user_id] = {role: 'owner'}; }); promise.resolve(new_memberships); scrivito.dialog.close_without_transition(view); return false; }; var cancel = function() { promise.reject(); scrivito.dialog.close_without_transition(view); return false; }; select_owners.select2({ multiple: true, minimumInputLength: 1, query: scrivito.throttle(function(query) { scrivito.user.suggest(query.term).then(function(users) { query.callback({results: _.map(users, function(user) { return {id: user.id, text: user.description}; })}); }); }, 500), initSelection: function(element, callback) { var value = $(element).val(); if (value) { callback(_.map(value.split(','), function(user_id) { return { id: user_id, text: _.findWhere(memberships, {user_id: user_id}).description, locked: user_id === scrivito.user.current.id() }; })); } }, formatNoMatches: scrivito.t('workspace_settings_dialog.nothing_found'), formatSearching: scrivito.t('workspace_settings_dialog.searching'), formatInputTooShort: scrivito.t('workspace_settings_dialog.too_short') }); view.find('.scrivito_confirm').on('click', confirm); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust_without_transition(view); view.on('keyup', function(e) { if ((e.keyCode === 13 || e.keyCode === 27) && $(e.target).attr('class').indexOf('select2') > -1) { return false; } }); return scrivito.withDialogBehaviour(view, promise, {enter: confirm, escape: cancel}); } } }); }()); (function() { $(function() { var iframe = $('iframe[name=scrivito_application]'); scrivito.application_window = scrivito.cms_window.from(iframe); // Fallback behavior in case that application window renders a page with no SDK, e.g. an error // or a static page. iframe.on('load', function() { var application_document = scrivito.application_document(); var browser_window = scrivito.application_window.browser_window(); var has_config = !!application_document.page_config(); var has_sdk = !!browser_window.scrivito; // The application window is completely missing the SDK and the config. if (!has_config && !has_sdk) { // Install jQuery in order to allow correct application document bootstrapping. if (!browser_window.jQuery) { browser_window.jQuery = jQuery; } if (!browser_window.$) { browser_window.$ = $; } // Bootstrap the application document. application_document.installPublicApi(); application_document.connect(); } }); scrivito.init(scrivito.ui_config()); scrivito.gui.start(); }); }());