/*! * 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
" + container.escapeExpression((helpers.translate || (depth0 && depth0.translate) || helpers.helperMissing).call(depth0 != null ? depth0 : {},"menu_bar.show_controls",{"name":"translate","hash":{},"data":data})) + "
\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_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.reasonForBeingDisabled || (depth0 != null ? depth0.reasonForBeingDisabled : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"reasonForBeingDisabled","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) { var stack1; return "scrivito_" + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.obj : depth0)) != null ? stack1.modification : stack1), depth0)); },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return "\n\n\n\n"; },"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); 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); }, changeEditingContext: function(params) { return scrivito.redirect_to(scrivito.editingContext.location(params).href()); }, open_obj: function(obj) { if (obj.is_binary() && ( obj.is_edited() || obj.is_new() && !scrivito.editingContext.isDeletedMode() || obj.is_deleted() && scrivito.editingContext.isDeletedMode())) { 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.editingContext.isDeletedMode()) { params._scrivito_display_mode = 'added'; } if (obj.is_deleted() && !scrivito.editingContext.isDeletedMode()) { params._scrivito_display_mode = 'deleted'; } url += obj.id(); if (!_.isEmpty(params)) { url += '?'+$.param(params); } return scrivito.withSavingOverlay(scrivito.redirect_to(url)); } }, // For test purpose only. location: function() { return window.location; }, // For test 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 test 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) { var creation_promise = scrivito.withDefaults.createObjFromLegacyAttributes(attributes) .then(function(obj) { return { id: obj.id }; }).catch(function(e) { scrivito.handleAjaxError(e); return scrivito.Promise.reject(convert_internal_error(e)); }); return scrivito.promise.wrapInJqueryDeferred(creation_promise); }, delete_obj: function(id) { if (id) { return scrivito.legacy_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.editingContext.displayMode === 'editing' && scrivito.editingContext.visibleWorkspace.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.legacy_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.i18n.locale = config.i18n.locale; scrivito.forgery_protection.init(); scrivito.editingContext.init(config.editing_context); 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.isDevelopmentMode = config.is_development_mode; scrivito.i18nBackend.shouldThrowErrors = config.is_development_mode; scrivito.inplace_marker.init(); scrivito.option_marker.init(); scrivito.menu_bar_saving_indicator.init(); scrivito.menu_bar_warning.init(); scrivito.menu_bar_display_mode_toggle.init(); scrivito.currentPageMenu.init(); scrivito.SelectedWorkspaceButton.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(); if (window.location.hash === '#__scrivito_enable_sidebar_details') { scrivito.enableSidebarDetails = true; } scrivito.DeviceAdjuster.init(); scrivito.Sidebar.init(); scrivito.fileDrop.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 () { _.extend(scrivito, { ajax: function ajax(type, path) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var isWriteRequest = type === 'PUT' || type === 'POST' || type === 'DELETE'; var skipWriteMonitor = options && options.skip_write_monitor; if (isWriteRequest) { options.timeout = 15000; // miliseconds if (!skipWriteMonitor) { scrivito.write_monitor.start_write(); } } var ajaxPromise = singleAjax(type, path, options).then(function (result) { if (result && result.task && _.size(result) === 1) { return handleTask(result.task); } return $.Deferred().resolve(result); }); if (isWriteRequest && !skipWriteMonitor) { ajaxPromise.always(function () { scrivito.write_monitor.end_write(); }); } return ajaxPromise; }, ajaxWithErrorDialog: function ajaxWithErrorDialog(type, path, options) { return scrivito.ajax(type, path, options).fail(function (error) { scrivito.displayAjaxError(error); }); }, displayAjaxError: function displayAjaxError(error) { var message = undefined; var messageForEditor = undefined; if (_.isObject(error)) { message = scrivito.t('ajax_error', error.message); messageForEditor = 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(messageForEditor || scrivito.t('ajax_error.message_for_editor'), [error.timestamp, message]); } } }); function handleTask(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 singleAjax('GET', 'tasks/' + task.id); }).then(handleTask); default: throw { message: 'Invalid task (unknown status)', task: task }; } } function singleAjax(type, path, options) { var baseUrl = window.location.protocol + '//' + window.location.host + '/__scrivito/'; if (options && options.data) { options.data = JSON.stringify(options.data); } var ajaxRequest = $.ajax(baseUrl + path, _.extend({ type: type, dataType: 'json', contentType: 'application/json; charset=utf-8', cache: false }, // Don't cache GET requests. options || {})); return ajaxRequest.then(function (result) { return $.Deferred().resolve(result); }, function (xhr, _textStatus, xhrError) { try { return $.Deferred().reject(JSON.parse(xhr.responseText)); } catch (SyntaxError) { return $.Deferred().reject(xhrError); } }); } })(); '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 () { var CONVERT_TO_CAMELCASE = /_(\w)/g; var CONVERT_TO_UNDERSCORE = /([A-Z])/g; var TEST_CAMEL_CASE = /^_?[^_]+$/; var TEST_UNDERSCORE = /^[a-z0-9_]+$/; scrivito.attributeInflection = { isUnderscore: function isUnderscore(name) { return TEST_UNDERSCORE.test(name); }, isCamelCase: function isCamelCase(name) { return TEST_CAMEL_CASE.test(name); }, underscore: function underscore(name) { return name.replace(CONVERT_TO_UNDERSCORE, function (_match, group) { return "_" + group.toLowerCase(); }); }, camelCase: function camelCase(name) { return name.replace(CONVERT_TO_CAMELCASE, function (match, group, index) { return index ? group.toUpperCase() : match; }); } }; })(); "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.BatchRetrieval = (function () { function BatchRetrieval(mget) { _classCallCheck(this, BatchRetrieval); this._mget = mget; this._deferreds = {}; } _createClass(BatchRetrieval, [{ key: "retrieve", value: function retrieve(id) { var _this = this; if (_.isEmpty(this._deferreds)) { scrivito.nextTick(function () { return _this._performRetrieval(); }); } if (!this._deferreds[id]) { var deferred = new scrivito.Deferred(); this._deferreds[id] = deferred; } return this._deferreds[id].promise; } }, { key: "_performRetrieval", value: function _performRetrieval() { var _this2 = this; var currentRequestDeferreds = this._deferreds; this._deferreds = {}; var ids = _.keys(currentRequestDeferreds); this._mget(ids).then(function (results) { _.each(ids, function (id, index) { var deferred = currentRequestDeferreds[id]; var result = results[index]; if (index < results.length) { deferred.resolve(result); } else { _this2.retrieve(id).then(deferred.resolve, deferred.reject); } }); }, function (error) { _.each(currentRequestDeferreds, function (deferred) { return deferred.reject(error); }); }); } // For test purpose only. }, { key: "reset", value: function reset() { this._deferreds = {}; } }]); return BatchRetrieval; })(); })(); "use strict"; (function () { scrivito.BinaryUtils = { 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'; 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, requestParams) { return fetch('DELETE', path, requestParams); } }; 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 ajaxParams; } function ajax(method, path, requestParams, timeout, token) { var url = 'https://' + backendEndpoint + '/tenants/' + tenant + '/perform'; var ajaxParams = prepareAjaxParams(method, path, requestParams); return scrivito.fetch(method, url, ajaxParams, timeout, token); } 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.computeCacheKey = function (data) { var normalizedData = normalizeData(data); return JSON.stringify(normalizedData); }; 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'; (function () { function configure(_ref) { var tenant = _ref.tenant; var endpoint = _ref.endpoint; if (!tenant) { throw scrivito.ArgumentError('Required configuration "tenant" missing.'); } scrivito.CmsRestApi.init(endpoint || 'api.scrivito.com', tenant); scrivito.Realm.init(window.scrivito); } scrivito.configure = configure; })(); 'use strict'; (function () { var PUBLISHED_WORKSPACE_ID = 'published'; scrivito.currentWorkspaceId = function () { if (scrivito.editingContext) { return scrivito.editingContext.selectedWorkspace.id(); } return PUBLISHED_WORKSPACE_ID; }; })(); "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'; 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); /** * 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); /** * 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); /** * An error thrown in case wrong arguments are passed to an SDK function. */ scrivito.ArgumentError = (function (_scrivito$ScrivitoError2) { _inherits(ArgumentError, _scrivito$ScrivitoError2); /** * 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); scrivito.CommunicationError = (function (_scrivito$ScrivitoError3) { _inherits(CommunicationError, _scrivito$ScrivitoError3); function CommunicationError(message, httpCode) { _classCallCheck(this, CommunicationError); _get(Object.getPrototypeOf(CommunicationError.prototype), 'constructor', this).call(this, message); this.httpCode = httpCode; } return CommunicationError; })(scrivito.ScrivitoError); /** * 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); /** * 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$ScrivitoError4) { _inherits(InternalError, _scrivito$ScrivitoError4); /** * 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); /** * An error thrown in case a backend request from the UI * fails due to network problems. */ scrivito.NetworkError = (function (_scrivito$CommunicationError2) { _inherits(NetworkError, _scrivito$CommunicationError2); /** * 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); /** * 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$ScrivitoError5) { _inherits(NotLoadedError, _scrivito$ScrivitoError5); /** * 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); /** * An error thrown in case a backend request from the UI * exceeds the rate limit of the backend. */ scrivito.RateLimitExceededError = (function (_scrivito$CommunicationError3) { _inherits(RateLimitExceededError, _scrivito$CommunicationError3); /** * 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); /** * An error thrown in case a given Scrivito resource is not found. */ scrivito.ResourceNotFoundError = (function (_scrivito$ScrivitoError6) { _inherits(ResourceNotFoundError, _scrivito$ScrivitoError6); /** * 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); /** * An error thrown in case a backend request from the UI is denied access. */ scrivito.UnauthorizedError = (function (_scrivito$ClientError2) { _inherits(UnauthorizedError, _scrivito$ClientError2); /** * 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); scrivito.TranslationError = (function (_scrivito$InternalError) { _inherits(TranslationError, _scrivito$InternalError); function TranslationError(message) { _classCallCheck(this, TranslationError); _get(Object.getPrototypeOf(TranslationError.prototype), 'constructor', this).call(this, message); } return TranslationError; })(scrivito.InternalError); scrivito.InterpolationError = (function (_scrivito$TranslationError) { _inherits(InterpolationError, _scrivito$TranslationError); function InterpolationError(message) { _classCallCheck(this, InterpolationError); _get(Object.getPrototypeOf(InterpolationError.prototype), 'constructor', this).call(this, message); } return InterpolationError; })(scrivito.TranslationError); })(); 'use strict'; (function () { var isDisabled = false; var connectionCounter = 0; // For test purpose only scrivito.isFetchingActive = function () { return connectionCounter > 0; }; // For test purpose only scrivito.disableFetching = function () { isDisabled = true; }; scrivito.fetch = function (method, url, requestParams, timeout, token) { if (isDisabled) { return scrivito.Promise.reject(); } connectionCounter += 1; return new scrivito.Promise(function (resolve, reject) { var request = createRequestObj(method, url, timeout, token, resolve, reject); request.send(JSON.stringify(requestParams)); }); }; function createRequestObj(method, url, timeout, token, resolve, reject) { var request = new XMLHttpRequest(); request.open(method === 'POST' ? 'POST' : 'PUT', url); request.responseType = 'json'; request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); if (token) { request.setRequestHeader('Authorization', 'Session ' + token); } request.timeout = timeout; request.withCredentials = true; request.onload = function () { return onAjaxLoad(request, resolve, reject); }; request.onerror = function (error) { return onAjaxError(error, reject); }; return request; } function onAjaxLoad(request, resolve, reject) { connectionCounter -= 1; if (request.status >= 200 && request.status < 300) { return resolve(request.response); } return reject(request.response); } function onAjaxError(error, reject) { connectionCounter -= 1; reject(new Error('Network Error: ' + 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 () { // 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 () { var loadIdCounter = 0; var useEventualConsistency = false; var dataToReload = undefined; // An instance of LoadableData might be in one of these states: var MISSING = undefined; var AVAILABLE = 'AVAILABLE'; var ERROR = 'ERROR'; // Additionally, it may either be loading or not loading. // Usually, the value goes through the following transitions: // (missing, not loading) -> (missing, loading) -> (available, not loading) // However when something goes wrong, this transition might occur: // (missing, not loading) -> (missing, loading) -> (error, not loading) // // Other transitions are also valid, // i.e. all possible transtions may eventually occur. var LoadableData = (function () { _createClass(LoadableData, null, [{ key: 'withEventualConsistency', // execute the given function with eventual consistency. // when using eventual consistency, LoadableData is not invalidated immediately. // instead, the outdated data remains available, while an updated version // of the data is loaded in the background. this reduces flicker in the UI. value: function withEventualConsistency(fn) { if (useEventualConsistency) { throw new scrivito.InternalError('withEventualConsistency should not be nested!'); } try { useEventualConsistency = true; dataToReload = []; return fn(); } finally { var collectedData = dataToReload; dataToReload = undefined; useEventualConsistency = false; _.each(collectedData, function (data) { return data.triggerLoading(); }); } } // state is the stateContainer where the LoadableData should store its state. }]); function LoadableData(_ref) { var state = _ref.state; var loader = _ref.loader; var invalidation = _ref.invalidation; _classCallCheck(this, LoadableData); if (!state) { throw new scrivito.InternalError('LoadableData needs state'); } this._value = new scrivito.LoadableValue(state); this._loader = loader; this._invalidation = invalidation; } // export // Access the LoadableData synchronously, assuming it is available. // If the LoadableData is an error, the error is thrown. // If the LoadableData is missing or loading, // a NotLoadedError is thrown, with the provided loader function. _createClass(LoadableData, [{ key: 'get', value: function get() { var _this = this; if (!this._treatAsInvalidated()) { if (this.isAvailable()) { return this._value.value(); } if (this.isError()) { throw this._value.value(); } } throw new scrivito.NotLoadedError(function () { if (_this.isAvailable() || _this.isError()) { return scrivito.Promise.resolve(); } _this.triggerLoading(); return _this._promiseForNextChange(); }); } // set the data to a value. this makes the value available. }, { key: 'set', value: function set(value) { this._value.transitionTo(AVAILABLE, value, this._currentVersion()); } // set the data to an error. }, { key: 'setError', value: function setError(error) { if (error instanceof scrivito.NotLoadedError) { // prevent setting a NotLoadedError, since that would // unravel the space-time continuum and destroy the world. var warning = new scrivito.InternalError('tried to set a Loadable to a NotLoadedError'); this._value.transitionTo(ERROR, warning, this._currentVersion()); throw warning; } this._value.transitionTo(ERROR, error, this._currentVersion()); } // transition back to missing, removes any value or errors. }, { key: 'reset', value: function reset() { this._value.transitionTo(MISSING); } // returns true iff the value is missing }, { key: 'isMissing', value: function isMissing() { if (this._treatAsInvalidated()) { return true; } return this._value.status() === MISSING; } // returns true iff the value not available and not an error, but // has started loading. }, { key: 'isLoading', value: function isLoading() { return this._value.getLoading() !== undefined; } // return true iff value is available. }, { key: 'isAvailable', value: function isAvailable() { if (this._treatAsInvalidated()) { return false; } return this._value.status() === AVAILABLE; } // return true iff an error was set. }, { key: 'isError', value: function isError() { if (this._treatAsInvalidated()) { return false; } return this._value.status() === ERROR; } // trigger loading the data. does nothing if the data is already loading. }, { key: 'triggerLoading', value: function triggerLoading() { var _this2 = this; if (this.isLoading()) { return; } var loadId = loadIdCounter++; var ifUnchanged = function ifUnchanged(fn) { if (_this2._value.getLoading() === loadId) { fn(); } }; var versionWhenLoadingStarted = this._currentVersion(); this._loader().then(function (result) { return ifUnchanged(function () { return _this2._value.transitionTo(AVAILABLE, result, versionWhenLoadingStarted); }); }, function (error) { return ifUnchanged(function () { return _this2._value.transitionTo(ERROR, error, versionWhenLoadingStarted); }); }); this._value.setLoading(loadId); } }, { key: '_promiseForNextChange', value: function _promiseForNextChange() { var deferred = new scrivito.Deferred(); var unsubscribe = this._value.subscribe(function () { deferred.resolve(); unsubscribe(); }); return deferred.promise; } }, { key: '_treatAsInvalidated', value: function _treatAsInvalidated() { if (!this._hasBeenInvalidated()) { return false; } if (useEventualConsistency) { dataToReload.push(this); return false; } return true; } }, { key: '_hasBeenInvalidated', value: function _hasBeenInvalidated() { if (!this._invalidation) { return false; } return this._currentVersion() !== this._value.version(); } }, { key: '_currentVersion', value: function _currentVersion() { var callback = this._invalidation; if (!callback) { return undefined; } var version = callback(); // protect against "crazy" objects like NaN if (typeof version === 'number' && isNaN(version)) { var message = 'invalidation callback returned unsuitable version ' + version; throw new scrivito.InternalError(message); } return version; } }]); return LoadableData; })(); scrivito.LoadableData = LoadableData; })(); '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 EMPTY_STATE = {}; // A wrapper around a value 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 var LoadableValue = (function () { // stateContainer is where the LoadableValue should store its state. function LoadableValue(stateContainer) { _classCallCheck(this, LoadableValue); if (!stateContainer) { throw new scrivito.InternalError('LoadableValue needs stateContainer'); } this._container = stateContainer; } // export // store a loadId to identify the current 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. _createClass(LoadableValue, [{ key: 'setLoading', value: function setLoading(loadId) { this._container.set(_.extend({}, this._getState(), { loadId: loadId })); } // return the current loadId. should only be called if loading. }, { key: 'getLoading', value: function getLoading() { return this._getState().loadId; } }, { key: 'subscribe', value: function subscribe(listener) { return this._container.subscribe(listener); } }, { key: 'status', value: function status() { return this._getState().status; } }, { key: 'value', value: function value() { return this._getState().value; } }, { key: 'version', value: function version() { return this._getState().version; } }, { key: 'transitionTo', value: function transitionTo(status, value, version) { this._container.set({ status: status, value: value, version: version }); } }, { key: '_getState', value: function _getState() { return this._container.get() || EMPTY_STATE; } }]); return LoadableValue; })(); scrivito.LoadableValue = LoadableValue; })(); "use strict"; (function () { scrivito.mapAndLoadParallel = function (list, iteratee) { var results = []; var errors = []; _.each(list, function (item) { try { results.push(iteratee(item)); } catch (error) { if (error instanceof scrivito.NotLoadedError) { errors.push(error); } else { throw error; } } }); if (errors.length) { throw new scrivito.NotLoadedError(function () { return new scrivito.Promise(function (resolve) { var counter = 0; _.map(errors, function (error) { error.load(function () { counter += 1; if (counter === errors.length) { resolve(); } }); }); }); }); } return results; }; })(); '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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { var VALID_KEYS = ['attributes', 'extend', 'name']; var Schema = (function () { function Schema(definition, parent) { _classCallCheck(this, Schema); ensureDefinitionIsValid(definition); if (parent._scrivitoPrivateSchema) { definition.attributes = _.extend({}, parent._scrivitoPrivateSchema.attributes, definition.attributes); } this.definition = definition; } _createClass(Schema, [{ key: 'attributes', get: function get() { return this.definition.attributes; } }, { key: 'name', get: function get() { return this.definition.name; } }]); return Schema; })(); function ensureDefinitionIsValid(definition) { var _ref; if (!isValidAttributesHash(definition.attributes)) { throw new scrivito.ArgumentError('Required key "attributes" missing or it is not a valid ' + 'Scrivito class definition.'); } var invalidKeys = (_ref = _).without.apply(_ref, [_.keys(definition)].concat(VALID_KEYS)); if (invalidKeys.length) { throw new scrivito.ArgumentError('Invalid key(s) ' + scrivito.prettyPrint(invalidKeys) + ' ' + ('given. Valid keys are ' + scrivito.prettyPrint(VALID_KEYS) + '.')); } } function isValidAttributesHash(attributes) { if (attributes && attributes.constructor === Object) { return _.every(attributes, function (typeInfo) { return _.isArray(typeInfo) || _.isString(typeInfo); }); } return false; } function AppClassFactory(definition, parent) { var schema = new Schema(definition, parent); return (function (_parent) { _inherits(_class, _parent); function _class() { _classCallCheck(this, _class); _get(Object.getPrototypeOf(_class.prototype), 'constructor', this).apply(this, arguments); } _createClass(_class, null, [{ key: '_scrivitoPrivateSchema', get: function get() { return schema; } }]); return _class; })(parent); } scrivito.AppClassFactory = AppClassFactory; })(); '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 () { function AttributeContentFactory(registry) { var AttributeContent = (function () { function AttributeContent() { _classCallCheck(this, AttributeContent); } _createClass(AttributeContent, [{ key: 'finishSaving', /** * Resolves when all previous updates have been persisted. * If an update fails the promise is rejected. * * @returns {Promise} */ value: function finishSaving() { return this._scrivitoPrivateContent.finishSaving(); } /** * 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[]| * Obj|Obj[]|Widget|Widget[]| * scrivito.Binary|scrivito.Link|scrivito.Link[])} * the value of the attribute */ }, { key: 'get', value: function get(attributeName) { if (!this.constructor._scrivitoPrivateSchema) { return; } var typeInfo = this.constructor._scrivitoPrivateSchema.attributes[attributeName]; if (!typeInfo) { return; } var internalValue = this._scrivitoPrivateContent.get(attributeName, typeInfo); return scrivito.wrapInAppClass(registry, internalValue); } /** * Updates the attributes of the Obj or Widget. * * @param {Object} attributes - the new attributes * * @example * // Change a string attribute * widget.update({title: 'My new title'}); */ }, { key: 'update', value: function update(attributes) { var appClassName = registry.objClassNameFor(this.constructor); if (!appClassName) { var baseClass = this.constructor === registry.defaultClassForObjs ? 'Obj' : 'Widget'; throw new scrivito.ArgumentError('Updating is not supported on the base class "' + baseClass + '".'); } if (attributes.constructor !== Object) { throw new scrivito.ArgumentError('The provided attributes are invalid. They have ' + 'to be an Object with valid Scrivito attribute values.'); } var schema = this.constructor._scrivitoPrivateSchema; var attributesWithTypeInfo = prepareAttributes(attributes, schema, appClassName); this._scrivitoPrivateContent.update(attributesWithTypeInfo); } }, { key: 'id', /** * The `id` of the Obj or Widget * @type {String} */ get: function get() { return this._scrivitoPrivateContent.id; } /** * The object class name of the Obj or Widget * @type {String} */ }, { key: 'objClass', get: function get() { return this._scrivitoPrivateContent.objClass; } }]); return AttributeContent; })(); return AttributeContent; } function prepareAttributes(attributes, schema, appClassName) { return _.mapObject(attributes, function (value, name) { if (scrivito.Attribute.isSystemAttribute(name)) { return [value]; } var typeInfo = schema.attributes[name]; if (!typeInfo) { throw new scrivito.ArgumentError('Attribute "' + name + '" is not defined for CMS object ' + ('class "' + appClassName + '".')); } var unwrappedValue = scrivito.unwrapAppClassValues(value); return [unwrappedValue, typeInfo]; }); } scrivito.AttributeContentFactory = AttributeContentFactory; scrivito.AttributeContentFactory.prepareAttributes = prepareAttributes; })(); '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.AttributeDeserializer = { deserialize: function deserialize(model, rawValue, type, options) { var _rawValue = _slicedToArray(rawValue, 2); var typeFromBackend = _rawValue[0]; var valueFromBackend = _rawValue[1]; switch (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, options); 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, options); 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) { var isPublic = scrivito.currentWorkspaceId() === 'published'; return new scrivito.Binary(valueFromBackend.id, isPublic); } return null; } function deserializeDateValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'date') { return null; } return scrivito.types.deserializeAsDate(valueFromBackend); } function deserializeHtmlValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'html' || !_.isString(valueFromBackend)) { return ''; } return valueFromBackend; } function deserializeEnumValue(typeFromBackend, valueFromBackend, _ref) { var validValues = _ref.validValues; if (typeFromBackend === 'string' && _.contains(validValues, valueFromBackend)) { return valueFromBackend; } return null; } function deserializeMultienumValue(typeFromBackend, valueFromBackend, _ref2) { var validValues = _ref2.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 null; case 'number': return convertToFloat(valueFromBackend); default: return null; } } function convertToFloat(valueFromBackend) { var floatValue = parseFloat(valueFromBackend); if (scrivito.types.isValidFloat(floatValue)) { return floatValue; } return null; } function deserializeIntegerValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': case 'number': return scrivito.types.deserializeAsInteger(valueFromBackend); default: return null; } } 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.BasicLink.build(linkParams); } 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 = scrivito.mapAndLoadParallel(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; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { scrivito.BasicAttributeContent = (function () { function BasicAttributeContent() { _classCallCheck(this, BasicAttributeContent); } _createClass(BasicAttributeContent, [{ key: 'get', value: function get(attributeName, typeInfo) { if (!scrivito.attributeInflection.isCamelCase(attributeName)) { throw new scrivito.ArgumentError('Attribute names have to be in camel case.'); } var internalAttributeName = scrivito.attributeInflection.underscore(attributeName); if (scrivito.Attribute.isSystemAttribute(internalAttributeName)) { if (_.has(this._systemAttributes, internalAttributeName)) { return this[this._systemAttributes[internalAttributeName]]; } return undefined; } var _scrivito$typeInfo$normalize = scrivito.typeInfo.normalize(typeInfo); var _scrivito$typeInfo$normalize2 = _slicedToArray(_scrivito$typeInfo$normalize, 2); var type = _scrivito$typeInfo$normalize2[0]; var options = _scrivito$typeInfo$normalize2[1]; var rawValue = this._current[internalAttributeName]; if (!rawValue || !_.isArray(rawValue)) { rawValue = []; } return scrivito.AttributeDeserializer.deserialize(this, rawValue, type, options); } }, { 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 publicAttrName = scrivito.attributeInflection.camelCase(name); var serializedAttributes = _.invoke(_this.get(publicAttrName, ['widgetlist']), 'serializeAttributes'); serializedAttrs[name] = ['widgetlist', serializedAttributes]; return; } serializedAttrs[name] = value; }); return serializedAttrs; } }, { key: '_persistWidgets', value: function _persistWidgets(obj, attributes) { _.each(attributes, function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var widgets = _ref2[0]; var typeInfo = _ref2[1]; if (typeInfo && typeInfo[0] === 'widgetlist') { _.each(widgets, 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 BasicAttributeContent; })(); })(); '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']; scrivito.BasicLink = (function () { _createClass(BasicLink, null, [{ key: 'build', value: function build(attributes) { var objId = attributes.objId; delete attributes.objId; var link = new this(attributes); if (objId) { link._objId = objId; } return link; } }]); function BasicLink(attributes) { _classCallCheck(this, BasicLink); 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(BasicLink, [{ key: 'fetchObj', 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 {Link} */ }, { key: 'copy', value: function copy(attributes) { ensureValidPublicAttributes(attributes); var newAttributes = this.buildAttributes(); if (_.has(attributes, 'obj')) { delete newAttributes.objId; } _.extend(newAttributes, attributes); return this.constructor.build(newAttributes); } }, { key: 'buildAttributes', value: function buildAttributes() { return _.pick(this, 'title', 'query', 'fragment', 'target', 'url', 'objId'); } }, { 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 Obj|CMS object} this link references. * Returns `null` if the link is external. * @type {?String} */ }, { key: 'objId', get: function get() { return this._objId; } }, { key: 'obj', get: function get() { if (this.objId) { return scrivito.BasicObj.get(this.objId); } return null; } }]); return BasicLink; })(); 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))); } } })(); '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' }; scrivito.BasicObj = (function (_scrivito$BasicAttributeContent) { _inherits(BasicObj, _scrivito$BasicAttributeContent); _createClass(BasicObj, null, [{ key: 'fetch', value: function fetch(_id) { scrivito.asyncMethodStub(); } }, { key: 'get', value: function get(idOrList) { var _this = this; if (_.isArray(idOrList)) { return scrivito.mapAndLoadParallel(idOrList, function (id) { return _this.get(id); }); } var obj = this.getIncludingDeleted(idOrList); if (obj.isDeleted()) { throwObjNotFound(idOrList); } return obj; } }, { key: 'getIncludingDeleted', value: function getIncludingDeleted(idOrList) { var _this2 = this; if (_.isArray(idOrList)) { return scrivito.mapAndLoadParallel(idOrList, function (id) { return _this2.getIncludingDeleted(id); }); } var objData = scrivito.ObjDataStore.get(idOrList); var obj = new scrivito.BasicObj(objData); if (obj.isFinallyDeleted()) { throwObjNotFound(idOrList); } return obj; } }, { key: 'create', value: function create(attributes) { var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); ensureObjClassExists(normalizedAttributes._objClass); if (!normalizedAttributes._id) { normalizedAttributes._id = [this.generateId()]; } var serializedAttributes = { _id: normalizedAttributes._id, _obj_class: normalizedAttributes._objClass }; return this.createWithSerializedAttributes(scrivito.typeInfo.unwrapAttributes(serializedAttributes), _.omit(attributes, '_objClass', '_id')); } }, { 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(); } }, { key: 'all', value: function all() { return new scrivito.BasicObjSearchIterable().batchSize(1000); } }, { key: 'where', value: function where(field, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; return new scrivito.BasicObjSearchIterable().and(field, operator, value, boost); } }, { key: 'getByPath', value: function getByPath(path) { return scrivito.iterable.firstValueFromIterator(this.where('_path', 'equals', path).iterator()); } }, { key: 'getByPermalink', value: function getByPermalink(permalink) { var iterator = this.where('_permalink', 'equals', permalink).iterator(); return scrivito.iterable.firstValueFromIterator(iterator); } }]); function BasicObj(objData) { _classCallCheck(this, BasicObj); _get(Object.getPrototypeOf(BasicObj.prototype), 'constructor', this).call(this); this.objData = objData; } _createClass(BasicObj, [{ key: 'getParent', value: function getParent() { if (this._hasParent()) { return scrivito.BasicObj.getByPath(computeParentPath(this.path)); } return null; } }, { key: 'hasConflicts', value: function hasConflicts() { return !!this._current._conflicts; } }, { key: 'isNew', value: function isNew() { return this.modification === 'new'; } }, { key: 'isEdited', value: function isEdited() { return this.modification === 'edited'; } }, { key: 'isDeleted', value: function isDeleted() { return this.modification === 'deleted'; } }, { key: 'isFinallyDeleted', value: function isFinallyDeleted() { return !!this._current._deleted; } }, { key: 'isBinary', value: function isBinary() { var blobAttribute = this._objClass.attribute('blob'); if (blobAttribute) { return blobAttribute.type === 'binary'; } return false; } }, { key: 'fetchParent', value: function fetchParent() { scrivito.asyncMethodStub(); } }, { key: 'update', value: function update(attributes) { var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); this._persistWidgets(this, normalizedAttributes); var patch = scrivito.AttributeSerializer.serialize(normalizedAttributes); this.objData.update(patch); this._linkResolution.start(); } }, { key: 'destroy', value: function destroy() { this.update({ _modification: ['deleted'] }); } }, { 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(); } }, { key: 'finishSaving', value: function finishSaving() { var _this3 = this; var finish = this._linkResolution.finishResolving().then(function () { return _this3.objData.finishSaving(); }); return new scrivito.PublicPromise(finish); } }, { key: 'widget', value: function widget(id) { if (this.widgetData(id)) { return scrivito.BasicWidget.build(id, this); } return null; } }, { key: 'widgets', value: function widgets() { var _this4 = this; return _.map(_.keys(this._widgetPool), function (id) { return _this4.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; if (this.path) { serializedAttributes._path = computeParentPath(this.path) + '/' + objId; } return scrivito.PublicPromise.all(uploadPromises).then(function (binaries) { _.each(binaries, function (_ref) { var name = _ref.name; var binary = _ref.binary; serializedAttributes[name] = ['binary', { id: binary.id }]; }); return serializedAttributes; }); } }, { key: 'id', get: function get() { return this._current._id; } }, { key: 'objClass', get: function get() { return this._current._obj_class; } }, { key: 'lastChanged', get: function get() { if (this._current._last_changed) { return scrivito.parseDate(this._current._last_changed); } return null; } }, { key: 'version', get: function get() { return this._current._version; } }, { key: 'path', get: function get() { return this._current._path || null; } }, { key: 'permalink', get: function get() { return this._current._permalink || null; } }, { key: 'parent', get: function get() { return this.getParent(); } }, { key: 'modification', get: function get() { if (this._current._deleted) { return 'deleted'; } return this._current._modification || null; } }, { key: 'descriptionForEditor', get: function get() { return this._uiConfig.get('description_for_editor'); } }, { 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 []; } }, { key: 'backlinks', get: function get() { var iterator = scrivito.BasicObj.where('*', 'links_to', this).iterator(); return scrivito.iterable.collectValuesFromIterator(iterator); } }, { key: 'ancestors', get: function get() { if (this._hasParent()) { var parentPath = computeParentPath(this.path); return collectPathComponents(parentPath).map(function (ancestorPath) { return scrivito.BasicObj.getByPath(ancestorPath); }); } return []; } }, { key: '_widgetPool', get: function get() { return this._current._widget_pool || {}; } }, { key: '_uiConfig', get: function get() { return scrivito.UiConfig.get(this.id); } }, { 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.BasicAttributeContent); scrivito.provideAsyncClassMethods(scrivito.BasicObj, { get: 'fetch' }); scrivito.provideAsyncInstanceMethods(scrivito.BasicObj, { getParent: 'fetchParent' }); function ensureObjClassExists(attrInfoAndValue) { if (!attrInfoAndValue) { throw new scrivito.ArgumentError('Please provide an obj class as the "_objClass" property.'); } } function extractAttributeDict(attributes) { var serializedAttributes = {}; var attributeDict = {}; _.each(attributes, function (serializedValue, name) { if (_.isArray(serializedValue) && _.first(serializedValue) === 'widgetlist') { var widgets = _.map(_.last(serializedValue), function (serializedWidgetAttributes) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidgetAttributes); }); var attrName = scrivito.attributeInflection.camelCase(name); attributeDict[attrName] = [widgets, ['widgetlist']]; } 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.'); } } function throwObjNotFound(id) { throw new scrivito.ResourceNotFoundError('Obj with id "' + id + '" not found.'); } })(); '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 _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 () { var NEGATEABLE_OPERATORS = ['equals', 'starts_with', 'is_greater_than', 'is_less_than']; var BOOSTABLE_PARAMETERS = ['contains', 'contains_prefix']; var DEFAULT_BATCH_SIZE = 10; scrivito.BasicObjSearchIterable = (function () { function BasicObjSearchIterable() { _classCallCheck(this, BasicObjSearchIterable); this._query = []; this._batchSize = DEFAULT_BATCH_SIZE; } _createClass(BasicObjSearchIterable, [{ key: 'and', value: function and(fieldOrSearch, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; if (fieldOrSearch instanceof scrivito.BasicObjSearchIterable) { this._query = [].concat(_toConsumableArray(this._query), _toConsumableArray(fieldOrSearch._query)); } else { var subQuery = buildSubQuery(fieldOrSearch, operator, value); if (boost) { ensureBoostableOperator(operator); subQuery.boost = boost; } this._query.push(subQuery); } return this; } }, { 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 {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 * Obj.all.order('_last_changed', 'desc') * * @return {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 {ObjSearchIterable} itself */ }, { key: 'batchSize', value: function batchSize(_batchSize) { this._batchSize = _batchSize; return this; } }, { key: 'includeDeleted', value: function includeDeleted() { this._includeDeleted = true; return this; } }, { 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 purpose only. }, { key: 'getBatchSize', // For test purpose only. value: function getBatchSize() { return this._batchSize; } }, { key: 'params', get: function get() { return this._params; } }, { key: '_params', get: function get() { var params = _.omit({ query: this._query, offset: this._offset, sort_by: this._sortBy, sort_order: this._sortDirection }, _.isUndefined); if (this._includeDeleted) { params.options = { include_deleted: true }; } return params; } }]); return BasicObjSearchIterable; })(); 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); } if (value instanceof scrivito.BasicObj) { return value.id; } 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'; case 'links_to': return 'links_to'; case 'refers_to': return 'refers_to'; 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; }; })(); 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' }; scrivito.BasicWidget = (function (_scrivito$BasicAttributeContent) { _inherits(_class, _scrivito$BasicAttributeContent); _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: 'newWithSerializedAttributes', value: function newWithSerializedAttributes(attributes) { var unserializedAttributes = {}; var serializedAttributes = {}; _.each(attributes, function (value, name) { if (name === '_obj_class') { unserializedAttributes._objClass = [value]; return; } if (_.isArray(value) && _.first(value) === 'widgetlist') { var newWidgets = _.map(_.last(value), function (serializedWidget) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidget); }); var attrName = scrivito.attributeInflection.camelCase(name); unserializedAttributes[attrName] = [newWidgets, ['widgetlist']]; return; } serializedAttributes[name] = value; }); var widget = new scrivito.BasicWidget(unserializedAttributes); widget.preserializedAttributes = serializedAttributes; return widget; } }]); function _class(attributes) { _classCallCheck(this, _class); _get(Object.getPrototypeOf(_class.prototype), 'constructor', this).call(this); this._attributesToBeSaved = scrivito.typeInfo.normalizeAttrs(attributes); ensureWidgetClassExists(attributes._objClass); } _createClass(_class, [{ key: 'widget', value: function widget(id) { return this.obj.widget(id); } }, { key: 'update', value: function update(attributes) { var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); this._persistWidgets(this.obj, normalizedAttributes); var patch = scrivito.AttributeSerializer.serialize(normalizedAttributes); this._updateSelf(patch); } }, { key: 'copy', value: function copy() { var serializedAttributes = this.serializeAttributes(); return scrivito.BasicWidget.newWithSerializedAttributes(serializedAttributes); } }, { key: 'persistInObj', value: function persistInObj(obj) { this._persistWidgets(obj, this._attributesToBeSaved); var patch = scrivito.AttributeSerializer.serialize(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', 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 = { _widgetPool: [_defineProperty({}, this.id, patch)] }; this.obj.update(widgetPoolPatch); } }, { key: 'id', get: function get() { if (this.isPersisted()) { return this._id; } this._throwUnpersistedError(); } }, { key: 'objClass', get: function get() { return this._current._obj_class; } }, { 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; } }]); return _class; })(scrivito.BasicAttributeContent); function ensureWidgetClassExists(attrInfoAndValue) { if (!attrInfoAndValue) { throw new scrivito.ArgumentError('Please provide a widget class as the "_objClass" property.'); } } })(); '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, isPublic, definition, original) { var _this = this; _classCallCheck(this, Binary); this.id = id; this._isPublic = !!isPublic; this._transformationDefinition = definition; this._original = original; this._loadableData = new scrivito.LoadableData({ state: modelState(id, definition), loader: function loader() { return _this._loadUrlData(); } }); } /** * 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); } /** * Some Scrivito data is considered private, i.e. it is not currently intended * for the general public, for example content in a workspace that has not * been published yet. * * @returns {Boolean} */ }, { key: 'isPrivate', value: function isPrivate() { return !this._isPublic; } /** * Use this method to transform images, i.e. to scale down large images or * to generate thumbnails of images. Only applicable if this {scrivito.Binary} is an image. * * This method does not change the binary. Instead, it returns a copy of it, * transformed using the `definition`. * * If the original binary has already been transformed, the returned binary will be a * combination of the transformations. Thus, the transformations can be chained (see examples). * * The transformed data is calculated "lazily", so calling {@link scrivito.Binary#transform} * does not trigger any calculation. The calculation is triggered only when data is accessed, * for example via {@link scrivito.Binary#url}. * * @param {Object} definition transformation definition * @param {(number|string)} definition.width The width in pixels of the output image. * Must be a positive integer. * * If only this dimension has been specified, the other dimension is calculated automatically * to preserve the aspect ratio of the input image. * * If the `fit` parameter is set to `resize`, then either the actual output width or the * output height may be less than the amount you specified to prevent distortion. * * If neither `width` nor `height` is given, the width and height of the input image is used. * * The maximum size of the output image is defined as `width` + `height` = `4096` pixels. * The given `width` and `height` may be adjusted to accommodate this limit. * The output image will never be larger than the source image, i.e. the given `width` and * `height` may be adjusted to prevent the dimensions of the output image from exceeding * those of the input image. * * If the given `width` and `height` are adjusted, the aspect ratio is preserved. * @param {(number|string)} definition.height The height in pixels of the output image. * Must be a positive integer. * * If only this dimension has been specified, the other dimension is calculated automatically * to preserve the aspect ratio of the input image. * * If the `fit` parameter is set to `resize`, then either the actual output width or the * output height may be less than the amount you specified to prevent distortion. * * If neither `width` nor `height` is given, the width and height of the input image is used. * * The maximum size of the output image is defined as `width` + `height` = `4096` pixels. * The given `width` and `height` may be adjusted to accommodate this limit. * The output image will never be larger than the source image, i.e. the given `width` and * `height` may be adjusted to prevent the dimensions of the output image from exceeding * those of the input image. * * If the given `width` and `height` are adjusted, the aspect ratio is preserved. * @param {string} definition.fit Controls how the transformed image is fitted to the * given `width` and `height`. Valid values are `resize` and `crop`. * The default value is `resize`. * * If set to `resize`, the image is resized so as to fit within the `width` and `height` * boundaries without cropping or distorting the image. The resulting image is assured to * match one of the constraining dimensions, while the other dimension is altered to maintain * the same aspect ratio of the input image. * * If set to `crop`, the image is resized so as to fill the given `width` and `height`, * preserving the aspect ratio by cropping any excess image data. The resulting image will * match both the given `width` and `height` without distorting the image. Cropping is done * centered by default, i.e. the center of the image is preserved. The area to preserve can * be configured using the `crop` parameter. * @param {(number|string)} definition.quality Controls the output quality of lossy * file formats. * * Applies if the format is `jpg`. Valid values are in the range from `0` to `100`. * The default value is `75`. * @param {string} definition.crop Controls the area to preserve when cropping. * * Is only applicable if `fit` is set to `crop`. * Valid values are `center`, `top`, `left`, `right`, and `bottom`. * * For example, setting `crop` to `left` means that the left part of the image will be * preserved when cropping, i.e. if necessary, cropping cuts away the right side of the image. * * @example Crop image to fit into 50 x 50 pixel square. * binary.transform({ width: 50, height: 50, fit: 'crop' }) * * @example Convert image to a low quality JPEG. * binary.transform({ quality: 25 }) * * @example Combine two transformations. * binary.transform({ width: 50, height: 50, fit: 'crop' }).transform({ quality: 25 }) * * @returns {scrivito.Binary} transformed binary */ }, { key: 'transform', value: function transform(definition) { var newDefinition = {}; _.extend(newDefinition, this._transformationDefinition, definition); return new scrivito.Binary(this.id, this._isPublic, newDefinition, this.original); } /** * Returns the original version of a transformed binary. * * If a binary is the result of a transformation, the original version of the binary * is returned. Otherwise it returns itself. * * @example * binary.id // => "abc123" * binary.original.id // => "abc123" * binary.transform({ width: 50 }).original.id // => "abc123" * binary.transform({ width: 50 }).transform({ height: 50 }).original.id // => "abc123" * * @type {scrivito.Binary} */ }, { key: 'isTransformed', /** * Returns whether the binary has been transformed. * * @returns {Boolean} */ value: function isTransformed() { return !!this._transformationDefinition; } /** * The URL for accessing the binary data and downloading it using an HTTP GET request. * * The URLs should not be used for long-term storage since they are no longer * accessible hours or days after they have been generated. * * @throws {scrivito.NotLoadedError} If the URL is not yet loaded. * @type {String} */ }, { key: '_loadUrlData', value: function _loadUrlData() { var path = 'blobs/' + encodeURIComponent(this.id); var params = undefined; if (this._transformationDefinition) { path = path + '/transform'; params = { transformation: this._transformationDefinition }; } return scrivito.CmsRestApi.get(path, params); } }, { key: '_assertNotTransformed', value: function _assertNotTransformed(fieldName) { if (this.isTransformed()) { throw new scrivito.ScrivitoError(fieldName + ' is not available for transformed images.'); } } }, { key: 'original', get: function get() { return this._original || this; } }, { key: 'url', get: function get() { return this._urlData[this._accessType].get.url; } /** * The filename of this binary data, for example `my_image.jpg`. * * @throws {scrivito.NotLoadedError} If the filename is not yet loaded. * @type {string} */ }, { key: 'filename', get: function get() { var path = URI(this.url).pathname(); return path.split('/').pop(); } /** * Returns the metadata for the given binary. * * See {@link scrivito.MetadataCollection} for a list of available metadata attributes. * * @example Accessing metadata * binary.metadata.get('width') // => 150 * binary.metadata.get('content_type') // => 'image/jpeg' * * @throws {scrivito.ScrivitoError} If the binary is the result of a transformation. * @type {scrivito.MetadataCollection} */ }, { key: 'metadata', get: function get() { this._assertNotTransformed('Metadata'); return new scrivito.MetadataCollection(this.id); } /** * Returns the content type of this binary data, for example "image/jpeg". * * @throws {scrivito.ScrivitoError} If the binary is the result of a transformation. * @throws {scrivito.NotLoadedError} If the content type is not yet loaded. * @type {String} */ }, { key: 'contentType', get: function get() { this._assertNotTransformed('Content type'); return this.metadata.get('content_type'); } /** * Returns the length of this binary data, in bytes. * * @throws {scrivito.ScrivitoError} If the binary is the result of a transformation. * @throws {scrivito.NotLoadedError} If the content length is not yet loaded. * @type {Number} */ }, { key: 'contentLength', get: function get() { this._assertNotTransformed('Content length'); return this.metadata.get('content_length'); } // For test purpose only. }, { key: 'transformationDefinition', get: function get() { return this._transformationDefinition; } }, { key: '_accessType', get: function get() { if (this.isPrivate()) { return 'private_access'; } return 'public_access'; } }, { key: '_urlData', get: function get() { return this._loadableData.get(); } }], [{ key: 'upload', value: function upload(source) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; options.source = source; return new scrivito.FutureBinary(options); } // This method is not part of the public API. }, { key: 'store', value: function store(binaryId, transformationDefinition, cmsRestApiResponse) { var loadableData = new scrivito.LoadableData({ state: modelState(binaryId, transformationDefinition) }); loadableData.set(cmsRestApiResponse); } // This method is not part of the public API. }, { key: 'storeMetadata', value: function storeMetadata(binaryId, cmsRestApiResponse) { return scrivito.MetadataCollection.store(binaryId, cmsRestApiResponse); } }]); return Binary; })(); function modelState(binaryId, transformationDefinition) { var subStateKey = scrivito.computeCacheKey([binaryId, transformationDefinition]); return scrivito.modelState.subState('binary').subState(subStateKey); } /** * 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; }; })(); 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 () { function LinkFactory(registry) { /** * This class represents individual external or internal links Scrivito is able to identify and * to process. * * @borrows scrivito.BasicLink#title as #title * @borrows scrivito.BasicLink#query as #query * @borrows scrivito.BasicLink#fragment as #fragment * @borrows scrivito.BasicLink#target as #target * @borrows scrivito.BasicLink#objId as #objId * @borrows scrivito.BasicLink#isExternal as #isExternal * @borrows scrivito.BasicLink#isInternal as #isInternal * @borrows scrivito.BasicLink#copy as #copy */ var Link = (function (_scrivito$BasicLink) { _inherits(Link, _scrivito$BasicLink); /** * 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 Obj#update} or {@link Obj#update}. * * @param {Object} attributes - the attributes of the new Link. * @throws {scrivito.ArgumentError} If invalid attributes are given. */ function Link(attributes) { _classCallCheck(this, Link); _get(Object.getPrototypeOf(Link.prototype), "constructor", this).call(this, attributes); } /** * The {@link Obj|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 {?Obj} */ _createClass(Link, [{ key: "fetchObj", /** * Fetch the {@link Obj|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(id) { return _get(Object.getPrototypeOf(Link.prototype), "fetchObj", this).call(this, id).then(function (basicObj) { return scrivito.wrapInAppClass(registry, basicObj); }); } }, { key: "obj", get: function get() { return scrivito.wrapInAppClass(registry, _get(Object.getPrototypeOf(Link.prototype), "obj", this)); } }]); return Link; })(scrivito.BasicLink); return Link; } scrivito.LinkFactory = LinkFactory; })(); '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 () { /** * This class represents a collection of metadata attributes. * * ### Available metadata attributes * * All binaries have the meta attributes `content_length` and `content_type`, in addition, PDFs * and images have attributes specific to their type. * * If not specified otherwise, the attributes contain `string` values. * * - `content_length` (Number value) - Size in bytes of the given file. * - `content_type` - MIME-type of the given file. * * ### Available metadata attributes for PDFs * * - `text` - Text content of the PDF document. * * ### Available metadata attributes for Images * * The metadata attributes starting with `iptc_` or `exif_` are extracted from the image itself * and therefore may not be available for every image. `iptc` and `exif` are both standardized * formats supported by a wide array of software and hardware, like cameras and phones. * * - `width` (Number value) - Width in pixels. * - `height` (Number value) - Height in pixels. * - `exif_copyright` - Copyright of the image. * - `exif_date_time` - The date at which the image was produced. * * - `iptc_keywords` (Array with Strings value) - A list of keywords associated with the image. * - `iptc_headline` - The headline of the image. * - `iptc_copyright` - Copyright of the image. * - `iptc_byline` - The name of the image creator. * - `iptc_credit` - Contains the persons or companies that should be credited. * - `iptc_source` - The original copyright holder. * - `iptc_profile` - The color profile of the image. * - `iptc_city` - The city in which the image was produced. * - `iptc_state` - The state in which the image was produced. * - `iptc_country_name` - The country in which the image was produced. * - `iptc_country_code` - The code of the country in which the image was produced. * * ### Searching for metadata * * Metadata is taken into account when searching. See the * {@link ObjSearchIterable ObjSearchIterable} for details. * * @example Search for all JPEGs * Image.where('blob:content_type', 'equals', 'image/jpeg') * * @example Search for wide images * Image.where('blob:width', 'is_greater_than', 1024) */ scrivito.MetadataCollection = (function () { /** * This `constructor` is not part of the public API and should **not** be used. * * See `{@link scrivito.Binary#metadata}` for information on how to access `MetadataCollection`. */ function MetadataCollection(binaryId) { var _this = this; _classCallCheck(this, MetadataCollection); this._binaryId = binaryId; this._loadableData = new scrivito.LoadableData({ state: modelState(binaryId), loader: function loader() { return _this._loadData(); } }); } // This method is not part of the public API. _createClass(MetadataCollection, [{ key: 'get', /** * Find value of a metadata attribute. * * @param {String} name the name of the metadata attribute. * @throws {scrivito.NotLoadedError} If the metadata is not yet loaded. * @returns {String|String[]|Number|Date} metadata attribute value if found * or undefined otherwise. */ value: function get(name) { return this._loadableData.get()[name]; } // For test purpose only. }, { key: '_loadData', value: function _loadData() { var path = 'blobs/' + encodeURIComponent(this._binaryId) + '/meta_data'; return scrivito.CmsRestApi.get(path).then(deserializeMetadata); } }, { key: 'binaryId', get: function get() { return this._binaryId; } }], [{ key: 'store', value: function store(binaryId, cmsRestApiResponse) { var loadableData = new scrivito.LoadableData({ state: modelState(binaryId) }); loadableData.set(deserializeMetadata(cmsRestApiResponse)); } }]); return MetadataCollection; })(); function modelState(binaryId) { return scrivito.modelState.subState('metadataCollection').subState(binaryId); } function deserializeMetadata(rawMetadata) { return _.mapObject(rawMetadata.meta_data, function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var type = _ref2[0]; var value = _ref2[1]; switch (type) { case 'date': return scrivito.types.deserializeAsDate(value); case 'number': return scrivito.types.deserializeAsInteger(value); default: return value; } }); } })(); '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(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _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 { _x2 = parent; _x3 = property; _x4 = 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 () { function ObjFactory(registry) { function buildObjSearchIterable(objClassName) { var iterable = new registry.ObjSearchIterable(); if (objClassName) { iterable.and('_obj_class', 'equals', objClassName); } return iterable; } /** * The base class for CMS objects. * * * A CMS object is a collection of properties and their values, as defined * by its object class. * * @borrows AttributeContent#get as #get * @borrows AttributeContent#id as #id * @borrows AttributeContent#objClass as #objClass * @borrows AttributeContent#finishSaving as #finishSaving * @borrows AttributeContent#update as #update */ var Obj = (function (_scrivito$AttributeContentFactory) { _inherits(Obj, _scrivito$AttributeContentFactory); function Obj() { _classCallCheck(this, Obj); _get(Object.getPrototypeOf(Obj.prototype), 'constructor', this).apply(this, arguments); } _createClass(Obj, [{ key: 'destroy', /** * Destroy this CMS object in the current Workspace. */ value: function destroy() { this._scrivitoPrivateContent.destroy(); } /** * Access widgets by their ids * * @param {String} id - the widget's id * @returns {scrivito.Widget} */ }, { key: 'widget', value: function widget(id) { var widget = this._scrivitoPrivateContent.widget(id); if (widget) { return scrivito.wrapInAppClass(registry, widget); } } }, { key: 'lastChanged', /** * The date the CMS object was last changed. * Returns `null` if the obj has not been changed yet. * @type {?Date} */ get: function get() { return this._scrivitoPrivateContent.lastChanged; } /** * The path of the CMS object * @type {?String} */ }, { key: 'path', get: function get() { return this._scrivitoPrivateContent.path; } /** * The permalink of the CMS object * @type {?String} */ }, { key: 'permalink', get: function get() { return this._scrivitoPrivateContent.permalink; } }], [{ key: 'get', /** * 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 {Obj} */ value: function get(id) { var instance = scrivito.BasicObj.get(id); var objClassName = registry.objClassNameFor(this); if (objClassName && objClassName !== instance.objClass) { throw new scrivito.ResourceNotFoundError('Obj with id "' + id + '" is not of type "' + objClassName + '".'); } return scrivito.wrapInAppClass(registry, instance); } /** * Returns an {@link ObjSearchIterable} of all {@link Obj}s. * @return {ObjSearchIterable} */ }, { key: 'all', value: function all() { var objClassName = registry.objClassNameFor(this); return buildObjSearchIterable(objClassName).batchSize(1000); } /** * Returns an {@link 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 ObjSearchIterable}. * * @example * // Look for objects with left-over "Lorem", boosting headline matches: * Obj.where(:*, :contains, 'Lorem', headline: 2) * * @param {String|String[]} field See {@link ObjSearchIterable#and} for details * @param {String} operator See {@link ObjSearchIterable#and} for details * @param {String|String[]} value See {@link ObjSearchIterable#and} for details * @param {Object} [boost] See {@link ObjSearchIterable#and} for details * @return {ObjSearchIterable} */ }, { key: 'where', value: function where(field, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var objClassName = registry.objClassNameFor(this); return buildObjSearchIterable(objClassName).and(field, operator, value, boost); } /** * Create a new {@link Obj}. * * @param attributes the new obj's attributes. The `_obj_class` has to be provided * * @return {Obj} the newly created obj. * @throws {scrivito.ArgumentError} if the `_obj_class` is missing or invalid. */ }, { key: 'create', value: function create(attributes) { var schema = this._scrivitoPrivateSchema; var appClassName = registry.objClassNameFor(this); if (!appClassName) { throw new scrivito.ArgumentError('Creating CMS objects is not supported for the class Obj or abstract classes.'); } if (attributes.constructor !== Object) { throw new scrivito.ArgumentError('The provided attributes are invalid. They have ' + 'to be an Object with valid Scrivito attribute values.'); } if (attributes._objClass) { throw new scrivito.ArgumentError('Invalid attribute "_objClass". ' + ('"' + attributes._objClass + '.create" will automatically set the CMS object class ') + 'correctly.'); } attributes._objClass = appClassName; var attributesWithTypeInfo = scrivito.AttributeContentFactory.prepareAttributes(attributes, schema, appClassName); var basicObj = scrivito.BasicObj.create(attributesWithTypeInfo); return scrivito.wrapInAppClass(registry, basicObj); } }]); return Obj; })(scrivito.AttributeContentFactory(registry)); return Obj; } scrivito.ObjFactory = ObjFactory; })(); "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(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _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 { _x2 = parent; _x3 = property; _x4 = 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 () { function ObjSearchIterableFactory(registry) { /** * Allows iterating over the results of searches for CMS objects to retrieve instances of * {@link Obj}. 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 Obj}. This is a `string` field. * - `'_path'` - Path of an {@link Obj}. This is a `string` field. * - `'_obj_class'` - Object class of an {@link Obj}. This is a `string` field. * - `'_permalink'` - Permalink of an {@link Obj}. This is a `string` field. * - `'_last_changed'` - Date of last change to an {@link Obj}. * - every `custom_attribute` Custom attribute of an {@link Obj}. 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 Obj Objs} and **not** of * {@link Widget 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) * * **`links_to`** * * The `links_to` operator searches for CMS objects containing one or more attributes linking to * specific CMS objects. So the operator returns the CMS objects in which at least one `html`, * `link`, `linklist`, `reference` or `referencelist` attribute links to specific CMS objects. * * The operator can only be applied to all attributes, so the `"*"` wildcard _must_ be specified * for the attributes to search. If you want to search specific `reference` or `referencelist` * attributes, please use the `refers_to` operator. * * Using `null` instead of an instance of {@link Obj} results in an error. * * Note that, in contrast to the `refers_to` operator, the `links_to` operator searches the * attributes directly part of the CMS objects _as_ _well_ _as_ the attributes contained in * widgets. * * Example subquery values: * * ✔ `myObj` (an instance of {@link Obj}) * * ✔ `[myObj1, myObj2]` (an `Array` of instances of {@link Obj}) * * ✘ `null` (not an instance of {@link Obj}) * * ✘ "someString" (not an instance of {@link Obj}) * * **`refers_to`** * * The `refers_to` operator searches for CMS objects in which at least one of the specified * `reference` or `referencelist` attributes refers to specific CMS objects. * * Using the `"*"` wildcard for the attributes to search causes all `reference` and * `referencelist` attributes of the searched CMS objects to be taken into account. * * Using `null` instead of {@link Obj Objs} searches for all CMS objects in which * none of the specified attributes refer to a CMS object. * * Note that, in contrast to the `links_to` operator, the `refers_to` operator only searches * attributes _directly_ _part_ _of_ _the_ _CMS_ _objects_. Currently, attributes contained in * widgets are _not_ searched. * * Example subquery values: * * ✔ `myObj` (an instance of {@link Obj}) * * ✔ `[myObj1, myObj2]` (an `Array` of instances of {@link Obj}) * * ✔ `null` * * ✘ "someString" (not an instance of {@link Obj}) * * **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. * * ## Limits * * The number of chainable subqueries is limited. The limit depends on the number of values, * fields, and boost parameters requested, as well as the number of words in a free text * search. * * @borrows BasicObjSearchIterable#offset #offset * @borrows BasicObjSearchIterable#order #order * @borrows BasicObjSearchIterable#batchSize #batchSize */ var ObjSearchIterable = (function (_scrivito$BasicObjSearchIterable) { _inherits(ObjSearchIterable, _scrivito$BasicObjSearchIterable); function ObjSearchIterable() { _classCallCheck(this, ObjSearchIterable); _get(Object.getPrototypeOf(ObjSearchIterable.prototype), "constructor", this).apply(this, arguments); } _createClass(ObjSearchIterable, [{ key: "iterator", /** * 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 Obj} 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. */ value: function iterator() { var basicIterator = _get(Object.getPrototypeOf(ObjSearchIterable.prototype), "iterator", this).call(this); return { next: function next() { var _basicIterator$next = basicIterator.next(); var done = _basicIterator$next.done; var value = _basicIterator$next.value; if (done) { return { done: done }; } return { done: done, value: scrivito.wrapInAppClass(registry, value) }; } }; } /** * Adds the given AND subquery to this {@link 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 "Available operators" above. * @param {String|Date|Time|Number| String[]|Date[]|Time[]|Number[]| * Obj|Obj[]} * 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 {ObjSearchIterable} itself * * @example * // Searching for the string "Scrivito" and * // boosting the fields "headline" and "keywords": * * Obj.where("*", "contains", "Scrivito", { * headline: 5, * keywords: 10, * }); * * @example * // Find CMS objects linking to "myImage" through any link or reference: * * Obj.where("*", :links_to, myImage); * * @example * // Find "BlogPostPage" objects linking to "myImage1" or "myImage2" * // through any link or reference: * * Obj.where("_obj_class", "equals", "BlogPostPage") * .and("*", :links_to, [myImage1, myImage2]); * * @example * // Find all objects of the "BlogPost" class that reference "authorObj" * // via the "authors" referencelist attribute: * * Obj.where("_obj_class", "equals", "BlogPost"). * .and("authors", "refers_to", authorObj); */ }, { key: "and", value: function and(field, operator, value) { var boost = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var unwrappedValue = scrivito.unwrapAppClassValues(value); return _get(Object.getPrototypeOf(ObjSearchIterable.prototype), "and", this).call(this, field, operator, unwrappedValue, boost); } /** * Adds the given negated AND subquery to this {@link 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 {ObjSearchIterable} itself */ }, { key: "andNot", value: function andNot(field, operator, value) { var unwrappedValue = scrivito.unwrapAppClassValues(value); return _get(Object.getPrototypeOf(ObjSearchIterable.prototype), "andNot", this).call(this, field, operator, unwrappedValue); } }]); return ObjSearchIterable; })(scrivito.BasicObjSearchIterable); return ObjSearchIterable; } scrivito.ObjSearchIterableFactory = ObjSearchIterableFactory; })(); '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 () { function WidgetFactory(registry) { /** * The base class for widgets. * * @example * // Creating and attaching a widget * let widget = new Widget({_obj_class: 'TextWidget', text: 'Hello World'}); * obj.update({my_widgetlist: [widget]}); * * @borrows AttributeContent#get as #get * @borrows AttributeContent#id as #id * @borrows AttributeContent#objClass as #objClass * @borrows AttributeContent#finishSaving as #finishSaving * @borrows AttributeContent#update as #update */ var Widget = (function (_scrivito$AttributeContentFactory) { _inherits(Widget, _scrivito$AttributeContentFactory); /** * 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 Obj#update} or {@link Widget#update}. * * @param {Object} attributes - the new widget's attributes. The `_obj_class` has to be * provided. */ function Widget(attributes) { _classCallCheck(this, Widget); _get(Object.getPrototypeOf(Widget.prototype), 'constructor', this).call(this); var schema = this.constructor._scrivitoPrivateSchema; var appClassName = registry.objClassNameFor(this.constructor); if (!appClassName) { throw new scrivito.ArgumentError('Creating widgets is not supported for the class Widget or abstract classes.'); } if (attributes.constructor !== Object) { throw new scrivito.ArgumentError('The provided attributes are invalid. They have ' + 'to be an Object with valid Scrivito attribute values.'); } if (attributes._objClass) { throw new scrivito.ArgumentError('Invalid attribute "_objClass". ' + ('"new ' + attributes._objClass + '" will automatically set the CMS object class correctly.')); } attributes._objClass = appClassName; var attributesWithTypeInfo = scrivito.AttributeContentFactory.prepareAttributes(attributes, schema, appClassName); this._scrivitoPrivateContent = new scrivito.BasicWidget(attributesWithTypeInfo); } return Widget; })(scrivito.AttributeContentFactory(registry)); return Widget; } scrivito.WidgetFactory = WidgetFactory; })(); "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 purpose 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 purpose only. enableNextTickCapture: function enableNextTickCapture() { captureEnabled = 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 () { scrivito.ObjData = (function () { function ObjData(id, state) { var _this = this; _classCallCheck(this, ObjData); this._loadableData = new scrivito.LoadableData({ state: state, loader: function loader() { return scrivito.ObjRetrieval.retrieveObj(_this._id).then(function (data) { scrivito.ObjReplication.get(_this._id).notifyBackendState(data); return data; }); } }); 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() { this._loadableData.get(); } }, { 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: "current", get: function get() { return this._loadableData.get(); } }]); return ObjData; })(); })(); '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().clear(); } }; function cacheStore() { return scrivito.modelState.subState('objData'); } function objDataFor(id) { return new scrivito.ObjData(id, cacheStore().subState(id)); } })(); "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 priorObjIds = {}; var currentBatch = scrivito.ObjQueryBatch.firstBatchFor(this._params, batchSize); var currentIndex = 0; function next() { var _again = true; _function: while (_again) { _again = false; var currentObjIds = currentBatch.objIds(); if (currentIndex < currentObjIds.length) { var objId = currentObjIds[currentIndex]; currentIndex++; if (priorObjIds[objId]) { _again = true; currentObjIds = objId = undefined; continue _function; } priorObjIds[objId] = true; return { value: objId, done: false }; } var nextBatch = currentBatch.nextBatch(); if (nextBatch) { currentBatch = nextBatch; currentIndex = 0; _again = true; currentObjIds = objId = nextBatch = undefined; continue _function; } return { done: true }; } } return { next: next }; } }]); 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.ObjQueryBatch = (function () { _createClass(ObjQueryBatch, [{ key: "objIds", // throws NotLoadedError if not available value: function objIds() { return this._response().results; } // returns the next batch or undefined if this is the last batch // throws NotLoadedError if not available }, { key: "nextBatch", value: function nextBatch() { var continuation = this._response().continuation; if (continuation) { return new ObjQueryBatch(this._params, this._batchSize, continuation); } } // the constructor should only be called internally, // i.e. by ObjQueryBatch itself }], [{ key: "firstBatchFor", value: function firstBatchFor(params, batchSize) { return new ObjQueryBatch(params, batchSize); } }]); function ObjQueryBatch(params, batchSize, continuation) { _classCallCheck(this, ObjQueryBatch); this._params = params; this._continuation = continuation; this._batchSize = batchSize; } _createClass(ObjQueryBatch, [{ key: "_response", value: function _response() { return this._data().get(); } }, { key: "_data", value: function _data() { var _this = this; var paramsWithContinuation = _.extend({}, this._params, { continuation: this._continuation }); var key = scrivito.ObjQueryStore.computeCacheKey(paramsWithContinuation); return new scrivito.LoadableData({ state: scrivito.ObjQueryStore.stateContainer().subState(key), loader: function loader() { return _this._load(); }, invalidation: function invalidation() { return scrivito.ObjReplication.getWorkspaceVersion(); } }); } }, { key: "_load", value: function _load() { var batchSpecificParams = { size: this._batchSize, continuation: this._continuation }; var requestParams = _.extend({}, this._params, batchSpecificParams); return scrivito.ObjQueryRetrieval.retrieve(requestParams).then(function (response) { preloadObjData(response.results); return response; }); } }]); return ObjQueryBatch; })(); function preloadObjData(ids) { _.each(ids, function (id) { return scrivito.ObjDataStore.preload(id); }); } })(); "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 () { scrivito.ObjQueryRetrieval = { retrieve: function retrieve(params) { var workspaceId = scrivito.currentWorkspaceId(); 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'; (function () { scrivito.ObjQueryStore = { computeCacheKey: function computeCacheKey(obj) { return scrivito.computeCacheKey(obj); }, get: function get(params, batchSize) { var objQuery = new scrivito.ObjQuery(params); return new scrivito.ObjQueryIterator(objQuery, batchSize); }, stateContainer: function stateContainer() { return scrivito.modelState.subState('objQuery'); }, clearCache: function clearCache() { this.stateContainer().clear(); } }; })(); '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; var workspaceVersion = 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]; } }, { key: 'subscribeWrites', value: function subscribeWrites(callback) { subscriptionToken += 1; writeCallbacks[subscriptionToken] = callback; return subscriptionToken; } }, { key: 'unsubscribeWrites', value: function unsubscribeWrites(token) { delete writeCallbacks[token]; } // a version counter that increases whenever an Obj in the Workspace is changed. }, { key: 'getWorkspaceVersion', value: function getWorkspaceVersion() { return workspaceVersion; } }]); 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 (disabled) { return; } if (this._backendState === undefined) { throw new scrivito.InternalError('Can not set local state before backend state.'); } if (this._backendState && this._backendState._deleted) { throw new scrivito.InternalError('Can not update a fully deleted obj.'); } this._localState = localState; this._startReplication(); } }, { key: 'notifyBackendState', value: function notifyBackendState(newBackendState) { if (this._backendState === undefined) { this._updateBackendState(newBackendState); this._updateLocalState(newBackendState); return; } var newestKnownBackendState = this._bufferedBackendState || this._backendState; if (compareStates(newBackendState, newestKnownBackendState) > 0) { if (this._replicationActive) { this._bufferedBackendState = newBackendState; } else { if (newBackendState._deleted) { this._updateLocalState(null); } else { var patch = diff(this._backendState, newBackendState); this._updateLocalState(apply(this.localState, patch)); } this._updateBackendState(newBackendState); } } } }, { 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 (!_.isEmpty(diff(this._backendState, this._localState))) { 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 = diff(this._backendState, this._localState); this._scheduledReplication = false; this._replicationActive = true; this._replicatePatchToBackend(patch).then(function (backendState) { _this2._handleBackendUpdate(localState, backendState); _this2._currentRequestDeferred.resolve(_this2._id); _this2._currentRequestDeferred = null; _this2._replicationActive = false; _this2._startReplication(); }, function (error) { _this2._currentRequestDeferred.reject(error); _this2._currentRequestDeferred = null; _this2._replicationActive = false; }); } }, { key: '_replicatePatchToBackend', value: function _replicatePatchToBackend(patch) { if (patch._modification === 'deleted') { return this._deleteObj(); } if (_.isEmpty(patch)) { return scrivito.Promise.resolve(this._backendState); } var workspaceId = scrivito.editingContext.selectedWorkspace.id(); var path = 'workspaces/' + workspaceId + '/objs/' + this._id; return scrivito.CmsRestApi.put(path, { obj: patch }); } }, { key: '_deleteObj', value: function _deleteObj() { var workspaceId = scrivito.editingContext.selectedWorkspace.id(); var path = 'workspaces/' + workspaceId + '/objs/' + this._id; return scrivito.CmsRestApi['delete'](path, { include_deleted: true }); } }, { 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 = diff(replicatedState, this._localState); this._updateBackendState(newerState(backendState, this._bufferedBackendState)); this._bufferedBackendState = undefined; this._updateLocalState(apply(this._backendState, bufferedLocalChanges)); } }, { key: '_updateLocalState', value: function _updateLocalState(localState) { this._localState = localState; scrivito.ObjDataStore.set(this._id, this._localState); } }, { key: '_updateBackendState', value: function _updateBackendState(newBackendState) { if (this._backendState !== undefined) { workspaceVersion++; } this._backendState = newBackendState; } // For test purpose only. }, { key: 'isNotStoredInBackend', // For test purpose only. value: function isNotStoredInBackend() { return this._backendState === null; } // For test purpose only. }, { key: 'isRequestInFlight', value: function isRequestInFlight() { return this._replicationActive; } // For test purpose only. }, { key: 'backendState', get: function get() { return this._backendState; } // For test purpose only. }, { key: 'localState', get: function get() { return this._localState; } }], [{ 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 diff(stateA, stateB) { return scrivito.ObjPatch.diff(stateA, stateB); } function apply(stateA, patch) { return scrivito.ObjPatch.apply(stateA, patch); } function newerState(stateA, stateB) { if (compareStates(stateA, stateB) > 0) { return stateA; } return stateB; } function compareStates(stateA, stateB) { if (!stateA) { return -1; } if (!stateB) { return 1; } return strCompare(stateA._version, stateB._version); } function strCompare(str1, str2) { if (str1 > str2) { return 1; } if (str2 > str1) { return -1; } return 0; } function writeStarted(promise) { _.each(writeCallbacks, function (callback) { callback(promise); }); } })(); "use strict"; (function () { var batchRetrieval = new scrivito.BatchRetrieval(function (ids) { var workspaceId = scrivito.currentWorkspaceId(); return scrivito.CmsRestApi.get("workspaces/" + workspaceId + "/objs/mget", { ids: ids, include_deleted: true }).then(function (response) { return response.results; }); }); scrivito.ObjRetrieval = { retrieveObj: function retrieveObj(id) { return batchRetrieval.retrieve(id).then(function (value) { if (value) { return value; } throw new scrivito.ResourceNotFoundError("Obj with id \"" + id + "\" not found."); }); }, // For test purpose only. reset: function reset() { batchRetrieval.reset(); } }; })(); "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'; 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 Realm = (function () { _createClass(Realm, null, [{ key: 'init', value: function init(context) { var realm = new Realm(); context.Obj = realm.Obj; context.Widget = realm.Widget; context.Link = realm.Link; context.createObjClass = function () { return realm.createObjClass.apply(realm, arguments); }; context.createWidgetClass = function () { return realm.createWidgetClass.apply(realm, arguments); }; context.getClass = function () { return realm.getClass.apply(realm, arguments); }; context.registerClass = function () { return realm.registerClass.apply(realm, arguments); }; } }]); function Realm() { _classCallCheck(this, Realm); this._registry = new scrivito.Registry(); this._registry.defaultClassForObjs = scrivito.ObjFactory(this._registry); this._registry.defaultClassForWidgets = scrivito.WidgetFactory(this._registry); this._registry.defaultClassForLinks = scrivito.LinkFactory(this._registry); this._registry.ObjSearchIterable = scrivito.ObjSearchIterableFactory(this._registry); } _createClass(Realm, [{ key: 'createObjClass', /** * @global * * @description Creates a new CMS object class. * * @param createObjClass.attributes The attribute defintion of the CMS object class * @param createObjClass.name The name of the CMS object class. If omitted, then an * abstract class will be created * @param createOptions.extend The CMS object class from which this one should inherit its * attributes. By default the base class `Obj` is used. * * @example * // Creating a Page class * const Page = scrivito.createObjClass({ name: 'Page', attributes: { * body: 'widgetlist', * bgColor: ['enum', { validValues: ['black', 'white', 'grey'], * }); * * // Creating an Image Class * const Image = scrivito.createObjClass({ name: 'Image', attributes: { * blob: 'binary', * tags: 'stringlist', * }); */ value: function createObjClass(createOptions) { return this._createAppClass(createOptions, this.Obj); } /** * @global * * @description Creates a new Widget class. * * @param createObjClass.attributes The attribute defintion of the Widget class * @param createObjClass.name The name of the Widget class. If omitted, then an * abstract class will be created * @param createOptions.extend The Widget class from which this one should inherit its * attributes. By default the base class `Widget` is used. * * @example * // Creating a Text Widget class * const TextWidget = scrivito.createObjClass({ name: 'TextWidget', attributes: { * text: 'html', * alignment: ['enum', { validValues: ['left', 'center', 'right'], * }); * * // Creating an Image Widget class * const ImageWidget = scrivito.createObjClass({ name: 'ImageWidget', attributes: { * image: 'reference', * }); */ }, { key: 'createWidgetClass', value: function createWidgetClass(createOptions) { return this._createAppClass(createOptions, this.Widget); } /** * @global * * @description Returns the CMS object or Widget class with the given name or `undefined` */ }, { key: 'getClass', value: function getClass(name) { return this._registry.getClass(name); } /** * @global * * @description Register an unnamed CMS object or Widget class under the given name. * * @param name The name under which the class should be registered * @param the CMS object or Widget class * * @example * const BaseClass = scrivito.createObjClass(attributes: { * body: 'widgetlist', * bgColor: ['enum', { validValues: ['black', 'white', 'grey'], * }); * * class Page extends BaseClass { * * } * * scrivito.registerClass('Page', Page); */ }, { key: 'registerClass', value: function registerClass(name, appClass) { if (!this._isAppClass(appClass)) { throw new scrivito.ArgumentError('registerClass has to be called with a CMS object or Widget class.'); } this._registry.register(name, appClass); } }, { key: '_createAppClass', value: function _createAppClass(createOptions, prototypeClass) { var parentClass = createOptions.extend || prototypeClass; var appClass = scrivito.AppClassFactory(createOptions, parentClass); if (createOptions.name) { this._registry.register(createOptions.name, appClass); } return appClass; } }, { key: '_isAppClass', value: function _isAppClass(appClass) { var appProto = appClass.prototype; return appProto instanceof this.Obj || appProto instanceof this.Widget; } }, { key: 'Obj', get: function get() { return this._registry.defaultClassForObjs; } }, { key: 'Widget', get: function get() { return this._registry.defaultClassForWidgets; } }, { key: 'Link', get: function get() { return this._registry.defaultClassForLinks; } }, { key: 'ObjSearchIterable', get: function get() { return this._registry.ObjSearchIterable; } }]); return Realm; })(); scrivito.Realm = Realm; })(); "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 Registry = (function () { function Registry() { _classCallCheck(this, Registry); this._mapping = {}; } _createClass(Registry, [{ key: "register", value: function register(name, klass) { this._mapping[name] = klass; } }, { key: "getClass", value: function getClass(name) { return this._mapping[name]; } }, { key: "objClassFor", value: function objClassFor(name) { return this._appClassFor(name, this.defaultClassForObjs); } }, { key: "widgetClassFor", value: function widgetClassFor(name) { return this._appClassFor(name, this.defaultClassForWidgets); } }, { key: "objClassNameFor", value: function objClassNameFor(modelClass) { return _.findKey(this._mapping, function (klass) { return klass === modelClass; }); } }, { key: "_appClassFor", value: function _appClassFor(name, baseClass) { var appClass = this.getClass(name); if (appClass && baseClass.isPrototypeOf(appClass)) { return appClass; } return baseClass; } }]); return Registry; })(); scrivito.Registry = Registry; })(); '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 VISITOR_SESSION = { token: undefined }; var session = VISITOR_SESSION; 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 (session !== VISITOR_SESSION && error instanceof scrivito.UnauthorizedError) { if (!sessionRenewalPromise) { clearTimeout(timeoutId); sessionRenewalPromise = renewSession(); } return sessionRenewalPromise.then(function () { return callback(session.token); }); } throw error; }); } }, { key: 'clearSession', // For test purpose only. value: function clearSession() { session = VISITOR_SESSION; } }, { 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 () { 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.ajax('PUT', 'sessions/' + session.id, { skip_write_monitor: true })); } })(); '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'); } // reset the state back to undefined }, { key: 'clear', value: function clear() { this.set(undefined); } }, { key: 'subState', value: function subState(key) { return new StateTreeNode(this, key); } }, { key: 'setSubState', value: function setSubState(key, newState) { var priorState = this._getAssumingSubTree(); 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._getAssumingSubTree(); if (state) { return state.get(key); } } // return current state, but only if it's a subtree or undefined. }, { key: '_getAssumingSubTree', value: function _getAssumingSubTree() { var getValue = this.get(); if (getValue === undefined) { return getValue; } if (getValue instanceof Immutable.Map) { return getValue; } throw new scrivito.InternalError('Tried to access subtree, but found ' + getValue + '. ' + "Parent nodes can't contain values."); } }]); 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 purpose only. }, { key: 'listenerCount', value: function listenerCount() { return this._listeners.size; } // For test purpose only. }, { key: 'clearListeners', value: function clearListeners() { this._listeners = Immutable.Set(); } }]); 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(); })(); '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.typeInfo = { normalize: function normalize(typeInfo) { if (_.isString(typeInfo)) { return [typeInfo]; } if (_.isArray(typeInfo)) { return typeInfo; } throw new scrivito.InternalError('Type Info needs to be a string or an array containing a string and optionally a hash'); }, normalizeAttrs: function normalizeAttrs(attributes) { var _this = this; return _.mapObject(attributes, function (_ref, name) { var _ref2 = _slicedToArray(_ref, 2); var value = _ref2[0]; var typeInfo = _ref2[1]; if (scrivito.Attribute.isSystemAttribute(name)) { return [value]; } return [value, _this.normalize(typeInfo)]; }); }, unwrapAttributes: function unwrapAttributes(attributes) { return _.mapObject(attributes, function (_ref3) { var _ref32 = _slicedToArray(_ref3, 1); var value = _ref32[0]; return value; }); } }; })(); "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_RANGE_START = -9007199254740991; var INTEGER_RANGE_END = 9007199254740991; var BACKEND_FORMAT_REGEXP = /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/; scrivito.types = { deserializeAsInteger: function deserializeAsInteger(value) { if (_.isString(value)) { if (value.match(/^-?\d+$/)) { return convertToInteger(value); } return null; } return convertToInteger(value); }, isValidInteger: function isValidInteger(value) { return isInteger(value) && INTEGER_RANGE_START <= value && value <= INTEGER_RANGE_END; }, isValidFloat: function isValidFloat(value) { return _.isNumber(value) && _.isFinite(value); }, deserializeAsDate: function deserializeAsDate(value) { if (!_.isString(value)) { return null; } if (!scrivito.types.isValidDateString(value)) { throw new scrivito.InternalError("The value is not a valid ISO date time: \"" + value + "\""); } return scrivito.parseDate(value); }, parseStringToDate: function parseStringToDate(dateString) { if (!dateString) { return; } var _dateString$match = dateString.match(BACKEND_FORMAT_REGEXP); var _dateString$match2 = _slicedToArray(_dateString$match, 7); var _match = _dateString$match2[0]; var year = _dateString$match2[1]; var month = _dateString$match2[2]; var day = _dateString$match2[3]; var hours = _dateString$match2[4]; var minutes = _dateString$match2[5]; var seconds = _dateString$match2[6]; return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)); }, formatDateToString: function formatDateToString(date) { var yearMonth = "" + date.getUTCFullYear() + pad(date.getUTCMonth() + 1); var dateHours = "" + pad(date.getUTCDate()) + pad(date.getUTCHours()); var minutesSeconds = "" + pad(date.getUTCMinutes()) + pad(date.getUTCSeconds()); return "" + yearMonth + dateHours + minutesSeconds; }, isValidDateString: function isValidDateString(dateString) { return _.isString(dateString) && dateString.match(/^\d{14}$/); } }; function pad(number) { return number < 10 ? "0" + number : number; } function isInteger(value) { return _.isNumber(value) && _.isFinite(value) && Math.floor(value) === value; } 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 null; } })(); "use strict"; (function () { function wrapInAppClass(registry, internalValue) { if (_.isArray(internalValue)) { return _.map(internalValue, function (value) { return wrapInAppClass(registry, value); }); } if (internalValue instanceof scrivito.BasicObj) { return buildAppClassInstance(internalValue, registry.objClassFor(internalValue.objClass)); } if (internalValue instanceof scrivito.BasicWidget) { return buildAppClassInstance(internalValue, registry.widgetClassFor(internalValue.objClass)); } if (internalValue instanceof scrivito.BasicLink) { return registry.defaultClassForLinks.build(internalValue.buildAttributes()); } return internalValue; } function buildAppClassInstance(internalValue, appClass) { var externalValue = Object.create(appClass.prototype); externalValue._scrivitoPrivateContent = internalValue; return externalValue; } function unwrapAppClassValues(values) { if (_.isArray(values)) { return _.map(values, unwrapSingleValue); } return unwrapSingleValue(values); } function unwrapSingleValue(value) { if (value && value._scrivitoPrivateContent) { return value._scrivitoPrivateContent; } return value; } scrivito.wrapInAppClass = wrapInAppClass; scrivito.unwrapAppClassValues = unwrapAppClassValues; })(); (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(); } }); }()); "use strict"; (function () { _.extend(scrivito, { path_for_id: function path_for_id(id) { return "/__scrivito/" + id; }, id_from_path: function id_from_path(url) { var match = /__scrivito\/([a-z0-9]{16})/.exec(url); if (match) { return match[1]; } }, detailsPathForId: function detailsPathForId(objId) { return "/__scrivito/page_details/" + objId; } }); })(); '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.obj_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) { return; } 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.obj_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 purpose 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 purpose 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)); } } }); }()); 'use strict'; (function () { var displayMode = undefined; var selectedWorkspace = undefined; var visibleWorkspace = undefined; scrivito.editingContext = Object.defineProperties({ init: function init(config) { var _this = this; displayMode = config.display_mode; selectedWorkspace = scrivito.legacy_workspace.from_data(config.selected_workspace); visibleWorkspace = scrivito.legacy_workspace.from_data(config.visible_workspace); if (document.hasFocus()) { this.writeCookie(); } $.ajaxPrefilter(this.ajaxPrefilter); scrivito.gui.on('document', function (cmsDocument) { cmsDocument.local_jquery().ajaxPrefilter(_this.ajaxPrefilter); }); // 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 () { return _this.writeCookie(); }); }, location: function location(params) { var uri = new URI(scrivito.location()); if (params.workspaceId) { uri.setQuery('_scrivito_workspace_id', params.workspaceId); } if (params.displayMode) { uri.setQuery('_scrivito_display_mode', params.displayMode); } return uri; }, isViewMode: function isViewMode() { return displayMode === 'view'; }, isEditingMode: function isEditingMode() { return displayMode === 'editing'; }, isAddedMode: function isAddedMode() { return displayMode === 'added'; }, isDeletedMode: function isDeletedMode() { return displayMode === 'deleted'; }, isDiffMode: function isDiffMode() { return displayMode === 'diff'; }, isComparingMode: function isComparingMode() { return this.isAddedMode() || this.isDeletedMode() || this.isDiffMode(); }, ajaxPrefilter: function ajaxPrefilter(options, _originalOptions, xhr) { if (!options.crossDomain) { xhr.setRequestHeader('Scrivito-Editing-Context', serialize()); } }, writeCookie: function writeCookie() { $.cookie('scrivito_editing_context', serialize(), { path: '/' }); }, comparingMode: function comparingMode() { var storageKey = 'editing_context.comparing_mode'; if (this.isComparingMode()) { scrivito.storage.set(storageKey, displayMode); return displayMode; } if (scrivito.storage.hasKey(storageKey)) { return scrivito.storage.get(storageKey); } return 'diff'; }, reasonForDisplayModeBeingDisabled: function reasonForDisplayModeBeingDisabled(mode) { if (mode === 'editing') { return scrivito.editingMode.reasonForBeingDisabled; } }, conflictingWorkspacesFor: function conflictingWorkspacesFor(obj) { if (scrivito.Workspace.selected.isPublished()) { return []; } var workspaces = scrivito.Workspace.byModifiedObj(obj); var selectedWorkspaceId = scrivito.Workspace.selected.id; return _.reject(workspaces, function (workspace) { return workspace.id === selectedWorkspaceId; }); }, restrictionMessagesFor: function restrictionMessagesFor(obj) { var user = scrivito.User.current; return scrivito.Workspace.selected.isPublished() ? [] : user.restrictionMessagesFor(obj); } }, { displayMode: { get: function get() { return displayMode; }, set: function set(newDisplayMode) { displayMode = newDisplayMode; }, configurable: true, enumerable: true }, selectedWorkspace: { get: function get() { return selectedWorkspace; }, set: function set(workspace) { selectedWorkspace = workspace; }, configurable: true, enumerable: true }, visibleWorkspace: { get: function get() { return visibleWorkspace; }, set: function set(workspace) { visibleWorkspace = workspace; }, configurable: true, enumerable: true } }); function serialize() { return JSON.stringify({ display_mode: displayMode, workspace_id: selectedWorkspace.id() }); } })(); 'use strict'; (function () { var reasonStorageKey = 'edit_mode_disabled.reason'; scrivito.editingMode = Object.defineProperties({ disable: function disable(reason) { var oldReason = scrivito.editingMode.reasonForBeingDisabled; scrivito.storage.set(reasonStorageKey, reason); if (scrivito.editingContext.isEditingMode()) { return scrivito.withSavingOverlay(scrivito.changeEditingContext({ displayMode: 'view' })); } if (oldReason !== reason) { reloadUI(); } }, enable: function enable(reloadCallback) { if (!scrivito.editingMode.isEnabled()) { scrivito.storage.remove(reasonStorageKey); if (reloadCallback) { reloadCallback(); } else { reloadUI(); } } }, isEnabled: function isEnabled() { return !scrivito.editingMode.reasonForBeingDisabled; } }, { reasonForBeingDisabled: { get: function get() { return scrivito.storage.get(reasonStorageKey); }, configurable: true, enumerable: true } }); function reloadUI() { 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.editingContext.displayMode); _.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 test purpose only. reset_callbacks: function() { callbacks = {}; }, is_started: function() { return is_started; }, hide_controls: function() { $('#scrivito_ui').addClass('scrivito_hide_ui'); }, show_controls: function() { $('#scrivito_ui').removeClass('scrivito_hide_ui'); } } }); function preload(dom_element) { if (scrivito.editingContext.isEditingMode()) { 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'); }); } } }); }()); 'use strict'; (function () { var STORAGE_KEY = 'devices.active'; var handlers = {}; var Devices = Object.defineProperties({ subscribeChange: function subscribeChange(handler) { var token = _.uniqueId('scrivito.devices.token'); handlers[token] = handler; return token; }, unsubscribeChange: function unsubscribeChange(token) { delete handlers[token]; }, // For test purpose only. reset: function reset() { handlers = {}; scrivito.storage.remove(STORAGE_KEY); } }, { all: { get: function get() { return ['mobile', 'tablet', 'laptop', 'desktop']; }, configurable: true, enumerable: true }, active: { get: function get() { return scrivito.storage.get(STORAGE_KEY) || 'desktop'; }, set: function set(activeDevice) { if (!_.contains(this.all, activeDevice)) { throw new scrivito.InternalError('Unknown device "' + activeDevice + '"'); } scrivito.storage.set(STORAGE_KEY, activeDevice); _.map(handlers, function (handler) { return handler(activeDevice); }); }, configurable: true, enumerable: true } }); scrivito.Devices = Devices; })(); 'use strict'; (function () { var DeviceAdjuster = { init: function init() { var $iframe = $('iframe[name=scrivito_application]'); scrivito.gui.on('document', function () { return adjust($iframe); }); scrivito.Devices.subscribeChange(function () { return readjust($iframe); }); } }; function adjust($iframe) { var device = scrivito.Devices.active; if (device === 'desktop') { $('#scrivito_ui').removeClass('scrivito_iframe_resize_bg'); } else { $('#scrivito_ui').addClass('scrivito_iframe_resize_bg'); } $iframe.attr('class', 'scrivito_iframe_' + device); } function readjust($iframe) { scrivito.transition($iframe, function () { adjust($iframe); $iframe.addClass('scrivito_iframe_animate_resize'); }).then(function () { return $iframe.removeClass('scrivito_iframe_animate_resize'); }); } scrivito.DeviceAdjuster = DeviceAdjuster; })(); 'use strict'; (function () { var _store = {}; scrivito.i18nBackend = { load: function load(locale, translations) { if (this.store()[locale]) { this.store()[locale] = _.extend(this.store()[locale], translations); } else { this.store()[locale] = translations; } }, translate: function translate(locale, key) { if (!locale) { throw new scrivito.ArgumentError('Missing locale'); } if (!key) { throw new scrivito.ArgumentError('Missing key'); } var translation = undefined; try { var translations = this.store()[locale]; translation = lookup(locale, key, translations); for (var _len = arguments.length, params = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { params[_key - 2] = arguments[_key]; } return interpolate(locale, key, translation, params); } catch (e) { if (e instanceof scrivito.TranslationError) { if (this.shouldThrowErrors) { throw e; } scrivito.logError(e.message); if (e instanceof scrivito.InterpolationError) { return translation; } return key; } throw e; } }, // For test purpose only. store: function store() { return _store; }, shouldThrowErrors: false }; function lookup(locale, key, translations) { if (!translations) { throw new scrivito.TranslationError('No translations found for locale "' + locale + '"'); } if (_.isEmpty(translations)) { throw new scrivito.TranslationError('Translations for locale "' + locale + '" are empty'); } var translation = translations[key]; if (!translation) { throw new scrivito.TranslationError('No translation found for key "' + key + '" in locale "' + locale + '"'); } return translation; } function interpolate(locale, key, translation, params) { var placeholders = translation.match(/\$[0-9]+/g); if (placeholders) { var _ret = (function () { if (params.length !== placeholders.length) { throw new scrivito.InterpolationError('Translation for key "' + key + '" in locale "' + locale + '" received invalid number of ' + ('interpolation params: expected - ' + placeholders.length + ', received - ' + params.length)); } var interpolatedTranslation = translation; _.each(params, function (param, i) { var placeholder = placeholders[i]; interpolatedTranslation = interpolatedTranslation.replace(placeholder, param); }); return { v: interpolatedTranslation }; })(); if (typeof _ret === 'object') return _ret.v; } if (params.length) { throw new scrivito.InterpolationError('Translation for key "' + key + '" in locale "' + locale + '" received invalid number of ' + ('interpolation params: expected - 0, received - ' + params.length)); } return translation; } })(); 'use strict'; (function () { var validLocales = ['en', 'de']; var locale = undefined; scrivito.i18n = Object.defineProperties({ load: function load(forLocale, translations) { scrivito.i18nBackend.load(forLocale, translations); }, // In addition to the key you can pass multiple parameters that will be interpolated into // the translated string. translate: function translate(key) { var _scrivito$i18nBackend; for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } return (_scrivito$i18nBackend = scrivito.i18nBackend).translate.apply(_scrivito$i18nBackend, [locale, key].concat(params)); }, // localizeDate localizes an ISO6801 date string according to the current locale. localizeDate: function localizeDate(dateString) { return moment(dateString).format('LLLL'); }, // localizeDateRelative converts an ISO6801 date string to a relative time and localizes it // according to the current locale. localizeDateRelative: function localizeDateRelative(dateString) { return moment(dateString).fromNow(); } }, { locale: { set: function set(newLocale) { locale = _.contains(validLocales, newLocale) ? newLocale : 'en'; moment.locale(locale); }, get: function get() { return locale; }, configurable: true, enumerable: true } }); })(); /* eslint max-len: 0, quote-props: 0 */ 'use strict'; scrivito.i18n.load('de', { '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', 'models.page.name': 'Seite', 'models.resource.name': 'Ressource', 'models.obj.name.plural': 'Objekte', '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.', 'revision.published_by': 'Benutzer mit der ID "$1"', 'workspace.title.published': 'Veröffentlichte Inhalte', 'workspace.title.blank': '[Leerer Titel]', 'workspace_settings_dialog.title': 'Einstellungen von "$1"', 'workspace_settings_dialog.input.title': 'Titel', 'workspace_settings_dialog.input.owners': 'Besitzer', 'workspace_settings_dialog.nothing_found': 'Nichts gefunden', 'workspace_settings_dialog.searching': 'Suche...', 'workspace_settings_dialog.too_short': 'Benutzer suchen...', 'workspace_settings_dialog.cancel': 'Abbrechen', 'workspace_settings_dialog.confirm': 'Bestätigen', 'workspace_publisher.exceeds_obj_limit': 'Diese Arbeitskopie kann nicht veröffentlicht werden, weil die maximale Anzahl der in Ihrem Tarif enthaltenen CMS-Objekte überschritten wurde.', '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', 'loader_error.title': 'Beim Laden der Daten 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.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.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.', 'sidebar.workspace_list.workspace_item.is_disabled': 'Diese Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht ausgewählt werden', 'sidebar.workspaces_panel.general_workspaces_group.title': 'Arbeitskopien', 'sidebar.workspaces_panel.current_workspace_group.title': 'Diese Arbeitskopie', 'sidebar.workspaces_panel.other_workspaces_group.title': 'Andere Arbeitskopien', 'sidebar.workspaces_panel.create_workspace_button.title': 'Neu', 'sidebar.workspaces_panel.create_workspace_button.is_disabled': 'Eine Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht angelegt werden.', 'sidebar.workspaces_panel.publish_history_button.title': 'Verlauf', 'sidebar.workspaces_panel.changes_button.title': 'Änderungen', 'sidebar.workspaces_panel.changes_button.is_forbidden': 'Die Änderungen in dieser Arbeitskopie können aufgrund fehlender Benutzerrechte nicht angezeigt werden.', 'sidebar.workspaces_panel.publish_button.title': 'Veröffentlichen', 'sidebar.workspaces_panel.publish_button.is_forbidden': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht veröffentlicht werden.', 'sidebar.workspaces_panel.rebase_button.title': 'Aktualisieren', 'sidebar.workspaces_panel.rebase_button.is_forbidden': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht aktualisiert werden.', 'sidebar.workspaces_panel.settings_button.title': 'Einstellungen', 'sidebar.workspaces_panel.settings_button.is_forbidden': 'Die Einstellungen der Arbeitskopie können aufgrund fehlender Benutzerrechte nicht bearbeitet werden.', 'sidebar.notifications_panel.publish_restrictions_group.title': 'Veröffentlichung nicht möglich', 'sidebar.notifications_panel.potential_conflicts_group.title': 'Potenzieller Konflikt', 'sidebar.notifications_panel.potential_conflicts_group.description': 'Änderungen an dieser Seite führen beim Veröffentlichen zu einem Konflikt. Die Seite wurde bereits in folgenden Arbeitskopien geändert:', 'sidebar.notifications_panel.conflict_group.title': 'Konflikt', 'sidebar.notifications_panel.conflict_group.description1': 'Eine andere Version dieser Seite wurde zwischenzeitlich veröffentlicht. ', 'sidebar.notifications_panel.conflict_group.link': 'Lösen Sie den Konflikt', 'sidebar.notifications_panel.conflict_group.description2': ', um diese Arbeitskopie veröffentlichen zu können.', 'sidebar.notifications_panel.no_notifications': 'Derzeit keine Benachrichtigungen.', 'sidebar.devices_panel.title': 'Vorschaugrößen', 'sidebar.devices_panel.device.desktop': 'Desktop', 'sidebar.devices_panel.device.laptop': 'Laptop', 'sidebar.devices_panel.device.mobile': 'Mobiltelefon im Hochformat', 'sidebar.devices_panel.device.tablet': 'Tablet im Hochformat', '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.mark_resolved_obj.title': 'Parallele Änderungen an der Ressource überschreiben', 'resource_dialog.commands.restore_obj.title': 'Ressource wiederherstellen', 'resource_dialog.title': 'Eigenschaften der Ressource "$1"', 'menu_bar.create': 'Anlegen', 'menu_bar.move': 'Verschieben', 'menu_bar.copy': 'Kopieren', 'menu_bar.show_controls': 'Bedienleiste einblenden', '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.', '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.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.open_user_guide.title': 'Hilfe öffnen', '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', 'workflows.delete_workspace.dialog.title': 'Wirklich "$1" löschen?', 'workflows.delete_workspace.dialog.description': 'Eine gelöschte Arbeitskopie kann nicht wiederhergestellt werden.', 'workflows.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.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.', 'confirm_delete_dialog.cancel': 'Abbrechen', 'confirm_delete_dialog.confirm': 'Löschen', 'confirm_delete_dialog.confirm.has_backlinks': 'Trotzdem löschen', 'confirm_delete_dialog.is_edited': 'Diese $1 kann bei Bedarf später wiederhergestellt werden, jedoch ohne die Änderungen, die in der aktuellen Arbeitskopie an ihr vorgenommen wurden.', 'confirm_delete_dialog.is_new': 'Sie sind dabei, eine neue $1 dieser Arbeitskopie zu löschen. Dies kann nicht rückgängig gemacht werden. Bei Bedarf können Sie die $1 jedoch erneut erstellen und verlinken.', 'confirm_delete_dialog.many_backlinks': '$1 Objekte verlinken diese $1:', 'confirm_delete_dialog.not_modified': 'Diese $1 kann bei Bedarf später wiederhergestellt werden.', 'confirm_delete_dialog.one_backlink': 'Ein Objekt verlinkt diese $1:', 'confirm_delete_dialog.title': 'Sind Sie sicher, dass Sie diese $1 löschen möchten?', 'commands.delete_obj.has_children': 'Seiten mit Unterseiten können noch nicht gelöscht werden.', 'commands.delete_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden.', 'commands.delete_obj.title': '$1 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.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.forbidden.invalid_workspace': 'Eine Seite kann nur innerhalb ihrer Arbeitskopie verschoben werden.', 'commands.move_obj_from_clipboard.forbidden.invalid_class': '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.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', 'workflows.publish_workspace.dialog.confirm': 'Veröffentlichen', 'workflows.publish_workspace.dialog.title': '"$1" veröffentlichen?', 'workflows.publish_workspace.dialog.description': 'Sie können diese Veröffentlichung mit Hilfe des Veröffentlichungsverlaufs rückgängig machen.', 'workflows.publish_workspace.error_dialog.title': 'Arbeitskopie konnte nicht veröffentlicht werden', 'workflows.publish_workspace.error_dialog.description': 'Bitte entnehmen Sie die Details der Liste der Änderungen.', 'workflows.publish_workspace.error_dialog.confirm': 'Liste der Änderungen', 'workflows.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.', 'test.two_arguments': '$1, $2', 'test.four_arguments': '$1, $2, $3, $4' }); /* eslint max-len: 0, quote-props: 0 */ 'use strict'; scrivito.i18n.load('en', { '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', 'models.page.name': 'page', 'models.resource.name': 'resource', 'models.obj.name.plural': 'objects', '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.', 'revision.published_by': 'User with ID "$1"', 'workspace.title.published': 'Published content', 'workspace.title.blank': '[Empty title]', 'workspace_settings_dialog.title': 'Settings for "$1"', 'workspace_settings_dialog.input.title': 'Title', 'workspace_settings_dialog.input.owners': 'Owners', 'workspace_settings_dialog.nothing_found': 'Nothing found', 'workspace_settings_dialog.searching': 'Searching...', 'workspace_settings_dialog.too_short': 'Find user...', 'workspace_settings_dialog.cancel': 'Cancel', 'workspace_settings_dialog.confirm': 'Confirm', 'workspace_publisher.exceeds_obj_limit': 'This working copy cannot be published because the maximum number of CMS objects included in your plan has been exceeded.', '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', 'loader_error.title': 'An error occurred while retrieving the data. Please try again later. If the problem persists, contact a technician familiar with this website.', '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.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.', 'sidebar.workspace_list.workspace_item.is_disabled': 'This working copy can not be selected due to missing user permissions.', 'sidebar.workspaces_panel.general_workspaces_group.title': 'Working copies', 'sidebar.workspaces_panel.current_workspace_group.title': 'This working copy', 'sidebar.workspaces_panel.other_workspaces_group.title': 'Other working copies', 'sidebar.workspaces_panel.create_workspace_button.title': 'New', 'sidebar.workspaces_panel.create_workspace_button.is_disabled': 'You cannot create a workspace due to missing user permissions.', 'sidebar.workspaces_panel.publish_history_button.title': 'History', 'sidebar.workspaces_panel.changes_button.title': 'Changes', 'sidebar.workspaces_panel.changes_button.is_forbidden': 'The cannot see the changes to the working copy due to missing user permissions.', 'sidebar.workspaces_panel.publish_button.title': 'Publish', 'sidebar.workspaces_panel.publish_button.is_forbidden': 'The working copy can not be published due to missing user permissions.', 'sidebar.workspaces_panel.settings_button.title': 'Settings', 'sidebar.workspaces_panel.settings_button.is_forbidden': 'You cannot change the settings of the workspace due to missing user permissions.', 'sidebar.workspaces_panel.rebase_button.title': 'Update', 'sidebar.workspaces_panel.rebase_button.is_forbidden': 'You cannot update the working copy to missing user permissions.', 'sidebar.notifications_panel.publish_restrictions_group.title': 'Publishing not possible', 'sidebar.notifications_panel.potential_conflicts_group.title': 'Potential conflict', 'sidebar.notifications_panel.potential_conflicts_group.description': 'Changes to this page will cause a conflict when publishing. The page has already been modified in these working copies:', 'sidebar.notifications_panel.conflict_group.title': 'Conflict', 'sidebar.notifications_panel.conflict_group.description1': 'A different version of this page has been published in the meantime. ', 'sidebar.notifications_panel.conflict_group.link': 'Resolve the conflict', 'sidebar.notifications_panel.conflict_group.description2': ' to be able to publish this working copy.', 'sidebar.notifications_panel.no_notifications': 'No notifications at present.', 'sidebar.devices_panel.title': 'Preview sizes', 'sidebar.devices_panel.device.desktop': 'Desktop', 'sidebar.devices_panel.device.laptop': 'Laptop', 'sidebar.devices_panel.device.mobile': 'Mobile phone, portrait', 'sidebar.devices_panel.device.tablet': 'Tablet, portrait', 'confirm_delete_dialog.cancel': 'Cancel', 'confirm_delete_dialog.confirm': 'Delete', 'confirm_delete_dialog.confirm.has_backlinks': 'Delete anyway', 'confirm_delete_dialog.is_edited': 'This $1 can be restored if required. However, the changes made to it in this working copy cannot be recovered.', 'confirm_delete_dialog.is_new': 'You are in the process of deleting a $1 that has been created in this working copy. This cannot be undone. However, you can create the $2 once again and reapply the links and references pointing to it.', 'confirm_delete_dialog.many_backlinks': '$1 objects link to this $2:', 'confirm_delete_dialog.not_modified': 'This $1 can be restored if required.', 'confirm_delete_dialog.one_backlink': 'One object links to this $1:', 'confirm_delete_dialog.title': 'Are you sure you want to delete this $1?', '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.mark_resolved_obj.title': 'Override concurrent changes to resource', 'resource_dialog.commands.restore_obj.title': 'Restore resource', 'resource_dialog.title': 'Properties of resource "$1"', 'menu_bar.create': 'Create', 'menu_bar.move': 'Move', 'menu_bar.copy': 'Copy', 'menu_bar.show_controls': 'Show control panel', '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.', '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.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.open_user_guide.title': 'Open help', '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', 'workflows.delete_workspace.dialog.title': 'Are you sure you want to delete "$1"?', 'workflows.delete_workspace.dialog.description': 'A deleted working copy cannot be restored.', 'workflows.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.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.has_children': 'Pages with subpages can not yet be deleted.', 'commands.delete_obj.published_workspace': 'Since this is the published content, nothing can be modified.', 'commands.delete_obj.title': 'Delete $1', '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': 'Are you sure you want to discard the 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': 'Are you sure you want to discard the 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': 'Are you sure you want to discard the 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': 'Are you sure you want to override the 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.forbidden.invalid_workspace': 'A page can only be moved within its working copy.', 'commands.move_obj_from_clipboard.forbidden.invalid_class': '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.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': 'Are you sure you want to 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', 'workflows.publish_workspace.dialog.confirm': 'Publish', 'workflows.publish_workspace.dialog.title': 'Publish "$1"?', 'workflows.publish_workspace.dialog.description': 'You can undo this publishing action using the publishing history.', 'workflows.publish_workspace.error_dialog.title': 'Working copy could not be published', 'workflows.publish_workspace.error_dialog.description': 'Please check the changes list for details.', 'workflows.publish_workspace.error_dialog.confirm': 'Open changes list', 'workflows.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' }); (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.createCommand(_.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.updateParams(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.createCommand(_.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 test purpose 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) { var workspaceId = scrivito.editingContext.selectedWorkspace.id(); var serializedAttributes = obj.serializeAttributes(); scrivito.storage.set(STORAGE_KEY, { workspaceId: workspaceId, serializedAttributes: serializedAttributes }); }, isPresent: function isPresent() { return scrivito.storage.hasKey(STORAGE_KEY); }, clear: function clear() { scrivito.storage.remove(STORAGE_KEY); } }, { serializedAttributes: { get: function get() { return this._clipboard.serializedAttributes; }, configurable: true, enumerable: true }, workspaceId: { get: function get() { return this._clipboard.workspaceId; }, configurable: true, enumerable: true }, _clipboard: { 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 test purpose only. scrivito.setResolvedUrl = function (url, resolution) { resolvedUrlCache[url] = resolution; }; // For test purpose only. scrivito.clearResolvedUrlCache = function () { resolvedUrlCache = {}; requestCache = {}; }; // For test purpose only. scrivito.resolvedUrlRequestCacheIsEmpty = function () { return _.isEmpty(requestCache); }; function classifyUrls(unresolvedUrls) { var inFlight = []; var missingUrls = []; _.each(unresolvedUrls, function (unresolvedUrl) { var requestDeferred = requestCache[unresolvedUrl]; if (requestDeferred) { inFlight.push(requestDeferred.promise); } else { missingUrls.push(unresolvedUrl); } }); return [inFlight, missingUrls]; } function preloadChunk(chunk) { _.each(chunk, function (unresolvedUrl) { requestCache[unresolvedUrl] = new scrivito.Deferred(); }); return preloadFromSdk(chunk).then(function (unresolvedUrls) { return preloadFromBackend(unresolvedUrls); }).then(function () { _.each(chunk, function (unresolvedUrl) { requestCache[unresolvedUrl].resolve(null); delete requestCache[unresolvedUrl]; }); return null; })['catch'](function (reason) { _.each(chunk, function (unresolvedUrl) { requestCache[unresolvedUrl].reject(reason); delete requestCache[unresolvedUrl]; }); throw reason; }); } function preloadFromSdk(unresolvedUrls) { var ajaxRequest = scrivito.ajax('PUT', 'resolve_paths', { data: { paths: unresolvedUrls } }); var promise = scrivito.Promise.resolve(ajaxRequest); return promise.then(function (resolvedUrls) { var stillUnresolvedUrls = []; unresolvedUrls.forEach(function (unresolvedUrl, index) { var resolvedUrl = resolvedUrls[index]; if (resolvedUrl === null) { stillUnresolvedUrls.push(unresolvedUrl); } else { resolvedUrlCache[unresolvedUrl] = resolvedUrl; } }); return stillUnresolvedUrls; }); } function preloadFromBackend(unresolvedUrls) { if (!unresolvedUrls.length) { return; } var promise = scrivito.CmsRestApi.get('blobs/resolve_urls', { urls: unresolvedUrls }); return promise.then(function (_ref) { var resolvedUrls = _ref.results; unresolvedUrls.forEach(function (unresolvedUrl, index) { resolvedUrlCache[unresolvedUrl] = resolvedUrls[index]; }); }); } })(); "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.ajaxWithErrorDialog('GET', 'suggest_completion?' + param) .then(function(suggestions) { cache[attribute] = suggestions; return suggestions; }); } }; }()); (function() { Handlebars.registerHelper('translate', function() { return scrivito.i18n.translate(arguments[0]); }); Handlebars.registerHelper('localizeDate', function(date_value_function) { return scrivito.i18n.localizeDate(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.editingContext.selectedWorkspace.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.legacy_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; }); }); }); } }); })(); (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 () { 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 test 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 }); } })(); (function () { function createReactClass(params) { var shouldRenderLoader = params.shouldRenderLoader; var render = params.render; var componentDidMount = params.componentDidMount; var componentWillUnmount = params.componentWillUnmount; var unsubscribeModelState = undefined; return React.createClass(_.extend(params, { componentDidMount: function () { var _this = this; unsubscribeModelState = scrivito.modelState.subscribe(function () { scrivito.nextTick(function () { if (_this.isMounted()) { _this.forceUpdate(); } }); }); if (componentDidMount) { componentDidMount.apply(this); } }, componentWillUnmount: function () { unsubscribeModelState(); if (componentWillUnmount) { componentWillUnmount.apply(this); } }, render: function () { var _this2 = this; var handleError = function (error) { scrivito.nextTick(function () { throw error; }); return shouldRenderLoader ? React.createElement(scrivito.LoaderError, null) : null; }; try { return scrivito.LoadableData.withEventualConsistency(function () { return render.apply(_this2); }); } catch (error) { if (error instanceof scrivito.NotLoadedError) { try { error.load(); } catch (error) { return handleError(error); } if (this.renderWhileLoading) { return this.renderWhileLoading(); } return shouldRenderLoader ? React.createElement(scrivito.Loader, null) : null; } return handleError(error); } } })); } scrivito.createReactClass = createReactClass; })(); "use strict"; (function () { var shouldTrackComponents = false; var trackedNodes = []; function renderReactComponent(reactComponent, $mountNode) { var mountNode = $mountNode.get(0); if (shouldTrackComponents) { trackedNodes.push(mountNode); } return ReactDOM.render(reactComponent, mountNode); } function trackRenderedComponents() { shouldTrackComponents = true; } function unmountAllComponents() { trackedNodes.forEach(ReactDOM.unmountComponentAtNode); trackedNodes = []; } scrivito.renderReactComponent = renderReactComponent; scrivito.trackRenderedComponents = trackRenderedComponents; scrivito.unmountAllComponents = unmountAllComponents; })(); "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) { resolve(_this2._preprocessor(value)); }); } }]); return BufferedWriter; })(); })(); '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) { 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(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(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); } 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(valueInA, valueInB, function () { if (!_.isEqual(valueInA, valueInB)) { return valueInB; } }); if (patchValue !== undefined) { patch[attribute] = patchValue; } } }); return patch; } }; })(); "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; }); } }; }, // For test purpose only. requestAnimationFrame: function requestAnimationFrame(fn) { window.requestAnimationFrame(fn); } }); })(); '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 _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.AttributeSerializer = { serialize: function serialize(attributes) { var serializedAttributes = {}; _.each(attributes, function (_ref, name) { var _ref2 = _slicedToArray(_ref, 2); var value = _ref2[0]; var attrInfo = _ref2[1]; var serializedName = convertCamelCasedAttributeName(name); if (scrivito.Attribute.isSystemAttribute(serializedName)) { serializedAttributes[serializedName] = value; } else { var _attrInfo = _slicedToArray(attrInfo, 2); var attrType = _attrInfo[0]; var attrOptions = _attrInfo[1]; serializedAttributes[serializedName] = [serializeAttributeType(attrType, name), valueOrNull(serializeAttributeValue(attrType, attrOptions, value, name))]; } }); return serializedAttributes; } }; function convertCamelCasedAttributeName(name) { if (!scrivito.attributeInflection.isCamelCase(name)) { throw new scrivito.ArgumentError('Attribute names have to be in camel case.'); } return scrivito.attributeInflection.underscore(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.ArgumentError('Attribute "' + name + '" is of unsupported type "' + type + '".'); } } function serializeAttributeValue(type, options, value, name) { if (value === null) { return value; } switch (type) { case 'binary': return serializeBinaryAttributeValue(value, name); case 'date': return serializeDateAttributeValue(value, name); case 'enum': return serializeEnumAttributeValue(options, value, name); case 'float': return serializeFloatAttributeValue(value, name); case 'html': return serializeHtmlAttributeValue(value, name); case 'integer': return serializeIntegerAttributeValue(value, name); case 'link': return serializeLinkAttributeValue(value, name); case 'linklist': return serializeLinklistAttributeValue(value, name); case 'multienum': return serializeMultienumAttributeValue(options, value, name); case 'reference': return serializeReferenceAttributeValue(value, name); case 'referencelist': return serializeReferencelistAttributeValue(value, name); case 'string': return serializeStringAttributeValue(value, name); case 'stringlist': return serializeStringlistAttributeValue(value, name); case 'widgetlist': return serializeWidgetlistAttributeValue(value, name); default: throw new scrivito.InternalError('serializeAttributeValue is not implemented for "' + type + '".'); } } function valueOrNull(value) { if ((_.isString(value) || _.isArray(value)) && _.isEmpty(value)) { return null; } return value; } function throwInvalidAttributeValue(value, name, expected) { throw new scrivito.ArgumentError('Unexpected value ' + scrivito.prettyPrint(value) + ' for' + (' attribute "' + name + '". Expected: ' + expected)); } function serializeBinaryAttributeValue(value, name) { if (value instanceof scrivito.Binary) { return { id: value.id }; } throwInvalidAttributeValue(value, name, 'A Binary.'); } function serializeDateAttributeValue(value, name) { if (_.isDate(value)) { return scrivito.types.formatDateToString(value); } if (scrivito.types.isValidDateString(value)) { return value; } throwInvalidAttributeValue(value, name, 'A Date.'); } function serializeEnumAttributeValue(_ref3, value, name) { var validValues = _ref3.validValues; if (_.contains(validValues, value)) { return value; } var e = 'Valid attribute values are contained in its "validValues" array [' + validValues + '].'; throwInvalidAttributeValue(value, name, e); } function serializeFloatAttributeValue(value, name) { if (scrivito.types.isValidFloat(value)) { return value; } var invalidValue = value; if (_.isNumber(value)) { invalidValue = String(value); } throwInvalidAttributeValue(invalidValue, name, 'A Number, that is #isFinite().'); } function serializeHtmlAttributeValue(value, name) { if (_.isString(value)) { return value; } throwInvalidAttributeValue(value, name, 'A String.'); } function serializeIntegerAttributeValue(value, name) { if (scrivito.types.isValidInteger(value)) { return value; } throwInvalidAttributeValue(value, name, 'A Number, that is #isSafeInteger().'); } function serializeLinkAttributeValue(value, name) { if (validLinkObject(value)) { return convertLinkToCmsApi(value); } throwInvalidAttributeValue(value, name, 'A Link instance.'); } function serializeLinklistAttributeValue(value, name) { if (_.isArray(value) && _.every(value, validLinkObject)) { return _.map(value, convertLinkToCmsApi); } throwInvalidAttributeValue(value, name, 'An array of Link instances.'); } function validLinkObject(value) { if (value instanceof scrivito.BasicLink) { 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(_ref4, value, name) { var validValues = _ref4.validValues; var errorMessage = 'An array with values from ' + scrivito.prettyPrint(validValues) + '.'; if (!_.isArray(value) || !_.every(value, _.isString)) { throwInvalidAttributeValue(value, name, errorMessage); } var forbiddenValues = _.difference(value, validValues); if (forbiddenValues.length) { var e = errorMessage + ' Forbidden values: ' + scrivito.prettyPrint(forbiddenValues) + '.'; throwInvalidAttributeValue(value, name, e); } return value; } function serializeReferenceAttributeValue(value, name) { if (isValidReference(value)) { return serializeSingleReferenceValue(value); } throwInvalidAttributeValue(value, name, 'A BasicObj or a String ID.'); } function serializeReferencelistAttributeValue(value, name) { if (isValidReferencelistValue(value)) { return _.map(value, serializeSingleReferenceValue); } throwInvalidAttributeValue(value, name, 'An array with BasicObjs or String IDs.'); } 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 serializeStringAttributeValue(value, name) { if (isValidString(value)) { return value.toString(); } throwInvalidAttributeValue(value, name, 'A String.'); } function serializeStringlistAttributeValue(value, name) { if (_.isArray(value) && _.every(value, function (v) { return isValidString(v); })) { return _.invoke(value, 'toString'); } throwInvalidAttributeValue(value, name, 'An array of strings.'); } function isValidString(value) { return _.isString(value) || _.isNumber(value); } function serializeWidgetlistAttributeValue(value, name) { if (_.isArray(value) && _.every(value, function (v) { return v instanceof scrivito.BasicWidget; })) { return _.pluck(value, 'id'); } throwInvalidAttributeValue(value, name, 'An array of scrivito.BasicWidget instances.'); } })(); "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); } })(); '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 allowedCreateObjAttributes = ['_obj_class', '_path', 'blob']; scrivito.withDefaults = { createObjFromLegacyAttributes: function createObjFromLegacyAttributes(attributes) { var objClassName = attributes._obj_class; var objClass = scrivito.ObjClass.find(objClassName); var objId = scrivito.BasicObj.generateId(); var _separateAttributesForDefault = separateAttributesForDefault(attributes); var _separateAttributesForDefault2 = _slicedToArray(_separateAttributesForDefault, 2); var attributesForDefault = _separateAttributesForDefault2[0]; var binaryValues = _separateAttributesForDefault2[1]; var fetchDefaultPromise = fetchDefaults(objClass, attributesForDefault); var uploadBinariesPromise = uploadBinaryValues(objId, binaryValues); return scrivito.Promise.all([fetchDefaultPromise, uploadBinariesPromise]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var serializedDefaultAttributes = _ref2[0]; var uploadedBinaryAttributes = _ref2[1]; return scrivito.BasicObj.createWithSerializedAttributes(_.extend(serializedDefaultAttributes, uploadedBinaryAttributes, { _id: objId })); }).then(function (createdObj) { return createdObj.finishSaving().then(function () { return createdObj; }); }); }, createObj: function createObj(attributes) { var _ref3; var unexpectedAttrs = (_ref3 = _).without.apply(_ref3, [_.keys(attributes)].concat(allowedCreateObjAttributes)); if (!_.isEmpty(unexpectedAttrs)) { throw new scrivito.InternalError('Unexpected attributes ' + scrivito.prettyPrint(unexpectedAttrs) + '.' + (' Available attributes: ' + scrivito.prettyPrint(allowedCreateObjAttributes))); } return scrivito.withDefaults.createObjFromLegacyAttributes(attributes); }, newWidget: function newWidget(className) { var widgetClass = scrivito.WidgetClass.find(className); return widgetClass.fetchDefaults().then(function (widgetDefaults) { return scrivito.BasicWidget.newWithSerializedAttributes(widgetDefaults); }); } }; function fetchDefaults(objClass, attributes) { return objClass.fetchDefaults(serializeAttributesForApplication(attributes)); } function separateAttributesForDefault(attributes) { var attributesForDefault = {}; var ignoredAttributes = {}; _.each(attributes, function (value, name) { if (isBinary(value)) { ignoredAttributes[name] = value; } else { attributesForDefault[name] = value; } }); return [attributesForDefault, ignoredAttributes]; } function serializeAttributesForApplication(attributes) { return _.mapObject(attributes, function (value) { if (_.isDate(value)) { return moment.utc(value).toISOString(); } return value; }); } function isBinary(value) { return scrivito.BinaryUtils.isFile(value) || value instanceof scrivito.FutureBinary || value instanceof scrivito.UploadedBlob; } function uploadBinaryValues(objId, binaryValues) { var promises = _.map(binaryValues, function (value, name) { if (scrivito.BinaryUtils.isFile(value)) { return serializeFile(objId, name, value); } if (value instanceof scrivito.UploadedBlob) { return serializeUploadedBlob(objId, name, value); } if (value instanceof scrivito.FutureBinary) { return serializeFutureBinary(objId, name, value); } }); return scrivito.Promise.all(promises).then(_.object); } 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, ['binary', { id: binary.id }]]; }); } })(); '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 MAX_CHECK_DURATION = 20000; scrivito.WorkspacePublisher = (function () { function WorkspacePublisher(workspace) { _classCallCheck(this, WorkspacePublisher); this._workspace = workspace; } // For test purpose only. _createClass(WorkspacePublisher, [{ key: 'check', // For test purpose only. value: function check() { var _this = this; return this._check(0).then(function (result) { return _this._handleCheckResult(result, []); }); } // For test purpose only. }, { key: 'publishApproval', value: function publishApproval(certificates) { return scrivito.ajax('PUT', 'workspaces/' + this._workspace.id + '/publish_approval', { data: { certificates: certificates } }); } }, { key: 'checkAndPublish', value: function checkAndPublish() { return this._checkAndPublish(Date.now() + MAX_CHECK_DURATION); } }, { key: '_checkAndPublish', value: function _checkAndPublish(retryUntil) { var _this2 = this; return scrivito.Promise.resolve(this.check()).then(function (certificates) { if (certificates) { return _this2.publishApproval(certificates); } return scrivito.Promise.reject({ type: 'check_failed' }); }).then(function (approval) { return scrivito.CmsRestApi.put('workspaces/' + _this2._workspace.id + '/publish', approval); })['catch'](function (error) { return _this2._handleCheckAndPublishError(error, retryUntil); }); } }, { key: '_check', value: function _check(offset) { return scrivito.ajax('GET', 'workspaces/' + this._workspace.id + '/check?from=' + offset); } }, { key: '_handleCheckResult', value: function _handleCheckResult(result, certificates) { var _this3 = this; if (result.result === 'fail') { return $.Deferred().resolve(false); } certificates.push(result.certificate); if (result.pass.until === 'END') { return $.Deferred().resolve(certificates); } var offset = parseInt(result.pass.until, 10) + 1; return this._check(offset).then(function (result) { return _this3._handleCheckResult(result, certificates); }); } }, { key: '_handleOutdatedError', value: function _handleOutdatedError(error) { if (this._workspace.isAutoUpdate()) { return this.checkAndPublish(); } scrivito.logError(error.message); scrivito.alertDialog(error.message); return scrivito.Promise.reject(error); } }, { key: '_handleCheckAndPublishError', value: function _handleCheckAndPublishError(error, retryUntil) { var _this4 = this; var backendCode = error.backend_code; var contentStateError = 'precondition_not_verifiable.workspace.publish.content_state_id'; if (error.type === 'check_failed') { return scrivito.Promise.reject(error); } if (backendCode === contentStateError) { return this._handleOutdatedError(error); } if (backendCode === 'precondition_not_met.workspace.publish.content_state_id') { // The workspace has been changed since last check. if (Date.now() > retryUntil) { // retried checkAndPublish for too long. return $.Deferred().reject({ type: 'outdated_certificates' }); } // retry again return scrivito.wait(1).then(function () { return _this4._checkAndPublish(retryUntil); }); } else if (backendCode === 'precondition_not_met.workspace.publish.exceeds_obj_limit') { scrivito.logError(error.message); scrivito.errorDialog(scrivito.t('workspace_publisher.exceeds_obj_limit'), [error.timestamp, error.message]); return scrivito.Promise.reject(error); } scrivito.displayAjaxError(error); return scrivito.Promise.reject(error); } }, { key: 'workspace', get: function get() { return this._workspace; } }]); return WorkspacePublisher; })(); })(); 'use strict'; (function () { var batchRetrieval = new scrivito.BatchRetrieval(function (ids) { return scrivito.ajax('PUT', 'users/mget', { data: { ids: ids } }); }); scrivito.UserRetrieval = { retrieveUser: function retrieveUser(id) { return batchRetrieval.retrieve(id).then(function (value) { if (value) { return value; } throw new scrivito.ResourceNotFoundError('User with id "' + id + '" not found'); }); }, // For test purpose only. reset: function reset() { batchRetrieval.reset(); } }; })(); 'use strict'; (function () { var batchRetrieval = new scrivito.BatchRetrieval(function (ids) { return scrivito.ajax('PUT', 'ui_configs/mget', { data: { ids: ids } }); }); scrivito.UiConfigRetrieval = { retrieve: function retrieve(id) { return batchRetrieval.retrieve(id).then(function (value) { return value || {}; }); }, // For test pusepose only reset: function reset() { batchRetrieval.reset(); } }; })(); (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.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) { var path = 'obj_class/' + this.name + '/defaults'; if (attributes) { path += '?' + $.param({ attributes: attributes }); } return scrivito.Promise.resolve(scrivito.ajax('GET', path)); } }]); 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); })(); 'use strict'; (function () { scrivito.childListElement = { create_instance: function create_instance(cmsElement) { if (cmsElement.dom_element().attr('data-scrivito-private-child-list-path')) { var _ret = (function () { var that = cmsElement; _.extend(that, { path: function path() { return that.dom_element().attr('data-scrivito-private-child-list-path'); }, obj: function obj() { return scrivito.legacy_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') }); }, fetchPageClassSelection: function fetchPageClassSelection() { return scrivito.legacy_obj.fetch_page_class_selection({ parent_path: that.path() }); }, allowedClasses: function allowedClasses() { return JSON.parse(that.dom_element().attr('data-scrivito-private-child-list-allowed-classes')); }, children: function children() { return _.map(that.dom_element().find('>[data-scrivito-private-obj-id]'), function (domElement) { return scrivito.cms_element.from_dom_element($(domElement)); }); }, hasChildOrder: function hasChildOrder() { return !!that.dom_element().attr('data-scrivito-private-child-list-order-obj-id'); }, fetchObj: function fetchObj() { return scrivito.BasicObj.fetch(that.obj().id()); }, saveOrder: function saveOrder() { if (that.hasChildOrder()) { var _ret2 = (function () { var newChildOrder = _.map(that.children(), function (child) { return child.obj().id(); }); return { v: that.fetchObj().then(function (obj) { obj.update({ childOrder: [newChildOrder, ['referencelist']] }); return obj.finishSaving(); })['catch'](function (error) { scrivito.handleAjaxError(error); throw error; }) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } $.error("Can't save order, when child order is not allowed!"); }, isValidChildClass: function isValidChildClass(objClass) { var allowedClasses = that.allowedClasses(); if (allowedClasses) { return _.contains(allowedClasses, objClass); } return true; } }); return { v: that }; })(); if (typeof _ret === 'object') return _ret.v; } }, all: function all(rootElement) { return scrivito.cms_element.all('[data-scrivito-private-child-list-path]', rootElement); } }; scrivito.cms_element.definitions.push(scrivito.childListElement); })(); (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 === Node.DOCUMENT_NODE) { 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 === Node.DOCUMENT_NODE) { return create_instance(cms_element); } }, // For test purpose 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.editingContext.isEditingMode()) { _.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.legacy_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', 'float', 'html', 'integer', 'link', 'linklist', 'multienum', 'reference', 'referencelist', 'string', 'stringlist' ], field_type); }; _.extend(scrivito, { cms_field_element: { create_instance: function(cms_element) { var that = cms_element; var basic_obj; _.extend(that, { field_name: function() { return that.dom_element().attr('data-scrivito-field-name'); }, attr_name: function() { return scrivito.attributeInflection.camelCase(that.field_name()); }, field_type: function() { return that.dom_element().attr('data-scrivito-field-type'); }, type_info: function() { if (scrivito.Attribute.isSystemAttribute(that.field_name())) { return; } var type = that.field_type(); if (type === 'enum' || type === 'multienum') { return [type, { validValues: that.valid_values() }]; } else { return [type]; } }, obj: function() { return scrivito.legacy_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.legacy_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"); } } var saving_promise = that.preprocess(content).then(function(value) { var changes = {}; changes[that.attr_name()] = [value, that.type_info()]; that.container().update(changes); return that.container().finishSaving().catch(function() { throw new Error(scrivito.t('ajax_error.communication')); }); }); return scrivito.promise.wrapInJqueryDeferred(saving_promise); }, 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 purpose 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.editingContext.selectedWorkspace.id()) { $.error('Tried to edit cms data from wrong workspace!'); } }; 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 purpose 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); }()); '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, false); }); } }]); 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; } } })(); (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); }()); (function() { var write_promises = {}; _.extend(scrivito, { legacy_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; }, 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); }, 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.ajaxWithErrorDialog.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.ajaxWithErrorDialog('GET', path).then(function(selection) { var names = _.pluck(selection, 'name'); var recent; if (names.length >= 15) { recent = scrivito.obj_class_selection.recent(names); } var popular = _.take(_.intersection(scrivito.popular_obj_classes, names), 5); return { all: selection, 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.legacy_obj.fetch_class_selection('objs/page_class_selection', params); }, 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, { legacy_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(); }, 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.ajaxWithErrorDialog( '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 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; } } }); }()); (function() { _.extend(scrivito, { legacy_workspace: { fromWorkspace: function(workspace) { return scrivito.legacy_workspace.from_data({ id: workspace.id, title: workspace.titleForEditor, auto_update: workspace.isAutoUpdate(), }); }, 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.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.newWithAttributes(membership.user_id, { description: membership.description }); }); }, is_accessible: function() { return data.id === 'published' || data.is_accessible; }, other_editable: function() { return scrivito.legacy_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.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.displayAjaxError(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.legacy_workspace.from_data(data); }) .sortBy(function(workspace) { return workspace.sort_value(); }) .value(); }, all: function() { return scrivito.ajaxWithErrorDialog('GET', 'workspaces').then(function(workspace_datas) { return scrivito.legacy_workspace.from_data_collection(workspace_datas); }); }, editable: function() { return scrivito.legacy_workspace.all().then(function(workspaces) { return _.select(workspaces, function(workspace) { return workspace.is_editable(); }); }); }, published: function() { return scrivito.legacy_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) { params.workspace.memberships = {}; params.workspace.memberships[userId] = {role: 'owner'}; } var promise = scrivito.CmsRestApi.post('workspaces', params).then(function(ws_data) { return scrivito.legacy_workspace.from_data(ws_data); }, function(error) { if (error.code === 'precondition_not_met.workspace.create.exceeds_limit') { scrivito.workspace_limit_exceeded(); } else { scrivito.handleAjaxError(error); } return scrivito.Promise.reject(); }); return scrivito.promise.wrapInJqueryDeferred(promise); } } }); }()); (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.legacy_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 test purpose 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.ajaxWithErrorDialog('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.ajaxWithErrorDialog('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) { if (value === null) { return value; } if (_.isDate(value)) { return moment.utc(value).toISOString(); } return String(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 PublishAbility = (function () { _createClass(PublishAbility, null, [{ key: 'get', value: function get(id) { var publishAbility = new PublishAbility(id); publishAbility.ensureAvailable(); return publishAbility; } }]); function PublishAbility(id) { _classCallCheck(this, PublishAbility); var state = scrivito.modelState.subState('publishAbility').subState(id); var loader = function loader() { return scrivito.ajax('GET', 'users/publish_ability?obj_id=' + id); }; var invalidation = function invalidation() { return scrivito.BasicObj.getIncludingDeleted(id).version; }; this._loadableData = new scrivito.LoadableData({ state: state, loader: loader, invalidation: invalidation }); } _createClass(PublishAbility, [{ key: 'ensureAvailable', value: function ensureAvailable() { this._loadableData.get(); } }, { key: 'restrictionMessages', get: function get() { return this._loadableData.get().restriction_messages; } }]); return PublishAbility; })(); scrivito.PublishAbility = PublishAbility; })(); '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 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: 'publishedBy', get: function get() { var userId = this._attributes.published_by; if (userId) { try { return scrivito.User.get(userId).description; } catch (error) { if (error instanceof scrivito.ResourceNotFoundError) { return scrivito.t('revision.published_by', userId); } throw error; } } return null; } }, { 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() { var _this = this; var loadableData = new scrivito.LoadableData({ state: cacheStore(), loader: function loader() { return scrivito.CmsRestApi.get('workspaces/published/revisions'); } }); var revisions = _.map(loadableData.get().results, function (attributes) { return new _this(attributes); }); if (loadableData.get().isLimited) { revisions.isLimited = true; } return revisions; } // For test purpose only. }, { key: 'clearCache', value: function clearCache() { cacheStore().set(null); } }]); return Revision; })(); function cacheStore() { return scrivito.modelState.subState('revision'); } })(); (function() { var field_types = [ 'enum', 'float', 'integer', '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 () { var UiConfig = (function () { _createClass(UiConfig, null, [{ key: 'get', value: function get(id) { var uiConfig = new UiConfig(id); uiConfig.ensureAvailable(); return uiConfig; } }]); function UiConfig(id, attributes) { _classCallCheck(this, UiConfig); var state = scrivito.modelState.subState('uiConfig').subState(id); var loader = function loader() { return scrivito.UiConfigRetrieval.retrieve(id); }; var invalidation = function invalidation() { return scrivito.BasicObj.getIncludingDeleted(id).version; }; this._loadableData = new scrivito.LoadableData({ state: state, loader: loader, invalidation: invalidation }); if (attributes) { this._loadableData.set(attributes); } } _createClass(UiConfig, [{ key: 'get', value: function get(configKey) { return this._loadableData.get()[configKey]; } }, { key: 'ensureAvailable', value: function ensureAvailable() { this._loadableData.get(); } }]); return UiConfig; })(); scrivito.UiConfig = UiConfig; })(); '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.ajaxWithErrorDialog('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; })(); })(); '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 VERBS = ['create', 'delete', 'invite_to', 'publish', 'read', 'write']; var current = undefined; var User = (function () { _createClass(User, null, [{ key: 'init', value: function init(_ref) { var attributes = _ref.current; var id = attributes.id; if (id) { current = User.newWithAttributes(id, attributes); } else { // If the id is missing, then it is the default system user. current = this.systemUser; } } }, { key: 'get', value: function get(id) { if (!id) { throw new scrivito.ArgumentError('Missing user id'); } var user = new User(id); user.ensureAvailable(); return user; } }, { key: 'suggest', value: function suggest(input) { return scrivito.ajaxWithErrorDialog('GET', 'users/suggest?input=' + input).then(function (suggestions) { return _.map(suggestions, function (attributes) { return User.newWithAttributes(attributes.id, attributes); }); }); } }, { key: 'newWithAttributes', value: function newWithAttributes(id, attributes) { var user = new User(id); user.assignAttributes(attributes); return user; } }, { key: 'storeWithAttributes', value: function storeWithAttributes(id, attributes) { var user = new User(id); user.assignAttributes(attributes); } }, { key: 'current', get: function get() { return current; } }, { key: 'systemUser', get: function get() { return new User(); } }]); function User(id) { var _this = this; _classCallCheck(this, User); this._id = id; if (id) { this._loadableData = new scrivito.LoadableData({ state: scrivito.modelState.subState('user').subState(id), loader: function loader() { return scrivito.UserRetrieval.retrieveUser(_this._id); } }); } } _createClass(User, [{ key: 'can', value: function can(verb, workspace) { if (!_.contains(VERBS, verb)) { throw new scrivito.InternalError('Unknown verb \'' + verb + '\''); } if (workspace && workspace.isPublished()) { return verb === 'read'; } if (this._canAlways(verb)) { return true; } if (this._canNever(verb)) { return false; } if (verb === 'create') { return true; } if (!workspace) { throw new scrivito.InternalError('Missing workspace'); } return workspace.isOwnedBy(this); } }, { key: 'restrictionMessagesFor', value: function restrictionMessagesFor(obj) { return this._publishAbilityFor(obj.id).restrictionMessages; } }, { key: 'assignAttributes', value: function assignAttributes(attributes) { this._loadableData.set(attributes); } }, { key: 'ensureAvailable', value: function ensureAvailable() { this._loadableData.get(); } }, { key: '_get', value: function _get(attribute) { if (this._id) { return this._loadableData.get()[attribute]; } return null; } }, { key: '_canAlways', value: function _canAlways(verb) { return this._isSystemUser() || this._hasExplicitRule('always', verb); } }, { key: '_canNever', value: function _canNever(verb) { return this._hasExplicitRule('never', verb); } }, { key: '_hasExplicitRule', value: function _hasExplicitRule(adverb, verb) { return _.contains(this._explicitRules, adverb + '-' + verb); } }, { key: '_isSystemUser', value: function _isSystemUser() { return !this._id; } }, { key: '_publishAbilityFor', value: function _publishAbilityFor(objId) { return scrivito.PublishAbility.get(objId); } }, { key: 'id', get: function get() { return this._id || null; } }, { key: 'description', get: function get() { return this._get('description'); } }, { key: '_explicitRules', get: function get() { return this._get('explicit_rules'); } }]); return User; })(); scrivito.User = User; scrivito.User.VERBS = VERBS; })(); "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); })(); 'use strict'; (function () { scrivito.widgetElement = { create_instance: function create_instance(cmsElement) { if (cmsElement.dom_element().attr('data-scrivito-private-widget-id')) { var _ret = (function () { var that = cmsElement; _.extend(that, { widget: function widget() { var domElement = that.dom_element(); return scrivito.legacy_widget.create_instance(that.widgetField().obj(), domElement.attr('data-scrivito-private-widget-id'), domElement.attr('data-scrivito-widget-obj-class'), { modification: domElement.attr('data-scrivito-private-widget-modification'), placement_modification: domElement.attr('data-scrivito-private-widget-placement-modification'), description_for_editor: domElement.attr('data-scrivito-private-widget-description-for-editor') }); }, widgetField: function widgetField() { return scrivito.cms_element.from_dom_element(that.dom_element().parent()); }, hasDetailsView: function hasDetailsView() { return !!that.dom_element().attr('data-scrivito-private-widget-has-details-view'); }, fetchMarkup: function fetchMarkup() { var templateName = that.widgetField().template_name(); var innerTag = that.widgetField().inner_tag(); return that.widget().fetch_markup(templateName, innerTag); }, detailsSrc: function detailsSrc() { return that.widget().details_src(); }, fieldName: function fieldName() { return that.widgetField().field_name(); }, hasWidgetlist: function hasWidgetlist() { return !!that.dom_element().find('[data-scrivito-field-type=widgetlist]').length; }, basicWidget: function basicWidget() { var widgetId = that.dom_element().attr('data-scrivito-private-widget-id'); return that.widgetField().basic_obj().widget(widgetId); } }); return { v: that }; })(); if (typeof _ret === 'object') return _ret.v; } }, all: function all(rootElement) { return scrivito.cms_element.all('[data-scrivito-private-widget-id]', rootElement); } }; scrivito.cms_element.definitions.push(scrivito.widgetElement); })(); (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, { save: function() { scrivito.warn('save() on a "widgetlist" is not supported!'); }, 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.attr_name(), ['widgetlist']); 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.attr_name()] = [current_widgets, ['widgetlist']]; that.container().update(update_params); return that.container().finishSaving().then(function() { scrivito.obj_class_selection.store(widget.objClass); var old_widget = scrivito.legacy_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.attr_name(), ['widgetlist']); var widget_id = widget_element.basicWidget().id; var new_widgets = _.reject(current_widgets, function(widget) { return widget.id === widget_id; }); var update_params = {}; update_params[that.attr_name()] = [new_widgets, ['widgetlist']]; 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.legacy_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); }()); '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.Workspace = (function () { _createClass(Workspace, null, [{ key: 'all', value: function all() { var _this = this; var loadableData = new scrivito.LoadableData({ state: queryCacheStoreFor('all'), loader: loadAll }); var workspaces = _.map(loadableData.get(), function (id) { return _this.get(id); }); return _.sortBy(workspaces, 'title'); } }, { key: 'get', value: function get(id) { return new scrivito.Workspace(id); } }, { key: 'byModifiedObj', value: function byModifiedObj(obj) { var _this2 = this; var objId = obj.id; var loadableData = new scrivito.LoadableData({ state: queryCacheStoreFor('byModifiedObj').subState(objId), loader: function loader() { return loadByModifiedObj(objId); } }); var workspaces = scrivito.mapAndLoadParallel(loadableData.get(), function (id) { return _this2.get(id); }); return _.sortBy(workspaces, 'title'); } // For test purpose only. }, { key: 'clearCache', value: function clearCache() { instanceCacheStore().clear(); queryCacheStore().clear(); } }, { key: 'storeWithAttributes', value: function storeWithAttributes(id, attributes) { var workspace = new scrivito.Workspace(id); workspace.assignAttributes(attributes); } }, { key: 'published', get: function get() { return this.get('published'); } }, { key: 'selected', get: function get() { var selectedWorkspaceId = scrivito.editingContext.selectedWorkspace.id(); return this.get(selectedWorkspaceId); } }]); function Workspace(id, attributes) { _classCallCheck(this, Workspace); if (!id) { throw new scrivito.InternalError('Missing workspace id'); } this._id = id; this._loadableData = new scrivito.LoadableData({ state: instanceCacheStoreFor(id), loader: loadAll }); if (attributes) { this.assignAttributes(attributes); } } _createClass(Workspace, [{ key: 'isPublished', value: function isPublished() { return this._id === 'published'; } }, { key: 'isEditable', value: function isEditable() { return !this.isPublished(); } }, { key: 'isAutoUpdate', value: function isAutoUpdate() { return this.get('auto_update'); } }, { key: 'isOwnedBy', value: function isOwnedBy(user) { return _.contains(this.ownerIds, user.id); } }, { key: 'get', value: function get(attributeName) { return this._workspaceData[attributeName]; } }, { key: 'destroy', value: function destroy() { var _this3 = this; return scrivito.CmsRestApi['delete']('workspaces/' + this._id).then(function () { return instanceCacheStoreFor(_this3._id).set(null); }); } }, { key: 'assignAttributes', value: function assignAttributes(attributes) { this._loadableData.set(attributes); } }, { key: 'update', value: function update(attributes) { var _this4 = this; return scrivito.CmsRestApi.put('workspaces/' + this._id, { workspace: attributes }).then(function (newAttributes) { return _this4.assignAttributes(newAttributes); }); } }, { key: 'id', get: function get() { return this._id; } }, { key: 'title', get: function get() { return this.get('title'); } }, { key: 'titleForEditor', get: function get() { if (this.isPublished()) { return scrivito.t('workspace.title.published'); } return this.title || scrivito.t('workspace.title.blank'); } }, { key: 'memberships', get: function get() { return _.omit(this.get('memberships'), 'undefined'); } }, { key: 'owners', get: function get() { return _.compact(scrivito.mapAndLoadParallel(this.ownerIds, function (ownerId) { try { return scrivito.User.get(ownerId); } catch (error) { if (error instanceof scrivito.ResourceNotFoundError) { return; } throw error; } })); } }, { key: 'otherEditableWorkspaces', get: function get() { var _this5 = this; return _.reject(scrivito.Workspace.all(), function (workspace) { return workspace.isPublished() || workspace.id === _this5._id; }); } }, { key: 'ownerIds', get: function get() { var ownerIds = []; _.each(this.memberships, function (_ref, userId) { var role = _ref.role; if (role === 'owner') { ownerIds.push(userId); } }); return ownerIds; } }, { key: '_workspaceData', get: function get() { return this._loadableData.get(); } }]); return Workspace; })(); function loadAll() { return scrivito.CmsRestApi.get('workspaces').then(function (_ref2) { var workspaceDatas = _ref2.results; _.each(workspaceDatas, function (workspaceData) { var loadableData = new scrivito.LoadableData({ state: instanceCacheStoreFor(workspaceData.id) }); loadableData.set(_.omit(workspaceData, 'id')); }); return _.pluck(workspaceDatas, 'id'); }); } function loadByModifiedObj(objId) { return scrivito.CmsRestApi.get('workspaces/by_modified_obj', { id: objId }).then(function (_ref3) { var ids = _ref3.results; return ids; }); } function instanceCacheStoreFor(id) { return instanceCacheStore().subState(id); } function instanceCacheStore() { return scrivito.modelState.subState('workspace'); } function queryCacheStoreFor(key) { return queryCacheStore().subState(key); } function queryCacheStore() { return scrivito.modelState.subState('workspaceQuery'); } })(); 'use strict'; (function () { scrivito.addSubpageCommand = function (childListElement) { return scrivito.createCommand({ 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.fetchPageClassSelection(); var chooseObjClass = scrivito.chooseObjClassDialog(classSelection, 'add_child_page'); return chooseObjClass.then(function (objClass) { var addSubpage = scrivito.withDefaults.createObj({ _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.editingContext.isEditingMode()) { scrivito.on('content', function(content) { _.each(scrivito.childListElement.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.widgetField) { widget_element = cms_element; widgetlist_field_element = widget_element.widgetField(); } else { widgetlist_field_element = cms_element; } return scrivito.createCommand({ id: 'scrivito.sdk.choose_and_create_widget', title: scrivito.t('commands.choose_and_create_widget.title'), icon: '', present: function() { return scrivito.editingContext.isEditingMode() && (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.withDefaults.newWidget(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_separator: { create_instance: function(params) { return { id: function() { return params.id; }, title: function() { return params.title; }, updateParams: function(new_params) { return _.extend(params, new_params); } }; } } }); }()); 'use strict'; (function () { scrivito.copyObjFromClipboardCommand = function (childListElement) { return scrivito.createCommand({ 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.isValidChildClass(objClass)) { return scrivito.t('commands.copy_obj_from_clipboard.paste_forbidden', childListElement.allowedClasses().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.widgetField) { widget_element = cms_element; } else { widgetlist_field_element = cms_element; } return scrivito.createCommand({ id: 'scrivito.sdk.copy_widget_from_clipboard', title: function() { return scrivito.t('commands.copy_widget_from_clipboard.title'); }, icon: '', present: function() { return scrivito.editingContext.isEditingMode() && scrivito.widgetClipboard.isPresent() && (widget_element || widgetlist_field_element.is_empty()); }, disabled: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widgetField(); } 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.widgetField(); } var widget = scrivito.widgetClipboard.widget(); return scrivito.withSavingOverlay( widgetlist_field_element.add_widget(widget, widget_element) ); } }); } }); }()); 'use strict'; (function () { scrivito.createCommand = function (params) { var command = { id: function id() { return params.id; }, domId: function domId() { return params.id.replace(/\./g, '_'); }, title: function title() { var title = params.title; return typeof title === 'function' ? title() : title; }, icon: function icon() { return params.icon || ''; }, subtitle: function subtitle() { return params.subtitle; }, tooltip: function tooltip() { return params.tooltip; }, isPresent: function isPresent() { var isPresent = params.present; switch (typeof isPresent) { case 'undefined': return true; case 'function': return !!isPresent(); default: return !!isPresent; } }, isEnabled: function isEnabled() { return !command.isDisabled(); }, isDisabled: function isDisabled() { return !!command.reasonForBeingDisabled(); }, isActionRequired: function isActionRequired() { var isActionRequired = params.actionRequired; return typeof isActionRequired === 'function' && isActionRequired(); }, reasonForBeingDisabled: function reasonForBeingDisabled() { var reasonForBeingDisabled = params.disabled; if (typeof reasonForBeingDisabled === 'function') { return reasonForBeingDisabled(); } }, update: function update() { if (command.needsUpdate()) { return params.update(); } }, needsUpdate: function needsUpdate() { return !!params.update; }, execute: function execute() { if (command.isPresent() && command.isEnabled()) { params.execute(); return true; } return false; }, updateParams: function updateParams(newParams) { return _.extend(params, newParams); } }; return command; }; })(); 'use strict'; (function () { scrivito.createPageCommand = function () { return scrivito.createCommand({ id: 'scrivito.sdk.create_page', title: scrivito.t('commands.create_page.title'), icon: '', disabled: function disabled() { if (!scrivito.editingContext.selectedWorkspace.is_editable()) { return scrivito.t('commands.create_page.published_workspace'); } if (scrivito.editingContext.isDeletedMode()) { return scrivito.t('commands.create_page.deleted_mode'); } }, execute: function execute() { chooseObjClass().then(createPage).then(redirectToPage); } }); }; function chooseObjClass() { var classSelection = scrivito.legacy_obj.fetch_page_class_selection(); return scrivito.chooseObjClassDialog(classSelection, 'create_page'); } function createPage(objClass) { return scrivito.withSavingOverlay(scrivito.withDefaults.createObj({ _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.widgetField) { widget_element = cms_element; widgetlist_field_element = widget_element.widgetField(); } 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.createCommand({ id: 'scrivito.sdk.create_widget', title: scrivito.t('commands.create_widget.title', description), icon: '', present: function() { return scrivito.editingContext.isEditingMode() && (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.withDefaults.newWidget(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.createCommand({ 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.legacy_workspace.create(title)).then(function(workspace) { var params = {workspaceId: workspace.id()}; if (!scrivito.editingContext.selectedWorkspace.is_editable()) { params.displayMode = 'editing'; } return scrivito.changeEditingContext(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.deleteObjCommand(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.createCommand({ 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(); } }); } }); }()); 'use strict'; (function () { scrivito.deleteObjCommand = function (obj, modelName, redirectTarget) { if (modelName === undefined) modelName = 'page'; return scrivito.createCommand({ id: 'scrivito.sdk.delete_obj', title: scrivito.t('commands.delete_obj.title', scrivito.t('models.' + modelName + '.name')), icon: '', present: function present() { return !scrivito.editingContext.isDeletedMode(); }, disabled: function disabled() { if (!scrivito.editingContext.selectedWorkspace.is_editable()) { return scrivito.t('commands.delete_obj.published_workspace'); } if (obj.has_children()) { return scrivito.t('commands.delete_obj.has_children'); } }, execute: function execute() { scrivito.ConfirmDeleteDialog.open(obj.id()).then(function (isConfirmed) { if (isConfirmed) { scrivito.withSavingOverlay(destroyObj(obj, redirectTarget)); } }); } }); }; function destroyObj(obj, redirectTarget) { return obj.destroy().then(function (defaultTarget) { return redirectTo(defaultTarget, redirectTarget); }); } function redirectTo(defaultTarget, redirectTarget) { var redirectURI = URI(redirectTarget || defaultTarget); redirectURI.path(scrivito.root_path() + redirectURI.path()); return scrivito.redirect_to(redirectURI.normalizePath().toString()); } })(); (function() { _.extend(scrivito, { delete_widget_command: function(widget_element) { return scrivito.createCommand({ id: 'scrivito.sdk.delete_widget', title: scrivito.t('commands.delete_widget.title'), icon: '', present: function() { return scrivito.editingContext.isEditingMode(); }, 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.widgetField().remove_widget(widget_element); }); } }); } }); }()); 'use strict'; (function () { scrivito.duplicateObjCommand = function (obj) { return scrivito.createCommand({ id: 'scrivito.sdk.duplicate_obj', title: scrivito.t('commands.duplicate_obj.title'), icon: '', present: function present() { return !scrivito.editingContext.isDeletedMode(); }, disabled: function disabled() { if (!scrivito.editingContext.selectedWorkspace.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.createCommand({ id: 'scrivito.sdk.duplicate_widget', title: scrivito.t('commands.duplicate_widget.title'), icon: '', present: function present() { return scrivito.editingContext.isEditingMode(); }, execute: function execute() { var widgetlistFieldElement = widgetElement.widgetField(); var widget = widgetElement.basicWidget(); 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.createCommand({ 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.createCommand({ 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() { if (scrivito.objClipboard.workspaceId !== scrivito.editingContext.selectedWorkspace.id()) { return scrivito.t('commands.move_obj_from_clipboard.forbidden.invalid_workspace'); } var objClass = scrivito.objClipboard.serializedAttributes._obj_class; if (!childListElement.isValidChildClass(objClass)) { return scrivito.t('commands.move_obj_from_clipboard.forbidden.invalid_class', childListElement.allowedClasses().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.createCommand({ id: 'scrivito.sdk.obj_details', title: function() { if (scrivito.editingContext.isEditingMode()) { 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.editingContext.isEditingMode()) { 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.createCommand({ 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'); } }); }; })(); (function() { _.extend(scrivito, { rebase_workspace_command: function(workspace) { return scrivito.createCommand({ 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, { restore_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.restore_obj'; } return scrivito.createCommand({ 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.createCommand({ 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.createCommand({ 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.legacy_workspace.create(workspaceTitle(revision), revision.id).then(function (workspace) { return scrivito.changeEditingContext({ workspaceId: workspace.id(), displayMode: 'editing' }); })); } function workspaceTitle(revision) { return scrivito.t('commands.restore_workspace.workspace_title', revision.publishedAtForEditor); } })(); (function() { _.extend(scrivito, { revert_obj_command: function(obj) { return scrivito.createCommand({ id: 'scrivito.sdk.revert_obj', title: scrivito.t('commands.revert_obj.title'), icon: '', present: function() { return scrivito.editingContext.selectedWorkspace.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.createCommand({ id: 'scrivito.sdk.revert_resource', title: scrivito.t('commands.revert_resource.title'), icon: '', present: function() { return scrivito.editingContext.selectedWorkspace.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.createCommand({ id: 'scrivito.sdk.revert_widget', title: scrivito.t('commands.revert_widget.title'), icon: '', present: function() { return scrivito.editingContext.selectedWorkspace.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.createCommand({ id: 'scrivito.sdk.save_obj_to_clipboard', title: scrivito.t('commands.save_obj_to_clipboard.title'), icon: '', present: function present() { return !scrivito.editingContext.isDeletedMode(); }, 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.createCommand({ id: 'scrivito.sdk.save_widget_to_clipboard', title: scrivito.t('commands.save_widget_to_clipboard.title'), icon: '', present: function present() { return scrivito.editingContext.isEditingMode(); }, execute: function execute() { scrivito.widgetClipboard.saveWidget(widgetElement.basicWidget()); } }); }; })(); (function() { _.extend(scrivito, { sort_items_command: function(child_list_element) { return scrivito.createCommand({ 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.hasChildOrder()) { 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.saveOrder(); }); } }); } }); }()); (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.createCommand({ id: 'scrivito.sdk.switch_to_' + mode + '_mode', title: scrivito.t('commands.switch_mode.' + mode), icon: icon, disabled: function() { if (scrivito.editingContext.displayMode === mode) { return scrivito.t('commands.switch_mode.disabled'); } return scrivito.editingContext.reasonForDisplayModeBeingDisabled(mode); }, execute: function() { if (mode !== 'view' && !scrivito.editingContext.selectedWorkspace.is_editable()) { scrivito.withSavingOverlay(scrivito.legacy_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.changeEditingContext({ workspaceId: workspace_id, displayMode: 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.editingContext.isViewMode()) { scrivito.on('content', function(content) { _.each(scrivito.widgetElement.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.createCommand({ id: 'scrivito.sdk.widget_details', title: scrivito.t('commands.widget_details.title'), icon: '', present: function() { return widget_element.widgetField().template_name() === 'show' && ( scrivito.editingContext.isEditingMode() || widget().is_modified() || widget().is_placement_modified() ); }, disabled: function() { if (!widget_element.hasDetailsView()) { 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.detailsSrc(), 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.editingContext.isEditingMode()) { 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())); }); }); } } } }); }()); 'use strict'; (function () { scrivito.deleteWorkspace = function (workspace) { askForConfirmation(workspace).then(function () { return destroyWorkspace(workspace); }); }; function askForConfirmation(workspace) { return scrivito.confirmation_dialog({ title: scrivito.t('workflows.delete_workspace.dialog.title', workspace.titleForEditor), description: scrivito.t('workflows.delete_workspace.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('workflows.delete_workspace.dialog.confirm'), confirm_button_color: 'red' }); } function destroyWorkspace(workspace) { scrivito.withSavingOverlay(workspace.destroy().then(function () { if (workspace.id === scrivito.editingContext.selectedWorkspace.id()) { return scrivito.changeEditingContext({ workspaceId: 'published' }); } return scrivito.reload(); })); } })(); 'use strict'; (function () { function openWorkspaceChanges() { scrivito.changes_dialog.open().then(function (transferredObjIds) { var page = scrivito.application_document().page(); if (transferredObjIds.length) { if (_.contains(transferredObjIds, page.id()) && page.is_new()) { scrivito.redirect_to(page.parent_path() || '/'); } scrivito.reload(); } }); } scrivito.openWorkspaceChanges = openWorkspaceChanges; })(); 'use strict'; (function () { scrivito.openWorkspaceSettings = function (workspace) { openDialog(workspace).then(function (attributes) { if (attributes) { updateWorkspace(workspace, attributes); } }); }; function openDialog(workspace) { var title = workspace.title; var titleForEditor = workspace.titleForEditor; var ownerIds = workspace.ownerIds; return scrivito.WorkspaceSettingsDialog.open({ title: title, titleForEditor: titleForEditor, ownerIds: ownerIds }); } function updateWorkspace(workspace, _ref) { var title = _ref.title; var ownerIds = _ref.ownerIds; var memberships = {}; _.each(ownerIds, function (userId) { return memberships[userId] = { role: 'owner' }; }); scrivito.withSavingOverlay(workspace.update({ title: title, memberships: memberships }).then(scrivito.reload)); } })(); 'use strict'; (function () { scrivito.publishWorkspace = function (workspace, publisher) { askForConfirmation(workspace).then(function () { return publishWorkspace(publisher)['catch'](function (error) { switch (error.type) { case 'check_failed': return alertCheckFailed(); case 'outdated_certificates': return alertOutdatedCertificated(); } }); }); }; function askForConfirmation(workspace) { return scrivito.confirmation_dialog({ title: scrivito.t('workflows.publish_workspace.dialog.title', workspace.titleForEditor), description: scrivito.t('workflows.publish_workspace.dialog.description'), icon: '', color: 'green', confirm_button_text: scrivito.t('workflows.publish_workspace.dialog.confirm'), confirm_button_color: 'green' }); } function publishWorkspace(publisher) { return scrivito.withSavingOverlay(publisher.checkAndPublish().then(redirectToPublished)); } function redirectToPublished() { return scrivito.changeEditingContext({ workspaceId: 'published' }); } function alertCheckFailed() { scrivito.confirmation_dialog({ title: scrivito.t('workflows.publish_workspace.error_dialog.title'), description: scrivito.t('workflows.publish_workspace.error_dialog.description'), icon: '', confirm_button_text: scrivito.t('workflows.publish_workspace.error_dialog.confirm') }).then(function () { return scrivito.changes_dialog.open(); }); } function alertOutdatedCertificated() { scrivito.alertDialog(scrivito.t('workflows.publish_workspace.alert.invalid_certificates')); } })(); "use strict"; (function () { scrivito.selectWorkspace = function (workspace) { scrivito.withSavingOverlay(scrivito.changeEditingContext({ workspaceId: workspace.id })); }; })(); (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.legacy_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.editingContext.selectedWorkspace.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.editingContext.isEditingMode()) { _.each(scrivito.childListElement.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') })); objClassesDeferred.done(function (objClassSelection) { view.find('#scrivito_replace_with_real_obj_classes').replaceWith(scrivito.template.render('choose_obj_class_dialog/list', { objClassSelection: sortClassSelection(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 sortClassSelection(objClassSelection) { var sortedClassSelection = {}; sortedClassSelection.all = sortClassSelectionItems(objClassSelection.all); sortedClassSelection.recent = sortClassSelectionItems(objClassSelection.recent); sortedClassSelection.popular = objClassSelection.popular; return sortedClassSelection; } function sortClassSelectionItems(selectionItems) { return _.sortBy(selectionItems, function (selectionItem) { var thumbnailTitle = $(selectionItem.markup).attr('data-scrivito-private-thumbnail-title'); return thumbnailTitle || selectionItem.name; }); } })(); (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}); }, // For 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) { var when_closed = options.when_closed; menu = render(commands); setup_commands(commands, when_closed); setup_update(dom_element, options.anchor); setup_close(dom_element, when_closed); show(dom_element, options.css_class); }; var close = function(when_closed) { menu.remove(); menu = null; if (when_closed) { when_closed(); } 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, when_closed) { _.each(commands, function(command) { if (command.domId) { menu.on('click', '.'+command.domId(), function() { if (command.isEnabled()) { close(when_closed); } 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, when_closed) { menu.find('.scrivito_menu_box_overlay').on('click', function() { close(when_closed); return false; }); }; 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.editingContext.selectedWorkspace.id(); var current_page_link = scrivito.editingContext.location({ workspaceId: workspace_id, displayMode: "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.objMenu.create($domElement, currentPage, function () { return scrivito.application_document().menu(); }); }); } }; })(); (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.objMenu.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'); } }); }, // For 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.widgetElement.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); }, _updateCursorDebounced: scrivito.oncePerFrame(function () { var _scrivito$dragDrool; (_scrivito$dragDrool = scrivito.dragDrool)._updateCursor.apply(_scrivito$dragDrool, arguments); }), _updateCursor: function _updateCursor(mouse, $body) { var drag = scrivito.dragDrool.buildDrag(); 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(); 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(); 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); }, // For test purpose only. buildDrag: function buildDrag() { 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.legacy_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; }; }()); 'use strict'; 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 () { scrivito.fileDrop = { init: function init() { var _this = this; scrivito.on('content', function (content) { if (!scrivito.in_editable_view()) { return; } _.each($(content).find('\n [data-scrivito-field-type=binary],\n img[data-scrivito-field-type=link],\n img[data-scrivito-field-type=linklist],\n img[data-scrivito-field-type=reference]\n '), function (field) { var $field = $(field); $field.on('dragenter', function () { _this.onDragenter($field); return false; }); $field.on('dragleave', function () { _this.onDragleave($field); return false; }); $field.on('drop', function (e) { _this.onDrop($field, e.originalEvent.dataTransfer); return false; }); }); }); }, onDragenter: function onDragenter($field) { $field.addClass('scrivito_file_dragover'); var dragenterCounter = $field.data('scrivito-dragenter-counter') || 0; dragenterCounter += 1; $field.data('scrivito-dragenter-counter', dragenterCounter); }, onDragleave: function onDragleave($field) { // We can assume, that a dragleave event always happens after the corresponding dragenter, // but we cannot assume it happends immediately after dragenter. var dragenterCounter = $field.data('scrivito-dragenter-counter'); dragenterCounter -= 1; $field.data('scrivito-dragenter-counter', dragenterCounter); if (dragenterCounter === 0) { $field.removeClass('scrivito_file_dragover'); } }, onDrop: function onDrop($field, dataTransfer) { if (dataTransfer.files && dataTransfer.files.length === 1) { var fieldElement = scrivito.cms_element.from_dom_element($field); $field.addClass('scrivito_element_overlay'); var attrName = scrivito.attributeInflection.camelCase(fieldElement.field_name()); this.save(fieldElement.field_type(), attrName, fieldElement.container(), dataTransfer.files[0]).then(function () { return $field.scrivito('reload'); }); } $field.removeClass('scrivito_file_dragover'); }, save: function save(attributeType, attributeName, container, file) { return uploadInto(attributeType, container, file).then(function (attributeValue) { container.update(_defineProperty({}, attributeName, [attributeValue, [attributeType]])); return container.finishSaving(); }); } }; function uploadInto(attributeType, container, file) { return new scrivito.Promise(function (resolve) { switch (attributeType) { case 'binary': return resolve(uploadIntoBinary(container, file)); case 'link': return resolve(uploadIntoLink(file)); case 'linklist': return resolve(uploadIntoLinklist(file)); case 'reference': return resolve(createBinaryFor(file)); } }); } function uploadIntoBinary(container, file) { var target = container instanceof scrivito.BasicObj ? container : container.obj; return scrivito.Binary.upload(file).into(target); } function uploadIntoLink(file) { return createBinaryFor(file).then(function (obj) { return new scrivito.BasicLink({ obj: obj }); }); } function uploadIntoLinklist(file) { return createBinaryFor(file).then(function (obj) { return [new scrivito.BasicLink({ obj: obj })]; }); } function createBinaryFor(file) { return scrivito.withDefaults.createObj({ _obj_class: scrivito.default_obj_class_for_content_type(file.type), blob: scrivito.Binary.upload(file) }); } })(); (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.is('[name=scrivito_application]')) { 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.editingContext.isViewMode()) { 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 { $('#scrivito_editing').append(view); } $('.scrivito_toggle_ui').on('click', function() { scrivito.gui.show_controls(); return false; }); }, // For test purpose only. reset_items_renderer: function() { menu_bar_items_renderer = []; }, // For test purpose only. remove: function() { $('.scrivito_topbar').remove(); } } }); }()); (function() { _.extend(scrivito, { menu_bar_display_mode_toggle: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { var comparing_mode = scrivito.editingContext.comparingMode(); 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.editingContext.displayMode, 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.domId()).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.isPresent()) { var view; if (command.needsUpdate()) { var id = _.uniqueId(command.domId()); 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); } }; }; }()); 'use strict'; (function () { scrivito.objMenu = { create: function create($domElement, obj, commandsOrFactory) { $domElement.append(scrivito.template.render('obj_menu', { obj: obj })); $domElement.on('click', function () { $domElement.addClass('active'); var commands = _.isFunction(commandsOrFactory) ? commandsOrFactory() : commandsOrFactory; scrivito.context_menu.toggle($domElement, commands, { css_class: 'obj_menu', when_closed: function when_closed() { return $domElement.removeClass('active'); } }); 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.editingContext.isEditingMode()) { _.each(scrivito.widgetElement.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.widgetField(); 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); view.find('input').focus().select(); 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}); }, // For test purpose only. remove_all: function() { $('.scrivito_prompt_dialog').remove(); } }); }()); (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.legacy_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.deleteObjCommand(obj, 'resource', 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(); }, // For 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 () { if (view) { view.addClass('scrivito_show'); } }); }, hide: function hide() { if (view) { view.remove(); view = null; } }, // For 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.widgetField) { targetElement = targetElement.widgetField(); } var draggedElement = scrivito.cms_element.from_dom_element(this._$domElement); var targetObjId = targetElement.basic_obj().id; var draggedObjId = draggedElement.widgetField().basic_obj().id; if (targetObjId !== draggedObjId) { return false; } 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(); } } } // For test purpose only. }, { 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); } } // For test purpose only. }, { 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')); } // For test purpose only. }, { key: 'save', value: function save($source, $target) { var _this = this; 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).then(function () { 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.attr_name(), [widgets, ['widgetlist']])); return container.finishSaving(); } }, { 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.editingContext.selectedWorkspace.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.editingContext.isEditingMode() || scrivito.editingContext.isComparingMode() && show_as_modified) { if (widget_element.hasWidgetlist()) { 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.hasWidgetlist()) { options.icon = 'scrivito_icon_structure_widget'; } if (scrivito.editingContext.isComparingMode()) { 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.fetchMarkup().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.editingContext.isEditingMode()) { 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 () { var Loader = function () { return React.createElement("span", { className: "scrivito_loader" }); }; var LoaderError = function () { return React.createElement("span", { className: "scrivito_loader_error", title: scrivito.t('loader_error.title') }); }; scrivito.Loader = Loader; scrivito.LoaderError = LoaderError; })(); (function () { var WorkspaceOwners = scrivito.createReactClass({ propTypes: { workspace: React.PropTypes.instanceOf(scrivito.Workspace).isRequired }, shouldRenderLoader: true, render: function () { var owners = this.props.workspace.owners; if (!owners.length) { return null; } var firstOwner = owners[0]; var restOwners = undefined; if (owners.length > 1) { restOwners = React.createElement( "span", { className: "amount" }, "+", owners.length - 1 ); } return React.createElement( "span", { className: "scrivito_list_meta" }, React.createElement( "span", { className: "first-owner" }, React.createElement("i", { className: "scrivito_icon scrivito_icon_user" }), firstOwner.description ), restOwners ); } }); scrivito.WorkspaceOwners = WorkspaceOwners; })(); (function () { var SelectedWorkspaceButton = scrivito.createReactClass({ statics: { init: function () { scrivito.menu_bar.register_item_renderer(function ($menuBar) { var $mountNode = $menuBar.find('#selected_workspace_button'); scrivito.renderReactComponent(React.createElement(scrivito.SelectedWorkspaceButton, null), $mountNode); }); } }, render: function () { var iconClassName = 'scrivito_icon scrivito_icon_ws'; if (scrivito.Workspace.selected.isPublished()) { iconClassName += '_published'; } return React.createElement( 'div', { className: 'scrivito_button_bar', onClick: this._onClick }, React.createElement('i', { className: iconClassName }), React.createElement(SelectedWorkspaceTitle, null), React.createElement( 'span', { className: 'scrivito_button_label_small' }, React.createElement(scrivito.WorkspaceOwners, { workspace: scrivito.Workspace.selected }) ) ); }, _onClick: function (e) { e.preventDefault(); scrivito.Sidebar.toggleWorkspacesPanel(); } }); var SelectedWorkspaceTitle = scrivito.createReactClass({ render: function () { return React.createElement( 'span', { className: 'scrivito_button_label' }, scrivito.Workspace.selected.titleForEditor ); } }); scrivito.SelectedWorkspaceButton = SelectedWorkspaceButton; })(); (function () { var $mountNode = undefined; var promise = undefined; scrivito.ConfirmDeleteDialog = scrivito.createReactClass({ statics: { open: function () { for (var _len = arguments.length, objIds = Array(_len), _key = 0; _key < _len; _key++) { objIds[_key] = arguments[_key]; } if (!objIds.length) { throw new scrivito.ArgumentError('Missing id(s)'); } $mountNode = $('
    ').appendTo($('#scrivito_editing')); promise = $.Deferred(); scrivito.withDialogBehaviour($mountNode, promise, { enter: confirm, escape: cancel }); scrivito.renderReactComponent(React.createElement(scrivito.ConfirmDeleteDialog, { objIds: objIds }), $mountNode); return promise; }, close: function () { close(); } }, propTypes: { objIds: React.PropTypes.arrayOf(React.PropTypes.string).isRequired }, componentDidMount: function () { this._updateHeight(); }, componentDidUpdate: function () { this._updateHeight(); }, render: function () { var objs = scrivito.BasicObj.get(this.props.objIds); var subjectName = this._subjectName(objs); var backlinks = function () { var iterator = scrivito.BasicObj.where('*', 'links_to', objs).iterator(); return scrivito.iterable.collectValuesFromIterator(iterator); }; return React.createElement( 'div', { className: 'scrivito_modal_prompt scrivito_center_dialog scrivito_red scrivito_show' }, React.createElement( 'div', { className: 'scrivito_modal_header' }, React.createElement( 'i', { className: 'scrivito_icon' }, '' ), React.createElement( 'h3', { className: 'scrivito_title' }, t('title', subjectName) ) ), React.createElement( 'div', { className: 'scrivito_modal_body' }, React.createElement(DialogContent, { objs: objs, backlinks: backlinks, subjectName: subjectName, onUpdate: this._centerDialog }) ), React.createElement( 'div', { className: 'scrivito_modal_footer' }, React.createElement(CancelButton, null), React.createElement(ConfirmButton, { backlinks: backlinks }) ) ); }, _updateHeight: function () { var $modalBody = this._findDOMNode().find('.scrivito_modal_body'); scrivito.updateAutoHeightFor($modalBody); }, _centerDialog: function () { scrivito.center(this._findDOMNode()); }, _findDOMNode: function () { return $(ReactDOM.findDOMNode(this)); }, _subjectName: function (objs) { if (objs.length > 1) { return scrivito.t('models.obj.name.plural'); } var modelType = objs[0].isBinary() ? 'resource' : 'page'; return scrivito.t('models.' + modelType + '.name'); } }); var DialogContent = scrivito.createReactClass({ propTypes: { objs: React.PropTypes.arrayOf(React.PropTypes.instanceOf(scrivito.BasicObj)).isRequired, backlinks: React.PropTypes.func.isRequired, subjectName: React.PropTypes.string.isRequired, onUpdate: React.PropTypes.func.isRequired }, componentDidMount: function () { this.props.onUpdate(); }, componentDidUpdate: function () { this.props.onUpdate(); }, shouldRenderLoader: true, render: function () { var _this = this; return React.createElement( 'div', null, React.createElement( 'p', null, this._modificationNotice() ), React.createElement( 'p', null, this._backlinksNotice() ), React.createElement( 'ul', null, this.props.backlinks().map(function (backlink) { return React.createElement(BacklinkItem, { key: backlink.id, backlink: backlink, onClick: _this._openBacklink }); }) ) ); }, _modificationNotice: function () { if (this.props.objs.length > 1) { return; } var obj = this.props.objs[0]; if (obj.isNew()) { return t('is_new', this.props.subjectName, this.props.subjectName); } if (obj.isEdited()) { return t('is_edited', this.props.subjectName); } return t('not_modified', this.props.subjectName); }, _backlinksNotice: function () { var backlinksCount = this.props.backlinks().length; if (backlinksCount === 1) { return t('one_backlink', this.props.subjectName); } else if (backlinksCount > 1) { return t('many_backlinks', backlinksCount, this.props.subjectName); } }, _openBacklink: function (backlink) { var _this2 = this; $mountNode.hide(); if (scrivito.browseContent) { scrivito.browseContent({ selection: [backlink.id], disableDelete: true }).then(function () { $mountNode.show(); _this2.forceUpdate(); }); } } }); var BacklinkItem = scrivito.createReactClass({ propTypes: { backlink: React.PropTypes.instanceOf(scrivito.BasicObj).isRequired, onClick: React.PropTypes.func.isRequired }, shouldRenderLoader: true, render: function () { return React.createElement( 'li', null, React.createElement( 'a', { href: '#', onClick: this._onClick }, this.props.backlink.descriptionForEditor ) ); }, _onClick: function (e) { this.props.onClick(this.props.backlink); e.stopPropagation(); } }); var ConfirmButton = scrivito.createReactClass({ propTypes: { backlinks: React.PropTypes.func.isRequired }, render: function () { var buttonTitle = this.props.backlinks().length ? t('confirm.has_backlinks') : t('confirm'); return React.createElement( 'a', { className: 'scrivito_button scrivito_red scrivito_confirm', onClick: this._onClick }, buttonTitle ); }, _onClick: function (e) { e.preventDefault(); confirm(); } }); var CancelButton = scrivito.createReactClass({ render: function () { return React.createElement( 'a', { className: 'scrivito_button scrivito_cancel', onClick: this._onClick }, t('cancel') ); }, _onClick: function (e) { e.preventDefault(); cancel(); } }); function confirm() { close(); promise.resolve(true); } function cancel() { close(); promise.resolve(false); } function close() { if ($mountNode && $mountNode.length) { ReactDOM.unmountComponentAtNode($mountNode.get(0)); $mountNode.remove(); } } function t(key) { var _scrivito; for (var _len2 = arguments.length, params = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { params[_key2 - 1] = arguments[_key2]; } return (_scrivito = scrivito).t.apply(_scrivito, ['confirm_delete_dialog.' + key].concat(params)); } })(); (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 }); scrivito.renderReactComponent(React.createElement(scrivito.PublishHistoryDialog, null), $mountNode); } }, componentDidMount: function () { this._updateHeight(); }, componentDidUpdate: function () { this._updateHeight(); }, 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" }), " ", t('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 }, t('close') ) ) ); }, _updateHeight: function () { var $modalBody = $(ReactDOM.findDOMNode(this)).find('.scrivito_modal_body'); scrivito.updateAutoHeightFor($modalBody); } }); 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" }, t('info'), React.createElement( "a", { href: "https://scrivito.com/publishing-history", target: "_blank" }, t('link') ), "." ) ); } }); var RevisionList = scrivito.createReactClass({ shouldRenderLoader: true, render: function () { return React.createElement( "div", null, React.createElement( "ul", { className: "scrivito_list_big" }, scrivito.Revision.getRecent().map(function (revision) { return React.createElement(RevisionListItem, { key: revision.id, revision: revision, publishedBy: revision.publishedBy }); }) ), React.createElement(NoticeBox, { isLimited: scrivito.Revision.getRecent().isLimited }) ); } }); var RevisionListItem = React.createClass({ displayName: "RevisionListItem", propTypes: { revision: React.PropTypes.instanceOf(scrivito.Revision).isRequired, publishedBy: React.PropTypes.oneOfType([React.PropTypes.instanceOf(scrivito.User), React.PropTypes.string]) }, render: function () { var className = undefined; if (this._isPublished()) { className = 'is_published'; } return React.createElement( "li", { className: className, onClick: this._onClick }, 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" }, React.createElement( "div", null, this._subtitle() ), React.createElement(PublishedBy, { publishedBy: this.props.publishedBy }) ) ), React.createElement( "span", { className: "scrivito_list_group scrivito_pull_right" }, React.createElement( "span", { className: "scrivito_list_label" }, t('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 ) ) ); }, _isPublished: function () { return this.props.revision.isPublished; }, _subtitle: function () { if (this._isPublished()) { return t('not_restorable'); } }, _publishedAtLabel: function () { return t('published_at') + scrivito.i18n.localizeDateRelative(this.props.revision.publishedAt); }, _changesCount: function () { var changesCount = this.props.revision.changesCount; if (changesCount === null) { return t('changes_count.not_available'); } if (changesCount === 1) { return t('changes_count.one'); } return t('changes_count.many', changesCount); }, _onClick: function () { if (!this._isPublished()) { scrivito.restoreWorkspaceCommand(this.props.revision).execute(); } } }); var PublishedBy = React.createClass({ displayName: "PublishedBy", propTypes: { publishedBy: React.PropTypes.oneOfType([React.PropTypes.instanceOf(scrivito.User), React.PropTypes.string]) }, render: function () { if (!this.props.publishedBy) { return null; } return React.createElement( "span", null, React.createElement("i", { className: "scrivito_icon scrivito_icon_user" }), this.props.publishedBy ); } }); var NoticeBox = React.createClass({ displayName: "NoticeBox", propTypes: { isLimited: React.PropTypes.bool }, render: function () { if (!this.props.isLimited) { return null; } 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" }, t('is_limited', scrivito.Revision.getRecent().length) ) ); } }); function close() { ReactDOM.unmountComponentAtNode($mountNode.get(0)); dialogPromise.resolve(); } function t(key) { var _scrivito; for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } return (_scrivito = scrivito).t.apply(_scrivito, ["publish_history_dialog." + key].concat(params)); } })(); (function () { var $mountNode = undefined; var dialogPromise = undefined; var WorkspaceSettingsDialog = scrivito.createReactClass({ statics: { open: function (props) { $mountNode = $('#workspace_settings_dialog'); dialogPromise = $.Deferred(); scrivito.withDialogBehaviour($mountNode, dialogPromise, { escape: cancel }); scrivito.renderReactComponent(React.createElement(WorkspaceSettingsDialog, props), $mountNode); return dialogPromise; } }, propTypes: { title: React.PropTypes.string, titleForEditor: React.PropTypes.string.isRequired, ownerIds: React.PropTypes.arrayOf(React.PropTypes.string).isRequired }, getInitialState: function () { return { title: this.props.title }; }, componentDidMount: function () { this._updateHeight(); }, render: function () { this._preloadOwners(); return React.createElement( "div", { className: "workspace_settings scrivito_modal_medium scrivito_show adjust_dialog" }, React.createElement( "div", { className: "scrivito_modal_header" }, React.createElement( "h3", null, React.createElement("i", { className: "scrivito_icon scrivito_icon_settings" }), scrivito.t('workspace_settings_dialog.title', this.props.titleForEditor) ) ), React.createElement( "div", { className: "scrivito_modal_body scrivito_dialog scrivito_auto_height" }, React.createElement( "div", { className: "scrivito_content_group" }, React.createElement( "h4", null, scrivito.t('workspace_settings_dialog.input.title') ), React.createElement("input", { name: "title", type: "text", onChange: this._onTitleChange, value: this.state.title, placeholder: this.props.titleForEditor }) ), React.createElement( "div", { className: "scrivito_content_group" }, React.createElement( "h4", null, scrivito.t('workspace_settings_dialog.input.owners') ), React.createElement(Select2Input, { ownerIds: this.props.ownerIds, onMount: this._updateHeight }) ) ), React.createElement( "div", { className: "scrivito_modal_footer" }, React.createElement( "a", { className: "scrivito_button scrivito_cancel", onClick: this._onCancel }, scrivito.t('workspace_settings_dialog.cancel') ), React.createElement( "a", { className: "scrivito_button scrivito_green scrivito_confirm", onClick: this._onConfirm }, scrivito.t('workspace_settings_dialog.confirm') ) ) ); }, _updateHeight: function () { var $modalBody = $(ReactDOM.findDOMNode(this)).find('.scrivito_modal_body'); scrivito.updateAutoHeightFor($modalBody); }, _preloadOwners: function () { scrivito.mapAndLoadParallel(this.props.ownerIds, scrivito.User.get); }, _onTitleChange: function (e) { this.setState({ title: e.target.value }); }, _onConfirm: function (e) { e.preventDefault(); var title = this.state.title; var ownerIds = _.pluck($mountNode.find('input[name=owners]').select2('data'), 'id'); ReactDOM.unmountComponentAtNode($mountNode.get(0)); if (title === this.props.title && _.isEqual(ownerIds, this.props.ownerIds)) { dialogPromise.resolve(false); } else { dialogPromise.resolve({ title: title, ownerIds: ownerIds }); } }, _onCancel: function (e) { e.preventDefault(); cancel(); } }); var Select2Input = scrivito.createReactClass({ propTypes: { ownerIds: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, onMount: React.PropTypes.func.isRequired }, componentDidMount: function () { this._setupSelect2(); this.props.onMount(); }, componentWillUnmount: function () { $mountNode.find('input[name=owners]').select2('destroy'); }, render: function () { return React.createElement("input", { name: "owners", type: "hidden", value: this.props.ownerIds }); }, _setupSelect2: function () { $mountNode.find('input[name=owners]').select2({ multiple: true, minimumInputLength: 1, query: scrivito.throttle(function (query) { scrivito.User.suggest(query.term).then(function (users) { var results = _.map(users, function (user) { return { id: user.id, text: user.description }; }); query.callback({ results: results }); }); }, 500), initSelection: function (element, callback) { var value = $(element).val(); if (value) { callback(_.map(value.split(','), function (userId) { return { id: userId, text: scrivito.User.get(userId).description, locked: userId === 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') }); } }); function cancel() { ReactDOM.unmountComponentAtNode($mountNode.get(0)); dialogPromise.resolve(false); } scrivito.WorkspaceSettingsDialog = WorkspaceSettingsDialog; })(); (function () { var STORAGE_KEY = 'sidebar.active_panel'; var DETAILS_PANEL = 'details'; var WORKSPACES_PANEL = 'workspaces'; var NOTIFICATIONS_PANEL = 'notifications'; var DEVICES_PANEL = 'devices'; var sidebarComponent = undefined; scrivito.Sidebar = React.createClass({ displayName: 'Sidebar', statics: { init: function () { scrivito.menu_bar.register_item_renderer(function ($menuBar) { if (sidebarComponent) { sidebarComponent.forceUpdate(); } else { var $mountNode = $menuBar.find('.scrivito_sidebar'); sidebarComponent = scrivito.renderReactComponent(React.createElement(scrivito.Sidebar, null), $mountNode); } }); }, toggleWorkspacesPanel: function () { if (sidebarComponent) { sidebarComponent.togglePanel(WORKSPACES_PANEL); } }, getCurrentObj: function () { var page = scrivito.application_document().page(); if (page) { return scrivito.BasicObj.getIncludingDeleted(page.id()); } }, countNotifications: function () { var notificationsCount = 0; var obj = this.getCurrentObj(); if (obj) { if (obj.hasConflicts()) { notificationsCount += 1; } notificationsCount += scrivito.editingContext.restrictionMessagesFor(obj).length; notificationsCount += scrivito.editingContext.conflictingWorkspacesFor(obj).length; } return notificationsCount; }, // For test purpose only. reset: function () { sidebarComponent = null; scrivito.storage.remove(STORAGE_KEY); }, // For test purpose only. getStoredActivePanel: function () { return scrivito.storage.get(STORAGE_KEY); }, // For test purpose only. setStoredActivePanel: function (panelName) { scrivito.storage.set(STORAGE_KEY, panelName); } }, getInitialState: function () { return { activePanel: scrivito.Sidebar.getStoredActivePanel() }; }, componentDidMount: function () { $('#scrivito_ui').addClass('scrivito_sidebar_show_first_level'); this._updateUIOffset(); }, componentDidUpdate: function () { this._updateUIOffset(); }, render: function () { return React.createElement( 'div', null, React.createElement(SidebarButtons, { activePanel: this.state.activePanel, togglePanel: this.togglePanel }), React.createElement(SidebarPanels, { activePanel: this.state.activePanel }) ); }, togglePanel: function (panelName) { var activePanel = this.state.activePanel === panelName ? null : panelName; scrivito.Sidebar.setStoredActivePanel(activePanel); this.setState({ activePanel: activePanel }); }, _updateUIOffset: function () { if (this.state.activePanel) { $('#scrivito_ui').addClass('scrivito_sidebar_show_second_level'); } else { $('#scrivito_ui').removeClass('scrivito_sidebar_show_second_level'); } } }); var SidebarButtons = scrivito.createReactClass({ propTypes: { activePanel: React.PropTypes.string, togglePanel: React.PropTypes.func }, render: function () { var _this = this; var detailsButton = undefined; if (scrivito.enableSidebarDetails) { detailsButton = React.createElement( 'div', null, React.createElement(DetailsButton, { isActive: this.props.activePanel === DETAILS_PANEL, togglePanel: function () { return _this.props.togglePanel(DETAILS_PANEL); } }), React.createElement('div', { className: 'scrivito_separator_bar' }) ); } return React.createElement( 'div', { className: 'scrivito_first_level' }, detailsButton, React.createElement(WorkspacesButton, { isActive: this.props.activePanel === WORKSPACES_PANEL, togglePanel: function () { return _this.props.togglePanel(WORKSPACES_PANEL); } }), React.createElement(BrowseContentButton, null), React.createElement(scrivito.Sidebar.NotificationsButton, { isActive: this.props.activePanel === NOTIFICATIONS_PANEL, togglePanel: function () { return _this.props.togglePanel(NOTIFICATIONS_PANEL); } }), React.createElement('div', { className: 'scrivito_separator_bar' }), React.createElement(DevicesButton, { isActive: this.props.activePanel === DEVICES_PANEL, togglePanel: function () { return _this.props.togglePanel(DEVICES_PANEL); } }), React.createElement(HideControlsButton, null) ); } }); var SidebarPanels = scrivito.createReactClass({ propTypes: { activePanel: React.PropTypes.string }, render: function () { if (!this.props.activePanel) { return null; } var detailsPanel = undefined; if (scrivito.enableSidebarDetails) { detailsPanel = React.createElement(scrivito.Sidebar.DetailsPanel, { isActive: this.props.activePanel === DETAILS_PANEL }); } return React.createElement( 'div', { className: 'scrivito_second_level' }, detailsPanel, React.createElement(scrivito.Sidebar.WorkspacesPanel, { isActive: this.props.activePanel === WORKSPACES_PANEL }), React.createElement(scrivito.Sidebar.NotificationsPanel, { isActive: this.props.activePanel === NOTIFICATIONS_PANEL }), React.createElement(scrivito.Sidebar.DevicesPanel, { isActive: this.props.activePanel === DEVICES_PANEL }) ); } }); var DetailsButton = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired, togglePanel: React.PropTypes.func.isRequired }, shouldRenderLoader: true, render: function () { return this._render(scrivito.Sidebar.getCurrentObj()); }, renderWhileLoading: function () { return this._render(); }, _render: function (obj) { return React.createElement( 'div', { className: this._buttonClassName(), onClick: this.props.togglePanel }, React.createElement('i', { className: this._iconClassName(obj) }) ); }, _buttonClassName: function () { var className = 'scrivito_details_button scrivito_button_bar'; if (this.props.isActive) { className += ' active'; } return className; }, _iconClassName: function (obj) { var className = 'scrivito_icon scrivito_icon_page'; if (obj && obj.modification) { className += ' scrivito_' + obj.modification; } return className; } }); var WorkspacesButton = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired, togglePanel: React.PropTypes.func.isRequired }, render: function () { return React.createElement( 'div', { className: this._buttonClassName(), onClick: this.props.togglePanel }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_ws' }) ); }, _buttonClassName: function () { var className = 'scrivito_workspaces_button scrivito_button_bar'; if (this.props.isActive) { className += ' active'; } return className; } }); var BrowseContentButton = scrivito.createReactClass({ render: function () { if (!scrivito.browseContent) { return null; } return React.createElement( 'div', { className: 'scrivito_browse_content scrivito_button_bar', onClick: this._onClick }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_content_browser' }) ); }, _onClick: function (e) { scrivito.browseContent(); e.stopPropagation(); } }); var DevicesButton = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired, togglePanel: React.PropTypes.func.isRequired }, componentDidMount: function () { var _this2 = this; this._subscriptionToken = scrivito.Devices.subscribeChange(function () { return _this2.forceUpdate(); }); }, componentWillUnmount: function () { scrivito.Devices.unsubscribeChange(this._subscriptionToken); }, render: function () { return React.createElement( 'div', { className: this._buttonClassName(), onClick: this.props.togglePanel }, React.createElement('i', { className: this._iconClassName() }) ); }, _buttonClassName: function () { var className = 'scrivito_devices_button scrivito_button_bar'; if (this.props.isActive) { className += ' active'; } return className; }, _iconClassName: function () { return 'scrivito_icon scrivito_icon_' + scrivito.Devices.active; } }); var HideControlsButton = React.createClass({ displayName: 'HideControlsButton', render: function () { return React.createElement( 'div', { className: 'scrivito_hide_controls scrivito_button_bar scrivito_bottom_fixed', onClick: this._hideControls }, React.createElement('i', { className: 'scrivito_icon scrivito_icon_hide_ui' }) ); }, _hideControls: function () { scrivito.gui.hide_controls(); return false; } }); })(); (function () { scrivito.Sidebar.DetailsPanel = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired }, render: function () { if (!this.props.isActive) { return null; } var obj = scrivito.Sidebar.getCurrentObj(); if (!obj) { return React.createElement("div", { className: "scrivito_second_level_content scrivito_details_panel" }); } return React.createElement(IframePanel, { src: scrivito.detailsPathForId(obj.id) }); } }); var IframePanel = scrivito.createReactClass({ propTypes: { src: React.PropTypes.string.isRequired }, getInitialState: function () { return { isLoaded: false }; }, componentWillReceiveProps: function (nextProps) { if (this.props.src !== nextProps.src) { this.setState({ isLoaded: false }); } }, render: function () { var spinner = undefined; if (!this.state.isLoaded) { spinner = React.createElement( "i", { className: "scrivito_icon scrivito_spinning" }, "" ); } return React.createElement( "div", { className: "scrivito_second_level_content scrivito_details_panel" }, spinner, React.createElement("iframe", { className: this._iframeClassName(), src: this.props.src, onLoad: this._onLoad }) ); }, _iframeClassName: function () { var className = 'scrivito_second_level_content_iframe'; if (this.state.isLoaded) { className += ' scrivito_show'; } return className; }, _onLoad: function () { this.setState({ isLoaded: true }); } }); })(); (function () { scrivito.Sidebar.DevicesPanel = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired }, componentDidMount: function () { var _this = this; this._subscriptionToken = scrivito.Devices.subscribeChange(function () { return _this.forceUpdate(); }); }, componentWillUnmount: function () { scrivito.Devices.unsubscribeChange(this._subscriptionToken); }, render: function () { if (!this.props.isActive) { return null; } return React.createElement( "div", { className: "scrivito_second_level_content scrivito_devices_panel scrivito_dark" }, React.createElement( "div", { className: "scrivito_sidebar_separator" }, React.createElement( "span", null, scrivito.t('sidebar.devices_panel.title') ) ), React.createElement( "div", { className: "scrivito_property_padding" }, React.createElement( "ul", { className: "scrivito_list_big" }, scrivito.Devices.all.map(function (device) { return React.createElement(DeviceItem, { key: device, device: device }); }) ) ) ); } }); var DeviceItem = scrivito.createReactClass({ propTypes: { device: React.PropTypes.string.isRequired }, render: function () { return React.createElement( "li", { className: this._className(), onClick: this._onClick }, React.createElement( "span", { className: "scrivito_list_group" }, React.createElement("i", { className: this._iconClassName() }) ), React.createElement( "span", { className: "scrivito_list_group" }, React.createElement( "span", { className: "scrivito_list_topic" }, scrivito.t("sidebar.devices_panel.device." + this.props.device) ) ) ); }, _className: function () { if (this._isActive()) { return 'active'; } }, _iconClassName: function () { return "scrivito_icon scrivito_icon_" + this.props.device; }, _isActive: function () { return this.props.device === scrivito.Devices.active; }, _onClick: function (e) { if (!this._isActive()) { scrivito.Devices.active = this.props.device; } e.preventDefault(); } }); })(); (function () { var NotificationsButton = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired, togglePanel: React.PropTypes.func.isRequired }, shouldRenderLoader: true, render: function () { return React.createElement( 'div', { className: this._buttonClassName(), onClick: this.props.togglePanel }, React.createElement(NotificationsButtonIcon, null), React.createElement(NotificationsButtonCounter, null) ); }, _buttonClassName: function () { var className = 'scrivito_notifications_button scrivito_button_bar'; if (this.props.isActive) { className += ' active'; } return className; } }); var NotificationsButtonIcon = scrivito.createReactClass({ shouldRenderLoader: true, render: function () { var className = 'scrivito_icon scrivito_icon_pot_error'; if (scrivito.Sidebar.countNotifications()) { className = className + ' scrivito_yellow scrivito_wobble scrivito_animated'; } return React.createElement('i', { className: className }); }, renderWhileLoading: function () { return React.createElement('i', { className: 'scrivito_icon scrivito_icon_pot_error' }); } }); var NotificationsButtonCounter = scrivito.createReactClass({ render: function () { var notificationsCount = scrivito.Sidebar.countNotifications(); if (notificationsCount) { return React.createElement( 'span', { className: 'amount' }, notificationsCount ); } return null; } }); scrivito.Sidebar.NotificationsButton = NotificationsButton; })(); (function () { scrivito.Sidebar.NotificationsPanel = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired }, render: function () { if (!this.props.isActive) { return null; } return React.createElement( ReactCustomScrollbars.Scrollbars, { className: "scrivito_notifications_panel scrivito_second_level_content scrivito_dark" }, React.createElement(NotificationGroups, null), React.createElement(NoNotificationsBox, null) ); } }); var NotificationGroups = scrivito.createReactClass({ render: function () { var obj = scrivito.Sidebar.getCurrentObj(); if (!obj) { return null; } return React.createElement( "div", null, React.createElement(ConflictGroup, { obj: obj }), React.createElement(PotentialConflictsGroup, { obj: obj }), React.createElement(PublishRestrictionsGroup, { obj: obj }) ); } }); var ConflictGroup = scrivito.createReactClass({ propTypes: { obj: React.PropTypes.instanceOf(scrivito.BasicObj).isRequired }, render: function () { if (this.props.obj.hasConflicts()) { return React.createElement( "div", { className: "scrivito_conflict_group scrivito_sidebar_separator scrivito_red" }, React.createElement("i", { className: "scrivito_icon scrivito_icon_error" }), React.createElement( "span", null, scrivito.t('sidebar.notifications_panel.conflict_group.title') ), React.createElement( "span", { className: "description" }, scrivito.t('sidebar.notifications_panel.conflict_group.description1'), React.createElement( "a", { href: "https://scrivito.com/conflicts", target: "_blank" }, scrivito.t('sidebar.notifications_panel.conflict_group.link') ), scrivito.t('sidebar.notifications_panel.conflict_group.description2') ) ); } return null; } }); var PotentialConflictsGroup = scrivito.createReactClass({ propTypes: { obj: React.PropTypes.instanceOf(scrivito.BasicObj).isRequired }, shouldRenderLoader: true, render: function () { var workspaces = scrivito.editingContext.conflictingWorkspacesFor(this.props.obj); if (!workspaces.length) { return null; } return React.createElement( "div", { className: "scrivito_potential_conflicts_group" }, React.createElement( "div", { className: "scrivito_sidebar_separator scrivito_orange" }, React.createElement("i", { className: "scrivito_icon scrivito_icon_error" }), React.createElement( "span", null, scrivito.t('sidebar.notifications_panel.potential_conflicts_group.title') ), React.createElement( "span", { className: "description" }, scrivito.t('sidebar.notifications_panel.potential_conflicts_group.description') ) ), React.createElement(scrivito.Sidebar.WorkspaceList, { workspaces: workspaces, includeInaccessible: true }) ); } }); var PublishRestrictionsGroup = scrivito.createReactClass({ propTypes: { obj: React.PropTypes.instanceOf(scrivito.BasicObj).isRequired }, shouldRenderLoader: true, render: function () { var restrictionMessages = scrivito.editingContext.restrictionMessagesFor(this.props.obj); if (!restrictionMessages.length) { return null; } return React.createElement( "div", { className: "scrivito_publish_restrictions_group" }, React.createElement( "div", { className: "scrivito_sidebar_separator scrivito_blue" }, React.createElement("i", { className: "scrivito_icon scrivito_icon_no_publish" }), React.createElement( "span", null, scrivito.t('sidebar.notifications_panel.publish_restrictions_group.title') ), restrictionMessages.map(function (restrictionMessage) { return React.createElement( "span", { key: restrictionMessage, className: "description" }, restrictionMessage ); }) ) ); } }); var NoNotificationsBox = scrivito.createReactClass({ render: function () { if (scrivito.Sidebar.countNotifications() === 0) { return React.createElement( "div", { className: "scrivito_no_notifications_box scrivito_property_padding" }, React.createElement( "div", { className: "scrivito_list_big" }, React.createElement( "div", { className: "scrivito_notice scrivito_grey" }, React.createElement( "div", { className: "scrivito_notice_body" }, scrivito.t('sidebar.notifications_panel.no_notifications') ) ) ) ); } return null; } }); })(); (function () { var WorkspaceList = scrivito.createReactClass({ propTypes: { workspaces: React.PropTypes.arrayOf(React.PropTypes.instanceOf(scrivito.Workspace)).isRequired, isActive: React.PropTypes.bool, includeInaccessible: React.PropTypes.bool }, render: function () { var _this = this; return React.createElement( "div", { className: "scrivito_property_padding" }, React.createElement( "ul", { className: "scrivito_list_big" }, this.props.workspaces.map(function (workspace) { return React.createElement(WorkspaceItem, { key: workspace.id, workspace: workspace, isActive: _this.props.isActive, includeInaccessible: _this.props.includeInaccessible }); }) ) ); } }); var WorkspaceItem = scrivito.createReactClass({ propTypes: { workspace: React.PropTypes.instanceOf(scrivito.Workspace).isRequired, isActive: React.PropTypes.bool, includeInaccessible: React.PropTypes.bool }, shouldRenderLoader: true, render: function () { if (!this._isDisplayable()) { return null; } return React.createElement( "li", { className: this._className(), title: this._title(), onClick: this._onClick }, React.createElement( "span", { className: "scrivito_list_group" }, React.createElement("i", { className: this._iconClassName() }) ), React.createElement( "span", { className: "scrivito_list_group" }, React.createElement( "span", { className: "scrivito_list_topic" }, this.props.workspace.titleForEditor ), React.createElement(scrivito.WorkspaceOwners, { workspace: this.props.workspace }) ), React.createElement( "span", { className: "scrivito_list_group_action" }, React.createElement(DeleteButton, { workspace: this.props.workspace }) ) ); }, _className: function () { if (this.props.isActive) { return 'active'; } if (this._isDisabled()) { return 'scrivito_disabled'; } }, _title: function () { if (!this._canReadWorkspace()) { return scrivito.t('sidebar.workspace_list.workspace_item.is_disabled'); } }, _iconClassName: function () { var className = 'scrivito_icon scrivito_icon_ws'; if (this.props.workspace.isPublished()) { className += '_published'; } return className; }, _onClick: function (e) { if (this._isSelectable()) { scrivito.selectWorkspace(this.props.workspace); } e.stopPropagation(); }, _isDisplayable: function () { return this._canReadWorkspace() || this.props.includeInaccessible; }, _isSelectable: function () { return this._canReadWorkspace() && !this.props.isActive; }, _isDisabled: function () { return this._isDisplayable() && !this._isSelectable(); }, _canReadWorkspace: function () { return scrivito.User.current.can('read', this.props.workspace); } }); var DeleteButton = scrivito.createReactClass({ propTypes: { workspace: React.PropTypes.instanceOf(scrivito.Workspace).isRequired }, render: function () { if (!this._isPresent()) { return null; } return React.createElement("i", { className: "scrivito_delete_button scrivito_icon scrivito_icon_trash", onClick: this._onClick }); }, _isPresent: function () { return scrivito.User.current.can('delete', this.props.workspace); }, _onClick: function (e) { scrivito.deleteWorkspace(this.props.workspace); e.stopPropagation(); } }); scrivito.Sidebar.WorkspaceList = WorkspaceList; })(); 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.Sidebar.WorkspacesPanel = scrivito.createReactClass({ propTypes: { isActive: React.PropTypes.bool.isRequired }, render: function () { if (!this.props.isActive) { return null; } return React.createElement( ReactCustomScrollbars.Scrollbars, { className: "scrivito_second_level_content scrivito_workspaces_panel scrivito_dark" }, React.createElement(GeneralWorkspacesGroup, null), React.createElement(CurrentWorkspaceGroup, null), React.createElement(OtherWorkspacesGroup, null) ); } }); var GeneralWorkspacesGroup = scrivito.createReactClass({ render: function () { return React.createElement( "div", { className: "scrivito_general_workspaces_group" }, React.createElement( "div", { className: "scrivito_sidebar_separator" }, React.createElement( "span", null, scrivito.t('sidebar.workspaces_panel.general_workspaces_group.title') ) ), React.createElement( "ul", { className: "scrivito_sidebar_action" }, React.createElement(CreateWorkspaceButton, null), React.createElement(PublishHistoryButton, null) ) ); } }); var CurrentWorkspaceGroup = scrivito.createReactClass({ render: function () { var currentWorkspace = scrivito.Workspace.selected; var currentWorkspaceButtons = undefined; if (currentWorkspace.isEditable()) { currentWorkspaceButtons = React.createElement( "ul", { className: "scrivito_sidebar_action" }, React.createElement(ChangesButton, { workspace: currentWorkspace }), React.createElement(PublishButton, { workspace: currentWorkspace }), React.createElement(SettingsButton, { workspace: currentWorkspace }), React.createElement(RebaseButton, { workspace: currentWorkspace }) ); } return React.createElement( "div", { className: "scrivito_current_workspace_group" }, React.createElement( "div", { className: "scrivito_sidebar_separator" }, React.createElement( "span", null, scrivito.t('sidebar.workspaces_panel.current_workspace_group.title') ) ), React.createElement(scrivito.Sidebar.WorkspaceList, { workspaces: [currentWorkspace], isActive: true }), currentWorkspaceButtons ); } }); var OtherWorkspacesGroup = scrivito.createReactClass({ render: function () { return React.createElement( "div", { className: "scrivito_other_workspaces_group" }, React.createElement( "div", { className: "scrivito_sidebar_separator" }, React.createElement( "span", null, scrivito.t('sidebar.workspaces_panel.other_workspaces_group.title') ) ), React.createElement(OtherWorkspacesList, null) ); } }); var OtherWorkspacesList = scrivito.createReactClass({ shouldRenderLoader: true, render: function () { var currentWorkspace = scrivito.Workspace.selected; var otherWorkspaces = currentWorkspace.otherEditableWorkspaces; if (currentWorkspace.isEditable()) { otherWorkspaces = [scrivito.Workspace.published].concat(_toConsumableArray(otherWorkspaces)); } return React.createElement(scrivito.Sidebar.WorkspaceList, { workspaces: otherWorkspaces }); } }); var CreateWorkspaceButton = scrivito.createReactClass({ render: function () { return React.createElement( "li", { className: this._buttonClassName(), title: this._buttonTitle(), onClick: this._onClick }, React.createElement("i", { className: "scrivito_icon scrivito_icon_inv_plus" }), React.createElement( "span", null, scrivito.t('sidebar.workspaces_panel.create_workspace_button.title') ) ); }, _onClick: function (e) { if (this._isEnabled()) { scrivito.create_workspace_command().execute(); } e.stopPropagation(); }, _buttonClassName: function () { var className = 'scrivito_create_workspace_button scrivito_sidebar_action_item'; if (!this._isEnabled()) { className += ' scrivito_disabled'; } return className; }, _buttonTitle: function () { if (!this._isEnabled()) { return scrivito.t('sidebar.workspaces_panel.create_workspace_button.is_disabled'); } }, _isEnabled: function () { return scrivito.User.current.can('create'); } }); var PublishHistoryButton = scrivito.createReactClass({ render: function () { return React.createElement( "li", { className: "scrivito_publish_history_button scrivito_sidebar_action_item", onClick: this._onClick }, React.createElement("i", { className: "scrivito_icon scrivito_icon_history" }), React.createElement( "span", null, scrivito.t('sidebar.workspaces_panel.publish_history_button.title') ) ); }, _onClick: function (e) { scrivito.PublishHistoryDialog.open(); e.stopPropagation(); } }); var ChangesButton = createWorkspaceButtonClass({ name: 'changes', icon: 'edited', verb: 'read', onClick: function () { scrivito.openWorkspaceChanges(); } }); var PublishButton = createWorkspaceButtonClass({ name: 'publish', verb: 'publish', onClick: function (workspace) { var publisher = new scrivito.WorkspacePublisher(workspace); scrivito.publishWorkspace(workspace, publisher); } }); var SettingsButton = createWorkspaceButtonClass({ name: 'settings', verb: 'invite_to', onClick: function (workspace) { scrivito.openWorkspaceSettings(workspace); } }); var RebaseButton = createWorkspaceButtonClass({ name: 'rebase', icon: 'refresh', verb: 'write', isButtonDisabled: function (workspace) { return workspace.isAutoUpdate(); }, onClick: function (workspace) { var legacyWorkspace = scrivito.legacy_workspace.fromWorkspace(workspace); scrivito.rebase_workspace_command(legacyWorkspace).execute(); } }); function createWorkspaceButtonClass(_ref) { var name = _ref.name; var icon = _ref.icon; var verb = _ref.verb; var isButtonDisabled = _ref.isButtonDisabled; var onClick = _ref.onClick; return scrivito.createReactClass({ propTypes: { workspace: React.PropTypes.instanceOf(scrivito.Workspace).isRequired }, render: function () { if (isButtonDisabled && isButtonDisabled(this.props.workspace)) { return null; } return React.createElement( "li", { className: this._className(), title: this._title(), onClick: this._onClick }, React.createElement("i", { className: "scrivito_icon scrivito_icon_" + (icon || name) }), React.createElement( "span", null, scrivito.t("sidebar.workspaces_panel." + name + "_button.title") ) ); }, _className: function () { var className = "scrivito_sidebar_action_item scrivito_" + name + "_button"; if (!this._canAccessWorkspace()) { className += ' scrivito_disabled'; } return className; }, _title: function () { if (!this._canAccessWorkspace()) { return scrivito.t("sidebar.workspaces_panel." + name + "_button.is_forbidden"); } }, _canAccessWorkspace: function () { return scrivito.User.current.can(verb, this.props.workspace); }, _onClick: function (e) { if (this._canAccessWorkspace()) { onClick(this.props.workspace); } e.stopPropagation(); } }); } })(); // (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(); }); }());